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
//! 三角形 BVH:局部空间一次构建、多次查询。
//!
//! 设计参照 Blender `BLI_kdopbvh` / Cycles 的两级 BVH 思路:
//! 树按**网格局部空间**构建,实例变换不重建树;查询时把世界射线用模型逆矩阵
//! 变换到局部空间。仿射变换保持射线参数 `t` 不变
//! (`O_w + t·D_w = M·(O_l + t·D_l)`),因此命中距离可以直接与世界空间比较。
//!
//! 镜像变换(行列式为负)会让三角形绕序翻转,查询方据符号翻转面朝向测试。
//! 树结构只依赖三角形的空间分布,变形网格可用 [`Bvh3d::refit`] 只更新包围盒。

use crate::{Bounds3d, Vertex3d};

/// 叶节点目标三角形数:过大则粗筛失效,过小则遍历开销上升。
const LEAF_SIZE: u32 = 4;
/// SAH 分箱数量。
const BINS: usize = 12;
/// 遍历栈深度上限,超出按最近子节点丢弃(保守,只影响速度不影响正确性)。
const STACK_DEPTH: usize = 64;

#[derive(Clone, Copy, Debug, PartialEq)]
struct Node {
    min: [f32; 3],
    max: [f32; 3],
    /// 叶子:首个三角形序号;内部节点:右子节点下标(左子节点恒为 `index + 1`)。
    first: u32,
    /// 叶子为三角形数量,内部节点为 0。
    count: u32,
}

/// 一次 BVH 命中。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BvhHit3d {
    /// 三角形序号(`indices.chunks_exact(3)` 的下标)。
    pub triangle: u32,
    /// 射线参数,与世界空间距离一致。
    pub t: f32,
}

/// 三角形包围体层级。
#[derive(Clone, Debug)]
pub struct Bvh3d {
    nodes: Vec<Node>,
    /// 按叶节点顺序重排的三角形序号,构建后不再变动。
    order: Vec<u32>,
    triangles: u32,
    depth: u32,
    bounds: Option<Bounds3d>,
}

impl PartialEq for Bvh3d {
    /// 结构由三角形数据唯一决定,比较节点与顺序即可。
    fn eq(&self, other: &Self) -> bool {
        self.nodes == other.nodes && self.order == other.order
    }
}

impl Bvh3d {
    /// 按三角形重心分箱 SAH 构建;退化输入(空网格、重复点)回退到中位数切分。
    pub fn build(vertices: &[Vertex3d], indices: &[u32]) -> Self {
        let count = (indices.len() / 3) as u32;
        let mut order: Vec<u32> = (0..count).collect();
        let mut nodes = Vec::with_capacity(count as usize * 2);
        let mut depth = 0;
        let bounds = if count == 0 {
            None
        } else {
            let centroids: Vec<[f32; 3]> = (0..count as usize)
                .map(|i| centroid(vertices, indices, i))
                .collect();
            build_node(
                vertices,
                indices,
                &centroids,
                &mut order,
                0..count,
                &mut nodes,
                0,
                &mut depth,
            );
            total_bounds(&nodes)
        };
        Self {
            nodes,
            order,
            triangles: count,
            depth,
            bounds,
        }
    }

