Cube
By Ayfri
Image
precision mediump float;
uniform float uAspect;
uniform float uDeltaTime;
uniform float uFrameRate;
uniform float uTime;
uniform int uFrameCount;
uniform vec2 uResolution;
uniform vec3 uMouse;
uniform vec4 uDate;
mat2 rotate2D(float angle){
return mat2(
cos(angle),
-sin(angle),
sin(angle),
cos(angle)
);
}
float getCubeDist(vec3 currentRayPos) {
float size = 1.0;
vec3 size3D = vec3(size);
currentRayPos.xz = currentRayPos.xz;
vec3 a = abs(currentRayPos) - size3D;
vec3 b = max(a, 0.0);
return length(b);
}
vec3 getNormal(vec3 p) {
float e = 0.001;
vec3 n = vec3(0.0);
n.x = getCubeDist(vec3(p.x + e, p.yz)) - getCubeDist(vec3(p.x - e, p.yz));
n.y = getCubeDist(vec3(p.x, p.y + e, p.z)) - getCubeDist(vec3(p.x, p.y - e, p.z));
n.z = getCubeDist(vec3(p.xy, p.z + e)) - getCubeDist(vec3(p.xy, p.z - e));
return normalize(n);
}
void main()
{
// colors
vec3 cubeColor = vec3(1.0);
vec3 ambiantColor = vec3(0.1);
// light
vec3 lightColor = vec3(1.0, 0, 0);
vec3 lightPos = vec3(2.0, 2.0, -3.0);
lightPos.x = sin(uTime) * 5.0;
// camera
vec3 cameraPosition = vec3(0.0, 0.0, -6.0);
cameraPosition.x = sin(uTime) * 3.0 * cos(uTime);
cameraPosition.y = sin(uTime) * 2.0;
cameraPosition.z = -5.0 + sin(uTime) * 1.0;
// screen
float aspectRatio = uResolution.x / uResolution.y;
// Normalized pixel coordinates (from -1 to 1)
vec2 uv = ((gl_FragCoord.xy / uResolution.xy) * 2.0 - 1.0);
uv.x *= aspectRatio;
vec3 rayDirection = normalize(vec3(uv.xy, 1.0));
// loop
float totalDistance = 0.0;
for (int i = 0; i < 100; i++) {
vec3 currentRayPos = cameraPosition + rayDirection * totalDistance;
float disanceToScene = getCubeDist(currentRayPos);
totalDistance += disanceToScene;
if (totalDistance < 0.001 || totalDistance > 100.0) break;
}
if (totalDistance < 100.0) {
vec3 position = cameraPosition + rayDirection * totalDistance;
vec3 normal = getNormal(position);
vec3 lightDirection = normalize(lightPos - position);
float diffuseCalc = clamp(dot(normal, lightDirection), 0.0, 1.0);
vec3 finalColor = cubeColor * lightColor * diffuseCalc;
vec3 ambient = ambiantColor * cubeColor;
gl_FragColor = vec4(finalColor + ambient, 1.0);
}
else gl_FragColor = vec4(0.0);
}