feat: bound scene visibility rendering and continuous native input

This commit is contained in:
2026-11-11 00:53:21 +08:00
parent 15fc01542c
commit 32d5da5528
15 changed files with 900 additions and 134 deletions
+124 -29
View File
@@ -2,6 +2,7 @@
//! visibility and picking use the same camera and transformed world triangles.
pub mod math;
pub mod panel;
pub mod spatial;
use math::{Camera, Matrix, Projection, Vec3};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
@@ -90,12 +91,22 @@ pub struct Light {
pub color: [f32; 3],
pub intensity: f32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Scene {
pub meshes: Vec<Mesh>,
pub lights: Vec<Light>,
pub ambient: f32,
pub background: [f32; 3],
#[serde(skip)]
pub acceleration: Arc<spatial::Index>,
}
impl PartialEq for Scene {
fn eq(&self, other: &Self) -> bool {
self.meshes == other.meshes
&& self.lights == other.lights
&& self.ambient == other.ambient
&& self.background == other.background
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct View {
@@ -154,6 +165,20 @@ impl View {
&& color_valid(self.scene.background)
&& self.scene.meshes.len() <= 4096
&& self.scene.lights.len() <= 32
&& self
.scene
.meshes
.iter()
.map(|mesh| mesh.geometry.vertices.len())
.sum::<usize>()
<= 262_144
&& self
.scene
.meshes
.iter()
.map(|mesh| mesh.geometry.triangles.len())
.sum::<usize>()
<= MAX_TRIANGLES
&& self.scene.meshes.iter().all(|mesh| {
mesh.geometry.valid()
&& mesh.world.0.iter().all(|v| v.is_finite())
@@ -173,6 +198,12 @@ impl View {
surface.commands.len() <= 10001
&& surface.commands.len() == surface.views.len()
&& surface.commands.len() == surface.clips.len()
&& surface.views.iter().flatten().all(|view| view.valid())
&& surface.clips.iter().flatten().all(|clip| {
clip.iter().all(|value| value.is_finite())
&& clip[2] >= 0.
&& clip[3] >= 0.
})
&& surface
.commands
.iter()
@@ -187,20 +218,6 @@ impl View {
&& light.intensity.is_finite()
&& (0.0..=32.0).contains(&light.intensity)
})
&& self
.scene
.meshes
.iter()
.map(|mesh| mesh.geometry.vertices.len())
.sum::<usize>()
<= 262_144
&& self
.scene
.meshes
.iter()
.map(|mesh| mesh.geometry.triangles.len())
.sum::<usize>()
<= MAX_TRIANGLES
}
pub fn pick(&self, u: f32, v: f32, aspect: f32) -> Option<Hit> {
if !self.camera.valid()
@@ -214,7 +231,18 @@ impl View {
let ray = self.camera.ray(u, v, aspect)?;
let basis = self.camera.basis()?;
let mut hit: Option<Hit> = None;
for (instance, mesh) in self.scene.meshes.iter().enumerate() {
let temporary;
let index = if self.scene.acceleration.matches(self.scene.meshes.len()) {
&*self.scene.acceleration
} else {
temporary = spatial::Index::build(&self.scene.meshes);
&temporary
};
for (entry, instance) in index.ray(ray) {
if hit.as_ref().is_some_and(|hit| entry > hit.distance) {
break;
}
let mesh = &self.scene.meshes[instance];
for (triangle, indices) in mesh.geometry.triangles.iter().enumerate() {
let [a, b, c] =
indices.map(|i| mesh.world.point(mesh.geometry.vertices[i as usize]));
@@ -225,7 +253,10 @@ impl View {
let depth = self.camera.view(basis, point).z;
if depth < self.camera.near
|| depth > self.camera.far
|| hit.as_ref().is_some_and(|hit| hit.distance <= distance)
|| hit.as_ref().is_some_and(|hit| {
hit.distance < distance
|| hit.distance == distance && hit.instance <= instance
})
{
continue;
}
@@ -258,6 +289,7 @@ struct CachedSurface {
view: Arc<View>,
width: u32,
height: u32,
aspect: f32,
pixels: Arc<[u32]>,
}
#[derive(Default)]
@@ -266,20 +298,28 @@ struct SurfaceCache {
pixels: usize,
}
pub fn surface(view: &Arc<View>, width: u32, height: u32) -> Result<Arc<[u32]>, &'static str> {
pub fn surface(
view: &Arc<View>,
width: u32,
height: u32,
aspect: f32,
) -> Result<Arc<[u32]>, &'static str> {
static CACHE: std::sync::OnceLock<std::sync::Mutex<SurfaceCache>> = std::sync::OnceLock::new();
let cache = CACHE.get_or_init(Default::default);
{
let cache = cache.lock().map_err(|_| "3D surface cache poisoned")?;
if let Some(entry) = cache.entries.iter().find(|entry| {
Arc::ptr_eq(&entry.view, view) && entry.width == width && entry.height == height
Arc::ptr_eq(&entry.view, view)
&& entry.width == width
&& entry.height == height
&& entry.aspect == aspect
}) {
return Ok(entry.pixels.clone());
}
}
// Do not hold a cache lock across rendering: world UI can contain another
// 3D viewport and recurse through the compositor.
let pixels: Arc<[u32]> = render(view, width, height)?.into();
let pixels: Arc<[u32]> = render_aspect(view, width, height, aspect)?.into();
let mut cache = cache.lock().map_err(|_| "3D surface cache poisoned")?;
while cache.entries.len() >= 8 || cache.pixels + pixels.len() > 8_388_608 {
let Some(entry) = cache.entries.pop_front() else {
@@ -292,6 +332,7 @@ pub fn surface(view: &Arc<View>, width: u32, height: u32) -> Result<Arc<[u32]>,
view: view.clone(),
width,
height,
aspect,
pixels: pixels.clone(),
});
Ok(pixels)
@@ -315,7 +356,7 @@ impl Vertex {
}
}
}
fn clip(mut polygon: Vec<Vertex>, camera: Camera, aspect: f32) -> Vec<Vertex> {
fn frustum_planes(camera: Camera, aspect: f32) -> [[f32; 4]; 6] {
let (x, y, slope) = match camera.projection {
Projection::Perspective { fov } => {
let y = (fov.to_radians() / 2.).tan();
@@ -323,15 +364,17 @@ fn clip(mut polygon: Vec<Vertex>, camera: Camera, aspect: f32) -> Vec<Vertex> {
}
Projection::Orthographic { height } => (height * aspect / 2., height / 2., 0.),
};
let planes = [
[
[0., 0., 1., -camera.near],
[0., 0., -1., camera.far],
[1., 0., x * slope, x * (1. - slope)],
[-1., 0., x * slope, x * (1. - slope)],
[0., 1., y * slope, y * (1. - slope)],
[0., -1., y * slope, y * (1. - slope)],
];
for [a, b, c, d] in planes {
]
}
fn clip(mut polygon: Vec<Vertex>, camera: Camera, aspect: f32) -> Vec<Vertex> {
for [a, b, c, d] in frustum_planes(camera, aspect) {
if polygon.is_empty() {
break;
}
@@ -358,11 +401,26 @@ fn clip(mut polygon: Vec<Vertex>, camera: Camera, aspect: f32) -> Vec<Vertex> {
polygon
}
#[cfg(test)]
pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static str> {
render_aspect(view, width, height, width as f32 / height as f32)
}
fn render_aspect(
view: &View,
width: u32,
height: u32,
aspect: f32,
) -> Result<Vec<u32>, &'static str> {
let _scope = crate::software_renderer::RenderScope::enter()?;
let area = width as usize * height as usize;
// Offscreen targets have a hard per-surface resource bound.
if area > 4_194_304 || width == 0 || height == 0 || !view.valid() {
if area > 4_194_304
|| width == 0
|| height == 0
|| !aspect.is_finite()
|| aspect <= 0.
|| !view.valid()
{
return Err("invalid 3D surface or resource budget exceeded");
}
crate::software_renderer::reserve_pixels(area.saturating_mul(2))?;
@@ -370,7 +428,6 @@ pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static
let mut depths = vec![f32::INFINITY; area];
let camera = view.camera;
let basis = camera.basis().unwrap();
let aspect = width as f32 / height as f32;
let perspective = matches!(camera.projection, Projection::Perspective { .. });
let project = |point: Vec3| {
let half = match camera.projection {
@@ -384,7 +441,15 @@ pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static
)
};
let mut work = 0usize;
for mesh in &view.scene.meshes {
let temporary;
let index = if view.scene.acceleration.matches(view.scene.meshes.len()) {
&*view.scene.acceleration
} else {
temporary = spatial::Index::build(&view.scene.meshes);
&temporary
};
for instance in index.visible(camera, aspect) {
let mesh = &view.scene.meshes[instance];
let texture = mesh.panel.as_ref().map(panel::texture).transpose()?;
for indices in &mesh.geometry.triangles {
let [a, b, c] = indices.map(|i| mesh.world.point(mesh.geometry.vertices[i as usize]));
@@ -494,6 +559,32 @@ pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn spatial_index_culls_offscreen_meshes_and_preserves_ray_pick() {
let mut view = view(Geometry::cuboid(1., 1., 1.));
let scene = Arc::make_mut(&mut view.scene);
let mesh = scene.meshes[0].clone();
for index in 1..100 {
let mut far = mesh.clone();
far.identity = format!("far{index}");
far.world = Matrix::trs(
Vec3::new(index as f32 * 100., 0., 0.),
Vec3::default(),
Vec3::new(1., 1., 1.),
);
scene.meshes.push(far);
}
scene.acceleration = Arc::new(spatial::Index::build(&scene.meshes));
assert_eq!(scene.acceleration.visible(view.camera, 1.), vec![0]);
let ray = view.camera.ray(0.5, 0.5, 1.).unwrap();
assert_eq!(scene.acceleration.ray(ray).len(), 1);
let indexed = view.pick(0.5, 0.5, 1.).unwrap();
let mut plain = view.clone();
Arc::make_mut(&mut plain.scene).acceleration = Arc::default();
let fallback = plain.pick(0.5, 0.5, 1.).unwrap();
assert_eq!(indexed.identity, fallback.identity);
assert_eq!(indexed.distance, fallback.distance);
}
fn view(geometry: Geometry) -> View {
View {
camera: Camera::default(),
@@ -508,6 +599,7 @@ mod tests {
lights: vec![],
ambient: 1.,
background: [1., 1., 1.],
acceleration: Arc::default(),
}),
}
}
@@ -560,9 +652,12 @@ mod tests {
#[test]
fn surface_cache_reuses_immutable_frames_and_rejects_invalid_resources() {
let view = Arc::new(view(Geometry::cuboid(1., 1., 1.)));
let first = surface(&view, 64, 64).unwrap();
let second = surface(&view, 64, 64).unwrap();
let first = surface(&view, 64, 64, 1.).unwrap();
let second = surface(&view, 64, 64, 1.).unwrap();
assert!(Arc::ptr_eq(&first, &second));
let wide = surface(&view, 64, 64, 2.).unwrap();
assert!(!Arc::ptr_eq(&first, &wide));
assert_ne!(first, wide);
assert!(render(&view, 4000, 4000).is_err());
let mut invalid = (*view).clone();
invalid.camera.target = invalid.camera.position;