arc-graphics3d 0.2.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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
//! 3D 离屏渲染器第一轮:明确小范围、可测量、可扩展。

use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;

/// 右手坐标系相机:相机朝 -Z,`up` 为 +Y。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Camera3d {
    pub eye: [f32; 3],
    pub target: [f32; 3],
    pub up: [f32; 3],
    pub fov_y_radians: f32,
    pub near: f32,
    pub far: f32,
}

impl Default for Camera3d {
    fn default() -> Self {
        Self {
            eye: [2.8, 2.2, 4.8],
            target: [0.0, 0.5, 0.0],
            up: [0.0, 1.0, 0.0],
            fov_y_radians: 0.75,
            near: 0.1,
            far: 100.0,
        }
    }
}

impl Camera3d {
    /// 轨道相机:绕 `target` 按 yaw(绕 +Y,弧度)与 pitch(仰角,弧度)
    /// 半径 `distance` 取景。向上方向恒为 +Y。
    pub fn orbit(target: [f32; 3], yaw: f32, pitch: f32, distance: f32) -> Self {
        let cos_pitch = pitch.cos();
        let eye = [
            target[0] + distance * cos_pitch * yaw.sin(),
            target[1] + distance * pitch.sin(),
            target[2] + distance * cos_pitch * yaw.cos(),
        ];
        Self {
            eye,
            target,
            up: [0.0, 1.0, 0.0],
            ..Self::default()
        }
    }
}

/// 方向光;颜色和强度预留给后续 PBR/IBL。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DirectionalLight {
    pub direction: [f32; 3],
    pub color: [f32; 3],
    pub intensity: f32,
}

impl Default for DirectionalLight {
    fn default() -> Self {
        Self {
            direction: [-0.5, -1.0, -0.4],
            color: [1.0, 1.0, 1.0],
            intensity: 1.0,
        }
    }
}

/// 顶点位置与法线;UV、切线和索引拓展留给下一轮。
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Vertex3d {
    pub position: [f32; 3],
    pub normal: [f32; 3],
}

impl Vertex3d {
    pub const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
        0 => Float32x3,
        1 => Float32x3,
    ];

    pub fn layout<'a>() -> wgpu::VertexBufferLayout<'a> {
        wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<Self>() as u64,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &Self::ATTRIBS,
        }
    }
}

/// 一个三角形网格。第一轮使用非索引三角形,减少 API 复杂度。
#[derive(Clone, Debug, PartialEq)]
pub struct Mesh3d {
    pub vertices: Vec<Vertex3d>,
}