    /// 变形网格:拓扑不变,只按新顶点位置重算各层包围盒。
    ///
    /// 与重建相比省掉重心计算、分箱与排序;Blender 的 refit 同理,
    /// 坐标偏离原分布越远树质量越差,此时应改用 [`Self::build`]。
    /// 三角形数量不一致时返回 `false`,由调用方决定是否重建。
    pub fn refit(&mut self, vertices: &[Vertex3d], indices: &[u32]) -> bool {
        if indices.len() / 3 != self.triangles as usize || self.nodes.is_empty() {
            return false;
        }
        // 自底向上:节点前序排列,子节点下标恒大于父节点,倒序遍历即后序。
        let mut bounds = vec![[0.0f32; 6]; self.nodes.len()];
        for index in (0..self.nodes.len()).rev() {
            let node = self.nodes[index];
            if node.count > 0 {
                let start = node.first as usize;
                let end = start + node.count as usize;
                let mut min = [f32::INFINITY; 3];
                let mut max = [f32::NEG_INFINITY; 3];
                for &triangle in &self.order[start..end] {
                    for corner in triangle_positions(vertices, indices, triangle as usize) {
                        for axis in 0..3 {
                            min[axis] = min[axis].min(corner[axis]);
                            max[axis] = max[axis].max(corner[axis]);
                        }
                    }
                }
                if !min[0].is_finite() {
                    min = node.min;
                    max = node.max;
                }
                bounds[index] = [min[0], min[1], min[2], max[0], max[1], max[2]];
            } else {
                let left = bounds[index + 1];
                let right = bounds[node.first as usize];
                bounds[index] = [
                    left[0].min(right[0]),
                    left[1].min(right[1]),
                    left[2].min(right[2]),
                    left[3].max(right[3]),
                    left[4].max(right[4]),
                    left[5].max(right[5]),
                ];
            }
        }
        for (node, boxed) in self.nodes.iter_mut().zip(bounds) {
            node.min = [boxed[0], boxed[1], boxed[2]];
            node.max = [boxed[3], boxed[4], boxed[5]];
        }
        self.bounds = total_bounds(&self.nodes);
        true
    }

    pub fn triangle_count(&self) -> u32 {
        self.triangles
    }

    /// 树深度,用于验证建树没有退化成链表。
    pub fn depth(&self) -> u32 {
        self.depth
    }

    pub fn bounds(&self) -> Option<Bounds3d> {
        self.bounds
    }

    /// 射线求交,返回最近命中。`sign` 为模型矩阵行列式符号(镜像时为 -1)。
    #[allow(clippy::too_many_arguments)]
    pub fn ray_cast(
        &self,
        vertices: &[Vertex3d],
        indices: &[u32],
        origin: [f32; 3],
        direction: [f32; 3],
        t_min: f32,
        t_max: f32,
        sign: f32,
    ) -> Option<BvhHit3d> {
        self.ray_cast_counted(vertices, indices, origin, direction, t_min, t_max, sign)
            .0
    }

    /// 与 [`Self::ray_cast`] 相同,额外返回实际执行的三角形精确测试次数。
    /// 供测试验证粗筛确实生效,不参与生产路径。
    #[allow(clippy::too_many_arguments)]
    pub fn ray_cast_counted(
        &self,
        vertices: &[Vertex3d],
        indices: &[u32],
        origin: [f32; 3],
        direction: [f32; 3],
        t_min: f32,
        t_max: f32,
        sign: f32,
    ) -> (Option<BvhHit3d>, u32) {
        let Some(root) = self.nodes.first() else {
            return (None, 0);
        };
        let mut best: Option<BvhHit3d> = None;
        let mut limit = t_max;
        let mut tested = 0u32;
        let mut stack = [(0u32, 0.0f32); STACK_DEPTH];
        let mut top = 0usize;
        if slab(root, origin, direction, t_min, limit).is_some() {
            stack[0] = (0, 0.0);
            top = 1;
        }
        while top > 0 {
            top -= 1;
            let (index, _) = stack[top];
            let node = &self.nodes[index as usize];
            if node.count == 0 {
                let left = index + 1;
                let right = node.first;
                // 先压远节点,弹出时先处理近的一侧。
                for child in [left, right] {
                    let Some(child_node) = self.nodes.get(child as usize) else {
                        continue;
                    };
                    if slab(child_node, origin, direction, t_min, limit).is_some()
                        && top < STACK_DEPTH
                    {
                        stack[top] = (child, 0.0);
                        top += 1;
                    }
                }
                continue;
            }
            let start = node.first as usize;
            let end = start + node.count as usize;
            for &triangle in &self.order[start..end] {
                let [a, b, c] = triangle_positions(vertices, indices, triangle as usize);
                tested += 1;
                if let Some(t) = intersect_triangle(a, b, c, origin, direction, t_min, limit, sign)
                    && t < limit
                {
                    limit = t;
                    best = Some(BvhHit3d { triangle, t });
                }
            }
        }
        (best, tested)
    }
}

