euv-core 0.53.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Default empty `TsrUpscaler` with identity previous view-projection matrix.
impl Default for TsrUpscaler {
    /// Creates an empty `TsrUpscaler` ready to accumulate temporal history on the first frame.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized TSR upscaler.
    fn default() -> Self {
        Self {
            history_width: 0,
            history_height: 0,
            has_history: false,
            prev_view_projection: Mat4::identity(),
            accumulated_frames: 0,
            history_rgba: Vec::new(),
            next_history_rgba: Vec::new(),
            history_inv_w: Vec::new(),
            next_inv_w: Vec::new(),
        }
    }
}

/// Color-space helpers and analytical motion-vector temporal reconstruction for `TsrUpscaler`.
impl TsrUpscaler {
    /// Invalidates accumulated temporal history cleanly on camera cuts, teleports, or resolution changes.
    pub fn invalidate_history(&mut self) {
        self.set_has_history(false);
        self.set_accumulated_frames(0);
    }

    /// Multiplies a 3D direction vector (`w = 0`) by a column-major 4x4 projection matrix.
    ///
    /// # Arguments
    ///
    /// - `&Mat4` - Column-major view-projection matrix.
    /// - `Vec3` - 3D direction vector.
    ///
    /// # Returns
    ///
    /// - `[f32; 4]` - Homogeneous directional clip coordinates `(x, y, z, w)`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    fn mul_dir4(mat: &Mat4, dir: Vec3) -> [f32; 4] {
        let elems: [f32; 16] = mat.get_elements();
        let dx: f32 = dir.get_x();
        let dy: f32 = dir.get_y();
        let dz: f32 = dir.get_z();
        [
            dx.mul_add(elems[0], dy.mul_add(elems[4], dz * elems[8])),
            dx.mul_add(elems[1], dy.mul_add(elems[5], dz * elems[9])),
            dx.mul_add(elems[2], dy.mul_add(elems[6], dz * elems[10])),
            dx.mul_add(elems[3], dy.mul_add(elems[7], dz * elems[11])),
        ]
    }

    /// Folds output viewport pixel scaling directly into a homogeneous clip vector `(cx, cy, _, cw) -> [sx_num, sy_num, cw]`.
    ///
    /// # Arguments
    ///
    /// - `[f32; 4]` - Homogeneous clip vector.
    /// - `f32` - Half output width `dst_w * 0.5`.
    /// - `f32` - Half output height `dst_h * 0.5`.
    ///
    /// # Returns
    ///
    /// - `[f32; 3]` - Screen-folded `[sx_numerator, sy_numerator, cw]` basis vector.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    fn fold_screen_basis(clip: [f32; 4], half_dw: f32, half_dh: f32) -> [f32; 3] {
        let cx: f32 = clip[0];
        let cy: f32 = clip[1];
        let cw: f32 = clip[3];
        [
            cx.mul_add(half_dw, cw * (half_dw - 0.5)),
            (-cy).mul_add(half_dh, cw * (half_dh - 0.5)),
            cw,
        ]
    }

    /// Packs RGB channels of an RGBA8 pixel into 16-bit SWAR lanes `0x0000_00BB_00GG_00RR`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Source RGBA8 buffer.
    /// - `usize` - Byte offset of the pixel (`idx * 4`).
    ///
    /// # Returns
    ///
    /// - `u64` - Lane-packed 16-bit RGB word.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    fn load_swar_rgb(rgba: &[u8], byte_off: usize) -> u64 {
        (rgba[byte_off] as u64)
            | ((rgba[byte_off + 1] as u64) << 16)
            | ((rgba[byte_off + 2] as u64) << 32)
    }

    /// Samples an RGBA8 image bilinearly via 64-bit SWAR fixed-point arithmetic using precomputed row offsets.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Source RGBA8 buffer.
    /// - `(usize, usize, u64)` - Precomputed `(row_y0_bytes, row_y1_bytes, wy_256)` row offsets and vertical weight.
    /// - `(usize, usize, u64)` - `(x0_bytes, x1_bytes, wx_256)` horizontal byte offsets and weight.
    ///
    /// # Returns
    ///
    /// - `(u32, u32, u32)` - Bilinearly filtered `(r, g, b)` channels in `0..=255`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    fn sample_swar_rows(
        rgba: &[u8],
        row_info: (usize, usize, u64),
        col_info: (usize, usize, u64),
    ) -> (u32, u32, u32) {
        let (row0, row1, wy): (usize, usize, u64) = row_info;
        let (x0_b, x1_b, wx): (usize, usize, u64) = col_info;
        let inv_wx: u64 = 256 - wx;
        let inv_wy: u64 = 256 - wy;
        let c00: u64 = Self::load_swar_rgb(rgba, row0 + x0_b);
        let c10: u64 = Self::load_swar_rgb(rgba, row0 + x1_b);
        let c01: u64 = Self::load_swar_rgb(rgba, row1 + x0_b);
        let c11: u64 = Self::load_swar_rgb(rgba, row1 + x1_b);
        let top: u64 = ((c00 * inv_wx + c10 * wx + 0x0000_0080_0080_0080_u64) >> 8)
            & 0x0000_00FF_00FF_00FF_u64;
        let bot: u64 = ((c01 * inv_wx + c11 * wx + 0x0000_0080_0080_0080_u64) >> 8)
            & 0x0000_00FF_00FF_00FF_u64;
        let blended: u64 = ((top * inv_wy + bot * wy + 0x0000_0080_0080_0080_u64) >> 8)
            & 0x0000_00FF_00FF_00FF_u64;
        (
            (blended & 0xFF) as u32,
            ((blended >> 16) & 0xFF) as u32,
            ((blended >> 32) & 0xFF) as u32,
        )
    }

    /// Samples an RGBA8 image bilinearly at fractional pixel coordinates `(fx, fy)` via 64-bit SWAR fixed-point arithmetic.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Source RGBA8 pixel buffer.
    /// - `(usize, usize)` - Image `(width, height)` in pixels.
    /// - `(f32, f32)` - Fractional `(fx, fy)` coordinates.
    ///
    /// # Returns
    ///
    /// - `(u32, u32, u32)` - Bilinearly filtered `(r, g, b)` channels in `0..=255`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    fn sample_rgba_bilinear_swar(
        rgba: &[u8],
        dims: (usize, usize),
        coords: (f32, f32),
    ) -> (u32, u32, u32) {
        let (width, height): (usize, usize) = dims;
        let (fx, fy): (f32, f32) = coords;
        let max_x: usize = width.saturating_sub(1);
        let max_y: usize = height.saturating_sub(1);
        let cx: f32 = fx.clamp(0.0, max_x as f32);
        let cy: f32 = fy.clamp(0.0, max_y as f32);
        let x0: usize = cx as usize;
        let y0: usize = cy as usize;
        let x1: usize = (x0 + 1).min(max_x);
        let y1: usize = (y0 + 1).min(max_y);
        let wx: u64 = ((cx - (x0 as f32)) * 256.0) as u64;
        let wy: u64 = ((cy - (y0 as f32)) * 256.0) as u64;
        let row_bytes: usize = width * 4;
        Self::sample_swar_rows(
            rgba,
            (y0 * row_bytes, y1 * row_bytes, wy),
            (x0 * 4, x1 * 4, wx),
        )
    }

    /// Reconstructs a full-resolution temporally super-resolved RGBA8 frame from a sub-native render and reverse-Z depth buffer.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Sub-native rendered RGBA8 frame (`src_width * src_height * 4`).
    /// - `&[f32]` - Sub-native reverse-Z `1/w` depth buffer (`src_width * src_height`).
    /// - `&TsrFrameParams` - Per-frame camera basis, projection, jitter, and sharpening configuration.
    /// - `&mut Vec<u8>` - Destination full-resolution RGBA8 output buffer populated in-place without redundant allocations.
    pub fn upscale_rgba(
        &mut self,
        src_rgba: &[u8],
        src_depth: &[f32],
        params: &TsrFrameParams,
        out_rgba: &mut Vec<u8>,
    ) {
        let src_w: usize = params.get_src_width().max(1);
        let src_h: usize = params.get_src_height().max(1);
        let dst_w: usize = params.get_dst_width().max(1);
        let dst_h: usize = params.get_dst_height().max(1);
        let src_pixels: usize = src_w * src_h;
        let dst_pixels: usize = dst_w * dst_h;
        let dst_bytes: usize = dst_pixels * 4;
        if src_rgba.len() < src_pixels * 4 || src_depth.len() < src_pixels {
            out_rgba.clear();
            return;
        }
        if self.get_history_width() != dst_w || self.get_history_height() != dst_h {
            self.set_history_width(dst_w);
            self.set_history_height(dst_h);
            self.set_has_history(false);
            self.set_accumulated_frames(0);
            let Self {
                history_rgba,
                next_history_rgba,
                history_inv_w,
                next_inv_w,
                ..
            } = self;
            history_rgba.resize(dst_bytes, 0);
            next_history_rgba.resize(dst_bytes, 0);
            history_inv_w.resize(dst_pixels, 0.0);
            next_inv_w.resize(dst_pixels, 0.0);
        }
        out_rgba.clear();
        if out_rgba.capacity() < dst_bytes {
            out_rgba.reserve_exact(dst_bytes - out_rgba.capacity());
        }
        let has_hist: bool = self.get_has_history();
        let prev_vp: Mat4 = self.get_prev_view_projection();
        let inv_dst_w: f32 = 1.0 / (dst_w as f32);
        let inv_dst_h: f32 = 1.0 / (dst_h as f32);
        let scale_x: f32 = (src_w as f32) * inv_dst_w;
        let scale_y: f32 = (src_h as f32) * inv_dst_h;
        let (jit_x, jit_y): (f32, f32) = params.get_jitter_offset();
        let sharp_i32: i32 = (params.get_sharpness().clamp(0.0, 0.5) * 256.0) as i32;
        let dst_w_f: f32 = dst_w as f32;
        let dst_h_f: f32 = dst_h as f32;
        let half_dw: f32 = dst_w_f * 0.5;
        let half_dh: f32 = dst_h_f * 0.5;
        let max_ox: f32 = dst_w_f - 0.5;
        let max_oy: f32 = dst_h_f - 0.5;
        let src_w_max: usize = src_w.saturating_sub(1);
        let src_h_max: usize = src_h.saturating_sub(1);
        let src_w_max_f: f32 = src_w_max as f32;
        let src_h_max_f: f32 = src_h_max as f32;
        let dst_w_max: usize = dst_w.saturating_sub(1);
        let dst_h_max: usize = dst_h.saturating_sub(1);
        let src_row_bytes: usize = src_w * 4;
        let cam_sc: [f32; 3] = Self::fold_screen_basis(
            prev_vp.mul_point4(params.get_camera_position()),
            half_dw,
            half_dh,
        );
        let fwd_sc: [f32; 3] = Self::fold_screen_basis(
            Self::mul_dir4(&prev_vp, params.get_camera_forward()),
            half_dw,
            half_dh,
        );
        let right_sc: [f32; 3] = Self::fold_screen_basis(
            Self::mul_dir4(&prev_vp, params.get_camera_right_scaled()),
            half_dw,
            half_dh,
        );
        let up_sc: [f32; 3] = Self::fold_screen_basis(
            Self::mul_dir4(&prev_vp, params.get_camera_up_scaled()),
            half_dw,
            half_dh,
        );
        let step_scale: f32 = 2.0 * inv_dst_w;
        let step_sc: [f32; 3] = [
            right_sc[0] * step_scale,
            right_sc[1] * step_scale,
            right_sc[2] * step_scale,
        ];
        let ndc_x0: f32 = inv_dst_w - 1.0;
        let base_hist_w: f32 = TSR_BASE_HISTORY_WEIGHT * 256.0;
        let delta_hist_w: f32 = (TSR_MOTION_HISTORY_WEIGHT - TSR_BASE_HISTORY_WEIGHT) * 256.0;
        {
            let Self {
                history_rgba,
                next_history_rgba,
                history_inv_w,
                next_inv_w,
                ..
            } = self;
            let hist_rgba_ref: &[u8] = history_rgba.as_slice();
            let hist_depth_ref: &[f32] = history_inv_w.as_slice();
            let out_base: usize = out_rgba.as_mut_ptr() as usize;
            let next_hist_base: usize = next_history_rgba.as_mut_ptr() as usize;
            let next_depth_base: usize = next_inv_w.as_mut_ptr() as usize;
            parallel_for_ranges(dst_h, TSR_PARALLEL_ROW_GRAIN, |y0: usize, y1: usize| {
                for dst_y in y0..y1 {
                    let row_out: usize = dst_y * dst_w;
                    let ndc_y: f32 = 1.0 - 2.0 * (((dst_y as f32) + 0.5) * inv_dst_h);
                    let mut ray_sx: f32 = fwd_sc[0] + up_sc[0] * ndc_y + right_sc[0] * ndc_x0;
                    let mut ray_sy: f32 = fwd_sc[1] + up_sc[1] * ndc_y + right_sc[1] * ndc_x0;
                    let mut ray_cw: f32 = fwd_sc[2] + up_sc[2] * ndc_y + right_sc[2] * ndc_x0;
                    let sy_f: f32 =
                        (((dst_y as f32) + 0.5) * scale_y - 0.5 - jit_y).clamp(0.0, src_h_max_f);
                    let sy0: usize = sy_f as usize;
                    let sy1: usize = (sy0 + 1).min(src_h_max);
                    let wy_src: u64 = ((sy_f - (sy0 as f32)) * 256.0) as u64;
                    let src_row0_b: usize = sy0 * src_row_bytes;
                    let src_row1_b: usize = sy1 * src_row_bytes;
                    let iy: usize = ((sy_f + 0.5) as usize).min(src_h_max);
                    let row_iy: usize = iy * src_w;
                    let row_up: usize = iy.saturating_sub(1) * src_w;
                    let row_dn: usize = (iy + 1).min(src_h_max) * src_w;
                    let mut sx_f: f32 = 0.5 * scale_x - 0.5 - jit_x;
                    for dst_x in 0..dst_w {
                        let clamped_sx: f32 = sx_f.clamp(0.0, src_w_max_f);
                        let sx0: usize = clamped_sx as usize;
                        let sx1: usize = (sx0 + 1).min(src_w_max);
                        let wx_src: u64 = ((clamped_sx - (sx0 as f32)) * 256.0) as u64;
                        let (mut out_r, mut out_g, mut out_b): (u32, u32, u32) =
                            Self::sample_swar_rows(
                                src_rgba,
                                (src_row0_b, src_row1_b, wy_src),
                                (sx0 * 4, sx1 * 4, wx_src),
                            );
                        let ix: usize = ((clamped_sx + 0.5) as usize).min(src_w_max);
                        let c_idx: usize = row_iy + ix;
                        let up_idx: usize = row_up + ix;
                        let dn_idx: usize = row_dn + ix;
                        let lt_idx: usize = row_iy + ix.saturating_sub(1);
                        let rt_idx: usize = row_iy + (ix + 1).min(src_w_max);
                        let dilated_inv_w: f32 = src_depth[c_idx]
                            .max(src_depth[up_idx])
                            .max(src_depth[dn_idx])
                            .max(src_depth[lt_idx])
                            .max(src_depth[rt_idx]);
                        if dilated_inv_w > 1.0e-6 {
                            let oc: usize = c_idx * 4;
                            let ou: usize = up_idx * 4;
                            let od: usize = dn_idx * 4;
                            let ol: usize = lt_idx * 4;
                            let or: usize = rt_idx * 4;
                            let r0: u32 = src_rgba[oc] as u32;
                            let r1: u32 = src_rgba[ou] as u32;
                            let r2: u32 = src_rgba[od] as u32;
                            let r3: u32 = src_rgba[ol] as u32;
                            let r4: u32 = src_rgba[or] as u32;
                            let g0: u32 = src_rgba[oc + 1] as u32;
                            let g1: u32 = src_rgba[ou + 1] as u32;
                            let g2: u32 = src_rgba[od + 1] as u32;
                            let g3: u32 = src_rgba[ol + 1] as u32;
                            let g4: u32 = src_rgba[or + 1] as u32;
                            let b0: u32 = src_rgba[oc + 2] as u32;
                            let b1: u32 = src_rgba[ou + 2] as u32;
                            let b2: u32 = src_rgba[od + 2] as u32;
                            let b3: u32 = src_rgba[ol + 2] as u32;
                            let b4: u32 = src_rgba[or + 2] as u32;
                            let min_r: u32 = r0.min(r1).min(r2).min(r3).min(r4);
                            let max_r: u32 = r0.max(r1).max(r2).max(r3).max(r4);
                            let min_g: u32 = g0.min(g1).min(g2).min(g3).min(g4);
                            let max_g: u32 = g0.max(g1).max(g2).max(g3).max(g4);
                            let min_b: u32 = b0.min(b1).min(b2).min(b3).min(b4);
                            let max_b: u32 = b0.max(b1).max(b2).max(b3).max(b4);
                            if has_hist {
                                let cw: f32 = cam_sc[2].mul_add(dilated_inv_w, ray_cw);
                                if cw > 0.15 * dilated_inv_w {
                                    let inv_cw: f32 = 1.0 / cw;
                                    let prev_ox: f32 =
                                        cam_sc[0].mul_add(dilated_inv_w, ray_sx) * inv_cw;
                                    let prev_oy: f32 =
                                        cam_sc[1].mul_add(dilated_inv_w, ray_sy) * inv_cw;
                                    if (-0.5..=max_ox).contains(&prev_ox)
                                        && (-0.5..=max_oy).contains(&prev_oy)
                                    {
                                        let px_i: usize =
                                            ((prev_ox + 0.5).max(0.0) as usize).min(dst_w_max);
                                        let py_i: usize =
                                            ((prev_oy + 0.5).max(0.0) as usize).min(dst_h_max);
                                        let prev_stored_inv_w: f32 =
                                            hist_depth_ref[py_i * dst_w + px_i];
                                        if prev_stored_inv_w > 1.0e-6
                                            && (dilated_inv_w - prev_stored_inv_w).abs()
                                                <= dilated_inv_w.max(prev_stored_inv_w)
                                                    * TSR_DISOCCLUSION_REL_DEPTH
                                        {
                                            let (hr, hg, hb): (u32, u32, u32) =
                                                Self::sample_rgba_bilinear_swar(
                                                    hist_rgba_ref,
                                                    (dst_w, dst_h),
                                                    (prev_ox, prev_oy),
                                                );
                                            let clamped_r: u32 = hr.clamp(min_r, max_r);
                                            let clamped_g: u32 = hg.clamp(min_g, max_g);
                                            let clamped_b: u32 = hb.clamp(min_b, max_b);
                                            let motion_px: f32 = (prev_ox - (dst_x as f32))
                                                .abs()
                                                .max((prev_oy - (dst_y as f32)).abs());
                                            let motion_t: f32 = (motion_px * 0.12).clamp(0.0, 1.0);
                                            let hw: u32 =
                                                delta_hist_w.mul_add(motion_t, base_hist_w) as u32;
                                            let cw_i: u32 = 256 - hw;
                                            out_r = (out_r * cw_i + clamped_r * hw + 128) >> 8;
                                            out_g = (out_g * cw_i + clamped_g * hw + 128) >> 8;
                                            out_b = (out_b * cw_i + clamped_b * hw + 128) >> 8;
                                        }
                                    }
                                }
                            }
                            if sharp_i32 > 1 {
                                let avg_r: i32 = ((r0 + r1 + r2 + r3 + r4 + 2) / 5) as i32;
                                let avg_g: i32 = ((g0 + g1 + g2 + g3 + g4 + 2) / 5) as i32;
                                let avg_b: i32 = ((b0 + b1 + b2 + b3 + b4 + 2) / 5) as i32;
                                let sr: i32 =
                                    (out_r as i32) + ((((out_r as i32) - avg_r) * sharp_i32) >> 8);
                                let sg: i32 =
                                    (out_g as i32) + ((((out_g as i32) - avg_g) * sharp_i32) >> 8);
                                let sb: i32 =
                                    (out_b as i32) + ((((out_b as i32) - avg_b) * sharp_i32) >> 8);
                                out_r = sr.clamp(min_r as i32, max_r as i32) as u32;
                                out_g = sg.clamp(min_g as i32, max_g as i32) as u32;
                                out_b = sb.clamp(min_b as i32, max_b as i32) as u32;
                            }
                        }
                        let dst_idx: usize = row_out + dst_x;
                        let out_off: usize = dst_idx * 4;
                        let packed: [u8; 4] = [out_r as u8, out_g as u8, out_b as u8, 255];
                        // SAFETY: `parallel_for_ranges` partitions `0..dst_h` into strictly disjoint rows;
                        // `out_rgba` and `next_history_rgba` have capacity `>= dst_bytes` and `next_inv_w` has length `dst_pixels`.
                        unsafe {
                            (out_base as *mut u8)
                                .add(out_off)
                                .cast::<[u8; 4]>()
                                .write(packed);
                            (next_hist_base as *mut u8)
                                .add(out_off)
                                .cast::<[u8; 4]>()
                                .write(packed);
                            *(next_depth_base as *mut f32).add(dst_idx) = dilated_inv_w;
                        }
                        ray_sx += step_sc[0];
                        ray_sy += step_sc[1];
                        ray_cw += step_sc[2];
                        sx_f += scale_x;
                    }
                }
            });
            // SAFETY: Every byte in `0..dst_bytes` was initialized by disjoint row bands above.
            unsafe {
                out_rgba.set_len(dst_bytes);
            }
            swap(history_rgba, next_history_rgba);
            swap(history_inv_w, next_inv_w);
        }
        self.set_prev_view_projection(params.get_view_projection());
        self.set_has_history(true);
        self.set_accumulated_frames(self.get_accumulated_frames().saturating_add(1));
    }
}

