shader-web-test/raymarcher.glsl

67 lines
1.6 KiB
Text
Raw Normal View History

#version 300 es
precision highp float;
// Inputs
in vec2 texture_coordinates;
uniform float time;
uniform sampler2D uSampler1;
uniform sampler2D uSampler2;
2024-12-17 23:37:57 -08:00
uniform vec3 camera_pos;
// Output
out vec4 color;
const float PI = 3.1415;
2024-12-17 23:37:57 -08:00
// Raymarching variables
#define MAX_ITERATIONS 20
#define MIN_TOLERANCE .01
//const vec3 camera_pos = vec3(0.);
const vec3 color1 = vec3(0.494, 0.361, 0.678);
const vec3 color2 = vec3(0.827, 0.945, 0.875);
// Scene Object (sphere)
// returns the distance from the ray to this sphere in the scene
float sphere_render(vec3 ray_pos, float radius, vec3 sphere_pos) {
2024-12-18 00:32:49 -08:00
return distance(ray_pos, sphere_pos) - radius;
2024-12-17 23:37:57 -08:00
}
2024-12-18 00:32:49 -08:00
float remap11(float val) {
return ((val - .5) * 2.);
2024-12-17 23:37:57 -08:00
}
void main() {
2024-12-18 00:32:49 -08:00
// Set up camera and sphere object
vec3 ray_dir = normalize(vec3(remap11(texture_coordinates.x), remap11(texture_coordinates.y), 1.));
vec3 ray_pos = camera_pos;
const vec3 sphere_pos = vec3(0., 0., 3.);
const float rad = 1.;
2024-12-17 23:37:57 -08:00
2024-12-18 00:32:49 -08:00
for (int i = 0; i < MAX_ITERATIONS; i++) {
float distance = sphere_render(ray_pos, rad, sphere_pos);
2024-12-17 23:37:57 -08:00
2024-12-18 00:32:49 -08:00
// Check If within tolerances
if (distance < MIN_TOLERANCE) {
break;
}
2024-12-17 23:37:57 -08:00
2024-12-18 00:32:49 -08:00
ray_pos += (distance * ray_dir);
color = vec4(mix(color1, color2, float(i) / float(MAX_ITERATIONS)), 1.);
2024-12-17 23:37:57 -08:00
}
2024-12-18 00:32:49 -08:00
// Image stuff for later
/*
if ((texture_coordinates.x + texture_coordinates.y) > 1.) {
color = texture(uSampler1, texture_coordinates);
}
else {
color = texture(uSampler2, texture_coordinates);
}*/
// Basic color time shift
// color = vec4( texture_coordinates, (sin( time * PI) + 1.)/2. , 1.);
}