#[allow(clippy::too_many_arguments)]
fn build_node(
    vertices: &[Vertex3d],
    indices: &[u32],
    centroids: &[[f32; 3]],
    order: &mut [u32],
    range: std::ops::Range<u32>,
    nodes: &mut Vec<Node>,
    level: u32,
    depth: &mut u32,
) -> u32 {
    let index = nodes.len() as u32;
    *depth = (*depth).max(level);
    // 先占位,递归结束后回填,保证子节点连续(左 = index + 1)。
    nodes.push(Node {
        min: [0.0; 3],
        max: [0.0; 3],
        first: 0,
        count: 0,
    });
    let bounds = triangle_bounds_range(
        vertices,
        indices,
        &order[range.start as usize..range.end as usize],
    );
    let size = range.end - range.start;
    debug_assert!(size > 0);
    nodes[index as usize] = Node {
        min: bounds.min,
        max: bounds.max,
        first: range.start,
        count: size,
    };
    if size <= LEAF_SIZE {
        return index;
    }
    let Some((split_axis, split_pos)) =
        best_split(vertices, indices, centroids, order, range.clone())
    else {
        return index; // 所有重心重合:退化叶节点
    };
    let slice = &mut order[range.start as usize..range.end as usize];
    let mid = slice
        .iter()
        .position(|&t| centroids[t as usize][split_axis] >= split_pos)
        .unwrap_or(slice.len());
    let mid = if mid == 0 || mid == slice.len() {
        slice.len() / 2
    } else {
        mid
    };
    let (left, right) = slice.split_at_mut(mid);
    left.sort_unstable_by(|a, b| {
        centroids[*a as usize][split_axis].total_cmp(&centroids[*b as usize][split_axis])
    });
    right.sort_unstable_by(|a, b| {
        centroids[*a as usize][split_axis].total_cmp(&centroids[*b as usize][split_axis])
    });
    let left_count = mid as u32;
    build_node(
        vertices,
        indices,
        centroids,
        order,
        range.start..range.start + left_count,
        nodes,
        level + 1,
        depth,
    );
    let right_index = build_node(
        vertices,
        indices,
        centroids,
        order,
        range.start + left_count..range.end,
        nodes,
        level + 1,
        depth,
    );
    nodes[index as usize] = Node {
        min: bounds.min,
        max: bounds.max,
        first: right_index,
        count: 0,
    };
    index
}

/// 分箱 SAH:沿重心跨度最大的轴分 12 箱,取表面积代价最小者。
fn best_split(
    vertices: &[Vertex3d],
    indices: &[u32],
    centroids: &[[f32; 3]],
    order: &[u32],
    range: std::ops::Range<u32>,
) -> Option<(usize, f32)> {
    let slice = &order[range.start as usize..range.end as usize];
    let mut cmin = [f32::INFINITY; 3];
    let mut cmax = [f32::NEG_INFINITY; 3];
    for &t in slice {
        let c = centroids[t as usize];
        for axis in 0..3 {
            cmin[axis] = cmin[axis].min(c[axis]);
            cmax[axis] = cmax[axis].max(c[axis]);
        }
    }
    let extent = [cmax[0] - cmin[0], cmax[1] - cmin[1], cmax[2] - cmin[2]];
    let axis = (0..3).max_by(|a, b| extent[*a].total_cmp(&extent[*b]))?;
    if !extent[axis].is_finite() || extent[axis] <= 0.0 {
        return None;
    }
    let scale = BINS as f32 / extent[axis];
    let mut bin_count = [0u32; BINS];
    let mut bin_bounds = [[[0.0f32; 3]; 2]; BINS];
    for bin in bin_bounds.iter_mut() {
        bin[0] = [f32::INFINITY; 3];
        bin[1] = [f32::NEG_INFINITY; 3];
    }
    for &t in slice {
        let bin = (((centroids[t as usize][axis] - cmin[axis]) * scale) as usize).min(BINS - 1);
        bin_count[bin] += 1;
        for position in triangle_positions(vertices, indices, t as usize) {
            for (axis_index, value) in position.iter().enumerate() {
                bin_bounds[bin][0][axis_index] = bin_bounds[bin][0][axis_index].min(*value);
                bin_bounds[bin][1][axis_index] = bin_bounds[bin][1][axis_index].max(*value);
            }
        }
    }
    // 前缀/后缀面积,代价 = 两侧面积加权和的 SAH 近似。
    let mut left_area = [0.0f32; BINS];
    let mut left_count = [0u32; BINS];
    let mut acc_min = [f32::INFINITY; 3];
    let mut acc_max = [f32::NEG_INFINITY; 3];
    let mut count = 0u32;
    for bin in 0..BINS {
        for axis_index in 0..3 {
            acc_min[axis_index] = acc_min[axis_index].min(bin_bounds[bin][0][axis_index]);
            acc_max[axis_index] = acc_max[axis_index].max(bin_bounds[bin][1][axis_index]);
        }
        count += bin_count[bin];
        left_count[bin] = count;
        left_area[bin] = area(acc_min, acc_max);
    }
    let mut right_area = [0.0f32; BINS];
    let mut right_count = [0u32; BINS];
    acc_min = [f32::INFINITY; 3];
    acc_max = [f32::NEG_INFINITY; 3];
    count = 0;
    for bin in (0..BINS).rev() {
        for axis_index in 0..3 {
            acc_min[axis_index] = acc_min[axis_index].min(bin_bounds[bin][0][axis_index]);
            acc_max[axis_index] = acc_max[axis_index].max(bin_bounds[bin][1][axis_index]);
        }
        count += bin_count[bin];
        right_count[bin] = count;
        right_area[bin] = area(acc_min, acc_max);
    }
    let mut best: Option<(usize, f32)> = None;
    for bin in 0..BINS - 1 {
        if left_count[bin] == 0 || right_count[bin + 1] == 0 {
            continue;
        }
        let cost = left_area[bin] * left_count[bin] as f32
            + right_area[bin + 1] * right_count[bin + 1] as f32;
        if best.is_none_or(|(_, best_cost)| cost < best_cost) {
            best = Some((bin, cost));
        }
    }
    let (bin, _) = best?;
    Some((
        axis,
        cmin[axis] + extent[axis] * (bin + 1) as f32 / BINS as f32,
    ))
}