impl Mesh3d {
    /// 轴对齐立方体:半边长 0.5,中心在原点;每面独立法线,外向 CCW 绕序。
    /// 6 面 × 2 三角形 × 3 顶点 = 36 顶点(保持非索引,与 `triangle` 一致)。
    pub fn cube() -> Self {
        // (法线 n, 切线 t, 副切线 b),均满足 t × b = n,保证从外部看为逆时针绕序,
        // 与 wgpu 默认 FrontFace::Ccw + 背面剔除配套。
        const FACES: [([f32; 3], [f32; 3], [f32; 3]); 6] = [
            ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
            ([-1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
            ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]),
            ([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
            ([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
            ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]),
        ];
        let mut vertices = Vec::with_capacity(36);
        for &(n, t, b) in &FACES {
            let center = [n[0] * 0.5, n[1] * 0.5, n[2] * 0.5];
            let corner = |st: f32, sb: f32| -> [f32; 3] {
                [
                    center[0] + (t[0] * st + b[0] * sb) * 0.5,
                    center[1] + (t[1] * st + b[1] * sb) * 0.5,
                    center[2] + (t[2] * st + b[2] * sb) * 0.5,
                ]
            };
            for (st, sb) in [
                (-1.0, -1.0),
                (1.0, -1.0),
                (1.0, 1.0),
                (-1.0, -1.0),
                (1.0, 1.0),
                (-1.0, 1.0),
            ] {
                vertices.push(Vertex3d {
                    position: corner(st, sb),
                    normal: n,
                });
            }
        }
        Self { vertices }
    }

    /// 一个三角形。最小冒烟场景:法线朝 +Z。
    pub fn triangle() -> Self {
        Self {
            vertices: vec![
                Vertex3d {
                    position: [-1.0, -1.0, 0.0],
                    normal: [0.0, 0.0, 1.0],
                },
                Vertex3d {
                    position: [1.0, -1.0, 0.0],
                    normal: [0.0, 0.0, 1.0],
                },
                Vertex3d {
                    position: [0.0, 1.0, 0.0],
                    normal: [0.0, 0.0, 1.0],
                },
            ],
        }
    }
}

/// 实例变换与材质基础色。
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Instance3d {
    pub model: [[f32; 4]; 4],
    pub color: [f32; 4],
}

impl Default for Instance3d {
    fn default() -> Self {
        Self {
            model: identity(),
            color: [0.22, 0.50, 0.94, 1.0],
        }
    }
}

impl Instance3d {
    /// 便捷构造:平移 + yaw/pitch 欧拉旋转 + 非均匀缩放,颜色取 `base_color`。
    pub fn trs(pos: [f32; 3], yaw: f32, pitch: f32, scale: [f32; 3], base_color: [f32; 4]) -> Self {
        Self {
            model: trs_matrix(pos, yaw, pitch, scale),
            color: base_color,
        }
    }
}

/// 平移 + Y/X 欧拉旋转(先 X 后 Y)+ 非均匀缩放 的模型矩阵(列主序)。
pub fn trs_matrix(pos: [f32; 3], yaw: f32, pitch: f32, scale: [f32; 3]) -> [[f32; 4]; 4] {
    let (sy, cy) = yaw.sin_cos();
    let (sp, cp) = pitch.sin_cos();
    // M = R_y·R_x,逐列 = M·e_i:
    // col0 = R_y·(1,0,0) = (cy, 0, -sy)
    // col1 = R_y·(0,cp,sp) = (sy·sp, cp, cy·sp)
    // col2 = R_y·(0,-sp,cp) = (sy·cp, -sp, cy·cp)
    let col0 = [cy, 0.0, -sy];
    let col1 = [sy * sp, cp, cy * sp];
    let col2 = [sy * cp, -sp, cy * cp];
    [
        [
            col0[0] * scale[0],
            col0[1] * scale[0],
            col0[2] * scale[0],
            0.0,
        ],
        [
            col1[0] * scale[1],
            col1[1] * scale[1],
            col1[2] * scale[1],
            0.0,
        ],
        [
            col2[0] * scale[2],
            col2[1] * scale[2],
            col2[2] * scale[2],
            0.0,
        ],
        [pos[0], pos[1], pos[2], 1.0],
    ]
}

/// 第一轮材质:Lambert 基础色,后续再引入金属度/粗糙度/纹理。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Material3d {
    pub base_color: [f32; 4],
}

impl Default for Material3d {
    fn default() -> Self {
        Self {
            base_color: [0.22, 0.50, 0.94, 1.0],
        }
    }
}

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct CameraUniform {
    view_proj: [[f32; 4]; 4],
    light_direction: [f32; 4],
    light_color: [f32; 4],
}

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct InstanceGpu {
    model: [[f32; 4]; 4],
    /// 模型矩阵逆转置的 3x3(法线矩阵),非均匀缩放下法线仍保持垂直于表面。
    /// 每列补齐到 16 字节,与 WGSL `mat3x3<f32>` 的 vec4 对齐存储一致。
    normal: [[f32; 4]; 3],
    color: [f32; 4],
}

/// 独立于 UI 的 3D GPU 渲染器。
pub struct Renderer3d {
    device: wgpu::Device,
    queue: wgpu::Queue,
    format: wgpu::TextureFormat,
    pipeline: wgpu::RenderPipeline,
    camera_buffer: wgpu::Buffer,
    camera_bind_group: wgpu::BindGroup,
    vertex_buffer: wgpu::Buffer,
    instance_buffer: wgpu::Buffer,
    depth_format: wgpu::TextureFormat,
    vertex_count: u32,
    instance_count: u32,
    /// None 保持原单网格实例化;Some 按对象绘制对应网格范围。
    scene_draws: Option<Vec<std::ops::Range<u32>>>,
    mesh_ranges: Vec<std::ops::Range<u32>>,
}

impl Renderer3d {
    pub async fn new(
        device: wgpu::Device,
        queue: wgpu::Queue,
        format: wgpu::TextureFormat,
        mesh: &Mesh3d,
        max_instances: usize,
    ) -> Self {
        let depth_format = wgpu::TextureFormat::Depth32Float;
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("arc-graphics3d.shader"),
            source: wgpu::ShaderSource::Wgsl(SHADER.into()),
        });
        let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("arc-graphics3d.camera"),
            size: std::mem::size_of::<CameraUniform>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let camera_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("arc-graphics3d.camera-layout"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: wgpu::BufferSize::new(
                        std::mem::size_of::<CameraUniform>() as u64
                    ),
                },
                count: None,
            }],
        });
        let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("arc-graphics3d.camera-bind-group"),
            layout: &camera_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: camera_buffer.as_entire_binding(),
            }],
        });
        let instance_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("arc-graphics3d.instance-layout"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: true },
                    has_dynamic_offset: false,
                    min_binding_size: wgpu::BufferSize::new(
                        std::mem::size_of::<InstanceGpu>() as u64
                    ),
                },
                count: None,
            }],
        });
        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("arc-graphics3d.pipeline-layout"),
            bind_group_layouts: &[Some(&camera_layout), Some(&instance_layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("arc-graphics3d.pipeline"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[Some(Vertex3d::layout())],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState {
                cull_mode: Some(wgpu::Face::Back),
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: depth_format,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: Default::default(),
                bias: Default::default(),
            }),
            multisample: Default::default(),
            multiview_mask: None,
            cache: None,
        });
        let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("arc-graphics3d.vertices"),
            contents: bytemuck::cast_slice(&mesh.vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });
        let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("arc-graphics3d.instances"),
            size: (max_instances.max(1) * std::mem::size_of::<InstanceGpu>()) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        Self {
            device,
            queue,
            format,
            pipeline,
            camera_buffer,
            camera_bind_group,
            vertex_buffer,
            instance_buffer,
            depth_format,
            vertex_count: mesh.vertices.len() as u32,
            instance_count: 0,
            scene_draws: None,
            mesh_ranges: Vec::new(),
        }
    }

    pub fn set_camera(&self, camera: Camera3d, light: DirectionalLight, aspect: f32) {
        let view = look_at(camera.eye, camera.target, camera.up);
        let projection = perspective(
            camera.fov_y_radians,
            aspect.max(0.001),
            camera.near,
            camera.far,
        );
        let uniform = CameraUniform {
            view_proj: mul4(projection, view),
            light_direction: [
                light.direction[0],
                light.direction[1],
                light.direction[2],
                0.0,
            ],
            light_color: [
                light.color[0],
                light.color[1],
                light.color[2],
                light.intensity,
            ],
        };
        self.queue
            .write_buffer(&self.camera_buffer, 0, bytemuck::bytes_of(&uniform));
    }

    /// 上传多网格几何及对象,保留一个共享顶点缓冲和实例缓冲。
    pub fn set_scene(&mut self, scene: &crate::Scene3d) -> Result<(), String> {
        scene.validate()?;
        let count: usize = scene.meshes.iter().map(|m| m.vertices.len()).sum();
        if count > u32::MAX as usize {
            return Err("场景顶点超出绘制范围".into());
        }
        let vertices: Vec<_> = scene
            .meshes
            .iter()
            .flat_map(|m| m.vertices.iter().copied())
            .collect();
        // 空场景也创建有效的非零缓冲,绘制次数为零。
        let fallback = [Vertex3d {
            position: [0.0; 3],
            normal: [0.0, 1.0, 0.0],
        }];
        self.vertex_buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("arc-graphics3d.scene-vertices"),
                contents: bytemuck::cast_slice(if vertices.is_empty() {
                    &fallback
                } else {
                    &vertices
                }),
                usage: wgpu::BufferUsages::VERTEX,
            });
        let mut offset = 0;
        self.mesh_ranges = scene
            .meshes
            .iter()
            .map(|mesh| {
                let start = offset;
                offset += mesh.vertices.len() as u32;
                start..offset
            })
            .collect();
        self.vertex_count = count as u32;
        self.update_scene_objects(&scene.objects)
    }

    /// 仅对象 TRS/颜色变化时复用几何资源,不重新上传网格。
    pub fn update_scene_objects(&mut self, objects: &[crate::Object3d]) -> Result<(), String> {
        if objects.iter().any(|o| !o.valid_instance()) {
            return Err("对象包含无效变换或颜色".into());
        }
        let draws: Option<Vec<_>> = objects
            .iter()
            .map(|o| self.mesh_ranges.get(o.mesh_index).cloned())
            .collect();
        let draws = draws.ok_or("对象引用了不存在的 GPU 网格")?;
        self.update_instances(&objects.iter().map(|o| o.instance).collect::<Vec<_>>());
        self.scene_draws = Some(draws);
        Ok(())
    }

    pub fn update_instances(&mut self, instances: &[Instance3d]) {
        self.scene_draws = None;
        let required = (instances.len().max(1) * std::mem::size_of::<InstanceGpu>()) as u64;
        if required > self.instance_buffer.size() {
            self.instance_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("arc-graphics3d.instances-grown"),
                size: required,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }
        let gpu: Vec<_> = instances
            .iter()
            .map(|instance| InstanceGpu {
                model: instance.model,
                normal: normal_matrix(instance.model),
                color: instance.color,
            })
            .collect();
        self.queue
            .write_buffer(&self.instance_buffer, 0, bytemuck::cast_slice(&gpu));
        self.instance_count = gpu.len() as u32;
    }

    pub fn create_offscreen_target(
        &self,
        width: u32,
        height: u32,
    ) -> (wgpu::Texture, wgpu::TextureView, wgpu::TextureView) {
        let color = self.device.create_texture(&wgpu::TextureDescriptor {
            label: Some("arc-graphics3d.color"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: self.format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let depth = self.device.create_texture(&wgpu::TextureDescriptor {
            label: Some("arc-graphics3d.depth"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: self.depth_format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let color_view = color.create_view(&Default::default());
        (color, color_view, depth.create_view(&Default::default()))
    }

    pub fn render(&self, color: &wgpu::TextureView, depth: &wgpu::TextureView, clear: wgpu::Color) {
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("arc-graphics3d.frame"),
            });
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("arc-graphics3d.pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: color,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(clear),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                view: depth,
                depth_ops: Some(wgpu::Operations {
                    load: wgpu::LoadOp::Clear(1.0),
                    store: wgpu::StoreOp::Store,
                }),
                stencil_ops: None,
            }),
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        if self.instance_count > 0 {
            pass.set_pipeline(&self.pipeline);
            pass.set_bind_group(0, &self.camera_bind_group, &[]);
            pass.set_bind_group(1, &self.instance_bind_group(), &[]);
            pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
            if let Some(draws) = &self.scene_draws {
                for (index, vertices) in draws.iter().enumerate() {
                    pass.draw(vertices.clone(), index as u32..index as u32 + 1);
                }
            } else {
                pass.draw(0..self.vertex_count, 0..self.instance_count);
            }
        }
        drop(pass);
        self.queue.submit(Some(encoder.finish()));
    }

    /// 供集成层(viewport)与测试访问设备/队列。
    pub fn device_queue(&self) -> (&wgpu::Device, &wgpu::Queue) {
        (&self.device, &self.queue)
    }

    fn instance_bind_group(&self) -> wgpu::BindGroup {
        let layout = self.pipeline.get_bind_group_layout(1);
        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("arc-graphics3d.instance-bind-group"),
            layout: &layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: self.instance_buffer.as_entire_binding(),
            }],
        })
    }
}

