in lowp vec4 colorV;
out vec4 fragColor;
in lowp vec2 tc;
in lowp float aspect;
in lowp vec2 pp;

// flanger
in lowp float phz;
in lowp float dpth;
in lowp float fdbk;

// bitcooker

// normalized
uniform lowp float bitDepth;
uniform lowp float sampleRate;
uniform lowp float jitter;
uniform lowp float mix_;

// output volume
uniform mediump float level;

// time
uniform highp float t;
uniform lowp vec3 bg;

float saw(float x) {
	float o = sin(x);
	// if(filterEnable==0.0) {
	// o += 0.3*sin(3.0*x);
	// }
	return o;
}

float rand(float n) {
	return fract(sin(n) * 43758.5453123);
}

float noise(float p) {
	float fl = floor(p);
	float fc = fract(p);
	return mix(rand(fl), rand(fl + 1.0), fc);
}
float rand(vec2 n) {
	return fract(sin(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);
}
float noise(vec2 n) {
	const vec2 d = vec2(0.0, 1.0);
	vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));
	return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);
}

#define PI 3.1415926535897932384626433832795

float rectangle(vec2 samplePosition, vec2 halfSize) {
	vec2 componentWiseEdgeDistance = abs(samplePosition) - halfSize;
	float outsideDistance = length(max(componentWiseEdgeDistance, 0.0));
	float insideDistance = min(max(componentWiseEdgeDistance.x, componentWiseEdgeDistance.y), 0.0);
	return outsideDistance + insideDistance;
}

float sinny(float s) {
	float jit = jitter * 0.08 * (rand(t + s) - 0.5);
	return sin(s) * (1.0 + level) + jit;
}

void main() {
	vec3 fg = vec3(76.0 / 255.0, 222.0 / 255.0, 255.0 / 255.0);

	vec3 pink = vec3(254. / 255., 46. / 255., 90. / 255.);

	vec2 p = (tc - vec2(0.5)) * 2.1;
	// p /= 500.0;
	vec2 dc = p;
	dc *= dc;
	float warp = 0.15; //sampleRate / 64000.0;

	// warp the fragment coordinates
	p.x *= 1.0 + (dc.y * (0.3 * warp));
	p.y *= 1.0 + (dc.x * (0.4 * warp));

	// pink = vec3(0.0, 1.0, 0.0);

	// meter border, and outside meter
	float borderAmt = max(step(1.0, abs(p.y)), step(1.0, abs(p.x)));

	// if (abs(p.y) > 1.0 || abs(p.x)>1.0) {
	float r = rectangle(p, vec2(1., 1.));

	r = smoothstep(0.02, 0.01, r)
		// glow below
		// +
		// 0.9*smoothstep(0.3, -0.2, r)
		;

	vec3 border = pink * r + bg * (1.0 - r);
	// return;
	// }

	float px = p.x;

	float p_x = p.x * 4.0;

	// quantize x axis
	float sr = 0.4 + (sampleRate) *20.0;
	p_x = floor(p_x * sr) / sr;

	// quantize y axis
	float p_y = p.y * 2.0;

	float bd = 1.0 + bitDepth * bitDepth * 48.0;
	p_y = floor(p_y * bd) / bd;
	float a = 1.f - abs(p_y - sinny(p_x));
	float b = 1.f - abs(p.y * 2.0 - sinny(p.x * 4.0));

	a = a * a * a * 2.0 * (1.0 + level);

	b = b * b * b * b * b * 2.0 * (1.0 + level);

	fragColor.rgb = bg + fg * a * mix_ + pink * b * (1.0 - mix_);

	// tint and grain
	fragColor.rgb *= 0.7 + 0.3 * rand(p);
	fragColor.rgb *= 0.9 + 0.1 * sin(p.y * 400.0);
	fragColor.rgb *= 1.0 - 0.3 * length(p);
	fragColor.rgb = fragColor.rgb * (1.0 - borderAmt) + border * borderAmt;
	fragColor.a = 1.0;
}
