sphere.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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, Intersection *hit)
  31. {
  32. return (point - Point(0, 0, 0)).normalise();
  33. }
  34. void Sphere::dumpMe(FILE *fp)
  35. {
  36. fprintf(fp, "\"Type\": \"Sphere\",\n");
  37. Tuple t = this->transformMatrix * Point(0, 0, 0);
  38. fprintf(fp, "\"center\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  39. t.x, t.y, t.z);
  40. t = this->transformMatrix * Point(1, 1, 1);
  41. fprintf(fp, "\"radius\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  42. t.x, t.y, t.z);
  43. Shape::dumpMe(fp);
  44. }