/// 读取离屏纹理为 RGBA8 字节(含 256 字节行距对齐填充),供像素级验收与 PNG 输出。
///
/// 返回 `(数据, 行距字节数)`。
pub fn capture_rgba(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    texture: &wgpu::Texture,
    width: u32,
    height: u32,
) -> (Vec<u8>, u32) {
    let bytes_per_row = width.div_ceil(64) * 256;
    let readback = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("arc-graphics3d.readback"),
        size: (bytes_per_row * height) as u64,
        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
        mapped_at_creation: false,
    });
    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
        label: Some("arc-graphics3d.readback-enc"),
    });
    encoder.copy_texture_to_buffer(
        texture.as_image_copy(),
        wgpu::TexelCopyBufferInfo {
            buffer: &readback,
            layout: wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(bytes_per_row),
                rows_per_image: None,
            },
        },
        wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
    );
    queue.submit(Some(encoder.finish()));
    let slice = readback.slice(..);
    slice.map_async(wgpu::MapMode::Read, |_| {});
    device
        .poll(wgpu::PollType::wait_indefinitely())
        .expect("读取回传失败");
    let mapped = slice.get_mapped_range().expect("映射回传缓冲失败");
    let data = mapped.to_vec();
    drop(mapped); // 必须先释放映射视图才能 unmap
    readback.unmap();
    (data, bytes_per_row)
}

