gpuray_glsl

view src/sphere.cc @ 0:f234630e38ff

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 09 Nov 2014 13:03:36 +0200
parents
children 297dbc5080c4
line source
1 #include <stdio.h>
2 #include "sphere.h"
4 Sphere::Sphere()
5 {
6 radius = 1.0;
7 }
9 Sphere::Sphere(const Vector3 &pos, float rad)
10 {
11 radius = rad;
12 this->pos = pos;
13 }
15 bool Sphere::intersect(const Ray &inray, HitPoint *pt) const
16 {
17 Ray ray = inray.transformed(inv_xform);
19 float a = dot_product(ray.dir, ray.dir);
20 float b = 2.0 * ray.dir.x * (ray.origin.x - pos.x) +
21 2.0 * ray.dir.y * (ray.origin.y - pos.y) +
22 2.0 * ray.dir.z * (ray.origin.z - pos.z);
23 float c = dot_product(ray.origin, ray.origin) + dot_product(pos, pos) -
24 2.0 * dot_product(ray.origin, pos) - radius * radius;
26 float discr = b * b - 4.0 * a * c;
27 if(discr < 1e-4)
28 return false;
30 float sqrt_discr = sqrt(discr);
31 float t0 = (-b + sqrt_discr) / (2.0 * a);
32 float t1 = (-b - sqrt_discr) / (2.0 * a);
34 if(t0 < 1e-4)
35 t0 = t1;
36 if(t1 < 1e-4)
37 t1 = t0;
39 float t = t0 < t1 ? t0 : t1;
40 if(t < 1e-4)
41 return false;
43 // fill the HitPoint structure
44 pt->obj = this;
45 pt->dist = t;
46 pt->pos = ray.origin + ray.dir * t;
47 pt->normal = (pt->pos - pos) / radius;
49 pt->pos.transform(xform);
50 pt->normal.transform(dir_xform);
51 return true;
52 }