sphere.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Sphere implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <math.h>
  10. #include <sphere.h>
  11. #include <ray.h>
  12. #include <tuple.h>
  13. #include <intersect.h>
  14. Intersect Sphere::intersect(Ray r)
  15. {
  16. Intersect ret;
  17. double a, b, c, discriminant;
  18. Ray transRay = this->invTransform(r);
  19. Tuple sphere_to_ray = transRay.origin - Point(0, 0, 0);
  20. a = transRay.direction.dot(transRay.direction);
  21. b = 2 * transRay.direction.dot(sphere_to_ray);
  22. c = sphere_to_ray.dot(sphere_to_ray) - 1;
  23. discriminant = b * b - 4 * a * c;
  24. if (discriminant >= 0)
  25. {
  26. ret.add(Intersection((-b - sqrt(discriminant)) / (2 * a), this));
  27. ret.add(Intersection((-b + sqrt(discriminant)) / (2 * a), this));
  28. }
  29. return ret;
  30. }
  31. Tuple Sphere::normalAt(Tuple point)
  32. {
  33. Tuple object_point = this->inverseTransform * point;
  34. Tuple object_normal = (object_point - Point(0, 0, 0)).normalise();
  35. Tuple world_normal = this->inverseTransform.transpose() * object_normal;
  36. /* W may get wrong, so hack it. This is perfectly normal as we are using a 4x4 matrix instead of a 3x3 */
  37. world_normal.w = 0;
  38. return world_normal.normalise();
  39. }