const SHADER: &str = r#"
struct Camera { view_proj: mat4x4<f32>, light_direction: vec4<f32>, light_color: vec4<f32> };
@group(0) @binding(0) var<uniform> camera: Camera;
struct Instance { model: mat4x4<f32>, normal_matrix: mat3x3<f32>, color: vec4<f32> };
@group(1) @binding(0) var<storage, read> instances: array<Instance>;
struct In { @location(0) position: vec3<f32>, @location(1) normal: vec3<f32> };
struct Out { @builtin(position) position: vec4<f32>, @location(0) normal: vec3<f32>, @location(1) color: vec4<f32> };
@vertex fn vs_main(input: In, @builtin(instance_index) iid: u32) -> Out { let i = instances[iid]; let world = i.model * vec4<f32>(input.position, 1.0); var out: Out; out.position = camera.view_proj * world; out.normal = i.normal_matrix * input.normal; out.color = i.color; return out; }
@fragment fn fs_main(input: Out) -> @location(0) vec4<f32> { let light = normalize(-camera.light_direction.xyz); let diffuse = max(dot(normalize(input.normal), light), 0.0); let shade = 0.18 + diffuse * camera.light_color.w * 0.82; return vec4<f32>(input.color.rgb * shade, input.color.a); }
"#;

fn identity() -> [[f32; 4]; 4] {
    [
        [1.0, 0.0, 0.0, 0.0],
        [0.0, 1.0, 0.0, 0.0],
        [0.0, 0.0, 1.0, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ]
}

/// 模型矩阵上 3×3 的逆转置(法线矩阵)。返回列主序,每列补齐到 vec4
/// (第 4 分量为 0),与 WGSL `mat3x3<f32>` 的存储布局逐字节一致。
///
/// 非均匀缩放与旋转组合时,`model * normal` 会破坏法线与表面的垂直关系;
/// 逆转置矩阵(伴随矩阵除以行列式)在变换方向向量后保持该关系。
/// 奇异矩阵(行列式 ≈ 0)退化为单位阵,避免除零产生 NaN。
pub fn normal_matrix(model: [[f32; 4]; 4]) -> [[f32; 4]; 3] {
    // 列主序 m[c][r] → 行主序 a[r][c],套用标准伴随/行列式公式。
    let a = [
        [model[0][0], model[1][0], model[2][0]],
        [model[0][1], model[1][1], model[2][1]],
        [model[0][2], model[1][2], model[2][2]],
    ];
    let c00 = a[1][1] * a[2][2] - a[1][2] * a[2][1];
    let c01 = -(a[1][0] * a[2][2] - a[1][2] * a[2][0]);
    let c02 = a[1][0] * a[2][1] - a[1][1] * a[2][0];
    let c10 = -(a[0][1] * a[2][2] - a[0][2] * a[2][1]);
    let c11 = a[0][0] * a[2][2] - a[0][2] * a[2][0];
    let c12 = -(a[0][0] * a[2][1] - a[0][1] * a[2][0]);
    let c20 = a[0][1] * a[1][2] - a[0][2] * a[1][1];
    let c21 = -(a[0][0] * a[1][2] - a[0][2] * a[1][0]);
    let c22 = a[0][0] * a[1][1] - a[0][1] * a[1][0];
    let det = a[0][0] * c00 + a[0][1] * c01 + a[0][2] * c02;
    if !det.is_finite() || det.abs() < 1e-8 {
        return [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
        ];
    }
    // 逆转置(行主序)= 伴随矩阵(余子式矩阵)/ 行列式。
    let nit = [
        [c00 / det, c01 / det, c02 / det],
        [c10 / det, c11 / det, c12 / det],
        [c20 / det, c21 / det, c22 / det],
    ];
    // 行主序 nit[r][c] → 列主序 out[col][row],第 4 分量补 0。
    [
        [nit[0][0], nit[1][0], nit[2][0], 0.0],
        [nit[0][1], nit[1][1], nit[2][1], 0.0],
        [nit[0][2], nit[1][2], nit[2][2], 0.0],
    ]
}
/// 世界空间射线。方向为单位向量,距离单位与世界坐标一致。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Ray3d {
    pub origin: [f32; 3],
    pub direction: [f32; 3],
    pub min_distance: f32,
    pub max_distance: f32,
}

