The Code Therapy

my raynarch

this uses raymaching and perlin noise

Created by purplejragon on Thu, 26 Jan 2023 15:32:05 GMT.


#version 300 es
precision highp float;

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

#define MAGIC 43758.5453123

float random (vec2 st) {
    float s = dot(st, vec2(0.400,0.230));
    return -1. + 2. * fract(sin(s) * MAGIC);
}

vec2 random2(vec2 st){
    vec2 s = vec2(
      dot(st, vec2(127.1,311.7)),
      dot(st, vec2(269.5,183.3))
    );
    return -1. + 2. * fract(sin(s) * MAGIC);
}
float dotGridToGradient(vec2 cell, vec2 pos) {
  vec2 gradient = random2(cell);
  vec2 cellToPos = pos - cell;
  return dot(cellToPos, gradient);
}
float perlin(vec2 pos) {
  vec2 cell = floor(pos);
  vec2 f = smoothstep(vec2(0.), vec2(1.), fract(pos));

  float bl = dotGridToGradient(cell, pos);
  float br = dotGridToGradient(cell + vec2(1.0, 0.0), pos);
  float b = mix(bl, br, f.x);
  float tl = dotGridToGradient(cell + vec2(0.0, 1.0), pos);
  float tr = dotGridToGradient(cell + vec2(1.0, 1.0), pos);
  float t = mix(tl, tr, f.x);
  return mix(b, t, f.y);
}
float height(in vec3 p) {
  float s = 1.0;
  float d = 0.0;
  for (int i = 0; i < 6; i++) {
    float n = s * perlin(p.xz);
    d += n;
    p *= 2.0;
    s *= 0.5;
  }
  return d;
}
float sphere(vec3 p, float r) {
  return length(p) - r;
}
float map(vec3 p) {
  return p.y - height(p / 4.0) * 4.0;
}
vec3 calcNormal(vec3 p)
{
    const float eps = 0.0001;
    const vec2 h = vec2(eps,0);
    return normalize( vec3(map(p+h.xyy) - map(p-h.xyy),
                           map(p+h.yxy) - map(p-h.yxy),
                           map(p+h.yyx) - map(p-h.yyx) ) );
}
float raymarch(vec3 ro, vec3 rd) {
  vec3 p = vec3(0.0);
  float t = 0.0;
  for (int i = 0; i < 500; i++) {
    p = ro + rd * t;
    float dist = map(p);
    t += dist;
    if (t > 100.0) return -1.0;
    if (dist <= 0.01) return t;
  }
  return t;
}

void main(void) {
  vec2 uv = gl_FragCoord.xy / resolution;
  vec3 ro = vec3(0, 2.0, 3.0);
  vec3 rd = normalize(vec3((gl_FragCoord.xy - 0.5 * resolution) / resolution.y, -1.0));
  float t = raymarch(ro, rd);
  vec3 col = vec3(0.0);
  if (t > 0.0) {
    vec3 p = ro + rd * t;
    vec3 n = calcNormal(p);
    col = n * 0.5 + 0.5;
  }
  fragColor = vec4(col, 1.0);
}