sphere.cpp 864 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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::localIntersect(Ray r)
  15. {
  16. Intersect ret;
  17. double a, b, c, discriminant;
  18. Tuple sphere_to_ray = r.origin - Point(0, 0, 0);
  19. a = r.direction.dot(r.direction);
  20. b = 2 * r.direction.dot(sphere_to_ray);
  21. c = sphere_to_ray.dot(sphere_to_ray) - 1;
  22. discriminant = b * b - 4 * a * c;
  23. if (discriminant >= 0)
  24. {
  25. ret.add(Intersection((-b - sqrt(discriminant)) / (2 * a), this));
  26. ret.add(Intersection((-b + sqrt(discriminant)) / (2 * a), this));
  27. }
  28. return ret;
  29. }
  30. Tuple Sphere::localNormalAt(Tuple point)
  31. {
  32. return (point - Point(0, 0, 0)).normalise();
  33. }