gpuray_glsl

view src/sphere.cc @ 5:000017955721

fixed the cone normal
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 11 Nov 2014 20:25:59 +0200
parents f234630e38ff
children
line source
1 /*
2 Simple introductory ray tracer
3 Copyright (C) 2012 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 #include <stdio.h>
19 #include "sphere.h"
21 Sphere::Sphere()
22 {
23 radius = 1.0;
24 }
26 Sphere::Sphere(const Vector3 &pos, float rad)
27 {
28 radius = rad;
29 this->pos = pos;
30 }
32 bool Sphere::intersect(const Ray &inray, HitPoint *pt) const
33 {
34 Ray ray = inray.transformed(inv_xform);
36 float a = dot_product(ray.dir, ray.dir);
37 float b = 2.0 * ray.dir.x * (ray.origin.x - pos.x) +
38 2.0 * ray.dir.y * (ray.origin.y - pos.y) +
39 2.0 * ray.dir.z * (ray.origin.z - pos.z);
40 float c = dot_product(ray.origin, ray.origin) + dot_product(pos, pos) -
41 2.0 * dot_product(ray.origin, pos) - radius * radius;
43 float discr = b * b - 4.0 * a * c;
44 if(discr < 1e-4)
45 return false;
47 float sqrt_discr = sqrt(discr);
48 float t0 = (-b + sqrt_discr) / (2.0 * a);
49 float t1 = (-b - sqrt_discr) / (2.0 * a);
51 if(t0 < 1e-4)
52 t0 = t1;
53 if(t1 < 1e-4)
54 t1 = t0;
56 float t = t0 < t1 ? t0 : t1;
57 if(t < 1e-4)
58 return false;
60 // fill the HitPoint structure
61 pt->obj = this;
62 pt->dist = t;
63 pt->pos = ray.origin + ray.dir * t;
64 pt->normal = (pt->pos - pos) / radius;
66 pt->pos.transform(xform);
67 pt->normal.transform(dir_xform);
68 return true;
69 }