/Users/lyon/j4p/src/graphics/raytracers/tracer/primatives/Sphere.java
|
1 package graphics.raytracers.tracer.primatives;
2
3 import graphics.raytracers.tracer.geometry.Ray3d;
4 import graphics.raytracers.tracer.geometry.Vector3d;
5
6 public class Sphere extends Primitive {
7 Vector3d c;
8 double r, r2;
9
10 public Sphere(Vector3d center, double radius) {
11 c = center;
12 r = radius;
13 r2 = r * r;
14 }
15
16 public Isect intersect(Ray3d ry) {
17 double b, disc, t;
18 Isect ip;
19 Vector3d v;
20 v = Vector3d.sub(c, ry.getStartPoint());
21 b = Vector3d.dot(v, ry.getDirection());
22 disc = b * b - Vector3d.dot(v, v) + r2;
23 if (disc < 0.0) {
24 return null;
25 }
26 disc = Math.sqrt(disc);
27 t = (b - disc < 1e-6) ? b + disc : b - disc;
28 if (t < 1e-6) {
29 return null;
30 }
31 ip = new Isect();
32 ip.t = t;
33 ip.enter = Vector3d.dot(v, v) > r2 + 1e-6 ? 1 : 0;
34 ip.prim = this;
35 ip.surf = surf;
36 return ip;
37 }
38
39 public Vector3d normal(Vector3d p) {
40 Vector3d r;
41 r = Vector3d.sub(p, c);
42 r.normalize();
43 return r;
44 }
45
46 public String toString() {
47 return "Sphere {" + c.toString() + "," + r + "}";
48 }
49 }
50