971 lines
41 KiB
Rust
971 lines
41 KiB
Rust
//! 将 Endor 托管场景对象转换成可供渲染线程读取的 3D 数据。
|
||
//! 构造器和字段仍属于 VM;快照复制必要的数值、不可变网格和依赖,渲染器不读取托管堆。
|
||
//! 场景遍历组合局部变换、检查环和资源限制,并为 Panel3D 提取独立 UI 根。控制器更新相机;拾取结果再映射回托管节点。
|
||
//!
|
||
//! Traced 3D objects and checked immutable snapshots. No managed handle enters
|
||
//! the renderer; cameras and node transforms remain editable Endor attributes.
|
||
use crate::{
|
||
object_list,
|
||
scene3d::{
|
||
self,
|
||
math::{Camera, Matrix, Projection, Vec3},
|
||
},
|
||
};
|
||
use endor_core::{NativeContext, ObjectPayload, ObjectRef, ObjectStore, Value, VmError};
|
||
use std::{collections::HashSet, sync::Arc};
|
||
|
||
#[derive(Debug, Clone, Copy)]
|
||
/// 源 3D 类型的构造元数据入口,统一管理名称、参数、数量和可变子项。
|
||
pub enum Constructor {
|
||
Vec3,
|
||
Triangle,
|
||
Geometry,
|
||
Mesh,
|
||
Box,
|
||
Group,
|
||
Scene,
|
||
Light,
|
||
Perspective,
|
||
Orthographic,
|
||
Orbit,
|
||
Panel,
|
||
}
|
||
impl Constructor {
|
||
/// 返回内部枚举或对象对应的稳定源名称。
|
||
pub fn name(self) -> &'static str {
|
||
match self {
|
||
Self::Vec3 => "Vec3",
|
||
Self::Triangle => "Triangle3D",
|
||
Self::Geometry => "Geometry3D",
|
||
Self::Mesh => "Mesh3D",
|
||
Self::Box => "Box3D",
|
||
Self::Group => "Group3D",
|
||
Self::Scene => "Scene3D",
|
||
Self::Light => "DirectionalLight",
|
||
Self::Perspective => "PerspectiveCamera",
|
||
Self::Orthographic => "OrthographicCamera",
|
||
Self::Orbit => "OrbitController",
|
||
Self::Panel => "Panel3D",
|
||
}
|
||
}
|
||
/// 取得本构造器对应的源工厂函数名称。
|
||
pub fn function(self) -> &'static str {
|
||
match self {
|
||
Self::Vec3 => "vec3",
|
||
Self::Triangle => "triangle3D",
|
||
Self::Geometry => "geometry3D",
|
||
Self::Mesh => "mesh3D",
|
||
Self::Box => "box3D",
|
||
Self::Group => "group3D",
|
||
Self::Scene => "scene3D",
|
||
Self::Light => "directionalLight",
|
||
Self::Perspective => "perspectiveCamera",
|
||
Self::Orthographic => "orthographicCamera",
|
||
Self::Orbit => "orbitController",
|
||
Self::Panel => "panel3D",
|
||
}
|
||
}
|
||
/// 反查源构造器名称对应的原生 3D 种类,不认识的名称返回空值。
|
||
pub fn from_function(name: &str) -> Option<Self> {
|
||
[
|
||
Self::Vec3,
|
||
Self::Triangle,
|
||
Self::Geometry,
|
||
Self::Mesh,
|
||
Self::Box,
|
||
Self::Group,
|
||
Self::Scene,
|
||
Self::Light,
|
||
Self::Perspective,
|
||
Self::Orthographic,
|
||
Self::Orbit,
|
||
Self::Panel,
|
||
]
|
||
.into_iter()
|
||
.find(|kind| kind.function() == name)
|
||
}
|
||
/// 返回三维原生构造的显式最小/最大参数数,不含请求 Type;Group/Scene 支持最多4096子节点。
|
||
pub fn arity(self) -> (usize, usize) {
|
||
// 构造器 arity 不含 NativeTyped 的类型首参,Group/Scene 允许零到 4096 个孩子,其他零参对象使用默认属性。
|
||
match self {
|
||
Self::Vec3 | Self::Triangle => (3, 3),
|
||
Self::Geometry | Self::Mesh => (2, 2),
|
||
Self::Box => (4, 4),
|
||
Self::Group | Self::Scene => (0, 4096),
|
||
Self::Light => (5, 5),
|
||
Self::Panel => (3, 3),
|
||
_ => (0, 0),
|
||
}
|
||
}
|
||
/// 列出本构造器的参数类型名称,供签名安装与源调用检查使用。
|
||
pub fn parameters(self) -> &'static [&'static str] {
|
||
match self {
|
||
Self::Vec3 | Self::Triangle => &["Number", "Number", "Number"],
|
||
Self::Geometry => &["ObjectList", "ObjectList"],
|
||
Self::Mesh => &["Geometry3D", "String"],
|
||
Self::Box => &["Number", "Number", "Number", "String"],
|
||
Self::Light => &["Number", "Number", "Number", "String", "Number"],
|
||
Self::Panel => &["Number", "Number", "Block"],
|
||
_ => &[],
|
||
}
|
||
}
|
||
/// 标记构造器是否接收数量可变的子对象。
|
||
pub fn variadic(self) -> bool {
|
||
matches!(self, Self::Group | Self::Scene)
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
/// 托管 3D 节点的名义种类,防止仅有同名字段的任意对象冒充场景节点。
|
||
pub enum NodeKind {
|
||
Vector,
|
||
Triangle,
|
||
Mesh,
|
||
Group,
|
||
Scene,
|
||
Light,
|
||
Perspective,
|
||
Orthographic,
|
||
Orbit,
|
||
Panel,
|
||
}
|
||
#[derive(Debug)]
|
||
/// 允许普通属性的 3D 标记 payload;数值字段仍由托管属性系统拥有。
|
||
pub struct Node(pub NodeKind);
|
||
impl ObjectPayload for Node {
|
||
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
|
||
fn as_any(&self) -> &dyn std::any::Any {
|
||
self
|
||
}
|
||
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
|
||
fn kind_name(&self) -> &'static str {
|
||
"scene-3d-object"
|
||
}
|
||
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
|
||
fn reference_assignment_only(&self) -> bool {
|
||
true
|
||
}
|
||
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
|
||
fn allows_attributes(&self) -> bool {
|
||
true
|
||
}
|
||
}
|
||
#[derive(Debug)]
|
||
/// 托管不可变网格包装,顶点和三角形数值已经复制为原生 Arc 数据。
|
||
pub struct Geometry(pub Arc<scene3d::Geometry>);
|
||
impl ObjectPayload for Geometry {
|
||
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
|
||
fn as_any(&self) -> &dyn std::any::Any {
|
||
self
|
||
}
|
||
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
|
||
fn kind_name(&self) -> &'static str {
|
||
"geometry-3d"
|
||
}
|
||
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
|
||
fn reference_assignment_only(&self) -> bool {
|
||
true
|
||
}
|
||
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
|
||
fn allows_attributes(&self) -> bool {
|
||
true
|
||
}
|
||
}
|
||
/// 统一构造本模块的参数错误,让调用方停止处理无效输入。
|
||
fn invalid(message: &'static str) -> VmError {
|
||
VmError::InvalidArgument(message)
|
||
}
|
||
/// 把源 Value 转换为受检查的托管对象引用,拒绝非对象输入。
|
||
fn object_ref(value: &Value) -> Result<ObjectRef, VmError> {
|
||
if let Value::Object(object) = value {
|
||
Ok(*object)
|
||
} else {
|
||
Err(invalid("3D field requires an object"))
|
||
}
|
||
}
|
||
/// 在源 Value 与所需数值表示之间转换,并沿用本调用的有限值/范围检查。
|
||
fn number(value: &Value) -> Result<f32, VmError> {
|
||
crate::scroll::coordinate(value)
|
||
}
|
||
/// 把当前源值或文本选择解码成此调用需要的文本表示。
|
||
fn text(value: &Value) -> Result<String, VmError> {
|
||
if let Value::Text(text) = value {
|
||
Ok(text.clone())
|
||
} else {
|
||
Err(invalid("3D field requires text"))
|
||
}
|
||
}
|
||
/// 把经过转换的数值写回指定托管字段,仍通过 VM/NativeContext 的检查入口。
|
||
fn set_number(
|
||
cx: &mut NativeContext<'_>,
|
||
object: ObjectRef,
|
||
name: &str,
|
||
value: f32,
|
||
) -> Result<(), VmError> {
|
||
cx.set_attr(object, name, crate::native_visual::value(value))
|
||
}
|
||
/// 解析颜色值并检查其满足当前原生绘制约定。
|
||
fn color(value: &str) -> Result<[f32; 3], VmError> {
|
||
// 3D 不透明材质拒绝半透明颜色,转换为 [0,1] RGB 数值;普通二维 UI 的 alpha 不受这里限制。
|
||
let color = crate::document::parse_color(value).map_err(|_| invalid("invalid 3D color"))?;
|
||
if color.alpha != 255 {
|
||
return Err(invalid("3D opaque material color requires full alpha"));
|
||
}
|
||
Ok([
|
||
color.red as f32 / 255.,
|
||
color.green as f32 / 255.,
|
||
color.blue as f32 / 255.,
|
||
])
|
||
}
|
||
|
||
/// 按构造器建立对应托管 3D 类型,检查几何输入并安装默认属性。
|
||
pub fn allocate(
|
||
cx: &mut NativeContext<'_>,
|
||
desktop: ObjectRef,
|
||
definition: ObjectRef,
|
||
constructor: Constructor,
|
||
args: &[Value],
|
||
) -> Result<ObjectRef, VmError> {
|
||
// 入口假设桥接工厂已按 arity/类型检查 args;Geometry 特殊地复制缓冲并提前返回,其余创建可编辑标记节点。
|
||
let kind = match constructor {
|
||
Constructor::Vec3 => NodeKind::Vector,
|
||
Constructor::Triangle => NodeKind::Triangle,
|
||
Constructor::Mesh | Constructor::Box => NodeKind::Mesh,
|
||
Constructor::Group => NodeKind::Group,
|
||
Constructor::Scene => NodeKind::Scene,
|
||
Constructor::Light => NodeKind::Light,
|
||
Constructor::Perspective => NodeKind::Perspective,
|
||
Constructor::Orthographic => NodeKind::Orthographic,
|
||
Constructor::Orbit => NodeKind::Orbit,
|
||
Constructor::Panel => NodeKind::Panel,
|
||
Constructor::Geometry => {
|
||
// Geometry 构造只接受受控 ObjectList,逐成员验证 Vec3 payload 并复制数值;以后改源 Vec3 不会改已建几何。
|
||
let vertices = object_list::items(cx.store(), object_ref(&args[0])?)?
|
||
.iter()
|
||
.map(|&item| {
|
||
let p = cx.store();
|
||
if p.payload::<Node>(item, "Vec3")?.0 != NodeKind::Vector {
|
||
return Err(invalid("geometry vertices require Vec3"));
|
||
}
|
||
Ok(Vec3::new(
|
||
number(&p.get_attr(item, "x")?)?,
|
||
number(&p.get_attr(item, "y")?)?,
|
||
number(&p.get_attr(item, "z")?)?,
|
||
))
|
||
})
|
||
.collect::<Result<Vec<_>, VmError>>()?;
|
||
let triangles = object_list::items(cx.store(), object_ref(&args[1])?)?
|
||
.iter()
|
||
.map(|&item| {
|
||
if cx.store().payload::<Node>(item, "Triangle3D")?.0 != NodeKind::Triangle {
|
||
return Err(invalid("geometry indices require Triangle3D"));
|
||
}
|
||
let mut triangle = [0; 3];
|
||
// 索引先从 Number 检查非负整数,再转 u32;是否越出顶点范围在整份 geometry.valid 校验。
|
||
for (index, name) in ["a", "b", "c"].into_iter().enumerate() {
|
||
let value = number(&cx.store().get_attr(item, name)?)?;
|
||
if value < 0. || value.fract() != 0. {
|
||
return Err(invalid("triangle indices must be nonnegative integers"));
|
||
}
|
||
triangle[index] = value as u32;
|
||
}
|
||
Ok(triangle)
|
||
})
|
||
.collect::<Result<Vec<_>, VmError>>()?;
|
||
let geometry = scene3d::Geometry {
|
||
vertices,
|
||
triangles,
|
||
uv: vec![],
|
||
};
|
||
// 缓存为原生 Arc 前统一验证顶点/三角形预算与下标范围,避免渲染线程再接触源缓冲对象。
|
||
if !geometry.valid() {
|
||
return Err(invalid(
|
||
"invalid Geometry3D buffers or geometry budget exceeded",
|
||
));
|
||
}
|
||
let object = cx.allocate(Geometry(Arc::new(geometry)))?;
|
||
cx.attach_type(object, definition)?;
|
||
return Ok(object);
|
||
}
|
||
};
|
||
let instance = cx.allocate(Node(kind))?;
|
||
cx.attach_type(instance, definition)?;
|
||
match kind {
|
||
NodeKind::Vector | NodeKind::Triangle => {
|
||
for (name, value) in (if kind == NodeKind::Vector {
|
||
["x", "y", "z"]
|
||
} else {
|
||
["a", "b", "c"]
|
||
})
|
||
.into_iter()
|
||
.zip(args)
|
||
{
|
||
set_number(cx, instance, name, number(value)?)?;
|
||
}
|
||
}
|
||
NodeKind::Mesh => {
|
||
let (geometry, material) = if matches!(constructor, Constructor::Box) {
|
||
let (w, h, d) = (number(&args[0])?, number(&args[1])?, number(&args[2])?);
|
||
// Box 允许零尺寸产生退化面,后续光栅/拾取跳过退化三角形;负尺寸在构造入口拒绝。
|
||
if w < 0. || h < 0. || d < 0. {
|
||
return Err(invalid("Box3D dimensions must be nonnegative"));
|
||
}
|
||
let geometry =
|
||
cx.allocate(Geometry(Arc::new(scene3d::Geometry::cuboid(w, h, d))))?;
|
||
crate::ui_bridge::attach_desktop_type(cx, geometry, "Geometry3D", desktop)?;
|
||
(geometry, text(&args[3])?)
|
||
} else {
|
||
(object_ref(&args[0])?, text(&args[1])?)
|
||
};
|
||
cx.store().payload::<Geometry>(geometry, "Geometry3D")?;
|
||
color(&material)?;
|
||
cx.set_attr(instance, "geometry", Value::Object(geometry))?;
|
||
cx.set_attr(instance, "color", Value::Text(material))?;
|
||
}
|
||
// 孩子只接受 Mesh/Group/Light/Panel 标记,不允许把相机、控制器或任意 Object 放进场景组成。
|
||
NodeKind::Group | NodeKind::Scene => {
|
||
let children = args.iter().map(object_ref).collect::<Result<Vec<_>, _>>()?;
|
||
for child in &children {
|
||
if !matches!(
|
||
cx.store().payload::<Node>(*child, "3D node")?.0,
|
||
NodeKind::Mesh | NodeKind::Group | NodeKind::Light | NodeKind::Panel
|
||
) {
|
||
return Err(invalid(
|
||
"Scene3D/Group3D children require meshes, groups or lights",
|
||
));
|
||
}
|
||
}
|
||
// 托管 children 列表拥有子节点;Node payload 自身只是标记,属性拥有边由 VM 正常追踪。
|
||
let children = object_list::collection(cx, children, desktop)?;
|
||
cx.set_attr(instance, "children", Value::Object(children))?;
|
||
if kind == NodeKind::Scene {
|
||
set_number(cx, instance, "ambient", 0.25)?;
|
||
cx.set_attr(instance, "background", Value::Text("#F1F3F6".into()))?;
|
||
}
|
||
}
|
||
NodeKind::Light => {
|
||
for (name, value) in ["directionX", "directionY", "directionZ"]
|
||
.into_iter()
|
||
.zip(args)
|
||
{
|
||
set_number(cx, instance, name, number(value)?)?;
|
||
}
|
||
color(&text(&args[3])?)?;
|
||
cx.set_attr(instance, "color", args[3].clone())?;
|
||
set_number(cx, instance, "intensity", number(&args[4])?)?;
|
||
}
|
||
// 世界宽高与 UI 像素分辨率独立:初始纹理 512×320,content 是普通 Block 图,稍后参与独立有限布局。
|
||
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.),
|
||
("y", 0.),
|
||
("z", 5.),
|
||
("targetX", 0.),
|
||
("targetY", 0.),
|
||
("targetZ", 0.),
|
||
("upX", 0.),
|
||
("upY", 1.),
|
||
("upZ", 0.),
|
||
("near", 0.1),
|
||
("far", 1000.),
|
||
("fov", 50.),
|
||
("height", 5.),
|
||
] {
|
||
set_number(cx, instance, name, value)?;
|
||
}
|
||
}
|
||
NodeKind::Orbit => {
|
||
set_number(cx, instance, "rotationSpeed", 0.005)?;
|
||
set_number(cx, instance, "panSpeed", 1.)?;
|
||
}
|
||
}
|
||
// 只有可放置节点安装 TRS;相机用 position/target/up,方向光用方向向量,不复用网格欧拉角字段。
|
||
if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
|
||
for (name, value) in [
|
||
("x", 0.),
|
||
("y", 0.),
|
||
("z", 0.),
|
||
("rotationX", 0.),
|
||
("rotationY", 0.),
|
||
("rotationZ", 0.),
|
||
("scaleX", 1.),
|
||
("scaleY", 1.),
|
||
("scaleZ", 1.),
|
||
] {
|
||
set_number(cx, instance, name, value)?;
|
||
}
|
||
}
|
||
Ok(instance)
|
||
}
|
||
|
||
/// 快照字段读取器,同时记录实际观察到的对象/属性依赖。
|
||
struct Reader<'a> {
|
||
store: &'a ObjectStore,
|
||
reads: HashSet<(ObjectRef, String)>,
|
||
}
|
||
impl Reader<'_> {
|
||
/// 读取字段并登记依赖,使后续字段变更能够使 3D 快照失效。
|
||
fn value(&mut self, object: ObjectRef, name: &str) -> Result<Value, VmError> {
|
||
// 读取前登记精确对象/属性依赖,HashSet 去重;返回给视觉缓存后,相关字段变化才能驱动重建。
|
||
self.reads.insert((object, name.into()));
|
||
self.store.get_attr(object, name)
|
||
}
|
||
/// 在源 Value 与所需数值表示之间转换,并沿用本调用的有限值/范围检查。
|
||
fn number(&mut self, object: ObjectRef, name: &str) -> Result<f32, VmError> {
|
||
number(&self.value(object, name)?)
|
||
}
|
||
/// 连续读取三个数值字段,组成位置、旋转或缩放向量。
|
||
fn vector(&mut self, object: ObjectRef, names: [&str; 3]) -> Result<Vec3, VmError> {
|
||
Ok(Vec3::new(
|
||
self.number(object, names[0])?,
|
||
self.number(object, names[1])?,
|
||
self.number(object, names[2])?,
|
||
))
|
||
}
|
||
/// 读取并校验透视或正交摄像机字段,生成不持有 VM 引用的投影描述。
|
||
fn camera(&mut self, object: ObjectRef) -> Result<Camera, VmError> {
|
||
// 先验证宿主相机种类,再按投影策略读取 fov 或 height;不把有同名字段的对象当相机。
|
||
let projection = match self.store.payload::<Node>(object, "3D camera")?.0 {
|
||
NodeKind::Perspective => Projection::Perspective {
|
||
fov: self.number(object, "fov")?,
|
||
},
|
||
NodeKind::Orthographic => Projection::Orthographic {
|
||
height: self.number(object, "height")?,
|
||
},
|
||
_ => {
|
||
return Err(invalid(
|
||
"Viewport3D requires a PerspectiveCamera or OrthographicCamera",
|
||
));
|
||
}
|
||
};
|
||
let camera = Camera {
|
||
position: self.vector(object, ["x", "y", "z"])?,
|
||
target: self.vector(object, ["targetX", "targetY", "targetZ"])?,
|
||
up: self.vector(object, ["upX", "upY", "upZ"])?,
|
||
near: self.number(object, "near")?,
|
||
far: self.number(object, "far")?,
|
||
projection,
|
||
};
|
||
if !camera.valid() {
|
||
return Err(invalid("invalid 3D camera basis or projection range"));
|
||
}
|
||
Ok(camera)
|
||
}
|
||
}
|
||
|
||
/// 从场景中提取的有限 UI 根,携带稳定面板 key 和逻辑排版尺寸。
|
||
pub struct PanelMount {
|
||
pub key: u64,
|
||
pub content: ObjectRef,
|
||
pub size: crate::layout::Size,
|
||
}
|
||
// 三部分分别是可跨线程的不可变 View、VM 内缓存用的属性依赖、仍由 VM 驱动布局的面板 Block 根。
|
||
pub type Snapshot = (
|
||
Arc<scene3d::View>,
|
||
Vec<(ObjectRef, String)>,
|
||
Vec<PanelMount>,
|
||
);
|
||
/// 将当前托管或可变状态提取为后续阶段使用的派生表示。
|
||
pub fn snapshot(
|
||
store: &ObjectStore,
|
||
scene: ObjectRef,
|
||
camera: ObjectRef,
|
||
) -> Result<Snapshot, VmError> {
|
||
snapshot_reusing(store, scene, camera, None)
|
||
}
|
||
/// 遍历场景并记录字段依赖;如果世界数据未变则复用不可变场景和 BVH,只替换摄像机视图。
|
||
pub fn snapshot_reusing(
|
||
store: &ObjectStore,
|
||
scene: ObjectRef,
|
||
camera: ObjectRef,
|
||
reuse: Option<Arc<scene3d::Scene>>,
|
||
) -> Result<Snapshot, VmError> {
|
||
if store.payload::<Node>(scene, "Scene3D")?.0 != NodeKind::Scene {
|
||
return Err(invalid("Viewport3D requires a Scene3D"));
|
||
}
|
||
let mut reader = Reader {
|
||
store,
|
||
reads: HashSet::new(),
|
||
};
|
||
let camera = reader.camera(camera)?;
|
||
let ambient = reader.number(scene, "ambient")?;
|
||
if !(0.0..=1.0).contains(&ambient) {
|
||
return Err(invalid("Scene3D.ambient expects 0 through 1"));
|
||
}
|
||
let background = color(&text(&reader.value(scene, "background")?)?)?;
|
||
let mut output = scene3d::Scene {
|
||
meshes: Vec::new(),
|
||
lights: Vec::new(),
|
||
ambient,
|
||
background,
|
||
acceleration: Arc::default(),
|
||
};
|
||
// 显式进入/退出栈保存节点、父世界矩阵、退出标记与路径 key;path 仅追踪祖先,因此允许共享子树多次出现。
|
||
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;
|
||
let mut vertices = 0;
|
||
while let Some((object, parent, finish, key)) = work.pop() {
|
||
if finish {
|
||
path.remove(&object);
|
||
continue;
|
||
}
|
||
visits += 1;
|
||
// 预算按展开出现次数,重复共享同一网格也消耗实例/顶点/三角形工作,不能只数不同对象身份。
|
||
if visits > 4096 {
|
||
return Err(VmError::ExecutionLimit("3D scene occurrences"));
|
||
}
|
||
if !path.insert(object) {
|
||
return Err(invalid("cyclic 3D scene graph"));
|
||
}
|
||
work.push((object, parent, true, key));
|
||
let kind = store.payload::<Node>(object, "3D node")?.0;
|
||
let world = if matches!(kind, NodeKind::Mesh | NodeKind::Group | NodeKind::Panel) {
|
||
// 局部先缩放、旋转、平移,再乘父 world;Scene/Light 不新增 TRS,方向光仍受祖先 Group 变换。
|
||
parent.compose(Matrix::trs(
|
||
reader.vector(object, ["x", "y", "z"])?,
|
||
reader.vector(object, ["rotationX", "rotationY", "rotationZ"])?,
|
||
reader.vector(object, ["scaleX", "scaleY", "scaleZ"])?,
|
||
))
|
||
} else {
|
||
parent
|
||
};
|
||
match kind {
|
||
NodeKind::Scene | NodeKind::Group => {
|
||
let list = object_ref(&reader.value(object, "children")?)?;
|
||
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 包含父 key、当前孩子索引和托管身份,区分同一 Panel 节点在不同路径的出现。
|
||
// 此 key 与普通 Block slot 不同,场景列表重排会改变路径身份。
|
||
key.hash(&mut hasher);
|
||
index.hash(&mut hasher);
|
||
child.hash(&mut hasher);
|
||
work.push((*child, world, false, hasher.finish()));
|
||
}
|
||
}
|
||
NodeKind::Mesh => {
|
||
let geometry = object_ref(&reader.value(object, "geometry")?)?;
|
||
let geometry = store.payload::<Geometry>(geometry, "Geometry3D")?.0.clone();
|
||
// 每次 mesh 出现都累计完整几何,Arc 共享只节约存储,不减少本帧实例绘制工作预算。
|
||
triangles += geometry.triangles.len();
|
||
vertices += geometry.vertices.len();
|
||
if vertices > 262_144 {
|
||
return Err(VmError::ExecutionLimit("3D scene vertices"));
|
||
}
|
||
if triangles > scene3d::MAX_TRIANGLES {
|
||
return Err(VmError::ExecutionLimit("3D scene triangles"));
|
||
}
|
||
let material = color(&text(&reader.value(object, "color")?)?)?;
|
||
output.meshes.push(scene3d::Mesh {
|
||
identity: object.to_string(),
|
||
geometry,
|
||
world,
|
||
color: material,
|
||
panel: None,
|
||
});
|
||
}
|
||
NodeKind::Panel => {
|
||
// Arrangement slots cross Endor's signed integer API. A raw
|
||
// u64 hash can turn negative when native Bounds are created.
|
||
// Bounds.slot 经有符号整数 API 传递,清最高位避免变负;仍显式检测碰撞,不能假设哈希必然唯一。
|
||
let key = key & i64::MAX as u64;
|
||
if panels.iter().any(|panel: &PanelMount| panel.key == key) {
|
||
return Err(invalid("colliding 3D UI occurrence identities"));
|
||
}
|
||
// 有限面板根数量另限 64;每个面板还有独立像素分辨率限制和递归纹理总预算。
|
||
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")?)?)?;
|
||
// 面板平面以中心为原点,顶点 y 向上,UV 左上为 (0,0);两三角形共用四个角点。
|
||
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,
|
||
}),
|
||
});
|
||
// 同时把普通 UI 根交给宿主布局,scene Mesh 先只带分辨率/背景,surface 由后续 panel::compose 装配。
|
||
panels.push(PanelMount {
|
||
key,
|
||
content,
|
||
size: crate::layout::Size {
|
||
width: ui_width,
|
||
height: ui_height,
|
||
},
|
||
});
|
||
}
|
||
NodeKind::Light => {
|
||
if output.lights.len() >= 32 {
|
||
return Err(VmError::ExecutionLimit("3D scene lights"));
|
||
}
|
||
let direction =
|
||
reader.vector(object, ["directionX", "directionY", "directionZ"])?;
|
||
// 用两点之差撤销父矩阵平移,仅保留线性部分对方向的影响,再归一化;零方向拒绝。
|
||
let direction = (world.point(direction) - world.point(Vec3::default()))
|
||
.normalized()
|
||
.ok_or(invalid("light direction cannot be zero"))?;
|
||
let color = color(&text(&reader.value(object, "color")?)?)?;
|
||
let intensity = reader.number(object, "intensity")?;
|
||
if !(0.0..=32.0).contains(&intensity) {
|
||
return Err(invalid("light intensity expects 0 through 32"));
|
||
}
|
||
output.lights.push(scene3d::Light {
|
||
direction,
|
||
color,
|
||
intensity,
|
||
});
|
||
}
|
||
_ => return Err(invalid("invalid node in 3D scene graph")),
|
||
}
|
||
}
|
||
// 完整世界值相等时复用旧 Scene/BVH,单独换 camera 生成新 View;不相等才重建世界空间索引。
|
||
let scene = if let Some(scene) = reuse.filter(|scene| **scene == output) {
|
||
scene
|
||
} else {
|
||
output.acceleration = Arc::new(scene3d::spatial::Index::build(&output.meshes));
|
||
Arc::new(output)
|
||
};
|
||
let view = Arc::new(scene3d::View { scene, camera });
|
||
// 提取各项之后仍做完整视图校验,覆盖累计世界变换、光照、面板及整体资源不变量。
|
||
if !view.valid() {
|
||
return Err(invalid("invalid 3D scene snapshot"));
|
||
}
|
||
Ok((view, reader.reads.into_iter().collect(), panels))
|
||
}
|
||
|
||
/// 把视口中的指针射线结果转换成 RayHit3D,关联实际托管网格和交点数据。
|
||
pub fn pick(
|
||
cx: &mut NativeContext<'_>,
|
||
desktop: ObjectRef,
|
||
mount: &crate::mount::Mount,
|
||
point: crate::geometry::Point,
|
||
) -> Result<Value, VmError> {
|
||
if mount.layout.is_some() {
|
||
return Err(invalid("pick3D requires a committed viewport"));
|
||
}
|
||
let (_, data) = crate::block::resolve(cx.store(), mount.block)?;
|
||
let data = crate::block::visual_data(cx.store(), data)?;
|
||
if !matches!(data.kind, crate::block::Kind::Viewport3D { .. }) {
|
||
return Err(invalid("pick3D requires a Viewport3D"));
|
||
}
|
||
// 先做出现/面板遮挡和裁剪命中,未命中直接 Nil;即使场景射线有交点也不能点穿外层遮挡。
|
||
if !mount.geometry.contains(point) {
|
||
return Ok(Value::Nil);
|
||
}
|
||
let node = crate::block::snapshot(cx.store(), mount.block)?;
|
||
let inset = crate::layout::insets(&node);
|
||
let Some(point) = mount.geometry.logical_point(point) else {
|
||
return Ok(Value::Nil);
|
||
};
|
||
// 从布局盒扣 inset 得到实际内容视口,再把逻辑点归一化;零面积视口没有有效投影。
|
||
let (width, height) = (
|
||
(mount.geometry.width - inset.horizontal()).max(0.),
|
||
(mount.geometry.height - inset.vertical()).max(0.),
|
||
);
|
||
if width <= 0. || height <= 0. {
|
||
return Ok(Value::Nil);
|
||
}
|
||
let (view, reads, _) = snapshot(
|
||
cx.store(),
|
||
data.scene3d.ok_or(invalid("missing Scene3D"))?,
|
||
data.camera.ok_or(invalid("missing 3D camera"))?,
|
||
)?;
|
||
let hit = view.pick(
|
||
(point.x - mount.geometry.x - inset.left) / width,
|
||
(point.y - mount.geometry.y - inset.top) / height,
|
||
width / height,
|
||
);
|
||
let Some(hit) = hit else {
|
||
return Ok(Value::Nil);
|
||
};
|
||
// 原生 Hit.identity 只带文本,通过本次实际读取的托管身份重新关联节点;渲染器本身从不解引用 VM 对象。
|
||
let mesh = reads
|
||
.iter()
|
||
.find_map(|(object, _)| (object.to_string() == hit.identity).then_some(*object))
|
||
.ok_or(invalid("picked mesh is unavailable"))?;
|
||
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",
|
||
crate::native_visual::value(hit.distance),
|
||
)?;
|
||
cx.set_attr(
|
||
result,
|
||
"triangle",
|
||
Value::Number((hit.triangle as i64).into()),
|
||
)?;
|
||
// 交点、法线、重心权重都包装为名义 Vec3,结果对象通过普通属性强持有它们。
|
||
for (name, vector) in [
|
||
("point", hit.point),
|
||
("normal", hit.normal),
|
||
(
|
||
"barycentric",
|
||
Vec3::new(hit.barycentric[0], hit.barycentric[1], hit.barycentric[2]),
|
||
),
|
||
] {
|
||
let definition = crate::ui_bridge::desktop_type(cx.store(), "Vec3", desktop)?;
|
||
let vector = allocate(
|
||
cx,
|
||
desktop,
|
||
definition,
|
||
Constructor::Vec3,
|
||
&[
|
||
crate::native_visual::value(vector.x),
|
||
crate::native_visual::value(vector.y),
|
||
crate::native_visual::value(vector.z),
|
||
],
|
||
)?;
|
||
cx.set_attr(result, name, Value::Object(vector))?;
|
||
}
|
||
Ok(Value::Object(result))
|
||
}
|
||
|
||
#[derive(Debug)]
|
||
/// 指针拾取的中间结果,保留交点与所属实例信息供 Event/RayHit3D 使用。
|
||
pub struct PointerPick {
|
||
pub mount: ObjectRef,
|
||
pub desktop: ObjectRef,
|
||
pub point: crate::geometry::Point,
|
||
}
|
||
|
||
/// The default controller is replaceable; camera data has no dependency on it.
|
||
/// 默认 OrbitController 根据已解码的 CameraGesture 更新相机,处理轨道、平移和缩放;可由源控制器替换。
|
||
pub fn control(
|
||
cx: &mut NativeContext<'_>,
|
||
controller: ObjectRef,
|
||
camera_ref: ObjectRef,
|
||
gesture: ObjectRef,
|
||
) -> Result<(), VmError> {
|
||
if cx.store().payload::<Node>(controller, "OrbitController")?.0 != NodeKind::Orbit {
|
||
return Err(invalid("invalid orbit controller"));
|
||
}
|
||
let mut reader = Reader {
|
||
store: cx.store(),
|
||
reads: HashSet::new(),
|
||
};
|
||
let camera = reader.camera(camera_ref)?;
|
||
let dx = reader.number(gesture, "dx")?;
|
||
let dy = reader.number(gesture, "dy")?;
|
||
let kind = text(&reader.value(gesture, "kind")?)?;
|
||
// 默认轨道控制围绕 target 使用 position-target 偏移和半径;相机有效性保证观察方向不退化。
|
||
let offset = camera.position - camera.target;
|
||
let radius = offset.length();
|
||
let mut position = camera.position;
|
||
let mut target = camera.target;
|
||
match kind.as_str() {
|
||
"scene-orbit" => {
|
||
let speed = reader.number(controller, "rotationSpeed")?;
|
||
if !(0.0..=1.0).contains(&speed) {
|
||
return Err(invalid("rotationSpeed expects 0 through 1"));
|
||
}
|
||
let up = camera
|
||
.up
|
||
.normalized()
|
||
.ok_or(invalid("camera up cannot be zero"))?;
|
||
// 将偏移分解为 up 方向和水平面方向,用水平旋转更新 yaw、asin(vertical) 更新 pitch。
|
||
let vertical = (offset.dot(up) / radius).clamp(-1., 1.);
|
||
let horizontal = (offset - up * offset.dot(up))
|
||
.normalized()
|
||
.ok_or(invalid("orbit at pole requires a different up vector"))?;
|
||
let (sine, cosine) = (dx * speed).sin_cos();
|
||
let horizontal = horizontal * cosine + up.cross(horizontal) * sine;
|
||
// 俯仰限制在两极内侧 0.01 弧度,避免绕极点时水平基退化并导致轨道跳变。
|
||
let pitch = (vertical.asin() + dy * speed).clamp(
|
||
-std::f32::consts::FRAC_PI_2 + 0.01,
|
||
std::f32::consts::FRAC_PI_2 - 0.01,
|
||
);
|
||
position = target + horizontal * (radius * pitch.cos()) + up * (radius * pitch.sin());
|
||
}
|
||
"scene-pan" => {
|
||
let speed = reader.number(controller, "panSpeed")?;
|
||
if !(0.0..=100.0).contains(&speed) {
|
||
return Err(invalid("panSpeed expects 0 through 100"));
|
||
}
|
||
let height = reader.number(gesture, "height")?.max(1.);
|
||
// 把逻辑像素位移换成世界单位:透视按 target 距离处的可见高度,正交按固定投影高度。
|
||
let units = match camera.projection {
|
||
Projection::Perspective { fov } => {
|
||
2. * radius * (fov.to_radians() / 2.).tan() / height
|
||
}
|
||
Projection::Orthographic { height: extent } => extent / height,
|
||
};
|
||
let basis = camera.basis().ok_or(invalid("invalid camera basis"))?;
|
||
let delta = basis.right * (dx * units * speed) + basis.up * (-dy * units * speed);
|
||
// 平移同时移动 position 和 target,保留观察方向与轨道半径;屏幕 y 向下所以 up 分量取负。
|
||
position = position + delta;
|
||
target = target + delta;
|
||
}
|
||
"scene-zoom" => {
|
||
let factor = reader.number(gesture, "factor")?;
|
||
if !(0.1..=10.0).contains(&factor) {
|
||
return Err(invalid("zoom factor expects 0.1 through 10"));
|
||
}
|
||
// 正交缩放只改投影高度,透视缩放改变到 target 的距离;倍率大于一均表现为拉近。
|
||
if let Projection::Orthographic { height } = camera.projection {
|
||
set_number(
|
||
cx,
|
||
camera_ref,
|
||
"height",
|
||
(height / factor).clamp(0.001, 1_000_000.),
|
||
)?;
|
||
} else {
|
||
let next =
|
||
(radius / factor).clamp(camera.near * 2., camera.far.max(camera.near * 2.));
|
||
position = target + offset * (next / radius);
|
||
}
|
||
}
|
||
_ => return Err(invalid("unsupported 3D camera gesture")),
|
||
}
|
||
// 写回前校验整个计算结果,拒绝超世界范围;控制器通过普通属性更新让后续快照依赖观察变化。
|
||
if !position.valid() || !target.valid() {
|
||
return Err(invalid("camera movement exceeds world budget"));
|
||
}
|
||
for (name, value) in [
|
||
("x", position.x),
|
||
("y", position.y),
|
||
("z", position.z),
|
||
("targetX", target.x),
|
||
("targetY", target.y),
|
||
("targetZ", target.z),
|
||
] {
|
||
set_number(cx, camera_ref, name, value)?;
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// 对允许的 3D 节点累计平移或角度旋转;相机平移同时更新 target,旋转值归一到 [0,360)。
|
||
pub fn transform(
|
||
cx: &mut NativeContext<'_>,
|
||
owner: ObjectRef,
|
||
args: &[Value],
|
||
rotate: bool,
|
||
) -> Result<(), VmError> {
|
||
let kind = cx.store().payload::<Node>(owner, "3D transform target")?.0;
|
||
let camera = matches!(kind, NodeKind::Perspective | NodeKind::Orthographic);
|
||
if !matches!(
|
||
kind,
|
||
NodeKind::Mesh
|
||
| NodeKind::Group
|
||
| NodeKind::Panel
|
||
| NodeKind::Perspective
|
||
| NodeKind::Orthographic
|
||
) || rotate && camera
|
||
{
|
||
return Err(invalid("unsupported 3D transform target"));
|
||
}
|
||
// 旋转增量作用欧拉角,平移增量作用位置;相机不接受本接口的欧拉角旋转。
|
||
let names = if rotate {
|
||
["rotationX", "rotationY", "rotationZ"]
|
||
} else {
|
||
["x", "y", "z"]
|
||
};
|
||
// 先收集并验证全部轴再写入,避免验证到第二/三轴才发现越界时已修改前面轴。
|
||
let mut updates = Vec::new();
|
||
for (index, name) in names.into_iter().enumerate() {
|
||
let delta = number(&args[index])?;
|
||
let value = number(&cx.store().get_attr(owner, name)?)? + delta;
|
||
if !value.is_finite() || !rotate && value.abs() > 1_000_000. {
|
||
return Err(invalid("3D transform exceeds world budget"));
|
||
}
|
||
updates.push((
|
||
name,
|
||
if rotate {
|
||
// 角度归一到 [0,360),支持负增量而不使用产生负余数的普通取模。
|
||
value.rem_euclid(360.)
|
||
} else {
|
||
value
|
||
},
|
||
));
|
||
// 相机平移同步改 target,保留朝向;不把“移动摄像机”意外变成绕固定目标转动。
|
||
if camera {
|
||
let name = ["targetX", "targetY", "targetZ"][index];
|
||
let value = number(&cx.store().get_attr(owner, name)?)? + delta;
|
||
if value.abs() > 1_000_000. {
|
||
return Err(invalid("camera target exceeds world budget"));
|
||
}
|
||
updates.push((name, value));
|
||
}
|
||
}
|
||
for (name, value) in updates {
|
||
set_number(cx, owner, name, value)?;
|
||
}
|
||
Ok(())
|
||
}
|
||
impl endor_core::NativeCallable for PointerPick {
|
||
/// 输入 Mount 与点击点已捕获,拾取/分发准备步骤不再接受实参。
|
||
fn arity(&self) -> Option<endor_core::CallArity> {
|
||
Some(endor_core::CallArity::exact(0))
|
||
}
|
||
/// 在当前 Mount 中重新射线拾取,构造含真实 mesh 命中的 click Event,再交托管事件系统分发。
|
||
fn invoke(
|
||
&self,
|
||
cx: &mut NativeContext<'_>,
|
||
_: &[Value],
|
||
) -> Result<endor_core::NativeResult, VmError> {
|
||
let mount = cx
|
||
.store()
|
||
.payload::<crate::mount::Mount>(self.mount, "Mount")?
|
||
.clone();
|
||
let hit = pick(cx, self.desktop, &mount, self.point)?;
|
||
let definition = crate::ui_bridge::desktop_type(cx.store(), "Event", self.desktop)?;
|
||
let event = crate::event_dispatch::new_event(cx, definition, "click")?;
|
||
// 点击事件把精确拾取值放到 hit(未击中则 Nil),仍以 Viewport 的 Block/Mount 作为事件传播目标。
|
||
cx.set_attr(event, "hit", hit)?;
|
||
crate::event_dispatch::dispatch(cx, mount.block, event, Some(self.mount), self.desktop)
|
||
}
|
||
}
|