/// Default 60Hz `AdaptiveFrameGovernor`.
impl Default for AdaptiveFrameGovernor {
    /// Creates a 60Hz closed-loop frame pacing governor with `[0.50, 1.00]` TSR/DRS scale bounds.
    ///
    /// # Returns
    ///
    /// - `Self` - Default frame pacing governor.
    fn default() -> Self {
        Self::for_target_hz(60.0)
    }
}

/// Damped PI + asymmetric hysteresis frame-time stabilization for `AdaptiveFrameGovernor`.
impl AdaptiveFrameGovernor {
    /// Creates a closed-loop `AdaptiveFrameGovernor` targeting `target_hz` (`30.0..=1000.0` Hz).
    ///
    /// # Arguments
    ///
    /// - `f32` - Desired display refresh rate in Hertz.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized closed-loop frame governor.
    #[must_use]
    pub fn for_target_hz(target_hz: f32) -> Self {
        let clamped_hz: f32 = if target_hz.is_finite() {
            target_hz.max(30.0)
        } else {
            60.0
        };
        let budget_ms: f32 = 1000.0 / clamped_hz;
        Self {
            target_hz: clamped_hz,
            min_scale: TSR_MIN_SCALE,
            max_scale: TSR_MAX_SCALE,
            current_scale: 1.0,
            rt_stride_bias: 0,
            lod_bias: 1.0,
            ema_frame_ms: budget_ms * 0.75,
            ema_jitter_ms: 0.0,
            p99_est_ms: budget_ms * 0.85,
            last_frame_ms: budget_ms * 0.75,
            under_budget_streak: 0,
            over_budget_streak: 0,
            hysteresis_frames: GOVERNOR_DEFAULT_HYSTERESIS_FRAMES,
            total_frames: 0,
        }
    }

