summaryrefslogtreecommitdiff
path: root/src/shaders/ray_sphere.wgsl
diff options
context:
space:
mode:
Diffstat (limited to 'src/shaders/ray_sphere.wgsl')
-rw-r--r--src/shaders/ray_sphere.wgsl21
1 files changed, 21 insertions, 0 deletions
diff --git a/src/shaders/ray_sphere.wgsl b/src/shaders/ray_sphere.wgsl
new file mode 100644
index 0000000..659e144
--- /dev/null
+++ b/src/shaders/ray_sphere.wgsl
@@ -0,0 +1,21 @@
+// Ray-sphere intersection.
+// ro: ray origin, rd: ray direction (must be normalized).
+// center: sphere center, radius: sphere radius.
+// Returns t of the nearest positive intersection, or -1.0 if no hit.
+
+struct RaySphereHit {
+ t: f32, // distance along ray to nearest hit (negative = miss)
+ hit: bool,
+};
+
+fn ray_sphere_intersection(ro: vec3f, rd: vec3f,
+ center: vec3f, radius: f32) -> RaySphereHit {
+ let oc = ro - center;
+ let b = dot(oc, rd);
+ let c = dot(oc, oc) - radius * radius;
+ let disc = b * b - c;
+ if (disc < 0.0) { return RaySphereHit(-1.0, false); }
+ let t = -b - sqrt(disc);
+ if (t < 0.0) { return RaySphereHit(-1.0, false); }
+ return RaySphereHit(t, true);
+}