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. void Sphere::localIntersect(Ray r, Intersect &xs)
  15. {
  16. double a, b, c, discriminant;
  17. Tuple sphere_to_ray = r.origin - Point(0, 0, 0);
  18. a = r.direction.dot(r.direction);
  19. b = 2 * r.direction.dot(sphere_to_ray);
  20. c = sphere_to_ray.dot(sphere_to_ray) - 1;
  21. discriminant = b * b - 4 * a * c;
  22. if (discriminant >= 0)
  23. {
  24. xs.add(Intersection((-b - sqrt(discriminant)) / (2 * a), this));
  25. xs.add(Intersection((-b + sqrt(discriminant)) / (2 * a), this));
  26. }
  27. }
  28. Tuple Sphere::localNormalAt(Tuple point, Intersection *hit)
  29. {
  30. return (point - Point(0, 0, 0)).normalise();
  31. }
  32. void Sphere::dumpMe(FILE *fp)
  33. {
  34. fprintf(fp, "\"Type\": \"Sphere\",\n");
  35. Tuple t = this->transformMatrix * Point(0, 0, 0);
  36. fprintf(fp, "\"center\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  37. t.x, t.y, t.z);
  38. t = this->transformMatrix * Point(1, 1, 1);
  39. fprintf(fp, "\"radius\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  40. t.x, t.y, t.z);
  41. Shape::dumpMe(fp);
  42. }