#version 330 core


// CBS
// ported from https://www.shadertoy.com/view/lslGWr
// Added some stars: Thanks to http://glsl.heroku.com/e#6904.0
// Modified for use

uniform float time;
uniform vec2 resolution;

float xtime=0.3*time;

// halfspace discard uniforms: ////////////////////////////////

in vec4 aPos;

uniform int iside=0; // 0=>noDiscard

uniform vec3 eyePos;

uniform vec3  port1;
uniform vec3  port2;

// halfspace discard uniforms end /////////////////////////////





float field(in vec3 p) {
	float strength = 7. + .03 * log(1.e-6 + fract(sin(xtime) * 4373.11));
	float accum = 0.;
	float prev = 0.;
	float tw = 0.;
	for (int i = 0; i < 32; ++i) {
		float mag = dot(p, p);
		p = abs(p) / mag + vec3(-.5, -.4, -1.5);
		float w = exp(-float(i) / 7.);
		accum += w * exp(-strength * pow(abs(mag - prev), 2.3));
		tw += w;
		prev = mag;
	}
	return max(0., 5. * accum / tw - .7);
}

/*
vec3 nrand3( vec2 co )
{
	vec3 a = fract( cos( co.x*8.3e-3 + co.y )*vec3(1.3e5, 4.7e5, 2.9e5) );
	vec3 b = fract( sin( co.x*0.3e-3 + co.y )*vec3(8.1e5, 1.0e5, 0.1e5) );
	vec3 c = mix(a, b, 1111110.5);
	return c;
}
*/

in vec2 mypos; // xz coords of vertex
out vec4 fragColor;

void main() {

	//vec2 uv = 2. * gl_FragCoord.xy / resolution.xy - 1.; //orig

	//note mypos.xy is (x,z) coords on ceiling -10<x<+10, -20<z<20

	vec2 uv = mypos/30.0; // not bad ! but need green highlights in water
	//vec2 uv = vec2( mypos.x/20.0, mypos.y/40.0 );

	vec2 uvs = uv * resolution.xy / max(resolution.x, resolution.y);
	vec3 p = vec3(uvs / 4., 0) + vec3(1., -1.3, 0.);
	//orig: p += .2 * vec3(sin(xtime / 16.), sin(xtime / 12.),  sin(xtime / 128.));
	p += .2 * vec3(sin(xtime / 16.), sin(xtime / 12.),  0.5*sin(xtime / 128.));
	float t = field(p);
	float v = (1. - exp((abs(uv.x) - 1.) * 6.)) * (1. - exp((abs(uv.y) - 1.) * 6.));
	fragColor = mix(.4, 1., v) * vec4(1.8 * t * t * t, 2.4 * t * t, t, 1.0);

	fragColor = 0.5*fragColor; //20nov19 addendum darker...better

	fragColor.a = 1.0; // 21mar16


	// fastrgv:  my halfspace-discard addendum:
	vec3 cP1 =  port1 - eyePos;
	vec3 cP2 =  port2 - eyePos;
	vec3 vP0 = aPos.xyz - eyePos;
	float PRAD = 0.85; // larger, but synched with adagate.adb
	float FOV1 = atan(PRAD/length(cP1));
	float FOV2 = atan(PRAD/length(cP2));
	vec3 nP1 = normalize(cP1);
	vec3 nP2 = normalize(cP2);
	vec3 nP0 = normalize(vP0);
	float d1=dot(nP0,nP1);
	float d2=dot(nP0,nP2);
	float a1=acos(d1);
	float a2=acos(d2);
	if( iside != 0 ) {
		if( (iside==2) && (a1>FOV1) ) discard;
		if( (iside==1) && (a2>FOV2) ) discard;
	}



}
