use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
#[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 {
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()
}
}
}
#[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,
}
}
}
#[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,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Mesh3d {
pub vertices: Vec<Vertex3d>,
}
impl Mesh3d {
pub fn cube() -> Self {
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 }
}
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 {
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,
}
}
}
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();
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],
]
}
#[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],
normal: [[f32; 4]; 3],
color: [f32; 4],
}
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,
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)
}
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()));
}
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(),
}],
})
}
}
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); 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],
]
}
pub fn normal_matrix(model: [[f32; 4]; 4]) -> [[f32; 4]; 3] {
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[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,
}
#[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 {
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,
})
}
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
}
}
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);
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],
]
}
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
}