/// 取第 `triangle` 个三角形的三个顶点位置;索引越界时返回零向量。
fn triangle_positions(vertices: &[Vertex3d], indices: &[u32], triangle: usize) -> [[f32; 3]; 3] {
    let mut out = [[0.0f32; 3]; 3];
    for (slot, corner) in out.iter_mut().enumerate() {
        let Some(&vertex_index) = indices.get(triangle * 3 + slot) else {
            continue;
        };
        if let Some(vertex) = vertices.get(vertex_index as usize) {
            *corner = vertex.position;
        }
    }
    out
}

fn centroid(vertices: &[Vertex3d], indices: &[u32], triangle: usize) -> [f32; 3] {
    let [a, b, c] = triangle_positions(vertices, indices, triangle);
    std::array::from_fn(|axis| (a[axis] + b[axis] + c[axis]) / 3.0)
}

fn area(min: [f32; 3], max: [f32; 3]) -> f32 {
    if !min[0].is_finite() || !max[0].is_finite() || min[0] > max[0] {
        return 0.0;
    }
    let d = [max[0] - min[0], max[1] - min[1], max[2] - min[2]];
    2.0 * (d[0] * d[1] + d[1] * d[2] + d[2] * d[0])
}

fn triangle_bounds_range(vertices: &[Vertex3d], indices: &[u32], order: &[u32]) -> Bounds3d {
    let mut min = [f32::INFINITY; 3];
    let mut max = [f32::NEG_INFINITY; 3];
    for &triangle in order {
        for position in triangle_positions(vertices, indices, triangle as usize) {
            for axis in 0..3 {
                min[axis] = min[axis].min(position[axis]);
                max[axis] = max[axis].max(position[axis]);
            }
        }
    }
    if min[0] > max[0] {
        return Bounds3d {
            min: [0.0; 3],
            max: [0.0; 3],
        };
    }
    Bounds3d { min, max }
}

fn total_bounds(nodes: &[Node]) -> Option<Bounds3d> {
    let root = nodes.first()?;
    Some(Bounds3d {
        min: root.min,
        max: root.max,
    })
}