/// 最近的可见三角形命中;实例索引对应调用方传入切片,不充当持久对象 ID。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PickHit3d {
    pub instance_index: usize,
    pub triangle_index: usize,
    pub distance: f32,
    pub position: [f32; 3],
}

/// 世界空间轴对齐包围盒,用于取景而非精确拾取。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Bounds3d {
    pub min: [f32; 3],
    pub max: [f32; 3],
}

impl Bounds3d {
    /// 从同一网格的实例计算包围盒;忽略非有限或非仿射实例。
    pub fn from_instances(mesh: &Mesh3d, instances: &[Instance3d]) -> Option<Self> {
        let mut bounds: Option<Self> = None;
        for instance in instances.iter().filter(|i| valid_model(i.model)) {
            for vertex in &mesh.vertices {
                let point = world_point(instance.model, vertex.position);
                if !point.iter().all(|v| v.is_finite()) {
                    continue;
                }
                let b = bounds.get_or_insert(Self {
                    min: point,
                    max: point,
                });
                for (axis, value) in point.into_iter().enumerate() {
                    b.min[axis] = b.min[axis].min(value);
                    b.max[axis] = b.max[axis].max(value);
                }
            }
        }
        bounds
    }

    pub fn center(self) -> [f32; 3] {
        std::array::from_fn(|i| self.min[i] * 0.5 + self.max[i] * 0.5)
    }
}

