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];
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],
]
}
#[test]
fn normal_matrix_survives_rotation_plus_nonuniform_scale() {
let transform = |m: [[f32; 4]; 3], v: [f32; 3]| -> [f32; 3] {
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]
};
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:?}"
);
}
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()
);
}
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);
}
}
}
}
#[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);
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);
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,
));
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,
);
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("三帧捕获");
let corner = px(&frame_a, 4, 4);
assert_eq!(
corner, clear,
"角落应为 sRGB 编码后的清空色,实际 {corner:?}"
);
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, "右半屏应出现珊瑚色实例");
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}"
);
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}"
);
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);
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());
}
}
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
}
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);
}
#[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();
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:?}");
}