indicatrix 0.9.0

A physically-based spectral gemstone renderer that turns GemCAD-style cutting instructions into rendered output.
Documentation
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! Primary-ray-only guide-buffer prepass for denoising radiance that came without guides.
//!
//! An image whose radiance arrived without guide buffers (a remote worker's summed XYZ,
//! or a coordinator's merged lane sum) can then still be denoised by the same
//! edge-avoiding À-Trous filter the local render loop uses.
//!
//! # Why this exists
//!
//! [`crate::renderer::denoise`] is edge-avoiding: it needs a first-hit depth/normal/
//! facet-id per pixel to decide which neighbours may blend together. The GUI's local
//! render loop gets those for free from `trace_spectral_ray`'s `primary_hit_out`
//! parameter; a remote worker's `FRAME`/`PREVIEW` payload carries only summed XYZ
//! radiance, so guide buffers never travel over the wire. Instead this module casts one
//! un-jittered camera ray per pixel and records its first hit via the same
//! intersection `trace_spectral_ray` makes at bounce 0 (through the bit-identical SIMD
//! twin of `intersect_polyhedron`, with the plane arena built once per call), without paying
//! for anything downstream (wavelengths, Stokes vectors, Fresnel splitting).
//!
//! The guides depend only on camera pose and the active facet geometry -- never on which
//! backend produced the radiance, and never on light direction, material or exposure --
//! so a caller computes them once per pose/geometry and reuses them for every frame of
//! that accumulation (the GUI's `bridge::frame_cache::guide_pass::GuideCache`, or a
//! coordinator's per-request display denoiser).
//!
//! # Measured cost
//!
//! One [`generate_guide_buffers`] call, parallel across `thread::available_parallelism`
//! (`StandardGemCuts::standard_round_brilliant`): ~19ms at 800x600, ~82ms at 1920x1080,
//! ~288ms at 3840x2160 -- large enough at 4K that a UI or socket thread runs it on a
//! background thread via [`generate_guide_buffers_cancellable`]. Cancellation is
//! cooperative, via an `AtomicBool` checked between rows.
//!
//! On `wasm32` the prepass runs on the calling thread: `std::thread::Scope::spawn`
//! panics there, so the thread count is pinned to 1 exactly like
//! `renderer::tonemap`/`renderer::denoise` do. Every pixel is a pure function of the
//! camera and planes, so the single-thread output is bit-identical to the threaded one.
//!
//! # Path signature
//!
//! With a refractive index `n_d > 1` the prepass also follows the un-jittered centre ray
//! through the stone at that one index (ordinary ray, Snell refraction, total internal
//! reflection, at most [`SIGNATURE_BOUNCES`] interior hits) and hashes the facets it meets
//! into [`GuideBuffers::path_sig`]. The reflection pattern seen inside one crown facet is
//! the map of those interior facet regions, so the denoiser uses the signature as a second
//! hard edge-stop (`GBuffers::path_sig`). `n_d <= 1` (the old entry points pass `0.0`)
//! means "no signature": the buffer is all zeros. The walk uses plain `f32` operations,
//! never `mul_add`, so `wasm32` and x86 hash identical signatures.
//!
//! CPU only: no GPU program is involved, so this never takes a `GpuBackend` turn.
//!
//! Moved here unchanged from `apps/indicatrix-cut`'s `bridge::frame_cache::guide_pass`
//! (which re-exports it) so a server can reproduce the viewer's denoised picture;
//! `renderer::frame_denoise`'s pin test covers this prepass together with the denoise.