impl Camera3d {
    /// 画布局部坐标 → 相机射线。viewport 与 position 使用相同单位(逻辑像素即可),
    /// 左上角为原点;射线裁剪范围与渲染使用的相机 near/far 平面一致。
    pub fn screen_ray(self, position: [f32; 2], viewport: [f32; 2]) -> Option<Ray3d> {
        let [width, height] = viewport;
        if !width.is_finite()
            || !height.is_finite()
            || width <= 0.0
            || height <= 0.0
            || !position.iter().all(|v| v.is_finite())
            || position[0] < 0.0
            || position[1] < 0.0
            || position[0] > width
            || position[1] > height
            || !self.valid_projection()
        {
            return None;
        }
        let forward = unit(sub(self.target, self.eye))?;
        let right = unit(cross(forward, self.up))?;
        let up = cross(right, forward);
        let tan = (self.fov_y_radians * 0.5).tan();
        let x = (2.0 * position[0] / width - 1.0) * tan * width / height;
        let y = (1.0 - 2.0 * position[1] / height) * tan;
        let direction = unit(std::array::from_fn(|i| {
            forward[i] + right[i] * x + up[i] * y
        }))?;
        let cosine = dot(direction, forward);
        Some(Ray3d {
            origin: self.eye,
            direction,
            min_distance: self.near / cosine,
            max_distance: self.far / cosine,
        })
    }