    /// Configures custom TSR/DRS resolution scale bounds `(min_scale, max_scale)`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Minimum resolution scale (`0.40..=1.0`).
    /// - `f32` - Maximum resolution scale (`min_scale..=1.25`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated governor.
    #[must_use]
    pub fn with_scale_bounds(mut self, min_scale: f32, max_scale: f32) -> Self {
        let lo: f32 = min_scale.clamp(0.40, 1.0);
        let hi: f32 = max_scale.clamp(lo, 4.0);
        self.set_min_scale(lo);
        self.set_max_scale(hi);
        self.set_current_scale(self.get_current_scale().clamp(lo, hi));
        self
    }

    /// Quantizes a raw resolution scale onto `GOVERNOR_SCALE_QUANTUM` steps to eliminate buffer reallocation churn.
    ///
    /// # Arguments
    ///
    /// - `f32` - Unquantized resolution scale.
    /// - `f32` - Minimum scale clamp.
    /// - `f32` - Maximum scale clamp.
    ///
    /// # Returns
    ///
    /// - `f32` - Quantized scale within `[min_scale, max_scale]`.
    #[must_use]
    fn quantize_scale(raw: f32, min_scale: f32, max_scale: f32) -> f32 {
        let stepped: f32 = (raw / GOVERNOR_SCALE_QUANTUM).round() * GOVERNOR_SCALE_QUANTUM;
        stepped.clamp(min_scale, max_scale)
    }

