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
+32
View File
@@ -63,6 +63,38 @@ impl Default for Matrix {
}
}
impl Matrix {
pub fn inverse(self) -> Option<Self> {
let m = self.0;
let determinant = m[0] * (m[5] * m[10] - m[6] * m[9]) - m[1] * (m[4] * m[10] - m[6] * m[8])
+ m[2] * (m[4] * m[9] - m[5] * m[8]);
if !determinant.is_finite() || determinant.abs() < 1e-9 {
return None;
}
let d = 1. / determinant;
let mut out = Self([
(m[5] * m[10] - m[6] * m[9]) * d,
(m[2] * m[9] - m[1] * m[10]) * d,
(m[1] * m[6] - m[2] * m[5]) * d,
0.,
(m[6] * m[8] - m[4] * m[10]) * d,
(m[0] * m[10] - m[2] * m[8]) * d,
(m[2] * m[4] - m[0] * m[6]) * d,
0.,
(m[4] * m[9] - m[5] * m[8]) * d,
(m[1] * m[8] - m[0] * m[9]) * d,
(m[0] * m[5] - m[1] * m[4]) * d,
0.,
0.,
0.,
0.,
1.,
]);
let translation = out.point(Vec3::new(m[3], m[7], m[11])) * -1.;
out.0[3] = translation.x;
out.0[7] = translation.y;
out.0[11] = translation.z;
Some(out)
}
pub fn compose(self, local: Self) -> Self {
let mut out = [0.; 16];
for row in 0..4 {
+255
View File
@@ -0,0 +1,255 @@
//! Perspective UI mapping. The same world plane supplies texture coordinates
//! during rendering and inverse pointer coordinates during event dispatch.
use super::{
View,
math::{Projection, Vec3},
};
use crate::{
geometry::{Point, Rect},
viewport::Transform,
};
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Mapping {
pub owner: u64,
pub key: u64,
pub view: Arc<View>,
pub rect: [f32; 4],
pub outer: Transform,
pub clip: Option<[f32; 4]>,
pub parent: Option<Arc<Mapping>>,
}
impl Mapping {
pub fn texture_point(&self, point: Point, clipped: bool) -> Option<Point> {
let point = if let Some(parent) = &self.parent {
parent.texture_point(point, clipped)?
} else {
point
};
if clipped
&& self
.clip
.is_some_and(|clip| !Rect::new(clip[0], clip[1], clip[2], clip[3]).contains(point))
{
return None;
}
let point = self.outer.inverse(point);
let [x, y, width, height] = self.rect;
if width <= 0. || height <= 0. {
return None;
}
let (u, v) = ((point.x - x) / width, (point.y - y) / height);
let mesh = self.view.scene.meshes.iter().find(|mesh| {
mesh.panel
.as_ref()
.is_some_and(|panel| panel.key == self.key)
})?;
let panel = mesh.panel.as_ref()?;
if clipped {
let hit = self.view.pick(u, v, width / height)?;
if self.view.scene.meshes[hit.instance]
.panel
.as_ref()
.is_none_or(|panel| panel.key != self.key)
{
return None;
}
}
let ray = self.view.camera.ray(u, v, width / height)?;
let center = mesh.world.point(Vec3::default());
let normal = (mesh.world.point(Vec3::new(1., 0., 0.)) - center)
.cross(mesh.world.point(Vec3::new(0., 1., 0.)) - center);
let denominator = normal.dot(ray.direction);
if denominator.abs() < 1e-7 {
return None;
}
let distance = (center - ray.origin).dot(normal) / denominator;
if !distance.is_finite() || distance <= 0. {
return None;
}
let local = mesh
.world
.inverse()?
.point(ray.origin + ray.direction * distance);
let world_width = mesh.geometry.vertices[1].x - mesh.geometry.vertices[0].x;
let world_height = mesh.geometry.vertices[0].y - mesh.geometry.vertices[2].y;
let point = Point::new(
(local.x / world_width + 0.5) * panel.width as f32,
(0.5 - local.y / world_height) * panel.height as f32,
);
(point.x.is_finite() && point.y.is_finite()).then_some(point)
}
pub fn project_point(&self, point: Point) -> Option<Point> {
let mesh = self.view.scene.meshes.iter().find(|mesh| {
mesh.panel
.as_ref()
.is_some_and(|panel| panel.key == self.key)
})?;
let panel = mesh.panel.as_ref()?;
let width = mesh.geometry.vertices[1].x - mesh.geometry.vertices[0].x;
let height = mesh.geometry.vertices[0].y - mesh.geometry.vertices[2].y;
let world = mesh.world.point(Vec3::new(
(point.x / panel.width as f32 - 0.5) * width,
(0.5 - point.y / panel.height as f32) * height,
0.,
));
let camera = self.view.camera;
let local = camera.view(camera.basis()?, world);
if local.z <= camera.near || local.z >= camera.far {
return None;
}
let [x, y, w, h] = self.rect;
let half = match camera.projection {
Projection::Perspective { fov } => local.z * (fov.to_radians() / 2.).tan(),
Projection::Orthographic { height } => height / 2.,
};
let point = self.outer.point(Point::new(
x + (local.x / (half * w / h) + 1.) * w / 2.,
y + (1. - local.y / half) * h / 2.,
));
if let Some(parent) = &self.parent {
parent.project_point(point)
} else {
Some(point)
}
}
}
#[derive(Clone)]
struct Entry {
command: crate::document::RenderCommand,
clip: Option<[f32; 4]>,
view: Option<Transform>,
owner: u64,
}
/// Collect a panel's ordinary paint subtree into its texture. Nested 3D
/// commands are assembled recursively before their containing texture.
pub fn compose(frame: &mut crate::document::Frame) -> anyhow::Result<()> {
use crate::document::RenderCommand;
use std::collections::{HashMap, HashSet};
let mounts: HashMap<_, _> = frame.mounts.iter().map(|mount| (mount.id, mount)).collect();
let mut groups = HashMap::<(u64, u64), Vec<Entry>>::new();
let mut roots = Vec::new();
for (index, command) in frame.commands.iter().enumerate() {
let owner = frame.command_mounts[index];
let mount = mounts[&owner];
let entry = Entry {
command: command.clone(),
clip: frame.command_clips[index],
view: frame.command_views[index],
owner,
};
if let Some(panel) = &mount.panel {
groups
.entry((panel.owner, panel.key))
.or_default()
.push(entry);
} else {
roots.push(entry);
}
}
if let Some(mount) = frame.focus.and_then(|id| mounts.get(&id))
&& let Some(panel) = &mount.panel
{
groups
.entry((panel.owner, panel.key))
.or_default()
.push(Entry {
command: RenderCommand::StrokeRoundedRect {
x: mount.x,
y: mount.y,
width: mount.width,
height: mount.height,
radius: 7.,
stroke_width: 2.,
color: "#4F6FDB".into(),
},
clip: mount.clip,
view: mount.view,
owner: mount.id,
});
}
fn assemble(
entry: Entry,
groups: &HashMap<(u64, u64), Vec<Entry>>,
path: &mut HashSet<u64>,
depth: usize,
) -> anyhow::Result<Entry> {
let mut entry = entry;
if let RenderCommand::Scene3D { view, .. } = &mut entry.command
&& view.scene.meshes.iter().any(|mesh| mesh.panel.is_some())
{
anyhow::ensure!(
depth < 8 && path.insert(entry.owner),
"3D UI paint nesting cycle or depth budget exceeded"
);
let mut scene = (*view.scene).clone();
for mesh in &mut scene.meshes {
if let Some(panel) = &mut mesh.panel {
let mut surface = super::UiSurface {
commands: Vec::new(),
clips: Vec::new(),
views: Vec::new(),
};
for child in groups.get(&(entry.owner, panel.key)).into_iter().flatten() {
let child = assemble(child.clone(), groups, path, depth + 1)?;
surface.commands.push(child.command);
surface.clips.push(child.clip);
surface.views.push(child.view);
}
panel.surface = Some(Arc::new(surface));
}
}
*view = Arc::new(View {
scene: Arc::new(scene),
camera: view.camera,
});
path.remove(&entry.owner);
}
Ok(entry)
}
let mut path = HashSet::new();
frame.commands.clear();
frame.command_clips.clear();
frame.command_views.clear();
frame.command_mounts.clear();
for entry in roots {
let entry = assemble(entry, &groups, &mut path, 0)?;
frame.commands.push(entry.command);
frame.command_clips.push(entry.clip);
frame.command_views.push(entry.view);
frame.command_mounts.push(entry.owner);
}
Ok(())
}
pub fn texture(panel: &super::Panel) -> Result<Vec<u32>, &'static str> {
crate::software_renderer::reserve_pixels(panel.width as usize * panel.height as usize)?;
let mut pixels =
vec![super::rgb(panel.background); panel.width as usize * panel.height as usize];
if let Some(surface) = &panel.surface {
let document = crate::document::RenderDocument {
frame: crate::document::Frame {
background: format!("#{:06X}", super::rgb(panel.background)),
commands: surface.commands.clone(),
command_views: surface.views.clone(),
command_clips: surface.clips.clone(),
..Default::default()
},
..Default::default()
};
let list = document
.display_list(1.)
.map_err(|_| "invalid 3D UI texture commands")?;
crate::software_renderer::SoftwareRenderer::render(
&list,
&mut pixels,
panel.width,
panel.height,
)?;
}
Ok(pixels)
}