use crate::{
    geometry::{
        plane::GpuFacetPlane,
        tool::{StoneGeometry, ToolPrimitive},
    },
    optics::raytracer::{
        Camera, HitRecord, Ray, build_plane_soa, intersect_stone::intersect_stone_soa,
    },
    simd::PlanesSoA32,
};
use glam::Vec3;
use std::{
    sync::{
        Mutex,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
    thread,
};

/// One pixel-per-camera-ray depth/normal/facet-id capture.
///
/// Row-major (`index = y * width + x`) -- exactly the shape [`crate::renderer::denoise::GBuffers`]
/// expects for its `depth`/`normal`/`facet_id` fields.
#[derive(Debug, Clone)]
pub struct GuideBuffers {
    /// First-hit ray parameter `t` per pixel; `1.0e6` for a miss.
    pub depth: Vec<f32>,
    /// First-hit facet normal per pixel; [`Vec3::ZERO`] for a miss.
    pub normal: Vec<Vec3>,
    /// First-hit facet index per pixel; `-1` for a miss.
    pub facet_id: Vec<i32>,
    /// Hash of the facets the centre ray meets inside the stone (see the module docs'
    /// "Path signature"); `0` for a miss and for every pixel when no index was given.
    pub path_sig: Vec<u32>,
}

impl GuideBuffers {
    /// An all-miss buffer of the given size: `depth = 1.0e6` (matching the GUI render
    /// loop's own "no hit yet" sentinel), `normal = ZERO`, `facet_id = -1`, `path_sig = 0`.
    #[must_use]
    pub fn miss(width: u32, height: u32) -> Self {
        let pixel_count = (width as usize) * (height as usize);
        Self {
            depth: vec![1.0e6; pixel_count],
            normal: vec![Vec3::ZERO; pixel_count],
            facet_id: vec![-1; pixel_count],
            path_sig: vec![0; pixel_count],
        }
    }
}

/// Casts one un-jittered camera ray per pixel and records its first hit.
///
/// Thin wrapper over [`generate_guide_buffers_cancellable`] with a cancel flag that's
/// never set, so it always runs to completion.
///
/// # Panics
///
/// Never in practice: the wrapped call only returns `None` once its cancel flag is set,
/// and this one's never is.
#[must_use]
pub fn generate_guide_buffers(
    width: u32,
    height: u32,
    camera: &Camera,
    planes: &[GpuFacetPlane],
) -> GuideBuffers {
    generate_guide_buffers_with_index(width, height, camera, planes, 0.0)
}

/// [`generate_guide_buffers`] that also fills [`GuideBuffers::path_sig`].
///
/// The signature is for the reference refractive index `n_d` (`DispersionModel::n_d`).
/// `n_d <= 1.0` (or NaN) leaves
/// the signature all zeros, which is exactly what [`generate_guide_buffers`] returns.
///
/// # Panics
///
/// Never in practice, for the reason [`generate_guide_buffers`] gives.
#[must_use]
pub fn generate_guide_buffers_with_index(
    width: u32,
    height: u32,
    camera: &Camera,
    planes: &[GpuFacetPlane],
    n_d: f32,
) -> GuideBuffers {
    generate_guide_buffers_cancellable_with_index(
        width,
        height,
        camera,
        planes,
        n_d,
        &AtomicBool::new(false),
    )
    .expect("a cancel flag that is never set to true never yields a cancelled result")
}

/// [`generate_guide_buffers`] for a stone with tools.
///
/// A tool hit records a facet id of `planes.len() + k`, which fits the `i32` id buffer
/// and the guide's equality-based edge test unchanged. With no tools the output is
/// [`generate_guide_buffers`]'s, bit for bit.
///
/// # Panics
///
/// Never in practice, for the reason [`generate_guide_buffers`] gives.
#[must_use]
pub fn generate_guide_buffers_geom(
    width: u32,
    height: u32,
    camera: &Camera,
    geom: StoneGeometry<'_>,
) -> GuideBuffers {
    generate_guide_buffers_geom_with_index(width, height, camera, geom, 0.0)
}

/// [`generate_guide_buffers_geom`] with the path signature of
/// [`generate_guide_buffers_with_index`].
///
/// # Panics
///
/// Never in practice, for the reason [`generate_guide_buffers`] gives.
#[must_use]
pub fn generate_guide_buffers_geom_with_index(
    width: u32,
    height: u32,
    camera: &Camera,
    geom: StoneGeometry<'_>,
    n_d: f32,
) -> GuideBuffers {
    generate_guide_buffers_cancellable_geom_with_index(
        width,
        height,
        camera,
        geom,
        n_d,
        &AtomicBool::new(false),
    )
    .expect("a cancel flag that is never set to true never yields a cancelled result")
}

/// Geometry-aware guides on the calling worker only, for externally governed jobs.
///
/// # Panics
///
/// Never in practice: the cancellation flag it passes is never set.
#[must_use]
pub fn generate_guide_buffers_geom_single_thread(
    width: u32,
    height: u32,
    camera: &Camera,
    geom: StoneGeometry<'_>,
    n_d: f32,
) -> GuideBuffers {
    generate_with_threads(
        GuideJob {
            width,
            height,
            camera,
            planes: geom.planes,
            tools: geom.tools,
            n_d,
            cancel: &AtomicBool::new(false),
        },
        1,
    )
    .expect("an unset cancellation flag cannot cancel guide generation")
}

/// The cancellable core [`generate_guide_buffers`] wraps.
///
/// Casts one un-jittered camera ray per pixel and records its first hit. Parallel across
/// `thread::available_parallelism` natively, chunked by row; single-threaded on
/// `wasm32` (see the module doc comment), with bit-identical output either way.
///
/// `cancel` is checked once per row, so a generation abandoned mid-flight (pose changed
/// again before it finished) stops within roughly one row's work. Returns `None` if
/// cancellation was observed at any point -- the caller must discard any partial
/// buffers rather than publish them.
///
/// Returns an all-miss [`GuideBuffers`] (still correctly sized) for a zero-area image
/// rather than panicking, even if `cancel` is already set.
#[must_use]
pub fn generate_guide_buffers_cancellable(
    width: u32,
    height: u32,
    camera: &Camera,
    planes: &[GpuFacetPlane],
    cancel: &AtomicBool,
) -> Option<GuideBuffers> {
    generate_guide_buffers_cancellable_with_index(width, height, camera, planes, 0.0, cancel)
}

/// [`generate_guide_buffers_cancellable`] with the path signature of
/// [`generate_guide_buffers_with_index`].
#[must_use]
pub fn generate_guide_buffers_cancellable_with_index(
    width: u32,
    height: u32,
    camera: &Camera,
    planes: &[GpuFacetPlane],
    n_d: f32,
    cancel: &AtomicBool,
) -> Option<GuideBuffers> {
    generate_guide_buffers_cancellable_geom_with_index(
        width,
        height,
        camera,
        StoneGeometry::planes_only(planes),
        n_d,
        cancel,
    )
}

/// [`generate_guide_buffers_cancellable`] for a stone with tools.
#[must_use]
pub fn generate_guide_buffers_cancellable_geom(
    width: u32,
    height: u32,
    camera: &Camera,
    geom: StoneGeometry<'_>,
    cancel: &AtomicBool,
) -> Option<GuideBuffers> {
    generate_guide_buffers_cancellable_geom_with_index(width, height, camera, geom, 0.0, cancel)
}

/// [`generate_guide_buffers_cancellable_geom`] with the path signature of
/// [`generate_guide_buffers_with_index`].
#[must_use]
pub fn generate_guide_buffers_cancellable_geom_with_index(
    width: u32,
    height: u32,
    camera: &Camera,
    geom: StoneGeometry<'_>,
    n_d: f32,
    cancel: &AtomicBool,
) -> Option<GuideBuffers> {
    let job = GuideJob {
        width,
        height,
        camera,
        planes: geom.planes,
        tools: geom.tools,
        n_d,
        cancel,
    };
    generate_with_threads(job, auto_thread_count())
}

/// [`generate_guide_buffers_cancellable`] writing into caller-owned buffers.
///
/// A caller that regenerates guides repeatedly (a pose that keeps moving) reuses one
/// allocation instead of paying three fresh full-frame vectors per call.
///
/// `out` is resized to `width * height` pixels; every pixel of a completed run is
/// overwritten, so its previous contents are irrelevant. Returns `false` if cancellation
/// was observed, in which case `out` holds a partial mix of old and new rows and must be
/// discarded rather than published. The result of a `true` return is bit-identical to
/// the buffers [`generate_guide_buffers_cancellable`] would allocate.
#[must_use]
pub fn generate_guide_buffers_into(
    width: u32,
    height: u32,
    camera: &Camera,
    planes: &[GpuFacetPlane],
    cancel: &AtomicBool,
    out: &mut GuideBuffers,
) -> bool {
    generate_guide_buffers_into_with_index(width, height, camera, planes, 0.0, cancel, out)
}

/// [`generate_guide_buffers_into`] with the path signature of
/// [`generate_guide_buffers_with_index`].
#[must_use]
pub fn generate_guide_buffers_into_with_index(
    width: u32,
    height: u32,
    camera: &Camera,
    planes: &[GpuFacetPlane],
    n_d: f32,
    cancel: &AtomicBool,
    out: &mut GuideBuffers,
) -> bool {
    generate_guide_buffers_into_geom_with_index(
        width,
        height,
        camera,
        StoneGeometry::planes_only(planes),
        n_d,
        cancel,
        out,
    )
}

/// [`generate_guide_buffers_into`] for a stone with tools.
#[must_use]
pub fn generate_guide_buffers_into_geom(
    width: u32,
    height: u32,
    camera: &Camera,
    geom: StoneGeometry<'_>,
    cancel: &AtomicBool,
    out: &mut GuideBuffers,
) -> bool {
    generate_guide_buffers_into_geom_with_index(width, height, camera, geom, 0.0, cancel, out)
}

/// [`generate_guide_buffers_into_geom`] with the path signature of
/// [`generate_guide_buffers_with_index`].
#[must_use]
pub fn generate_guide_buffers_into_geom_with_index(
    width: u32,
    height: u32,
    camera: &Camera,
    geom: StoneGeometry<'_>,
    n_d: f32,
    cancel: &AtomicBool,
    out: &mut GuideBuffers,
) -> bool {
    let job = GuideJob {
        width,
        height,
        camera,
        planes: geom.planes,
        tools: geom.tools,
        n_d,
        cancel,
    };
    fill_with_threads(job, auto_thread_count(), out)
}

/// The thread count [`generate_guide_buffers_cancellable`] splits its rows across.
// wasm32-unknown-unknown has no OS thread to spawn (`std::thread::Scope::spawn` panics
// at runtime there), so this is pinned to 1, which makes `generate_with_threads` take its
// inline single-chunk path and never reach `thread::scope`. Two cfg-gated definitions,
// like `renderer::tonemap::effective_thread_count`, so the wasm32 arm can be `const fn`.
#[cfg(target_arch = "wasm32")]
const fn auto_thread_count() -> usize {
    1
}

#[cfg(not(target_arch = "wasm32"))]
fn auto_thread_count() -> usize {
    crate::renderer::tonemap::effective_thread_count(0)
}

/// The per-call inputs every row of the prepass shares, bundled so the row worker
/// ([`fill_rows`]) stays under clippy's argument-count limit.
#[derive(Clone, Copy)]
struct GuideJob<'a> {
    width: u32,
    height: u32,
    camera: &'a Camera,
    planes: &'a [GpuFacetPlane],
    /// Tools subtracted from the polyhedron `planes` define; empty for a planar stone.
    tools: &'a [ToolPrimitive],
    /// Reference refractive index of the path signature; `<= 1.0` disables it.
    n_d: f32,
    cancel: &'a AtomicBool,
}

