Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. struct Ellipsoid : public Intersectable {
  2.     vec3 center;
  3.     float a;
  4.     float b;
  5.     float c;
  6.  
  7.     Ellipsoid(const vec3& _center, float _a, float _b, float _c, Material* _material) {
  8.         center = _center;
  9.         a = _a;
  10.         b = _b;
  11.         c = _c;
  12.         material = _material;
  13.     }
  14.  
  15.     Hit intersect(const Ray& ray) {
  16.         Hit hit;
  17.         mat4 M(
  18.             1.0f / (a*a), 0, 0, 0,
  19.             0, 1.0f / (b*b), 0, 0,
  20.             0, 0, 1.0f / (c*c), 0,
  21.             0, 0, 0, -1
  22.         );
  23.  
  24.         vec4 v(ray.dir, 0);
  25.         vec4 eye(ray.start-center, 1);
  26.        
  27.         float A = dot(v*M,v);
  28.        
  29.         float B = dot(eye*M, v) + dot(v*M, eye);
  30.        
  31.         float C = dot(eye*M,eye);
  32.  
  33.         float discr = B * B - 4.0 * A * C;
  34.         if (discr < 0) return hit;
  35.         float sqrt_discr = sqrtf(discr);
  36.         float t1 = (-B + sqrt_discr) / 2.0 / A;
  37.         float t2 = (-B - sqrt_discr) / 2.0 / A;
  38.         if (t1 <= 0 && t2 <= 0) return hit;
  39.         if (t1 <= 0 && t2 > 0)       hit.t = t2;
  40.         else if (t2 <= 0 && t1 > 0)  hit.t = t1;
  41.         else if (t1 < t2)            hit.t = t1;
  42.         else                         hit.t = t2;
  43.        
  44.         hit.position = ray.start + ray.dir * hit.t;
  45.         float x_c = hit.position.x - center.x;
  46.         float y_c = hit.position.y - center.y;
  47.         float z_c = hit.position.z - center.z;
  48.         hit.normal = vec3(x_c/(a*a), y_c/(b*b), z_c/(c*c)).normalize();
  49.         if (dot(hit.normal, ray.dir) > 0) hit.normal = hit.normal * (-1);
  50.         hit.material = material;
  51.         return hit;
  52.     }
  53. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement