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
+33 -2
View File
@@ -263,6 +263,7 @@ impl RenderDocument {
if let Some(focus) = frame
.focus
.and_then(|id| frame.mounts.iter().find(|m| m.id == id))
.filter(|mount| mount.panel.is_none())
{
if let Some(c) = focus.clip {
list.push(DrawCommand::PushClip(scaled_rect(
@@ -419,6 +420,8 @@ impl Default for Frame {
/// A position in a published frame. Identifiers are opaque data, never VM handles.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MountGeometry {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub panel: Option<Arc<crate::scene3d::panel::Mapping>>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub canvas_viewport: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
@@ -446,7 +449,33 @@ pub struct MountGeometry {
}
impl MountGeometry {
pub fn view_point(&self, point: Point, clipped: bool) -> Option<Point> {
self.panel
.as_ref()
.map_or(Some(point), |panel| panel.texture_point(point, clipped))
}
pub fn logical_point(&self, point: Point) -> Option<Point> {
let point = self.view_point(point, true)?;
Some(self.view.unwrap_or_default().inverse(point))
}
pub fn logical_delta(&self, point: Option<[f32; 2]>, delta: [f32; 2]) -> Option<[f32; 2]> {
let zoom = self.view.unwrap_or_default().zoom;
if self.panel.is_none() {
return Some([delta[0] / zoom, delta[1] / zoom]);
}
let point = point?;
let current = self.view_point(Point::new(point[0], point[1]), false)?;
let previous =
self.view_point(Point::new(point[0] + delta[0], point[1] + delta[1]), false)?;
Some([
((previous.x - current.x) / zoom).clamp(-1_000_000., 1_000_000.),
((previous.y - current.y) / zoom).clamp(-1_000_000., 1_000_000.),
])
}
pub fn contains(&self, point: Point) -> bool {
let Some(point) = self.view_point(point, true) else {
return false;
};
let local = self.view.map_or(point, |view| view.inverse(point));
Rect::new(self.x, self.y, self.width, self.height).contains(local)
&& self.clip.is_none_or(|c| {
@@ -461,7 +490,9 @@ impl Frame {
(mount.canvas_viewport || mount.scene3d_viewport && mount.camera_controls)
&& mount.contains(point)
&& mount.viewport_clip.is_some_and(|clip| {
Rect::new(clip[0], clip[1], clip[2], clip[3]).contains(point)
mount.view_point(point, true).is_some_and(|point| {
Rect::new(clip[0], clip[1], clip[2], clip[3]).contains(point)
})
})
})
}
@@ -484,7 +515,7 @@ fn default_background() -> String {
"#F7F7F5".to_owned()
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RenderCommand {
Scene3D {
+69 -3
View File
@@ -57,6 +57,8 @@ enum Query {
ScrollIntoView,
FitView,
Pick3D,
ToView,
ToLocal,
Parent,
FirstChild,
NextSibling,
@@ -81,7 +83,12 @@ impl NativeCallable for Method {
Some(endor_core::CallArity::exact(
if matches!(
self.query,
Query::HitTest | Query::Pick3D | Query::ScrollTo | Query::ScrollBy
Query::HitTest
| Query::Pick3D
| Query::ToView
| Query::ToLocal
| Query::ScrollTo
| Query::ScrollBy
) {
2
} else {
@@ -103,6 +110,8 @@ impl NativeCallable for Method {
| Query::ScrollIntoView
| Query::FitView
| Query::Pick3D
| Query::ToView
| Query::ToLocal
| Query::ScrollPosition
)
{
@@ -110,7 +119,12 @@ impl NativeCallable for Method {
}
let arity = if matches!(
self.query,
Query::HitTest | Query::Pick3D | Query::ScrollTo | Query::ScrollBy
Query::HitTest
| Query::Pick3D
| Query::ToView
| Query::ToLocal
| Query::ScrollTo
| Query::ScrollBy
) {
2
} else {
@@ -120,6 +134,50 @@ impl NativeCallable for Method {
return Err(VmError::InvalidArgument("incorrect Mount method arity"));
}
let value = match self.query {
Query::ToView | Query::ToLocal => {
if mount.layout.is_some() {
return Err(VmError::InvalidArgument(
"coordinate conversion requires committed geometry",
));
}
let point = crate::geometry::Point::new(
crate::scroll::coordinate(&args[0])?,
crate::scroll::coordinate(&args[1])?,
);
let point =
if matches!(self.query, Query::ToView) {
let point = mount.geometry.view.unwrap_or_default().point(
crate::geometry::Point::new(
point.x + mount.geometry.x,
point.y + mount.geometry.y,
),
);
mount
.geometry
.panel
.as_ref()
.map_or(Some(point), |panel| panel.project_point(point))
} else {
mount.geometry.logical_point(point).map(|point| {
crate::geometry::Point::new(
point.x - mount.geometry.x,
point.y - mount.geometry.y,
)
})
};
if let Some(point) = point {
let result = cx.new_object()?;
let desktop = cx.upgrade(self.desktop)?.ok_or(VmError::InvalidArgument(
"coordinate conversion desktop expired",
))?;
crate::ui_bridge::attach_desktop_type(cx, result, "Point", desktop)?;
cx.set_attr(result, "x", crate::native_visual::value(point.x))?;
cx.set_attr(result, "y", crate::native_visual::value(point.y))?;
Value::Object(result)
} else {
Value::Nil
}
}
Query::ScrollTo | Query::ScrollBy => {
crate::scroll::set(
cx,
@@ -281,6 +339,7 @@ fn mount_signature(
Query::Page => CallType::nullable(nominal("Page")?),
Query::HitTest => T::Bool.into(),
Query::Pick3D => CallType::nullable(nominal("RayHit3D")?),
Query::ToView | Query::ToLocal => CallType::nullable(nominal("Point")?),
Query::ScrollPosition => T::Any.into(),
_ => T::Unit.into(),
};
@@ -294,7 +353,12 @@ fn mount_signature(
};
let parameters = if matches!(
query,
Query::HitTest | Query::Pick3D | Query::ScrollTo | Query::ScrollBy
Query::HitTest
| Query::Pick3D
| Query::ToView
| Query::ToLocal
| Query::ScrollTo
| Query::ScrollBy
) {
vec![T::Number, T::Number]
} else {
@@ -433,6 +497,8 @@ impl NativeCallable for Sync {
("scrollIntoView", Query::ScrollIntoView),
("fitView", Query::FitView),
("pick3D", Query::Pick3D),
("toView", Query::ToView),
("toLocal", Query::ToLocal),
("parent", Query::Parent),
("firstChild", Query::FirstChild),
("nextSibling", Query::NextSibling),
+113 -13
View File
@@ -23,6 +23,7 @@ pub enum Constructor {
Perspective,
Orthographic,
Orbit,
Panel,
}
impl Constructor {
pub fn name(self) -> &'static str {
@@ -38,6 +39,7 @@ impl Constructor {
Self::Perspective => "PerspectiveCamera",
Self::Orthographic => "OrthographicCamera",
Self::Orbit => "OrbitController",
Self::Panel => "Panel3D",
}
}
pub fn function(self) -> &'static str {
@@ -53,6 +55,7 @@ impl Constructor {
Self::Perspective => "perspectiveCamera",
Self::Orthographic => "orthographicCamera",
Self::Orbit => "orbitController",
Self::Panel => "panel3D",
}
}
pub fn from_function(name: &str) -> Option<Self> {
@@ -68,6 +71,7 @@ impl Constructor {
Self::Perspective,
Self::Orthographic,
Self::Orbit,
Self::Panel,
]
.into_iter()
.find(|kind| kind.function() == name)
@@ -79,6 +83,7 @@ impl Constructor {
Self::Box => (4, 4),
Self::Group | Self::Scene => (0, 4096),
Self::Light => (5, 5),
Self::Panel => (3, 3),
_ => (0, 0),
}
}
@@ -89,6 +94,7 @@ impl Constructor {
Self::Mesh => &["Geometry3D", "String"],
Self::Box => &["Number", "Number", "Number", "String"],
Self::Light => &["Number", "Number", "Number", "String", "Number"],
Self::Panel => &["Number", "Number", "Block"],
_ => &[],
}
}
@@ -108,6 +114,7 @@ pub enum NodeKind {
Perspective,
Orthographic,
Orbit,
Panel,
}
#[derive(Debug)]
pub struct Node(pub NodeKind);
@@ -198,6 +205,7 @@ pub fn allocate(
Constructor::Perspective => NodeKind::Perspective,
Constructor::Orthographic => NodeKind::Orthographic,
Constructor::Orbit => NodeKind::Orbit,
Constructor::Panel => NodeKind::Panel,
Constructor::Geometry => {
let vertices = object_list::items(cx.store(), object_ref(&args[0])?)?
.iter()
@@ -233,6 +241,7 @@ pub fn allocate(
let geometry = scene3d::Geometry {
vertices,
triangles,
uv: vec![],
};
if !geometry.valid() {
return Err(invalid(
@@ -282,7 +291,7 @@ pub fn allocate(
for child in &children {
if !matches!(
cx.store().payload::<Node>(*child, "3D node")?.0,
NodeKind::Mesh | NodeKind::Group | NodeKind::Light
NodeKind::Mesh | NodeKind::Group | NodeKind::Light | NodeKind::Panel
) {
return Err(invalid(
"Scene3D/Group3D children require meshes, groups or lights",
@@ -307,6 +316,16 @@ pub fn allocate(
cx.set_attr(instance, "color", args[3].clone())?;
set_number(cx, instance, "intensity", number(&args[4])?)?;
}
NodeKind::Panel => {
let content = object_ref(&args[2])?;
crate::block::validate(cx.store(), content, None)?;
set_number(cx, instance, "width", number(&args[0])?)?;
set_number(cx, instance, "height", number(&args[1])?)?;
set_number(cx, instance, "uiWidth", 512.)?;
set_number(cx, instance, "uiHeight", 320.)?;
cx.set_attr(instance, "content", Value::Object(content))?;
cx.set_attr(instance, "background", Value::Text("#FFFFFF".into()))?;
}
NodeKind::Perspective | NodeKind::Orthographic => {
for (name, value) in [
("x", 0.),
@@ -331,7 +350,7 @@ pub fn allocate(
set_number(cx, instance, "panSpeed", 1.)?;
}
}
if matches!(kind, NodeKind::Mesh | NodeKind::Group) {
if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
for (name, value) in [
("x", 0.),
("y", 0.),
@@ -397,7 +416,16 @@ impl Reader<'_> {
}
}
pub type Snapshot = (Arc<scene3d::View>, Vec<(ObjectRef, String)>);
pub struct PanelMount {
pub key: u64,
pub content: ObjectRef,
pub size: crate::layout::Size,
}
pub type Snapshot = (
Arc<scene3d::View>,
Vec<(ObjectRef, String)>,
Vec<PanelMount>,
);
pub fn snapshot(
store: &ObjectStore,
scene: ObjectRef,
@@ -422,11 +450,12 @@ pub fn snapshot(
ambient,
background,
};
let mut work = vec![(scene, Matrix::default(), false)];
let mut work = vec![(scene, Matrix::default(), false, 0u64)];
let mut panels = Vec::new();
let mut path = HashSet::new();
let mut visits = 0;
let mut triangles = 0;
while let Some((object, parent, finish)) = work.pop() {
while let Some((object, parent, finish, key)) = work.pop() {
if finish {
path.remove(&object);
continue;
@@ -438,9 +467,9 @@ pub fn snapshot(
if !path.insert(object) {
return Err(invalid("cyclic 3D scene graph"));
}
work.push((object, parent, true));
work.push((object, parent, true, key));
let kind = store.payload::<Node>(object, "3D node")?.0;
let world = if matches!(kind, NodeKind::Mesh | NodeKind::Group) {
let world = if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
parent.compose(Matrix::trs(
reader.vector(object, ["x", "y", "z"])?,
reader.vector(object, ["rotationX", "rotationY", "rotationZ"])?,
@@ -452,8 +481,13 @@ pub fn snapshot(
match kind {
NodeKind::Scene | NodeKind::Group => {
let list = object_ref(&reader.value(object, "children")?)?;
for child in object_list::items(store, list)?.iter().rev() {
work.push((*child, world, false));
for (index, child) in object_list::items(store, list)?.iter().enumerate().rev() {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut hasher);
index.hash(&mut hasher);
child.hash(&mut hasher);
work.push((*child, world, false, hasher.finish()));
}
}
NodeKind::Mesh => {
@@ -469,6 +503,60 @@ pub fn snapshot(
geometry,
world,
color: material,
panel: None,
});
}
NodeKind::Panel => {
if panels.len() >= 64 {
return Err(VmError::ExecutionLimit("3D UI panels"));
}
let width = reader.number(object, "width")?;
let height = reader.number(object, "height")?;
let ui_width = reader.number(object, "uiWidth")?;
let ui_height = reader.number(object, "uiHeight")?;
if width <= 0.
|| height <= 0.
|| ![ui_width, ui_height]
.iter()
.all(|size| (1.0..=2048.0).contains(size) && size.fract() == 0.)
{
return Err(invalid(
"Panel3D requires positive world dimensions and integer UI dimensions from 1 through 2048",
));
}
let content = object_ref(&reader.value(object, "content")?)?;
crate::block::resolve(store, content)?;
let background = color(&text(&reader.value(object, "background")?)?)?;
let geometry = Arc::new(scene3d::Geometry {
vertices: vec![
Vec3::new(-width / 2., height / 2., 0.),
Vec3::new(width / 2., height / 2., 0.),
Vec3::new(width / 2., -height / 2., 0.),
Vec3::new(-width / 2., -height / 2., 0.),
],
triangles: vec![[0, 1, 2], [0, 2, 3]],
uv: vec![[0., 0.], [1., 0.], [1., 1.], [0., 1.]],
});
output.meshes.push(scene3d::Mesh {
identity: object.to_string(),
geometry,
world,
color: [1., 1., 1.],
panel: Some(scene3d::Panel {
key,
width: ui_width as u32,
height: ui_height as u32,
background,
surface: None,
}),
});
panels.push(PanelMount {
key,
content,
size: crate::layout::Size {
width: ui_width,
height: ui_height,
},
});
}
NodeKind::Light => {
@@ -501,7 +589,7 @@ pub fn snapshot(
if !view.valid() {
return Err(invalid("invalid 3D scene snapshot"));
}
Ok((view, reader.reads.into_iter().collect()))
Ok((view, reader.reads.into_iter().collect(), panels))
}
pub fn pick(
@@ -523,7 +611,9 @@ pub fn pick(
}
let node = crate::block::snapshot(cx.store(), mount.block)?;
let inset = crate::layout::insets(&node);
let point = mount.geometry.view.unwrap_or_default().inverse(point);
let Some(point) = mount.geometry.logical_point(point) else {
return Ok(Value::Nil);
};
let (width, height) = (
(mount.geometry.width - inset.horizontal()).max(0.),
(mount.geometry.height - inset.vertical()).max(0.),
@@ -531,7 +621,7 @@ pub fn pick(
if width <= 0. || height <= 0. {
return Ok(Value::Nil);
}
let (view, reads) = snapshot(
let (view, reads, _) = snapshot(
cx.store(),
data.scene3d.ok_or(invalid("missing Scene3D"))?,
data.camera.ok_or(invalid("missing 3D camera"))?,
@@ -551,6 +641,12 @@ pub fn pick(
let result = cx.new_object()?;
crate::ui_bridge::attach_desktop_type(cx, result, "RayHit3D", desktop)?;
cx.set_attr(result, "mesh", Value::Object(mesh))?;
cx.set_attr(result, "node", Value::Object(mesh))?;
cx.set_attr(
result,
"instance",
Value::Number((hit.instance as i64).into()),
)?;
cx.set_attr(
result,
"distance",
@@ -700,7 +796,11 @@ pub fn transform(
let camera = matches!(kind, NodeKind::Perspective | NodeKind::Orthographic);
if !matches!(
kind,
NodeKind::Mesh | NodeKind::Group | NodeKind::Perspective | NodeKind::Orthographic
NodeKind::Mesh
| NodeKind::Group
| NodeKind::Panel
| NodeKind::Perspective
| NodeKind::Orthographic
) || rotate && camera
{
return Err(invalid("unsupported 3D transform target"));
+30 -17
View File
@@ -128,7 +128,7 @@ impl RenderCache {
}
store.check_typed_instance_storage(block)?;
let (data_ref, raw_data, raw_dependencies) = block::resolve_tracked(store, block)?;
let data = block::visual_data(store, raw_data)?;
let mut data = block::visual_data(store, raw_data)?;
let mut dependencies: Vec<_> = raw_dependencies
.into_iter()
.map(|object| Dependency {
@@ -164,6 +164,33 @@ impl RenderCache {
});
}
}
let mut panel_sizes = Vec::new();
let view3d = if matches!(data.kind, Kind::Viewport3D { .. }) {
let (view, reads, panels) = crate::scene3d_model::snapshot(
store,
data.scene3d
.ok_or(VmError::InvalidArgument("missing Scene3D"))?,
data.camera
.ok_or(VmError::InvalidArgument("missing 3D camera"))?,
)?;
dependencies.extend(reads.into_iter().map(|(object, name)| Dependency {
object,
property: Some(name),
}));
data.children = panels
.into_iter()
.map(|panel| {
panel_sizes.push(panel.size);
crate::block::Child {
slot: panel.key,
block: panel.content,
}
})
.collect();
Some(view)
} else {
None
};
if !finish {
if !path.insert(data_ref) {
return Err(VmError::InvalidArgument("cyclic Block composition"));
@@ -175,22 +202,6 @@ impl RenderCache {
continue;
}
path.remove(&data_ref);
let view3d = if matches!(data.kind, Kind::Viewport3D { .. }) {
let (view, reads) = crate::scene3d_model::snapshot(
store,
data.scene3d
.ok_or(VmError::InvalidArgument("missing Scene3D"))?,
data.camera
.ok_or(VmError::InvalidArgument("missing 3D camera"))?,
)?;
dependencies.extend(reads.into_iter().map(|(object, name)| Dependency {
object,
property: Some(name),
}));
Some(view)
} else {
None
};
let mut protocol_key = String::new();
let mut custom_event = false;
if let Some(definition) = store.type_of(block)? {
@@ -290,6 +301,8 @@ impl RenderCache {
height: *height,
view: view3d.ok_or(VmError::InvalidArgument("missing 3D view"))?,
controls: data.controller.is_some(),
panels: panel_sizes,
children,
},
Kind::CanvasViewport { width, height } => UiKind::CanvasViewport {
width: *width,