/// [`generate_guide_buffers_cancellable`] with an explicit thread count (`0` is treated
/// as 1). A count that leaves every row in one chunk runs inline on the calling thread
/// without `thread::scope`; the output does not depend on the count.
fn generate_with_threads(job: GuideJob<'_>, num_threads: usize) -> Option<GuideBuffers> {
    let mut buffers = GuideBuffers {
        depth: Vec::new(),
        normal: Vec::new(),
        facet_id: Vec::new(),
        path_sig: Vec::new(),
    };
    fill_with_threads(job, num_threads, &mut buffers).then_some(buffers)
}

/// The shared body of [`generate_with_threads`] and [`generate_guide_buffers_into`]:
/// fits `out` to the image and fills every pixel of it, returning `false` on cancellation.
///
/// The plane arena is built once here and shared by every row worker; the `SoA` scan is the
/// bit-identical twin of the scalar `intersect_polyhedron` loop, so the output does not
/// depend on which one runs.
fn fill_with_threads(job: GuideJob<'_>, num_threads: usize, out: &mut GuideBuffers) -> bool {
    let GuideJob {
        width,
        height,
        cancel,
        planes,
        ..
    } = job;
    let pixel_count = (width as usize) * (height as usize);
    if pixel_count == 0 {
        out.depth.clear();
        out.normal.clear();
        out.facet_id.clear();
        out.path_sig.clear();
        return true;
    }
    if cancel.load(Ordering::Relaxed) {
        return false;
    }

    // Every pixel is written below, so a reused buffer needs no re-initialisation: only
    // growth fills, with the miss sentinels.
    out.depth.resize(pixel_count, 1.0e6);
    out.normal.resize(pixel_count, Vec3::ZERO);
    out.facet_id.resize(pixel_count, -1);
    out.path_sig.resize(pixel_count, 0);

    let soa = build_plane_soa(planes);
    let soa = &soa;
    let threads = num_threads.max(1).min(height as usize);

    if threads <= 1 {
        fill_rows(
            job,
            soa,
            0,
            &mut out.depth,
            &mut out.normal,
            &mut out.facet_id,
            &mut out.path_sig,
        );
    } else {
        fill_rows_dynamic(job, soa, threads, out);
    }

    !cancel.load(Ordering::Relaxed)
}