    /// 保留观察方向,按包围球适配宽高比并留出 10% 余量;同时调整裁剪平面。
    pub fn frame_bounds(self, bounds: Bounds3d, aspect: f32) -> Option<Self> {
        if !self.valid_projection()
            || !aspect.is_finite()
            || aspect <= 0.0
            || !(0..3).all(|i| {
                bounds.min[i].is_finite()
                    && bounds.max[i].is_finite()
                    && bounds.min[i] <= bounds.max[i]
            })
        {
            return None;
        }
        let direction = unit(sub(self.eye, self.target))?;
        unit(cross(direction, self.up))?;
        let center = bounds.center();
        let half = sub(bounds.max, center);
        let radius = dot(half, half).sqrt().max(0.01);
        let half_fov =
            (self.fov_y_radians * 0.5).min(((self.fov_y_radians * 0.5).tan() * aspect).atan());
        let distance = radius * 1.1 / half_fov.sin();
        let camera = Self {
            eye: std::array::from_fn(|i| center[i] + direction[i] * distance),
            target: center,
            near: (distance - radius * 1.2).max(0.001),
            far: distance + radius * 1.2,
            ..self
        };
        camera.valid_projection().then_some(camera)
    }

    fn valid_projection(self) -> bool {
        self.eye
            .into_iter()
            .chain(self.target)
            .chain(self.up)
            .all(f32::is_finite)
            && self.fov_y_radians.is_finite()
            && self.fov_y_radians > 0.0
            && self.fov_y_radians < std::f32::consts::PI
            && self.near.is_finite()
            && self.far.is_finite()
            && self.near > 0.0
            && self.far > self.near
    }
}

