gpuray_glsl

annotate src/sphere.cc @ 3:297dbc5080c4

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