/// One image row's four output slices, as handed to a worker by [`fill_rows_dynamic`].
type GuideRowSlices<'a> = (&'a mut [f32], &'a mut [Vec3], &'a mut [i32], &'a mut [u32]);

/// Fills every row of `out` on `threads` scoped threads that claim rows one at a time
/// from an atomic counter (the scheme `scanline.rs` uses), instead of one static band
/// each. Rows cost very different amounts -- a miss is one failed intersection, a gem row
/// with the path signature is up to four -- so equal-height bands left the thread holding
/// the stone's centre running long after the others finished. Every row is a pure
/// function of the camera and planes and lands in its own fixed slice, so the output is
/// bit-identical to the static split; only which thread fills which row varies.
fn fill_rows_dynamic(job: GuideJob<'_>, soa: &PlanesSoA32, threads: usize, out: &mut GuideBuffers) {
    let width = job.width as usize;
    let rows: Vec<Option<GuideRowSlices<'_>>> = out
        .depth
        .chunks_mut(width)
        .zip(out.normal.chunks_mut(width))
        .zip(out.facet_id.chunks_mut(width))
        .zip(out.path_sig.chunks_mut(width))
        .map(|(((depth, normal), facet), sig)| Some((depth, normal, facet, sig)))
        .collect();
    let row_count = rows.len();
    let rows = Mutex::new(rows);
    let next_row = AtomicUsize::new(0);
    thread::scope(|s| {
        for _ in 0..threads {
            let (rows, next_row) = (&rows, &next_row);
            s.spawn(move || {
                loop {
                    let y = next_row.fetch_add(1, Ordering::Relaxed);
                    if y >= row_count || job.cancel.load(Ordering::Relaxed) {
                        break;
                    }
                    // The lock is held only to take the row's slices out, never while
                    // tracing it.
                    let claimed = rows
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)[y]
                        .take();
                    // `fetch_add` hands each index out once, so `None` cannot happen.
                    let Some((depth, normal, facet, sig)) = claimed else {
                        break;
                    };
                    fill_rows(job, soa, y, depth, normal, facet, sig);
                }
            });
        }
    });
}