/// 射线与 AABB 的 slab 测试。
fn slab(node: &Node, origin: [f32; 3], direction: [f32; 3], t_min: f32, t_max: f32) -> Option<f32> {
    let mut near = t_min;
    let mut far = t_max;
    for axis in 0..3 {
        let d = direction[axis];
        let o = origin[axis];
        if d.abs() < 1e-12 {
            if o < node.min[axis] || o > node.max[axis] {
                return None;
            }
            continue;
        }
        let inv = 1.0 / d;
        let mut t0 = (node.min[axis] - o) * inv;
        let mut t1 = (node.max[axis] - o) * inv;
        if t0 > t1 {
            std::mem::swap(&mut t0, &mut t1);
        }
        near = near.max(t0);
        far = far.min(t1);
        if near > far {
            return None;
        }
    }
    Some(near)
}

/// Möller–Trumbore,语义与逐三角形扫描一致;`sign` 处理镜像变换的面朝向。
#[allow(clippy::too_many_arguments)]
fn intersect_triangle(
    a: [f32; 3],
    b: [f32; 3],
    c: [f32; 3],
    origin: [f32; 3],
    direction: [f32; 3],
    t_min: f32,
    t_max: f32,
    sign: f32,
) -> Option<f32> {
    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 = [
        direction[1] * e2[2] - direction[2] * e2[1],
        direction[2] * e2[0] - direction[0] * e2[2],
        direction[0] * e2[1] - direction[1] * e2[0],
    ];
    let determinant = e1[0] * p[0] + e1[1] * p[1] + e1[2] * p[2];
    let edge_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();
    // 相对面积容差:非均匀小尺度物体不会被固定 epsilon 吞掉。
    if !determinant.is_finite() || determinant * sign <= edge_area * 1e-7 {
        return None;
    }
    let t = [origin[0] - a[0], origin[1] - a[1], 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) {
        return None;
    }
    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 = (direction[0] * q[0] + direction[1] * q[1] + direction[2] * q[2]) / determinant;
    if v < 0.0 || u + v > 1.0 {
        return None;
    }
    let distance = (e2[0] * q[0] + e2[1] * q[1] + e2[2] * q[2]) / determinant;
    (distance.is_finite() && distance >= t_min && distance <= t_max).then_some(distance)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn triangle(offset: [f32; 3]) -> Vec<Vertex3d> {
        vec![
            Vertex3d {
                position: [offset[0] - 0.5, offset[1] - 0.5, offset[2]],
                normal: [0.0, 0.0, 1.0],
            },
            Vertex3d {
                position: [offset[0] + 0.5, offset[1] - 0.5, offset[2]],
                normal: [0.0, 0.0, 1.0],
            },
            Vertex3d {
                position: [offset[0], offset[1] + 0.5, offset[2]],
                normal: [0.0, 0.0, 1.0],
            },
        ]
    }

    fn identity(count: usize) -> Vec<u32> {
        (0..count as u32).collect()
    }

    fn brute(
        vertices: &[Vertex3d],
        indices: &[u32],
        origin: [f32; 3],
        direction: [f32; 3],
        sign: f32,
    ) -> Option<BvhHit3d> {
        let mut best: Option<BvhHit3d> = None;
        for index in 0..indices.len() / 3 {
            let [a, b, c] = triangle_positions(vertices, indices, index);
            if let Some(t) = intersect_triangle(a, b, c, origin, direction, 0.0, 1000.0, sign)
                && best.is_none_or(|b| t < b.t)
            {
                best = Some(BvhHit3d {
                    triangle: index as u32,
                    t,
                });
            }
        }
        best
    }

    #[test]
    fn empty_mesh_has_no_hit() {
        let bvh = Bvh3d::build(&[], &[]);
        assert_eq!(bvh.triangle_count(), 0);
        assert!(bvh.bounds().is_none());
        assert!(
            bvh.ray_cast(&[], &[], [0.0, 0.0, 5.0], [0.0, 0.0, -1.0], 0.0, 100.0, 1.0)
                .is_none()
        );
    }

    #[test]
    fn grid_matches_brute_force_and_prunes() {
        // 40×40 互不重叠的小三角形;射线只应精确测试极少数。
        let mut vertices = Vec::new();
        let mut indices = Vec::new();
        for y in 0..40 {
            for x in 0..40 {
                let z = (x % 3) as f32 * 0.5;
                let base = vertices.len() as u32;
                vertices.extend([
                    Vertex3d {
                        position: [x as f32 - 0.2, y as f32 - 0.2, z],
                        normal: [0.0, 0.0, 1.0],
                    },
                    Vertex3d {
                        position: [x as f32 + 0.2, y as f32 - 0.2, z],
                        normal: [0.0, 0.0, 1.0],
                    },
                    Vertex3d {
                        position: [x as f32, y as f32 + 0.2, z],
                        normal: [0.0, 0.0, 1.0],
                    },
                ]);
                indices.extend([base, base + 1, base + 2]);
            }
        }
        let bvh = Bvh3d::build(&vertices, &indices);
        assert_eq!(bvh.triangle_count(), 1600);
        assert!(bvh.depth() <= 24, "退化树深度 {}", bvh.depth());
        let origin = [23.05, 12.03, 5.0];
        let direction = [0.0, 0.0, -1.0];
        let (hit, tested) =
            bvh.ray_cast_counted(&vertices, &indices, origin, direction, 0.0, 100.0, 1.0);
        let expect = brute(&vertices, &indices, origin, direction, 1.0);
        assert_eq!(hit.map(|h| h.triangle), expect.map(|h| h.triangle));
        assert!(tested <= 32, "粗筛未生效:精确测试 {tested} 个三角形");
    }

    #[test]
    fn direction_away_from_scene_misses_fast() {
        let mut vertices = Vec::new();
        let mut indices = Vec::new();
        for i in 0..500 {
            let base = vertices.len() as u32;
            vertices.extend(triangle([i as f32, 0.0, 0.0]));
            indices.extend([base, base + 1, base + 2]);
        }
        let bvh = Bvh3d::build(&vertices, &indices);
        let (hit, tested) = bvh.ray_cast_counted(
            &vertices,
            &indices,
            [0.0, 0.0, 5.0],
            [0.0, 0.0, 1.0],
            0.0,
            100.0,
            1.0,
        );
        assert!(hit.is_none());
        assert_eq!(tested, 0, "整棵树应被根节点粗筛拒绝");
    }

    #[test]
    fn mirrored_winding_rejects_back_faces() {
        let vertices = triangle([0.0, 0.0, 0.0]);
        let indices = identity(3);
        let bvh = Bvh3d::build(&vertices, &indices);
        let origin = [0.0, 0.0, 5.0];
        let direction = [0.0, 0.0, -1.0];
        assert!(
            bvh.ray_cast(&vertices, &indices, origin, direction, 0.0, 100.0, 1.0)
                .is_some()
        );
        assert!(
            bvh.ray_cast(&vertices, &indices, origin, direction, 0.0, 100.0, -1.0)
                .is_none()
        );
    }

    #[test]
    fn refit_tracks_deformation_without_rebuilding() {
        let mut vertices = Vec::new();
        let mut indices = Vec::new();
        for i in 0..64 {
            let base = vertices.len() as u32;
            vertices.extend(triangle([i as f32, 0.0, 0.0]));
            indices.extend([base, base + 1, base + 2]);
        }
        let mut bvh = Bvh3d::build(&vertices, &indices);
        let depth = bvh.depth();
        let order = bvh.order.clone();
        assert!(bvh.bounds().unwrap().max[2] < 0.001);

        // 整片几何抬起 5 个单位:refit 后包围盒与查询都要跟上。
        for vertex in &mut vertices {
            vertex.position[2] += 5.0;
        }
        assert!(bvh.refit(&vertices, &indices));
        assert_eq!(bvh.depth(), depth, "refit 不应改变拓扑");
        assert_eq!(bvh.order, order);
        assert!((bvh.bounds().unwrap().min[2] - 5.0).abs() < 1e-5);

        let origin = [31.05, 0.03, 15.0];
        let direction = [0.0, 0.0, -1.0];
        let hit = bvh
            .ray_cast(&vertices, &indices, origin, direction, 0.0, 100.0, 1.0)
            .expect("变形后仍应命中");
        let expect = brute(&vertices, &indices, origin, direction, 1.0).unwrap();
        assert!((hit.t - expect.t).abs() < 1e-4);
    }

    #[test]
    fn refit_rejects_changed_topology() {
        let vertices = triangle([0.0, 0.0, 0.0]);
        let mut bvh = Bvh3d::build(&vertices, &identity(3));
        assert!(!bvh.refit(&vertices, &[0, 1, 2, 0, 1, 2]));
    }
}