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): ContentRect, the rectangle world content occupies — Sprite and Text follow it, a UIMask on the entity clips to it, a world point can be tested against it; the Cocos UITransform and Mask are views on it, and the importer writes it

yhh4327156dc611
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c4c168f1e..d9e650c61 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,10 @@ published separately; it ships inside the editor.
### Added
+- **Rich text reads the tags other engines write.** `<size=24>…</size>`, a colour by name (`<color=red>`), and `<br/>` now work beside `<color=#RRGGBB>`, `<font size=…>`, `<b>` and `<i>`. `<u>`, `<s>`, `<outline …>` and `<on click=…>` are accepted so text written for another engine shows no raw tags: the words are kept, the underline, outline and click are not drawn. Unknown tags still show as text.
+- **Scroll areas can be pulled past an end and spring back.** A scroll area whose movement is Elastic now does what the setting always said: a drag past an end is stiffer the further out it goes, letting go returns the content, and a flick that reaches an end bounces off it. It is opt-in per area (`ScrollMovement.Elastic`; Clamped, the default, behaves as before), and the gesture model (`ScrollMotion`, with `ScrollContainer.dragTo` and `getOverscroll`) is exported for scrolling anything else the same way.
+- **More easing curves.** Sine, quart, quint, expo and circ (each in, out and in-out), bounce in and in-out, and smoothstep and smootherstep join the quad, cubic, back, elastic and out-bounce curves. They are new `EasingType` members after the existing ones, so a saved tween keeps its curve, and they ease the same in a C++ tween and a script value tween.
+- **World content has a rectangle: `ContentRect`.** A size and the pivot the entity's transform sits on, which the `Sprite` and `Text` on the entity follow and which a `UIMask` on it clips to — no `UINode` needed, so a clipping region or a scroll viewport can stand in the world. `contentRectContains` tests a world point against it.
- **The engine's runtime tuning is a project setting.** Project Settings → Game → Runtime sets how a scene switch fades (duration and colour), how far one frame may advance the game and how many fixed steps it may catch up, how long an asset may take to load and how soon a failed one is tried again, how much memory the texture, audio and device-loss caches keep, the text canvas size and the default font family. They were reachable only from code (`RuntimeConfig`) and no project file could carry them. The project holds `features.runtime` with only what differs from the engine's own values (`RUNTIME_BUILD_DEFAULTS`), a build ships the same block, and `initRuntime` applies it before the first asset loads on the web, desktop, native, mini-game and playable targets and in Play. The edit viewport keeps the engine's values.
- **Rows for the choices that could only be written into the project file.** Under Rendering: compile shaders in the background, warm them up behind the loading screen and how long to wait, draw only changing frames and how many frames to keep after a change, each level's anti-aliasing (MSAA or temporal; the MSAA count is hidden where temporal ignores it) and its depth pre-pass. Under Game → Display: the render resolution (screen, design resolution or integer multiple). Under the web build: the servers the page may connect to, each checked by the parser the export uses. `check-project-settings` now reads the keys of `QualityConfig`, `QualityProfile` and `RuntimeBuildConfig` and fails a key that has no row and no stated reason, which is how these went unnoticed behind the one row the block had.
diff --git a/docs/astro/src/content/docs/ui/overview.mdx b/docs/astro/src/content/docs/ui/overview.mdx
index 748ea6a88..81c8f92c7 100644
--- a/docs/astro/src/content/docs/ui/overview.mdx
+++ b/docs/astro/src/content/docs/ui/overview.mdx
@@ -163,6 +163,26 @@ the shape the mask actually draws, testing the **sprite's** alpha (not the tinte
because a mask graphic is routinely tinted to near-zero alpha so it masks without being
seen). `0` stays the default, so scenes authored against box clipping are unchanged.
+### `ContentRect` — a rectangle for world content
+
+`UINode` is the engine's box layout, and it is what UI is built from. Content placed in the
+world by its `Transform` — a HUD pinned to a camera, an imported scene — has no layout, and
+until now its extent lived in several places: a `Sprite` has a size and pivot, a `Text` a box,
+and an entity that draws nothing has no extent at all, so nothing could be clipped to it.
+
+`ContentRect` is that one rectangle: a `size` in local units and the `pivot` of it the entity's
+transform sits on (`(0.5, 0.5)` is the centre). Add it, and:
+
+- the `Sprite` and `Text` on the same entity take their size and pivot from it, so the
+ rectangle is written in one place;
+- a `UIMask` on the entity clips its descendants to it, with no `UINode` needed;
+- `contentRectContains(world, entity, x, y)` tests a world point against it, with the
+ entity's position, rotation and scale applied.
+
+An entity with both a `UINode` and a `ContentRect` keeps the layout's box for clipping.
+Adding a `Sprite` or `Text` to an entity that already has a rect: call `applyContentRect`
+once, or write the rect again; a changed rect is followed by itself.
+
### Subtree opacity and pointer gating
`UINode` carries two fields that resolve **hierarchically**, in the same pass that already
diff --git a/docs/astro/src/content/docs/zh-cn/ui/overview.mdx b/docs/astro/src/content/docs/zh-cn/ui/overview.mdx
index 0a690f2cf..459c71b76 100644
--- a/docs/astro/src/content/docs/zh-cn/ui/overview.mdx
+++ b/docs/astro/src/content/docs/zh-cn/ui/overview.mdx
@@ -149,6 +149,22 @@ addStartupSystem(buildPauseMenu);
(而非着色后的结果——遮罩图形常被调到接近全透明,好让它遮挡而不被看见)。默认仍是 `0`,因此
按外框裁剪创作的场景不受影响。
+### `ContentRect` —— 世界内容的矩形
+
+`UINode` 是引擎的盒子布局,UI 由它构成。靠 `Transform` 摆在世界里的内容——钉在相机上的 HUD、
+导入的场景——没有布局,它的范围分散在好几处:`Sprite` 有尺寸和轴心,`Text` 有文本框,
+而不绘制任何东西的实体根本没有范围,于是没法对它做裁剪。
+
+`ContentRect` 就是那一个矩形:局部单位的 `size`,以及实体变换所在的那一点 `pivot`
+(`(0.5, 0.5)` 是中心)。加上它之后:
+
+- 同一实体上的 `Sprite` 和 `Text` 的尺寸与轴心都跟随它,矩形只在一处写;
+- 实体上的 `UIMask` 把后代裁剪到它,不需要 `UINode`;
+- `contentRectContains(world, entity, x, y)` 用实体的位置、旋转和缩放判断一个世界点是否在其中。
+
+同时有 `UINode` 和 `ContentRect` 的实体,裁剪仍用布局的盒子。给已有矩形的实体再加
+`Sprite` 或 `Text` 时:调用一次 `applyContentRect`,或者把矩形再写一遍;矩形变化时它们会自己跟随。
+
### 子树透明度与指针门
`UINode` 上有两个**沿层级解析**的字段,与已有的 `display` 在同一趟里完成:
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 0fcf69743..51890db70 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 171,
- "experimental": 2730,
+ "experimental": 2732,
"deprecated": 3
},
- "total": 3016,
+ "total": 3018,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 9463ad35d..7211633f7 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -120,6 +120,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
UINode: { category: 'ui', summary: 'The UI box: size, position, margins and padding in design pixels. Every UI entity has one.', doc: 'ui/layout', anchor: 'uinode--the-box', anchorZh: 'uinode盒子' },
UIVisual: { category: 'ui', summary: 'What a UI node actually paints — a colour, a texture, or a nine-sliced sprite.', doc: 'ui/overview', anchor: 'uivisual-and-uimask', anchorZh: 'uivisual-与-uimask' },
UIMask: { category: 'ui', summary: "Clips descendants to this node's rect, with an optional alpha cutoff.", doc: 'ui/lists', anchor: 'clipping--uimask', anchorZh: '裁剪--uimask' },
+ ContentRect: { category: 'ui', summary: 'The rectangle world content occupies — a size and the pivot the transform sits on — that its sprite, text and clip mask follow.', doc: 'ui/overview', anchor: 'contentrect--a-rectangle-for-world-content', anchorZh: 'contentrect--世界内容的矩形' },
UIScroll: { category: 'ui', summary: 'Scrollable content inside a clipped viewport, with momentum and scrollbars.', doc: 'ui/overview', anchor: 'scrolling', anchorZh: '滚动' },
FlexContainer: { category: 'ui', summary: 'Lays children out along an axis — direction, justification, alignment, wrapping and gaps.', doc: 'ui/layout', anchor: 'flexcontainer--laying-out-children', anchorZh: 'flexcontainer排布子项' },
Interactable: { category: 'ui', summary: 'Makes a UI node hit-testable, so pointer events can land on it.', doc: 'ui/interaction', anchor: 'hit-testing-interactable--uiinteraction', anchorZh: '命中测试interactable--uiinteraction' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 54a177fa9..afe581112 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1072,6 +1072,25 @@
}
]
},
+ {
+ "name": "ContentRect",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "size",
+ "type": "Vec2",
+ "default": "(100, 100)",
+ "doc": "Width and height of the content in local units (before scale).",
+ "range": "≥ 0"
+ },
+ {
+ "key": "pivot",
+ "type": "Vec2",
+ "default": "(0.5, 0.5)",
+ "doc": "The point of the rectangle the entity sits on, as a fraction of its size (0.5,0.5 = centre). Rotation and scale turn about it."
+ }
+ ]
+ },
{
"name": "ConvexCollider3D",
"source": "cpp",
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index 1f399eb1f..8a642be44 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -271,8 +271,19 @@ function camera(c: CocosComponent, ctx: ComponentContext): ComponentData {
/** Names of the components the layer declares for built-ins; a scene that holds one needs `esengine/cocos` loaded. */
const LAYER = 'Cocos.';
-function uiTransformData(box: UiBox): ComponentData {
- return { type: `${LAYER}UITransform`, data: { width: box.width, height: box.height, anchorX: box.ax, anchorY: box.ay } };
+/** A node's rectangle as the engine's `ContentRect`: the size, and the pivot the node's position is the position of. */
+function contentRectData(box: UiBox): ComponentData {
+ return { type: 'ContentRect', data: { size: { x: box.width, y: box.height }, pivot: { x: box.ax, y: box.ay } } };
+}
+
+/**
+ * `cc.Mask` as the engine's `UIMask`, clipping to the node's rectangle. The rectangle mask is exact; ellipse, graphics and image masks
+ * clip to the same rectangle rather than to their shape (the engine's shaped clip is a stencil cut from a sprite on the node, which a
+ * Cocos mask does not carry), so those are counted as partial.
+ */
+function mask(c: CocosComponent, ctx: ComponentContext): ComponentData {
+ ctx.report.component('cc.Mask', num(c.data._type, 0) === 0 ? 'mapped' : 'partial');
+ return { type: 'UIMask', data: { enabled: c.enabled, mode: 0, alphaCutoff: 0 } };
}
/** Copy the serialised fields named in @p map to the layer's names, leaving out the ones the file does not carry. */
@@ -431,7 +442,10 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strin
break;
case 'cc.UITransform':
// Also the size the renderers below were given; this keeps the rectangle for a node that draws nothing.
- if (box) components.push(uiTransformData(box));
+ if (box) components.push(contentRectData(box));
+ break;
+ case 'cc.Mask':
+ out = mask(c, ctx);
break;
case 'cc.Widget':
out = widget(c);
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 759e2bc3a..4f4e8b0cb 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -10,6 +10,7 @@
*/
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
+import { isInsideRoot } from '../../fs/pathSandbox';
import { buildScriptIndex } from './scripts';
import { buildCocosAssetIndex, type CocosAssetEntry } from './assets';
import type { AssetHints, SliceBorder } from './components';
@@ -91,8 +92,7 @@ function declareBakedOutline(fnt: string): string {
export function importCocosProject(opts: CocosImportOptions): ImportReportData {
const source = path.resolve(opts.source);
const out = path.resolve(opts.out);
- const rel = path.relative(source, out);
- if (rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))) {
+ if (out === source || isInsideRoot(source, out)) {
throw new Error('the output project must not be inside the Cocos project: the source is never written to');
}
const assetsDir = path.join(source, 'assets');
diff --git a/pipeline/tests/cocos-compat-bundle.test.ts b/pipeline/tests/cocos-compat-bundle.test.ts
index 2f6b71e3b..59db65995 100644
--- a/pipeline/tests/cocos-compat-bundle.test.ts
+++ b/pipeline/tests/cocos-compat-bundle.test.ts
@@ -33,7 +33,7 @@ describe('bundling a Cocos script', () => {
writeFileSync(path.join(root, 'scripts', 'Plain.ts'), 'export const answer: number = 42;\n');
writeFileSync(path.join(root, 'layer.js'), 'export const _decorator = { ccclass: (n) => (c) => c, property: () => () => {} };\nexport class Component {}\nexport const EDITOR = false;\n');
});
- afterAll(() => rmSync(root, { recursive: true, force: true }));
+ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
const run = (extra: object) => build({
entryPoints: [path.join(root, 'scripts', 'Counter.ts')],
diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.ts
index 4ec99ecf9..87a588879 100644
--- a/pipeline/tests/cocos-import-layer.test.ts
+++ b/pipeline/tests/cocos-import-layer.test.ts
@@ -45,7 +45,7 @@ const scene = [
buttonOf: { __id__: 8 }, icon: { __uuid__: PLAIN }, _hidden: { __id__: 99 } }, // 9
{ __type__: 'cc.ClickEvent', target: { __id__: 4 }, component: '', _componentId: compressUuid(HUD), handler: 'onBuy', customEventData: 'gold' }, // 10
{ __type__: 'cc.Layout', node: { __id__: 4 }, _enabled: true, _layoutType: 2, _resizeMode: 1, _spacingY: 8, _paddingTop: 4, _cellSize: { width: 50, height: 60 }, _verticalDirection: 1 }, // 11
- node('Panel', 2, [], [13, 14, 15, 16, 17]), // 12
+ node('Panel', 2, [], [13, 14, 15, 16, 17, 19]), // 12
ui(12, 80, 20), // 13
{ __type__: 'cc.Toggle', node: { __id__: 12 }, _enabled: true, _isChecked: true, _checkMark: { __id__: 15 }, _interactable: true, _transition: 0,
clickEvents: [], checkEvents: [{ __id__: 18 }] }, // 14
@@ -53,6 +53,7 @@ const scene = [
{ __type__: 'cc.ScrollView', node: { __id__: 12 }, _enabled: true, _content: { __id__: 3 }, vertical: true, horizontal: false, brake: 0.75, bounceDuration: 0.23, scrollEvents: [] }, // 16
{ __type__: 'cc.ProgressBar', node: { __id__: 12 }, _enabled: true, _barSprite: { __id__: 15 }, _progress: 0.4, _totalLength: 80, _mode: 0 }, // 17
{ __type__: 'cc.ClickEvent', target: { __id__: 4 }, component: '', _componentId: compressUuid(HUD), handler: 'onPicked', customEventData: 'x' }, // 18
+ { __type__: 'cc.Mask', node: { __id__: 12 }, _enabled: true, _type: 0 }, // 19
];
describe('importing for the compatibility layer', () => {
@@ -89,13 +90,13 @@ describe('importing for the compatibility layer', () => {
report = importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });
scenes = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8'));
});
- afterAll(() => rmSync(root, { recursive: true, force: true }));
+ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
const entity = (name: string) => scenes.entities.find((e) => e.name === name)!;
const comp = (name: string, type: string) => entity(name).components.find((c) => c.type === type)!;
it('keeps a node\'s rectangle as a component of its own, as well as the size its renderers got', () => {
- expect(comp('Canvas', 'Cocos.UITransform').data).toEqual({ width: 960, height: 640, anchorX: 0.5, anchorY: 0.5 });
+ expect(comp('Canvas', 'ContentRect').data).toEqual({ size: { x: 960, y: 640 }, pivot: { x: 0.5, y: 0.5 } });
});
it('carries a widget\'s and a layout\'s settings under the names the layer uses', () => {
@@ -162,6 +163,12 @@ describe('importing for the compatibility layer', () => {
expect([bar.barSprite, bar.progress_, bar.totalLength]).toEqual([panel, 0.4, 80]);
});
+ it('turns a rectangle mask into the engine UIMask, which clips to the ContentRect beside it', () => {
+ expect(comp('Panel', 'UIMask').data).toEqual({ enabled: true, mode: 0, alphaCutoff: 0 });
+ expect(comp('Panel', 'ContentRect').data.size).toEqual({ x: 80, y: 20 });
+ expect(report.components['cc.Mask']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });
+ });
+
it('counts the components it maps', () => {
for (const type of ['cc.Widget', 'cc.Layout', 'cc.Button', 'cc.UITransform']) expect(report.components[type]!.unmapped).toBe(0);
});
diff --git a/pipeline/tests/cocos-import.test.ts b/pipeline/tests/cocos-import.test.ts
index b24a0070c..257423d67 100644
--- a/pipeline/tests/cocos-import.test.ts
+++ b/pipeline/tests/cocos-import.test.ts
@@ -162,7 +162,7 @@ beforeAll(async () => {
report = importCocosProject({ source: src, out });
});
-afterAll(() => rmSync(root, { recursive: true, force: true }));
+afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
const readJson = (rel: string): any => JSON.parse(readFileSync(path.join(out, rel), 'utf8'));
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index e1bffd924..b984db5b2 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,11 +1,11 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1963 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1965 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"6c653a8ebb70b5bc"
+"ac076564c4c51626"
```
## ANCHOR_AXES — const @experimental
@@ -2827,6 +2827,14 @@ usedBytes: number | null
versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]
```
+## ContentRectPlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): ContentRectPlugin
+static prototype: ContentRectPlugin
+```
+
## ControllerState — interface @experimental
```
current: string
@@ -10762,9 +10770,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
-boxHeight: number
-boxPivot: Vec2
-boxWidth: number
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color
content: string
enabled: boolean
@@ -13760,6 +13768,11 @@ MotionDriver<AnimatorBlend2DMotion>
(data: Uint8Array | string): string
```
+## contentRectPlugin — const @experimental
+```
+ContentRectPlugin
+```
+
## controllerState — function @experimental
```
(name: string, pages: string[], current?: string): ControllerState
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 6d9ca0f72..96d377508 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,11 +1,11 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 1982 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1984 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"6c653a8ebb70b5bc"
+"ac076564c4c51626"
```
## ANCHOR_AXES — const @experimental
@@ -2835,6 +2835,14 @@ usedBytes: number | null
versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]
```
+## ContentRectPlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): ContentRectPlugin
+static prototype: ContentRectPlugin
+```
+
## ControllerState — interface @experimental
```
current: string
@@ -10975,9 +10983,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
-boxHeight: number
-boxPivot: Vec2
-boxWidth: number
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color
content: string
enabled: boolean
@@ -13988,6 +13996,11 @@ MotionDriver<AnimatorBlend2DMotion>
(data: Uint8Array | string): string
```
+## contentRectPlugin — const @experimental
+```
+ContentRectPlugin
+```
+
## controllerState — function @experimental
```
(name: string, pages: string[], current?: string): ControllerState
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index cc4036be0..10b5c8f8d 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 161 beta · 1962 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1964 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2822,6 +2822,14 @@ usedBytes: number | null
versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]
```
+## ContentRectPlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): ContentRectPlugin
+static prototype: ContentRectPlugin
+```
+
## ControllerState — interface @experimental
```
current: string
@@ -10757,9 +10765,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
-boxHeight: number
-boxPivot: Vec2
-boxWidth: number
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color
content: string
enabled: boolean
@@ -13755,6 +13763,11 @@ MotionDriver<AnimatorBlend2DMotion>
(data: Uint8Array | string): string
```
+## contentRectPlugin — const @experimental
+```
+ContentRectPlugin
+```
+
## controllerState — function @experimental
```
(name: string, pages: string[], current?: string): ControllerState
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 092df67d7..56a9db07b 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1984 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1986 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2822,6 +2822,14 @@ usedBytes: number | null
versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]
```
+## ContentRectPlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): ContentRectPlugin
+static prototype: ContentRectPlugin
+```
+
## ControllerState — interface @experimental
```
current: string
@@ -11052,9 +11060,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
-boxHeight: number
-boxPivot: Vec2
-boxWidth: number
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color
content: string
enabled: boolean
@@ -14056,6 +14064,11 @@ MotionDriver<AnimatorBlend2DMotion>
(data: Uint8Array | string): string
```
+## contentRectPlugin — const @experimental
+```
+ContentRectPlugin
+```
+
## controllerState — function @experimental
```
(name: string, pages: string[], current?: string): ControllerState
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 29c84a512..09bad5650 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -24,6 +24,7 @@ addCapsuleCollider3D: (entity: Entity, component: CapsuleCollider3D) => void
addCharacterController3D: (entity: Entity, component: CharacterController3D) => void
addChildren: (entity: Entity, component: Children) => void
addCircleCollider2D: (entity: Entity, component: CircleCollider2D) => void
+addContentRect: (entity: Entity, component: ContentRect) => void
addConvexCollider3D: (entity: Entity, component: ConvexCollider3D) => void
addDraggable: (entity: Entity, component: Draggable) => void
addDragonBonesAnimation: (entity: Entity, component: DragonBonesAnimation) => void
@@ -82,6 +83,7 @@ getCapsuleCollider3D: (entity: Entity) => CapsuleCollider3D
getCharacterController3D: (entity: Entity) => CharacterController3D
getChildren: (entity: Entity) => Children
getCircleCollider2D: (entity: Entity) => CircleCollider2D
+getContentRect: (entity: Entity) => ContentRect
getConvexCollider3D: (entity: Entity) => ConvexCollider3D
getDraggable: (entity: Entity) => Draggable
getDragonBonesAnimation: (entity: Entity) => DragonBonesAnimation
@@ -133,6 +135,7 @@ hasCapsuleCollider3D: (entity: Entity) => boolean
hasCharacterController3D: (entity: Entity) => boolean
hasChildren: (entity: Entity) => boolean
hasCircleCollider2D: (entity: Entity) => boolean
+hasContentRect: (entity: Entity) => boolean
hasConvexCollider3D: (entity: Entity) => boolean
hasDraggable: (entity: Entity) => boolean
hasDragonBonesAnimation: (entity: Entity) => boolean
@@ -189,6 +192,7 @@ removeCapsuleCollider3D: (entity: Entity) => void
removeCharacterController3D: (entity: Entity) => void
removeChildren: (entity: Entity) => void
removeCircleCollider2D: (entity: Entity) => void
+removeContentRect: (entity: Entity) => void
removeConvexCollider3D: (entity: Entity) => void
removeDraggable: (entity: Entity) => void
removeDragonBonesAnimation: (entity: Entity) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f85e5e646..aeef68f9e 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1975 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1977 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2822,6 +2822,14 @@ usedBytes: number | null
versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]
```
+## ContentRectPlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): ContentRectPlugin
+static prototype: ContentRectPlugin
+```
+
## ControllerState — interface @experimental
```
current: string
@@ -10764,9 +10772,9 @@ ComponentDef<TextData>
```
align: TextAlign
bold: boolean
-boxHeight: number
-boxPivot: Vec2
-boxWidth: number
+boxHeight: number | undefined
+boxPivot: Vec2 | undefined
+boxWidth: number | undefined
color: Color
content: string
enabled: boolean
@@ -13787,6 +13795,11 @@ MotionDriver<AnimatorBlend2DMotion>
(data: Uint8Array | string): string
```
+## contentRectPlugin — const @experimental
+```
+ContentRectPlugin
+```
+
## controllerState — function @experimental
```
(name: string, pages: string[], current?: string): ControllerState
diff --git a/sdk/src/cocos/builtinScripts.ts b/sdk/src/cocos/builtinScripts.ts
index be8079433..09a3874e3 100644
--- a/sdk/src/cocos/builtinScripts.ts
+++ b/sdk/src/cocos/builtinScripts.ts
@@ -9,10 +9,11 @@
* again, and does so here; asking twice for the same context is harmless.
*/
import { getDefaultContext } from '../ecs/context';
+import { registerComponent } from '../ecs/component';
+import { ContentRect } from '../ui/core/content-rect';
import { declareButton } from './ui/button';
import { declareInputSystem } from './input';
import { declareUiPass } from './ui/pass';
-import { uiTransformDef } from './ui/uiTransform';
import { declareTweenSystem } from './tween';
import { declarePrefabSystem } from './prefabs';
import { declareGameSystem } from './game';
@@ -25,10 +26,10 @@ export function declareBuiltinScripts(): void {
const context = getDefaultContext();
if (declared.has(context)) return;
declared.add(context);
+ // `UITransform` is a view on the engine's rectangle; a scene that holds one needs it registered even in an app without the UI pipeline.
+ registerComponent('ContentRect', ContentRect);
declareButton();
declareInputSystem();
- // A scene holds `Cocos.UITransform` before any script asks for one, so the component has to exist when it loads.
- uiTransformDef();
declareUiPass();
declareTweenSystem();
declarePrefabSystem();
diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.ts
index 986959531..56e920554 100644
--- a/sdk/src/cocos/index.ts
+++ b/sdk/src/cocos/index.ts
@@ -26,7 +26,7 @@ export {
AnimationClip, SceneAsset, EffectAsset, Mesh,
} from './assets';
export { registerBuiltinComponent, type BuiltinAdapter } from './builtins';
-export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, Camera, RichText, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, getVisibleSize, setVisibleSize } from './ui';
+export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, Camera, RichText, Mask, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, getVisibleSize, setVisibleSize } from './ui';
export { Touch, EventTouch, pumpTouches } from './input';
export { tween, Tween, tweenUtil, easing, updateTweens } from './tween';
export { instantiate, loadPrefab, providePrefab } from './prefabs';
diff --git a/sdk/src/cocos/ui/index.ts b/sdk/src/cocos/ui/index.ts
index 35ed4acf6..0657f6c18 100644
--- a/sdk/src/cocos/ui/index.ts
+++ b/sdk/src/cocos/ui/index.ts
@@ -4,7 +4,7 @@
* @file cocos/ui/index.ts
* @brief Cocos's built-in UI components, as views on the engine's. Importing this registers their adapters.
*/
-export { UITransform, uiTransformDef, ensureUITransform } from './uiTransform';
+export { UITransform, ensureUITransform } from './uiTransform';
export { Label, LabelOutline, LabelShadow } from './label';
export { Sprite, UIOpacity } from './sprite';
export { Button, EventHandler, declareButton } from './button';
@@ -15,3 +15,4 @@ export { Layout } from './layout';
export { getVisibleSize, setVisibleSize } from './screen';
export { Camera } from './camera';
export { RichText } from './richText';
+export { Mask } from './mask';
diff --git a/sdk/src/cocos/ui/mask.ts b/sdk/src/cocos/ui/mask.ts
new file mode 100644
index 000000000..41535de38
--- /dev/null
+++ b/sdk/src/cocos/ui/mask.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/ui/mask.ts
+ * @brief `Mask`: a view on the engine's `UIMask`, clipping the node's children to its rectangle.
+ *
+ * The clip box is the node's `ContentRect` (what `UITransform` reads and writes), so a mask is an engine `UIMask` on a node that
+ * has a size, and the renderer's scissor does the work. A rectangle mask is exact. The shaped types — ellipse, graphics, image — clip
+ * to the same rectangle: the engine cuts a shape from a sprite on the node, which a Cocos mask does not carry. `inverted` is not
+ * carried either. Both are held so a script can read back what it set.
+ */
+import { UIMask, MaskMode } from '../../ui/core/ui-mask';
+import type { World } from '../../ecs/world';
+import type { Entity } from '../../types';
+import { Component } from '../component';
+import { registerBuiltinComponent } from '../builtins';
+import { ensureUITransform } from './uiTransform';
+import { viewAdapter } from './view';
+
+const Type = Object.freeze({ RECT: 0, ELLIPSE: 1, GRAPHICS_STENCIL: 2, IMAGE_STENCIL: 3 });
+
+export class Mask extends Component {
+ static readonly Type = Type;
+
+ type: number = Type.RECT;
+ inverted = false;
+ segments = 64;
+ alphaThreshold = 0.1;
+
+ get enabled(): boolean { return this._world.get(this._entity, UIMask).enabled; }
+ set enabled(v: boolean) { this._world.set(this._entity, UIMask, { ...this._world.get(this._entity, UIMask), enabled: v }); }
+}
+
+const hasMask = (world: World, entity: Entity): boolean => world.has(entity, UIMask);
+const addMask = (world: World, entity: Entity): void => {
+ ensureUITransform(world, entity);
+ world.insert(entity, UIMask, { enabled: true, mode: MaskMode.Scissor, alphaCutoff: 0 });
+};
+
+registerBuiltinComponent(Mask, ['cc.Mask', 'Mask'], viewAdapter(Mask, hasMask, addMask));
diff --git a/sdk/src/cocos/ui/pass.ts b/sdk/src/cocos/ui/pass.ts
index bfdfaf067..617b16d71 100644
--- a/sdk/src/cocos/ui/pass.ts
+++ b/sdk/src/cocos/ui/pass.ts
@@ -11,6 +11,7 @@
import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../../ecs/system';
import { Res } from '../../ecs/resource';
import { UICameraInfo } from '../../ui/core/ui-camera-info';
+import { ScreenLayout } from '../../ui/core/screen-layout';
import { setCurrentWorld } from '../node';
import { alignAllWidgets, declareWidget } from './widget';
import { layoutAll, declareLayout } from './layout';
@@ -24,13 +25,14 @@ export function declareUiPass(): void {
declareControls();
declareScrollView();
const system = defineSystem(
- [Res(UICameraInfo), GetWorld()],
- (camera, world) => {
- // What the UI camera shows is the visible area scripts and widgets measure against; the surface is the window.
+ [Res(UICameraInfo), Res(ScreenLayout), GetWorld()],
+ (camera, screen, world) => {
+ // The camera is kept for the conversions a Cocos `Camera` offers. What the player sees, and the window, are the screen's: the
+ // layout box UI is placed within, and the framebuffer it projects onto.
setUiCameraData(camera ?? null);
- if (camera?.valid) {
- setVisibleSize(camera.worldRight - camera.worldLeft, camera.worldTop - camera.worldBottom);
- setWindowPixels(camera.screenW, camera.screenH);
+ if (screen?.valid) {
+ setVisibleSize(screen.right - screen.left, screen.top - screen.bottom);
+ setWindowPixels(screen.viewportW, screen.viewportH);
}
const previous = setCurrentWorld(world);
try {
diff --git a/sdk/src/cocos/ui/richText.ts b/sdk/src/cocos/ui/richText.ts
index 4b4a76031..138135c37 100644
--- a/sdk/src/cocos/ui/richText.ts
+++ b/sdk/src/cocos/ui/richText.ts
@@ -40,7 +40,7 @@ export class RichText extends TextView {
set horizontalAlign(v: number) { this.patch_({ align: v as TextData['align'] }); }
/** The width at which lines wrap; 0 means they do not. */
- get maxWidth(): number { const t = this.text_(); return t.wordWrap ? t.boxWidth : 0; }
+ get maxWidth(): number { const t = this.text_(); return t.wordWrap ? (t.boxWidth ?? 0) : 0; }
set maxWidth(v: number) { this.patch_(v > 0 ? { wordWrap: true, boxWidth: v } : { wordWrap: false }); }
get enabled(): boolean { return this.text_().enabled; }
diff --git a/sdk/src/cocos/ui/uiTransform.ts b/sdk/src/cocos/ui/uiTransform.ts
index 71c9fcd42..cac893a4b 100644
--- a/sdk/src/cocos/ui/uiTransform.ts
+++ b/sdk/src/cocos/ui/uiTransform.ts
@@ -2,19 +2,17 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file cocos/ui/uiTransform.ts
- * @brief `UITransform`: a node's content size and anchor point.
+ * @brief `UITransform`: a node's content size and anchor point, as a view on the engine's `ContentRect`.
*
- * In Cocos the rectangle belongs to the node and the renderers draw into it. The engine has the opposite arrangement — a `Sprite`
- * has its own size and pivot, a `Text` its own box — and nothing for a node that draws nothing but still has an extent (a button's
- * hit area, a layout container, a scroll view's viewport). So the extent is kept in a small data component of the compatibility layer,
- * `Cocos.UITransform`, which is the one place a script's `contentSize` lives, and a write to it is carried through to the `Sprite` and
- * `Text` on the same node so they draw into the rectangle the script set.
+ * In Cocos the rectangle belongs to the node and the renderers draw into it; the engine's `ContentRect` is the same idea (a size and
+ * the pivot the transform sits on), and the `Sprite`, `Text` and clip mask on the entity follow it. So `UITransform` has no
+ * storage and no copying of its own: it reads and writes `ContentRect`, and the rectangle's consumers are the engine's.
*
- * Importing a scene writes this component for every node that had a `UITransform`, so it starts out as authored; a node that never
- * had one gets it when a script first asks, filled in from the renderer it has.
+ * Importing a scene writes a `ContentRect` for every node that had a `UITransform`; a node that never had one gets it when a
+ * script first asks, filled in from the renderer it has.
*/
-import { defineComponent } from '../../ecs/component';
import { Sprite, Transform } from '../../ecs/component';
+import { ContentRect, applyContentRect, contentRectContains, type ContentRectData } from '../../ui/core/content-rect';
import { Text } from '../../ui/core/text';
import type { World } from '../../ecs/world';
import type { Entity } from '../../types';
@@ -23,81 +21,58 @@ import { Component } from '../component';
import { registerBuiltinComponent } from '../builtins';
import { viewAdapter } from './view';
-export interface UITransformData {
- width: number;
- height: number;
- anchorX: number;
- anchorY: number;
-}
-
-/** The data component, defined per context so a fresh `AppContext` still finds it. */
-export function uiTransformDef() {
- return defineComponent<UITransformData>('Cocos.UITransform', { width: 100, height: 100, anchorX: 0.5, anchorY: 0.5 });
-}
-
/** The rectangle a node's renderers say it has, for a node that was never given one. */
-function derive(world: World, entity: Entity): UITransformData {
+function derive(world: World, entity: Entity): ContentRectData {
const sprite = world.has(entity, Sprite) ? world.get(entity, Sprite) : null;
- if (sprite) return { width: sprite.size.x, height: sprite.size.y, anchorX: sprite.pivot.x, anchorY: sprite.pivot.y };
+ if (sprite) return { size: { x: sprite.size.x, y: sprite.size.y }, pivot: { x: sprite.pivot.x, y: sprite.pivot.y } };
const text = world.has(entity, Text) ? world.get(entity, Text) : null;
- if (text && (text.boxWidth > 0 || text.boxHeight > 0)) {
- return { width: text.boxWidth, height: text.boxHeight, anchorX: text.boxPivot.x, anchorY: text.boxPivot.y };
+ const w = text?.boxWidth ?? 0, h = text?.boxHeight ?? 0;
+ if (text && (w > 0 || h > 0)) {
+ const pivot = text.boxPivot ?? { x: 0.5, y: 0.5 };
+ return { size: { x: w, y: h }, pivot: { x: pivot.x, y: pivot.y } };
}
- return { width: 100, height: 100, anchorX: 0.5, anchorY: 0.5 };
+ return { size: { x: 100, y: 100 }, pivot: { x: 0.5, y: 0.5 } };
}
-/** The rectangle data of a node, made if it has none. */
-export function ensureUITransform(world: World, entity: Entity): UITransformData {
- const def = uiTransformDef();
- if (!world.has(entity, def)) world.insert(entity, def, derive(world, entity));
- return world.get(entity, def);
-}
-
-/** Carry a rectangle to the renderers on the same node, which draw it. */
-function propagate(world: World, entity: Entity, rect: UITransformData): void {
- if (world.has(entity, Sprite)) {
- const s = world.get(entity, Sprite);
- world.set(entity, Sprite, { ...s, size: { x: rect.width, y: rect.height }, pivot: { x: rect.anchorX, y: rect.anchorY } });
- }
- if (world.has(entity, Text)) {
- const t = world.get(entity, Text);
- world.set(entity, Text, { ...t, boxWidth: rect.width, boxHeight: rect.height, boxPivot: { x: rect.anchorX, y: rect.anchorY } });
- }
+/** The rectangle of a node, made if it has none. */
+export function ensureUITransform(world: World, entity: Entity): ContentRectData {
+ if (!world.has(entity, ContentRect)) world.insert(entity, ContentRect, derive(world, entity));
+ return world.get(entity, ContentRect);
}
export class UITransform extends Component {
- private read_(): UITransformData { return ensureUITransform(this._world, this._entity); }
- private write_(patch: Partial<UITransformData>): void {
- const next = { ...this.read_(), ...patch };
- this._world.set(this._entity, uiTransformDef(), next);
- propagate(this._world, this._entity, next);
+ private rect_(): ContentRectData { return ensureUITransform(this._world, this._entity); }
+ /** Write the rectangle, and let the sprite and text on the node follow it now rather than at the end of the frame. */
+ private write_(size: { x: number; y: number }, pivot: { x: number; y: number }): void {
+ this._world.set(this._entity, ContentRect, { size, pivot });
+ applyContentRect(this._world, this._entity);
}
- get contentSize(): Size { const r = this.read_(); return new Size(r.width, r.height); }
- set contentSize(v: Size) { this.write_({ width: v.width, height: v.height }); }
+ get contentSize(): Size { const r = this.rect_(); return new Size(r.size.x, r.size.y); }
+ set contentSize(v: Size) { this.write_({ x: v.width, y: v.height }, this.rect_().pivot); }
setContentSize(w: number | Size, h?: number): void {
- if (typeof w === 'object') this.contentSize = w; else this.write_({ width: w, height: h ?? this.read_().height });
+ if (typeof w === 'object') this.contentSize = w; else this.write_({ x: w, y: h ?? this.rect_().size.y }, this.rect_().pivot);
}
- get width(): number { return this.read_().width; }
- set width(v: number) { this.write_({ width: v }); }
- get height(): number { return this.read_().height; }
- set height(v: number) { this.write_({ height: v }); }
+ get width(): number { return this.rect_().size.x; }
+ set width(v: number) { const r = this.rect_(); this.write_({ x: v, y: r.size.y }, r.pivot); }
+ get height(): number { return this.rect_().size.y; }
+ set height(v: number) { const r = this.rect_(); this.write_({ x: r.size.x, y: v }, r.pivot); }
- get anchorPoint(): Vec2 { const r = this.read_(); return new Vec2(r.anchorX, r.anchorY); }
- set anchorPoint(v: Vec2) { this.write_({ anchorX: v.x, anchorY: v.y }); }
+ get anchorPoint(): Vec2 { const r = this.rect_(); return new Vec2(r.pivot.x, r.pivot.y); }
+ set anchorPoint(v: Vec2) { this.write_(this.rect_().size, { x: v.x, y: v.y }); }
setAnchorPoint(x: number | Vec2, y?: number): void {
- if (typeof x === 'object') this.anchorPoint = x; else this.write_({ anchorX: x, anchorY: y ?? this.read_().anchorY });
+ if (typeof x === 'object') this.anchorPoint = x; else this.write_(this.rect_().size, { x, y: y ?? this.rect_().pivot.y });
}
- get anchorX(): number { return this.read_().anchorX; }
- set anchorX(v: number) { this.write_({ anchorX: v }); }
- get anchorY(): number { return this.read_().anchorY; }
- set anchorY(v: number) { this.write_({ anchorY: v }); }
+ get anchorX(): number { return this.rect_().pivot.x; }
+ set anchorX(v: number) { const r = this.rect_(); this.write_(r.size, { x: v, y: r.pivot.y }); }
+ get anchorY(): number { return this.rect_().pivot.y; }
+ set anchorY(v: number) { const r = this.rect_(); this.write_(r.size, { x: r.pivot.x, y: v }); }
/** The rectangle in the node's own space: its left/bottom corner is minus the anchor times the size. */
private local_(): Rect {
- const r = this.read_();
- return new Rect(-r.anchorX * r.width, -r.anchorY * r.height, r.width, r.height);
+ const r = this.rect_();
+ return new Rect(-r.pivot.x * r.size.x, -r.pivot.y * r.size.y, r.size.x, r.size.y);
}
/** A point in the node's space (relative to its anchor) as a point in world space, scale and rotation applied. */
@@ -136,8 +111,8 @@ export class UITransform extends Component {
/** Whether a world-space point is inside the rectangle. */
isHit(worldPoint: Vec2): boolean {
- const local = this.convertToNodeSpaceAR(new Vec3(worldPoint.x, worldPoint.y, 0));
- return this.local_().contains(new Vec2(local.x, local.y));
+ this.rect_();
+ return contentRectContains(this._world, this._entity, worldPoint.x, worldPoint.y);
}
/** The axis-aligned box of the rectangle in world space. */
@@ -153,6 +128,6 @@ export class UITransform extends Component {
registerBuiltinComponent(UITransform, ['cc.UITransform', 'UITransform'], viewAdapter(
UITransform,
- (world, entity) => world.has(entity, uiTransformDef()) || world.has(entity, Sprite) || world.has(entity, Text),
+ (world, entity) => world.has(entity, ContentRect) || world.has(entity, Sprite) || world.has(entity, Text),
(world, entity) => { ensureUITransform(world, entity); },
));
diff --git a/sdk/src/core-plugins.ts b/sdk/src/core-plugins.ts
index fdc41f43f..552000aef 100644
--- a/sdk/src/core-plugins.ts
+++ b/sdk/src/core-plugins.ts
@@ -23,6 +23,7 @@ export { uiPlugins } from './app/uiPlugins';
export { uiPlugin, UIPlugin } from './ui/ui-plugin';
export { textPlugin, TextPlugin } from './ui/text/plugin';
export { uiMaskPlugin, UIMaskPlugin } from './ui/render/mask';
+export { contentRectPlugin, ContentRectPlugin } from './ui/render/content-rect';
export { uiInteractionPlugin, UIInteractionPlugin } from './ui/input/interaction';
export { uiLayoutPlugin, UILayoutPlugin } from './ui/layout/layout';
export { uiRenderOrderPlugin, UIRenderOrderPlugin } from './ui/render/render-order';
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index b901a368f..92e9016ab 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -505,6 +505,34 @@ export function createCircleCollider2DData(): CircleCollider2DPtrData {
};
}
+export interface ContentRectPtrData {
+ size: Vec2;
+ pivot: Vec2;
+}
+
+export function fillContentRect(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: ContentRectPtrData,
+): void {
+ const size_ = out.size; size_.x = f32[ptr >> 2]; size_.y = f32[(ptr >> 2) + 1];
+ const pivot_ = out.pivot; pivot_.x = f32[(ptr + 8) >> 2]; pivot_.y = f32[((ptr + 8) >> 2) + 1];
+}
+
+export function writeContentRect(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: ContentRectPtrData,
+): void {
+ f32[ptr >> 2] = data.size.x; f32[(ptr >> 2) + 1] = data.size.y;
+ f32[(ptr + 8) >> 2] = data.pivot.x; f32[((ptr + 8) >> 2) + 1] = data.pivot.y;
+}
+
+export function createContentRectData(): ContentRectPtrData {
+ return {
+ size: { x: 0, y: 0 },
+ pivot: { x: 0, y: 0 },
+ };
+}
+
export interface ConvexCollider3DPtrData {
mesh: number;
friction: number;
@@ -2709,6 +2737,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
CapsuleCollider3D: { fill: fillCapsuleCollider3D, write: writeCapsuleCollider3D, create: createCapsuleCollider3DData },
CharacterController3D: { fill: fillCharacterController3D, write: writeCharacterController3D, create: createCharacterController3DData },
CircleCollider2D: { fill: fillCircleCollider2D, write: writeCircleCollider2D, create: createCircleCollider2DData },
+ ContentRect: { fill: fillContentRect, write: writeContentRect, create: createContentRectData },
ConvexCollider3D: { fill: fillConvexCollider3D, write: writeConvexCollider3D, create: createConvexCollider3DData },
Draggable: { fill: fillDraggable, write: writeDraggable, create: createDraggableData },
DragonBonesAnimation: { fill: fillDragonBonesAnimation, write: writeDragonBonesAnimation, create: createDragonBonesAnimationData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 818ef1e8e..a7654676c 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '6c653a8ebb70b5bc';
+export const ABI_LAYOUT_HASH = 'ac076564c4c51626';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -319,6 +319,20 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
colorFields: [],
animatableFields: [],
},
+ ContentRect: {
+ defaults: {
+ size: { x: 100, y: 100 },
+ pivot: { x: 0.5, y: 0.5 },
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ size: { min: 0, tooltip: "Width and height of the content in local units (before scale)." },
+ pivot: { tooltip: "The point of the rectangle the entity sits on, as a fraction of its size (0.5,0.5 = centre). Rotation and scale turn about it.", normalizedOf: "size" },
+ },
+ },
ConvexCollider3D: {
defaults: {
mesh: 0,
@@ -1492,6 +1506,17 @@ export interface CircleCollider2DData {
maskBits: number;
}
+/**
+ * The fields of the engine's `ContentRect` component, generated from
+ * the C++ struct so the two shapes cannot drift.
+ *
+ * @experimental
+ */
+export interface ContentRectData {
+ size: Vec2;
+ pivot: Vec2;
+}
+
export interface ConvexCollider3DData {
mesh: number;
friction: number;
diff --git a/sdk/src/ui/core/content-rect.ts b/sdk/src/ui/core/content-rect.ts
new file mode 100644
index 000000000..0c8884873
--- /dev/null
+++ b/sdk/src/ui/core/content-rect.ts
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/core/content-rect.ts
+ * @brief `ContentRect` — the rectangle world content occupies, and how renderers follow it.
+ *
+ * A `Sprite` has a size and pivot, a `Text` a box and a box pivot, and an entity that draws nothing has neither. `ContentRect` is the
+ * one rectangle for all of them: write it, and the sprite and text on the same entity follow ({@link applyContentRect}); a clip
+ * mask takes its box from it (C++, `RenderFrameMask`); a pointer can be tested against it ({@link contentRectContains}).
+ *
+ * It is for content placed by its `Transform` (an imported scene, a hand-built HUD). `UINode` remains the engine's box layout; an
+ * entity with both keeps the layout's box for clipping.
+ */
+import { defineBuiltin, Sprite, Transform } from '../../ecs/component';
+import type { ContentRectData } from '../../ecs/component.generated';
+import type { World } from '../../ecs/world';
+import type { Entity } from '../../types';
+import { Text } from './text';
+
+export type { ContentRectData };
+
+export const ContentRect = defineBuiltin<ContentRectData>('ContentRect', {
+ size: { x: 100, y: 100 },
+ pivot: { x: 0.5, y: 0.5 },
+});
+
+const same = (a: { x: number; y: number }, b: { x: number; y: number }): boolean => a.x === b.x && a.y === b.y;
+
+/**
+ * Make the sprite and text on @p entity follow its `ContentRect`. Only what differs is written, so calling it again is free. Call it
+ * after adding a `Sprite` or `Text` to an entity that already has a rect; the plugin calls it whenever a rect changes.
+ */
+export function applyContentRect(world: World, entity: Entity): void {
+ const rect = world.tryGet(entity, ContentRect);
+ if (!rect) return;
+ if (world.has(entity, Sprite)) {
+ const s = world.get(entity, Sprite);
+ if (!same(s.size, rect.size) || !same(s.pivot, rect.pivot)) {
+ world.set(entity, Sprite, { ...s, size: { x: rect.size.x, y: rect.size.y }, pivot: { x: rect.pivot.x, y: rect.pivot.y } });
+ }
+ }
+ if (world.has(entity, Text)) {
+ const t = world.get(entity, Text);
+ if (t.boxWidth !== rect.size.x || t.boxHeight !== rect.size.y || !t.boxPivot || !same(t.boxPivot, rect.pivot)) {
+ world.set(entity, Text, {
+ ...t, boxWidth: rect.size.x, boxHeight: rect.size.y, boxPivot: { x: rect.pivot.x, y: rect.pivot.y },
+ });
+ }
+ }
+}
+
+/** The corners-in-local-space test: whether the entity-space point (relative to its pivot, unscaled) is inside the rectangle. */
+export function localPointInRect(rect: ContentRectData, x: number, y: number): boolean {
+ const left = -rect.pivot.x * rect.size.x;
+ const bottom = -rect.pivot.y * rect.size.y;
+ return x >= left && x <= left + rect.size.x && y >= bottom && y <= bottom + rect.size.y;
+}
+
+/**
+ * Whether the world point (@p worldX, @p worldY) is inside the entity's rectangle, with its transform's position, rotation and scale
+ * applied. False for an entity without a rect, or with a scale of zero.
+ */
+export function contentRectContains(world: World, entity: Entity, worldX: number, worldY: number): boolean {
+ const rect = world.tryGet(entity, ContentRect);
+ if (!rect) return false;
+ world.ensureTransformsComposed();
+ const t = world.get(entity, Transform);
+ const sx = t.worldScale.x, sy = t.worldScale.y;
+ if (sx === 0 || sy === 0) return false;
+ const dx = worldX - t.worldPosition.x, dy = worldY - t.worldPosition.y;
+ // rotation about z only: the flat case a rectangle has
+ const { z, w } = t.worldRotation;
+ const angle = 2 * Math.atan2(z, w);
+ const cos = Math.cos(-angle), sin = Math.sin(-angle);
+ return localPointInRect(rect, (dx * cos - dy * sin) / sx, (dx * sin + dy * cos) / sy);
+}
diff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.ts
index 7d74aad9f..45668eefe 100644
--- a/sdk/src/ui/core/text.ts
+++ b/sdk/src/ui/core/text.ts
@@ -126,14 +126,14 @@ export interface TextData {
* under a `UINode`, while the text stays world content sorted by `layer`. A `UINode`, when present, decides
* the box and these three are ignored.
*/
- boxWidth: number;
+ boxWidth?: number;
/** Height of that box; 0 for none. Vertical alignment and `Clip`/`Ellipsis` need it. */
- boxHeight: number;
+ boxHeight?: number;
/**
* Where the entity origin sits inside the box, as a fraction from its left and bottom edges: (0.5, 0.5) is
* the centre, (0, 1) the top-left corner. It is the anchor point of a Cocos or Unity rect transform.
*/
- boxPivot: Vec2;
+ boxPivot?: Vec2;
/** Render toggle — the editor's eye and runtime hiding both flip this. */
enabled: boolean;
}
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 7ffb262c1..a7d99f39c 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -60,6 +60,8 @@ export {
export { UIMask, MaskMode, type UIMaskData } from './core/ui-mask';
export { UIScroll, ScrollMovement, type UIScrollData } from './core/ui-scroll';
+export { ContentRect, applyContentRect, contentRectContains, localPointInRect, type ContentRectData } from './core/content-rect';
+export { contentRectPlugin, ContentRectPlugin } from './render/content-rect';
export {
Text,
diff --git a/sdk/src/ui/render/content-rect.ts b/sdk/src/ui/render/content-rect.ts
new file mode 100644
index 000000000..9b3c6f782
--- /dev/null
+++ b/sdk/src/ui/render/content-rect.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import type { App, Plugin } from '../../app/app';
+import { registerComponent } from '../../ecs/component';
+import { defineSystem, Schedule } from '../../ecs/system';
+import { ContentRect, applyContentRect } from '../core/content-rect';
+
+/**
+ * Registers `ContentRect` and keeps the sprites and texts that share an entity with one following it.
+ *
+ * Only entities whose rect changed since the last run are visited (change tracking), at the end of the update and again at the very
+ * end, so a script that resizes something in the frame's last system still draws it at the new size that frame.
+ */
+export class ContentRectPlugin implements Plugin {
+ name = 'contentRect';
+
+ build(app: App): void {
+ registerComponent('ContentRect', ContentRect);
+ const world = app.world;
+ world.enableChangeTracking(ContentRect);
+ let seen = -1;
+ const sync = (): void => {
+ if (!world.anyChangedSince(ContentRect, seen)) return;
+ const since = seen;
+ // the watermark trails by one tick so a write in this very tick is seen next time too
+ seen = world.getWorldTick() - 1;
+ for (const entity of world.getEntitiesWithComponents([ContentRect])) {
+ if (world.isChangedSince(entity, ContentRect, since)) applyContentRect(world, entity);
+ }
+ };
+ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem([], sync, { name: 'ContentRectSystem' }));
+ app.addSystemToSchedule(Schedule.Last, defineSystem([], sync, { name: 'ContentRectLateSystem' }));
+ }
+}
+
+export const contentRectPlugin = new ContentRectPlugin();
diff --git a/sdk/src/ui/ui-plugin.ts b/sdk/src/ui/ui-plugin.ts
index bcab0c165..a2b1c750e 100644
--- a/sdk/src/ui/ui-plugin.ts
+++ b/sdk/src/ui/ui-plugin.ts
@@ -18,6 +18,7 @@ import type { Entity } from '../types';
import { uiLayoutPlugin } from './layout/layout';
import { uiMaskPlugin } from './render/mask';
+import { contentRectPlugin } from './render/content-rect';
import { safeAreaPlugin } from './layout/safe-area';
import { textPlugin } from './text/plugin';
import { inlineImagePlugin } from './text/inline-image-plugin';
@@ -43,6 +44,7 @@ import type { ScrollContainer } from './collection/scroll-container';
const SUB_PLUGINS: Plugin[] = [
uiLayoutPlugin,
uiMaskPlugin,
+ contentRectPlugin,
safeAreaPlugin,
textPlugin,
inlineImagePlugin,
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index 14f570e03..b490b0c93 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -151,6 +151,13 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'maskBits', type: 'u32', offset: 32 },
],
},
+ ContentRect: {
+ ptrFn: 'getContentRectPtr',
+ fields: [
+ { name: 'size', type: 'vec2', offset: 0 },
+ { name: 'pivot', type: 'vec2', offset: 8 },
+ ],
+ },
ConvexCollider3D: {
ptrFn: 'getConvexCollider3DPtr',
fields: [
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index 2c23ddfef..342f3b615 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -558,6 +558,11 @@ export interface CircleCollider2D {
maskBits: number;
}
+export interface ContentRect {
+ size: Vec2;
+ pivot: Vec2;
+}
+
export interface ConvexCollider3D {
mesh: number;
friction: number;
@@ -1102,6 +1107,10 @@ export interface Registry {
getCircleCollider2D(entity: Entity): CircleCollider2D;
addCircleCollider2D(entity: Entity, component: CircleCollider2D): void;
removeCircleCollider2D(entity: Entity): void;
+ hasContentRect(entity: Entity): boolean;
+ getContentRect(entity: Entity): ContentRect;
+ addContentRect(entity: Entity, component: ContentRect): void;
+ removeContentRect(entity: Entity): void;
hasConvexCollider3D(entity: Entity): boolean;
getConvexCollider3D(entity: Entity): ConvexCollider3D;
addConvexCollider3D(entity: Entity, component: ConvexCollider3D): void;
@@ -1295,6 +1304,7 @@ export interface ESEngineModule {
CharacterController3D: new () => CharacterController3D;
Children: new () => Children;
CircleCollider2D: new () => CircleCollider2D;
+ ContentRect: new () => ContentRect;
ConvexCollider3D: new () => ConvexCollider3D;
Draggable: new () => Draggable;
DragonBonesAnimation: new () => DragonBonesAnimation;
diff --git a/sdk/tests/cocos/camera-richtext-wasm.test.ts b/sdk/tests/cocos/camera-richtext-wasm.test.ts
index c2934caf6..86a4f927f 100644
--- a/sdk/tests/cocos/camera-richtext-wasm.test.ts
+++ b/sdk/tests/cocos/camera-richtext-wasm.test.ts
@@ -14,10 +14,12 @@ import { Camera as EngineCamera, Transform, ensureBuiltinComponentsRegistered }
import { AppContext, setDefaultContext } from '../../src/ecs/context';
import { InputState } from '../../src/input/input';
import { Text } from '../../src/ui/core/text';
+import { UIMask, MaskMode } from '../../src/ui/core/ui-mask';
+import { ContentRect } from '../../src/ui/core/content-rect';
import { parseRichText } from '../../src/ui/text/rich-text-parser';
import { resetClassRegistry } from '../../src/cocos/registry';
import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';
-import { Camera, Color, EventTouch, Node, RichText, UITransform, Vec3, pumpTouches, setCurrentWorld } from '../../src/cocos';
+import { Camera, Color, EventTouch, Mask, Node, RichText, UITransform, Vec3, pumpTouches, setCurrentWorld } from '../../src/cocos';
import { setUiCameraData } from '../../src/cocos/ui/screen';
import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
@@ -205,4 +207,21 @@ describe.skipIf(!HAS_WASM)('Camera, RichText and touch locations', () => {
expect(n.getComponent(RichText)).toBeNull();
});
});
+
+ describe('Mask', () => {
+ it('is the engine UIMask on a node with a rectangle, so the clip box is the size of the node', () => {
+ boot();
+ const n = node('clip');
+ const m = n.addComponent(Mask)!;
+ expect(app!.world.has(n._entity, UIMask)).toBe(true);
+ expect(app!.world.get(n._entity, UIMask).mode).toBe(MaskMode.Scissor);
+ expect(app!.world.has(n._entity, ContentRect)).toBe(true);
+ n.getComponent(UITransform)!.setContentSize(300, 200);
+ const r = app!.world.get(n._entity, ContentRect);
+ expect([r.size.x, r.size.y]).toEqual([300, 200]);
+ m.enabled = false;
+ expect(app!.world.get(n._entity, UIMask).enabled).toBe(false);
+ expect(n.getComponent(Mask)).toBe(m);
+ });
+ });
});
diff --git a/sdk/tests/cocos/globals-wasm.test.ts b/sdk/tests/cocos/globals-wasm.test.ts
index 75494613b..14d776d5f 100644
--- a/sdk/tests/cocos/globals-wasm.test.ts
+++ b/sdk/tests/cocos/globals-wasm.test.ts
@@ -13,7 +13,7 @@ import { App, flushPendingRegistrations } from '../../src/app/app';
import { ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
import { AppContext, setDefaultContext } from '../../src/ecs/context';
import { InputState } from '../../src/input/input';
-import { UICameraInfo } from '../../src/ui/core/ui-camera-info';
+import { ScreenLayout } from '../../src/ui/core/screen-layout';
import { resetClassRegistry } from '../../src/cocos/registry';
import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';
import { pumpKeysAndMouse, pumpTouches } from '../../src/cocos/input';
@@ -124,10 +124,11 @@ describe.skipIf(!HAS_WASM)('input, game and view from the frame loop', () => {
expect(game.frameStartTime).toBeGreaterThan(0);
});
- it('takes the visible size and the window from what the UI camera shows', async () => {
+ it('takes the visible size and the window from the screen layout', async () => {
boot();
- app!.insertResource(UICameraInfo, {
- valid: true, worldLeft: -640, worldRight: 640, worldBottom: -360, worldTop: 360, screenW: 2560, screenH: 1440,
+ app!.insertResource(ScreenLayout, {
+ valid: true, left: -640, right: 640, bottom: -360, top: 360, safeLeft: -640, safeRight: 640, safeBottom: -360, safeTop: 360,
+ scale: 2, viewportW: 2560, viewportH: 1440,
} as never);
await app!.tick(1 / 60);
expect([view.getVisibleSize().width, view.getVisibleSize().height]).toEqual([1280, 720]);
diff --git a/sdk/tests/cocos/import-contract-wasm.test.ts b/sdk/tests/cocos/import-contract-wasm.test.ts
index 6a1bf70e9..af94ba0d1 100644
--- a/sdk/tests/cocos/import-contract-wasm.test.ts
+++ b/sdk/tests/cocos/import-contract-wasm.test.ts
@@ -3,7 +3,7 @@
/**
* @file A scene as the importer writes it, loaded into the real engine with the compatibility layer.
*
- * The importer (pipeline/src/import/cocos) and the layer agree on a contract by name only: `Cocos.UITransform`, `Cocos.Widget`,
+ * The importer (pipeline/src/import/cocos) and the layer agree on a contract by name only: `ContentRect` (the engine's), `Cocos.Widget`,
* `Cocos.Button`, `Cocos.<ScriptClass>`, with a node reference as the entity id the loader maps. This is the one place that agreement
* is exercised end to end, so a rename on either side fails here and not on a user's project.
*/
@@ -66,12 +66,12 @@ describe.skipIf(!HAS_WASM)('the importer\'s scene in the compatibility layer', (
entities: [
{ id: 0, name: 'Canvas', parent: null, children: [1, 2], visible: true, components: [
transform,
- { type: 'Cocos.UITransform', data: { width: 10, height: 10, anchorX: 0.5, anchorY: 0.5 } },
+ { type: 'ContentRect', data: { size: { x: 10, y: 10 }, pivot: { x: 0.5, y: 0.5 } } },
{ type: 'Cocos.Widget', data: { enabled: true, alignFlags: 45, left: 0, right: 0, top: 0, bottom: 0, alignMode: 1 } },
] },
{ id: 1, name: 'Buy', parent: 0, children: [], visible: true, components: [
transform,
- { type: 'Cocos.UITransform', data: { width: 120, height: 48, anchorX: 0.5, anchorY: 0.5 } },
+ { type: 'ContentRect', data: { size: { x: 120, y: 48 }, pivot: { x: 0.5, y: 0.5 } } },
{ type: 'Cocos.Button', data: { enabled: true, interactable: true, transition: 3, zoomScale: 1.1, clickTargets: [2], clickHandlers: [{ component: 'Hud', handler: 'onBuy', customEventData: 'gold' }] } },
] },
{ id: 2, name: 'Hud', parent: 0, children: [], visible: true, components: [
diff --git a/sdk/tests/cocos/ui-adapters-wasm.test.ts b/sdk/tests/cocos/ui-adapters-wasm.test.ts
index 89763723a..462ac780e 100644
--- a/sdk/tests/cocos/ui-adapters-wasm.test.ts
+++ b/sdk/tests/cocos/ui-adapters-wasm.test.ts
@@ -204,7 +204,7 @@ describe.skipIf(!HAS_WASM)('built-in UI components on the engine', () => {
const s = W().get(n._entity, EngineSprite);
expect([s.size.x, s.size.y, s.pivot.x, s.pivot.y]).toEqual([120, 60, 0.5, 1]);
const x = W().get(n._entity, Text);
- expect([x.boxWidth, x.boxHeight, x.boxPivot.x, x.boxPivot.y]).toEqual([120, 60, 0.5, 1]);
+ expect([x.boxWidth, x.boxHeight, x.boxPivot?.x, x.boxPivot?.y]).toEqual([120, 60, 0.5, 1]);
});
it('tests a world point against its rectangle, anchor and position applied', () => {
diff --git a/sdk/tests/content-rect-wasm.test.ts b/sdk/tests/content-rect-wasm.test.ts
new file mode 100644
index 000000000..a031ffe66
--- /dev/null
+++ b/sdk/tests/content-rect-wasm.test.ts
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ContentRect: the one rectangle world content occupies, and the sprites and texts that follow it.
+ */
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import type { ESEngineModule } from '../src/wasm';
+import { App, flushPendingRegistrations } from '../src/app/app';
+import { Sprite, Transform, ensureBuiltinComponentsRegistered } from '../src/ecs/component';
+import { AppContext, setDefaultContext } from '../src/ecs/context';
+import { Text } from '../src/ui/core/text';
+import { ContentRect, applyContentRect, contentRectContains, localPointInRect } from '../src/ui/core/content-rect';
+import { contentRectPlugin } from '../src/ui/render/content-rect';
+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+
+describe('localPointInRect', () => {
+ const rect = { size: { x: 20, y: 30 }, pivot: { x: 0.25, y: 0.5 } };
+
+ it('spans from minus the pivot times the size to the far side', () => {
+ // x in [-5, 15], y in [-15, 15]
+ expect(localPointInRect(rect, -5, -15)).toBe(true);
+ expect(localPointInRect(rect, 15, 15)).toBe(true);
+ expect(localPointInRect(rect, -5.01, 0)).toBe(false);
+ expect(localPointInRect(rect, 15.01, 0)).toBe(false);
+ expect(localPointInRect(rect, 0, 15.01)).toBe(false);
+ expect(localPointInRect(rect, 0, -15.01)).toBe(false);
+ });
+});
+
+describe.skipIf(!HAS_WASM)('ContentRect on the engine', () => {
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let app: App | undefined;
+
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+ afterEach(() => {
+ app?.world.disconnectCpp();
+ registry?.delete();
+ app = undefined;
+ registry = undefined;
+ });
+
+ function boot(): App {
+ setDefaultContext(new AppContext());
+ ensureBuiltinComponentsRegistered();
+ registry = new module.Registry();
+ app = App.new();
+ app.connectCpp(registry as never, module);
+ app.addPlugin(contentRectPlugin);
+ flushPendingRegistrations(app);
+ return app;
+ }
+
+ it('makes the sprite and text on its entity follow it, and writes nothing when they already do', () => {
+ const { world } = boot();
+ const e = world.spawn('node');
+ world.insert(e, Transform);
+ world.insert(e, ContentRect, { size: { x: 120, y: 60 }, pivot: { x: 0, y: 1 } });
+ world.insert(e, Sprite, {});
+ world.insert(e, Text, {});
+ applyContentRect(world, e);
+ const s = world.get(e, Sprite);
+ expect([s.size.x, s.size.y, s.pivot.x, s.pivot.y]).toEqual([120, 60, 0, 1]);
+ const t = world.get(e, Text);
+ expect([t.boxWidth, t.boxHeight, t.boxPivot?.x, t.boxPivot?.y]).toEqual([120, 60, 0, 1]);
+ // a second apply changes nothing (and does not need to touch the sprite)
+ applyContentRect(world, e);
+ expect(world.get(e, Sprite).size.x).toBe(120);
+ });
+
+ it('does nothing for an entity without a rect', () => {
+ const { world } = boot();
+ const e = world.spawn('plain');
+ world.insert(e, Sprite, { size: { x: 7, y: 8 } });
+ applyContentRect(world, e);
+ expect(world.get(e, Sprite).size.x).toBe(7);
+ });
+
+ it('follows a change to the rectangle by itself, a frame later at most', async () => {
+ const a = boot();
+ const e = a.world.spawn('node');
+ a.world.insert(e, Transform);
+ a.world.insert(e, Sprite, {});
+ a.world.insert(e, ContentRect, { size: { x: 50, y: 50 }, pivot: { x: 0.5, y: 0.5 } });
+ await a.tick(1 / 60);
+ expect(a.world.get(e, Sprite).size.x).toBe(50);
+ a.world.set(e, ContentRect, { size: { x: 90, y: 40 }, pivot: { x: 0.5, y: 0.5 } });
+ await a.tick(1 / 60);
+ const s = a.world.get(e, Sprite);
+ expect([s.size.x, s.size.y]).toEqual([90, 40]);
+ });
+
+ describe('contentRectContains', () => {
+ function placed(pos: { x: number; y: number }, scale = 1, angle = 0) {
+ const { world } = boot();
+ const e = world.spawn('node');
+ world.insert(e, Transform, {
+ position: { x: pos.x, y: pos.y, z: 0 },
+ scale: { x: scale, y: scale, z: 1 },
+ rotation: { x: 0, y: 0, z: Math.sin(angle / 2), w: Math.cos(angle / 2) },
+ });
+ world.insert(e, ContentRect, { size: { x: 40, y: 20 }, pivot: { x: 0.5, y: 0.5 } });
+ return { world, e };
+ }
+
+ it('tests a world point against the rectangle where the entity stands', () => {
+ const { world, e } = placed({ x: 100, y: 50 });
+ expect(contentRectContains(world, e, 100, 50)).toBe(true);
+ expect(contentRectContains(world, e, 119.9, 59.9)).toBe(true);
+ expect(contentRectContains(world, e, 120.1, 50)).toBe(false);
+ expect(contentRectContains(world, e, 100, 60.1)).toBe(false);
+ });
+
+ it('scales with the entity', () => {
+ const { world, e } = placed({ x: 0, y: 0 }, 2);
+ expect(contentRectContains(world, e, 39, 19)).toBe(true);
+ expect(contentRectContains(world, e, 41, 0)).toBe(false);
+ });
+
+ it('turns with the entity', () => {
+ const { world, e } = placed({ x: 0, y: 0 }, 1, Math.PI / 2); // the 40 x 20 box now stands 20 wide and 40 tall
+ expect(contentRectContains(world, e, 0, 19)).toBe(true);
+ expect(contentRectContains(world, e, 19, 0)).toBe(false);
+ });
+
+ it('is false for an entity without a rectangle', () => {
+ const { world } = boot();
+ const e = world.spawn('bare');
+ world.insert(e, Transform);
+ expect(contentRectContains(world, e, 0, 0)).toBe(false);
+ });
+ });
+});
diff --git a/src/esengine/aot/AotComponents.generated.cpp b/src/esengine/aot/AotComponents.generated.cpp
index 21d84ad74..10cc4e925 100644
--- a/src/esengine/aot/AotComponents.generated.cpp
+++ b/src/esengine/aot/AotComponents.generated.cpp
@@ -15,6 +15,7 @@
#include "esengine/ecs/components/Camera.hpp"
#include "esengine/ecs/components/Canvas.hpp"
#include "esengine/ecs/components/Hierarchy.hpp"
+#include "esengine/ecs/components/ContentRect.hpp"
#include "esengine/ecs/components/Draggable.hpp"
#include "esengine/ecs/components/DragonBonesAnimation.hpp"
#include "esengine/ecs/components/FlexContainer.hpp"
@@ -116,6 +117,11 @@ ComponentAt engineComponentAt(ecs::Registry& registry, const char* name) {
return registry.tryGet<esengine::ecs::CircleCollider2D>(Entity::fromRaw(raw));
};
}
+ if (std::strcmp(name, "ContentRect") == 0) {
+ return [&registry](std::uint32_t raw) -> void* {
+ return registry.tryGet<esengine::ecs::ContentRect>(Entity::fromRaw(raw));
+ };
+ }
if (std::strcmp(name, "ConvexCollider3D") == 0) {
return [&registry](std::uint32_t raw) -> void* {
return registry.tryGet<esengine::ecs::ConvexCollider3D>(Entity::fromRaw(raw));
@@ -375,6 +381,11 @@ CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name
return denseAsIds(registry.entitiesWith<esengine::ecs::CircleCollider2D>());
};
}
+ if (std::strcmp(name, "ContentRect") == 0) {
+ return [&registry]() -> Candidates {
+ return denseAsIds(registry.entitiesWith<esengine::ecs::ContentRect>());
+ };
+ }
if (std::strcmp(name, "ConvexCollider3D") == 0) {
return [&registry]() -> Candidates {
return denseAsIds(registry.entitiesWith<esengine::ecs::ConvexCollider3D>());
@@ -594,6 +605,7 @@ bool isEngineComponent(const char* name) {
if (std::strcmp(name, "CharacterController3D") == 0) return true;
if (std::strcmp(name, "Children") == 0) return true;
if (std::strcmp(name, "CircleCollider2D") == 0) return true;
+ if (std::strcmp(name, "ContentRect") == 0) return true;
if (std::strcmp(name, "ConvexCollider3D") == 0) return true;
if (std::strcmp(name, "Draggable") == 0) return true;
if (std::strcmp(name, "DragonBonesAnimation") == 0) return true;
diff --git a/src/esengine/aot/EngineDigest.generated.h b/src/esengine/aot/EngineDigest.generated.h
index 7bcd28dfb..dc76fa293 100644
--- a/src/esengine/aot/EngineDigest.generated.h
+++ b/src/esengine/aot/EngineDigest.generated.h
@@ -6,7 +6,7 @@
/* One per address width, because the width is IN the digest: a host that
took the other one would refuse every module built for it. */
-#define ES_ENGINE_ABI_DIGEST_32 0x2a2acef3f0ef9d3aULL
-#define ES_ENGINE_ABI_DIGEST_64 0xc74e6f71a7edb276ULL
+#define ES_ENGINE_ABI_DIGEST_32 0xce4ca38c1ff13f6aULL
+#define ES_ENGINE_ABI_DIGEST_64 0x454cb3975a040836ULL
#define ES_ENGINE_ABI_DIGEST \
(sizeof(es_addr_t) == 8 ? ES_ENGINE_ABI_DIGEST_64 : ES_ENGINE_ABI_DIGEST_32)
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index a714d38f2..ca0b83244 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 4f0846b4dd77f7d5
+ * @schema_hash 8522a64ede6f4d50
*/
-#define ES_EDITOR_API_SCHEMA_HASH "4f0846b4dd77f7d5"
+#define ES_EDITOR_API_SCHEMA_HASH "8522a64ede6f4d50"
#include <emscripten/bind.h>
#include <string>
@@ -17,6 +17,7 @@
#include "../ecs/components/Camera.hpp"
#include "../ecs/components/Canvas.hpp"
#include "../ecs/components/Collider2D.hpp"
+#include "../ecs/components/ContentRect.hpp"
#include "../ecs/components/Draggable.hpp"
#include "../ecs/components/DragonBonesAnimation.hpp"
#include "../ecs/components/FlexContainer.hpp"
@@ -78,6 +79,7 @@ std::vector<std::string> editor_getComponentNames() {
"CharacterController3D",
"Children",
"CircleCollider2D",
+ "ContentRect",
"ConvexCollider3D",
"Draggable",
"DragonBonesAnimation",
@@ -259,6 +261,13 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"categoryBits","type":"int","group":"CircleCollider2D"},
{"key":"maskBits","type":"int","group":"CircleCollider2D"}
])JSON";
+ } else if (name == "ContentRect") {
+ return R"JSON([
+ {"key":"size.x","type":"float","group":"ContentRect"},
+ {"key":"size.y","type":"float","group":"ContentRect"},
+ {"key":"pivot.x","type":"float","group":"ContentRect"},
+ {"key":"pivot.y","type":"float","group":"ContentRect"}
+ ])JSON";
} else if (name == "ConvexCollider3D") {
return R"JSON([
{"key":"mesh","type":"asset","group":"ConvexCollider3D"},
@@ -899,6 +908,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "CircleCollider2D") {
if (!reg.has<esengine::ecs::CircleCollider2D>(entity)) reg.emplace<esengine::ecs::CircleCollider2D>(entity);
return true;
+ } else if (name == "ContentRect") {
+ if (!reg.has<esengine::ecs::ContentRect>(entity)) reg.emplace<esengine::ecs::ContentRect>(entity);
+ return true;
} else if (name == "ConvexCollider3D") {
if (!reg.has<esengine::ecs::ConvexCollider3D>(entity)) reg.emplace<esengine::ecs::ConvexCollider3D>(entity);
return true;
@@ -1052,6 +1064,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
}
} else if (name == "CircleCollider2D") {
if (reg.has<esengine::ecs::CircleCollider2D>(entity)) { reg.remove<esengine::ecs::CircleCollider2D>(entity); return true; }
+ } else if (name == "ContentRect") {
+ if (reg.has<esengine::ecs::ContentRect>(entity)) { reg.remove<esengine::ecs::ContentRect>(entity); return true; }
} else if (name == "ConvexCollider3D") {
if (reg.has<esengine::ecs::ConvexCollider3D>(entity)) { reg.remove<esengine::ecs::ConvexCollider3D>(entity); return true; }
} else if (name == "Draggable") {
@@ -1151,6 +1165,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "CharacterController3D") return reg.has<esengine::ecs::CharacterController3D>(entity);
if (name == "Children") return reg.has<esengine::ecs::Children>(entity);
if (name == "CircleCollider2D") return reg.has<esengine::ecs::CircleCollider2D>(entity);
+ if (name == "ContentRect") return reg.has<esengine::ecs::ContentRect>(entity);
if (name == "ConvexCollider3D") return reg.has<esengine::ecs::ConvexCollider3D>(entity);
if (name == "Draggable") return reg.has<esengine::ecs::Draggable>(entity);
if (name == "DragonBonesAnimation") return reg.has<esengine::ecs::DragonBonesAnimation>(entity);
@@ -1211,6 +1226,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::CharacterController3D>(entity)) result.push_back("CharacterController3D");
if (reg.has<esengine::ecs::Children>(entity)) result.push_back("Children");
if (reg.has<esengine::ecs::CircleCollider2D>(entity)) result.push_back("CircleCollider2D");
+ if (reg.has<esengine::ecs::ContentRect>(entity)) result.push_back("ContentRect");
if (reg.has<esengine::ecs::ConvexCollider3D>(entity)) result.push_back("ConvexCollider3D");
if (reg.has<esengine::ecs::Draggable>(entity)) result.push_back("Draggable");
if (reg.has<esengine::ecs::DragonBonesAnimation>(entity)) result.push_back("DragonBonesAnimation");
@@ -1373,6 +1389,15 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "restitution") { c.restitution = value; }
else { return false; }
return true;
+ } else if (comp == "ContentRect") {
+ if (!reg.has<esengine::ecs::ContentRect>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::ContentRect>(entity);
+ if (field == "size.x") { c.size.x = value; }
+ else if (field == "size.y") { c.size.y = value; }
+ else if (field == "pivot.x") { c.pivot.x = value; }
+ else if (field == "pivot.y") { c.pivot.y = value; }
+ else { return false; }
+ return true;
} else if (comp == "ConvexCollider3D") {
if (!reg.has<esengine::ecs::ConvexCollider3D>(entity)) return false;
auto& c = reg.get<esengine::ecs::ConvexCollider3D>(entity);
@@ -1955,6 +1980,13 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "density") { return c.density; }
else if (field == "friction") { return c.friction; }
else if (field == "restitution") { return c.restitution; }
+ } else if (comp == "ContentRect") {
+ if (!reg.has<esengine::ecs::ContentRect>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::ContentRect>(entity);
+ if (field == "size.x") { return c.size.x; }
+ else if (field == "size.y") { return c.size.y; }
+ else if (field == "pivot.x") { return c.pivot.x; }
+ else if (field == "pivot.y") { return c.pivot.y; }
} else if (comp == "ConvexCollider3D") {
if (!reg.has<esengine::ecs::ConvexCollider3D>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::ConvexCollider3D>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index e363d646f..2d20534b7 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -17,6 +17,7 @@
#include "../ecs/components/Camera.hpp"
#include "../ecs/components/Canvas.hpp"
#include "../ecs/components/Collider2D.hpp"
+#include "../ecs/components/ContentRect.hpp"
#include "../ecs/components/Draggable.hpp"
#include "../ecs/components/DragonBonesAnimation.hpp"
#include "../ecs/components/FlexContainer.hpp"
@@ -1903,6 +1904,10 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("categoryBits", &esengine::ecs::CircleCollider2D::categoryBits)
.field("maskBits", &esengine::ecs::CircleCollider2D::maskBits);
+ value_object<esengine::ecs::ContentRect>("ContentRect")
+ .field("size", &esengine::ecs::ContentRect::size)
+ .field("pivot", &esengine::ecs::ContentRect::pivot);
+
value_object<ConvexCollider3DJS>("ConvexCollider3D")
.field("mesh", &ConvexCollider3DJS::mesh)
.field("friction", &ConvexCollider3DJS::friction)
@@ -2397,6 +2402,7 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
if (r.has<esengine::ecs::CharacterController3D>(entity)) { if (!names.empty()) names += "|"; names += "CharacterController3D"; }
if (r.has<esengine::ecs::Children>(entity)) { if (!names.empty()) names += "|"; names += "Children"; }
if (r.has<esengine::ecs::CircleCollider2D>(entity)) { if (!names.empty()) names += "|"; names += "CircleCollider2D"; }
+ if (r.has<esengine::ecs::ContentRect>(entity)) { if (!names.empty()) names += "|"; names += "ContentRect"; }
if (r.has<esengine::ecs::ConvexCollider3D>(entity)) { if (!names.empty()) names += "|"; names += "ConvexCollider3D"; }
if (r.has<esengine::ecs::Draggable>(entity)) { if (!names.empty()) names += "|"; names += "Draggable"; }
if (r.has<esengine::ecs::DragonBonesAnimation>(entity)) { if (!names.empty()) names += "|"; names += "DragonBonesAnimation"; }
@@ -2452,6 +2458,7 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
if (name == "CharacterController3D") return static_cast<int>(componentTypeId<esengine::ecs::CharacterController3D>());
if (name == "Children") return static_cast<int>(componentTypeId<esengine::ecs::Children>());
if (name == "CircleCollider2D") return static_cast<int>(componentTypeId<esengine::ecs::CircleCollider2D>());
+ if (name == "ContentRect") return static_cast<int>(componentTypeId<esengine::ecs::ContentRect>());
if (name == "ConvexCollider3D") return static_cast<int>(componentTypeId<esengine::ecs::ConvexCollider3D>());
if (name == "Draggable") return static_cast<int>(componentTypeId<esengine::ecs::Draggable>());
if (name == "DragonBonesAnimation") return static_cast<int>(componentTypeId<esengine::ecs::DragonBonesAnimation>());
@@ -2719,6 +2726,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::CircleCollider2D>(entity);
}))
+ // ContentRect
+ .function("hasContentRect", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::ContentRect>(static_cast<Entity>(e));
+ }))
+ .function("getContentRect", optional_override([](Registry& r, u32 e) -> esengine::ecs::ContentRect& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::ContentRect s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::ContentRect>(entity)) return s_dummy;
+ return r.get<esengine::ecs::ContentRect>(entity);
+ }), allow_raw_pointers())
+ .function("addContentRect", optional_override([](Registry& r, u32 e, const esengine::ecs::ContentRect& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::ContentRect>(entity, c);
+ }))
+ .function("removeContentRect", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::ContentRect>(entity)) return;
+ r.remove<esengine::ecs::ContentRect>(entity);
+ }))
+
// ConvexCollider3D
.function("hasConvexCollider3D", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::ConvexCollider3D>(static_cast<Entity>(e));
@@ -3687,6 +3715,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("CharacterController3D")));
arr.set(i++, val(std::string("Children")));
arr.set(i++, val(std::string("CircleCollider2D")));
+ arr.set(i++, val(std::string("ContentRect")));
arr.set(i++, val(std::string("ConvexCollider3D")));
arr.set(i++, val(std::string("Draggable")));
arr.set(i++, val(std::string("DragonBonesAnimation")));
@@ -3821,6 +3850,8 @@ static_assert(offsetof(esengine::ecs::CircleCollider2D, isSensor) == 24, "ABI of
static_assert(offsetof(esengine::ecs::CircleCollider2D, enabled) == 25, "ABI offset drift: esengine::ecs::CircleCollider2D.enabled (EHT expected 25)");
static_assert(offsetof(esengine::ecs::CircleCollider2D, categoryBits) == 28, "ABI offset drift: esengine::ecs::CircleCollider2D.categoryBits (EHT expected 28)");
static_assert(offsetof(esengine::ecs::CircleCollider2D, maskBits) == 32, "ABI offset drift: esengine::ecs::CircleCollider2D.maskBits (EHT expected 32)");
+static_assert(offsetof(esengine::ecs::ContentRect, size) == 0, "ABI offset drift: esengine::ecs::ContentRect.size (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::ContentRect, pivot) == 8, "ABI offset drift: esengine::ecs::ContentRect.pivot (EHT expected 8)");
static_assert(offsetof(esengine::ecs::ConvexCollider3D, mesh) == 0, "ABI offset drift: esengine::ecs::ConvexCollider3D.mesh (EHT expected 0)");
static_assert(offsetof(esengine::ecs::ConvexCollider3D, friction) == 4, "ABI offset drift: esengine::ecs::ConvexCollider3D.friction (EHT expected 4)");
static_assert(offsetof(esengine::ecs::ConvexCollider3D, restitution) == 8, "ABI offset drift: esengine::ecs::ConvexCollider3D.restitution (EHT expected 8)");
@@ -4184,7 +4215,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "6c653a8ebb70b5bc";
+static const char* kEsAbiLayoutHash = "ac076564c4c51626";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/ecs/components/ContentRect.hpp b/src/esengine/ecs/components/ContentRect.hpp
new file mode 100644
index 000000000..f78f62fff
--- /dev/null
+++ b/src/esengine/ecs/components/ContentRect.hpp
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ContentRect.hpp
+ * @brief The rectangle a piece of world content occupies: a size, and the point of it the entity's transform sits on.
+ * @details A `Sprite` has a size and a pivot, a `Text` a box and a box pivot, and an entity that draws nothing — a clipping region,
+ * a scroll view's viewport, a touch area — has neither. Content laid out as nodes in the world (an imported scene, a
+ * hand-built HUD) wants ONE rectangle that all of those read: the renderer sizes its quad by it, the mask clips to it, a
+ * pointer is tested against it.
+ *
+ * It is not a layout. `UINode` is the engine's box layout (flex, insets, percentages) and does not go away: this is for
+ * content positioned by its `Transform`, where the box does not depend on its siblings. When an entity has both, the
+ * layout's computed box wins for clipping, as before.
+ *
+ * A `Sprite` or `Text` on the same entity takes its size and pivot from here instead of its own (`ContentRectPlugin`), so
+ * the rectangle is written in one place and the renderers follow it.
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+
+#include <glm/glm.hpp>
+
+namespace esengine::ecs {
+
+/**
+ * @brief The rectangle of this entity's content, in its own units.
+ */
+ES_COMPONENT(stability=experimental)
+struct ContentRect {
+ /** @brief Width and height in local units, before the transform's scale. */
+ ES_PROPERTY(min=0, tooltip="Width and height of the content in local units (before scale).")
+ glm::vec2 size{100.0f, 100.0f};
+
+ /** @brief The point of the rectangle the transform sits on, as a fraction of its size. */
+ ES_PROPERTY(normalized_of=size, tooltip="The point of the rectangle the entity sits on, as a fraction of its size (0.5,0.5 = centre). Rotation and scale turn about it.")
+ glm::vec2 pivot{0.5f, 0.5f};
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/renderer/frame/RenderFrameMask.cpp b/src/esengine/renderer/frame/RenderFrameMask.cpp
index 84683f185..7a47414a7 100644
--- a/src/esengine/renderer/frame/RenderFrameMask.cpp
+++ b/src/esengine/renderer/frame/RenderFrameMask.cpp
@@ -4,6 +4,7 @@
#include "../../core/Log.hpp"
#include "../../ecs/components/Transform.hpp"
#include "../../ecs/components/UINode.hpp"
+#include "../../ecs/components/ContentRect.hpp"
#include "../../ecs/components/UIMask.hpp"
#include "../../ecs/components/Hierarchy.hpp"
#include "../../ecs/FlatGeometry.hpp"
@@ -43,15 +44,34 @@ glm::vec2 worldToScreen(const glm::vec3& world, const glm::mat4& vp,
/// Whether the masks being laid out stand in the world (and so are taken from the render origin) or on the screen, whose units have none.
thread_local bool g_masksInWorld = false;
+/// The box a mask clips to and where it sits: a UINode's computed box centred on the transform, or, for content laid out by its
+/// transform alone, the entity's ContentRect about its pivot. A zero size means there is no box.
+struct MaskBox {
+ glm::vec2 size{0.0f, 0.0f};
+ /// The box centre's offset from the transform, in local units (0,0 for a UINode, whose box is centred).
+ glm::vec2 centerOffset{0.0f, 0.0f};
+ bool present = false;
+};
+
+MaskBox maskBoxOf(ecs::Registry& registry, Entity entity) {
+ if (const auto* node = registry.tryGet<ecs::UINode>(entity)) {
+ return {node->computed_size_, {0.0f, 0.0f}, true};
+ }
+ if (const auto* rect = registry.tryGet<ecs::ContentRect>(entity)) {
+ return {rect->size, {(0.5f - rect->pivot.x) * rect->size.x, (0.5f - rect->pivot.y) * rect->size.y}, true};
+ }
+ return {};
+}
+
ScreenRect computeMaskScreenRect(
ecs::Registry& registry, Entity entity,
const glm::mat4& vp, i32 vpX, i32 vpY, i32 vpW, i32 vpH
) {
- if (!registry.has<ecs::UINode>(entity) || !registry.has<ecs::Transform>(entity)) {
+ const MaskBox box = maskBoxOf(registry, entity);
+ if (!box.present || !registry.has<ecs::Transform>(entity)) {
return {0, 0, 0, 0};
}
- const auto& node = registry.get<ecs::UINode>(entity);
- if (node.computed_size_.x <= 0.0f || node.computed_size_.y <= 0.0f) return {0, 0, 0, 0};
+ if (box.size.x <= 0.0f || box.size.y <= 0.0f) return {0, 0, 0, 0};
auto& transform = registry.get<ecs::Transform>(entity);
// The world TRS below is decomposed on demand, so a mask whose transform no
// other pass has read this frame would be clipped to where it used to be.
@@ -68,9 +88,10 @@ ScreenRect computeMaskScreenRect(
axisX = glm::vec3(turn.x, turn.y, 0) * transform.worldScale.x;
axisY = glm::vec3(-turn.y, turn.x, 0) * transform.worldScale.y;
}
- const glm::vec3 hx = axisX * node.computed_size_.x * .5f;
- const glm::vec3 hy = axisY * node.computed_size_.y * .5f;
- const glm::vec3 center = g_masksInWorld ? rebased(transform.worldPosition) : glm::vec3(transform.worldPosition);
+ const glm::vec3 hx = axisX * box.size.x * .5f;
+ const glm::vec3 hy = axisY * box.size.y * .5f;
+ const glm::vec3 origin = g_masksInWorld ? rebased(transform.worldPosition) : glm::vec3(transform.worldPosition);
+ const glm::vec3 center = origin + axisX * box.centerOffset.x + axisY * box.centerOffset.y;
const glm::vec3 corners[] = {center - hx - hy, center + hx - hy,
center + hx + hy, center - hx + hy};
@@ -160,10 +181,10 @@ void applyScissorToDescendants(
static constexpr i32 MAX_STENCIL_REF = 255;
bool hasEmptyMaskBox(ecs::Registry& registry, Entity entity) {
- const auto* node = registry.tryGet<ecs::UINode>(entity);
+ const MaskBox box = maskBoxOf(registry, entity);
auto* transform = registry.tryGet<ecs::Transform>(entity);
- if (!node || !transform) return false;
- if (node->computed_size_.x <= 0.0f || node->computed_size_.y <= 0.0f) return true;
+ if (!box.present || !transform) return false;
+ if (box.size.x <= 0.0f || box.size.y <= 0.0f) return true;
transform->ensureDecomposed();
return transform->worldScale.x == 0 || transform->worldScale.y == 0
|| !ecs::hasFlatGeometryArea(registry, entity, *transform);
diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.h
index e9152eced..e507eee66 100644
--- a/tests/aot/generated/conformance/handshake.h
+++ b/tests/aot/generated/conformance/handshake.h
@@ -1,5 +1,5 @@
/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_CONF_EXPECTED_CONTRACT_HASH 0xc74e6f71a7edb276ULL
+#define ES_CONF_EXPECTED_CONTRACT_HASH 0x454cb3975a040836ULL
/* And which BUILD the artifact beside this one is. */
#define ES_CONF_EXPECTED_MODULE_CONTRACT 0xc3d0e057d5701a2eULL
diff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.c
index b4c73706b..77c700bf2 100644
--- a/tests/aot/generated/conformance/systems_decl.c
+++ b/tests/aot/generated/conformance/systems_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0xc74e6f71a7edb276ULL
+#define ES_ABI_ENGINE_DIGEST 0x454cb3975a040836ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/aot/generated/move_system_decl.c b/tests/aot/generated/move_system_decl.c
index 62af2fc5e..d807336f7 100644
--- a/tests/aot/generated/move_system_decl.c
+++ b/tests/aot/generated/move_system_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0xc74e6f71a7edb276ULL
+#define ES_ABI_ENGINE_DIGEST 0x454cb3975a040836ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/aot/generated/move_system_hash.h b/tests/aot/generated/move_system_hash.h
index dc8b32bf0..007e2eed1 100644
--- a/tests/aot/generated/move_system_hash.h
+++ b/tests/aot/generated/move_system_hash.h
@@ -1,6 +1,6 @@
/* GENERATED by @estella/compiler — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_EXPECTED_CONTRACT_HASH 0xc74e6f71a7edb276ULL
+#define ES_EXPECTED_CONTRACT_HASH 0x454cb3975a040836ULL
/* And which BUILD the artifact beside this one is, which the sidecar
written with it has to carry too. */
#define ES_EXPECTED_MODULE_CONTRACT 0x10bf77bb714ea1e3ULL
diff --git a/tests/renderer/test_batch_builder.cpp b/tests/renderer/test_batch_builder.cpp
index fc5449df6..1eddf0031 100644
--- a/tests/renderer/test_batch_builder.cpp
+++ b/tests/renderer/test_batch_builder.cpp
@@ -28,6 +28,7 @@
#include "esengine/ecs/components/UINode.hpp"
#include "esengine/ecs/components/UIVisual.hpp"
#include "esengine/ecs/components/UIMask.hpp"
+#include "esengine/ecs/components/ContentRect.hpp"
#include "esengine/ecs/components/Interactable.hpp"
#include "esengine/ui/UISystem.hpp"
#include "esengine/ecs/FlatGeometry.hpp"
@@ -824,6 +825,46 @@ TEST_CASE("UI scissor: affine corners determine the projected clip rectangle") {
frame.endFrame();
}
+TEST_CASE("UI scissor: a ContentRect gives world content a clip box, about its pivot") {
+ struct Case { glm::vec2 pivot; std::array<i32, 4> expected; };
+ // The entity stands at the world origin, which the orthographic view puts at pixel (100, 100). A 20 x 30 rectangle hangs from its
+ // pivot: pivot (0,0) reaches right and up from the origin; pivot (0.5,0.5) is centred on it; pivot (1,1) reaches left and down.
+ const Case cases[] = {
+ {{0.0f, 0.0f}, {100, 100, 20, 30}},
+ {{0.5f, 0.5f}, {90, 85, 20, 30}},
+ {{1.0f, 1.0f}, {80, 70, 20, 30}},
+ };
+ for (const auto& c : cases) {
+ MockGfxDevice device;
+ RenderContext context(device);
+ resource::ResourceManager resources;
+ ecs::Registry registry;
+ RenderFrame frame(device, context, resources);
+ frame.init(200, 200);
+ const auto mask = registry.create(), child = registry.create();
+ registry.emplace<ecs::Children>(mask).entities.push_back(child);
+ registry.emplace<ecs::Parent>(child).entity = mask;
+ registry.emplace<ecs::Transform>(mask);
+ auto& rect = registry.emplace<ecs::ContentRect>(mask);
+ rect.size = {20, 30};
+ rect.pivot = c.pivot;
+ registry.emplace<ecs::UIMask>(mask).mode = ecs::MaskMode::Scissor;
+ const f32 vertices[36] = {};
+ const u16 indices[] = {0, 1, 2, 2, 3, 0};
+ const glm::mat4 identity(1);
+ frame.beginFrame();
+ frame.begin(glm::ortho(-100.0f, 100.0f, -100.0f, 100.0f));
+ frame.processMasks(registry, 0, 0, 200, 200);
+ frame.collectAll(registry);
+ frame.submitTextBatch(vertices, 4, indices, 6, 1, &identity[0][0], child, 0, 0, TextGlyphMode::Color);
+ frame.flush();
+ frame.end();
+ CHECK(std::find(device.scissorRectangles.begin(), device.scissorRectangles.end(), c.expected)
+ != device.scissorRectangles.end());
+ frame.endFrame();
+ }
+}
+
TEST_CASE("flat geometry: collapsed parent bases skip uploads and recover") {
for (bool ui : {false, true}) {
for (u32 mode = 0; mode < (ui ? 5u : 3u); ++mode) {
diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjs
index 7f7005142..6ae4c2959 100644
--- a/tools/apiSubsystems.mjs
+++ b/tools/apiSubsystems.mjs
@@ -26,6 +26,7 @@
* subsystem cannot be mistaken for adding plumbing.
*/
export const INFRASTRUCTURE = {
+ cocos: 'the Cocos Creator compatibility layer (`esengine/cocos`): scripts written for Cocos run on it; a game built for this engine does not import it',
'debug-channel': 'a development build\'s line back to the editor — tooling, never in a shipped game',
diagnostics: 'the engine reporting on itself — a census and a stats overlay, read by tooling',
document: 'document-model diagnostics shared with the editor, not part of a game',
diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.js
index da25b4184..9090caf15 100644
--- a/tools/nativeScriptModules.js
+++ b/tools/nativeScriptModules.js
@@ -97,6 +97,10 @@ export const MODULES = {
disposition: 'forbidden-native-script',
why: 'the Node entry, for servers and tools (examples/multiplayer-arena/server) — it reaches for node: builtins a packaged game has none of',
},
+ 'esengine/cocos': {
+ disposition: 'forbidden-native-script',
+ why: 'the Cocos Creator compatibility layer, built for the web and mini-game bundles; a native build does not carry it yet',
+ },
'esengine/wechat': {
disposition: 'forbidden-native-script',
why: 'the WeChat mini-game entry, a different host with a different platform adapter',
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 0d57be24f..b08e5d19c 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,30 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(text): the engine\'s rich-text parser reads Cocos\'s tags (size, color names, br; underline/outline/click kept as plain text); Cocos Camera and RichText are views on the engine\'s Camera and Text; a touch has a screen point (getLocation) and a canvas point (getUILocation)':
+ {"note":"Rich text reads the tags other engines write."},
+ 'feat(animation): sine, quart, quint, expo, circ, bounce in/in-out, smoothstep and smootherstep easing curves in the engine (C++ and TypeScript, parity-tested); the Cocos tween\'s easing names map onto the engine\'s curves instead of carrying their own':
+ {"note":"More easing curves."},
+ 'feat(ui): scroll areas can be pulled past an end and spring back (ScrollContainer overscroll, ScrollMotion for the gesture); ScrollMovement.Elastic now does what its comment said. The Cocos ScrollView drives the engine\'s scroll model instead of carrying its own':
+ {"note":"Scroll areas can be pulled past an end and spring back."},
+ 'feat(cocos): Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents and ScrollView, Vec4 and Mat4, a capture phase for touches; the drag/inertia/elastic physics is an engine module (ui/collection/scroll-physics) the compatibility layer adapts':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
+ 'feat(cocos): sys, view/screen, macro, Layers, game, the global input with KeyCode and keyboard/mouse/touch events, and resources/assetManager/Bundle over a manifest the importer writes for resources and bundle folders':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
+ 'feat(cocos): instantiate (prepared prefab or node copy, held out of the scene until parented) and tween (to/by/set/delay/call/then/union/sequence/parallel/repeat, easing, Tween.stopAll*); the importer numbers scene entities from 1 so a reference to the first one is not read as none':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
+ 'feat(cocos): esengine/cocos as a published subpath, cc and cc/env resolved to it in every script bundle with legacy decorators, and an entry the importer writes that brings the Cocos scripts into the bundle':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
+ 'feat(cocos-import): emit the compatibility layer\'s components — UITransform, Widget, Layout, Button and the project\'s own scripts as Cocos.<Class>, with node references resolved to the entities those nodes became':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
+ 'feat(cocos): Widget and Layout — edge/centre/stretch alignment against the parent or the visible area, and row, column and grid layouts with Cocos\'s arithmetic, run in an end-of-frame pass':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
+ 'feat(cocos): UI component adapters, touch events on nodes, and Button — Label/Sprite/UIOpacity/UITransform as views on the engine\'s components, the topmost listener claiming a touch and bubbling it up, clicks that end inside':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
+ 'feat(cocos): the cc compatibility core — Node as a handle on an entity, Component with Cocos\'s lifecycle on the engine\'s frame loop, @ccclass/@property as Estella components, and the value types':
+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},
+
+
'feat(openpaas): build and verify native SUD test packages': { note: 'SUD OpenPaaS development export.' },
'fix(openpaas): align directory manifest with official web2sp': { note: 'SUD OpenPaaS development export.' },
'feat(openpaas): integrate SUD runtime and PinK directory export': { note: 'SUD OpenPaaS development export.' },