/// Interior hits the path signature follows after the entry refraction.
pub const SIGNATURE_BOUNCES: usize = 3;
/// Set on the facet word of the interior hit the ray leaves the stone through.
const SIG_EXIT_BIT: u32 = 0x8000;
/// Facet word of a ray that leaves the stone without meeting another facet.
const SIG_ESCAPE: u32 = 0xFFFF;
/// Offset along the new direction before the next interior intersection: the tracer's own
/// self-hit epsilon (`transport::bounce`).
const SIG_SELF_HIT_EPS: f32 = 1.0e-4;

/// One FNV-1a round over the four little-endian bytes of `word`.
#[inline]
const fn fnv_mix(mut hash: u32, word: u32) -> u32 {
    let mut shift = 0;
    while shift < 32 {
        hash ^= (word >> shift) & 0xFF;
        hash = hash.wrapping_mul(0x0100_0193);
        shift += 8;
    }
    hash
}

/// Plain `x*x + y*y + z*z` dot product (no fused multiply-add).
#[inline]
#[allow(
    clippy::suboptimal_flops,
    reason = "a fused multiply-add rounds once where wasm32 rounds twice, so x86 and wasm \
              would hash different signatures for the same pixel"
)]
fn dot3(a: Vec3, b: Vec3) -> f32 {
    a.x * b.x + a.y * b.y + a.z * b.z
}

/// Normalises `v` with plain operations, or returns it unchanged when it has no length.
#[inline]
fn unit(v: Vec3) -> Vec3 {
    let len = dot3(v, v).sqrt();
    if len > 0.0 { v / len } else { v }
}