    /// Observes the completed `frame_ms` duration, updates smoothed telemetry, and smoothly adjusts `config` to lock target FPS without oscillation.
    ///
    /// # Arguments
    ///
    /// - `f32` - Measured frame duration in milliseconds.
    /// - `&mut RenderQualityConfig` - Active quality configuration adjusted in-place when dynamic scaling is enabled.
    ///
    /// # Returns
    ///
    /// - `FramePacingTelemetry3D` - Live pacing, utilization, and stability diagnostics.
    pub fn record_frame(
        &mut self,
        frame_ms: f32,
        config: &mut RenderQualityConfig,
    ) -> FramePacingTelemetry3D {
        let safe_ms: f32 = if frame_ms.is_finite() {
            frame_ms.clamp(0.05, 250.0)
        } else {
            16.67
        };
        let target_hz: f32 = self.get_target_hz().max(30.0);
        let budget_ms: f32 = 1000.0 / target_hz;
        let frames: u64 = self.get_total_frames();
        let next_ema: f32 = if frames == 0 {
            safe_ms
        } else {
            self.get_ema_frame_ms() * 0.82 + safe_ms * 0.18
        };
        let delta_jitter: f32 = if frames == 0 {
            0.0
        } else {
            (safe_ms - self.get_last_frame_ms()).abs()
        };
        let next_jitter: f32 = if frames == 0 {
            0.0
        } else {
            self.get_ema_jitter_ms() * 0.85 + delta_jitter * 0.15
        };
        let prev_p99: f32 = self.get_p99_est_ms();
        let next_p99: f32 = if safe_ms > prev_p99 {
            prev_p99 * 0.65 + safe_ms * 0.35
        } else {
            prev_p99 * 0.96 + safe_ms * 0.04
        };
        self.set_ema_frame_ms(next_ema);
        self.set_ema_jitter_ms(next_jitter);
        self.set_p99_est_ms(next_p99);
        self.set_last_frame_ms(safe_ms);
        self.set_total_frames(frames.saturating_add(1));
        if config.get_dynamic_resolution() {
            let min_s: f32 = self.get_min_scale();
            let max_s: f32 = self.get_max_scale();
            let mut cur_s: f32 = self.get_current_scale().clamp(min_s, max_s);
            let mut rt_bias: usize = self.get_rt_stride_bias();
            let mut lod_b: f32 = self.get_lod_bias();
            let over_hard: bool = safe_ms > budget_ms * 1.06 || next_ema > budget_ms * 1.01;
            let under_safe: bool = safe_ms < budget_ms * 0.84 && next_ema < budget_ms * 0.78;
            if over_hard {
                self.set_under_budget_streak(0);
                let next_over: u32 = self.get_over_budget_streak().saturating_add(1);
                self.set_over_budget_streak(next_over);
                let pressure: f32 = ((safe_ms.max(next_ema) / budget_ms) - 1.0).clamp(0.02, 1.5);
                let step_down: f32 = (pressure * 0.12).clamp(GOVERNOR_SCALE_QUANTUM, 0.10);
                let next_s: f32 = Self::quantize_scale(cur_s - step_down, min_s, max_s);
                if next_s < cur_s - 1.0e-4 {
                    cur_s = next_s;
                } else if next_over >= 3 {
                    if rt_bias < 3 {
                        rt_bias += 1;
                    }
                    lod_b = (lod_b + 0.10).clamp(0.75, 1.80);
                }
            } else if under_safe {
                self.set_over_budget_streak(0);
                let next_under: u32 = self.get_under_budget_streak().saturating_add(1);
                self.set_under_budget_streak(next_under);
                if next_under >= self.get_hysteresis_frames().max(2) {
                    self.set_under_budget_streak(0);
                    if lod_b > 1.02 {
                        lod_b = (lod_b - 0.08).max(1.0);
                    } else if rt_bias > 0 {
                        rt_bias -= 1;
                    } else {
                        cur_s = Self::quantize_scale(cur_s + GOVERNOR_SCALE_QUANTUM, min_s, max_s);
                    }
                }
            } else {
                self.set_over_budget_streak(0);
                self.set_under_budget_streak(0);
            }
            self.set_current_scale(cur_s);
            self.set_rt_stride_bias(rt_bias);
            self.set_lod_bias(lod_b);
            config.set_resolution_scale(cur_s);
            config.set_lod_bias(lod_b);
        }
        let util: f32 = next_ema / budget_ms.max(0.01);
        let jitter_penalty: f32 = (next_jitter / budget_ms.max(0.01)).clamp(0.0, 1.0);
        let overrun_penalty: f32 = (util - 1.0).clamp(0.0, 1.0);
        let stability: f32 = (1.0 - jitter_penalty * 0.65 - overrun_penalty * 0.55).clamp(0.0, 1.0);
        FramePacingTelemetry3D {
            budget_ms,
            ema_frame_ms: next_ema,
            p99_est_ms: next_p99,
            budget_utilization: util,
            effective_resolution_scale: self.get_current_scale(),
            effective_rt_stride_bias: self.get_rt_stride_bias(),
            effective_lod_bias: self.get_lod_bias(),
            stability_score: stability,
        }
    }
}