feat: compose interactive world ui across nested 3d viewports

This commit is contained in:
2026-11-11 00:08:23 +08:00
parent ad2c01bc29
commit 15fc01542c
27 changed files with 1412 additions and 84 deletions
+127 -11
View File
@@ -1,6 +1,7 @@
//! Software 3D surfaces share the application's existing CPU compositor. Mesh
//! visibility and picking use the same camera and transformed world triangles.
pub mod math;
pub mod panel;
use math::{Camera, Matrix, Projection, Vec3};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
@@ -12,10 +13,15 @@ pub const MAX_VERTICES: usize = 32_768;
pub struct Geometry {
pub vertices: Vec<Vec3>,
pub triangles: Vec<[u32; 3]>,
#[serde(default)]
pub uv: Vec<[f32; 2]>,
}
impl Geometry {
pub fn valid(&self) -> bool {
self.vertices.len() <= MAX_VERTICES
&& (self.uv.is_empty()
|| self.uv.len() == self.vertices.len()
&& self.uv.iter().flatten().all(|value| value.is_finite()))
&& self.triangles.len() <= MAX_TRIANGLES
&& self.vertices.iter().all(|point| point.valid())
&& self
@@ -27,6 +33,7 @@ impl Geometry {
pub fn cuboid(width: f32, height: f32, depth: f32) -> Self {
let (x, y, z) = (width / 2., height / 2., depth / 2.);
Self {
uv: vec![],
vertices: vec![
Vec3::new(-x, -y, -z),
Vec3::new(x, -y, -z),
@@ -60,6 +67,22 @@ pub struct Mesh {
pub geometry: Arc<Geometry>,
pub world: Matrix,
pub color: [f32; 3],
pub panel: Option<Panel>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UiSurface {
pub commands: Vec<crate::document::RenderCommand>,
pub clips: Vec<Option<[f32; 4]>>,
pub views: Vec<Option<crate::viewport::Transform>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Panel {
pub key: u64,
pub width: u32,
pub height: u32,
pub background: [f32; 3],
pub surface: Option<Arc<UiSurface>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Light {
@@ -91,6 +114,7 @@ impl endor_core::ObjectPayload for PaintView {
}
#[derive(Debug, Clone, PartialEq)]
pub struct Hit {
pub instance: usize,
pub identity: String,
pub point: Vec3,
pub normal: Vec3,
@@ -101,6 +125,24 @@ pub struct Hit {
impl View {
pub fn valid(&self) -> bool {
thread_local! { static DEPTH:std::cell::Cell<usize>=const { std::cell::Cell::new(0) }; }
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
DEPTH.with(|depth| depth.set(depth.get() - 1));
}
}
if !DEPTH.with(|depth| {
if depth.get() >= 8 {
false
} else {
depth.set(depth.get() + 1);
true
}
}) {
return false;
}
let _guard = Guard;
let color_valid = |color: [f32; 3]| {
color
.iter()
@@ -121,6 +163,22 @@ impl View {
.vertices
.iter()
.all(|point| mesh.world.point(*point).valid())
&& mesh.panel.as_ref().is_none_or(|panel| {
panel.width > 0
&& panel.height > 0
&& panel.width <= 2048
&& panel.height <= 2048
&& color_valid(panel.background)
&& panel.surface.as_ref().is_none_or(|surface| {
surface.commands.len() <= 10001
&& surface.commands.len() == surface.views.len()
&& surface.commands.len() == surface.clips.len()
&& surface
.commands
.iter()
.all(|command| command.validate().is_ok())
})
})
})
&& self.scene.lights.iter().all(|light| {
color_valid(light.color)
@@ -156,7 +214,7 @@ impl View {
let ray = self.camera.ray(u, v, aspect)?;
let basis = self.camera.basis()?;
let mut hit: Option<Hit> = None;
for mesh in &self.scene.meshes {
for (instance, mesh) in self.scene.meshes.iter().enumerate() {
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]));
@@ -175,6 +233,7 @@ impl View {
continue;
};
hit = Some(Hit {
instance,
identity: mesh.identity.clone(),
point,
normal,
@@ -240,7 +299,23 @@ pub fn surface(view: &Arc<View>, width: u32, height: u32) -> Result<Arc<[u32]>,
/// Homogeneous frustum planes expressed in view space. Clipping before division
/// handles triangles crossing the near plane without huge screen coordinates.
fn clip(mut polygon: Vec<Vec3>, camera: Camera, aspect: f32) -> Vec<Vec3> {
#[derive(Clone, Copy)]
struct Vertex {
position: Vec3,
uv: [f32; 2],
}
impl Vertex {
fn lerp(self, other: Self, t: f32) -> Self {
Self {
position: self.position + (other.position - self.position) * t,
uv: [
self.uv[0] + (other.uv[0] - self.uv[0]) * t,
self.uv[1] + (other.uv[1] - self.uv[1]) * t,
],
}
}
}
fn clip(mut polygon: Vec<Vertex>, camera: Camera, aspect: f32) -> Vec<Vertex> {
let (x, y, slope) = match camera.projection {
Projection::Perspective { fov } => {
let y = (fov.to_radians() / 2.).tan();
@@ -260,14 +335,17 @@ fn clip(mut polygon: Vec<Vec3>, camera: Camera, aspect: f32) -> Vec<Vec3> {
if polygon.is_empty() {
break;
}
let distance = |p: Vec3| a * p.x + b * p.y + c * p.z + d;
let distance = |vertex: Vertex| {
let p = vertex.position;
a * p.x + b * p.y + c * p.z + d
};
let mut output = Vec::new();
let mut previous = *polygon.last().unwrap();
let mut before = distance(previous);
for current in polygon {
let after = distance(current);
if (before >= 0.) != (after >= 0.) {
output.push(previous + (current - previous) * (before / (before - after)));
output.push(previous.lerp(current, before / (before - after)));
}
if after >= 0. {
output.push(current);
@@ -281,11 +359,13 @@ fn clip(mut polygon: Vec<Vec3>, camera: Camera, aspect: f32) -> Vec<Vec3> {
}
pub fn render(view: &View, width: u32, height: u32) -> 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() {
return Err("invalid 3D surface or resource budget exceeded");
}
crate::software_renderer::reserve_pixels(area.saturating_mul(2))?;
let mut pixels = vec![rgb(view.scene.background); area];
let mut depths = vec![f32::INFINITY; area];
let camera = view.camera;
@@ -305,6 +385,7 @@ pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static
};
let mut work = 0usize;
for mesh in &view.scene.meshes {
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]));
let Some(normal) = (b - a).cross(c - a).normalized() else {
@@ -319,11 +400,20 @@ pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static
}
let color = rgb(std::array::from_fn(|i| mesh.color[i] * light[i]));
let polygon = clip(
vec![
camera.view(basis, a),
camera.view(basis, b),
camera.view(basis, c),
],
indices
.map(|index| Vertex {
position: camera.view(
basis,
mesh.world.point(mesh.geometry.vertices[index as usize]),
),
uv: mesh
.geometry
.uv
.get(index as usize)
.copied()
.unwrap_or([0., 0.]),
})
.to_vec(),
camera,
aspect,
);
@@ -331,7 +421,8 @@ pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static
continue;
}
for index in 1..polygon.len() - 1 {
let [a, b, c] = [polygon[0], polygon[index], polygon[index + 1]].map(project);
let vertices = [polygon[0], polygon[index], polygon[index + 1]];
let [a, b, c] = vertices.map(|vertex| project(vertex.position));
let min_x = a.x.min(b.x).min(c.x).floor().max(0.) as u32;
let max_x = a.x.max(b.x).max(c.x).ceil().min(width as f32) as u32;
let min_y = a.y.min(b.y).min(c.y).floor().max(0.) as u32;
@@ -367,7 +458,30 @@ pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static
let index = y as usize * width as usize + x as usize;
if depth < depths[index] {
depths[index] = depth;
pixels[index] = color;
pixels[index] =
if let (Some(texture), Some(panel)) = (&texture, &mesh.panel) {
let interpolated = |axis| {
if perspective {
depth
* (weights[0] * vertices[0].uv[axis] / a.z
+ weights[1] * vertices[1].uv[axis] / b.z
+ weights[2] * vertices[2].uv[axis] / c.z)
} else {
weights[0] * vertices[0].uv[axis]
+ weights[1] * vertices[1].uv[axis]
+ weights[2] * vertices[2].uv[axis]
}
};
let u = (interpolated(0).clamp(0., 1.) * panel.width as f32)
.min((panel.width - 1) as f32)
as usize;
let v = (interpolated(1).clamp(0., 1.) * panel.height as f32)
.min((panel.height - 1) as f32)
as usize;
texture[v * panel.width as usize + u]
} else {
color
};
}
}
}
@@ -385,6 +499,7 @@ mod tests {
camera: Camera::default(),
scene: Arc::new(Scene {
meshes: vec![Mesh {
panel: None,
identity: "mesh".into(),
geometry: Arc::new(geometry),
world: Matrix::default(),
@@ -399,6 +514,7 @@ mod tests {
#[test]
fn triangles_crossing_near_plane_are_clipped_and_pick_uses_the_same_range() {
let mut view = view(Geometry {
uv: vec![],
vertices: vec![
Vec3::new(-1., -1., 0.5),
Vec3::new(1., -1., 2.),