use arc_graphics3d::{
Camera3d, DirectionalLight, Instance3d, Mesh3d, Renderer3d, normal_matrix, 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());
}
}