Last active
August 29, 2015 14:22
-
-
Save ulyssesdotcodes/c98a3c64c97c6c876c0c to your computer and use it in GitHub Desktop.
GLSL talk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
float intersectSphere(vec3 origin, vec3 direction, vec3 center, float radius) { | |
vec3 co = origin - center; | |
float b = dot(co, direction); | |
float a = dot(co, co) - radius * radius; | |
float d = b * b - a; | |
if (d <= 0.0) { | |
return -1.0; | |
} | |
float t = -b - sqrt(b * b - a); | |
return t; | |
} | |
float intersectGround(vec3 origin, vec3 direction) { | |
return -origin.y / direction.y; | |
} | |
float intersect(vec3 origin, vec3 direction, vec3 sphereCenter, float sphereRadius, out float dist) { | |
float ground = intersectGround(origin, direction); | |
float sphere = intersectSphere(origin, direction, sphereCenter, sphereRadius); | |
if (ground + sphere <= 0.0) { | |
return 0.0; | |
} | |
if(sphere <= 0.0 || ground < sphere) { | |
dist = ground; | |
return 1.0; | |
} | |
if(ground <= 0.0 || sphere < ground) { | |
dist = sphere; | |
return 2.0; | |
} | |
} | |
void main(void) { | |
vec2 position = gl_FragCoord.xy / resolution.xy; | |
vec2 p = -1.0 + 2.0 * position; | |
p.x *= resolution.x / resolution.y; | |
vec3 origin = vec3(cos(mouse.x * 2.0 * 3.1415) * 5.0, 1.0, sin(mouse.x * 2.0 * 3.1415) * 5.0); | |
vec3 ww = normalize(vec3(0.0) - origin); | |
vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0))); | |
vec3 vv = normalize(cross(uu, ww)); | |
vec3 direction = normalize(p.x*uu + p.y * vv + ww); | |
float sphereRadius = 0.5; | |
vec3 sphereCenter = vec3(0.0, sphereRadius, 0.0); | |
float dist = -1.0; | |
float id = intersect(origin, direction, sphereCenter, sphereRadius, dist); | |
vec3 color = vec3(0.0); | |
if (id > 0.0) { | |
vec3 hit = origin + direction * dist; | |
vec3 light = normalize(vec3(-1.0, 1.0, -1.0)); | |
if (id == 1.0) { | |
color = vec3(1.0, 1.0, 1.0) * (length(hit.xz - sphereCenter.xz) / sphereRadius); | |
} | |
else if(id == 2.0) { | |
float diffuse = dot(light, (hit - sphereCenter) * (1.0 / sphereRadius)); | |
color = vec3(1.0) * diffuse; | |
} | |
} | |
gl_FragColor = vec4(color, 1.0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment