arc-graphics3d 0.4.0

Experimental standalone wgpu 3D renderer with orbit camera, OBJ geometry, multi-mesh scenes, picking and framing.
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! 3D 离屏渲染的像素级验收。
//!
//! - `cube_render_pixels`:立方体三场景验收——
//!   1. 背景清空色(Rgba8UnormSrgb 伽马编码);
//!   2. 双立方体前后遮挡:交换颜色/绘制顺序后,屏幕重叠区始终显示**靠前**实例,
//!      证明深度测试与绘制顺序无关;
//!   3. 方向光自上而下:立方体顶面(+Y 法线)明显亮于侧面。
//!
//! 设置 `ARC_GRAPHICS3D_RENDER_DIR` 时输出 PNG 供人工复核。
//!
//! 运行:`cargo test -p arc-graphics3d -- --nocapture`

use arc_graphics3d::{
    Camera3d, DirectionalLight, Instance3d, Mesh3d, Object3d, Ray3d, Renderer3d, Scene3d,
    capture_rgba, normal_matrix, pick_objects, trs_matrix,
};
use pollster::block_on;
use std::path::Path;
use wgpu::{Instance, InstanceDescriptor, PowerPreference, RequestAdapterOptions};

const WIDTH: u32 = 320;
const HEIGHT: u32 = 240;
const CLEAR: wgpu::Color = wgpu::Color {
    r: 0.06,
    g: 0.07,
    b: 0.09,
    a: 1.0,
};

/// 蓝色与珊瑚色实例基础色(与图例色盘一致)。
const BLUE: [f32; 4] = [0.22, 0.50, 0.94, 1.0];
const CORAL: [f32; 4] = [0.95, 0.55, 0.38, 1.0];

/// 前后两个立方体的位置:x 各偏 ±0.25 保证后方实例侧缘露出;z 相差 1.8 保证深度差。
const FRONT_POS: [f32; 3] = [-0.25, 0.5, 0.9];
const BACK_POS: [f32; 3] = [0.25, 0.5, -0.9];

fn adapter_and_device() -> Option<(wgpu::Device, wgpu::Queue, String)> {
    let instance = Instance::new(InstanceDescriptor::new_without_display_handle());
    let adapter = block_on(instance.request_adapter(&RequestAdapterOptions {
        power_preference: PowerPreference::HighPerformance,
        compatible_surface: None,
        force_fallback_adapter: false,
        apply_limit_buckets: false,
    }))
    .ok()?;
    let info = adapter.get_info();
    let desc = format!("{} ({:?}, {:?})", info.name, info.backend, info.device_type);
    let (device, queue) =
        block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()?;
    Some((device, queue, desc))
}

/// 平移 + 均匀缩放的模型矩阵(列主序;均匀缩放对法线变换正确)。
fn model_matrix(pos: [f32; 3], scale: f32) -> [[f32; 4]; 4] {
    [
        [scale, 0.0, 0.0, 0.0],
        [0.0, scale, 0.0, 0.0],
        [0.0, 0.0, scale, 0.0],
        [pos[0], pos[1], pos[2], 1.0],
    ]
}

/// 纯数学回归:逆转置法线矩阵在「旋转 + 非均匀缩放」下保持法线正确,
/// 而天真的 `model * normal` 会把法线拉向缩放轴。
#[test]
fn normal_matrix_survives_rotation_plus_nonuniform_scale() {
    let transform = |m: [[f32; 4]; 3], v: [f32; 3]| -> [f32; 3] {
        // 列主序 N·v:result[r] = Σ_c N[c][r]·v[c]。
        let out = [
            m[0][0] * v[0] + m[1][0] * v[1] + m[2][0] * v[2],
            m[0][1] * v[0] + m[1][1] * v[1] + m[2][1] * v[2],
            m[0][2] * v[0] + m[1][2] * v[1] + m[2][2] * v[2],
        ];
        let len = (out[0] * out[0] + out[1] * out[1] + out[2] * out[2]).sqrt();
        [out[0] / len, out[1] / len, out[2] / len]
    };

    // 场景:局部先沿 Y 放大 4 倍,再绕 Y 旋转 45°;取局部对角法线 (1,1,0)。
    // 正确:N·n = R·S⁻¹·n = R·(1, 0.25, 0) = (0.7071, 0.25, -0.7071),
    // 归一化 ≈ (0.6859, 0.2425, -0.6859)。
    // 天真:R·S·n = R·(1, 4, 0) → 归一化 ≈ (0.1715, 0.9701, -0.1715),两者显著不同。
    let model = trs_matrix(
        [0.0, 0.0, 0.0],
        std::f32::consts::FRAC_PI_4,
        0.0,
        [1.0, 4.0, 1.0],
    );
    let n = normal_matrix(model);
    let got = transform(n, [1.0, 1.0, 0.0]);
    let s = std::f32::consts::FRAC_1_SQRT_2;
    let expected_raw = [s, 0.25, -s];
    let expected_len = (expected_raw[0] * expected_raw[0]
        + expected_raw[1] * expected_raw[1]
        + expected_raw[2] * expected_raw[2])
        .sqrt();
    let expected = [
        expected_raw[0] / expected_len,
        expected_raw[1] / expected_len,
        expected_raw[2] / expected_len,
    ];
    for i in 0..3 {
        assert!(
            (got[i] - expected[i]).abs() < 1e-4,
            "法线矩阵结果 {got:?} 应为 {expected:?}"
        );
    }
    // 天真做法(model*n 后归一化)会得到 (0.1715, 0.9701, -0.1715),两解必须显著不同。
    let naive_raw = [s, 4.0, -s];
    let naive_len =
        (naive_raw[0] * naive_raw[0] + naive_raw[1] * naive_raw[1] + naive_raw[2] * naive_raw[2])
            .sqrt();
    assert!(
        (got[1] - naive_raw[1] / naive_len).abs() > 0.5,
        "逆转置结果不应与天真变换重合"
    );

    // 单位阵 / 纯平移:法线应原样通过。
    let n_id = normal_matrix(trs_matrix([1.0, 2.0, 3.0], 0.0, 0.0, [1.0, 1.0, 1.0]));
    let got_id = transform(n_id, [0.0, 1.0, 0.0]);
    assert!((got_id[1] - 1.0).abs() < 1e-5);
}

/// 退化缩放没有可逆的法线矩阵,应按公开约定回退为有限单位阵。
#[test]
fn singular_normal_matrix_falls_back_to_identity() {
    let expected = [
        [1.0, 0.0, 0.0, 0.0],
        [0.0, 1.0, 0.0, 0.0],
        [0.0, 0.0, 1.0, 0.0],
    ];
    for scale in [[0.0, 0.0, 0.0], [1.0, 0.0, 2.0]] {
        assert_eq!(
            normal_matrix(trs_matrix([0.0; 3], 0.3, 0.2, scale)),
            expected
        );
    }
}

#[test]
fn picking_matches_camera_clipping_depth_and_transforms() {
    use arc_graphics3d::pick_mesh;
    let camera = Camera3d::orbit([0.0; 3], 0.0, 0.0, 5.0);
    let ray = camera.screen_ray([200.0, 150.0], [400.0, 300.0]).unwrap();
    assert_eq!(ray.direction, [0.0, 0.0, -1.0]);
    let mesh = Mesh3d::cube();
    let front = Instance3d::trs([0.0, 0.0, 1.0], 0.4, 0.2, [1.8, 0.5, 1.0], BLUE);
    let back = Instance3d::default();
    for (instances, expected) in [([back, front], 1), ([front, back], 0)] {
        let hit = pick_mesh(&mesh, &instances, ray).unwrap();
        assert_eq!(hit.instance_index, expected);
        assert!(hit.distance > 3.0 && hit.distance < 4.0);
        assert!((hit.position[2] - (5.0 - hit.distance)).abs() < 1e-5);
    }
    assert!(
        pick_mesh(
            &mesh,
            &[back],
            camera.screen_ray([0.0, 0.0], [400.0, 300.0]).unwrap()
        )
        .is_none()
    );
    for clipped in [
        Camera3d {
            near: 6.0,
            ..camera
        },
        Camera3d { far: 4.0, ..camera },
    ] {
        assert!(
            pick_mesh(
                &mesh,
                &[back],
                clipped.screen_ray([200.0, 150.0], [400.0, 300.0]).unwrap()
            )
            .is_none()
        );
    }
    // 负缩放的绕序仍与GPU背面剔除一致;退化点网格不产生假命中。
    let mirrored = Instance3d::trs([0.0; 3], 0.2, 0.1, [-1.0, 2.0, 0.5], BLUE);
    assert!(pick_mesh(&mesh, &[mirrored], ray).is_some());
    let collapsed = Instance3d::trs([0.0; 3], 0.0, 0.0, [0.0; 3], BLUE);
    assert!(pick_mesh(&mesh, &[collapsed], ray).is_none());
    let mut invalid = back;
    invalid.model[0][0] = f32::NAN;
    assert!(pick_mesh(&mesh, &[invalid], ray).is_none());
    assert!(camera.screen_ray([f32::NAN, 0.0], [400.0, 300.0]).is_none());
    assert!(camera.screen_ray([-1.0, 0.0], [400.0, 300.0]).is_none());
    assert!(camera.screen_ray([0.0; 2], [0.0; 2]).is_none());
    assert!(
        Camera3d {
            up: [0.0, 0.0, 1.0],
            ..camera
        }
        .screen_ray([200.0, 150.0], [400.0, 300.0])
        .is_none()
    );
}

#[test]
fn framing_keeps_all_transformed_vertices_inside_wide_and_narrow_frusta() {
    use arc_graphics3d::Bounds3d;
    let mesh = Mesh3d::cube();
    let instances = [
        Instance3d::trs([-2.0, 1.0, -1.0], 0.4, 0.2, [0.5, 3.0, 1.0], BLUE),
        Instance3d::trs([3.0, -1.0, 2.0], 0.8, 0.0, [2.0, 0.5, 1.0], CORAL),
    ];
    let bounds = Bounds3d::from_instances(&mesh, &instances).unwrap();
    assert!(Bounds3d::from_instances(&mesh, &[]).is_none());
    for aspect in [0.35, 1.0, 2.5] {
        // 正前方相机方便独立核验投影,不借助被测射线/取景代码。
        let camera = Camera3d::orbit([0.0; 3], 0.0, 0.0, 5.0)
            .frame_bounds(bounds, aspect)
            .unwrap();
        for instance in instances {
            for vertex in &mesh.vertices {
                let p: [f32; 3] = std::array::from_fn(|r| {
                    instance.model[3][r]
                        + (0..3)
                            .map(|c| instance.model[c][r] * vertex.position[c])
                            .sum::<f32>()
                });
                let depth = camera.eye[2] - p[2];
                assert!(depth >= camera.near && depth <= camera.far);
                let half_y = depth * (camera.fov_y_radians * 0.5).tan();
                assert!((p[1] - camera.target[1]).abs() < half_y);
                assert!((p[0] - camera.target[0]).abs() < half_y * aspect);
            }
        }
    }
}

/// 纯数学回归:轨道相机位置随 yaw/pitch/distance 的变化。
#[test]
fn orbit_camera_matches_spherical_layout() {
    let target = [1.0, 2.0, 3.0];
    let c0 = Camera3d::orbit(target, 0.0, 0.0, 5.0);
    assert!((c0.eye[0] - 1.0).abs() < 1e-5);
    assert!((c0.eye[1] - 2.0).abs() < 1e-5);
    assert!((c0.eye[2] - 8.0).abs() < 1e-5);
    // yaw = π/2:视线从 +X 方向看回目标。
    let c1 = Camera3d::orbit(target, std::f32::consts::FRAC_PI_2, 0.0, 5.0);
    assert!((c1.eye[0] - 6.0).abs() < 1e-5);
    assert!((c1.eye[2] - 3.0).abs() < 1e-5);
    // pitch 仰角抬高相机。
    let c2 = Camera3d::orbit(target, 0.0, std::f32::consts::FRAC_PI_2, 5.0);
    assert!((c2.eye[1] - 7.0).abs() < 1e-5);
}

#[test]
fn cube_render_pixels() {
    let Some((device, queue, adapter_desc)) = adapter_and_device() else {
        eprintln!("跳过:无可用 GPU 适配器");
        return;
    };
    println!("适配器:{adapter_desc}");

    let mut renderer = block_on(Renderer3d::new(
        device.clone(),
        queue.clone(),
        wgpu::TextureFormat::Rgba8UnormSrgb,
        &Mesh3d::cube(),
        8,
    ));

    // 场景 A:蓝前珊瑚后;场景 B:珊瑚前蓝后。位置与绘制顺序完全对称。
    let scene_a = [
        Instance3d {
            model: model_matrix(FRONT_POS, 0.8),
            color: BLUE,
        },
        Instance3d {
            model: model_matrix(BACK_POS, 0.8),
            color: CORAL,
        },
    ];
    let scene_b = [
        Instance3d {
            model: model_matrix(FRONT_POS, 0.8),
            color: CORAL,
        },
        Instance3d {
            model: model_matrix(BACK_POS, 0.8),
            color: BLUE,
        },
    ];

    // 单珊瑚立方体场景:验证方向光上下明暗。
    let scene_light = [Instance3d {
        model: model_matrix([0.0, 0.5, 0.0], 0.9),
        color: CORAL,
    }];

    let (texture, color_view, depth_view) = renderer.create_offscreen_target(WIDTH, HEIGHT);
    renderer.set_camera(
        Camera3d::default(),
        DirectionalLight::default(),
        WIDTH as f32 / HEIGHT as f32,
    );

    // Rgba8UnormSrgb 存储时做线性→sRGB 伽马编码,期望值按 sRGB 计算。
    let srgb_encode = |c: f64| -> u8 {
        let v = if c <= 0.003_130_8 {
            c * 12.92
        } else {
            1.055 * c.powf(1.0 / 2.4) - 0.055
        };
        ((v * 255.0).round() as u8).clamp(0, 255)
    };
    let clear = [
        srgb_encode(CLEAR.r),
        srgb_encode(CLEAR.g),
        srgb_encode(CLEAR.b),
        255,
    ];

    let mut captures: Vec<Vec<Vec<[u8; 4]>>> = Vec::new();
    for scene in [&scene_a[..], &scene_b[..], &scene_light[..]] {
        renderer.update_instances(scene);
        renderer.render(&color_view, &depth_view, CLEAR);
        let (data, bytes_per_row) =
            arc_graphics3d::capture_rgba(&device, &queue, &texture, WIDTH, HEIGHT);
        let frame: Vec<Vec<[u8; 4]>> = (0..HEIGHT as usize)
            .map(|y| {
                let row = y * bytes_per_row as usize;
                (0..WIDTH as usize)
                    .map(|x| data[row + x * 4..row + x * 4 + 4].try_into().unwrap())
                    .collect::<Vec<_>>()
            })
            .collect();
        captures.push(frame);
    }
    let px =
        |frame: &Vec<Vec<[u8; 4]>>, x: u32, y: u32| -> [u8; 4] { frame[y as usize][x as usize] };
    let is_object = |p: [u8; 4]| -> bool { p != clear && p[3] != 0 };
    let is_blue_like = |p: [u8; 4]| -> bool { p[2] > p[0] && p[2] > p[1] };
    let is_coral_like = |p: [u8; 4]| -> bool { p[0] > p[2] && p[1] > p[2] && p[0] > p[1] };

    let [frame_a, frame_b, frame_light] = captures.try_into().expect("三帧捕获");

    // ---- 场景 A ----
    // 1. 角落保持清空色。
    let corner = px(&frame_a, 4, 4);
    assert_eq!(
        corner, clear,
        "角落应为 sRGB 编码后的清空色,实际 {corner:?}"
    );

    // 2. 两实例各自可见(蓝左、珊瑚右)。
    let mut found_blue = false;
    let mut found_coral = false;
    for y in (0..HEIGHT).step_by(2) {
        for x in (0..WIDTH).step_by(2) {
            let p = px(&frame_a, x, y);
            if !is_object(p) {
                continue;
            }
            if is_blue_like(p) && (x as f32) < WIDTH as f32 * 0.45 {
                found_blue = true;
            }
            if is_coral_like(p) && (x as f32) > WIDTH as f32 * 0.55 {
                found_coral = true;
            }
        }
    }
    assert!(found_blue, "左半屏应出现蓝色实例");
    assert!(found_coral, "右半屏应出现珊瑚色实例");

    // 3. 深度遮挡:两帧的公共非背景区域 = 屏幕重叠区。
    //    场景 A 中靠前的是蓝、场景 B 中靠前的是珊瑚(绘制顺序相同,均为实例 0 在前)。
    //    若深度测试生效,重叠区颜色随前后关系翻转而交换,与绘制顺序无关。
    let mut common_blue = 0;
    let mut common_coral = 0;
    for y in (0..HEIGHT).step_by(2) {
        for x in (0..WIDTH).step_by(2) {
            let pa = px(&frame_a, x, y);
            let pb = px(&frame_b, x, y);
            if is_object(pa) && is_object(pb) {
                if is_blue_like(pa) {
                    common_blue += 1;
                }
                if is_coral_like(pa) {
                    common_coral += 1;
                }
                if is_blue_like(pb) {
                    common_blue += 1;
                }
                if is_coral_like(pb) {
                    common_coral += 1;
                }
            }
        }
    }
    assert!(
        common_blue >= 25,
        "重叠区应大量显示场景 A 的前层蓝色,实际 {common_blue}"
    );
    assert!(
        common_coral >= 25,
        "重叠区应大量显示场景 B 的前层珊瑚色,实际 {common_coral}"
    );

    // 4. 方向光自上而下(默认 direction = [-0.5, -1, -0.4]):立方体顶面(+Y 法线)
    //    受光最强,应明显亮于物体下部的侧面。用物体包围盒的上/下 1/3 对比。
    let mut min_y = HEIGHT;
    let mut max_y = 0;
    for y in (0..HEIGHT).step_by(2) {
        for x in (0..WIDTH).step_by(2) {
            if is_object(px(&frame_light, x, y)) {
                min_y = min_y.min(y);
                max_y = max_y.max(y);
            }
        }
    }
    assert!(min_y < max_y, "光照场景应存在物体像素");
    let band = (max_y - min_y) / 3;
    let brightness = |p: [u8; 4]| -> f32 { (p[0] as f32 + p[1] as f32 + p[2] as f32) / 765.0 };
    let band_avg = |lo: u32, hi: u32| -> (f32, u32) {
        let mut sum = 0.0;
        let mut n = 0;
        for y in (lo..hi).step_by(2) {
            for x in (0..WIDTH).step_by(2) {
                let p = px(&frame_light, x, y);
                if is_object(p) {
                    sum += brightness(p);
                    n += 1;
                }
            }
        }
        (if n > 0 { sum / n as f32 } else { 0.0 }, n)
    };
    let (top_avg, top_n) = band_avg(min_y, min_y + band);
    let (bottom_avg, bottom_n) = band_avg(max_y - band, max_y);
    assert!(top_n > 0 && bottom_n > 0, "物体上下带都应有像素");
    assert!(
        top_avg > bottom_avg,
        "方向光自上而下照射,顶面应更亮:top {top_avg:.3} vs bottom {bottom_avg:.3}"
    );

    // 独立GPU光栅结果对照CPU射线:宽高比、屏幕Y翻转、矩阵顺序与遮挡必须一致。
    let mut checked = 0;
    for y in (8..HEIGHT - 8).step_by(8) {
        for x in (8..WIDTH - 8).step_by(8) {
            let pixel = px(&frame_a, x, y);
            let ray = Camera3d::default()
                .screen_ray(
                    [x as f32 + 0.5, y as f32 + 0.5],
                    [WIDTH as f32, HEIGHT as f32],
                )
                .unwrap();
            let hit = arc_graphics3d::pick_mesh(&Mesh3d::cube(), &scene_a, ray);
            if let Some(hit) = hit {
                assert!(is_object(pixel), "射线命中却没有GPU像素:({x},{y})");
                assert_eq!(
                    is_blue_like(pixel),
                    hit.instance_index == 0,
                    "拾取必须等于深度测试后可见的物体:({x},{y})"
                );
                checked += 1;
            } else {
                assert!(!is_object(pixel), "可见像素未拾取:({x},{y})");
            }
        }
    }
    assert!(checked > 10);

    // 诊断输出:三帧并排一张 PNG。
    if let Ok(dir) = std::env::var("ARC_GRAPHICS3D_RENDER_DIR") {
        let total_w = WIDTH * 3 + 16;
        let img = image::RgbaImage::from_fn(total_w, HEIGHT, |x, y| {
            let frame = match x / (WIDTH + 8) {
                0 => &frame_a,
                1 => &frame_b,
                _ => &frame_light,
            };
            let x = (x % (WIDTH + 8)).min(WIDTH - 1);
            let p = frame[y as usize][x as usize];
            image::Rgba([p[0], p[1], p[2], 255])
        });
        let path = Path::new(&dir).join("graphics3d-smoke.png");
        img.save(&path).expect("保存 PNG 失败");
        println!("已输出 {}", path.display());
    }
}

/// 参考实现:逐对象、逐三角形做世界空间 Möller–Trumbore。
/// 用来验证两级加速(世界 AABB 宽相 + 局部 BVH)与全量扫描结果一致。
fn brute_pick(meshes: &[Mesh3d], objects: &[Object3d], ray: Ray3d) -> Option<(usize, f32)> {
    let mut best: Option<(usize, f32)> = None;
    for (index, object) in objects.iter().enumerate() {
        let mesh = &meshes[object.mesh_index];
        let model = object.instance.model;
        let world = |p: [f32; 3]| -> [f32; 3] {
            std::array::from_fn(|r| {
                model[0][r] * p[0] + model[1][r] * p[1] + model[2][r] * p[2] + model[3][r]
            })
        };
        for triangle in mesh.vertices.chunks_exact(3) {
            let a = world(triangle[0].position);
            let b = world(triangle[1].position);
            let c = world(triangle[2].position);
            let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
            let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
            let p = [
                ray.direction[1] * e2[2] - ray.direction[2] * e2[1],
                ray.direction[2] * e2[0] - ray.direction[0] * e2[2],
                ray.direction[0] * e2[1] - ray.direction[1] * e2[0],
            ];
            let determinant = e1[0] * p[0] + e1[1] * p[1] + e1[2] * p[2];
            let area = (e1[0] * e1[0] + e1[1] * e1[1] + e1[2] * e1[2]).sqrt()
                * (e2[0] * e2[0] + e2[1] * e2[1] + e2[2] * e2[2]).sqrt();
            if !determinant.is_finite() || determinant <= area * 1e-7 {
                continue;
            }
            let t = [
                ray.origin[0] - a[0],
                ray.origin[1] - a[1],
                ray.origin[2] - a[2],
            ];
            let u = (t[0] * p[0] + t[1] * p[1] + t[2] * p[2]) / determinant;
            if !(0.0..=1.0).contains(&u) {
                continue;
            }
            let q = [
                t[1] * e1[2] - t[2] * e1[1],
                t[2] * e1[0] - t[0] * e1[2],
                t[0] * e1[1] - t[1] * e1[0],
            ];
            let v = (ray.direction[0] * q[0] + ray.direction[1] * q[1] + ray.direction[2] * q[2])
                / determinant;
            if v < 0.0 || u + v > 1.0 {
                continue;
            }
            let distance = (e2[0] * q[0] + e2[1] * q[1] + e2[2] * q[2]) / determinant;
            if !distance.is_finite()
                || distance < ray.min_distance
                || distance > ray.max_distance
                || best.is_some_and(|(_, previous)| distance >= previous)
            {
                continue;
            }
            best = Some((index, distance));
        }
    }
    best
}

/// 起伏地形网格:`n×n×2` 个三角形,用于验证加速结构。
fn terrain_mesh(n: usize) -> Mesh3d {
    let mut vertices = Vec::new();
    for row in 0..n {
        for col in 0..n {
            let x0 = col as f32 * 0.2 - 3.0;
            let x1 = x0 + 0.2;
            let y0 = row as f32 * 0.2 - 3.0;
            let y1 = y0 + 0.2;
            let z = |x: f32, y: f32| (x * 0.7).sin() * (y * 0.9).cos() * 0.4;
            let p = [
                [x0, y0, z(x0, y0)],
                [x1, y0, z(x1, y0)],
                [x1, y1, z(x1, y1)],
                [x0, y0, z(x0, y0)],
                [x1, y1, z(x1, y1)],
                [x0, y1, z(x0, y1)],
            ];
            for position in p {
                vertices.push(arc_graphics3d::Vertex3d {
                    position,
                    // 法线只需非零,拾取不使用。
                    normal: [0.0, 0.0, 1.0],
                });
            }
        }
    }
    Mesh3d::new(vertices)
}

#[test]
fn picking_matches_brute_force_across_transforms() {
    let meshes = vec![terrain_mesh(30)];
    let objects = vec![
        Object3d {
            name: "identity".into(),
            mesh_index: 0,
            instance: Instance3d::trs([0.0, 0.0, 0.0], 0.0, 0.0, [1.0; 3], BLUE),
        },
        Object3d {
            name: "rotated".into(),
            mesh_index: 0,
            instance: Instance3d::trs([0.6, -0.4, 0.2], 0.35, 0.2, [1.3, 0.9, 1.0], CORAL),
        },
        Object3d {
            name: "mirrored".into(),
            mesh_index: 0,
            instance: Instance3d::trs([-0.8, 0.5, -0.3], -0.5, 0.1, [-1.0, 1.0, 1.0], BLUE),
        },
    ];
    let camera = Camera3d::orbit([0.0, 0.0, 0.0], 0.12, 0.62, 6.5);
    let mut compared = 0;
    let mut hits = 0;
    for row in 0..24 {
        for column in 0..32 {
            let position = [
                (column as f32 + 0.5) * WIDTH as f32 / 32.0,
                (row as f32 + 0.5) * HEIGHT as f32 / 24.0,
            ];
            let Some(ray) = camera.screen_ray(position, [WIDTH as f32, HEIGHT as f32]) else {
                continue;
            };
            let fast = pick_objects(&meshes, &objects, ray);
            let slow = brute_pick(&meshes, &objects, ray);
            match (fast, slow) {
                (None, None) => {}
                (Some(hit), Some((index, distance))) => {
                    assert_eq!(
                        hit.instance_index, index,
                        "射线 {position:?} 命中对象不一致:加速 {} 全量 {index}",
                        hit.instance_index
                    );
                    assert!(
                        (hit.distance - distance).abs() < 1e-3,
                        "射线 {position:?} 距离差异:加速 {} 全量 {distance}",
                        hit.distance
                    );
                    hits += 1;
                }
                (fast, slow) => panic!("射线 {position:?} 命中结论不一致:{fast:?} vs {slow:?}"),
            }
            compared += 1;
        }
    }
    assert!(compared > 500, "有效射线过少:{compared}");
    assert!(hits > 100, "命中样本过少:{hits}");
}

