gpuray_glsl
diff 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 diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/sphere.cc Sun Nov 09 13:03:36 2014 +0200 1.3 @@ -0,0 +1,52 @@ 1.4 +#include <stdio.h> 1.5 +#include "sphere.h" 1.6 + 1.7 +Sphere::Sphere() 1.8 +{ 1.9 + radius = 1.0; 1.10 +} 1.11 + 1.12 +Sphere::Sphere(const Vector3 &pos, float rad) 1.13 +{ 1.14 + radius = rad; 1.15 + this->pos = pos; 1.16 +} 1.17 + 1.18 +bool Sphere::intersect(const Ray &inray, HitPoint *pt) const 1.19 +{ 1.20 + Ray ray = inray.transformed(inv_xform); 1.21 + 1.22 + float a = dot_product(ray.dir, ray.dir); 1.23 + float b = 2.0 * ray.dir.x * (ray.origin.x - pos.x) + 1.24 + 2.0 * ray.dir.y * (ray.origin.y - pos.y) + 1.25 + 2.0 * ray.dir.z * (ray.origin.z - pos.z); 1.26 + float c = dot_product(ray.origin, ray.origin) + dot_product(pos, pos) - 1.27 + 2.0 * dot_product(ray.origin, pos) - radius * radius; 1.28 + 1.29 + float discr = b * b - 4.0 * a * c; 1.30 + if(discr < 1e-4) 1.31 + return false; 1.32 + 1.33 + float sqrt_discr = sqrt(discr); 1.34 + float t0 = (-b + sqrt_discr) / (2.0 * a); 1.35 + float t1 = (-b - sqrt_discr) / (2.0 * a); 1.36 + 1.37 + if(t0 < 1e-4) 1.38 + t0 = t1; 1.39 + if(t1 < 1e-4) 1.40 + t1 = t0; 1.41 + 1.42 + float t = t0 < t1 ? t0 : t1; 1.43 + if(t < 1e-4) 1.44 + return false; 1.45 + 1.46 + // fill the HitPoint structure 1.47 + pt->obj = this; 1.48 + pt->dist = t; 1.49 + pt->pos = ray.origin + ray.dir * t; 1.50 + pt->normal = (pt->pos - pos) / radius; 1.51 + 1.52 + pt->pos.transform(xform); 1.53 + pt->normal.transform(dir_xform); 1.54 + return true; 1.55 +}