Size: 1321 bytes.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// cs/renderer/shapes/sphere.cc
#include "cs/renderer/shapes/sphere.hh"

#include <cmath>

#include "cs/renderer/geo/dot.hh"
#include "cs/renderer/geo/ray3.h"
#include "cs/renderer/precision/floats.hh"
#include "cs/renderer/shapes/shape.hh"

using r3 = ::cs::renderer::geo::Ray3;
using v3 = ::cs::renderer::geo::Vector3;
using p3 = ::cs::renderer::geo::Point3;
using ::cs::renderer::geo::dot;
using ::cs::renderer::precision::FloatsNear;

bool cs::renderer::shapes::Sphere::intersected_by(
    r3 ray, p3* at_point, v3* at_normal) {
  float a = dot(ray.direction, ray.direction);
  float b = 2 * dot(ray.direction, (ray.origin - center));
  float c =
      dot((ray.origin - center), (ray.origin - center)) -
      radius * radius;

  if (!FloatsNear(a, 1.f)) {
    return false;
  }

  float discriminant = b * b - 4 * c;
  if (discriminant < 0.f) {
    return false;
  }

  float t_intersect;
  float t0 = (-b + sqrtf(discriminant)) / 2.f;
  float t1 = (-b - sqrtf(discriminant)) / 2.f;
  // Intersection time must be the positve solution
  if (t0 < t1) {
    t_intersect = t0;  // LCOV_EXCL_LINE
  } else {
    t_intersect = t1;
  }

  p3 intersection = ray(t_intersect);
  v3 normal = ((intersection - center) / radius);
  normal = normal.unit();

  *at_point = intersection;
  *at_normal = normal;
  return true;
};
v0 (commit) © 2025 @p13i.io | Load balancer proxied to: cs-code-viewer-3:8080 in 3ms.