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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! Triangle primitive for ray tracing (VIZ-016)
//!
//! This module implements ray-triangle intersection using the Möller-Trumbore algorithm,
//! which is the industry-standard method for efficient ray-triangle intersection testing.
//!
//! Single Responsibility: Ray-triangle intersection math only.
use super::hittable::{HitRecord, Hittable};
use super::math::{Ray, Vector3};
/// A single triangle defined by three vertices
///
/// Triangles are the fundamental building block of 3D meshes.
/// This implementation supports both flat shading (using geometric normal)
/// and smooth shading (using interpolated vertex normals).
#[derive(Debug, Clone, Copy)]
pub struct Triangle {
/// First vertex position
pub v0: Vector3,
/// Second vertex position
pub v1: Vector3,
/// Third vertex position
pub v2: Vector3,
/// Optional normal at v0 (for smooth shading)
pub n0: Option<Vector3>,
/// Optional normal at v1 (for smooth shading)
pub n1: Option<Vector3>,
/// Optional normal at v2 (for smooth shading)
pub n2: Option<Vector3>,
}
impl Triangle {
/// Create a new triangle with flat shading (no vertex normals)
///
/// The geometric normal will be computed from the triangle's vertices.
#[inline]
pub fn new(v0: Vector3, v1: Vector3, v2: Vector3) -> Self {
Self {
v0,
v1,
v2,
n0: None,
n1: None,
n2: None,
}
}
/// Create a new triangle with smooth shading (vertex normals provided)
///
/// Normals will be interpolated across the triangle surface using
/// barycentric coordinates for smooth shading.
#[inline]
pub fn with_normals(
v0: Vector3,
v1: Vector3,
v2: Vector3,
n0: Vector3,
n1: Vector3,
n2: Vector3,
) -> Self {
Self {
v0,
v1,
v2,
n0: Some(n0),
n1: Some(n1),
n2: Some(n2),
}
}
/// Calculate the geometric (face) normal of the triangle
///
/// This is computed from the cross product of two edges.
/// Used for flat shading when vertex normals are not provided.
#[inline]
fn geometric_normal(&self) -> Vector3 {
let edge1 = self.v1 - self.v0;
let edge2 = self.v2 - self.v0;
edge1.cross(&edge2).normalize()
}
}
impl Hittable for Triangle {
/// Test ray-triangle intersection using Möller-Trumbore algorithm
///
/// This is the industry-standard algorithm for ray-triangle intersection.
/// It computes barycentric coordinates (u, v, w) which are used for:
/// - Determining if the ray hits inside the triangle
/// - Interpolating vertex normals for smooth shading
///
/// Algorithm reference: Möller & Trumbore (1997)
/// "Fast, Minimum Storage Ray-Triangle Intersection"
fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
// Epsilon for floating-point comparisons
const EPSILON: f32 = 1e-6;
// Compute edges from v0
let edge1 = self.v1 - self.v0;
let edge2 = self.v2 - self.v0;
// Begin calculating determinant - also used to calculate u parameter
let h = ray.direction.cross(&edge2);
let a = edge1.dot(&h);
// If determinant is near zero, ray is parallel to triangle
if a.abs() < EPSILON {
return None;
}
let f = 1.0 / a;
let s = ray.origin - self.v0;
let u = f * s.dot(&h);
// Check if intersection is outside triangle (barycentric u coordinate)
if !(0.0..=1.0).contains(&u) {
return None;
}
let q = s.cross(&edge1);
let v = f * ray.direction.dot(&q);
// Check if intersection is outside triangle (barycentric v coordinate)
if v < 0.0 || u + v > 1.0 {
return None;
}
// At this point we can compute t to find out where the intersection point is on the line
let t = f * edge2.dot(&q);
// Check if intersection is within valid ray range
if t < t_min || t > t_max {
return None;
}
// We have a valid intersection!
let point = ray.at(t);
// Compute normal: interpolate if vertex normals provided, else use geometric normal
let normal = if let (Some(n0), Some(n1), Some(n2)) = (self.n0, self.n1, self.n2) {
// Smooth shading: interpolate normals using barycentric coordinates
// w = 1 - u - v (third barycentric coordinate)
let w = 1.0 - u - v;
(n0 * w + n1 * u + n2 * v).normalize()
} else {
// Flat shading: use geometric normal
self.geometric_normal()
};
Some(HitRecord::new(point, normal, t, ray))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn approx_equal(a: f32, b: f32) -> bool {
(a - b).abs() < 1e-4
}
#[test]
fn test_triangle_hit_center() {
// Triangle in XY plane at z = -3
let tri = Triangle::new(
Vector3::new(-1.0, 0.0, -3.0),
Vector3::new(1.0, 0.0, -3.0),
Vector3::new(0.0, 1.0, -3.0),
);
// Ray from origin pointing at center of triangle
let ray = Ray::new(Vector3::new(0.0, 0.3, 0.0), Vector3::new(0.0, 0.0, -1.0));
let hit = tri.hit(&ray, 0.001, f32::MAX);
assert!(hit.is_some(), "Ray should hit triangle center");
let hit = hit.unwrap();
assert!(approx_equal(hit.t, 3.0), "Hit distance should be ~3.0");
assert!(
approx_equal(hit.point.z, -3.0),
"Hit point should be at z=-3"
);
}
#[test]
fn test_triangle_hit_vertex() {
// Triangle in XY plane at z = -3
let tri = Triangle::new(
Vector3::new(-1.0, 0.0, -3.0),
Vector3::new(1.0, 0.0, -3.0),
Vector3::new(0.0, 1.0, -3.0),
);
// Ray pointing directly at v0
let ray = Ray::new(Vector3::new(-1.0, 0.0, 0.0), Vector3::new(0.0, 0.0, -1.0));
let hit = tri.hit(&ray, 0.001, f32::MAX);
assert!(hit.is_some(), "Ray should hit triangle vertex");
}
#[test]
fn test_triangle_miss_outside() {
// Triangle in XY plane at z = -3
let tri = Triangle::new(
Vector3::new(-1.0, 0.0, -3.0),
Vector3::new(1.0, 0.0, -3.0),
Vector3::new(0.0, 1.0, -3.0),
);
// Ray pointing way outside the triangle
let ray = Ray::new(Vector3::new(5.0, 5.0, 0.0), Vector3::new(0.0, 0.0, -1.0));
let hit = tri.hit(&ray, 0.001, f32::MAX);
assert!(hit.is_none(), "Ray should miss triangle");
}
#[test]
fn test_triangle_miss_parallel() {
// Triangle in XY plane at z = -3
let tri = Triangle::new(
Vector3::new(-1.0, 0.0, -3.0),
Vector3::new(1.0, 0.0, -3.0),
Vector3::new(0.0, 1.0, -3.0),
);
// Ray parallel to triangle (pointing along X axis)
let ray = Ray::new(Vector3::new(0.0, 0.5, -3.0), Vector3::new(1.0, 0.0, 0.0));
let hit = tri.hit(&ray, 0.001, f32::MAX);
assert!(hit.is_none(), "Parallel ray should miss triangle");
}
#[test]
fn test_triangle_miss_behind() {
// Triangle in XY plane at z = -3
let tri = Triangle::new(
Vector3::new(-1.0, 0.0, -3.0),
Vector3::new(1.0, 0.0, -3.0),
Vector3::new(0.0, 1.0, -3.0),
);
// Ray pointing away from triangle
let ray = Ray::new(Vector3::new(0.0, 0.3, 0.0), Vector3::new(0.0, 0.0, 1.0));
let hit = tri.hit(&ray, 0.001, f32::MAX);
assert!(hit.is_none(), "Ray pointing away should miss triangle");
}
#[test]
fn test_triangle_geometric_normal() {
// Triangle in XY plane, normal should point in +Z direction
let tri = Triangle::new(
Vector3::new(-1.0, 0.0, 0.0),
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(0.0, 1.0, 0.0),
);
let normal = tri.geometric_normal();
// Normal should point in +Z direction (perpendicular to XY plane)
assert!(approx_equal(normal.x, 0.0), "Normal X should be 0");
assert!(approx_equal(normal.y, 0.0), "Normal Y should be 0");
assert!(approx_equal(normal.z.abs(), 1.0), "Normal Z should be ±1");
}
#[test]
fn test_triangle_smooth_shading() {
// Triangle with custom vertex normals (all pointing in +Z)
let tri = Triangle::with_normals(
Vector3::new(-1.0, 0.0, -3.0),
Vector3::new(1.0, 0.0, -3.0),
Vector3::new(0.0, 1.0, -3.0),
Vector3::new(0.0, 0.0, 1.0), // n0
Vector3::new(0.0, 0.0, 1.0), // n1
Vector3::new(0.0, 0.0, 1.0), // n2
);
let ray = Ray::new(Vector3::new(0.0, 0.3, 0.0), Vector3::new(0.0, 0.0, -1.0));
let hit = tri.hit(&ray, 0.001, f32::MAX).expect("Should hit");
// Interpolated normal should be close to +Z
assert!(
approx_equal(hit.normal.z.abs(), 1.0),
"Interpolated normal should point in Z"
);
}
#[test]
fn test_triangle_edge_case_tiny() {
// Very small triangle (but not degenerate)
let tri = Triangle::new(
Vector3::new(0.0, 0.0, -3.0),
Vector3::new(0.01, 0.0, -3.0),
Vector3::new(0.0, 0.01, -3.0),
);
let ray = Ray::new(
Vector3::new(0.003, 0.003, 0.0),
Vector3::new(0.0, 0.0, -1.0),
);
let hit = tri.hit(&ray, 0.001, f32::MAX);
assert!(hit.is_some(), "Should hit tiny triangle");
}
#[test]
fn test_triangle_t_range() {
// Triangle at z = -3
let tri = Triangle::new(
Vector3::new(-1.0, 0.0, -3.0),
Vector3::new(1.0, 0.0, -3.0),
Vector3::new(0.0, 1.0, -3.0),
);
let ray = Ray::new(Vector3::new(0.0, 0.3, 0.0), Vector3::new(0.0, 0.0, -1.0));
// Hit should be rejected if t_max is too small
let hit = tri.hit(&ray, 0.001, 2.0);
assert!(
hit.is_none(),
"Should miss if t_max < intersection distance"
);
// Hit should be accepted if t_max is large enough
let hit = tri.hit(&ray, 0.001, 10.0);
assert!(hit.is_some(), "Should hit if t_max > intersection distance");
}
}