Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(ui)!: the screen is drawn by the screen, and no camera is consulted

esenginec996804d0b5a
diff --git a/cmake/ESEngineSources.cmake b/cmake/ESEngineSources.cmake
index 9d712b873..c685ff405 100644
--- a/cmake/ESEngineSources.cmake
+++ b/cmake/ESEngineSources.cmake
@@ -24,6 +24,7 @@ set(ESENGINE_SOURCES
${ESENGINE_ROOT}/src/esengine/renderer/graph/RenderGraph.cpp
${ESENGINE_ROOT}/src/esengine/renderer/frame/RenderFrame.cpp
${ESENGINE_ROOT}/src/esengine/renderer/frame/RenderFrameMask.cpp
+ ${ESENGINE_ROOT}/src/esengine/renderer/frame/RenderFrameOverlay.cpp
${ESENGINE_ROOT}/src/esengine/renderer/frame/RenderFrameSubmit.cpp
${ESENGINE_ROOT}/src/esengine/renderer/frame/FrameCapture.cpp
${ESENGINE_ROOT}/src/esengine/renderer/rhi/RenderTarget.cpp
diff --git a/fixtures/scenes/ui-screen-3d.esscene b/fixtures/scenes/ui-screen-3d.esscene
new file mode 100644
index 000000000..c6c97ccdc
--- /dev/null
+++ b/fixtures/scenes/ui-screen-3d.esscene
@@ -0,0 +1,219 @@
+{
+ "version": 4,
+ "name": "A HUD over a PERSPECTIVE camera. There is no world rectangle to lay a screen out in here, which is why this scene draws nothing at all until the screen has a coordinate domain of its own. The camera is driven far away at runtime by the gate that pairs with this one: the world blob leaves the frame and the two corners do not move a pixel.",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 300
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 60,
+ "nearPlane": 0.1,
+ "farPlane": 1000,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "WorldBlob",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 153.96,
+ "y": 86.6,
+ "z": 0
+ },
+ "scale": {
+ "x": 0.4,
+ "y": 0.4,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "color": {
+ "r": 0,
+ "g": 0,
+ "b": 1,
+ "a": 1
+ },
+ "layer": 0,
+ "enabled": true,
+ "opaque": true,
+ "mesh": "/scenes/textured-quad.esmesh"
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Canvas",
+ "parent": null,
+ "children": [
+ 3,
+ 4
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Canvas",
+ "data": {
+ "designResolution": {
+ "x": 1920,
+ "y": 1080
+ },
+ "scaleMode": 1
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "TopLeftQuadrant",
+ "parent": 2,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "width": {
+ "value": 50,
+ "unit": 1
+ },
+ "height": {
+ "value": 50,
+ "unit": 1
+ },
+ "insetTop": {
+ "value": 0,
+ "unit": 0
+ },
+ "insetLeft": {
+ "value": 0,
+ "unit": 0
+ }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": {
+ "visualType": 1,
+ "color": {
+ "r": 1,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 4,
+ "name": "BottomRightQuadrant",
+ "parent": 2,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "width": {
+ "value": 50,
+ "unit": 1
+ },
+ "height": {
+ "value": 50,
+ "unit": 1
+ },
+ "insetBottom": {
+ "value": 0,
+ "unit": 0
+ },
+ "insetRight": {
+ "value": 0,
+ "unit": 0
+ }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": {
+ "visualType": 1,
+ "color": {
+ "r": 0,
+ "g": 1,
+ "b": 0,
+ "a": 1
+ },
+ "enabled": true
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/ui-screen-3d.textures.json b/fixtures/scenes/ui-screen-3d.textures.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/fixtures/scenes/ui-screen-3d.textures.json
@@ -0,0 +1 @@
+{}
diff --git a/fixtures/scenes/ui-screen-order.esscene b/fixtures/scenes/ui-screen-order.esscene
new file mode 100644
index 000000000..1495d0726
--- /dev/null
+++ b/fixtures/scenes/ui-screen-order.esscene
@@ -0,0 +1,366 @@
+{
+ "version": 4,
+ "name": "Screen elements carrying z +/-10000. A screen root's z is layout STORAGE and nothing else: it must not decide whether an element is drawn (a projection that clips it), nor which of two overlapping ones is on top (an order taken from a depth rather than from the tree).",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 540,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "FarBehind",
+ "parent": null,
+ "children": [
+ 101
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": -10000
+ }
+ }
+ },
+ {
+ "type": "Canvas",
+ "data": {
+ "designResolution": {
+ "x": 1920,
+ "y": 1080
+ },
+ "scaleMode": 1
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "id": 101,
+ "name": "FarBehindFill",
+ "parent": 1,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetTop": {
+ "value": 0,
+ "unit": 1
+ },
+ "insetLeft": {
+ "value": 0,
+ "unit": 1
+ },
+ "width": {
+ "value": 33,
+ "unit": 1
+ },
+ "height": {
+ "value": 100,
+ "unit": 1
+ }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": {
+ "visualType": 1,
+ "color": {
+ "r": 1,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "AtZero",
+ "parent": null,
+ "children": [
+ 102
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Canvas",
+ "data": {
+ "designResolution": {
+ "x": 1920,
+ "y": 1080
+ },
+ "scaleMode": 1
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "id": 102,
+ "name": "AtZeroFill",
+ "parent": 2,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetTop": {
+ "value": 0,
+ "unit": 1
+ },
+ "insetLeft": {
+ "value": 33,
+ "unit": 1
+ },
+ "width": {
+ "value": 33,
+ "unit": 1
+ },
+ "height": {
+ "value": 100,
+ "unit": 1
+ }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": {
+ "visualType": 1,
+ "color": {
+ "r": 0,
+ "g": 1,
+ "b": 0,
+ "a": 1
+ },
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "FarAhead",
+ "parent": null,
+ "children": [
+ 103
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10000
+ }
+ }
+ },
+ {
+ "type": "Canvas",
+ "data": {
+ "designResolution": {
+ "x": 1920,
+ "y": 1080
+ },
+ "scaleMode": 1
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "id": 103,
+ "name": "FarAheadFill",
+ "parent": 3,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetTop": {
+ "value": 0,
+ "unit": 1
+ },
+ "insetLeft": {
+ "value": 66,
+ "unit": 1
+ },
+ "width": {
+ "value": 34,
+ "unit": 1
+ },
+ "height": {
+ "value": 100,
+ "unit": 1
+ }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": {
+ "visualType": 1,
+ "color": {
+ "r": 0,
+ "g": 0,
+ "b": 1,
+ "a": 1
+ },
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 4,
+ "name": "LastSibling",
+ "parent": null,
+ "children": [
+ 104
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": -20000
+ }
+ }
+ },
+ {
+ "type": "Canvas",
+ "data": {
+ "designResolution": {
+ "x": 1920,
+ "y": 1080
+ },
+ "scaleMode": 1
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "id": 104,
+ "name": "LastSiblingFill",
+ "parent": 4,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetTop": {
+ "value": 33,
+ "unit": 1
+ },
+ "insetLeft": {
+ "value": 0,
+ "unit": 1
+ },
+ "width": {
+ "value": 33,
+ "unit": 1
+ },
+ "height": {
+ "value": 34,
+ "unit": 1
+ }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": {
+ "visualType": 1,
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "enabled": true
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/ui-screen-order.textures.json b/fixtures/scenes/ui-screen-order.textures.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/fixtures/scenes/ui-screen-order.textures.json
@@ -0,0 +1 @@
+{}
diff --git a/fixtures/scenes/ui-screen-post.esscene b/fixtures/scenes/ui-screen-post.esscene
new file mode 100644
index 000000000..0199da9b4
--- /dev/null
+++ b/fixtures/scenes/ui-screen-post.esscene
@@ -0,0 +1,170 @@
+{
+ "version": 4,
+ "name": "A HUD over a graded scene. The overlay runs AFTER the post chain: a vignette at full strength eats the corners of the WORLD quad behind it, and the badge sitting in the same corner keeps the colour it was authored. The darkened world point is the control \u2014 without it this would pass just as well on a frame with no chain.",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 300
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 60,
+ "nearPlane": 0.1,
+ "farPlane": 1000,
+ "isActive": true,
+ "priority": 0
+ }
+ },
+ {
+ "type": "PostProcessVolume",
+ "data": {
+ "isGlobal": true,
+ "priority": 0,
+ "weight": 1,
+ "effects": [
+ {
+ "type": "vignette",
+ "enabled": true,
+ "uniforms": {
+ "u_intensity": 1.0,
+ "u_softness": 0.1
+ }
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "WorldFill",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 8,
+ "y": 8,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "color": {
+ "r": 0.2,
+ "g": 0.6,
+ "b": 1,
+ "a": 1
+ },
+ "layer": 0,
+ "enabled": true,
+ "opaque": true,
+ "mesh": "/scenes/textured-quad.esmesh"
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Canvas",
+ "parent": null,
+ "children": [
+ 3
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "Canvas",
+ "data": {
+ "designResolution": {
+ "x": 1920,
+ "y": 1080
+ },
+ "scaleMode": 1
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "CornerBadge",
+ "parent": 2,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetTop": {
+ "value": 0,
+ "unit": 0
+ },
+ "insetLeft": {
+ "value": 0,
+ "unit": 0
+ },
+ "width": {
+ "value": 20,
+ "unit": 1
+ },
+ "height": {
+ "value": 20,
+ "unit": 1
+ }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": {
+ "visualType": 1,
+ "color": {
+ "r": 1,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "enabled": true
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/ui-screen-post.textures.json b/fixtures/scenes/ui-screen-post.textures.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/fixtures/scenes/ui-screen-post.textures.json
@@ -0,0 +1 @@
+{}
diff --git a/fixtures/scenes/ui-screen-text.esscene b/fixtures/scenes/ui-screen-text.esscene
new file mode 100644
index 000000000..2ad818e13
--- /dev/null
+++ b/fixtures/scenes/ui-screen-text.esscene
@@ -0,0 +1,167 @@
+{
+ "version": 4,
+ "name": "HUD TEXT over a perspective camera. Glyph quads are submitted by the SDK, not collected by the engine, so they are the one screen primitive that could be left behind in the camera's list while the panel under them moved to the overlay \u2014 and the symptom would be a HUD with a hole in it rather than no HUD at all.",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 300
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 60,
+ "nearPlane": 0.1,
+ "farPlane": 1000,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Canvas",
+ "parent": null,
+ "children": [
+ 3
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "Canvas",
+ "data": {
+ "designResolution": {
+ "x": 1920,
+ "y": 1080
+ },
+ "scaleMode": 1
+ }
+ },
+ {
+ "type": "UINode",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "Panel",
+ "parent": 2,
+ "children": [
+ 4
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetTop": {
+ "value": 0,
+ "unit": 0
+ },
+ "insetLeft": {
+ "value": 0,
+ "unit": 0
+ },
+ "width": {
+ "value": 100,
+ "unit": 1
+ },
+ "height": {
+ "value": 100,
+ "unit": 1
+ }
+ }
+ },
+ {
+ "type": "UIVisual",
+ "data": {
+ "visualType": 1,
+ "color": {
+ "r": 0,
+ "g": 0,
+ "b": 0.6,
+ "a": 1
+ },
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 4,
+ "name": "Label",
+ "parent": 3,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetTop": {
+ "value": 0,
+ "unit": 0
+ },
+ "insetLeft": {
+ "value": 0,
+ "unit": 0
+ },
+ "width": {
+ "value": 100,
+ "unit": 1
+ },
+ "height": {
+ "value": 100,
+ "unit": 1
+ }
+ }
+ },
+ {
+ "type": "Text",
+ "data": {
+ "content": "IIIIIIII",
+ "fontFamily": "sans-serif",
+ "fontSize": 520,
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 0,
+ "a": 1
+ },
+ "align": 1,
+ "verticalAlign": 1,
+ "wordWrap": false
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/ui-screen-text.textures.json b/fixtures/scenes/ui-screen-text.textures.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/fixtures/scenes/ui-screen-text.textures.json
@@ -0,0 +1 @@
+{}
diff --git a/native/host/Host.cpp b/native/host/Host.cpp
index 4fdef5a86..e9ed5d6b5 100644
--- a/native/host/Host.cpp
+++ b/native/host/Host.cpp
@@ -74,6 +74,10 @@ void fallbackFrame(HostState& h) {
const glm::mat4 vp = glm::ortho(0.0f, h.w, 0.0f, h.h);
auto& rf = ctx.require<RenderFrame>();
rf.begin(vp, 0, RenderFrame::PassClear{true, true, kFallbackClear});
+ // One domain here. The screen/world split exists so a frame can draw the two
+ // through different projections, and this frame has no SDK to say what the
+ // screen is — so partitioning would take UI out of the only pass there is.
+ rf.setScreenDomain(nullptr);
rf.collectAll(*h.registry);
rf.flush();
rf.end();
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index a53d920c4..4d087ba2c 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6709,11 +6709,14 @@ width: number
## RenderPipeline — class @experimental
```
addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
+endFrame: () => void
endScreenCapture: () => void
render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
+renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
@@ -6797,7 +6800,7 @@ UIElement = 7
## Renderer — const @experimental
```
-{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
+{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
```
## Replicated — const @experimental
@@ -13051,7 +13054,7 @@ TrailPlugin
## uiHitTestWorld — function @experimental
```
-(world: PickableWorld, ray: WorldRay): Entity | null
+(world: PickableWorld, ray: WorldRay, screenRay?: WorldRay): Entity | null
```
## uiInteractionPlugin — const @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 969c2d2f1..24a119791 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6902,11 +6902,14 @@ width: number
## RenderPipeline — class @experimental
```
addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
+endFrame: () => void
endScreenCapture: () => void
render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
+renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
@@ -6990,7 +6993,7 @@ UIElement = 7
## Renderer — const @experimental
```
-{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
+{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
```
## Replicated — const @experimental
@@ -13294,7 +13297,7 @@ TrailPlugin
## uiHitTestWorld — function @experimental
```
-(world: PickableWorld, ray: WorldRay): Entity | null
+(world: PickableWorld, ray: WorldRay, screenRay?: WorldRay): Entity | null
```
## uiInteractionPlugin — const @experimental
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 93dcdb759..99aca21b2 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6704,11 +6704,14 @@ width: number
## RenderPipeline — class @experimental
```
addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
+endFrame: () => void
endScreenCapture: () => void
render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
+renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
@@ -6792,7 +6795,7 @@ UIElement = 7
## Renderer — const @experimental
```
-{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
+{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
```
## Replicated — const @experimental
@@ -13056,7 +13059,7 @@ TrailPlugin
## uiHitTestWorld — function @experimental
```
-(world: PickableWorld, ray: WorldRay): Entity | null
+(world: PickableWorld, ray: WorldRay, screenRay?: WorldRay): Entity | null
```
## uiInteractionPlugin — const @experimental
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 2c64b58bb..52a08f478 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6950,11 +6950,14 @@ width: number
## RenderPipeline — class @experimental
```
addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
+endFrame: () => void
endScreenCapture: () => void
render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
+renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
@@ -7038,7 +7041,7 @@ UIElement = 7
## Renderer — const @experimental
```
-{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
+{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
```
## Replicated — const @experimental
@@ -13313,7 +13316,7 @@ TrailPlugin
## uiHitTestWorld — function @experimental
```
-(world: PickableWorld, ray: WorldRay): Entity | null
+(world: PickableWorld, ray: WorldRay, screenRay?: WorldRay): Entity | null
```
## uiInteractionPlugin — const @experimental
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 4ef26951f..8a80eb4d8 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -346,6 +346,7 @@ registry_getCanvasEntity: (registry: CppRegistry) => number
registry_getGeneration: (registry: CppRegistry, entity: number) => number
renderer_begin: (matrixPtr: number, targetHandle: number, clearFlags: number, r: number, g: number, b: number, a: number, clearX: number, clearY: number, clearW: number, clearH: number) => void
renderer_beginFrame: (elapsedSec: number) => void
+renderer_beginScreenOverlay: ((projectionPtr: number, vpX: number, vpY: number, vpW: number, vpH: number) => void) | undefined
renderer_captureFrame: ((w: number, h: number) => number) | undefined
renderer_captureNextFrame: () => void
renderer_createSkeletalPreview: (w: number, h: number) => number
@@ -353,6 +354,8 @@ renderer_createTarget: (width: number, height: number, flags: number) => number
renderer_destroySkeletalPreview: (preview: number) => void
renderer_diagnose: () => void
renderer_end: () => void
+renderer_endFrame: (() => void) | undefined
+renderer_endScreenOverlay: ((targetHandle: number) => void) | undefined
renderer_entityVisibleToCamera: ((registry: CppRegistry, entity: number, layer: number, minX: number, minY: number, maxX: number, maxY: number, outVisiblePtr: number) => void) | undefined
renderer_flush: () => void
renderer_getCapturedCameraCount: () => number
@@ -406,6 +409,7 @@ renderer_setTextureParams: (textureId: number, minFilter: number, magFilter: num
renderer_setViewport: (x: number, y: number, w: number, h: number) => void
renderer_setYSortLayers: ((mask: number) => void) | undefined
renderer_submitAll: (registry: CppRegistry, vpX: number, vpY: number, vpW: number, vpH: number) => void
+renderer_submitScreenOverlay: ((registry: CppRegistry) => void) | undefined
renderer_submitSkeletalBatchByEntity: ((registry: CppRegistry, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number, materialId: number) => void) | undefined
renderer_submitSkeletalPreviewBatch: (preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number) => number
renderer_submitTextBatch: ((verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, sdf: number, cullBit: number) => void) | undefined
@@ -437,12 +441,14 @@ uiHitTest_pick: ((registry: CppRegistry, worldX: number, worldY: number) => numb
uiHitTest_pickAll: ((registry: CppRegistry, worldX: number, worldY: number) => number) | undefined
uiHitTest_pickResult: ((index: number) => number) | undefined
uiHitTest_update: (registry: CppRegistry, originX: number, originY: number, originZ: number, dirX: number, dirY: number, dirZ: number) => void
+uiHitTest_updateDomains: ((registry: CppRegistry, worldOriginX: number, worldOriginY: number, worldOriginZ: number, worldDirX: number, worldDirY: number, worldDirZ: number, screenOriginX: number, screenOriginY: number, screenOriginZ: number, screenDirX: number, screenDirY: number, screenDirZ: number) => void) | undefined
uiLayout_update: (registry: CppRegistry, boxLeft: number, boxBottom: number, boxRight: number, boxTop: number, propertyDirty: boolean) => void
uiNode_computedHeight: (registry: CppRegistry, entity: number) => number
uiNode_computedWidth: (registry: CppRegistry, entity: number) => number
uiRenderOrder_update: (registry: CppRegistry) => void
ui_getCullBit: ((registry: CppRegistry, entity: number) => number) | undefined
ui_getRenderOrder: ((registry: CppRegistry, entity: number) => number) | undefined
+ui_isScreenDomain: ((registry: CppRegistry, entity: number) => boolean) | undefined
wasmMemory: WebAssembly.Memory | undefined
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 9c7cd8ace..9e4a00a38 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6711,11 +6711,14 @@ width: number
## RenderPipeline — class @experimental
```
addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
+endFrame: () => void
endScreenCapture: () => void
render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
+renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
@@ -6799,7 +6802,7 @@ UIElement = 7
## Renderer — const @experimental
```
-{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
+{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }
```
## Replicated — const @experimental
@@ -13079,7 +13082,7 @@ TrailPlugin
## uiHitTestWorld — function @experimental
```
-(world: PickableWorld, ray: WorldRay): Entity | null
+(world: PickableWorld, ray: WorldRay, screenRay?: WorldRay): Entity | null
```
## uiInteractionPlugin — const @experimental
diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.ts
index de6cf7d2c..4996f1bc1 100644
--- a/sdk/src/app/app.ts
+++ b/sdk/src/app/app.ts
@@ -19,6 +19,7 @@ import { outputTransformCode, type OutputTransform } from '../postprocess';
import type { BridgeConnectOptions } from '../ecs/bridge/BuiltinBridge';
import { UICameraInfo } from '../ui/core/ui-camera-info';
import { ScreenLayout } from '../ui/core/screen-layout';
+import { ScreenOverlay, defaultScreenOverlay } from '../ui/core/screen-overlay';
import { inputPlugin, Input } from '../input/input';
import { assetPlugin } from '../asset';
import { prefabsPlugin } from '../prefab/prefabServer';
@@ -1708,6 +1709,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
app.setPipeline(new RenderPipeline());
app.insertResource(UICameraInfo, { ...DEFAULT_UI_CAMERA_INFO });
app.insertResource(ScreenLayout, { ...ScreenLayout._default });
+ app.insertResource(ScreenOverlay, defaultScreenOverlay());
app.addPlugin(cameraPlugin(options?.getViewportSize));
app.addPlugin(assetPlugin);
app.addPlugin(prefabsPlugin);
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index 39478e02b..eb35bc999 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -15,8 +15,9 @@ import { cameraBoundsUpdate } from './CameraBounds';
import type { ESEngineModule, CppRegistry } from '../wasm';
import type { World } from '../ecs/world';
import type { Entity } from '../types';
-import { UICameraInfo } from '../ui/core/ui-camera-info';
-import { ScreenLayout, screenLayoutRect } from '../ui/core/screen-layout';
+import { UICameraInfo, type UICameraData } from '../ui/core/ui-camera-info';
+import { ScreenLayout, screenLayoutRect, screenProjection } from '../ui/core/screen-layout';
+import { ScreenOverlay } from '../ui/core/screen-overlay';
import { ProjectionType, SceneOwner, ClearFlags } from '../ecs/component';
import { uiLayoutRect, computeEffectiveOrthoSize, EDITOR_VIEW_ENTITY, type CanvasScale } from './uiLayoutRect';
import { EditorView, DEFAULT_EDITOR_VIEW, editorViewStandoff, editorViewClipFar, editorViewClipNear, type EditorViewData } from './EditorView';
@@ -550,6 +551,44 @@ function resolveCameras(
// UICameraInfo Sync
// =============================================================================
+/**
+ * The aspect the design box is fitted to, when it is NOT the surface's — the
+ * editor's design view lays UI out for the DEVICE it simulates, not the panel
+ * showing it. Zero is every shipped frame. Mirrors uiLayoutRect's editor branch
+ * from the same inputs, so the design frame and the layout cannot disagree.
+ */
+function simulatedScreenAspect(app: App, fit: CanvasScale | null): number {
+ if (!fit || !app.hasResource(EditorView)) return 0;
+ const view = app.getResource(EditorView);
+ if (!view.active) return 0;
+ return view.uiPreviewAspect > 0
+ ? view.uiPreviewAspect
+ : fit.designResolution.x / fit.designResolution.y;
+}
+
+/**
+ * The screen domain, published from the fit and the surface and from NOTHING
+ * else — `screenLayoutRect` has no parameter a camera could reach. Unconditional,
+ * including with no camera at all: a HUD is not something a camera grants.
+ */
+function publishScreenLayout(
+ app: App,
+ module: ESEngineModule | null,
+ cppRegistry: CppRegistry,
+ width: number,
+ height: number,
+): void {
+ if (!app.hasResource(ScreenLayout)) return;
+ const fit = resolveFitSource(app, findCanvasData(module, cppRegistry));
+ const aspect = simulatedScreenAspect(app, fit);
+ Object.assign(
+ app.getResource(ScreenLayout),
+ aspect > 0
+ ? screenLayoutRect(fit, height * aspect, height)
+ : screenLayoutRect(fit, width, height),
+ );
+}
+
function syncUICameraInfo(
app: App,
module: ESEngineModule | null,
@@ -562,6 +601,7 @@ function syncUICameraInfo(
if (!cameras) {
cameras = collectCameras(module, cppRegistry, width, height, undefined, undefined, pool);
}
+ publishScreenLayout(app, module, cppRegistry, width, height);
const uiCam = app.getResource(UICameraInfo);
if (cameras.length > 0) {
const cam = cameras[0];
@@ -591,13 +631,6 @@ function syncUICameraInfo(
// and a shipped build lay UI out in one box.
const previewAspect = app.hasResource(EditorView) ? app.getResource(EditorView).uiPreviewAspect : 0;
const fit = resolveFitSource(app, findCanvasData(module, cppRegistry));
- // The screen domain is published from here because this is where the fit
- // is resolved, and from NOTHING here: `screenLayoutRect` takes the fit and
- // the viewport, and a camera has no way to reach it.
- if (app.hasResource(ScreenLayout)) {
- Object.assign(app.getResource(ScreenLayout),
- screenLayoutRect(fit, uiCam.vpW, uiCam.vpH));
- }
const rect = uiLayoutRect(cam, fit, width, height, previewAspect);
uiCam.worldLeft = rect.left;
uiCam.worldRight = rect.right;
@@ -607,6 +640,56 @@ function syncUICameraInfo(
} else {
uiCam.valid = false;
}
+ publishScreenOverlay(app, width, height, uiCam, cameras);
+}
+
+/**
+ * How the screen domain reaches the framebuffer this frame: {@link
+ * screenProjection} over the whole surface, which is every shipped frame.
+ *
+ * The editor's design VIEW is the one exception: there the screen box is shown
+ * inside the scene so it can be zoomed while it is authored.
+ */
+function publishScreenOverlay(
+ app: App,
+ width: number,
+ height: number,
+ uiCam: UICameraData,
+ cameras: CameraInfo[],
+): void {
+ if (!app.hasResource(ScreenOverlay)) return;
+ const overlay = app.getResource(ScreenOverlay);
+ overlay.surfaceW = width;
+ overlay.surfaceH = height;
+ // A layer any camera shows, this frame shows. `Camera.cullingMask` is a
+ // statement about layers rather than about geometry, so it survives the
+ // screen leaving the cameras' passes.
+ let mask = 0;
+ for (const cam of cameras) mask |= cam.cullingMask ?? 0xFFFFFFFF;
+ overlay.layerMask = (cameras.length > 0 ? mask : 0xFFFFFFFF) >>> 0;
+ const primary = cameras[0];
+
+ if (uiCam.valid && primary?.entity === EDITOR_VIEW_ENTITY) {
+ overlay.projection.set(uiCam.viewProjection);
+ overlay.vpX = uiCam.vpX;
+ overlay.vpY = uiCam.vpY;
+ overlay.vpW = uiCam.vpW;
+ overlay.vpH = uiCam.vpH;
+ overlay.active = true;
+ return;
+ }
+
+ const screen = app.hasResource(ScreenLayout) ? app.getResource(ScreenLayout) : null;
+ if (!screen?.valid) {
+ overlay.active = false;
+ return;
+ }
+ screenProjection(screen, overlay.projection);
+ overlay.vpX = 0;
+ overlay.vpY = 0;
+ overlay.vpW = width;
+ overlay.vpH = height;
+ overlay.active = true;
}
// =============================================================================
@@ -765,6 +848,17 @@ export function cameraPlugin(
pipeline.endScreenCapture();
Renderer.setViewport(0, 0, width, height);
}
+
+ // Last, and outside the camera branch: a frame with no
+ // camera still has a screen. After the post stack, since a
+ // HUD is not world content for an effect to grade.
+ if (app.hasResource(ScreenOverlay)) {
+ pipeline.renderScreenOverlay({ _cpp: cppRegistry },
+ app.getResource(ScreenOverlay));
+ }
+ // ...and now the frame is over, which is when a borrowed
+ // swapchain image goes back.
+ pipeline.endFrame();
}, { remainder: 'wait' });
},
};
diff --git a/sdk/src/ecs/bridge/nativeBindings.ts b/sdk/src/ecs/bridge/nativeBindings.ts
index 9cd5222be..7e6f93dad 100644
--- a/sdk/src/ecs/bridge/nativeBindings.ts
+++ b/sdk/src/ecs/bridge/nativeBindings.ts
@@ -171,6 +171,17 @@ export const RENDERER_OPTIONAL_BINDINGS = {
setDepthLayers: 'es_renderer_setDepthLayers',
/** Camera culling mask; hosts predating it draw every layer, as they always did. */
setCullingMask: 'es_renderer_setCullingMask',
+ /** Closes the frame. A host predating it released the swapchain image at
+ * every camera's end instead, which is where multi-camera and the screen
+ * overlay both fell over — so it is a fix, not only a new call. */
+ endFrame: 'es_renderer_endFrame',
+ /** The frame's screen-space overlay. All four or none: a host with only
+ * some of them would partition the world and then never draw the half it
+ * took out. The glue is generated from the same headers the engine
+ * compiles, so the pass and the partition arrive together. */
+ beginScreenOverlay: 'es_renderer_beginScreenOverlay',
+ submitScreenOverlay: 'es_renderer_submitScreenOverlay',
+ endScreenOverlay: 'es_renderer_endScreenOverlay',
} as const;
/** Whether the host bound the whole frame surface — the gate for the SDK driving
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 226b75ff5..8f00f3cf1 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -110,6 +110,7 @@ export interface NativeEngineApi {
registry_getGeneration?(registry: unknown, entity: number): number;
renderer_begin?(matrixPtr: number, targetHandle: number, clearFlags: number, r: number, g: number, b: number, a: number, clearX: number, clearY: number, clearW: number, clearH: number): void;
renderer_beginFrame?(elapsedSec: number): void;
+ renderer_beginScreenOverlay?(projectionPtr: number, vpX: number, vpY: number, vpW: number, vpH: number): void;
renderer_captureFrame?(w: number, h: number): number;
renderer_captureNextFrame?(): void;
renderer_createSkeletalPreview?(w: number, h: number): number;
@@ -117,6 +118,8 @@ export interface NativeEngineApi {
renderer_destroySkeletalPreview?(preview: number): void;
renderer_diagnose?(): void;
renderer_end?(): void;
+ renderer_endFrame?(): void;
+ renderer_endScreenOverlay?(targetHandle: number): void;
renderer_entityVisibleToCamera?(registry: unknown, entity: number, layer: number, minX: number, minY: number, maxX: number, maxY: number, outVisiblePtr: number): void;
renderer_flush?(): void;
renderer_getCapturedCameraCount?(): number;
@@ -164,6 +167,7 @@ export interface NativeEngineApi {
renderer_setViewport?(x: number, y: number, w: number, h: number): void;
renderer_setYSortLayers?(mask: number): void;
renderer_submitAll?(registry: unknown, vpX: number, vpY: number, vpW: number, vpH: number): void;
+ renderer_submitScreenOverlay?(registry: unknown): void;
renderer_submitSkeletalBatchByEntity?(registry: unknown, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number, materialId: number): void;
renderer_submitSkeletalPreviewBatch?(preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number): number;
renderer_submitTextBatch?(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, sdf: number, cullBit: number): void;
@@ -231,12 +235,14 @@ export interface NativeEngineApi {
uiHitTest_pickAll?(registry: unknown, worldX: number, worldY: number): number;
uiHitTest_pickResult?(index: number): number;
uiHitTest_update?(registry: unknown, originX: number, originY: number, originZ: number, dirX: number, dirY: number, dirZ: number): void;
+ uiHitTest_updateDomains?(registry: unknown, worldOriginX: number, worldOriginY: number, worldOriginZ: number, worldDirX: number, worldDirY: number, worldDirZ: number, screenOriginX: number, screenOriginY: number, screenOriginZ: number, screenDirX: number, screenDirY: number, screenDirZ: number): void;
uiLayout_update?(registry: unknown, boxLeft: number, boxBottom: number, boxRight: number, boxTop: number, propertyDirty: boolean): void;
uiNode_computedHeight?(registry: unknown, entity: number): number;
uiNode_computedWidth?(registry: unknown, entity: number): number;
uiRenderOrder_update?(registry: unknown): void;
ui_getCullBit?(registry: unknown, entity: number): number;
ui_getRenderOrder?(registry: unknown, entity: number): number;
+ ui_isScreenDomain?(registry: unknown, entity: number): boolean;
}
/** Build the API over a host scope (the QuickJS global object; a plain object
@@ -349,6 +355,7 @@ export function createNativeEngineApi(
bind('registry_getGeneration', 'es_registry_getGeneration', true);
bind('renderer_begin', 'es_renderer_begin', false);
bind('renderer_beginFrame', 'es_renderer_beginFrame', false);
+ bind('renderer_beginScreenOverlay', 'es_renderer_beginScreenOverlay', false);
bind('renderer_captureFrame', 'es_renderer_captureFrame', false);
bind('renderer_captureNextFrame', 'es_renderer_captureNextFrame', false);
bind('renderer_createSkeletalPreview', 'es_renderer_createSkeletalPreview', false);
@@ -356,6 +363,8 @@ export function createNativeEngineApi(
bind('renderer_destroySkeletalPreview', 'es_renderer_destroySkeletalPreview', false);
bind('renderer_diagnose', 'es_renderer_diagnose', false);
bind('renderer_end', 'es_renderer_end', false);
+ bind('renderer_endFrame', 'es_renderer_endFrame', false);
+ bind('renderer_endScreenOverlay', 'es_renderer_endScreenOverlay', false);
bind('renderer_entityVisibleToCamera', 'es_renderer_entityVisibleToCamera', true);
bind('renderer_flush', 'es_renderer_flush', false);
bind('renderer_getCapturedCameraCount', 'es_renderer_getCapturedCameraCount', false);
@@ -403,6 +412,7 @@ export function createNativeEngineApi(
bind('renderer_setViewport', 'es_renderer_setViewport', false);
bind('renderer_setYSortLayers', 'es_renderer_setYSortLayers', false);
bind('renderer_submitAll', 'es_renderer_submitAll', true);
+ bind('renderer_submitScreenOverlay', 'es_renderer_submitScreenOverlay', true);
bind('renderer_submitSkeletalBatchByEntity', 'es_renderer_submitSkeletalBatchByEntity', true);
bind('renderer_submitSkeletalPreviewBatch', 'es_renderer_submitSkeletalPreviewBatch', false);
bind('renderer_submitTextBatch', 'es_renderer_submitTextBatch', false);
@@ -470,11 +480,13 @@ export function createNativeEngineApi(
bind('uiHitTest_pickAll', 'es_uiHitTest_pickAll', true);
bind('uiHitTest_pickResult', 'es_uiHitTest_pickResult', false);
bind('uiHitTest_update', 'es_uiHitTest_update', true);
+ bind('uiHitTest_updateDomains', 'es_uiHitTest_updateDomains', true);
bind('uiLayout_update', 'es_uiLayout_update', true);
bind('uiNode_computedHeight', 'es_uiNode_computedHeight', true);
bind('uiNode_computedWidth', 'es_uiNode_computedWidth', true);
bind('uiRenderOrder_update', 'es_uiRenderOrder_update', true);
bind('ui_getCullBit', 'es_ui_getCullBit', true);
bind('ui_getRenderOrder', 'es_ui_getRenderOrder', true);
+ bind('ui_isScreenDomain', 'es_ui_isScreenDomain', true);
return api as NativeEngineApi;
}
diff --git a/sdk/src/ecs/bridge/nativeRenderer.ts b/sdk/src/ecs/bridge/nativeRenderer.ts
index 42301d1d0..e4a4f65ad 100644
--- a/sdk/src/ecs/bridge/nativeRenderer.ts
+++ b/sdk/src/ecs/bridge/nativeRenderer.ts
@@ -39,6 +39,15 @@ function hostCall(scope: Record<string, unknown>, name: string, args: unknown[])
* has exactly one C++ registry, the one it created the World over, so the
* bindings take none.
*/
+/** A host entry point that may not exist, as a callable or null. */
+function optional(
+ scope: Record<string, unknown>,
+ name: string,
+): ((...args: unknown[]) => unknown) | null {
+ const fn = scope[name];
+ return typeof fn === 'function' ? (fn as (...args: unknown[]) => unknown) : null;
+}
+
export function createNativeRendererBackend(
scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
): RendererBackend {
@@ -68,6 +77,21 @@ export function createNativeRendererBackend(
end: (): void => {
hostCall(scope, RENDERER_BINDINGS.end, []);
},
+ endFrame: (): void => {
+ optional(scope, RENDERER_OPTIONAL_BINDINGS.endFrame)?.();
+ },
+ hasScreenOverlay: (): boolean =>
+ optional(scope, RENDERER_OPTIONAL_BINDINGS.beginScreenOverlay) !== null,
+ beginScreenOverlay: (projection, vpX, vpY, vpW, vpH): void => {
+ optional(scope, RENDERER_OPTIONAL_BINDINGS.beginScreenOverlay)?.(
+ projection, vpX, vpY, vpW, vpH);
+ },
+ submitScreenOverlay: (_registry: CppRegistry): void => {
+ optional(scope, RENDERER_OPTIONAL_BINDINGS.submitScreenOverlay)?.();
+ },
+ endScreenOverlay: (target): void => {
+ optional(scope, RENDERER_OPTIONAL_BINDINGS.endScreenOverlay)?.(target);
+ },
setStage: (stage): void => {
hostCall(scope, RENDERER_BINDINGS.setStage, [stage]);
},
diff --git a/sdk/src/ecs/bridge/nativeRuntime.ts b/sdk/src/ecs/bridge/nativeRuntime.ts
index c505394ee..68749eded 100644
--- a/sdk/src/ecs/bridge/nativeRuntime.ts
+++ b/sdk/src/ecs/bridge/nativeRuntime.ts
@@ -40,6 +40,7 @@ import { RenderPipeline } from '../../render/renderPipeline';
import { cameraPlugin } from '../../camera/CameraPlugin';
import { UICameraInfo } from '../../ui/core/ui-camera-info';
import { ScreenLayout } from '../../ui/core/screen-layout';
+import { ScreenOverlay, defaultScreenOverlay } from '../../ui/core/screen-overlay';
import { DEFAULT_UI_CAMERA_INFO } from '../../app/corePlugin';
import { uiPlugin } from '../../ui/ui-plugin';
import { SpinePlugin } from '../../spine';
@@ -241,6 +242,7 @@ function installNativeRenderer(app: App, scope: Record<string, unknown>): void {
app.setPipeline(new RenderPipeline());
app.insertResource(UICameraInfo, { ...DEFAULT_UI_CAMERA_INFO });
app.insertResource(ScreenLayout, { ...ScreenLayout._default });
+ app.insertResource(ScreenOverlay, defaultScreenOverlay());
// The viewport is read per frame, so a rotation reaches the projection without
// anyone pushing a resize event.
app.addPlugin(cameraPlugin(() => nativeSurfaceSize(scope)));
diff --git a/sdk/src/render/renderPipeline.ts b/sdk/src/render/renderPipeline.ts
index d80dd7c5d..bb4bf980d 100644
--- a/sdk/src/render/renderPipeline.ts
+++ b/sdk/src/render/renderPipeline.ts
@@ -9,6 +9,7 @@ import type { CppRegistry } from '../wasm';
import type { Entity } from '../types';
import { Renderer } from './renderer';
import type { PostProcessAPI } from '../postprocess';
+import type { ScreenOverlayData } from '../ui/core/screen-overlay';
import { Draw, isDrawAPIReady } from './draw';
import {
getDrawCallbacks,
@@ -66,6 +67,7 @@ export class RenderPipeline {
private lastHeight_ = 0;
private activeScenes_: Set<string> | null = null;
private preFlushCallbacks_: ((registry: { _cpp: CppRegistry }) => void)[] = [];
+ private screenOverlayCallbacks_: ((registry: { _cpp: CppRegistry }) => void)[] = [];
private postProcess_: PostProcessAPI | null = null;
setActiveScenes(scenes: Set<string> | null): void {
@@ -85,6 +87,16 @@ export class RenderPipeline {
this.preFlushCallbacks_.push(cb);
}
+ /**
+ * Register geometry a plugin draws into the SCREEN overlay rather than into a
+ * camera — the sibling of {@link addPreFlushCallback}, separate for the same
+ * reason the two collects are: a callback that ran in both would put the same
+ * glyph in each list. Runs between the overlay's collect and its pass.
+ */
+ addScreenOverlayCallback(cb: (registry: { _cpp: CppRegistry }) => void): void {
+ this.screenOverlayCallbacks_.push(cb);
+ }
+
/**
* Run what plugins registered to draw just before the frame flushes (glyph
* quads, today). {@link submitScene} calls this in the middle of its own
@@ -100,6 +112,40 @@ export class RenderPipeline {
Renderer.beginFrame(elapsedSec);
}
+ /**
+ * Closes the frame. The pair of {@link beginFrame}, and the last thing a
+ * frame does: a backend that borrows the swapchain image for a frame gives it
+ * back here, so everything drawn after the first camera — a second camera,
+ * the screen post stack, the overlay — still has somewhere to land.
+ */
+ endFrame(): void {
+ Renderer.endFrame();
+ }
+
+ /**
+ * The frame's screen-space overlay: one pass, after every camera and after
+ * post. It takes a projection and a rect and no camera, which is what makes a
+ * HUD hold still while the view moves. Silent when the core has no overlay
+ * pass, which has not partitioned the domains either.
+ */
+ renderScreenOverlay(
+ registry: { _cpp: CppRegistry },
+ overlay: ScreenOverlayData,
+ target = 0,
+ ): void {
+ if (!overlay.active || overlay.vpW === 0 || overlay.vpH === 0) return;
+ if (!Renderer.hasScreenOverlay()) return;
+
+ Renderer.beginScreenOverlay(overlay.projection,
+ overlay.vpX, overlay.vpY, overlay.vpW, overlay.vpH);
+ // Set after begin (which clears the list) and before the collect it gates,
+ // exactly as a camera's own mask is.
+ Renderer.setCullingMask(overlay.layerMask);
+ Renderer.submitScreenOverlay(registry);
+ for (const cb of this.screenOverlayCallbacks_) cb(registry);
+ Renderer.endScreenOverlay(target);
+ }
+
beginScreenCapture(): void {
const pp = this.postProcess_;
if (pp && pp.screenStack && pp.screenStack.enabledPassCount > 0) {
diff --git a/sdk/src/render/renderer.ts b/sdk/src/render/renderer.ts
index fcd810545..c1211da7e 100644
--- a/sdk/src/render/renderer.ts
+++ b/sdk/src/render/renderer.ts
@@ -53,6 +53,18 @@ export interface RendererBackend {
vpX: number, vpY: number, vpW: number, vpH: number): void;
flush(): void;
end(): void;
+ /** Closes the frame. Per FRAME, not per camera: this is where a backend
+ * holding a swapchain image for the duration of one gives it back. */
+ endFrame(): void;
+ /** Whether this core can draw the frame's screen overlay. False means it
+ * keeps screen UI in the world domain, as every core did before the pass
+ * existed — the partition and the pass ship in the same binary, so the two
+ * answers cannot disagree. */
+ hasScreenOverlay(): boolean;
+ beginScreenOverlay(projection: Float32Array,
+ vpX: number, vpY: number, vpW: number, vpH: number): void;
+ submitScreenOverlay(registry: CppRegistry): void;
+ endScreenOverlay(target: number): void;
setStage(stage: number): void;
setViewport(x: number, y: number, w: number, h: number): void;
setYSortLayers(mask: number): void;
@@ -112,6 +124,37 @@ function wasmBackend(m: ESEngineModule): RendererBackend {
handleWasmError(e, 'Renderer.end');
}
},
+ endFrame: () => {
+ try {
+ m.renderer_endFrame?.();
+ } catch (e) {
+ handleWasmError(e, 'Renderer.endFrame');
+ }
+ },
+ hasScreenOverlay: () => typeof m.renderer_beginScreenOverlay === 'function',
+ beginScreenOverlay: (projection, vpX, vpY, vpW, vpH) => {
+ if (!viewProjectionPtr) return;
+ try {
+ m.HEAPF32.set(projection, viewProjectionPtr / 4);
+ m.renderer_beginScreenOverlay?.(viewProjectionPtr, vpX, vpY, vpW, vpH);
+ } catch (e) {
+ handleWasmError(e, 'Renderer.beginScreenOverlay');
+ }
+ },
+ submitScreenOverlay: (registry) => {
+ try {
+ m.renderer_submitScreenOverlay?.(registry);
+ } catch (e) {
+ handleWasmError(e, 'Renderer.submitScreenOverlay');
+ }
+ },
+ endScreenOverlay: (target) => {
+ try {
+ m.renderer_endScreenOverlay?.(target);
+ } catch (e) {
+ handleWasmError(e, 'Renderer.endScreenOverlay');
+ }
+ },
setStage: (stage) => m.renderer_setStage(stage),
setViewport: (x, y, w, h) => m.renderer_setViewport(x, y, w, h),
setYSortLayers: (mask) => m.renderer_setYSortLayers?.(mask >>> 0),
@@ -357,6 +400,30 @@ export const Renderer = {
backend?.end();
},
+ /** Closes the frame — after every camera, after the screen post stack, and
+ * after the overlay. See RendererBackend.endFrame. */
+ endFrame(): void {
+ backend?.endFrame();
+ },
+
+ /** Whether the core can draw the frame's screen overlay. */
+ hasScreenOverlay(): boolean {
+ return backend?.hasScreenOverlay() ?? false;
+ },
+
+ beginScreenOverlay(projection: Float32Array,
+ vpX: number, vpY: number, vpW: number, vpH: number): void {
+ backend?.beginScreenOverlay(projection, vpX, vpY, vpW, vpH);
+ },
+
+ submitScreenOverlay(registry: { _cpp: CppRegistry }): void {
+ backend?.submitScreenOverlay(registry._cpp);
+ },
+
+ endScreenOverlay(target: RenderTargetHandle = 0): void {
+ backend?.endScreenOverlay(target);
+ },
+
submitAll(registry: { _cpp: CppRegistry }, vpX: number, vpY: number, vpW: number, vpH: number): void {
backend?.submitAll(registry._cpp, vpX, vpY, vpW, vpH);
},
diff --git a/sdk/src/ui/behavior/plugin.ts b/sdk/src/ui/behavior/plugin.ts
index 117a30dde..df4ab8e22 100644
--- a/sdk/src/ui/behavior/plugin.ts
+++ b/sdk/src/ui/behavior/plugin.ts
@@ -11,6 +11,8 @@ import type { Entity, Vec2 } from '../../types';
import { UIEvents, UIEventQueue } from '../core/events';
import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';
import { ScreenLayout, type ScreenLayoutData } from '../core/screen-layout';
+import { ScreenOverlay, type ScreenOverlayData } from '../core/screen-overlay';
+import { uiPointerFor } from '../util/ui-pick';
import { PluginName, SystemLabel } from '../../ecs/systemLabels';
import { ListView, ListViewRegistry } from '../collection/list-view';
import { ScrollContainer, ScrollContainerRegistry } from '../collection/scroll-container';
@@ -224,10 +226,14 @@ export class UIBehaviorPlugin implements Plugin {
let lastOffset: Vec2 = { x: 0, y: 0 };
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
- [Res(Input), Res(UICameraInfo), Res(Time), Res(ScreenLayout)],
- (input: InputState, camera: UICameraData, time: TimeData, layout: ScreenLayoutData) => {
- if (!camera.valid) return;
- const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };
+ [Res(Input), Res(UICameraInfo), Res(Time), Res(ScreenLayout), Res(ScreenOverlay)],
+ (input: InputState, camera: UICameraData, time: TimeData, layout: ScreenLayoutData,
+ overlay: ScreenOverlayData) => {
+ if (!camera.valid && !overlay.active) return;
+ // In the domain the grabbed container is laid out in — a scroll
+ // subtracts a pointer from a transform, like a drag does.
+ const pointerFor = (entity: Entity): { x: number; y: number } =>
+ uiPointerFor(world, entity, camera, overlay);
// Press over a hovered container (or an interactive child of one)
// arms the drag; the nearest container wins so a nested list
@@ -238,7 +244,7 @@ export class UIBehaviorPlugin implements Plugin {
const container = scrollContainers.get(best)!;
dynamicsFor(best, container).stop();
pendingEntity = best;
- grabStartWorld = { x: worldMouse.x, y: worldMouse.y };
+ grabStartWorld = pointerFor(best);
}
}
@@ -253,8 +259,9 @@ export class UIBehaviorPlugin implements Plugin {
if (!container) {
pendingEntity = null;
} else {
- const dx = worldMouse.x - grabStartWorld.x;
- const dy = worldMouse.y - grabStartWorld.y;
+ const pointer = pointerFor(pendingEntity);
+ const dx = pointer.x - grabStartWorld.x;
+ const dy = pointer.y - grabStartWorld.y;
const screenDist = Math.hypot(dx, dy) * layout.scale;
if (screenDist >= SCROLL_DRAG_THRESHOLD_PX) {
activeEntity = pendingEntity;
@@ -282,8 +289,9 @@ export class UIBehaviorPlugin implements Plugin {
if (wt.worldScale.x !== 0) sx = wt.worldScale.x;
if (wt.worldScale.y !== 0) sy = wt.worldScale.y;
}
- const totalDx = worldMouse.x - grabStartWorld.x;
- const totalDy = worldMouse.y - grabStartWorld.y;
+ const pointer = pointerFor(activeEntity);
+ const totalDx = pointer.x - grabStartWorld.x;
+ const totalDy = pointer.y - grabStartWorld.y;
container.setOffset({
x: grabStartOffset.x - totalDx / sx,
y: grabStartOffset.y + totalDy / sy,
diff --git a/sdk/src/ui/behavior/slider.ts b/sdk/src/ui/behavior/slider.ts
index 5dbb473e0..4c3bc55ed 100644
--- a/sdk/src/ui/behavior/slider.ts
+++ b/sdk/src/ui/behavior/slider.ts
@@ -21,6 +21,8 @@ import { UIVisual, type UIVisualData } from '../core/ui-visual';
import { UINode, type UINodeData } from '../core/ui-node';
import { percent } from '../core/dimension';
import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';
+import { ScreenOverlay, type ScreenOverlayData } from '../core/screen-overlay';
+import { uiPointerFor } from '../util/ui-pick';
import { UIInteraction, type UIInteractionData } from '../input/interactable';
import { Interactable, type InteractableData } from '../input/interactable';
import { Focusable, type FocusableData } from '../input/focusable';
@@ -76,8 +78,8 @@ export function createSliderSystem(world: World, events: UIEventQueue): SystemDe
const shown = new EntityStateMap<number>(); // last value whose visuals were applied
return defineSystem(
- [Res(Input), Res(UICameraInfo)],
- (input: InputState, camera: UICameraData) => {
+ [Res(Input), Res(UICameraInfo), Res(ScreenOverlay)],
+ (input: InputState, camera: UICameraData, overlay: ScreenOverlayData) => {
for (const e of world.getEntitiesWithComponents([UISlider])) {
const d = world.get(e, UISlider) as UISliderData;
let next = d.value;
@@ -93,13 +95,17 @@ export function createSliderSystem(world: World, events: UIEventQueue): SystemDe
if (active === e) {
if (!input.isMouseButtonDown(0)) {
active = null;
- } else if (camera.valid && world.has(e, Transform)) {
+ } else if ((camera.valid || overlay.active) && world.has(e, Transform)) {
const t = world.get(e, Transform) as TransformData;
const w = getUINodeWidth(e) * t.worldScale.x;
if (w > 0) {
+ // The pointer in the track's own domain: the fraction
+ // is a ratio of two positions, so both have to be in
+ // the coordinates the track was laid out in.
+ const pointer = uiPointerFor(world, e, camera, overlay);
const left = t.worldPosition.x - w / 2;
next = sliderClamp(
- d.min + ((camera.worldMouseX - left) / w) * (d.max - d.min), d);
+ d.min + ((pointer.x - left) / w) * (d.max - d.min), d);
}
}
}
diff --git a/sdk/src/ui/core/screen-layout.ts b/sdk/src/ui/core/screen-layout.ts
index 154ed4f1b..485616821 100644
--- a/sdk/src/ui/core/screen-layout.ts
+++ b/sdk/src/ui/core/screen-layout.ts
@@ -17,6 +17,7 @@
*/
import { defineResource } from '../../ecs/resource';
import { computeEffectiveOrthoSize, type CanvasScale } from '../../camera/uiLayoutRect';
+import { ortho } from '../../math/mat4';
/** Insets, in layout pixels, the device asks content to stay clear of. */
export interface ScreenInsets {
@@ -102,3 +103,29 @@ export function screenLayoutRect(
viewportW, viewportH,
};
}
+
+/**
+ * How far a screen quad may sit either side of the plane before the projection
+ * clips it. Generous on purpose: a screen root's `Transform.worldPosition.z` is
+ * layout storage with no depth meaning, so a value left there must not decide
+ * whether the element exists.
+ */
+const SCREEN_Z_RANGE = 1e5;
+
+/**
+ * The projection the screen domain is drawn and picked through.
+ *
+ * @details ONE matrix, not two agreeing ones: the overlay renders with it and the
+ * pointer is inverted through it, so "the HUD is where it looks" holds
+ * by construction. Its only input is the layout box.
+ */
+export function screenProjection(l: ScreenLayoutData, out?: Float32Array): Float32Array {
+ const m = out ?? new Float32Array(16);
+ if (!l.valid) {
+ m.fill(0);
+ m[0] = m[5] = m[10] = m[15] = 1;
+ return m;
+ }
+ m.set(ortho(l.left, l.right, l.bottom, l.top, -SCREEN_Z_RANGE, SCREEN_Z_RANGE));
+ return m;
+}
diff --git a/sdk/src/ui/core/screen-overlay.ts b/sdk/src/ui/core/screen-overlay.ts
new file mode 100644
index 000000000..729dbde3a
--- /dev/null
+++ b/sdk/src/ui/core/screen-overlay.ts
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file screen-overlay.ts
+ * @brief How the screen domain reaches pixels this frame — read by the draw
+ * and by the pointer, which is why it is a published value.
+ *
+ * @details {@link ScreenLayout} says WHERE a screen element is; this says how
+ * that place becomes a framebuffer pixel. They are different facts and
+ * only this one can vary with the surface presenting it.
+ *
+ * Render and pick must not merely agree — they must read the SAME
+ * matrix. Two derivations that are equal today drift the moment either
+ * side gains a case, and the symptom (a HUD that looks right and clicks
+ * somewhere else) is worse to diagnose than one that never drew.
+ *
+ * In a shipped frame the projection is {@link screenProjection} over the
+ * whole surface: no camera, no world. The editor's design view is the
+ * one place it is anything else — there the screen box is shown IN the
+ * scene, zoomed and panned like the content it will sit over, so the
+ * view's own projection presents it. That is a value this carries, not
+ * a branch the renderer takes.
+ */
+import { defineResource } from '../../ecs/resource';
+
+export interface ScreenOverlayData {
+ /** False when nothing has a screen yet — no surface, no layout. */
+ active: boolean;
+ /** Layout-domain → clip. 16 floats, column-major, as a camera's is. */
+ projection: Float32Array;
+ /** The pixel rect of the surface this projection covers. */
+ vpX: number;
+ vpY: number;
+ vpW: number;
+ vpH: number;
+ /** The whole surface, which is what a pointer's coordinates are flipped by. */
+ surfaceW: number;
+ surfaceH: number;
+ /**
+ * The pointer, in LAYOUT pixels — the domain a screen element's transform is
+ * in, so a drag can subtract the two. Inverted through {@link projection} and
+ * nothing else: a UI system reading the camera's world mouse instead draws in
+ * the right place and answers a click somewhere else.
+ */
+ pointerX: number;
+ pointerY: number;
+ /**
+ * Sorting layers this frame shows, as a bitmask (a Canvas contributes its
+ * own layer's bit). Which layers a frame shows is a frame-level fact, so the
+ * overlay reads it here rather than from whichever camera happens to be
+ * first; where a HUD SITS still owes a camera nothing.
+ */
+ layerMask: number;
+}
+
+/** A fresh instance. A factory rather than a shared literal because the matrix
+ * is a buffer: two Apps spreading one default would write each other's frame. */
+export function defaultScreenOverlay(): ScreenOverlayData {
+ return {
+ active: false,
+ projection: new Float32Array(16),
+ vpX: 0, vpY: 0, vpW: 0, vpH: 0,
+ surfaceW: 0, surfaceH: 0,
+ pointerX: 0, pointerY: 0,
+ layerMask: 0xFFFFFFFF,
+ };
+}
+
+export const ScreenOverlay = defineResource<ScreenOverlayData>(
+ defaultScreenOverlay(), 'ScreenOverlay');
diff --git a/sdk/src/ui/input/drag.ts b/sdk/src/ui/input/drag.ts
index d1bce2794..5db83f12b 100644
--- a/sdk/src/ui/input/drag.ts
+++ b/sdk/src/ui/input/drag.ts
@@ -19,6 +19,8 @@ import type { UIInteractionData } from './interactable';
import { UIEvents, UIEventQueue } from '../core/events';
import { UICameraInfo } from '../core/ui-camera-info';
import { ScreenLayout, type ScreenLayoutData } from '../core/screen-layout';
+import { ScreenOverlay, type ScreenOverlayData } from '../core/screen-overlay';
+import { uiPointerFor } from '../util/ui-pick';
import type { UICameraData } from '../core/ui-camera-info';
import { playModeOnly } from '../../ecs/env';
import { getEntityDepth } from '../util/helpers';
@@ -92,11 +94,16 @@ export class DragPlugin implements Plugin {
let activeEntity: Entity | null = null;
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
- [Res(Input), Res(UICameraInfo), Res(ScreenLayout)],
- (input: InputState, camera: UICameraData, layout: ScreenLayoutData) => {
- if (!camera.valid) return;
+ [Res(Input), Res(UICameraInfo), Res(ScreenLayout), Res(ScreenOverlay)],
+ (input: InputState, camera: UICameraData, layout: ScreenLayoutData,
+ overlay: ScreenOverlayData) => {
+ if (!camera.valid && !overlay.active) return;
- const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };
+ // Per ENTITY, not once per frame: a drag subtracts a pointer from
+ // a transform, and the two share coordinates only if the pointer
+ // was projected into the domain the entity is laid out in.
+ const pointerFor = (entity: Entity): { x: number; y: number } =>
+ uiPointerFor(world, entity, camera, overlay);
if (input.isMouseButtonPressed(0)) {
const draggableEntities = world.getEntitiesWithComponents([Draggable, UIInteraction]);
@@ -124,7 +131,8 @@ export class DragPlugin implements Plugin {
if (bestEntity !== null) {
pendingEntity = bestEntity;
- pendingStartWorld = { x: worldMouse.x, y: worldMouse.y };
+ const pointer = pointerFor(bestEntity);
+ pendingStartWorld = { x: pointer.x, y: pointer.y };
if (!world.has(bestEntity, DragState)) {
world.insert(bestEntity, DragState);
@@ -133,7 +141,7 @@ export class DragPlugin implements Plugin {
world.update(bestEntity, DragState, (d) => {
d.startWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };
d.currentWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };
- d.pointerStartWorld = { x: worldMouse.x, y: worldMouse.y };
+ d.pointerStartWorld = { x: pointer.x, y: pointer.y };
d.deltaWorld = { x: 0, y: 0 };
d.totalDeltaWorld = { x: 0, y: 0 };
d.isDragging = false;
@@ -153,8 +161,9 @@ export class DragPlugin implements Plugin {
pendingEntity = null;
return;
}
- const dx = worldMouse.x - pendingStartWorld.x;
- const dy = worldMouse.y - pendingStartWorld.y;
+ const pointer = pointerFor(pendingEntity);
+ const dx = pointer.x - pendingStartWorld.x;
+ const dy = pointer.y - pendingStartWorld.y;
const dist = Math.sqrt(dx * dx + dy * dy);
const draggable = world.get(pendingEntity, Draggable) as DraggableData;
@@ -177,8 +186,9 @@ export class DragPlugin implements Plugin {
const dragState = world.get(activeEntity, DragState) as DragStateData;
const draggable = world.get(activeEntity, Draggable) as DraggableData;
- const pointerDeltaX = worldMouse.x - dragState.pointerStartWorld.x;
- const pointerDeltaY = worldMouse.y - dragState.pointerStartWorld.y;
+ const pointer = pointerFor(activeEntity);
+ const pointerDeltaX = pointer.x - dragState.pointerStartWorld.x;
+ const pointerDeltaY = pointer.y - dragState.pointerStartWorld.y;
let newWorldX = dragState.startWorldPos.x + pointerDeltaX;
let newWorldY = dragState.startWorldPos.y + pointerDeltaY;
diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.ts
index 8b7946b19..8922cced9 100644
--- a/sdk/src/ui/input/interaction.ts
+++ b/sdk/src/ui/input/interaction.ts
@@ -17,7 +17,8 @@ import { ensureEntityEvents } from '../../ecs/entityEvents';
import { UICameraInfo } from '../core/ui-camera-info';
import type { UICameraData } from '../core/ui-camera-info';
import type { InteractableData } from './interactable';
-import { screenToUiWorld, uiPointerRay, uiHitTestWorld } from '../util/ui-pick';
+import { screenToUiWorld, screenToUiLayout, uiPointerRay, uiLayoutRay, uiHitTestWorld } from '../util/ui-pick';
+import { ScreenOverlay, type ScreenOverlayData } from '../core/screen-overlay';
import { platformDevicePixelRatio } from '../../platform';
import { ensureComponent, walkParentChain } from '../util/helpers';
import type { CppRegistry } from '../../wasm';
@@ -63,11 +64,14 @@ export class UIInteractionPlugin implements Plugin {
let pressedEntity: Entity | null = null;
let lastPointerX = NaN;
let lastPointerY = NaN;
+ let lastWorldPointerX = NaN;
+ let lastWorldPointerY = NaN;
let lastLayoutGen = -1;
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
- [Res(Input), Res(UICameraInfo), Res(UILayoutGeneration)],
- (input: InputState, camera: UICameraData, layoutGen: UILayoutGenerationData) => {
+ [Res(Input), Res(UICameraInfo), Res(ScreenOverlay), Res(UILayoutGeneration)],
+ (input: InputState, camera: UICameraData, overlay: ScreenOverlayData,
+ layoutGen: UILayoutGenerationData) => {
events.drain();
const interactionEntities = world.getEntitiesWithComponents([UIInteraction]);
@@ -80,33 +84,59 @@ export class UIInteractionPlugin implements Plugin {
}
}
- if (!camera.valid) { input.pointerOverUI = false; return; }
+ // Either domain is enough to be pointing AT something: a scene
+ // with no camera still has a screen, and a HUD on it is still
+ // clickable.
+ if (!camera.valid && !overlay.active) { input.pointerOverUI = false; return; }
const dpr = platformDevicePixelRatio();
const mouseGLX = input.mouseX * dpr;
- const mouseGLY = camera.screenH - input.mouseY * dpr;
-
- const worldMouse = screenToUiWorld(camera, mouseGLX, mouseGLY);
-
+ const surfaceH = overlay.active ? overlay.surfaceH : camera.screenH;
+ const mouseGLY = surfaceH - input.mouseY * dpr;
+
+ // The pointer, once per domain. Neither is derived from the
+ // other: each is the inverse of the projection that domain is
+ // drawn with, which is what keeps a click where the pixel is.
+ const worldMouse = camera.valid
+ ? screenToUiWorld(camera, mouseGLX, mouseGLY)
+ : { x: 0, y: 0 };
camera.worldMouseX = worldMouse.x;
camera.worldMouseY = worldMouse.y;
+ const layoutMouse = overlay.active
+ ? screenToUiLayout(overlay, mouseGLX, mouseGLY)
+ : worldMouse;
+ overlay.pointerX = layoutMouse.x;
+ overlay.pointerY = layoutMouse.y;
+
const mouseDown = input.isMouseButtonDown(0);
const mousePressed = input.isMouseButtonPressed(0);
const mouseReleased = input.isMouseButtonReleased(0);
- const pointerMoved = worldMouse.x !== lastPointerX || worldMouse.y !== lastPointerY;
+ const pointerMoved = layoutMouse.x !== lastPointerX || layoutMouse.y !== lastPointerY
+ || worldMouse.x !== lastWorldPointerX
+ || worldMouse.y !== lastWorldPointerY;
const layoutChanged = layoutGen.generation !== lastLayoutGen;
const hasMouseEvent = mousePressed || mouseReleased;
const needsHitTest = pointerMoved || layoutChanged || hasMouseEvent;
- lastPointerX = worldMouse.x;
- lastPointerY = worldMouse.y;
+ lastPointerX = layoutMouse.x;
+ lastPointerY = layoutMouse.y;
+ lastWorldPointerX = worldMouse.x;
+ lastWorldPointerY = worldMouse.y;
lastLayoutGen = layoutGen.generation;
let hitEntity: Entity | null = hoveredEntity;
if (needsHitTest) {
- hitEntity = uiHitTestWorld(world, uiPointerRay(camera, mouseGLX, mouseGLY));
+ // With no camera there is no world ray: inverting a projection
+ // never written yields NaN, which answers "no" by accident.
+ // The screen's ray stands in — nothing is in the world.
+ const screenRay = overlay.active
+ ? uiLayoutRay(overlay, mouseGLX, mouseGLY) : undefined;
+ const worldRay = camera.valid
+ ? uiPointerRay(camera, mouseGLX, mouseGLY)
+ : screenRay!;
+ hitEntity = uiHitTestWorld(world, worldRay, screenRay);
}
if (hoveredEntity !== null && !world.valid(hoveredEntity)) {
diff --git a/sdk/src/ui/layout/layout.ts b/sdk/src/ui/layout/layout.ts
index 7806094ef..464275d5f 100644
--- a/sdk/src/ui/layout/layout.ts
+++ b/sdk/src/ui/layout/layout.ts
@@ -17,8 +17,8 @@ import { Res } from '../../ecs/resource';
import { UINode } from '../core/ui-node';
import { UIVisual } from '../core/ui-visual';
import { FlexContainer } from './flex';
-import { UICameraInfo } from '../core/ui-camera-info';
-import type { UICameraData } from '../core/ui-camera-info';
+import { ScreenLayout } from '../core/screen-layout';
+import type { ScreenLayoutData } from '../core/screen-layout';
import { UILayoutGeneration } from './ui-layout-generation';
import type { UILayoutGenerationData } from './ui-layout-generation';
import type { CppRegistry } from '../../wasm';
@@ -67,31 +67,34 @@ export class UILayoutPlugin implements Plugin {
return dirty;
};
- const layoutFn = (camera: UICameraData) => {
- if (!camera.valid) return;
+ // The box is the SCREEN's: the design resolution fitted to the viewport,
+ // centred on the origin — which is what makes a screen root's placement a
+ // fact about the screen rather than about where something is looking.
+ const layoutFn = (screen: ScreenLayoutData) => {
+ if (!screen.valid) return;
engine?.uiLayout_update?.(
registry,
- camera.worldLeft, camera.worldBottom,
- camera.worldRight, camera.worldTop,
+ screen.left, screen.bottom,
+ screen.right, screen.top,
propertyDirty(),
);
engine?.transform_update?.(registry);
layoutGen.generation++;
};
- const layoutOnlyFn = (camera: UICameraData) => {
- if (!camera.valid) return;
+ const layoutOnlyFn = (screen: ScreenLayoutData) => {
+ if (!screen.valid) return;
engine?.uiLayout_update?.(
registry,
- camera.worldLeft, camera.worldBottom,
- camera.worldRight, camera.worldTop,
+ screen.left, screen.bottom,
+ screen.right, screen.top,
propertyDirty(),
);
layoutGen.generation++;
};
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
- [Res(UICameraInfo)],
+ [Res(ScreenLayout)],
layoutFn,
{ name: 'UILayoutSystem' }
));
@@ -100,7 +103,7 @@ export class UILayoutPlugin implements Plugin {
// render reads world transforms (UIRenderOrder walks hierarchy only), and
// the renderer's ensureTransformsUpdated composes worlds before collect.
app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(
- [Res(UICameraInfo)],
+ [Res(ScreenLayout)],
layoutOnlyFn,
{ name: 'UILayoutLateSystem' }
), { runAfter: [SystemLabel.ListView], runBefore: [SystemLabel.UIRenderOrder] });
diff --git a/sdk/src/ui/layout/safe-area.ts b/sdk/src/ui/layout/safe-area.ts
index 81c8e4d8c..719b5578f 100644
--- a/sdk/src/ui/layout/safe-area.ts
+++ b/sdk/src/ui/layout/safe-area.ts
@@ -10,7 +10,6 @@ import { isWeChat, platformDevicePixelRatio } from '../../platform';
import { defineComponent, registerComponent } from '../../ecs/component';
import { Res } from '../../ecs/resource';
import { defineSystem, Schedule } from '../../ecs/system';
-import { UICameraInfo } from '../core/ui-camera-info';
import { ScreenLayout, type ScreenLayoutData } from '../core/screen-layout';
import type { UICameraData } from '../core/ui-camera-info';
import { UINode } from '../core/ui-node';
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index 280dc15e2..afa2899fa 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -22,6 +22,7 @@ import { UINode } from '../core/ui-node';
import { Localization } from '../../i18n/Localization';
import { applyTextLocalization, type TextWorldView } from './localize';
import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';
+import { ScreenOverlay } from '../core/screen-overlay';
import { getUINodeWidth, getUINodeHeight, ensureUIVisual } from '../util/helpers';
import { resolveTextFamily } from './font-registry';
import { platformDevicePixelRatio } from '../../platform';
@@ -55,36 +56,42 @@ export function resolveTextRenderMode(
}
/**
- * Pure: how many device pixels one world unit covers, which is the size bitmap
- * glyphs must be rasterized at to land on screen pixels.
+ * Pure: how many CSS pixels one unit of a DOMAIN covers, which is the size
+ * bitmap glyphs must be rasterized at to land on screen pixels.
*
- * It comes from what the camera SHOWS, not from the box UI lays out in. Those
- * agree in a shipped game — the camera frames the design box — and diverge in
- * the editor, whose free-zoom view deliberately holds the layout box fixed so UI
- * does not reflow while you zoom (see syncUICameraInfo). Taking the span from
- * the layout box therefore rasterized glyphs for the design scale and left the
- * camera to scale the result, so editor text went soft at every zoom but "fit" —
- * and the sharper look of SDF there was really the bitmap path being asked for
- * the wrong size.
+ * It comes from the projection that will DRAW the text, not from the box the
+ * text was laid out in: the editor's free-zoom view holds that box fixed on
+ * purpose, so reading the span off it asks for design-sized glyphs and leaves the
+ * projection to scale the result — which is soft text at every zoom but "fit".
*
- * An orthographic view-projection's first element is 2 / the span it covers.
+ * Two domains call this with their own projections. World text sharpens as the
+ * camera zooms in, which is correct; screen text follows the overlay, which is
+ * what keeps a 3D camera's field of view out of a HUD's glyphs.
+ *
+ * @param projScaleX element 0 of the projection: 2 / the span it shows.
+ * @param vpW the pixel width that span lands in.
*/
-export function glyphContentScale(
- cam: Pick<UICameraData, 'valid' | 'vpW' | 'worldLeft' | 'worldRight' | 'viewProjection'> | undefined,
- dpr: number,
-): number {
- if (!cam?.valid || !(dpr > 0)) return 1;
- const vpScaleX = cam.viewProjection?.[0] ?? 0;
- const layoutSpan = cam.worldRight - cam.worldLeft;
- const shownSpan = vpScaleX !== 0 ? Math.abs(2 / vpScaleX) : layoutSpan;
- return shownSpan > 0 ? cam.vpW / (shownSpan * dpr) : 1;
+export function glyphContentScale(projScaleX: number, vpW: number, dpr: number): number {
+ if (!(dpr > 0) || !(vpW > 0)) return 1;
+ if (!Number.isFinite(projScaleX) || projScaleX === 0) return 1;
+ const shownSpan = Math.abs(2 / projScaleX);
+ return shownSpan > 0 ? vpW / (shownSpan * dpr) : 1;
+}
+
+/** The two domains a Text can belong to, and the state each keeps. */
+interface TextDomainState {
+ bitmap: SdfTextRenderer | null;
+ sdf: SdfTextRenderer | null;
}
export class TextPlugin implements Plugin {
name = 'text';
- private bitmapRenderer_: SdfTextRenderer | null = null;
- private sdfRenderer_: SdfTextRenderer | null = null;
+ // One pair per DOMAIN: a bitmap atlas is rasterized at ONE content scale, and
+ // the two ask for different ones the moment a camera stops being the screen.
+ // Lazy, so text in only one domain pays for one pair.
+ private readonly world_: TextDomainState = { bitmap: null, sdf: null };
+ private readonly screen_: TextDomainState = { bitmap: null, sdf: null };
private readonly matrix_ = new Float32Array(16);
build(app: App): void {
@@ -114,149 +121,184 @@ export class TextPlugin implements Plugin {
const pipeline = app.pipeline;
if (!pipeline) return; // logic-only host → nothing to draw
+ // Two passes, because there are two lists: the world's glyphs go into the
+ // camera being collected, the screen's into the frame's overlay.
+ pipeline.addPreFlushCallback(() => this.drawDomain(app, /*screen=*/false));
+ pipeline.addScreenOverlayCallback(() => this.drawDomain(app, /*screen=*/true));
+ }
+
+ /**
+ * Draw every Text belonging to one domain, into whichever list is open.
+ *
+ * The domain is asked of the engine, not derived here: it is resolved once at
+ * a UI subtree's root and inherited (UISystem::screenDomain), and a second
+ * spelling of that rule in TS is a second rule.
+ */
+ private drawDomain(app: App, screen: boolean): void {
+ const world = app.world;
const registry = world.getCppRegistry() as CppRegistry;
+ // Through engineApi, not app.wasmModule: a device has no wasm module, and
+ // asking for one leaves every Text at the base UI layer (ecs/engineApi.ts).
+ const api = engineApi(app);
+ // A core that cannot answer has not partitioned anything either, so every
+ // Text is world content and the screen pass draws nothing.
+ const isScreen = (entity: number): boolean =>
+ api?.ui_isScreenDomain?.(registry, entity) ?? false;
+ if (screen && !api?.ui_isScreenDomain) return;
- pipeline.addPreFlushCallback(() => {
- // The engine queries below go through engineApi, not app.wasmModule: a
- // device has no wasm module, so asking for one left every Text at the
- // base UI layer — beneath any sibling panel — and hid it (ecs/engineApi.ts).
- const api = engineApi(app);
- // Design→device scale beyond DPR (vpW is device px); the bitmap
- // atlas folds it into rasterization. Resolved per frame — the
- // camera plugin may build after this one.
- // Camera-scaled ON PURPOSE, and correct for WORLD text: zooming in
- // rasterizes sharper. Screen text wants the layout domain, which
- // needs the two told apart — the collection split, not here.
- const uiCamera = app.getResource(UICameraInfo) as UICameraData | undefined;
- const dpr = platformDevicePixelRatio();
- const contentScale = glyphContentScale(uiCamera, dpr);
+ const dpr = platformDevicePixelRatio();
+ const contentScale = screen
+ ? this.screenContentScale(app, dpr)
+ : this.worldContentScale(app, dpr);
+ const state = screen ? this.screen_ : this.world_;
- const seen = new Set<number>();
- for (const e of world.getEntitiesWithComponents([Text, Transform])) {
- const entity = e as Entity;
- const t = world.get(entity, Text) as TextData;
- // enabled === false: pre-upgrade data lacks the field → visible.
- if (!t.content || t.enabled === false) continue;
- // display:none anywhere up the UI tree hides this text too.
- if (api?.getUINodeHiddenInTree?.(registry, entity)) continue;
- const groupAlpha = api?.getUINodeAlphaInTree?.(registry, entity) ?? 1;
- seen.add(entity as number);
+ const seen = new Set<number>();
+ for (const e of world.getEntitiesWithComponents([Text, Transform])) {
+ const entity = e as Entity;
+ if (isScreen(entity as number) !== screen) continue;
+ const t = world.get(entity, Text) as TextData;
+ // enabled === false: pre-upgrade data lacks the field → visible.
+ if (!t.content || t.enabled === false) continue;
+ // display:none anywhere up the UI tree hides this text too.
+ if (api?.getUINodeHiddenInTree?.(registry, entity)) continue;
+ const groupAlpha = api?.getUINodeAlphaInTree?.(registry, entity) ?? 1;
+ seen.add(entity as number);
- const tr = world.get(entity, Transform) as TransformData;
- const renderer = this.rendererFor(
- app,
- resolveTextRenderMode(t.renderMode, tr.worldScale.x),
- contentScale,
- );
- composeTRS(this.matrix_, tr.worldPosition, tr.worldRotation, tr.worldScale);
+ const tr = world.get(entity, Transform) as TransformData;
+ const renderer = this.rendererFor(
+ app, state,
+ resolveTextRenderMode(t.renderMode, tr.worldScale.x),
+ contentScale,
+ );
+ composeTRS(this.matrix_, tr.worldPosition, tr.worldRotation, tr.worldScale);
- const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);
- // Text.lineHeight is a ratio of fontSize (legacy convention).
- const lineHeightPx = t.lineHeight > 0 ? t.lineHeight * t.fontSize : undefined;
+ const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);
+ // Text.lineHeight is a ratio of fontSize (legacy convention).
+ const lineHeightPx = t.lineHeight > 0 ? t.lineHeight * t.fontSize : undefined;
- // The layout box: a UINode (CSS box, pivot-centered) or legacy
- // UINode. Text is placed + aligned + wrapped inside it and sorted
- // by the UI render order. No box ⇒ a world-space label at the
- // entity origin, sorted by Text.layer like any other world
- // renderer (it used to be pinned to 0, where anything else on
- // layer 0 drawn later covered it).
- let originX: number | undefined;
- let originY: number | undefined;
- let maxWidth: number | undefined;
- let boxWidth: number | undefined;
- let boxHeight: number | undefined;
- let layer = t.layer | 0;
- let w = 0, h = 0, hasBox = false;
- if (world.has(entity, UINode)) {
- w = getUINodeWidth(entity);
- h = getUINodeHeight(entity);
- hasBox = w > 0 || h > 0;
- }
- if (hasBox) {
- const box = rectTextBox(0.5, 0.5, w, h, t.fontSize);
- originX = box.originX;
- originY = box.originY;
- boxWidth = box.maxWidth; // align within the box regardless of word-wrap
- boxHeight = box.boxHeight;
- if (t.wordWrap) maxWidth = box.maxWidth; // wrap only when enabled
+ // The layout box: a UINode (CSS box, pivot-centered), which places,
+ // aligns and wraps the text and sorts it by UI render order. No box ⇒
+ // a world label at the entity origin, sorted by Text.layer.
+ let originX: number | undefined;
+ let originY: number | undefined;
+ let maxWidth: number | undefined;
+ let boxWidth: number | undefined;
+ let boxHeight: number | undefined;
+ let layer = t.layer | 0;
+ let w = 0, h = 0, hasBox = false;
+ if (world.has(entity, UINode)) {
+ w = getUINodeWidth(entity);
+ h = getUINodeHeight(entity);
+ hasBox = w > 0 || h > 0;
+ }
+ if (hasBox) {
+ const box = rectTextBox(0.5, 0.5, w, h, t.fontSize);
+ originX = box.originX;
+ originY = box.originY;
+ boxWidth = box.maxWidth; // align within the box regardless of word-wrap
+ boxHeight = box.boxHeight;
+ if (t.wordWrap) maxWidth = box.maxWidth; // wrap only when enabled
- const order = api?.ui_getRenderOrder?.(registry, entity as number) ?? -1;
- layer = order >= 0 ? UI_BASE_LAYER + order : UI_BASE_LAYER;
+ const order = api?.ui_getRenderOrder?.(registry, entity as number) ?? -1;
+ layer = order >= 0 ? UI_BASE_LAYER + order : UI_BASE_LAYER;
+ }
+
+ // A blur with no offset is still a shadow — a halo centred on the
+ // glyphs — so it counts as one for the "is there a shadow" test.
+ const shadow = t.shadowColor.a > 0
+ && (t.shadowOffsetX !== 0 || t.shadowOffsetY !== 0 || t.shadowBlur > 0)
+ ? {
+ color: [t.shadowColor.r, t.shadowColor.g, t.shadowColor.b, t.shadowColor.a] as RGBA,
+ dx: t.shadowOffsetX,
+ dy: t.shadowOffsetY,
+ blur: t.shadowBlur,
+ }
+ : undefined;
+ const outline = t.strokeWidth > 0 && t.strokeColor.a > 0
+ ? {
+ color: [t.strokeColor.r, t.strokeColor.g, t.strokeColor.b, t.strokeColor.a] as RGBA,
+ width: t.strokeWidth,
}
+ : undefined;
- // A blur with no offset is still a shadow — a halo centred on the
- // glyphs — so it counts as one for the "is there a shadow" test.
- const shadow = t.shadowColor.a > 0
- && (t.shadowOffsetX !== 0 || t.shadowOffsetY !== 0 || t.shadowBlur > 0)
- ? {
- color: [t.shadowColor.r, t.shadowColor.g, t.shadowColor.b, t.shadowColor.a] as RGBA,
- dx: t.shadowOffsetX,
- dy: t.shadowOffsetY,
- blur: t.shadowBlur,
- }
- : undefined;
- const outline = t.strokeWidth > 0 && t.strokeColor.a > 0
- ? {
- color: [t.strokeColor.r, t.strokeColor.g, t.strokeColor.b, t.strokeColor.a] as RGBA,
- width: t.strokeWidth,
- }
- : undefined;
+ renderer.drawText(
+ {
+ text: t.content,
+ fontFamily: resolveTextFamily(t.font, t.fontFamily),
+ fontSizePx: t.fontSize,
+ // Subtree opacity (UINode.opacity) is resolved in C++ by the
+ // layout pass; text is drawn here, so it multiplies the same
+ // inherited alpha in and fades with its panel like visuals do.
+ color: [t.color.r, t.color.g, t.color.b, t.color.a * groupAlpha],
+ style,
+ richText: t.richText,
+ align: t.align,
+ verticalAlign: t.verticalAlign,
+ lineHeight: lineHeightPx,
+ maxWidth,
+ boxWidth,
+ boxHeight,
+ overflow: t.overflow,
+ originX,
+ originY,
+ shadow,
+ outline,
+ },
+ this.matrix_,
+ entity as number,
+ layer,
+ // Screen draws all share one depth: their order is the UI tree's,
+ // and a z left on a screen root would otherwise outrank a sibling.
+ screen ? 0 : tr.worldPosition.z,
+ api?.ui_getCullBit?.(registry, entity as number) ?? 0,
+ );
+ }
- renderer.drawText(
- {
- text: t.content,
- fontFamily: resolveTextFamily(t.font, t.fontFamily),
- fontSizePx: t.fontSize,
- // Subtree opacity (UINode.opacity) is resolved in C++ by the
- // layout pass; text is drawn here, so it multiplies the same
- // inherited alpha in and fades with its panel like visuals do.
- color: [t.color.r, t.color.g, t.color.b, t.color.a * groupAlpha],
- style,
- richText: t.richText,
- align: t.align,
- verticalAlign: t.verticalAlign,
- lineHeight: lineHeightPx,
- maxWidth,
- boxWidth,
- boxHeight,
- overflow: t.overflow,
- originX,
- originY,
- shadow,
- outline,
- },
- this.matrix_,
- entity as number,
- layer,
- tr.worldPosition.z,
- api?.ui_getCullBit?.(registry, entity as number) ?? 0,
- );
- }
+ // Release cached geometry for text that vanished / hid this frame. Per
+ // domain, because each keeps its own atlases: retaining across the two
+ // would have each pass evict the other's glyphs every frame.
+ state.bitmap?.retainOnly(seen);
+ state.sdf?.retainOnly(seen);
+ }
+
+ /** World text rasterizes for the camera showing it — zoom in, get sharper. */
+ private worldContentScale(app: App, dpr: number): number {
+ const cam = app.getResource(UICameraInfo) as UICameraData | undefined;
+ if (!cam?.valid) return 1;
+ return glyphContentScale(cam.viewProjection?.[0] ?? 0, cam.vpW, dpr);
+ }
- // Release cached geometry for text that vanished / hid this frame.
- this.bitmapRenderer_?.retainOnly(seen);
- this.sdfRenderer_?.retainOnly(seen);
- });
+ /** Screen text rasterizes for the overlay that draws it, which is the one
+ * projection with no camera in it. */
+ private screenContentScale(app: App, dpr: number): number {
+ if (!app.hasResource(ScreenOverlay)) return 1;
+ const overlay = app.getResource(ScreenOverlay);
+ if (!overlay.active) return 1;
+ return glyphContentScale(overlay.projection[0] ?? 0, overlay.vpW, dpr);
}
- /** The two glyph pipelines, created lazily; they share layout, page store,
- * and batch submit — only the atlas contents and shader coverage differ. */
- private rendererFor(app: App, kind: 'bitmap' | 'sdf', contentScale: number): SdfTextRenderer {
+ /** The two glyph pipelines of one domain, created lazily; they share layout,
+ * page store, and batch submit — only the atlas contents and shader
+ * coverage differ. */
+ private rendererFor(
+ app: App,
+ state: TextDomainState,
+ kind: 'bitmap' | 'sdf',
+ contentScale: number,
+ ): SdfTextRenderer {
const module = app.wasmModule as ESEngineModule | null;
if (kind === 'sdf') {
- if (!this.sdfRenderer_) {
- this.sdfRenderer_ = new SdfTextRenderer(module, { sdf: true });
- }
- return this.sdfRenderer_;
+ if (!state.sdf) state.sdf = new SdfTextRenderer(module, { sdf: true });
+ return state.sdf;
}
- if (!this.bitmapRenderer_) {
+ if (!state.bitmap) {
const dpr = platformDevicePixelRatio();
- this.bitmapRenderer_ = new SdfTextRenderer(module, {
+ state.bitmap = new SdfTextRenderer(module, {
sdf: false, dpr, renderSize: Math.round(GLYPH_BASE_SIZE * dpr),
});
}
- this.bitmapRenderer_.setContentScale(contentScale);
- return this.bitmapRenderer_;
+ state.bitmap.setContentScale(contentScale);
+ return state.bitmap;
}
}
diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.ts
index e115cb3ff..6497be428 100644
--- a/sdk/src/ui/text/text-input-plugin.ts
+++ b/sdk/src/ui/text/text-input-plugin.ts
@@ -30,7 +30,8 @@ import {
splitLines, caretLineCol, lineSelections, imeAnchorCss, alignOffset,
type TextFieldDisplay,
} from './text-input-view';
-import { uiWorldToScreen } from '../util/ui-pick';
+import { uiWorldToScreen, uiLayoutToScreen, uiPointerFor, isScreenEntity } from '../util/ui-pick';
+import { ScreenOverlay, type ScreenOverlayData } from '../core/screen-overlay';
import { platformCreateTextEditor, platformDevicePixelRatio } from '../../platform';
import { CURSOR_BLINK_INTERVAL, TEXT_INPUT_LINE_HEIGHT_RATIO } from '../util/constants';
import { SystemLabel, PluginName } from '../../ecs/systemLabels';
@@ -190,8 +191,12 @@ export class TextInputPlugin implements Plugin {
// (no camera / no box).
function caretIndexFromPointer(entity: Entity): number | null {
const cam = app.getResource(UICameraInfo) as UICameraData | undefined;
- if (!cam || !cam.valid) return null;
+ const overlay = app.getResource(ScreenOverlay) as ScreenOverlayData | undefined;
+ if (!cam || !overlay || (!cam.valid && !overlay.active)) return null;
if (!world.has(entity, Transform) || !world.has(entity, UINode)) return null;
+ // The pointer in the FIELD's domain: every subtraction below is a
+ // pointer minus a transform, and the two have to be in one space.
+ const pointer = uiPointerFor(world, entity, cam, overlay);
const ti = world.get(entity, TextInput) as TextInputData;
const width = getUINodeWidth(entity);
if (width <= 0) return null;
@@ -213,12 +218,12 @@ export class TextInputPlugin implements Plugin {
const height = getUINodeHeight(entity);
const lineH = ti.fontSize * TEXT_INPUT_LINE_HEIGHT_RATIO;
const fieldTop = tr.worldPosition.y + height / 2;
- const localY = fieldTop - cam.worldMouseY; // y-down from the box top
+ const localY = fieldTop - pointer.y; // y-down from the box top
const lines = splitLines(val);
const li = Math.max(0, Math.min(Math.floor(localY / lineH), lines.length - 1));
const line = lines[li];
// Each line carries its own alignment offset, so undo THIS line's.
- const textX = cam.worldMouseX - fieldLeft - ti.padding
+ const textX = pointer.x - fieldLeft - ti.padding
- alignOffset(ti.textAlign, innerW, mw(line.text));
const prefixes: number[] = [];
for (let i = 0; i <= line.text.length; i++) prefixes.push(mw(line.text.slice(0, i)));
@@ -230,7 +235,7 @@ export class TextInputPlugin implements Plugin {
// a focused field's value can differ from what was last drawn, and a
// guess about the offset lands the caret on the wrong glyph.
const ao = alignOffsetOf.get(entity) ?? 0;
- const textX = cam.worldMouseX - fieldLeft - ti.padding - ao + scrollX;
+ const textX = pointer.x - fieldLeft - ti.padding - ao + scrollX;
const prefixes: number[] = [];
for (let i = 0; i <= val.length; i++) {
prefixes.push(mw(maskedPrefix(val, i, ti.password, PASSWORD_CHAR)));
@@ -267,15 +272,22 @@ export class TextInputPlugin implements Plugin {
* field-local px (y-down from the box top). */
function anchorCaret(entity: Entity, caretX: number, caretBottom: number): void {
const cam = app.getResource(UICameraInfo) as UICameraData | undefined;
- if (!cam || !cam.valid || !world.has(entity, Transform)) return;
+ const overlay = app.getResource(ScreenOverlay) as ScreenOverlayData | undefined;
+ if (!cam || !overlay || (!cam.valid && !overlay.active)) return;
+ if (!world.has(entity, Transform)) return;
+ const screen = isScreenEntity(world, entity);
const tr = world.get(entity, Transform) as TransformData;
const w = getUINodeWidth(entity);
const h = getUINodeHeight(entity);
// Box is centered on its Transform (pivot 0.5): left/top edges from it.
const worldX = (tr.worldPosition.x - w / 2) + caretX;
const worldY = (tr.worldPosition.y + h / 2) - caretBottom; // world y-up
- const scr = uiWorldToScreen(cam, worldX, worldY);
- const css = imeAnchorCss(scr.x, scr.y, cam.screenH, platformDevicePixelRatio());
+ // Forward through whichever projection actually drew the field.
+ const scr = screen
+ ? uiLayoutToScreen(overlay, worldX, worldY)
+ : uiWorldToScreen(cam, worldX, worldY);
+ const surfaceH = screen ? overlay.surfaceH : cam.screenH;
+ const css = imeAnchorCss(scr.x, scr.y, surfaceH, platformDevicePixelRatio());
editor!.setCaretAnchor?.(css.left, css.top);
}
diff --git a/sdk/src/ui/util/ui-pick.ts b/sdk/src/ui/util/ui-pick.ts
index 068abb09d..3725ec125 100644
--- a/sdk/src/ui/util/ui-pick.ts
+++ b/sdk/src/ui/util/ui-pick.ts
@@ -3,11 +3,13 @@
import type { Entity } from '../../types';
import type { World } from '../../ecs/world';
import type { UICameraData } from '../core/ui-camera-info';
+import type { ScreenOverlayData } from '../core/screen-overlay';
import { worldEngineApi } from '../../ecs/bridge/engineApi';
import { screenToWorld, worldToScreen, createInvVPCache, screenRay, type WorldRay } from './math';
const NO_HIT = 0xffffffff;
const vpCache = createInvVPCache();
+const overlayCache = createInvVPCache();
export function screenToUiWorld(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number } {
vpCache.update(camera.viewProjection);
@@ -27,6 +29,68 @@ export function uiPointerRay(camera: UICameraData, screenGLX: number, screenGLY:
return screenRay(screenGLX, screenGLY, invVP, camera.vpX, camera.vpY, camera.vpW, camera.vpH);
}
+/**
+ * The LAYOUT point a screen pixel names, through the same matrix the overlay
+ * draws with — the same one, not an equivalent one. Two derivations agree until
+ * either gains a case, and the symptom then is a HUD that looks right and clicks
+ * somewhere else.
+ */
+export function screenToUiLayout(
+ overlay: ScreenOverlayData, screenGLX: number, screenGLY: number,
+): { x: number; y: number } {
+ overlayCache.update(overlay.projection);
+ const invVP = overlayCache.getInverse(overlay.projection);
+ return screenToWorld(screenGLX, screenGLY, invVP,
+ overlay.vpX, overlay.vpY, overlay.vpW, overlay.vpH);
+}
+
+/** The layout-domain ray a screen point names — {@link screenToUiLayout}'s
+ * answer as the ray a pick needs, since a UI node stands at its own z. */
+export function uiLayoutRay(
+ overlay: ScreenOverlayData, screenGLX: number, screenGLY: number,
+): WorldRay {
+ overlayCache.update(overlay.projection);
+ const invVP = overlayCache.getInverse(overlay.projection);
+ return screenRay(screenGLX, screenGLY, invVP,
+ overlay.vpX, overlay.vpY, overlay.vpW, overlay.vpH);
+}
+
+/**
+ * The pointer, in the coordinates @p entity's own transform lives in.
+ *
+ * A UI system that subtracts a pointer from a transform — a drag, a slider's
+ * fraction, a caret — needs the two in one domain, and which domain that is
+ * depends on the entity.
+ */
+export function uiPointerFor(
+ world: PickableWorld,
+ entity: Entity,
+ camera: UICameraData,
+ overlay: ScreenOverlayData,
+): { x: number; y: number } {
+ return isScreenEntity(world, entity)
+ ? { x: overlay.pointerX, y: overlay.pointerY }
+ : { x: camera.worldMouseX, y: camera.worldMouseY };
+}
+
+/** Whether @p entity is laid out on the screen rather than in the world — the
+ * engine's own answer (UISystem::screenDomain), never a second derivation. */
+export function isScreenEntity(world: PickableWorld, entity: Entity): boolean {
+ const c = core(world);
+ return c?.engine.ui_isScreenDomain?.(c.registry, entity as number) ?? false;
+}
+
+/** A layout point's pixel on the surface, through the overlay's own projection —
+ * the forward of {@link screenToUiLayout}, for anchoring something the OS draws
+ * (an IME candidate window) under something the engine drew. */
+export function uiLayoutToScreen(
+ overlay: ScreenOverlayData, x: number, y: number,
+): { x: number; y: number } {
+ const [sx, sy] = worldToScreen(x, y, overlay.projection,
+ overlay.vpX, overlay.vpY, overlay.vpW, overlay.vpH);
+ return { x: sx, y: sy };
+}
+
export function uiWorldToScreen(camera: UICameraData, worldX: number, worldY: number): { x: number; y: number } {
const [x, y] = worldToScreen(worldX, worldY, camera.viewProjection, camera.vpX, camera.vpY, camera.vpW, camera.vpH);
return { x, y };
@@ -51,12 +115,27 @@ function core(world: PickableWorld) {
* interaction system runs, so a custom cursor agrees with the built-in one.
* A query: what a press or a hover MEANS is the interaction system's business.
*/
-export function uiHitTestWorld(world: PickableWorld, ray: WorldRay): Entity | null {
+export function uiHitTestWorld(
+ world: PickableWorld, ray: WorldRay, screenRay?: WorldRay,
+): Entity | null {
const c = core(world);
- if (!c?.engine.uiHitTest_update || !c.engine.uiHitTest_getHitEntity) return null;
- c.engine.uiHitTest_update(c.registry,
- ray.origin.x, ray.origin.y, ray.origin.z,
- ray.dir.x, ray.dir.y, ray.dir.z);
+ if (!c?.engine.uiHitTest_getHitEntity) return null;
+ // Two rays when the caller has a screen: each entity is tested through the
+ // projection it was drawn with. One ray is the older core's only question, and
+ // the right answer to it while the two domains coincide.
+ if (screenRay && c.engine.uiHitTest_updateDomains) {
+ c.engine.uiHitTest_updateDomains(c.registry,
+ ray.origin.x, ray.origin.y, ray.origin.z,
+ ray.dir.x, ray.dir.y, ray.dir.z,
+ screenRay.origin.x, screenRay.origin.y, screenRay.origin.z,
+ screenRay.dir.x, screenRay.dir.y, screenRay.dir.z);
+ } else if (c.engine.uiHitTest_update) {
+ c.engine.uiHitTest_update(c.registry,
+ ray.origin.x, ray.origin.y, ray.origin.z,
+ ray.dir.x, ray.dir.y, ray.dir.z);
+ } else {
+ return null;
+ }
const hit = c.engine.uiHitTest_getHitEntity();
return hit === NO_HIT ? null : hit;
}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index e12c57e0b..64f1996fb 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -282,6 +282,9 @@ export interface ESEngineModule {
*/
ui_getRenderOrder?(registry: CppRegistry, entity: number): number;
ui_getCullBit?(registry: CppRegistry, entity: number): number;
+ /** Whether an entity belongs to the screen rather than the world — the same
+ * answer the renderer partitions its collects by (UISystem::screenDomain). */
+ ui_isScreenDomain?(registry: CppRegistry, entity: number): boolean;
/**
* Geometry posed by a skeletal runtime (Spine, DragonBones): x,y,u,v,r,g,b,a per
@@ -449,6 +452,15 @@ export interface ESEngineModule {
clearX: number, clearY: number, clearW: number, clearH: number): void;
renderer_flush(): void;
renderer_end(): void;
+ /** Closes the frame — per FRAME, not per camera. Optional: an older core
+ * released the surface at every camera's end and answers nothing here. */
+ renderer_endFrame?(): void;
+ /** The frame's screen-space overlay. Optional as a set: a core without them
+ * has no screen pass, and screen UI stays world content. */
+ renderer_beginScreenOverlay?(projectionPtr: number, vpX: number, vpY: number,
+ vpW: number, vpH: number): void;
+ renderer_submitScreenOverlay?(registry: CppRegistry): void;
+ renderer_endScreenOverlay?(targetHandle: number): void;
renderer_submitAll(registry: CppRegistry, vpX: number, vpY: number, vpW: number, vpH: number): void;
particle_update?(registry: CppRegistry, dt: number): void;
particle_play?(registry: CppRegistry, entity: number): void;
@@ -588,6 +600,13 @@ export interface ESEngineModule {
uiHitTest_update(registry: CppRegistry,
originX: number, originY: number, originZ: number,
dirX: number, dirY: number, dirZ: number): void;
+ /** The hit test with a ray per domain: world content answers the first,
+ * screen UI the second. Optional — an older core has one domain. */
+ uiHitTest_updateDomains?(registry: CppRegistry,
+ worldOriginX: number, worldOriginY: number, worldOriginZ: number,
+ worldDirX: number, worldDirY: number, worldDirZ: number,
+ screenOriginX: number, screenOriginY: number, screenOriginZ: number,
+ screenDirX: number, screenDirY: number, screenDirZ: number): void;
uiHitTest_getHitEntity(): number;
uiHitTest_pick?(registry: CppRegistry, worldX: number, worldY: number): number;
uiHitTest_pickAll?(registry: CppRegistry, worldX: number, worldY: number): number;
diff --git a/sdk/tests/camera-render-order.test.ts b/sdk/tests/camera-render-order.test.ts
index 507a6651c..80cc84490 100644
--- a/sdk/tests/camera-render-order.test.ts
+++ b/sdk/tests/camera-render-order.test.ts
@@ -56,7 +56,11 @@ describe('render order: transforms resolve before cameras are read', () => {
},
begin: (viewProjection) => { calls.push('begin'); lastViewProjection = viewProjection; },
submitAll: () => { calls.push('submitAll'); },
- flush: () => {}, end: () => {},
+ flush: () => {}, end: () => {}, endFrame: () => { calls.push('endFrame'); },
+ // No overlay from this fake: what it records is the ORDER a frame
+ // drives its cameras in, and a screen pass is not one of them.
+ hasScreenOverlay: () => false,
+ beginScreenOverlay: () => {}, submitScreenOverlay: () => {}, endScreenOverlay: () => {},
setStage: () => {}, setViewport: () => {},
setYSortLayers: () => {}, setDepthLayers: () => {}, setCullingMask: () => {},
getStats: () => ({ drawCalls: 0, triangles: 0, sprites: 0, text: 0, skeletal: 0, meshes: 0, culled: 0 }),
diff --git a/sdk/tests/helpers/screenBox.ts b/sdk/tests/helpers/screenBox.ts
new file mode 100644
index 000000000..252321c5d
--- /dev/null
+++ b/sdk/tests/helpers/screenBox.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The screen a UI test lays out on.
+ *
+ * One helper because the box UI lays out in has ONE authority (`ScreenLayout`):
+ * a test that sets it some other way is testing a path the engine does not take.
+ */
+import type { App } from '../../src/app/app';
+import { ScreenLayout, type ScreenLayoutData } from '../../src/ui/core/screen-layout';
+
+/** A layout box, in layout pixels. One layout pixel is one device pixel here. */
+export function screenBox(
+ left: number, bottom: number, right: number, top: number,
+): ScreenLayoutData {
+ return {
+ valid: true,
+ left, bottom, right, top,
+ safeLeft: left, safeBottom: bottom, safeRight: right, safeTop: top,
+ scale: 1,
+ viewportW: right - left,
+ viewportH: top - bottom,
+ };
+}
+
+/** Install it, whether or not the App already carries one. */
+export function setScreenBox(
+ app: App, left: number, bottom: number, right: number, top: number,
+): void {
+ const box = screenBox(left, bottom, right, top);
+ if (app.hasResource(ScreenLayout)) Object.assign(app.getResource(ScreenLayout), box);
+ else app.insertResource(ScreenLayout, box);
+}
diff --git a/sdk/tests/screen-overlay.test.ts b/sdk/tests/screen-overlay.test.ts
new file mode 100644
index 000000000..ddda805f0
--- /dev/null
+++ b/sdk/tests/screen-overlay.test.ts
@@ -0,0 +1,298 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The screen is a domain, and these are the four facts that make it one.
+ *
+ * 1. A screen subtree is not consumed by any world camera.
+ * 2. Render and pick read the SAME projection, not two equal ones.
+ * 3. `Transform.worldPosition` is layout STORAGE here — it carries no depth
+ * and no world meaning, so a z left on it cannot reorder anything.
+ * 4. Nothing about the screen moves when a camera does.
+ *
+ * The pixels are gated separately (tools/renderScenes.mjs: ui-screen-3d,
+ * ui-screen-3d-camera-moved, ui-screen-root). What is here is everything a
+ * frame's pixels cannot show: which entities belong to which domain, and where
+ * a pointer lands once the two are told apart.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import { App } from '../src/app/app';
+import { Canvas, Transform, Sprite } from '../src/ecs/component';
+import { UINode, type UINodeData } from '../src/ui/core/ui-node';
+import { Interactable } from '../src/ui/input/interactable';
+import { uiLayoutPlugin } from '../src/ui/layout/layout';
+import { uiRenderOrderPlugin } from '../src/ui/render/render-order';
+import { screenLayoutRect, screenProjection } from '../src/ui/core/screen-layout';
+import { defaultScreenOverlay, type ScreenOverlayData } from '../src/ui/core/screen-overlay';
+import { screenToUiLayout, uiLayoutToScreen, uiLayoutRay, uiHitTestWorld } from '../src/ui/util/ui-pick';
+import { px, auto } from '../src/ui/core/dimension';
+import { CanvasScaleMode } from '../src/wasm/wasm.generated';
+import type { ESEngineModule, CppRegistry } from '../src/wasm';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+import { setScreenBox } from './helpers/screenBox';
+
+const FIT = {
+ designResolution: { x: 1920, y: 1080 },
+ scaleMode: CanvasScaleMode.FixedHeight,
+ matchWidthOrHeight: 0.5,
+};
+
+/** The screen as it is actually published: a layout box and the projection over it. */
+function screenAt(viewportW: number, viewportH: number): ScreenOverlayData {
+ const layout = screenLayoutRect(FIT, viewportW, viewportH);
+ const overlay = defaultScreenOverlay();
+ screenProjection(layout, overlay.projection);
+ overlay.active = true;
+ overlay.vpX = 0;
+ overlay.vpY = 0;
+ overlay.vpW = viewportW;
+ overlay.vpH = viewportH;
+ overlay.surfaceW = viewportW;
+ overlay.surfaceH = viewportH;
+ return overlay;
+}
+
+describe('the screen projection', () => {
+ it('puts the layout box exactly on the framebuffer', () => {
+ const overlay = screenAt(1280, 720);
+ const layout = screenLayoutRect(FIT, 1280, 720);
+
+ // The box's corners are the surface's corners. Nothing is cropped and
+ // nothing is padded, because the box IS the screen.
+ const bl = uiLayoutToScreen(overlay, layout.left, layout.bottom);
+ const tr = uiLayoutToScreen(overlay, layout.right, layout.top);
+ expect(bl.x).toBeCloseTo(0, 3);
+ expect(bl.y).toBeCloseTo(0, 3);
+ expect(tr.x).toBeCloseTo(1280, 3);
+ expect(tr.y).toBeCloseTo(720, 3);
+ // ...and the origin is the middle, which is what makes a screen root's
+ // placement a fact about the screen rather than about a camera.
+ const mid = uiLayoutToScreen(overlay, 0, 0);
+ expect(mid.x).toBeCloseTo(640, 3);
+ expect(mid.y).toBeCloseTo(360, 3);
+ });
+
+ it('round-trips a layout point through a pixel and back', () => {
+ for (const [w, h] of [[1280, 720], [800, 600], [390, 844]] as const) {
+ const overlay = screenAt(w, h);
+ const layout = screenLayoutRect(FIT, w, h);
+ for (const p of [
+ { x: 0, y: 0 },
+ { x: layout.left, y: layout.bottom },
+ { x: layout.right * 0.5, y: layout.top * 0.25 },
+ { x: -123.5, y: 77.25 },
+ ]) {
+ const pixel = uiLayoutToScreen(overlay, p.x, p.y);
+ const back = screenToUiLayout(overlay, pixel.x, pixel.y);
+ expect(back.x).toBeCloseTo(p.x, 3);
+ expect(back.y).toBeCloseTo(p.y, 3);
+ }
+ }
+ });
+
+ /**
+ * Not "the two agree" — "there is only one". The pick reads the very matrix
+ * the overlay is handed, so changing it changes both; two derivations drift
+ * the moment either gains a case.
+ */
+ it('is the one matrix the pointer is inverted through', () => {
+ const overlay = screenAt(1280, 720);
+ const before = screenToUiLayout(overlay, 320, 180);
+
+ // Halve the span the projection covers, in place — as a resize does.
+ screenProjection(screenLayoutRect(FIT, 640, 360), overlay.projection);
+ overlay.vpW = 640;
+ overlay.vpH = 360;
+ const after = screenToUiLayout(overlay, 160, 90);
+
+ // Same fraction of the surface, same layout point: the pointer followed
+ // the projection because it reads it rather than re-deriving it.
+ expect(after.x).toBeCloseTo(before.x, 3);
+ expect(after.y).toBeCloseTo(before.y, 3);
+ });
+});
+
+function node(over: Partial<UINodeData> = {}): UINodeData {
+ return {
+ position: 0,
+ width: auto(), height: auto(),
+ minWidth: auto(), minHeight: auto(),
+ maxWidth: auto(), maxHeight: auto(),
+ flexGrow: 0, flexShrink: 1, flexBasis: auto(),
+ alignSelf: 0,
+ marginLeft: px(0), marginTop: px(0), marginRight: px(0), marginBottom: px(0),
+ insetLeft: auto(), insetTop: auto(), insetRight: auto(), insetBottom: auto(),
+ ...over,
+ } as UINodeData;
+}
+
+/** Absolute, pinned to the box's top-left, at a fixed size. */
+function pinned(w: number, h: number): UINodeData {
+ return node({
+ position: 1,
+ insetLeft: px(0), insetTop: px(0),
+ width: px(w), height: px(h),
+ });
+}
+
+function transform(x = 0, y = 0, z = 0) {
+ return {
+ position: { x, y, z },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+ };
+}
+
+describe.skipIf(!HAS_WASM)('the screen domain (WASM integration)', () => {
+ let module: ESEngineModule;
+ beforeAll(async () => { module = await loadWasmModule(); });
+
+ function createApp() {
+ const app = App.new();
+ const registry = new module.Registry() as unknown as CppRegistry;
+ app.connectCpp(registry, module);
+ setScreenBox(app, -960, -540, 960, 540);
+ app.addPlugin(uiLayoutPlugin);
+ app.addPlugin(uiRenderOrderPlugin);
+ return { app, registry };
+ }
+
+ function dispose(app: App, registry: CppRegistry): void {
+ for (const e of app.world.getAllEntities()) {
+ try { app.world.despawn(e); } catch { /* already gone */ }
+ }
+ app.world.disconnectCpp();
+ (registry as unknown as { delete(): void }).delete();
+ }
+
+ const isScreen = (registry: CppRegistry, e: number): boolean =>
+ module.ui_isScreenDomain!(registry, e);
+
+ it('is inherited by the whole subtree, whatever each entity carries', async () => {
+ const { app, registry } = createApp();
+ const world = app.world;
+
+ const canvas = world.spawn();
+ world.insert(canvas, Canvas, {});
+ world.insert(canvas, UINode, node());
+ world.insert(canvas, Transform, transform());
+
+ const panel = world.spawn();
+ world.insert(panel, UINode, pinned(200, 100));
+ world.insert(panel, Transform, transform());
+ world.setParent(panel, canvas);
+
+ // A bare Sprite parented into the HUD: not a layout node, so a set built
+ // from the LAYOUT tree would leave exactly this one renderable behind in
+ // the world domain, drawn at layout-pixel coordinates.
+ const decoration = world.spawn();
+ world.insert(decoration, Sprite, {});
+ world.insert(decoration, Transform, transform());
+ world.setParent(decoration, panel);
+
+ await app.tick(1 / 60);
+
+ expect(isScreen(registry, canvas as number)).toBe(true);
+ expect(isScreen(registry, panel as number)).toBe(true);
+ expect(isScreen(registry, decoration as number)).toBe(true);
+
+ dispose(app, registry);
+ });
+
+ it('stops at a Canvas that hangs off a world entity', async () => {
+ const { app, registry } = createApp();
+ const world = app.world;
+
+ const anchor = world.spawn();
+ world.insert(anchor, Transform, transform(500, 250));
+
+ const worldCanvas = world.spawn();
+ world.insert(worldCanvas, Canvas, {});
+ world.insert(worldCanvas, UINode, node());
+ world.insert(worldCanvas, Transform, transform());
+ world.setParent(worldCanvas, anchor);
+
+ const badge = world.spawn();
+ world.insert(badge, UINode, pinned(64, 64));
+ world.insert(badge, Transform, transform());
+ world.setParent(badge, worldCanvas);
+
+ await app.tick(1 / 60);
+
+ // It rides its parent through the world, so it is the world's — a HUD is
+ // what has no parent to ride.
+ expect(isScreen(registry, worldCanvas as number)).toBe(false);
+ expect(isScreen(registry, badge as number)).toBe(false);
+
+ dispose(app, registry);
+ });
+
+ it('places a screen root about the origin, in layout pixels', async () => {
+ const { app, registry } = createApp();
+ const world = app.world;
+
+ const canvas = world.spawn();
+ world.insert(canvas, Canvas, {});
+ world.insert(canvas, UINode, node());
+ world.insert(canvas, Transform, transform(777, -333, 0));
+
+ await app.tick(1 / 60);
+
+ // Whatever the scene authored, the layout pass owns a screen root's
+ // placement, and the box it places within is centred on nothing.
+ const t = registry.getTransform(canvas as number);
+ expect(t.position.x).toBeCloseTo(0, 3);
+ expect(t.position.y).toBeCloseTo(0, 3);
+
+ dispose(app, registry);
+ });
+
+ /**
+ * The half that no pixel shows. A HUD drawn through the overlay and picked
+ * through a camera is the failure mode that looks like success, so the ray
+ * the pointer becomes has to come from the same place the picture did.
+ */
+ it('answers a pointer through the overlay, whatever the camera is doing', async () => {
+ const { app, registry } = createApp();
+ const world = app.world;
+
+ const canvas = world.spawn();
+ world.insert(canvas, Canvas, {});
+ world.insert(canvas, UINode, node());
+ world.insert(canvas, Transform, transform());
+
+ // Top-left quarter of a 1920x1080 design box.
+ const button = world.spawn();
+ world.insert(button, UINode, pinned(960, 540));
+ world.insert(button, Transform, transform());
+ world.insert(button, Interactable, {});
+ world.setParent(button, canvas);
+
+ await app.tick(1 / 60);
+
+ const overlay = screenAt(1920, 1080);
+ const pickable = { getCppRegistry: () => registry, getWasmModule: () => module };
+
+ // A pixel inside the button's quarter of the screen (GL coordinates, so
+ // y counts up from the bottom: the top-left quarter is high y).
+ const inside = uiLayoutRay(overlay, 480, 810);
+ // ...and one in the opposite corner, which nothing covers.
+ const outside = uiLayoutRay(overlay, 1440, 270);
+
+ // The world ray is deliberately absurd — a camera a mile away, looking
+ // somewhere else. It must change nothing: the button is not in its world.
+ const farAway = {
+ origin: { x: 40000, y: -9000, z: 500 },
+ dir: { x: 0, y: 0, z: -1 },
+ };
+
+ expect(uiHitTestWorld(pickable, farAway, inside)).toBe(button);
+ expect(uiHitTestWorld(pickable, farAway, outside)).toBe(null);
+
+ // One ray for everything cannot answer it: that ray is in the world and
+ // the button is not. Without this the assertions above would pass just as
+ // well on a build that ignored the second ray.
+ expect(uiHitTestWorld(pickable, farAway)).toBe(null);
+
+ dispose(app, registry);
+ });
+});
diff --git a/sdk/tests/ui-anchor-preset.test.ts b/sdk/tests/ui-anchor-preset.test.ts
index f49c1081c..b2fda9211 100644
--- a/sdk/tests/ui-anchor-preset.test.ts
+++ b/sdk/tests/ui-anchor-preset.test.ts
@@ -21,6 +21,7 @@ import { DimensionUnit, px, auto } from '../src/ui/core/dimension';
import { App } from '../src/app/app';
import { Canvas, Transform, Sprite } from '../src/ecs/component';
import { UICameraInfo } from '../src/ui/core/ui-camera-info';
+import { setScreenBox } from './helpers/screenBox';
import { uiLayoutPlugin } from '../src/ui/layout/layout';
import type { ESEngineModule, CppRegistry } from '../src/wasm';
import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
@@ -115,6 +116,7 @@ describe.skipIf(!HAS_WASM)('anchor presets lay out via Yoga (WASM integration)',
worldLeft: -400, worldBottom: -300, worldRight: 400, worldTop: 300,
worldMouseX: 0, worldMouseY: 0, valid: true,
});
+ setScreenBox(app, -400, -300, 400, 300);
app.addPlugin(uiLayoutPlugin);
return { app, registry };
}
diff --git a/sdk/tests/ui-components.test.ts b/sdk/tests/ui-components.test.ts
index 4f0648272..c3416ca16 100644
--- a/sdk/tests/ui-components.test.ts
+++ b/sdk/tests/ui-components.test.ts
@@ -17,6 +17,7 @@ import { UIMask, MaskMode } from '../src/ui/core/ui-mask';
import { FlexContainer, FlexDirection, JustifyContent, AlignItems } from '../src/ui/layout/flex';
import { Interactable, UIInteraction } from '../src/ui/input/interactable';
import { UICameraInfo } from '../src/ui/core/ui-camera-info';
+import { setScreenBox } from './helpers/screenBox';
import { uiLayoutPlugin } from '../src/ui/layout/layout';
import { uiRenderOrderPlugin } from '../src/ui/render/render-order';
import type { ESEngineModule, CppRegistry } from '../src/wasm';
@@ -92,13 +93,10 @@ describe.skipIf(!HAS_WASM)('UI Components (WASM integration)', () => {
(registry as unknown as { delete(): void }).delete();
}
+ // The box UI lays out in is the screen's, and a camera has no way to reach
+ // it (ui/core/screen-layout.ts).
function setCanvasRect(app: App, left: number, bottom: number, right: number, top: number): void {
- const cam = app.getResource(UICameraInfo);
- cam.worldLeft = left;
- cam.worldBottom = bottom;
- cam.worldRight = right;
- cam.worldTop = top;
- cam.valid = true;
+ setScreenBox(app, left, bottom, right, top);
}
function makeTransform() {
diff --git a/sdk/tests/ui-layout-incremental.test.ts b/sdk/tests/ui-layout-incremental.test.ts
index 6920a6576..6df9957cf 100644
--- a/sdk/tests/ui-layout-incremental.test.ts
+++ b/sdk/tests/ui-layout-incremental.test.ts
@@ -25,6 +25,7 @@ import { App } from '../src/app/app';
import { Canvas, Transform } from '../src/ecs/component';
import { FlexContainer } from '../src/ui/layout/flex';
import { UICameraInfo } from '../src/ui/core/ui-camera-info';
+import { setScreenBox } from './helpers/screenBox';
import { uiLayoutPlugin } from '../src/ui/layout/layout';
import type { ESEngineModule, CppRegistry } from '../src/wasm';
import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
@@ -65,6 +66,7 @@ describe.skipIf(!HAS_WASM)('incremental layout equals a fresh solve', () => {
worldRight: camW / 2, worldTop: camH / 2,
worldMouseX: 0, worldMouseY: 0, valid: true,
});
+ setScreenBox(app, -camW / 2, -camH / 2, camW / 2, camH / 2);
app.addPlugin(uiLayoutPlugin);
return { app, registry };
}
@@ -155,9 +157,8 @@ describe.skipIf(!HAS_WASM)('incremental layout equals a fresh solve', () => {
await live.app.tick(1 / 60);
await perturb(live.app, liveIds, () => live.app.tick(1 / 60));
if (camAfter) {
- const cam = live.app.getResource(UICameraInfo);
- cam.worldLeft = -camAfter.w / 2; cam.worldRight = camAfter.w / 2;
- cam.worldBottom = -camAfter.h / 2; cam.worldTop = camAfter.h / 2;
+ setScreenBox(live.app, -camAfter.w / 2, -camAfter.h / 2,
+ camAfter.w / 2, camAfter.h / 2);
}
await live.app.tick(1 / 60);
const incremental = read(live.registry, label(liveIds));
diff --git a/sdk/tests/ui-layout-integration.test.ts b/sdk/tests/ui-layout-integration.test.ts
index 2b3d4a266..a5da23cba 100644
--- a/sdk/tests/ui-layout-integration.test.ts
+++ b/sdk/tests/ui-layout-integration.test.ts
@@ -14,6 +14,7 @@ import { UINode, type UINodeData } from '../src/ui/core/ui-node';
import { FlexContainer, type FlexContainerData } from '../src/ui/layout/flex';
import { Canvas } from '../src/ecs/component';
import { UICameraInfo } from '../src/ui/core/ui-camera-info';
+import { ScreenLayout } from '../src/ui/core/screen-layout';
import { uiLayoutPlugin } from '../src/ui/layout/layout';
import { uiRenderOrderPlugin } from '../src/ui/render/render-order';
import { Transform, Sprite } from '../src/ecs/component';
@@ -108,6 +109,7 @@ describe.skipIf(!HAS_WASM)('UI Layout via App.tick() (WASM integration)', () =>
worldMouseX: 0, worldMouseY: 0,
valid: false,
});
+ app.insertResource(ScreenLayout, { ...ScreenLayout._default });
app.addPlugin(uiLayoutPlugin);
app.addPlugin(uiRenderOrderPlugin);
@@ -123,13 +125,22 @@ describe.skipIf(!HAS_WASM)('UI Layout via App.tick() (WASM integration)', () =>
(registry as unknown as { delete(): void }).delete();
}
+ // The box UI lays out in is the SCREEN's, not a camera's — a camera has no
+ // way to reach it (see ui/core/screen-layout.ts).
function setCanvasRect(app: App, left: number, bottom: number, right: number, top: number): void {
- const cam = app.getResource(UICameraInfo);
- cam.worldLeft = left;
- cam.worldBottom = bottom;
- cam.worldRight = right;
- cam.worldTop = top;
- cam.valid = true;
+ const screen = app.getResource(ScreenLayout);
+ screen.left = left;
+ screen.bottom = bottom;
+ screen.right = right;
+ screen.top = top;
+ screen.safeLeft = left;
+ screen.safeBottom = bottom;
+ screen.safeRight = right;
+ screen.safeTop = top;
+ screen.scale = 1;
+ screen.viewportW = right - left;
+ screen.viewportH = top - bottom;
+ screen.valid = true;
}
const nodeW = (registry: CppRegistry, e: number) => module.getUINodeComputedWidth!(registry, e);
diff --git a/sdk/tests/ui-text-render-mode.test.ts b/sdk/tests/ui-text-render-mode.test.ts
index ee5e8890a..27b42fd8a 100644
--- a/sdk/tests/ui-text-render-mode.test.ts
+++ b/sdk/tests/ui-text-render-mode.test.ts
@@ -83,37 +83,34 @@ describe('GlyphAtlas content scale (bitmap rasterization density)', () => {
});
describe('glyphContentScale (what size to rasterize FOR)', () => {
- const cam = (over: Record<string, unknown> = {}) => ({
- valid: true, vpW: 1920, worldLeft: -960, worldRight: 960,
- viewProjection: new Float32Array([2 / 1920, 0, 0, 0]),
- ...over,
- } as never);
+ // Element 0 of an orthographic projection: 2 / the span it shows. It takes
+ // the PROJECTION, not a camera — world text asks with the camera's and screen
+ // text with the overlay's.
+ const projFor = (span: number) => 2 / span;
it('is device pixels per world unit, so a 1:1 view rasterizes 1:1', () => {
- expect(glyphContentScale(cam(), 1)).toBeCloseTo(1, 5);
- expect(glyphContentScale(cam(), 2)).toBeCloseTo(0.5, 5); // dpr folded in by the atlas
+ expect(glyphContentScale(projFor(1920), 1920, 1)).toBeCloseTo(1, 5);
+ expect(glyphContentScale(projFor(1920), 1920, 2)).toBeCloseTo(0.5, 5); // dpr folded in by the atlas
});
// The editor holds the layout box at the design size on purpose, so UI does
// not reflow while the view zooms. Reading the span from that box asked for
// design-sized glyphs and let the camera scale them — the blur this fixes.
- it('follows the camera when it shows less than the layout box (zoomed in)', () => {
- const zoomed = cam({ viewProjection: new Float32Array([2 / 480, 0, 0, 0]) }); // 4× in
- expect(glyphContentScale(zoomed, 1)).toBeCloseTo(4, 5);
+ it('follows the projection when it shows less than the layout box (zoomed in)', () => {
+ expect(glyphContentScale(projFor(480), 1920, 1)).toBeCloseTo(4, 5); // 4x in
});
- it('follows the camera when it shows more than the layout box (zoomed out)', () => {
- const wide = cam({ viewProjection: new Float32Array([2 / 3840, 0, 0, 0]) }); // 2× out
- expect(glyphContentScale(wide, 1)).toBeCloseTo(0.5, 5);
+ it('follows the projection when it shows more than the layout box (zoomed out)', () => {
+ expect(glyphContentScale(projFor(3840), 1920, 1)).toBeCloseTo(0.5, 5); // 2x out
});
- it('falls back to the layout box when the projection says nothing', () => {
- expect(glyphContentScale(cam({ viewProjection: new Float32Array(4) }), 1)).toBeCloseTo(1, 5);
+ it('is 1 when the projection says nothing, rather than guessing from a box', () => {
+ expect(glyphContentScale(0, 1920, 1)).toBe(1);
+ expect(glyphContentScale(NaN, 1920, 1)).toBe(1);
});
- it('is 1 when there is no valid camera, or a nonsense dpr', () => {
- expect(glyphContentScale(undefined, 1)).toBe(1);
- expect(glyphContentScale(cam({ valid: false }), 1)).toBe(1);
- expect(glyphContentScale(cam(), 0)).toBe(1);
+ it('is 1 with no viewport, or a nonsense dpr', () => {
+ expect(glyphContentScale(projFor(1920), 0, 1)).toBe(1);
+ expect(glyphContentScale(projFor(1920), 1920, 0)).toBe(1);
});
});
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 59c418248..764af6419 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -31,6 +31,7 @@
#include "../core/RandomSource.hpp"
#endif
#include "../trail/TrailSystem.hpp"
+#include "../ui/UISystem.hpp"
#ifdef __EMSCRIPTEN__
#include <emscripten/val.h>
@@ -451,6 +452,11 @@ void renderer_end() {
checkGLErrors("renderer_end");
}
+void renderer_endFrame() {
+ if (!g_renderFrame) return;
+ g_renderFrame->endFrame();
+}
+
/** Compose if a producer said the inputs moved. The renderer is a consumer of
* world transforms, not the authority over when they are computed. */
static void ensureTransformsUpdated(ecs::Registry& registry) {
@@ -484,9 +490,41 @@ void renderer_setEntityDrawOrder(ecs::Registry& registry, uintptr_t entitiesPtr,
ecs::applySceneEntityOrder(registry, order.data(), order.size());
}
+/** The screen's entities, as a membership set the renderer can partition by.
+ * Empty when there is no UI system — then every collect is a world one, which
+ * is what a project with no Canvas has always had. */
+static const std::unordered_set<u32>* screenDomain() {
+ auto* ui = ctx().tryGet<ecs::UISystem>();
+ return ui ? &ui->screenDomain() : nullptr;
+}
+
+void renderer_beginScreenOverlay(uintptr_t projectionPtr, i32 vpX, i32 vpY, u32 vpW, u32 vpH) {
+ if (!g_renderFrame) return;
+ const f32* matrixData = boundarySpan<f32>(projectionPtr, 16, "renderer_beginScreenOverlay.matrix");
+ if (!matrixData) return;
+ g_renderFrame->beginScreenOverlay(glm::make_mat4(matrixData), vpX, vpY, vpW, vpH);
+}
+
+void renderer_submitScreenOverlay(ecs::Registry& registry) {
+ if (!g_renderFrame) return;
+ ensureTransformsUpdated(registry);
+ g_renderFrame->setScreenDomain(screenDomain());
+ g_renderFrame->submitScreenOverlay(registry);
+}
+
+void renderer_endScreenOverlay(u32 targetHandle) {
+ if (!g_renderFrame) return;
+ g_renderFrame->endScreenOverlay(targetHandle);
+ checkGLErrors("renderer_endScreenOverlay");
+}
+
void renderer_submitAll(ecs::Registry& registry, i32 vpX, i32 vpY, i32 vpW, i32 vpH) {
if (!g_renderFrame) return;
ensureTransformsUpdated(registry);
+ // What this camera must NOT draw. Set on every collect rather than once a
+ // frame: the set is rebuilt by each layout pass, and a camera holding the
+ // previous one would draw a just-reparented element in the wrong domain.
+ g_renderFrame->setScreenDomain(screenDomain());
g_renderFrame->processMasks(registry, vpX, vpY, vpW, vpH);
g_renderFrame->collectAll(registry);
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index b467bd2c0..4b7f6e745 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -30,6 +30,16 @@ void renderer_begin(uintptr_t matrixPtr, u32 targetHandle, i32 clearFlags,
i32 clearX, i32 clearY, u32 clearW, u32 clearH);
void renderer_flush();
void renderer_end();
+/// Closes the frame — the pair of beginFrame, and where a borrowed swapchain
+/// image goes back. Per FRAME, not per camera (see RenderFrame::endFrame).
+void renderer_endFrame();
+
+/// The frame's screen-space overlay, drawn once after every camera and after
+/// post: begin with the projection the layout domain reaches pixels through,
+/// collect, let the host add its own screen geometry, then declare and run it.
+void renderer_beginScreenOverlay(uintptr_t projectionPtr, i32 vpX, i32 vpY, u32 vpW, u32 vpH);
+void renderer_submitScreenOverlay(ecs::Registry& registry);
+void renderer_endScreenOverlay(u32 targetHandle);
#ifdef ES_ENABLE_BITMAP_TEXT
#endif
/// Geometry posed by a skeletal runtime (Spine, DragonBones): x,y,u,v,r,g,b,a per
diff --git a/src/esengine/bindings/UIBindings.cpp b/src/esengine/bindings/UIBindings.cpp
index 65770c7e2..dca722770 100644
--- a/src/esengine/bindings/UIBindings.cpp
+++ b/src/esengine/bindings/UIBindings.cpp
@@ -41,6 +41,19 @@ void uiHitTest_update(ecs::Registry& registry,
ctx().tryGet<resource::ResourceManager>());
}
+void uiHitTest_updateDomains(ecs::Registry& registry,
+ f32 worldOriginX, f32 worldOriginY, f32 worldOriginZ,
+ f32 worldDirX, f32 worldDirY, f32 worldDirZ,
+ f32 screenOriginX, f32 screenOriginY, f32 screenOriginZ,
+ f32 screenDirX, f32 screenDirY, f32 screenDirZ) {
+ const ecs::PickRay world{{worldOriginX, worldOriginY, worldOriginZ},
+ {worldDirX, worldDirY, worldDirZ}};
+ const ecs::PickRay screen{{screenOriginX, screenOriginY, screenOriginZ},
+ {screenDirX, screenDirY, screenDirZ}};
+ ctx().require<ecs::UISystem>().hitTestUpdate(registry, world, screen,
+ ctx().tryGet<resource::ResourceManager>());
+}
+
u32 uiHitTest_getHitEntity() {
return ctx().require<ecs::UISystem>().getHitEntity();
}
@@ -88,6 +101,12 @@ u32 ui_getCullBit(ecs::Registry& registry, u32 entity) {
return ui ? ui->uiCullBit : 0u;
}
+bool ui_isScreenDomain(ecs::Registry& registry, u32 entity) {
+ (void)registry;
+ auto* ui = ctx().tryGet<ecs::UISystem>();
+ return ui && ui->screenDomain().count(entity) != 0;
+}
+
// UINode (CSS box) computed size — its internal computed_size_ is not
// embind-readable, so expose it for TS uiHelpers.
bool getUINodeHiddenInTree(ecs::Registry& registry, u32 entity) {
diff --git a/src/esengine/bindings/UIBindings.hpp b/src/esengine/bindings/UIBindings.hpp
index 2fe5550ce..4729c4ffa 100644
--- a/src/esengine/bindings/UIBindings.hpp
+++ b/src/esengine/bindings/UIBindings.hpp
@@ -35,6 +35,19 @@ void uiLayout_update(ecs::Registry& registry, f32 boxLeft, f32 boxBottom, f32 bo
void uiHitTest_update(ecs::Registry& registry,
f32 originX, f32 originY, f32 originZ,
f32 dirX, f32 dirY, f32 dirZ);
+/**
+ * @brief The hit test with a ray per domain — world content and world-space UI
+ * answer the first, screen UI the second.
+ *
+ * @details A separate entry point rather than more parameters: these are bound by
+ * NAME, and widening a signature makes an older core throw rather than
+ * decline.
+ */
+void uiHitTest_updateDomains(ecs::Registry& registry,
+ f32 worldOriginX, f32 worldOriginY, f32 worldOriginZ,
+ f32 worldDirX, f32 worldDirY, f32 worldDirZ,
+ f32 screenOriginX, f32 screenOriginY, f32 screenOriginZ,
+ f32 screenDirX, f32 screenDirY, f32 screenDirZ);
u32 uiHitTest_getHitEntity();
u32 uiHitTest_pick(ecs::Registry& registry, f32 worldX, f32 worldY);
u32 uiHitTest_pickAll(ecs::Registry& registry, f32 worldX, f32 worldY);
@@ -52,6 +65,14 @@ void uiRenderOrder_update(ecs::Registry& registry);
i32 ui_getRenderOrder(ecs::Registry& registry, u32 entity);
/** Mask bit of the owning Canvas' layer, for Camera.cullingMask. 0 = not a UI node. */
u32 ui_getCullBit(ecs::Registry& registry, u32 entity);
+/**
+ * @brief Whether @p entity belongs to the SCREEN rather than to the world.
+ *
+ * @details The same answer the renderer partitions its collects by, asked here
+ * because the SDK submits some of the screen's geometry itself — glyph
+ * quads — into the list the panel behind them went into.
+ */
+bool ui_isScreenDomain(ecs::Registry& registry, u32 entity);
/** UINode computed state that is not embind-readable off the component. */
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 04a6a9a3c..2c142dc96 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -632,6 +632,10 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_begin", &esengine::renderer_begin);
emscripten::function("renderer_flush", &esengine::renderer_flush);
emscripten::function("renderer_end", &esengine::renderer_end);
+ emscripten::function("renderer_endFrame", &esengine::renderer_endFrame);
+ emscripten::function("renderer_beginScreenOverlay", &esengine::renderer_beginScreenOverlay);
+ emscripten::function("renderer_submitScreenOverlay", &esengine::renderer_submitScreenOverlay);
+ emscripten::function("renderer_endScreenOverlay", &esengine::renderer_endScreenOverlay);
#ifdef ES_ENABLE_BITMAP_TEXT
#endif
@@ -774,6 +778,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
EMSCRIPTEN_BINDINGS(esengine_ui_systems) {
emscripten::function("uiLayout_update", &esengine::uiLayout_update);
emscripten::function("uiHitTest_update", &esengine::uiHitTest_update);
+ emscripten::function("uiHitTest_updateDomains", &esengine::uiHitTest_updateDomains);
emscripten::function("uiHitTest_getHitEntity", &esengine::uiHitTest_getHitEntity);
emscripten::function("uiHitTest_pick", &esengine::uiHitTest_pick);
emscripten::function("uiHitTest_pickAll", &esengine::uiHitTest_pickAll);
@@ -783,6 +788,7 @@ EMSCRIPTEN_BINDINGS(esengine_ui_systems) {
emscripten::function("uiRenderOrder_update", &esengine::uiRenderOrder_update);
emscripten::function("ui_getRenderOrder", &esengine::ui_getRenderOrder);
emscripten::function("ui_getCullBit", &esengine::ui_getCullBit);
+ emscripten::function("ui_isScreenDomain", &esengine::ui_isScreenDomain);
emscripten::function("getUINodeHiddenInTree", &esengine::getUINodeHiddenInTree);
emscripten::function("getUINodeAlphaInTree", &esengine::getUINodeAlphaInTree);
emscripten::function("getUINodeComputedWidth", &esengine::getUINodeComputedWidth);
diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hpp
index 90467e747..d7707ed76 100644
--- a/src/esengine/renderer/RenderTypePlugin.hpp
+++ b/src/esengine/renderer/RenderTypePlugin.hpp
@@ -4,6 +4,7 @@
#include "../core/Types.hpp"
#include "./frame/RenderStage.hpp"
+#include "./frame/Frustum.hpp"
#include "./frame/FrameConstants.hpp"
#include "./draw/RenderItem.hpp"
#include "./draw/DrawCommand.hpp"
@@ -19,10 +20,10 @@
#include <glm/gtc/quaternion.hpp>
#include <cmath>
+#include <unordered_set>
namespace esengine {
-struct Frustum;
class RenderContext;
class MaterialStore;
class RenderFrame;
@@ -38,6 +39,10 @@ class RenderFrame;
enum class RenderPurpose : u8 {
Scene,
ShadowDepth,
+ /// The frame's screen-space overlay: one pass after every camera and after
+ /// post, drawing what belongs to the screen rather than the world. It has no
+ /// camera — the projection it is given comes from the layout domain.
+ ScreenOverlay,
};
struct RenderFrameContext {
@@ -107,6 +112,53 @@ struct RenderCollectContext {
RenderFrameContext& frame_context;
CameraView camera;
+ /**
+ * @brief The entities the SCREEN owns (UISystem::screenDomain), or null.
+ *
+ * @details A set rather than the UI system itself, so the renderer keeps
+ * knowing nothing about UI: what it needs is a membership answer,
+ * and that is all a set is.
+ */
+ const std::unordered_set<u32>* screen_ui = nullptr;
+
+ /** @brief Whether this collect is the frame's screen overlay. */
+ bool isOverlay() const { return frame_context.purpose == RenderPurpose::ScreenOverlay; }
+
+ /**
+ * @brief Whether @p entity belongs to THIS collect.
+ *
+ * @details One predicate, not a test on each side: the two collects partition
+ * the world, and two tests drifting apart is how something is drawn
+ * twice — or by nobody, which is what a 3D HUD was.
+ */
+ bool accepts(Entity entity) const {
+ const bool screen = screen_ui && screen_ui->count(entity.id()) != 0;
+ return isOverlay() == screen;
+ }
+
+ /**
+ * @brief Whether a renderable bounded by @p centre / @p halfExtents survives
+ * this collect's cull.
+ *
+ * @details The overlay has no camera to be outside of: a screen element is on
+ * the screen by construction, and a frustum test would ask about
+ * wherever something else happens to be looking.
+ */
+ bool visible(const glm::vec3& centre, const glm::vec3& halfExtents) const {
+ return isOverlay() || frustum.intersectsAABB(centre, halfExtents);
+ }
+
+ /**
+ * @brief The sort depth of a draw anchored at @p worldPos.
+ *
+ * @details One value for every screen draw: their order is the UI tree's
+ * (layer = UI_BASE_LAYER + uiOrder), so a z left on a screen root's
+ * transform cannot outrank its siblings.
+ */
+ f32 sortDepth(const glm::vec3& worldPos) const {
+ return isOverlay() ? 0.0f : camera.viewDepth(worldPos);
+ }
+
/**
* @brief How many renderables this collect's frustum rejected.
*
@@ -213,6 +265,15 @@ public:
*/
virtual bool castsShadows() const { return false; }
+ /**
+ * @brief Whether this plugin can draw an entity that lives in a UI tree.
+ *
+ * @details The overlay collect runs only these. Saying yes is a promise to
+ * consult RenderCollectContext::accepts, without which the plugin
+ * draws the screen's entities in the world's pass too.
+ */
+ virtual bool drawsScreenUI() const { return false; }
+
virtual void collect(RenderCollectContext& ctx) = 0;
};
diff --git a/src/esengine/renderer/frame/Frustum.hpp b/src/esengine/renderer/frame/Frustum.hpp
new file mode 100644
index 000000000..aa45af61f
--- /dev/null
+++ b/src/esengine/renderer/frame/Frustum.hpp
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Frustum.hpp
+ * @brief The six planes a projection bounds, and the box test against them.
+ *
+ * @details Its own header because both sides of the collect need it: the frame
+ * builds one, and the collect context each plugin is handed answers
+ * "is this visible" with it. Left inside RenderFrame.hpp those two
+ * could not both see it — RenderFrame.hpp includes RenderTypePlugin.hpp,
+ * so the plugin side only ever had a forward declaration.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+
+#include <glm/glm.hpp>
+
+namespace esengine {
+
+struct Plane {
+ glm::vec3 normal;
+ f32 distance;
+ f32 signedDistance(const glm::vec3& point) const;
+};
+
+struct Frustum {
+ Plane planes[6];
+ void extractFromMatrix(const glm::mat4& vp);
+ bool intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtents) const;
+};
+
+} // namespace esengine
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 0c8fea0ce..3d0a79a59 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -271,6 +271,10 @@ void RenderFrame::releaseFrameTargets() {
}
void RenderFrame::beginFrame() {
+ // A frame a host never closed. Forgiving rather than strict: the cost of
+ // closing it here is one frame's deferral, and the cost of NOT is a backend
+ // holding a swapchain image forever.
+ device_.endFrame();
// Here and not at end(), which runs once per CAMERA: every camera plans and
// renders its own maps, and the pool hands the same physical atlas to each in
// turn. Then one tick of the clock, by the frame that owns the pool.
@@ -409,6 +413,36 @@ void RenderFrame::openPass(const PassClear& clear, RenderTargetManager::Handle t
scene_fbo_ = pass.target;
}
+// What a finalized list cost, added to the frame's tally. Accumulated rather
+// than assigned because a frame reports more than one list: the scene's, and the
+// screen overlay's after every camera.
+void RenderFrame::accumulateStats(const DrawList& list) {
+ stats_.draw_calls += list.mergedDrawCallCount();
+ for (u32 i = 0; i < list.commandCount(); ++i) {
+ const auto& cmd = list.command(i);
+ // An instanced command holds ONE copy of the geometry and draws it
+ // instance_count times; a batched one merged its indices in already. The
+ // multiply is what stops the number meaning two things on the two paths.
+ stats_.triangles += (cmd.index_count / 3) * (cmd.instance_count ? cmd.instance_count : 1);
+ switch (cmd.type) {
+ case RenderType::Sprite:
+ case RenderType::UIElement:
+ stats_.sprites += cmd.entity_count; break;
+ case RenderType::Text: stats_.text += cmd.entity_count; break;
+ case RenderType::Mesh:
+ case RenderType::ExternalMesh:
+ case RenderType::Trail:
+ stats_.meshes += cmd.entity_count; break;
+#ifdef ES_ENABLE_PARTICLES
+ case RenderType::Particle: stats_.particles += cmd.entity_count; break;
+#endif
+ case RenderType::Shape: stats_.shapes += cmd.entity_count; break;
+ case RenderType::Skeletal: stats_.skeletal += cmd.entity_count; break;
+ default: break;
+ }
+ }
+}
+
void RenderFrame::flush() {
if (!in_frame_ || flushed_) return;
@@ -436,30 +470,7 @@ void RenderFrame::flush() {
// pass carries the camera's own rather than inheriting it.
scene_viewport_ = device_.viewport();
- stats_.draw_calls = draw_list_.mergedDrawCallCount();
- for (u32 i = 0; i < draw_list_.commandCount(); ++i) {
- const auto& cmd = draw_list_.command(i);
- // An instanced command holds ONE copy of the geometry and draws it
- // instance_count times; a batched one merged its indices in already. The
- // multiply is what stops the number meaning two things on the two paths.
- stats_.triangles += (cmd.index_count / 3) * (cmd.instance_count ? cmd.instance_count : 1);
- switch (cmd.type) {
- case RenderType::Sprite:
- case RenderType::UIElement:
- stats_.sprites += cmd.entity_count; break;
- case RenderType::Text: stats_.text += cmd.entity_count; break;
- case RenderType::Mesh:
- case RenderType::ExternalMesh:
- case RenderType::Trail:
- stats_.meshes += cmd.entity_count; break;
-#ifdef ES_ENABLE_PARTICLES
- case RenderType::Particle: stats_.particles += cmd.entity_count; break;
-#endif
- case RenderType::Shape: stats_.shapes += cmd.entity_count; break;
- case RenderType::Skeletal: stats_.skeletal += cmd.entity_count; break;
- default: break;
- }
- }
+ accumulateStats(draw_list_);
// What the frame's render targets cost. The atlas and every chain
// intermediate come out of one pool, so one number answers for all of them —
@@ -481,6 +492,10 @@ void RenderFrame::flush() {
#endif
}
+void RenderFrame::endFrame() {
+ device_.endFrame();
+}
+
void RenderFrame::end() {
if (!in_frame_) return;
@@ -552,9 +567,6 @@ void RenderFrame::end() {
// not ride into the next one (the swapchain recycles it at task end). On
// GL this is just the default-framebuffer rebind.
device_.endRenderPass();
- // ...and the frame itself ends here, which is when a borrowed swapchain
- // image goes back. Not at the pass: this frame may have opened several.
- device_.endFrame();
frame_capture_.endCapture();
in_frame_ = false;
@@ -1430,6 +1442,7 @@ void RenderFrame::executeShadowPass(ecs::Registry& registry) {
RenderCollectContext collectCtx{registry, viewFrustum, clip_state_, shadow_pool_,
list, ctx,
computeCameraView(view.view_projection)};
+ collectCtx.screen_ui = screen_domain_;
for (auto& plugin : plugins_) {
if (plugin->castsShadows()) plugin->collect(collectCtx);
}
@@ -1542,6 +1555,10 @@ void RenderFrame::collectAll(ecs::Registry& registry) {
RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_, ctx,
computeCameraView(ctx.view_projection)};
+ // What this collect must NOT draw. A camera's job is the world; the screen's
+ // entities are laid out in pixels centred on the origin, and drawing them
+ // through a view matrix puts a HUD wherever the view happens to be looking.
+ collectCtx.screen_ui = screen_domain_;
collectSky(collectCtx);
for (auto& plugin : plugins_) plugin->collect(collectCtx);
diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hpp
index b7ceaa232..5ea40c4ba 100644
--- a/src/esengine/renderer/frame/RenderFrame.hpp
+++ b/src/esengine/renderer/frame/RenderFrame.hpp
@@ -54,18 +54,6 @@ inline constexpr u32 kShadowCascadeCells = 2;
*/
enum class ShadowShape : u8 { Box, Cone, Cube };
-struct Plane {
- glm::vec3 normal;
- f32 distance;
- f32 signedDistance(const glm::vec3& point) const;
-};
-
-struct Frustum {
- Plane planes[6];
- void extractFromMatrix(const glm::mat4& vp);
- bool intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtents) const;
-};
-
// GPU frame timer: a small ring of device timer queries so a frame's result is
// read a few frames later without stalling the CPU on the GPU.
class GpuTimer {
@@ -137,6 +125,16 @@ public:
*/
void beginFrame();
+ /**
+ * @brief Closes the FRAME, once, after every camera and every overlay.
+ *
+ * @details The pair of beginFrame, and the only place a backend that borrows
+ * the swapchain image gives it back. Releasing it in end(), which
+ * runs per CAMERA, leaves the post stack and the overlay drawing
+ * into an image the surface has taken away.
+ */
+ void endFrame();
+
void begin(const glm::mat4& view_projection, RenderTargetManager::Handle target = 0);
void begin(const glm::mat4& view_projection, RenderTargetManager::Handle target,
const PassClear& clear);
@@ -144,6 +142,35 @@ public:
void end();
void processMasks(ecs::Registry& registry, i32 vpX, i32 vpY, i32 vpW, i32 vpH);
+ /// Same, resolved through @p projection rather than the current camera's —
+ /// a scissor rect is pixels, and which pixels a UI box covers is a question
+ /// only the projection that draws it can answer.
+ void processMasks(ecs::Registry& registry, const glm::mat4& projection,
+ i32 vpX, i32 vpY, i32 vpW, i32 vpH);
+
+ // ---- The screen-space overlay -------------------------------------------
+ //
+ // One pass a frame, after every camera and after post. The frame's, not a
+ // camera's: the projection comes from the layout domain.
+
+ /** @brief The screen's entities (UISystem::screenDomain), borrowed for the
+ * frame. Null partitions nothing — every collect is a world one. */
+ void setScreenDomain(const std::unordered_set<u32>* domain) { screen_domain_ = domain; }
+
+ /** @brief Opens the overlay: @p projection maps the layout domain onto the
+ * pixel rect @p vpX/@p vpY/@p vpW/@p vpH of the surface. */
+ void beginScreenOverlay(const glm::mat4& projection, i32 vpX, i32 vpY, u32 vpW, u32 vpH);
+
+ /** @brief Collects the screen's renderables. Between this and
+ * endScreenOverlay a host may submit its own screen geometry (the
+ * SDK's glyph quads), which lands in the same list. */
+ void submitScreenOverlay(ecs::Registry& registry);
+
+ /** @brief Declares the overlay as a graph pass over @p target and runs it. */
+ void endScreenOverlay(RenderTargetManager::Handle target);
+
+ /** @brief Whether the overlay is open — what routes a host's submissions. */
+ bool screenOverlayOpen() const { return overlay_active_; }
void setEntityClipRect(u32 entity, i32 x, i32 y, i32 w, i32 h);
void clearAllClipRects();
@@ -448,6 +475,11 @@ private:
RenderFrameContext makeContext();
void buildClipState();
+ /// Adds a finalized list's cost to this frame's tally (see the definition).
+ void accumulateStats(const DrawList& list);
+ /// The overlay pass's body: the projection its geometry was built for, then
+ /// the list. Runs inside the graph, like every other pass's draw.
+ void drawScreenOverlay();
/**
* @brief Tells the capture whether to carry a depth attachment.
@@ -611,6 +643,13 @@ private:
/// Emits the background quad when an environment asked to be seen behind the scene.
void collectSky(RenderCollectContext& ctx);
+ /// Borrowed from the UI system for the frame (see setScreenDomain).
+ const std::unordered_set<u32>* screen_domain_ = nullptr;
+ bool overlay_active_ = false;
+ glm::mat4 overlay_projection_{1.0f};
+ i32 overlay_vp_x_ = 0, overlay_vp_y_ = 0;
+ u32 overlay_vp_w_ = 0, overlay_vp_h_ = 0;
+
// processMasks scratch, reused across cameras/frames.
std::vector<Entity> mask_scissor_scratch_;
std::vector<Entity> mask_stencil_scratch_;
diff --git a/src/esengine/renderer/frame/RenderFrameMask.cpp b/src/esengine/renderer/frame/RenderFrameMask.cpp
index bb0e205a2..e082b4123 100644
--- a/src/esengine/renderer/frame/RenderFrameMask.cpp
+++ b/src/esengine/renderer/frame/RenderFrameMask.cpp
@@ -194,6 +194,11 @@ void applyStencilDescendants(ecs::Registry& registry, RenderFrame& frame,
} // anonymous namespace
void RenderFrame::processMasks(ecs::Registry& registry, i32 vpX, i32 vpY, i32 vpW, i32 vpH) {
+ processMasks(registry, view_projection_, vpX, vpY, vpW, vpH);
+}
+
+void RenderFrame::processMasks(ecs::Registry& registry, const glm::mat4& projection,
+ i32 vpX, i32 vpY, i32 vpW, i32 vpH) {
clearAllClipRects();
clearAllStencilMasks();
@@ -231,8 +236,8 @@ void RenderFrame::processMasks(ecs::Registry& registry, i32 vpX, i32 vpY, i32 vp
}
for (auto entity : rootScissors) {
- ScreenRect rect = computeMaskScreenRect(registry, entity, view_projection_, vpX, vpY, vpW, vpH);
- applyScissorToDescendants(registry, *this, entity, rect, maskSet, view_projection_, vpX, vpY, vpW, vpH);
+ ScreenRect rect = computeMaskScreenRect(registry, entity, projection, vpX, vpY, vpW, vpH);
+ applyScissorToDescendants(registry, *this, entity, rect, maskSet, projection, vpX, vpY, vpW, vpH);
}
}
diff --git a/src/esengine/renderer/frame/RenderFrameOverlay.cpp b/src/esengine/renderer/frame/RenderFrameOverlay.cpp
new file mode 100644
index 000000000..32b60f499
--- /dev/null
+++ b/src/esengine/renderer/frame/RenderFrameOverlay.cpp
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file RenderFrameOverlay.cpp
+ * @brief The frame's screen-space overlay — one graph pass, no camera.
+ *
+ * @details The geometry is already in the layout domain when it arrives here
+ * (UILayoutSystem places screen roots in pixels about the origin); this
+ * pass says only how that domain reaches the framebuffer, and it is
+ * TOLD — the projection is an input, so no camera can leak in.
+ *
+ * It runs inside the RenderGraph like every other pass. Drawing after
+ * graph_.execute() would be simpler and would break the one rule that
+ * keeps this renderer explicable: the graph is the whole frame.
+ */
+#include "./RenderFrame.hpp"
+#include "../../core/FrameProfiler.hpp"
+
+#include <algorithm>
+
+namespace esengine {
+
+void RenderFrame::beginScreenOverlay(const glm::mat4& projection,
+ i32 vpX, i32 vpY, u32 vpW, u32 vpH) {
+ if (overlay_active_ || !device_.isDeviceUsable()) return;
+
+ overlay_projection_ = projection;
+ overlay_vp_x_ = vpX;
+ overlay_vp_y_ = vpY;
+ overlay_vp_w_ = vpW;
+ overlay_vp_h_ = vpH;
+ overlay_active_ = true;
+
+ // The frame's own scratch, reused: every camera has drawn AND had its graph
+ // run by the time this opens, so what is being reset is spent.
+ pool_.beginFrame();
+ draw_list_.clear();
+ // Every layer until the caller says otherwise: which layers a frame shows is
+ // the caller's to decide, and a host that never says shows all of them.
+ draw_list_.setCullingMask(0xFFFFFFFFu);
+ clip_state_.clear();
+}
+
+void RenderFrame::submitScreenOverlay(ecs::Registry& registry) {
+ if (!overlay_active_) return;
+
+ ES_PROFILE_SCOPE("render.overlay.collect");
+
+ // Masks resolve in the overlay's OWN projection: a scissor rect is pixels,
+ // and which pixels a UI box covers is a question only the projection that
+ // draws it can answer.
+ processMasks(registry, overlay_projection_, overlay_vp_x_, overlay_vp_y_,
+ static_cast<i32>(overlay_vp_w_), static_cast<i32>(overlay_vp_h_));
+ buildClipState();
+
+ auto ctx = makeContext();
+ ctx.view_projection = overlay_projection_;
+ ctx.purpose = RenderPurpose::ScreenOverlay;
+
+ // Extracted for completeness of the context, never consulted: the overlay
+ // does not cull (RenderCollectContext::visible short-circuits on the purpose).
+ // A screen element is on the screen by construction.
+ Frustum overlayFrustum;
+ overlayFrustum.extractFromMatrix(overlay_projection_);
+
+ RenderCollectContext collectCtx{registry, overlayFrustum, clip_state_, pool_, draw_list_,
+ ctx, computeCameraView(overlay_projection_)};
+ collectCtx.screen_ui = screen_domain_;
+ // Only the plugins that can draw an entity out of a UI tree. Everything else
+ // draws world content, which by definition is not what this pass is for —
+ // and would land in it at layout-pixel coordinates.
+ for (auto& plugin : plugins_) {
+ if (plugin->drawsScreenUI()) plugin->collect(collectCtx);
+ }
+ stats_.culled += collectCtx.culled;
+}
+
+void RenderFrame::drawScreenOverlay() {
+ context_.updateCameraConstants(overlay_projection_);
+ {
+ ES_PROFILE_SCOPE("render.overlay.submit");
+ draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
+ &frame_capture_, context_.skinUbo());
+ }
+ device_.invalidatePipelineCache();
+ device_.setScissorTest(false);
+}
+
+void RenderFrame::endScreenOverlay(RenderTargetManager::Handle target) {
+ if (!overlay_active_) return;
+ overlay_active_ = false;
+ if (!device_.isDeviceUsable()) return;
+ // Nothing to draw is not the same as nothing to do elsewhere, but here it is:
+ // a pass that would write no pixel is one the graph would run anyway.
+ if (draw_list_.commandCount() == 0) return;
+
+ {
+ ES_PROFILE_SCOPE("render.overlay.finalize");
+ draw_list_.finalize(pool_);
+ pool_.upload();
+ }
+ accumulateStats(draw_list_);
+
+ FramebufferHandle fbo = FramebufferHandle::Default;
+ if (target != RenderTargetManager::INVALID_HANDLE) {
+ if (auto* rt = target_manager_.get(target)) fbo = rt->getFramebuffer();
+ }
+
+ device_.invalidatePipelineCache();
+ device_.setScissorTest(false);
+
+ // Its own graph and its own run, on the same terms as the screen post stack:
+ // this composes what every camera drew and happens after the last of them
+ // ended, so no frame is declaring here.
+ ES_PROFILE_SCOPE("render.overlay.graph");
+ graph_.begin(width_, height_);
+ rg::PassDesc pass;
+ pass.name = "screen-ui";
+ pass.write = graph_.importTarget(fbo, width_, height_);
+ // Never clears. The HUD lands ON the frame; clearing here would be the pass
+ // deciding the scene was not worth keeping.
+ pass.clear = false;
+ pass.viewportX = static_cast<u32>(std::max(overlay_vp_x_, 0));
+ pass.viewportY = static_cast<u32>(std::max(overlay_vp_y_, 0));
+ pass.viewportW = overlay_vp_w_;
+ pass.viewportH = overlay_vp_h_;
+ pass.execute = [this](const rg::PassContext&) { drawScreenOverlay(); };
+ graph_.addPass(std::move(pass));
+ graph_.execute();
+
+ device_.endRenderPass();
+ device_.invalidatePipelineCache();
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/plugins/ParticlePlugin.cpp b/src/esengine/renderer/plugins/ParticlePlugin.cpp
index b4c6df881..542c4998d 100644
--- a/src/esengine/renderer/plugins/ParticlePlugin.cpp
+++ b/src/esengine/renderer/plugins/ParticlePlugin.cpp
@@ -76,6 +76,7 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
auto emitterView = registry.view<ecs::Transform, ecs::ParticleEmitter>();
for (auto entity : emitterView) {
+ if (!collect_ctx.accepts(entity)) continue;
const auto& emitter = emitterView.get<ecs::ParticleEmitter>(entity);
if (!emitter.enabled) continue;
@@ -181,7 +182,7 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
.shaderId = shaderId,
.blend = blend,
.textureId = textureId,
- .depth = collect_ctx.camera.viewDepth(emitterWorldPos),
+ .depth = collect_ctx.sortDepth(emitterWorldPos),
// Sorted by world Y like every other draw — a burst left at y = 0
// loses to any sprite standing anywhere else, so an emitter placed on
// a character disappears behind them.
@@ -208,7 +209,7 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
.shaderId = ctx.batch_shader_id,
.blend = blendMode,
.textureId = ctx.white_texture_id,
- .depth = collect_ctx.camera.viewDepth(emitterWorldPos),
+ .depth = collect_ctx.sortDepth(emitterWorldPos),
.y = emitterWorldPos.y,
.entity = entity,
.type = RenderType::Trail,
diff --git a/src/esengine/renderer/plugins/ParticlePlugin.hpp b/src/esengine/renderer/plugins/ParticlePlugin.hpp
index 570fe4fe8..e86855eb4 100644
--- a/src/esengine/renderer/plugins/ParticlePlugin.hpp
+++ b/src/esengine/renderer/plugins/ParticlePlugin.hpp
@@ -20,6 +20,10 @@ public:
void setParticleSystem(particle::ParticleSystem* system) { particle_system_ = system; }
+ // An emitter inside a UI tree draws where that tree says it does — the reason
+ // a UI particle is a first-class thing here rather than an extension — so it
+ // follows the tree into the screen domain too.
+ bool drawsScreenUI() const override { return true; }
void collect(RenderCollectContext& ctx) override;
private:
diff --git a/src/esengine/renderer/plugins/SpritePlugin.cpp b/src/esengine/renderer/plugins/SpritePlugin.cpp
index 181643461..816490d39 100644
--- a/src/esengine/renderer/plugins/SpritePlugin.cpp
+++ b/src/esengine/renderer/plugins/SpritePlugin.cpp
@@ -15,7 +15,6 @@ namespace esengine {
void SpritePlugin::collect(RenderCollectContext& collect_ctx) {
auto& registry = collect_ctx.registry;
- auto& frustum = collect_ctx.frustum;
auto& clips = collect_ctx.clip_state;
auto& buffers = collect_ctx.buffer_pool;
auto& draw_list = collect_ctx.draw_list;
@@ -25,6 +24,7 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {
u32 litProgram = 0;
for (auto entity : spriteView) {
+ if (!collect_ctx.accepts(entity)) continue;
const auto& sprite = spriteView.get<ecs::Sprite>(entity);
if (!sprite.enabled) continue;
if (registry.has<ecs::UINode>(entity)) continue; // UI sprites are drawn by UIElementPlugin
@@ -46,7 +46,7 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {
0.0f);
glm::vec3 halfExtents = flatHalfExtents(
turn, glm::vec3(std::abs(finalSize.x), std::abs(finalSize.y), 0.0f) * 0.5f);
- if (!frustum.intersectsAABB(aabbCenter, halfExtents)) {
+ if (!collect_ctx.visible(aabbCenter, halfExtents)) {
++collect_ctx.culled;
continue;
}
@@ -93,7 +93,7 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {
.shaderId = batch_shader_id_,
.blend = BlendMode::Normal,
.textureId = textureId,
- .depth = collect_ctx.camera.viewDepth(position),
+ .depth = collect_ctx.sortDepth(position),
.y = position.y,
.entity = entity,
.type = RenderType::Sprite,
diff --git a/src/esengine/renderer/plugins/SpritePlugin.hpp b/src/esengine/renderer/plugins/SpritePlugin.hpp
index 4014949c0..d53dc532b 100644
--- a/src/esengine/renderer/plugins/SpritePlugin.hpp
+++ b/src/esengine/renderer/plugins/SpritePlugin.hpp
@@ -9,6 +9,10 @@ namespace esengine {
class SpritePlugin : public BatchPlugin {
public:
+ // A Sprite parented into a UI tree is laid out and ordered by that tree
+ // (UIRenderOrderSystem assigns it a layer), so it is screen content when the
+ // tree is — and has to be drawn by the pass that owns those coordinates.
+ bool drawsScreenUI() const override { return true; }
void collect(RenderCollectContext& ctx) override;
private:
diff --git a/src/esengine/renderer/plugins/UIElementPlugin.cpp b/src/esengine/renderer/plugins/UIElementPlugin.cpp
index 873b6183c..ba090987a 100644
--- a/src/esengine/renderer/plugins/UIElementPlugin.cpp
+++ b/src/esengine/renderer/plugins/UIElementPlugin.cpp
@@ -46,7 +46,6 @@ static f32 radialMaxSweep(ecs::UIFillMethod m) {
void UIElementPlugin::collect(RenderCollectContext& collect_ctx) {
auto& registry = collect_ctx.registry;
- auto& frustum = collect_ctx.frustum;
auto& clips = collect_ctx.clip_state;
auto& buffers = collect_ctx.buffer_pool;
auto& draw_list = collect_ctx.draw_list;
@@ -54,6 +53,7 @@ void UIElementPlugin::collect(RenderCollectContext& collect_ctx) {
auto uiView = registry.view<ecs::Transform, ecs::UIVisual>();
for (auto entity : uiView) {
+ if (!collect_ctx.accepts(entity)) continue;
const auto& renderer = uiView.get<ecs::UIVisual>(entity);
if (!renderer.enabled || renderer.visualType == ecs::UIVisualType::None) continue;
@@ -90,7 +90,7 @@ void UIElementPlugin::collect(RenderCollectContext& collect_ctx) {
// `position` above already carries the turned offset, so only the extents do.
glm::vec3 halfExtents = flatHalfExtents(
flatTurnZ(rotation), glm::vec3(w * scale.x, h * scale.y, 0.0f) * 0.5f);
- if (!frustum.intersectsAABB(position, halfExtents)) { ++collect_ctx.culled; continue; }
+ if (!collect_ctx.visible(position, halfExtents)) { ++collect_ctx.culled; continue; }
f32 angle = 2.0f * std::atan2(rotation.z, rotation.w);
i32 layer = UI_BASE_LAYER + renderer.uiOrder;
@@ -225,7 +225,7 @@ void UIElementPlugin::collect(RenderCollectContext& collect_ctx) {
.shaderId = batch_shader_id_,
.blend = BlendMode::Normal,
.textureId = textureId,
- .depth = collect_ctx.camera.viewDepth(position),
+ .depth = collect_ctx.sortDepth(position),
.cullBit = renderer.uiCullBit,
.entity = entity,
.type = RenderType::UIElement,
diff --git a/src/esengine/renderer/plugins/UIElementPlugin.hpp b/src/esengine/renderer/plugins/UIElementPlugin.hpp
index ef1819e02..1a9a5f9d3 100644
--- a/src/esengine/renderer/plugins/UIElementPlugin.hpp
+++ b/src/esengine/renderer/plugins/UIElementPlugin.hpp
@@ -10,6 +10,7 @@ namespace esengine {
class UIElementPlugin : public BatchPlugin {
public:
+ bool drawsScreenUI() const override { return true; }
void collect(RenderCollectContext& ctx) override;
// UI draws above world content: its sort layer is offset past the world
diff --git a/src/esengine/ui/UILayoutSystem.cpp b/src/esengine/ui/UILayoutSystem.cpp
index ffb48949d..9302a4546 100644
--- a/src/esengine/ui/UILayoutSystem.cpp
+++ b/src/esengine/ui/UILayoutSystem.cpp
@@ -473,6 +473,33 @@ void placeScreenRoots(Registry& registry, UITree& tree, LayoutCache& cache,
}
}
+/** @brief Adds @p entity and its whole Transform subtree to @p out. */
+void addSubtree(Registry& registry, Entity entity, std::unordered_set<u32>& out) {
+ out.insert(entity.id());
+ auto* children = registry.tryGet<Children>(entity);
+ if (!children) return;
+ for (Entity child : children->entities) {
+ if (registry.valid(child)) addSubtree(registry, child, out);
+ }
+}
+
+/**
+ * @brief Which entities are the screen's rather than the world's.
+ *
+ * @details Decided at each Canvas and inherited downward, so one subtree has one
+ * answer. Walks the TRANSFORM hierarchy, not the layout tree: a plain
+ * Sprite parented into a HUD is not a layout node, yet its transform
+ * composes from a screen root all the same.
+ */
+void collectScreenDomain(Registry& registry, std::unordered_set<u32>& out) {
+ out.clear();
+ registry.each<Canvas>([&](Entity entity, Canvas&) {
+ if (!registry.has<UINode>(entity) || !registry.has<Transform>(entity)) return;
+ if (!isScreenRoot(registry, entity)) return;
+ addSubtree(registry, entity, out);
+ });
+}
+
void unifiedLayoutPass(Registry& registry, UITree& tree, LayoutCache& cache,
const LayoutRect& box, bool structureChanged,
bool forceWriteback) {
@@ -524,6 +551,10 @@ void UISystem::layoutUpdate(
// the reliable structural signal we don't otherwise have. The expensive part
// (orphan + propagateHidden + Yoga solve + reap) is what the gate below skips.
tree.rebuild(registry);
+ // Beside the rebuild and never behind the skip gate below: a frame that needs
+ // no re-solve can still have reparented something, and a renderer reading a
+ // stale set would draw it in the wrong domain rather than in the wrong place.
+ collectScreenDomain(registry, screen_domain_);
LayoutRect box{ boxLeft, boxBottom, boxRight, boxTop };
diff --git a/src/esengine/ui/UISystem.cpp b/src/esengine/ui/UISystem.cpp
index a8d6d6c8e..3bce5e819 100644
--- a/src/esengine/ui/UISystem.cpp
+++ b/src/esengine/ui/UISystem.cpp
@@ -26,6 +26,11 @@ namespace esengine::ecs {
void UISystem::hitTestUpdate(Registry& registry, const PickRay& ray,
const resource::ResourceManager* resources) {
+ hitTestUpdate(registry, ray, ray, resources);
+}
+
+void UISystem::hitTestUpdate(Registry& registry, const PickRay& worldRay, const PickRay& screenRay,
+ const resource::ResourceManager* resources) {
hitResult.prev_hit_entity = hitResult.hit_entity;
hitResult.hit_entity = INVALID_ENTITY;
@@ -38,6 +43,11 @@ void UISystem::hitTestUpdate(Registry& registry, const PickRay& ray,
if (!interactable || !interactable->enabled || !interactable->raycastTarget) continue;
if (!registry.has<Transform>(entity)) continue;
+ // Which projection this node was drawn through decides which ray reaches
+ // it. Resolved from the same set the renderer partitions by, so what is
+ // clickable and what is visible cannot come apart.
+ const PickRay& ray = screen_domain_.count(entity.id()) != 0 ? screenRay : worldRay;
+
registry.getOrEmplace<UIInteraction>(entity);
auto& t = registry.get<Transform>(entity);
@@ -76,7 +86,8 @@ void UISystem::hitTestUpdate(Registry& registry, const PickRay& ray,
}
}
- hitWorldContent(registry, ray, resources);
+ // World content is world content: the screen has no sprites or meshes in it.
+ hitWorldContent(registry, worldRay, resources);
}
/**
diff --git a/src/esengine/ui/UISystem.hpp b/src/esengine/ui/UISystem.hpp
index 380fee783..35c4df6a2 100644
--- a/src/esengine/ui/UISystem.hpp
+++ b/src/esengine/ui/UISystem.hpp
@@ -19,6 +19,7 @@
#include "./UIHitTestSystem.hpp"
#include <memory>
+#include <unordered_set>
#include <vector>
namespace esengine::resource { class ResourceManager; }
@@ -90,6 +91,17 @@ public:
void hitTestUpdate(Registry& registry, const PickRay& ray,
const resource::ResourceManager* resources = nullptr);
+ /**
+ * @brief The same, with a ray per DOMAIN.
+ *
+ * @details A pixel is in no domain until it is projected into one, so screen
+ * UI answers @p screenRay and world content @p worldRay — each
+ * entity through the projection it is DRAWN with. One ray for both
+ * draws the HUD where it should be and clicks somewhere else.
+ */
+ void hitTestUpdate(Registry& registry, const PickRay& worldRay, const PickRay& screenRay,
+ const resource::ResourceManager* resources);
+
/** @brief Editor pick: the most specific UI entity under the point. Unlike
* hitTestUpdate it ignores Interactable and mutates no state. */
u32 pick(Registry& registry, f32 worldX, f32 worldY);
@@ -109,6 +121,16 @@ public:
/** @brief Entity hit by the previous frame's hitTestUpdate */
u32 getPrevHitEntity() const { return hitResult.prev_hit_entity.id(); }
+ /**
+ * @brief Every entity that belongs to the SCREEN, as opposed to the world.
+ *
+ * @details Resolved once at a subtree's root and inherited by all of it: a
+ * Canvas with no Transform parent IS the screen. The whole Transform
+ * subtree, not just the laid-out nodes — what decides the domain is
+ * where a transform composes FROM. Rebuilt by every layout pass.
+ */
+ const std::unordered_set<u32>& screenDomain() const { return screen_domain_; }
+
private:
/** @brief World-space pick for entities outside the layout tree (see .cpp) */
void hitWorldContent(Registry& registry, const PickRay& ray,
@@ -128,6 +150,8 @@ private:
// Which registry the retained Yoga nodes belong to — entity ids restart with
// each one, so they mean nothing across registries (Registry::instanceId).
u64 lastRegistryId_{0};
+
+ std::unordered_set<u32> screen_domain_;
};
} // namespace esengine::ecs
diff --git a/tools/check-screen-domain.mjs b/tools/check-screen-domain.mjs
index 076378d8a..00bda4a74 100644
--- a/tools/check-screen-domain.mjs
+++ b/tools/check-screen-domain.mjs
@@ -12,6 +12,13 @@
* lists every one and fails on an undeclared reader. A reader that still belongs
* to the camera says so here, with the reason it is not screen-space.
*
+ * The migration is DONE: what remains declares the field, publishes it, or asks
+ * the camera a camera's question. Nothing left reads it to decide where a piece
+ * of UI goes — the layout box comes from `ScreenLayout` and the projection from
+ * `ScreenOverlay`, neither of which has a parameter a camera could reach. So a
+ * new entry here is now a regression, not a step: it means something has started
+ * asking a camera where the screen is again.
+ *
* node tools/check-screen-domain.mjs
*/
import { readFileSync } from 'node:fs';
@@ -33,11 +40,6 @@ const DECLARED = new Map([
['sdk/src/app/corePlugin.ts', 'zeroes the resource at startup'],
['sdk/src/ecs/resourceShapes.ts', 'declares the resource shape'],
['sdk/src/camera/Camera.ts', 'getWorldBounds is a camera query, not a UI one'],
- ['sdk/src/ui/layout/layout.ts',
- 'still hands the box to uiLayout_update — moves with the collection split'],
- ['sdk/src/ui/text/plugin.ts',
- 'glyph raster scale is camera-correct for WORLD text; screen text needs the '
- + 'two told apart, which is the collection split'],
]);
const files = execFileSync('git', ['ls-files', 'sdk/src'], { cwd: ROOT, encoding: 'utf8' })
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index b7d6c1a5f..b1683d82f 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -215,6 +215,26 @@ export const SCENES = [
{ id: "camera-culling", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/camera-culling.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/camera-culling.textures.json", ESTELLA_VERIFY_W: "320", ESTELLA_VERIFY_H: "180", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":30},{\"x\":0.75,\"y\":0.5,\"rgb\":[255,255,0],\"tol\":30}]" } },
// Where the UI layout box SITS. The camera is driven away from the origin at runtime, so the box moves without resizing: the unparented Canvas (a screen root) must travel with it — red/green stay in their quadrants — while the Canvas parented to a world entity must not, landing blue at the anchor's own world position. Before screen roots existed the whole HUD stayed at the origin and this frame came back black.
{ id: "ui-screen-root", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-root.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-root.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_MOVE: "{\"component\":\"Camera\",\"to\":[5000,-800],\"steps\":4}", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.25,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.75,\"y\":0.75,\"rgb\":[0,255,0],\"tol\":30},{\"x\":0.75,\"y\":0.25,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.25,\"y\":0.75,\"rgb\":[0,0,0],\"tol\":30}]" } },
+ // A HUD over a PERSPECTIVE camera. That view has no world rectangle, so a
+ // layout box taken from a camera resolves every HUD element to 0x0 and the two
+ // corners here come back black.
+ { id: "ui-screen-3d", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-3d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-3d.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.25, \"y\": 0.25, \"rgb\": [255, 0, 0], \"tol\": 30}, {\"x\": 0.75, \"y\": 0.75, \"rgb\": [0, 255, 0], \"tol\": 30}, {\"x\": 0.75, \"y\": 0.25, \"rgb\": [0, 0, 255], \"tol\": 40}, {\"x\": 0.25, \"y\": 0.75, \"rgb\": [0, 0, 0], \"tol\": 30}]" } },
+ // ...and the camera leaves. The world blob goes with it — the control, without
+ // which this would pass on a frame where nothing moved — and the two corners
+ // stay exactly where they were.
+ { id: "ui-screen-3d-camera-moved", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-3d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-3d.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_MOVE: "{\"component\": \"Camera\", \"to\": [4000, 1000], \"steps\": 4}", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.25, \"y\": 0.25, \"rgb\": [255, 0, 0], \"tol\": 30}, {\"x\": 0.75, \"y\": 0.75, \"rgb\": [0, 255, 0], \"tol\": 30}, {\"x\": 0.75, \"y\": 0.25, \"rgb\": [0, 0, 0], \"tol\": 30}, {\"x\": 0.25, \"y\": 0.75, \"rgb\": [0, 0, 0], \"tol\": 30}]" } },
+ // What a screen element's z may decide, which is nothing. Three roots carry
+ // z -10000 / 0 / +10000 and all three must draw; a fourth, LATER sibling with
+ // the furthest z of all covers the first, because the tree orders a screen.
+ { id: "ui-screen-order", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-order.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-order.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.16, \"y\": 0.1, \"rgb\": [255, 0, 0], \"tol\": 30}, {\"x\": 0.5, \"y\": 0.5, \"rgb\": [0, 255, 0], \"tol\": 30}, {\"x\": 0.83, \"y\": 0.5, \"rgb\": [0, 0, 255], \"tol\": 30}, {\"x\": 0.16, \"y\": 0.5, \"rgb\": [255, 255, 255], \"tol\": 30}]" } },
+ // Where the overlay sits, which is after the post chain. A vignette crushes
+ // the WORLD quad to black a third of the way in (the two black points are the
+ // control) while the badge in the very corner keeps the red it was authored.
+ { id: "ui-screen-post", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-post.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-post.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.03, \"y\": 0.03, \"rgb\": [255, 0, 0], \"tol\": 6}, {\"x\": 0.3, \"y\": 0.03, \"rgb\": [0, 0, 0], \"tol\": 6}, {\"x\": 0.97, \"y\": 0.97, \"rgb\": [0, 0, 0], \"tol\": 6}, {\"x\": 0.5, \"y\": 0.5, \"rgb\": [51, 153, 255], \"tol\": 10}]" } },
+ // HUD TEXT, which the SDK submits itself — the one screen primitive that could
+ // be left in a camera's list while the panel under it moved. Under this
+ // perspective camera such text lands nowhere and the panel comes back blue.
+ { id: "ui-screen-text", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/ui-screen-text.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ui-screen-text.textures.json", ESTELLA_VERIFY_W: "640", ESTELLA_VERIFY_H: "360", ESTELLA_VERIFY_STEPS: "6", ESTELLA_VERIFY_EXPECT: "[{\"x\": 0.4, \"y\": 0.5, \"rgb\": [255, 255, 0], \"tol\": 40}, {\"x\": 0.525, \"y\": 0.5, \"rgb\": [255, 255, 0], \"tol\": 40}, {\"x\": 0.5, \"y\": 0.5, \"rgb\": [0, 0, 153], \"tol\": 40}, {\"x\": 0.05, \"y\": 0.5, \"rgb\": [0, 0, 153], \"tol\": 40}]" } },
// Y-sort: same scene twice — mask on flips the overlap to the lower (higher-Y-key) entity; mask off preserves submission order. Both asserted so neither path can silently regress.
// Slices of one continuous pattern, each its OWN texture, at a fractional
// world-units-per-pixel — seamless art and a non-integer ratio are what a seam