erebus

view liberebus/src/geomobj.cc @ 4:93894c232d65

more changes across the board
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 29 Apr 2014 07:38:40 +0300
parents
children e2d9bf168a41
line source
1 #include <float.h>
2 #include "geomobj.h"
4 static LambertRefl lambert;
6 GeomObject::GeomObject()
7 {
8 brdf = &lambert;
9 }
11 ObjType GeomObject::get_type() const
12 {
13 return ObjType::geom;
14 }
16 bool GeomObject::intersect(const Ray &ray, RayHit *hit) const
17 {
18 return false;
19 }
21 // --- class Sphere ---
23 bool Sphere::intersect(const Ray &ray, RayHit *hit) const
24 {
25 // assumes center is the origin and radius is 1
26 float a = dot_product(ray.dir, ray.dir);
27 float b = 2.0 * dot_product(ray.dir, ray.origin);
28 float c = dot_product(ray.origin, ray.origin) - 1.0;
30 float d = b * b - 4.0 * a * c;
31 if(d < 1e-4) return false;
33 float sqrt_d = sqrt(d);
34 float t0 = (-b + sqrt_d) / (2.0 * a);
35 float t1 = (-b - sqrt_d) / (2.0 * a);
37 if(t0 < 1e-4) t0 = t1;
38 if(t1 < 1e-4) t1 = t0;
39 float t = t0 < t1 ? t0 : t1;
40 if(t < 1e-4) return false;
42 if(hit) {
43 hit->dist = t;
44 hit->obj = this;
45 hit->subobj = 0;
46 }
47 return true;
48 }
50 // --- class Box ---
52 bool Box::intersect(const Ray &ray, RayHit *hit) const
53 {
54 return false;
55 }
57 // --- class Triangle ---
59 bool Triangle::intersect(const Ray &ray, RayHit *hit) const
60 {
61 return false;
62 }
64 // --- class Mesh ---
66 bool Mesh::intersect(const Ray &ray, RayHit *hit) const
67 {
68 RayHit nearest;
69 nearest.dist = FLT_MAX;
71 for(size_t i=0; i<faces.size(); i++) {
72 if(faces[i].intersect(ray, hit)) {
73 if(!hit) return true;
74 if(hit->dist < nearest.dist) {
75 nearest = *hit;
76 }
77 }
78 }
80 if(nearest.dist < FLT_MAX) {
81 *hit = nearest;
82 hit->subobj = hit->obj;
83 hit->obj = this;
84 return true;
85 }
86 return false;
87 }