Phongo Clap RT  1.0
Simple Raytracing Renderer
Sphere.cpp
Go to the documentation of this file.
1 
4 #include <cmath>
5 #include <ngl/Vec3.h>
6 #include <ngl/Colour.h>
7 #include "Shape.h"
8 #include "Sphere.h"
9 
10 namespace geo
11 {
13  {
14  float ray_origin_x = ray.getOrigin().m_x;
15  float ray_origin_y = ray.getOrigin().m_y;
16  float ray_origin_z = ray.getOrigin().m_z;
17 
18  float ray_direction_x = ray.getDirection().m_x;
19  float ray_direction_y = ray.getDirection().m_y;
20  float ray_direction_z = ray.getDirection().m_z;
21 
22  float sphere_center_x = this->getCenter().m_x;
23  float sphere_center_y = this->getCenter().m_y;
24  float sphere_center_z = this->getCenter().m_z;
25 
26  //float a = 1;
27  float b = (2*(ray_origin_x - sphere_center_x)*ray_direction_x)
28  + (2*(ray_origin_y - sphere_center_y)*ray_direction_y)
29  + (2*(ray_origin_z - sphere_center_z)*ray_direction_z);
30  float c = pow(ray_origin_x - sphere_center_x, 2)
31  + pow(ray_origin_y - sphere_center_y, 2)
32  + pow(ray_origin_z - sphere_center_z, 2)
33  - (this->getRadius()*this->getRadius());
34  float discriminant = b*b - 4*c;
35 
36  if(discriminant > 0)
37  {
38  //ray intersects sphere
39 
40  // first root
41  float root_1 = ((-1*b - sqrt(discriminant))/2) - 0.000001;
42 
43  if (root_1 > 0)
44  {
45  return root_1;
46  }
47 
48  else
49  {
50  // second root is the smallest positive root
51  float root_2 = ((sqrt(discriminant)-b)/2) - 0.000001;
52  return root_2;
53  }
54  }
55  else
56  {
57  return -1;
58  }
59  }
60 
61  ngl::Vec3 Sphere::getNormalAt(ngl::Vec3 _p)
62  {
63  ngl::Vec3 normal;
64  normal = _p - m_center;
65  normal.normalize();
66  return normal;
67  }
68 }
virtual ngl::Vec3 getNormalAt(ngl::Vec3 _p)
Calculates what the normal is at a given point of a sphere. It doesn't check whether it is on the sur...
Definition: Sphere.cpp:61
ngl::Vec3 getOrigin()
Getter method for the origin.
Definition: Ray.cpp:39
virtual float getIntersection(geo::Ray &_ray)
Calculates the intersection of the passed ray with the sphere according to the parametric form of a r...
Definition: Sphere.cpp:12
A class for implicit sphere definitions.
float getRadius() const
Returns radius of a sphere.
Definition: Sphere.h:71
Definition: Ray.h:17
ngl::Vec3 getCenter() const
Returns center of a sphere.
Definition: Sphere.h:76
ngl::Vec3 m_center
Center of the sphere, in world space coordinates.
Definition: Sphere.h:110
Definition: Plane.cpp:9
ngl::Vec3 getDirection()
Getter method for the direction.
Definition: Ray.cpp:44