/// 视锥剔除只减少绘制,不改画面;绘制调用按网格合并。
#[test]
fn frustum_culling_preserves_pixels_and_batches_by_mesh() {
    let Some((device, queue, description)) = adapter_and_device() else {
        eprintln!("跳过:没有可用 GPU 适配器");
        return;
    };
    let cube = Mesh3d::cube();
    let triangle = Mesh3d::triangle();
    let mut renderer = block_on(Renderer3d::new(
        device,
        queue,
        wgpu::TextureFormat::Rgba8UnormSrgb,
        &cube,
        8,
    ));
    let object = |name: &str, mesh_index: usize, position: [f32; 3], color: [f32; 4]| Object3d {
        name: name.into(),
        mesh_index,
        instance: Instance3d::trs(position, 0.35, 0.2, [1.0, 1.0, 1.0], color),
    };
    let mut scene = Scene3d {
        meshes: vec![cube, triangle],
        objects: vec![
            object("cube-left", 0, [-1.0, 0.1, 0.0], BLUE),
            object("cube-right", 0, [1.0, 0.1, 0.0], CORAL),
            object("triangle", 1, [0.0, 1.0, 0.2], BLUE),
            object("offscreen", 0, [60.0, 0.0, 0.0], CORAL),
        ],
    };
    renderer.set_scene(&scene).expect("场景有效");
    // 四个对象、两个网格 → 两次绘制,而不是四次。
    assert_eq!(renderer.batch_count(), 2, "{description}");

    let camera = Camera3d::orbit([0.0, 0.0, 0.0], 0.0, 0.25, 6.0);
    let aspect = WIDTH as f32 / HEIGHT as f32;
    renderer.set_camera(camera, DirectionalLight::default(), aspect);
    let frustum = renderer.frustum(camera, aspect);
    let instances_drawn = |frustum: Option<&arc_graphics3d::Frustum3d>| -> u32 {
        renderer
            .plan_draws(frustum)
            .iter()
            .map(|(_, instances)| instances.end - instances.start)
            .sum()
    };
    assert_eq!(renderer.plan_draws(None).len(), 2, "两个网格两批绘制");
    assert_eq!(instances_drawn(None), 4);
    assert_eq!(instances_drawn(Some(&frustum)), 3, "视野外对象应被剔除");
    assert!(
        renderer
            .plan_draws(Some(&frustum))
            .iter()
            .all(|(_, instances)| !instances.contains(&2)),
        "被剔除的实例不应出现在绘制计划里"
    );

    let (texture_full, view_full, depth_full) = renderer.create_offscreen_target(WIDTH, HEIGHT);
    renderer.render(&view_full, &depth_full, CLEAR);
    let (device, queue) = renderer.device_queue();
    let full = capture_rgba(device, queue, &texture_full, WIDTH, HEIGHT).0;

    let (texture_culled, view_culled, depth_culled) =
        renderer.create_offscreen_target(WIDTH, HEIGHT);
    renderer.render_visible(&view_culled, &depth_culled, CLEAR, Some(&frustum));
    let culled = capture_rgba(device, queue, &texture_culled, WIDTH, HEIGHT).0;
    assert_eq!(full, culled, "剔除后可见像素必须与全量绘制一致");

    // 去掉视野外对象后仍是两批,剔除结果与全量绘制一致。
    scene.objects.pop();
    renderer.set_scene(&scene).expect("场景有效");
    assert_eq!(renderer.plan_draws(Some(&frustum)).len(), 2);
    renderer.render_visible(&view_culled, &depth_culled, CLEAR, Some(&frustum));
    let (device, queue) = renderer.device_queue();
    let without_offscreen = capture_rgba(device, queue, &texture_culled, WIDTH, HEIGHT).0;
    assert_eq!(full, without_offscreen);
}

