docs: 逐模块细化中文逻辑注释并覆盖测试与示例

This commit is contained in:
2026-11-12 10:31:35 +08:00
parent d29a1be329
commit cd23e70db1
123 changed files with 2664 additions and 249 deletions
+28 -1
View File
@@ -39,10 +39,12 @@ pub struct CameraView {
/// 读取并校验托管 Camera2D 的位置和缩放,生成原生投影描述。
pub fn camera(store: &ObjectStore, object: ObjectRef) -> Result<CameraView, VmError> {
// 先验证实际宿主 payload,避免只有 x/y/zoom 同名字段的普通对象冒充相机。
store.payload::<Camera2D>(object, "Camera2D")?;
let x = crate::scroll::coordinate(&store.get_attr(object, "x")?)?;
let y = crate::scroll::coordinate(&store.get_attr(object, "y")?)?;
let zoom = crate::scroll::coordinate(&store.get_attr(object, "zoom")?)?;
// coordinate 已检查有限性与绝对范围;zoom 还要严格为正并位于专门相机范围,保证可逆变换。
if !(0.01..=100.0).contains(&zoom) {
return Err(VmError::InvalidArgument(
"Camera2D.zoom expects 0.01 through 100",
@@ -63,6 +65,7 @@ pub fn fit(
cx: &mut endor_core::NativeContext<'_>,
mount: &crate::mount::Mount,
) -> Result<(), VmError> {
// 只接受已提交的 CanvasViewport,布局期间的临时几何不能作为 fitView 分配尺寸依据。
if !mount.geometry.canvas_viewport || mount.layout.is_some() {
return Err(VmError::InvalidArgument(
"fitView requires a committed CanvasViewport Mount",
@@ -83,6 +86,7 @@ pub fn fit(
.store()
.payload::<crate::mount::Mount>(root, "Mount")?
.clone();
// 只汇总场景直接子出现的有限边界,沿 sibling 链扫描;不把无限世界或整棵后代图作为布局盒。
let mut next = scene.first_child;
let mut bounds: Option<[f32; 4]> = None;
let mut count = 0;
@@ -95,12 +99,14 @@ pub fn fit(
.upgrade(weak)?
.ok_or(VmError::InvalidArgument("expired scene child"))?;
let child = cx.store().payload::<crate::mount::Mount>(object, "Mount")?;
// 先扣 scene 原点,把孩子绝对布局坐标转为场景相对坐标;此数组存左上/右下,而非宽高。
let rect = [
child.geometry.x - scene.geometry.x,
child.geometry.y - scene.geometry.y,
child.geometry.x - scene.geometry.x + child.geometry.width,
child.geometry.y - scene.geometry.y + child.geometry.height,
];
// 逐个扩展共同包围框,空场景保持 None 并在后面回到单位相机。
bounds = Some(bounds.map_or(rect, |b| {
[
b[0].min(rect[0]),
@@ -113,13 +119,16 @@ pub fn fit(
}
let node = crate::block::snapshot(cx.store(), mount.block)?;
let inset = crate::layout::insets(&node);
// 扣除布局 inset 后才是相机可用的内容区域;负值归零,避免用边框占用部分计算缩放。
let width = (mount.geometry.width - inset.horizontal()).max(0.0);
let height = (mount.geometry.height - inset.vertical()).max(0.0);
let (x, y, zoom) = if let Some(bounds) = bounds {
// 两个轴分别计算可容纳倍率再取较小者;内容跨度增加 48 世界单位形成留白,最终钳到相机范围。
let zoom = (width / (bounds[2] - bounds[0] + 48.0))
.min(height / (bounds[3] - bounds[1] + 48.0))
.clamp(0.01, 100.0);
(
// 让内容中心落在视口中心:相机位置 = 内容中心 - 半个视口的世界尺寸。
(bounds[0] + bounds[2]) / 2.0 - width / (2.0 * zoom),
(bounds[1] + bounds[3]) / 2.0 - height / (2.0 * zoom),
zoom,
@@ -127,6 +136,7 @@ pub fn fit(
} else {
(0.0, 0.0, 1.0)
};
// 最终通过普通属性写入走 VM 变更追踪/绑定机制;共享该相机的其他视口也会观察到更新。
for (name, value) in [("x", x), ("y", y), ("zoom", zoom)] {
cx.set_attr(
camera,
@@ -160,6 +170,7 @@ impl Transform {
Point::new(point.x * self.zoom + self.x, point.y * self.zoom + self.y)
}
/// 将视图点反算回逻辑坐标,供命中和手势锚点计算使用。
// 不在这里额外校验 zoom,调用方必须先保证 valid;零缩放无法反算。
pub fn inverse(self, point: Point) -> Point {
Point::new(
(point.x - self.x) / self.zoom,
@@ -177,6 +188,7 @@ impl Transform {
)
}
/// 将当前变换再放入外层变换,保持绘制与逆向命中的组合顺序一致。
// 组合为 outer(self(point)):内层平移也要乘外层缩放,不能只把两次平移相加。
pub fn then(self, outer: Self) -> Self {
Self {
zoom: self.zoom * outer.zoom,
@@ -184,8 +196,9 @@ impl Transform {
y: self.y * outer.zoom + outer.y,
}
}
/// 检查数值、几何和资源条件是否满足本类型约束,供上层拒绝非法输入。
/// 验证累计二维变换:zoom 有限且在 (0,1000000],平移有限且绝对值不超过一万亿。
pub fn valid(self) -> bool {
// 允许累计平移远大于单个世界坐标范围,因为相机偏移还会乘缩放;同时限制嵌套累计放大。
self.zoom.is_finite()
&& self.zoom > 0.0
&& self.zoom <= 1_000_000.0
@@ -198,6 +211,7 @@ impl Transform {
/// 计算视口与祖先裁剪的共同可见矩形。
fn intersect(a: [f32; 4], b: [f32; 4]) -> [f32; 4] {
// clip 用 [x,y,width,height],分离的矩形返回零面积,不产生负宽高。
let x = a[0].max(b[0]);
let y = a[1].max(b[1]);
[
@@ -222,12 +236,14 @@ pub fn project(
nodes.insert(node.block_id.as_str(), node);
work.extend(node.children().iter().map(|node| node.as_ref()));
}
// 每个出现向孩子传递累计二维变换、当前空间的裁剪和嵌套面板映射;业务布局坐标不被改写。
type Scope = (
Transform,
Option<[f32; 4]>,
Option<Arc<crate::scene3d::panel::Mapping>>,
);
let mut contexts = HashMap::<u64, Scope>::new();
// 保留 next_sibling 查找表,遍历可变 Mount 时仍可按稳定子出现顺序为面板根建立映射。
let next: HashMap<_, _> = frame
.mounts
.iter()
@@ -237,6 +253,7 @@ pub fn project(
HashMap::<u64, (Arc<crate::scene3d::panel::Mapping>, crate::layout::Size)>::new();
for mount in &mut frame.mounts {
let node = nodes[mount.block_id.as_str()];
// 面板根进入独立纹理像素空间,二维变换重置为单位,裁剪重置为面板尺寸;普通节点沿用父上下文。
let (view, clip, panel) = if let Some((panel, size)) = panels.get(&mount.id) {
(
Transform::default(),
@@ -253,6 +270,7 @@ pub fn project(
view.valid(),
"nested viewport transform exceeds numeric budget"
);
// 单位变换省略存储,其余保持为显式 Transform;每轮先清理旧 viewport_clip,避免残留上帧状态。
mount.view = (view != Transform::default()).then_some(view);
mount.panel = panel.clone();
mount.clip = clip;
@@ -263,6 +281,7 @@ pub fn project(
let viewport = if let UiKind::CanvasViewport { camera, .. } = &node.kind {
let x = mount.x + inset.left;
let y = mount.y + inset.top;
// 围绕视口内容原点建立相机变换:原点保持锚定,世界内容先减相机位置再缩放,最后套父变换。
child_view = Transform {
zoom: camera.zoom,
x: x * (1.0 - camera.zoom) - camera.x * camera.zoom,
@@ -282,6 +301,7 @@ pub fn project(
(mount.width - inset.horizontal()).max(0.),
(mount.height - inset.vertical()).max(0.),
))
// 普通节点的 clip_children 裁到边框内侧,独立视口裁内容盒,Scroll 默认裁整个滚动盒。
} else if node.clip_children {
let border = node.border;
Some(Rect::new(
@@ -296,6 +316,7 @@ pub fn project(
None
};
if let Some(rect) = viewport {
// 本视口边界按父变换投影,不能套当前相机的 child_view,否则相机会连自己的视口框一起移动。
let rect = view.rect(rect);
let rect = [rect.x, rect.y, rect.width, rect.height];
child_clip = Some(clip.map_or(rect, |clip| intersect(clip, rect)));
@@ -309,6 +330,7 @@ pub fn project(
..
} = &node.kind
{
// 沿面板映射链限制嵌套深度,防止递归纹理装配和输入逆投影无限展开。
let mut depth = 0;
let mut ancestor = panel.clone();
while let Some(mapping) = ancestor {
@@ -317,6 +339,7 @@ pub fn project(
}
anyhow::ensure!(depth < 8, "3D UI viewport nesting exceeds 8 surfaces");
let mut child = mount.first_child;
// slots、面板尺寸和直接子出现按同序配对;缺少预期子出现时立即报错,不能把内容映射到错误面板。
for (key, size) in node.slots.iter().zip(sizes) {
let id = child.ok_or_else(|| anyhow::anyhow!("missing 3D UI root occurrence"))?;
let mapping = Arc::new(crate::scene3d::panel::Mapping {
@@ -333,6 +356,7 @@ pub fn project(
clip: mount.viewport_clip,
parent: panel.clone(),
});
// 记录待遍历面板根的新上下文;之后走到该孩子时切换纹理空间,不把外层 clip 误当纹理像素。
panels.insert(id, (mapping, *size));
child = next[&id];
}
@@ -340,6 +364,7 @@ pub fn project(
contexts.insert(mount.id, (child_view, child_clip, panel));
}
let mounts: HashMap<_, _> = frame.mounts.iter().map(|mount| (mount.id, mount)).collect();
// 按每条命令的 Mount 归属重建 view/clip,确保源绘制、默认绘制和输入都使用这一轮最终投影。
frame.command_views.clear();
frame.command_clips.clear();
anyhow::ensure!(
@@ -353,6 +378,7 @@ pub fn project(
frame.command_views.push(mount.view);
frame.command_clips.push(mount.clip);
}
// 几何、裁剪和视图信息全部就绪后才建立屏幕宽阶段索引,避免查询旧投影候选。
frame.hit_index = std::sync::Arc::new(spatial::Index::build(&frame.mounts));
Ok(())
}
@@ -382,6 +408,7 @@ mod tests {
y: 20.0,
};
let point = Point::new(-5.0, 100.0);
// 以两次实际点变换验证组合顺序,再检查逆变换和矩形尺寸,避免只验证某一种公式写法。
let composed = inner.then(outer);
assert_eq!(composed.point(point), outer.point(inner.point(point)));
assert_eq!(composed.inverse(composed.point(point)), point);