/// 精确拾取同一网格的实例:世界空间 Möller–Trumbore 求交,最近命中优先。
/// 与当前渲染管线一致:CCW 正面、背面剔除、near/far 裁剪;支持旋转、
/// 非均匀/负缩放。不依赖 GPU 或 UI;当前为线性扫描,未引入 BVH。
pub fn pick_mesh(mesh: &Mesh3d, instances: &[Instance3d], ray: Ray3d) -> Option<PickHit3d> {
    if !ray
        .origin
        .into_iter()
        .chain(ray.direction)
        .all(f32::is_finite)
        || (dot(ray.direction, ray.direction) - 1.0).abs() > 1e-4
        || !ray.min_distance.is_finite()
        || !ray.max_distance.is_finite()
        || ray.min_distance < 0.0
        || ray.max_distance < ray.min_distance
    {
        return None;
    }
    let mut closest: Option<PickHit3d> = None;
    for (instance_index, instance) in instances.iter().enumerate() {
        if !valid_model(instance.model) {
            continue;
        }
        for (triangle_index, vertices) in mesh.vertices.chunks_exact(3).enumerate() {
            let a = world_point(instance.model, vertices[0].position);
            let b = world_point(instance.model, vertices[1].position);
            let c = world_point(instance.model, vertices[2].position);
            let e1 = sub(b, a);
            let e2 = sub(c, a);
            let p = cross(ray.direction, e2);
            let determinant = dot(e1, p);
            // 相对面积的容差避免非均匀小尺度物体被固定 epsilon 吞掉。
            let area = dot(e1, e1).sqrt() * dot(e2, e2).sqrt();
            if !determinant.is_finite() || determinant <= area * 1e-7 {
                continue;
            }
            let t = sub(ray.origin, a);
            let u = dot(t, p) / determinant;
            if !(0.0..=1.0).contains(&u) {
                continue;
            }
            let q = cross(t, e1);
            let v = dot(ray.direction, q) / determinant;
            if v < 0.0 || u + v > 1.0 {
                continue;
            }
            let distance = dot(e2, q) / determinant;
            if !distance.is_finite()
                || distance < ray.min_distance
                || distance > ray.max_distance
                || closest.is_some_and(|h| distance >= h.distance)
            {
                continue;
            }
            closest = Some(PickHit3d {
                instance_index,
                triangle_index,
                distance,
                position: std::array::from_fn(|i| ray.origin[i] + ray.direction[i] * distance),
            });
        }
    }
    closest
}

fn valid_model(model: [[f32; 4]; 4]) -> bool {
    model.iter().flatten().all(|v| v.is_finite())
        && model[0][3] == 0.0
        && model[1][3] == 0.0
        && model[2][3] == 0.0
        && model[3][3] == 1.0
}

fn world_point(model: [[f32; 4]; 4], point: [f32; 3]) -> [f32; 3] {
    std::array::from_fn(|r| {
        model[0][r] * point[0] + model[1][r] * point[1] + model[2][r] * point[2] + model[3][r]
    })
}

fn unit(vector: [f32; 3]) -> Option<[f32; 3]> {
    let length = dot(vector, vector).sqrt();
    (length.is_finite() && length > 1e-8).then(|| vector.map(|v| v / length))
}

fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
    [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]
}
fn norm(a: [f32; 3]) -> [f32; 3] {
    let n = dot(a, a).sqrt().max(1e-6);
    [a[0] / n, a[1] / n, a[2] / n]
}
fn look_at(eye: [f32; 3], target: [f32; 3], up: [f32; 3]) -> [[f32; 4]; 4] {
    let f = norm(sub(target, eye));
    let s = norm(cross(f, up));
    let u = cross(s, f);
    [
        [s[0], u[0], -f[0], 0.0],
        [s[1], u[1], -f[1], 0.0],
        [s[2], u[2], -f[2], 0.0],
        [-dot(s, eye), -dot(u, eye), dot(f, eye), 1.0],
    ]
}
fn perspective(fovy: f32, aspect: f32, near: f32, far: f32) -> [[f32; 4]; 4] {
    let f = 1.0 / (fovy * 0.5).tan();
    [
        [f / aspect, 0.0, 0.0, 0.0],
        [0.0, f, 0.0, 0.0],
        [0.0, 0.0, far / (near - far), -1.0],
        [0.0, 0.0, (near * far) / (near - far), 0.0],
    ]
}
/// 列主序矩阵乘法:`mul4(a, b)` 表示数学上的 `A·B`(先应用 B,再应用 A)。
/// `out[c][r] = Σ_k a[k][r] * b[c][k]`,与 WGSL 列主序 `mat4x4` 存储一致。
fn mul4(a: [[f32; 4]; 4], b: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
    let mut out = [[0.0; 4]; 4];
    for c in 0..4 {
        for r in 0..4 {
            out[c][r] = (0..4).map(|k| a[k][r] * b[c][k]).sum();
        }
    }
    out
}