/// 加速结构收益:同一大网格、同一批射线,比较 BVH 与全量扫描的总耗时。
/// 只断言「BVH 更快」,倍数打印出来供人工核对。
#[test]
fn bvh_outperforms_linear_scan_on_large_mesh() {
    let meshes = vec![terrain_mesh(80)];
    let objects = vec![Object3d {
        name: "terrain".into(),
        mesh_index: 0,
        instance: Instance3d::trs([0.0, 0.0, 0.0], 0.25, 0.15, [1.0; 3], BLUE),
    }];
    let triangles = meshes[0].vertices.len() / 3;
    let camera = Camera3d::orbit([0.0, 0.0, 0.0], 0.1, 0.5, 6.0);
    let rays: Vec<Ray3d> = (0..200)
        .filter_map(|i| {
            let x = (i % 20) as f32 / 20.0 * WIDTH as f32 + 4.0;
            let y = (i / 20) as f32 / 10.0 * HEIGHT as f32 + 4.0;
            camera.screen_ray([x, y], [WIDTH as f32, HEIGHT as f32])
        })
        .collect();
    // 预热:首次调用会构建并缓存 BVH,不计入比较。
    let _ = pick_objects(&meshes, &objects, rays[0]);

    let start = std::time::Instant::now();
    let accelerated: Vec<_> = rays
        .iter()
        .map(|ray| pick_objects(&meshes, &objects, *ray))
        .collect();
    let fast = start.elapsed();

    let start = std::time::Instant::now();
    let scanned: Vec<_> = rays
        .iter()
        .map(|ray| brute_pick(&meshes, &objects, *ray))
        .collect();
    let slow = start.elapsed();

    assert_eq!(accelerated.len(), scanned.len());
    for (fast_hit, slow_hit) in accelerated.iter().zip(&scanned) {
        assert_eq!(
            fast_hit.map(|hit| hit.instance_index),
            slow_hit.map(|(index, _)| index)
        );
    }
    println!(
        "拾取 {triangles} 三角形 × {} 条射线:BVH {fast:?},全量扫描 {slow:?},加速 {:.1}×",
        rays.len(),
        slow.as_secs_f64() / fast.as_secs_f64().max(f64::EPSILON)
    );
    assert!(fast < slow, "BVH 应快于全量扫描:{fast:?} vs {slow:?}");
}