The Code Therapy

Gowing cubes

cubes that glow

Created by daarfi on Thu, 21 Sep 2023 17:24:28 GMT.


#version 300 es
precision highp float;

uniform vec2 resolution;
uniform float time;
uniform float fft;
out vec4 fragColor;

const float PI = acos(-1.0);
const float TAU = PI * 2.0;
vec2 scale = vec2(20.);

float sdBox( in vec2 p, in vec2 b ) {
  vec2 d = abs(p)-b;
  return length(max(d,0.0)) + min(max(d.x,d.y),0.0);
}

// Returns hexagonal distance given a pixel position
float hexDist(vec2 position) {
  position = abs(position); // mirror axis
  float c = dot(position, normalize(vec2(1., 1.73)));
  c = max(c, position.x); // crop sides
  return c;
}

vec4 hexCoord(vec2 uv) {
  uv *= scale;
  vec2 gridRatio = vec2( 1.0, sqrt(3.));
  vec2 halfRatio = gridRatio * .5;
  vec2 gridA = mod(uv, gridRatio)-halfRatio;
  vec2 gridB = mod(uv - halfRatio, gridRatio) - halfRatio; // offset grid with centered gv
  vec2 gv = dot(gridA, gridA) < dot(gridB, gridB) ? gridA : gridB;  // get closest grid coordinate
  
  float x = atan(gv.x, gv.y); // polar coordinate
  float y = .5 - hexDist(gv); // distance to the border
  vec2 id = uv - gv;
  return vec4(x, y, id);
}

vec3 BSC(vec3 color, float brt, float sat, float con) {
  const float AvgLumR = 0.5;
  const float AvgLumG = 0.5;
  const float AvgLumB = 0.5;
  const vec3 LumCoeff = vec3(0.2125, 0.7154, 0.0721);
  vec3 AvgLumin = vec3(AvgLumR, AvgLumG, AvgLumB);
  vec3 brtColor = color * brt;
  vec3 intensity = vec3(dot(brtColor, LumCoeff));
  vec3 satColor = mix(intensity, brtColor, sat);
  vec3 conColor = mix(AvgLumin, satColor, con);
  return conColor;
}

vec3 paintGrid(vec2 uv) {
  float squareWaveDist = sdBox(uv, abs(vec2(sin(time / 2.), sin(time / 2.) / 2.)));
  vec3 color1 = vec3(20. / 255., 20. / 255., 20. / 255.);
  vec3 color2 = vec3(69. / 255., 14. / 255., 32. / 255.);
  vec3 color = vec3(1.);

  float fftOffset = sin(fft) / 100.;
  vec2 offset = vec2(uv.x, uv.y + .15 + fftOffset);
  vec4 hexCoords = hexCoord(uv);
  vec4 hexCoords2 = hexCoord(offset);

  float aa = 5.0 / resolution.y;
  float thickness = .03;

  float c1 = smoothstep( thickness - aa, thickness, hexCoords.y);
  float c2 = smoothstep( thickness - aa, thickness, hexCoords2.y);

  float dist = length(hexCoords.ba  / scale);

  float waveThickness = .1 + fft; // max hex dist
  float wave = sin(time * .5  * (dist)) * 0.5 + 0.5;

  color *= color2 * vec3(step(waveThickness, wave) - step(waveThickness + waveThickness, wave));
  color *= 1.5 * vec3(
    c1 * hexCoords.y +
    c1 * pow(1.0 - max(0., .15 - hexCoords.y), 5.0) * 2.5
  );
  
  
  return color;
}


void main(void) {
  vec2 uv = (gl_FragCoord.xy -.5*resolution.xy) / resolution.y;
  vec3 color = paintGrid(uv);
  color = clamp(BSC(color, 1.2, 0.8, 0.9), 0.0, 1.0);
  fragColor = vec4(color, 1.0);
}