/// The path signature of the centre ray whose first hit is `first`, or `0` when `n_d <= 1`.
///
/// Refracts into the stone at index `n_d` (Snell, ordinary ray), then follows up to
/// [`SIGNATURE_BOUNCES`] interior hits: total internal reflection continues the walk, the
/// first hit that transmits ends it with [`SIG_EXIT_BIT`] set, a ray that finds no further
/// facet ends it with [`SIG_ESCAPE`]. The facet words are folded with FNV-1a, so two pixels
/// share a signature exactly when their rays met the same facets in the same order. Plain
/// `f32` operations only (see the module docs).
#[allow(
    clippy::suboptimal_flops,
    reason = "the Snell and reflection arithmetic must stay unfused: an FMA would change \
              the refracted direction in the last bit and so the facet hash on x86 vs wasm32"
)]
fn path_signature(
    ray: Ray,
    first: &HitRecord,
    soa: &PlanesSoA32,
    tools: &[ToolPrimitive],
    n_d: f32,
) -> u32 {
    if n_d.is_nan() || n_d <= 1.0 {
        return 0;
    }
    let mut hash = fnv_mix(
        0x811c_9dc5,
        u32::try_from(first.facet_idx).expect("the facet index fits u32"),
    );

    // Entry refraction, air -> stone.
    let incident = unit(ray.dir);
    let cos_i = (-dot3(incident, first.normal)).max(0.0);
    let eta = 1.0 / n_d;
    let k = 1.0 - eta * eta * (1.0 - cos_i * cos_i);
    if k <= 0.0 {
        return fnv_mix(hash, SIG_ESCAPE).max(1);
    }
    let mut dir = unit(incident * eta + first.normal * (eta * cos_i - k.sqrt()));
    let mut origin = ray.origin + ray.dir * first.t;

    for _ in 0..SIGNATURE_BOUNCES {
        let probe = Ray {
            origin: origin + dir * SIG_SELF_HIT_EPS,
            dir,
        };
        let Some(hit) = intersect_stone_soa(probe, soa, soa.len(), tools) else {
            hash = fnv_mix(hash, SIG_ESCAPE);
            break;
        };
        origin = probe.origin + dir * hit.t;
        let facet = u32::try_from(hit.facet_idx & 0x7FFF).expect("masked to 15 bits");
        let cos_t = dot3(dir, hit.normal);
        let sin_sq = n_d * n_d * (1.0 - cos_t * cos_t);
        if sin_sq > 1.0 {
            // Total internal reflection: the walk continues along the mirrored direction.
            hash = fnv_mix(hash, facet);
            dir = unit(dir - hit.normal * (2.0 * cos_t));
        } else {
            hash = fnv_mix(hash, facet | SIG_EXIT_BIT);
            break;
        }
    }
    // `0` is reserved for "no signature".
    hash.max(1)
}

/// Fills the whole rows `depth`/`normal`/`facet_id`/`path_sig` hold (each a multiple of
/// `job.width` long), the first of which is image row `start_y`. Stops early once
/// `job.cancel` is set, checked once per row. `soa` is the arena built from `job.planes`.
fn fill_rows(
    job: GuideJob<'_>,
    soa: &PlanesSoA32,
    start_y: usize,
    depth: &mut [f32],
    normal: &mut [Vec3],
    facet_id: &mut [i32],
    path_sig: &mut [u32],
) {
    let width = job.width as usize;
    let rows = depth
        .chunks_mut(width)
        .zip(normal.chunks_mut(width))
        .zip(facet_id.chunks_mut(width))
        .zip(path_sig.chunks_mut(width));
    for (local_y, (((depth_row, normal_row), facet_row), sig_row)) in rows.enumerate() {
        if job.cancel.load(Ordering::Relaxed) {
            return;
        }
        let y = start_y + local_y;
        let cells = depth_row
            .iter_mut()
            .zip(normal_row.iter_mut())
            .zip(facet_row.iter_mut())
            .zip(sig_row.iter_mut());
        for (x, (((depth_out, normal_out), facet_out), sig_out)) in cells.enumerate() {
            // No jitter: this is a single deterministic prepass, not an accumulated
            // sample -- there is nothing to anti-alias against.
            let ray = job.camera.generate_ray(
                x as f32,
                y as f32,
                job.width as f32,
                job.height as f32,
                0.0,
                0.0,
            );
            let hit = intersect_stone_soa(ray, soa, soa.len(), job.tools);

            *depth_out = hit.map_or(1.0e6, |h| h.t);
            *normal_out = hit.map_or(Vec3::ZERO, |h| h.normal);
            *facet_out = hit.map_or(-1, |h| {
                i32::try_from(h.facet_idx).expect("the facet index fits i32")
            });
            *sig_out = hit.map_or(0, |h| path_signature(ray, &h, soa, job.tools, job.n_d));
        }
    }
}

#[cfg(test)]
mod tests;