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): RectAnchors pins world content to its parent rectangle or the screen in the engine, and the Cocos Widget is a view on it

yhh9b67bcf802ef
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f2a912924..1d91ddcae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ published separately; it ships inside the editor.
- **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.
+- **RectAnchors: world content that follows its parent.** A new engine component pins content placed by its `Transform` and sized by a `ContentRect` to the edges or centre of its parent rectangle (stretch, pin to an edge, centre with an offset, margins in units or as a fraction), or, with no parent rectangle, to the screen, which is centred on the world origin. An engine system aligns parents before the children that depend on them, in the editor edit mode as well as in play, on ONCE / ON_RESIZE / ALWAYS. The Cocos `Widget` is now a view on it, and a converted project carries `RectAnchors` instead of a compatibility-layer component, so a scene is laid out where the editor shows it. The visible area of the Cocos layer is centred on the origin, as the engine screen is.
- **A converted Cocos project fits the screen as the game does.** The Cocos design fit (fit width, fit height) becomes the project camera scale mode (fixed width, fixed height), so a UI laid out in design units comes out the same size on every screen instead of being drawn at the window pixel size. `cc.profiler` (`showStats`, `hideStats`) is accepted by the compatibility layer.
- **A Cocos node layer is its renderers layer.** The sprites, texts, shapes, spine, particles and meshes of a converted node are put in the layer the node had in Cocos (its bit index), which is what a camera culling mask selects among. A UI camera that draws only layer 25 used to draw none of the sprites left in layer 0, so the converted game launch scene was black.
- **A converted Cocos project starts as the game does.** The project opens at the Cocos launch scene (not the starter empty scene) and its design size, scripts that only define globals (the game configuration) run before the ones scenes name, and the editor built-in assets a scene names by uuid (the default progress bar images) are read from the Creator install, which took the missing sprite frames of the client from 385 to 15.
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.ts
index fe051489a..09e1e5162 100644
--- a/pipeline/src/import/cocos/components.ts
+++ b/pipeline/src/import/cocos/components.ts
@@ -359,9 +359,11 @@ function widget(c: CocosComponent): ComponentData {
_horizontalCenter: 'horizontalCenter', _verticalCenter: 'verticalCenter',
_isAbsLeft: 'isAbsLeft', _isAbsRight: 'isAbsRight', _isAbsTop: 'isAbsTop', _isAbsBottom: 'isAbsBottom',
_isAbsHorizontalCenter: 'isAbsHorizontalCenter', _isAbsVerticalCenter: 'isAbsVerticalCenter',
- _alignMode: 'alignMode', _target: 'target',
+ _alignMode: 'alignMode',
});
- return { type: `${LAYER}Widget`, data };
+ // The engine's own component: the same fields, aligned by the engine in the editor as well as in play. A widget that targets a node other
+ // than its parent has nothing to say that in; its fields come across and it aligns to the parent.
+ return { type: 'RectAnchors', data };
}
function layout(c: CocosComponent): ComponentData {
@@ -868,6 +870,7 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strin
break;
case 'cc.Widget':
out = widget(c);
+ ctx.report.component('cc.Widget', 'mapped');
break;
case 'cc.Layout':
out = layout(c);
diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.ts
index 25b1998c2..376b5801c 100644
--- a/pipeline/tests/cocos-import-layer.test.ts
+++ b/pipeline/tests/cocos-import-layer.test.ts
@@ -108,7 +108,7 @@ describe('importing for the compatibility layer', () => {
});
it('carries a widget\'s and a layout\'s settings under the names the layer uses', () => {
- const w = comp('Canvas', 'Cocos.Widget').data;
+ const w = comp('Canvas', 'RectAnchors').data;
expect([w.alignFlags, w.left, w.right, w.top, w.bottom, w.alignMode, w.enabled]).toEqual([45, 10, 10, 5, 5, 2, true]);
const l = comp('Hud', 'Cocos.Layout').data;
expect([l.type, l.resizeMode, l.spacingY, l.paddingTop, l.cellWidth, l.cellHeight, l.verticalDirection]).toEqual([2, 1, 8, 4, 50, 60, 1]);
diff --git a/sdk/src/cocos/ui/pass.ts b/sdk/src/cocos/ui/pass.ts
index a77d6f93b..111a6db91 100644
--- a/sdk/src/cocos/ui/pass.ts
+++ b/sdk/src/cocos/ui/pass.ts
@@ -11,18 +11,27 @@
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 { ScreenLayout, type ScreenLayoutData } from '../../ui/core/screen-layout';
import { setCurrentWorld } from '../node';
-import { alignAllWidgets, declareWidget } from './widget';
+import { declareWidget } from './widget';
+import { alignAllRectAnchors } from '../../ui/layout/rect-anchors';
import { layoutAll, declareLayout } from './layout';
import { declareControls } from './controls';
import { declareGraphics } from './graphics';
import { declareEditBox } from './editBox';
import { declareScrollView } from './scrollView';
-import { setSafeInsets, setUiCameraData, setVisibleSize, setWindowPixels } from './screen';
+import { getVisibleSize, setSafeInsets, setScreenLayout, setUiCameraData, setVisibleSize, setWindowPixels, visibleSizeGeneration } from './screen';
import { declarePages } from './pages';
import { declareMisc } from './misc';
+/** The screen the pass aligns to: the engine's, or — where there is none yet (a test, a host before its first frame) — the visible size it was told. */
+function screenOrVisible(screen: ScreenLayoutData | undefined): ScreenLayoutData {
+ if (screen?.valid) return screen;
+ const v = getVisibleSize();
+ const halfW = v.width / 2, halfH = v.height / 2;
+ return { valid: true, left: -halfW, right: halfW, bottom: -halfH, top: halfH, safeLeft: -halfW, safeRight: halfW, safeBottom: -halfH, safeTop: halfH, scale: 1, viewportW: v.width, viewportH: v.height };
+}
+
export function declareUiPass(): void {
declareWidget();
declareLayout();
@@ -38,6 +47,8 @@ export function declareUiPass(): void {
// 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);
+ const layout = screenOrVisible(screen);
+ setScreenLayout(layout);
if (screen?.valid) {
setVisibleSize(screen.right - screen.left, screen.top - screen.bottom);
setWindowPixels(screen.viewportW, screen.viewportH);
@@ -47,9 +58,10 @@ export function declareUiPass(): void {
}
const previous = setCurrentWorld(world);
try {
- alignAllWidgets(world);
+ // The engine's anchors, between the layouts that depend on them: a Layout resizes what a widget then pins to.
+ alignAllRectAnchors(world, layout, visibleSizeGeneration());
layoutAll(world);
- alignAllWidgets(world);
+ alignAllRectAnchors(world, layout, visibleSizeGeneration());
} finally {
setCurrentWorld(previous);
}
diff --git a/sdk/src/cocos/ui/screen.ts b/sdk/src/cocos/ui/screen.ts
index 2a7fd3546..79c61e4ae 100644
--- a/sdk/src/cocos/ui/screen.ts
+++ b/sdk/src/cocos/ui/screen.ts
@@ -5,12 +5,13 @@
* @brief The rectangle a root UI node aligns to (Cocos's "visible rect"), and the window it sits in.
*
* A widget on a node whose parent has no rectangle of its own (the canvas, or anything straight under the scene) aligns to the
- * visible area of the screen. In an imported scene the engine's world and Cocos's are one space, with the visible area running from
- * the origin to its size, so the rectangle is just a width and a height. The frame loop sets it from the UI camera every frame
+ * visible area of the screen, which in the engine is centred on the world origin, so the rectangle is a width and a height about it. The frame loop sets it from the UI camera every frame
* (see pass.ts); until it does, it is the size of a typical design resolution so a scene still lays out.
*/
import type { UICameraData } from '../../ui/core/ui-camera-info';
+import type { ScreenLayoutData } from '../../ui/core/screen-layout';
+import type { World } from '../../ecs/world';
let uiCamera: UICameraData | null = null;
let width = 960;
@@ -24,6 +25,12 @@ let windowW = 960;
let windowH = 640;
const listeners: Array<(kind: 'visible' | 'window') => void> = [];
+let screenLayout: ScreenLayoutData | null = null;
+/** @internal The layout the pass last saw, for an alignment a script asks for now. */
+export function setScreenLayout(layout: ScreenLayoutData | null): void { screenLayout = layout; }
+/** @internal */
+export function getScreenLayoutOf(_world: World): ScreenLayoutData | null { return screenLayout; }
+
/** The visible area's size, in the canvas units scripts see. */
export function getVisibleSize(): { width: number; height: number } { return { width, height }; }
diff --git a/sdk/src/cocos/ui/widget.ts b/sdk/src/cocos/ui/widget.ts
index e2ffd3c55..919e5836d 100644
--- a/sdk/src/cocos/ui/widget.ts
+++ b/sdk/src/cocos/ui/widget.ts
@@ -2,78 +2,99 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file cocos/ui/widget.ts
- * @brief `Widget`: a node pinned to the edges (or centre) of its parent's rectangle.
+ * @brief `Widget`: a view on the engine's `RectAnchors`.
*
- * The arithmetic is Cocos's own, so a panel lands where it landed there: each axis is either stretched (both edges set — the size
- * follows the parent), pinned to one edge, or centred with an offset, with margins in pixels or as a fraction of the parent. A node
- * whose parent has no rectangle aligns to the visible area (see screen.ts).
- *
- * When it runs follows `alignMode`: ONCE the first time, ON_WINDOW_RESIZE on enable and whenever the visible size changes, ALWAYS
- * every frame. Changing any of the widget's own settings re-aligns it whatever the mode, which is what the setters do in Cocos.
+ * The alignment itself (stretch, pin to an edge, centre, margins in units or as a fraction) is the engine's: `RectAnchors` is a component of
+ * its own, aligned by an engine system in the editor's edit mode as well as in play. A Cocos `Widget` is that component under Cocos's names.
+ * A node whose parent has no rectangle aligns to the screen, the centred layout box of the UI camera's domain.
*
* Only the parent as target is supported; a widget that names another node as its target aligns to the parent and says so once.
*/
+import { registerComponent } from '../../ecs/component';
+import { RectAnchors, AnchorFlag, AnchorMode, alignRectAnchorsNow, type RectAnchorsData } from '../../ui/layout/rect-anchors';
+import { ScreenLayout } from '../../ui/core/screen-layout';
import { Component } from '../component';
import { Node } from '../node';
-import { Vec3 } from '../math';
-import { declareClass } from '../host';
-import { instancesOfClass } from '../registry';
+import { registerBuiltinComponent } from '../builtins';
import { log } from '../../util/logger';
-import type { World } from '../../ecs/world';
-import type { Entity } from '../../types';
-import { UITransform } from './uiTransform';
-import { getVisibleSize, visibleSizeGeneration } from './screen';
+import { getScreenLayoutOf } from './screen';
+import { viewAdapter } from './view';
-const AlignFlags = Object.freeze({ TOP: 1, MID: 2, BOT: 4, LEFT: 8, CENTER: 16, RIGHT: 32, HORIZONTAL: 8 | 16 | 32, VERTICAL: 1 | 2 | 4 });
-const AlignMode = Object.freeze({ ONCE: 0, ON_WINDOW_RESIZE: 1, ALWAYS: 2 });
+const AlignFlags = Object.freeze({ TOP: AnchorFlag.TOP, MID: AnchorFlag.MID, BOT: AnchorFlag.BOTTOM, LEFT: AnchorFlag.LEFT, CENTER: AnchorFlag.CENTER, RIGHT: AnchorFlag.RIGHT, HORIZONTAL: AnchorFlag.HORIZONTAL, VERTICAL: AnchorFlag.VERTICAL });
+const AlignMode = Object.freeze({ ONCE: AnchorMode.ONCE, ON_WINDOW_RESIZE: AnchorMode.ON_RESIZE, ALWAYS: AnchorMode.ALWAYS });
-const SETTINGS = [
- 'alignFlags', 'left', 'right', 'top', 'bottom', 'horizontalCenter', 'verticalCenter',
- 'isAbsLeft', 'isAbsRight', 'isAbsTop', 'isAbsBottom', 'isAbsHorizontalCenter', 'isAbsVerticalCenter', 'alignMode',
-] as const;
+type NumberKey = 'alignFlags' | 'left' | 'right' | 'top' | 'bottom' | 'horizontalCenter' | 'verticalCenter' | 'alignMode';
+type FlagKey = 'isAbsLeft' | 'isAbsRight' | 'isAbsTop' | 'isAbsBottom' | 'isAbsHorizontalCenter' | 'isAbsVerticalCenter';
export class Widget extends Component {
static readonly AlignMode = AlignMode;
static readonly AlignFlags = AlignFlags;
- alignFlags = 0;
- left = 0;
- right = 0;
- top = 0;
- bottom = 0;
- horizontalCenter = 0;
- verticalCenter = 0;
- isAbsLeft = true;
- isAbsRight = true;
- isAbsTop = true;
- isAbsBottom = true;
- isAbsHorizontalCenter = true;
- isAbsVerticalCenter = true;
- alignMode: number = AlignMode.ON_WINDOW_RESIZE;
+ /** The node another widget setting names as its target; only the parent is honoured. */
target: Node | null = null;
+ private warnedTarget_ = false;
- /** @internal What the last alignment saw: the settings, and the visible size it was done at. */
- _seen = '';
- _seenGeneration = -1;
- _hadAlignOnce = false;
- _warnedTarget = false;
-
- private flag_(bit: number): boolean { return (this.alignFlags & bit) > 0; }
- private setFlag_(bit: number, on: boolean, clears = 0): void {
- this.alignFlags = on ? (this.alignFlags | bit) & ~clears : this.alignFlags & ~bit;
+ private data_(): RectAnchorsData { return this._world.get(this._entity, RectAnchors); }
+ private patch_(fields: Partial<RectAnchorsData>): void {
+ if (this.target && this.target !== this.node.parent && !this.warnedTarget_) {
+ this.warnedTarget_ = true;
+ log.warn('cocos', `${this.node.name}: Widget.target other than the parent is not supported; aligning to the parent`);
+ }
+ this._world.set(this._entity, RectAnchors, { ...this.data_(), ...fields });
}
- get isAlignLeft(): boolean { return this.flag_(AlignFlags.LEFT); }
- set isAlignLeft(v: boolean) { this.setFlag_(AlignFlags.LEFT, v, AlignFlags.CENTER); }
- get isAlignRight(): boolean { return this.flag_(AlignFlags.RIGHT); }
- set isAlignRight(v: boolean) { this.setFlag_(AlignFlags.RIGHT, v, AlignFlags.CENTER); }
- get isAlignTop(): boolean { return this.flag_(AlignFlags.TOP); }
- set isAlignTop(v: boolean) { this.setFlag_(AlignFlags.TOP, v, AlignFlags.MID); }
- get isAlignBottom(): boolean { return this.flag_(AlignFlags.BOT); }
- set isAlignBottom(v: boolean) { this.setFlag_(AlignFlags.BOT, v, AlignFlags.MID); }
- get isAlignHorizontalCenter(): boolean { return this.flag_(AlignFlags.CENTER); }
- set isAlignHorizontalCenter(v: boolean) { this.setFlag_(AlignFlags.CENTER, v, AlignFlags.LEFT | AlignFlags.RIGHT); }
- get isAlignVerticalCenter(): boolean { return this.flag_(AlignFlags.MID); }
- set isAlignVerticalCenter(v: boolean) { this.setFlag_(AlignFlags.MID, v, AlignFlags.TOP | AlignFlags.BOT); }
+ private num_(key: NumberKey): number { return this.data_()[key]; }
+ private flag_(key: FlagKey): boolean { return this.data_()[key]; }
+ private bit_(bit: number): boolean { return (this.data_().alignFlags & bit) > 0; }
+ private setBit_(bit: number, on: boolean, clears = 0): void {
+ const flags = this.data_().alignFlags;
+ this.patch_({ alignFlags: on ? (flags | bit) & ~clears : flags & ~bit });
+ }
+
+ get enabled(): boolean { return this.data_().enabled; }
+ set enabled(v: boolean) { this.patch_({ enabled: v }); }
+
+ get alignFlags(): number { return this.num_('alignFlags'); }
+ set alignFlags(v: number) { this.patch_({ alignFlags: v }); }
+ get alignMode(): number { return this.num_('alignMode'); }
+ set alignMode(v: number) { this.patch_({ alignMode: v }); }
+ get left(): number { return this.num_('left'); }
+ set left(v: number) { this.patch_({ left: v }); }
+ get right(): number { return this.num_('right'); }
+ set right(v: number) { this.patch_({ right: v }); }
+ get top(): number { return this.num_('top'); }
+ set top(v: number) { this.patch_({ top: v }); }
+ get bottom(): number { return this.num_('bottom'); }
+ set bottom(v: number) { this.patch_({ bottom: v }); }
+ get horizontalCenter(): number { return this.num_('horizontalCenter'); }
+ set horizontalCenter(v: number) { this.patch_({ horizontalCenter: v }); }
+ get verticalCenter(): number { return this.num_('verticalCenter'); }
+ set verticalCenter(v: number) { this.patch_({ verticalCenter: v }); }
+
+ get isAbsLeft(): boolean { return this.flag_('isAbsLeft'); }
+ set isAbsLeft(v: boolean) { this.patch_({ isAbsLeft: v }); }
+ get isAbsRight(): boolean { return this.flag_('isAbsRight'); }
+ set isAbsRight(v: boolean) { this.patch_({ isAbsRight: v }); }
+ get isAbsTop(): boolean { return this.flag_('isAbsTop'); }
+ set isAbsTop(v: boolean) { this.patch_({ isAbsTop: v }); }
+ get isAbsBottom(): boolean { return this.flag_('isAbsBottom'); }
+ set isAbsBottom(v: boolean) { this.patch_({ isAbsBottom: v }); }
+ get isAbsHorizontalCenter(): boolean { return this.flag_('isAbsHorizontalCenter'); }
+ set isAbsHorizontalCenter(v: boolean) { this.patch_({ isAbsHorizontalCenter: v }); }
+ get isAbsVerticalCenter(): boolean { return this.flag_('isAbsVerticalCenter'); }
+ set isAbsVerticalCenter(v: boolean) { this.patch_({ isAbsVerticalCenter: v }); }
+
+ get isAlignLeft(): boolean { return this.bit_(AlignFlags.LEFT); }
+ set isAlignLeft(v: boolean) { this.setBit_(AlignFlags.LEFT, v, AlignFlags.CENTER); }
+ get isAlignRight(): boolean { return this.bit_(AlignFlags.RIGHT); }
+ set isAlignRight(v: boolean) { this.setBit_(AlignFlags.RIGHT, v, AlignFlags.CENTER); }
+ get isAlignTop(): boolean { return this.bit_(AlignFlags.TOP); }
+ set isAlignTop(v: boolean) { this.setBit_(AlignFlags.TOP, v, AlignFlags.MID); }
+ get isAlignBottom(): boolean { return this.bit_(AlignFlags.BOT); }
+ set isAlignBottom(v: boolean) { this.setBit_(AlignFlags.BOT, v, AlignFlags.MID); }
+ get isAlignHorizontalCenter(): boolean { return this.bit_(AlignFlags.CENTER); }
+ set isAlignHorizontalCenter(v: boolean) { this.setBit_(AlignFlags.CENTER, v, AlignFlags.LEFT | AlignFlags.RIGHT); }
+ get isAlignVerticalCenter(): boolean { return this.bit_(AlignFlags.MID); }
+ set isAlignVerticalCenter(v: boolean) { this.setBit_(AlignFlags.MID, v, AlignFlags.TOP | AlignFlags.BOT); }
get isStretchWidth(): boolean { return (this.alignFlags & (AlignFlags.LEFT | AlignFlags.RIGHT)) === (AlignFlags.LEFT | AlignFlags.RIGHT); }
get isStretchHeight(): boolean { return (this.alignFlags & (AlignFlags.TOP | AlignFlags.BOT)) === (AlignFlags.TOP | AlignFlags.BOT); }
@@ -91,112 +112,14 @@ export class Widget extends Component {
set isAbsoluteVerticalCenter(v: boolean) { this.isAbsVerticalCenter = v; }
/** Align now, rather than at the end of the frame. */
- updateAlignment(): void {
- this._hadAlignOnce = false;
- alignWidget(this);
- }
+ updateAlignment(): void { alignRectAnchorsNow(this._world, this._entity, getScreenLayoutOf(this._world)); }
- /** Ask for alignment at the end of the frame, whatever the mode. */
- setDirty(): void { this._seen = ''; this._hadAlignOnce = false; }
-
- private signature_(): string {
- let s = '';
- for (const k of SETTINGS) s += `${this[k]},`;
- return s;
- }
-
- /** @internal Whether the pass should align this widget now. */
- _due(generation: number): boolean {
- if (this.alignFlags === 0) return false;
- if (this.alignMode === AlignMode.ALWAYS) return true;
- const sig = this.signature_();
- if (sig !== this._seen) { this._seen = sig; this._seenGeneration = generation; this._hadAlignOnce = false; return true; }
- if (this.alignMode === AlignMode.ONCE) return false;
- if (generation !== this._seenGeneration) { this._seenGeneration = generation; return true; }
- return false;
- }
+ /** Ask for alignment at the end of the frame, whatever the mode: a write of the settings is what the engine watches for. */
+ setDirty(): void { this.patch_({ alignFlags: this.alignFlags }); this.updateAlignment(); }
}
-interface Anchor { x: number; y: number }
-
-/** Align one widget to its parent, as Cocos's `align` does (rotation ignored). */
-export function alignWidget(widget: Widget): void {
- if (widget._hadAlignOnce) return;
- if (widget.alignMode === AlignMode.ONCE) widget._hadAlignOnce = true;
- const node = widget.node;
- const own = node.getComponent(UITransform);
- if (!own) return;
- if (widget.target && widget.target !== node.parent && !widget._warnedTarget) {
- widget._warnedTarget = true;
- log.warn('cocos', `${node.name}: Widget.target other than the parent is not supported; aligning to the parent`);
- }
-
- const parent = node.parent;
- const parentTransform = parent?.getComponent(UITransform) ?? null;
- const isRoot = !parentTransform;
- const visible = getVisibleSize();
- const targetW = parentTransform ? parentTransform.width : visible.width;
- const targetH = parentTransform ? parentTransform.height : visible.height;
- const targetAnchor: Anchor = parentTransform ? { x: parentTransform.anchorX, y: parentTransform.anchorY } : { x: 0, y: 0 };
-
- const pos = node.getPosition();
- const scale = node.getScale();
- let x = pos.x;
- let y = pos.y;
-
- if (widget.alignFlags & AlignFlags.HORIZONTAL) {
- let left = isRoot ? 0 : -targetAnchor.x * targetW;
- let right = isRoot ? visible.width : left + targetW;
- left += widget.isAbsLeft ? widget.left : widget.left * targetW;
- right -= widget.isAbsRight ? widget.right : widget.right * targetW;
- let anchorX = own.anchorX;
- let scaleX = scale.x;
- if (scaleX < 0) { anchorX = 1 - anchorX; scaleX = -scaleX; }
- if (widget.isStretchWidth) {
- const width = right - left;
- if (scaleX !== 0) own.width = width / scaleX;
- x = left + anchorX * width;
- } else {
- const width = own.width * scaleX;
- if (widget.isAlignHorizontalCenter) {
- const offset = widget.isAbsHorizontalCenter ? widget.horizontalCenter : widget.horizontalCenter * targetW;
- const center = (0.5 - targetAnchor.x) * targetW;
- x = center + (anchorX - 0.5) * width + offset;
- } else if (widget.isAlignLeft) {
- x = left + anchorX * width;
- } else {
- x = right + (anchorX - 1) * width;
- }
- }
- }
-
- if (widget.alignFlags & AlignFlags.VERTICAL) {
- let bottom = isRoot ? 0 : -targetAnchor.y * targetH;
- let top = isRoot ? visible.height : bottom + targetH;
- bottom += widget.isAbsBottom ? widget.bottom : widget.bottom * targetH;
- top -= widget.isAbsTop ? widget.top : widget.top * targetH;
- let anchorY = own.anchorY;
- let scaleY = scale.y;
- if (scaleY < 0) { anchorY = 1 - anchorY; scaleY = -scaleY; }
- if (widget.isStretchHeight) {
- const height = top - bottom;
- if (scaleY !== 0) own.height = height / scaleY;
- y = bottom + anchorY * height;
- } else {
- const height = own.height * scaleY;
- if (widget.isAlignVerticalCenter) {
- const offset = widget.isAbsVerticalCenter ? widget.verticalCenter : widget.verticalCenter * targetH;
- const middle = (0.5 - targetAnchor.y) * targetH;
- y = middle + (anchorY - 0.5) * height + offset;
- } else if (widget.isAlignBottom) {
- y = bottom + anchorY * height;
- } else {
- y = top + (anchorY - 1) * height;
- }
- }
- }
- node.setPosition(new Vec3(x, y, pos.z));
-}
+/** Align one widget to its parent now (rotation ignored). */
+export function alignWidget(widget: Widget): void { widget.updateAlignment(); }
/** How deep a node is: parents align before the children that depend on their size. */
export function depthOf(node: Node): number {
@@ -205,23 +128,13 @@ export function depthOf(node: Node): number {
return d;
}
-/** Align every widget that is due, parents first. */
-export function alignAllWidgets(world: World): void {
- const generation = visibleSizeGeneration();
- const due: Array<{ widget: Widget; depth: number }> = [];
- for (const [entity, inst] of instancesOfClass(world, Widget) as Array<[Entity, Widget]>) {
- if (!inst.enabled || !world.isEntityActive(entity)) continue;
- if (inst._due(generation)) due.push({ widget: inst, depth: depthOf(inst.node) });
- }
- due.sort((a, b) => a.depth - b.depth);
- for (const { widget } of due) alignWidget(widget);
-}
+registerBuiltinComponent(Widget, ['cc.Widget', 'Widget'], viewAdapter(
+ Widget,
+ (world, entity) => world.has(entity, RectAnchors),
+ (world, entity) => { world.insert(entity, RectAnchors, {}); },
+));
-/** Declare the widget's component, so a scene that holds one finds it. */
-export function declareWidget(): void {
- declareClass(Widget as never, 'Widget', [
- ...['alignFlags', 'left', 'right', 'top', 'bottom', 'horizontalCenter', 'verticalCenter', 'alignMode'].map((name) => ({ name, kind: 'number' as const })),
- ...['isAbsLeft', 'isAbsRight', 'isAbsTop', 'isAbsBottom', 'isAbsHorizontalCenter', 'isAbsVerticalCenter'].map((name) => ({ name, kind: 'boolean' as const })),
- { name: 'target', kind: 'node' as const },
- ]);
-}
+/** The component is the engine's; a host without the engine's UI plugin (a test, a bare app) still needs it registered for a scene to load. */
+export function declareWidget(): void { registerComponent('RectAnchors', RectAnchors); }
+
+export { ScreenLayout };
diff --git a/sdk/src/cocos/view.ts b/sdk/src/cocos/view.ts
index b61e3a7fd..0d56319ac 100644
--- a/sdk/src/cocos/view.ts
+++ b/sdk/src/cocos/view.ts
@@ -41,8 +41,9 @@ export class View extends Emitter {
/** The area the player sees, in canvas units. */
getVisibleSize(): Size { const v = getVisibleSize(); return new Size(v.width, v.height); }
getVisibleSizeInPixel(): Size { const v = getVisibleSize(); const s = this.getScaleX(); return new Size(v.width * s, v.height * s); }
- getVisibleOrigin(): Vec2 { return new Vec2(0, 0); }
- getVisibleOriginInPixel(): Vec2 { return new Vec2(0, 0); }
+ /** The visible area is centred on the world origin, as the engine's screen is. */
+ getVisibleOrigin(): Vec2 { const v = getVisibleSize(); return new Vec2(-v.width / 2, -v.height / 2); }
+ getVisibleOriginInPixel(): Vec2 { const v = this.getVisibleSizeInPixel(); return new Vec2(-v.width / 2, -v.height / 2); }
getViewportRect(): Rect { const w = getWindowPixels(); return new Rect(0, 0, w.width, w.height); }
getDesignResolutionSize(): Size { return this.design_ ? this.design_.clone() : this.getVisibleSize(); }
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index a7d99f39c..c6c16a208 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -62,6 +62,7 @@ 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 { RectAnchors, rectAnchorsPlugin, RectAnchorsPlugin, AnchorFlag, AnchorMode, anchoredRect, alignRectAnchorsNow, alignAllRectAnchors, forgetRectAnchors, type RectAnchorsData } from './layout/rect-anchors';
export {
Text,
diff --git a/sdk/src/ui/layout/rect-anchors.ts b/sdk/src/ui/layout/rect-anchors.ts
new file mode 100644
index 000000000..78835bb03
--- /dev/null
+++ b/sdk/src/ui/layout/rect-anchors.ts
@@ -0,0 +1,230 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/layout/rect-anchors.ts
+ * @brief `RectAnchors` — a piece of world content pinned to the edges (or the centre) of its parent's rectangle, and the system that keeps it there.
+ *
+ * `UINode` is the engine's flexbox layout, for UI that is laid out. Content placed by its `Transform` and sized by a `ContentRect` (an
+ * imported scene, a hand-built HUD) is not: its box does not depend on its siblings, but it often wants to follow its parent, or the screen.
+ * This is that, as data: each axis is stretched (both edges pinned: the size follows the parent), pinned to one edge, or centred with an
+ * offset, with margins in layout units or as a fraction of the parent.
+ *
+ * A node whose parent has no `ContentRect` aligns to the screen: the layout box of the UI camera's domain (`ScreenLayout`), which is
+ * centred on the world origin. Parents are aligned before the children that depend on their size, in the editor's edit mode as well as in play, so a
+ * scene shows laid out as it will run.
+ *
+ * How often it runs is `alignMode`: ONCE (the first time), ON_RESIZE (when it is enabled, when its own settings change, and whenever the screen
+ * changes), ALWAYS (every frame). Changing a setting re-aligns it whatever the mode.
+ */
+import type { App, Plugin } from '../../app/app';
+import { defineComponent, registerComponent, Transform } from '../../ecs/component';
+import { Parent } from '../../ecs/component';
+import { Res } from '../../ecs/resource';
+import { defineSystem, Schedule } from '../../ecs/system';
+import type { World } from '../../ecs/world';
+import type { Entity } from '../../types';
+import { ContentRect } from '../core/content-rect';
+import { ScreenLayout, type ScreenLayoutData } from '../core/screen-layout';
+
+/** Which edges are pinned: the flags of one axis are mutually exclusive between its edges and its centre. */
+export const AnchorFlag = Object.freeze({ TOP: 1, MID: 2, BOTTOM: 4, LEFT: 8, CENTER: 16, RIGHT: 32, HORIZONTAL: 8 | 16 | 32, VERTICAL: 1 | 2 | 4 });
+export const AnchorMode = Object.freeze({ ONCE: 0, ON_RESIZE: 1, ALWAYS: 2 });
+
+export interface RectAnchorsData {
+ /** The pinned edges, as {@link AnchorFlag} bits. Zero pins nothing. */
+ alignFlags: number;
+ /** Distance from each pinned edge of the parent rectangle: in layout units, or as a fraction of the parent's size (see the `isAbs…` flags). */
+ left: number;
+ right: number;
+ top: number;
+ bottom: number;
+ /** Offset from the centre of the parent rectangle, for a centred axis. */
+ horizontalCenter: number;
+ verticalCenter: number;
+ isAbsLeft: boolean;
+ isAbsRight: boolean;
+ isAbsTop: boolean;
+ isAbsBottom: boolean;
+ isAbsHorizontalCenter: boolean;
+ isAbsVerticalCenter: boolean;
+ /** When it aligns: {@link AnchorMode}. */
+ alignMode: number;
+ enabled: boolean;
+}
+
+export const RectAnchors = defineComponent<RectAnchorsData>('RectAnchors', {
+ alignFlags: 0,
+ left: 0, right: 0, top: 0, bottom: 0,
+ horizontalCenter: 0, verticalCenter: 0,
+ isAbsLeft: true, isAbsRight: true, isAbsTop: true, isAbsBottom: true, isAbsHorizontalCenter: true, isAbsVerticalCenter: true,
+ alignMode: AnchorMode.ON_RESIZE,
+ enabled: true,
+});
+
+/** The rectangle an anchored node aligns to, in the node's parent space: its edges and its centre. */
+interface Box { left: number; right: number; bottom: number; top: number }
+
+const isStretchWidth = (flags: number): boolean => (flags & (AnchorFlag.LEFT | AnchorFlag.RIGHT)) === (AnchorFlag.LEFT | AnchorFlag.RIGHT);
+const isStretchHeight = (flags: number): boolean => (flags & (AnchorFlag.TOP | AnchorFlag.BOTTOM)) === (AnchorFlag.TOP | AnchorFlag.BOTTOM);
+
+/**
+ * Where a rectangle goes, and how big, when pinned as @p a says inside @p target. Pure: the node's own size, pivot and scale in, its local
+ * position and (when an axis is stretched) its size out. Rotation is ignored.
+ */
+export function anchoredRect(
+ a: RectAnchorsData, target: Box,
+ own: { width: number; height: number; pivotX: number; pivotY: number },
+ scale: { x: number; y: number },
+ position: { x: number; y: number },
+): { x: number; y: number; width: number; height: number } {
+ const targetW = target.right - target.left;
+ const targetH = target.top - target.bottom;
+ let { x, y } = position;
+ let width = own.width;
+ let height = own.height;
+
+ if (a.alignFlags & AnchorFlag.HORIZONTAL) {
+ const left = target.left + (a.isAbsLeft ? a.left : a.left * targetW);
+ const right = target.right - (a.isAbsRight ? a.right : a.right * targetW);
+ let pivot = own.pivotX;
+ let sx = scale.x;
+ if (sx < 0) { pivot = 1 - pivot; sx = -sx; }
+ if (isStretchWidth(a.alignFlags)) {
+ const span = right - left;
+ if (sx !== 0) width = span / sx;
+ x = left + pivot * span;
+ } else {
+ const span = own.width * sx;
+ if (a.alignFlags & AnchorFlag.CENTER) {
+ const offset = a.isAbsHorizontalCenter ? a.horizontalCenter : a.horizontalCenter * targetW;
+ x = (target.left + targetW / 2) + (pivot - 0.5) * span + offset;
+ } else if (a.alignFlags & AnchorFlag.LEFT) {
+ x = left + pivot * span;
+ } else {
+ x = right + (pivot - 1) * span;
+ }
+ }
+ }
+
+ if (a.alignFlags & AnchorFlag.VERTICAL) {
+ const bottom = target.bottom + (a.isAbsBottom ? a.bottom : a.bottom * targetH);
+ const top = target.top - (a.isAbsTop ? a.top : a.top * targetH);
+ let pivot = own.pivotY;
+ let sy = scale.y;
+ if (sy < 0) { pivot = 1 - pivot; sy = -sy; }
+ if (isStretchHeight(a.alignFlags)) {
+ const span = top - bottom;
+ if (sy !== 0) height = span / sy;
+ y = bottom + pivot * span;
+ } else {
+ const span = own.height * sy;
+ if (a.alignFlags & AnchorFlag.MID) {
+ const offset = a.isAbsVerticalCenter ? a.verticalCenter : a.verticalCenter * targetH;
+ y = (target.bottom + targetH / 2) + (pivot - 0.5) * span + offset;
+ } else if (a.alignFlags & AnchorFlag.BOTTOM) {
+ y = bottom + pivot * span;
+ } else {
+ y = top + (pivot - 1) * span;
+ }
+ }
+ }
+ return { x, y, width, height };
+}
+
+/** What the last alignment of one node saw: its settings, and the screen it was done on. */
+interface Seen { signature: string; generation: number; once: boolean }
+const seenByWorld = new WeakMap<World, Map<Entity, Seen>>();
+
+const SETTINGS = ['alignFlags', 'left', 'right', 'top', 'bottom', 'horizontalCenter', 'verticalCenter', 'isAbsLeft', 'isAbsRight', 'isAbsTop', 'isAbsBottom', 'isAbsHorizontalCenter', 'isAbsVerticalCenter', 'alignMode'] as const;
+const signatureOf = (a: RectAnchorsData): string => SETTINGS.map((k) => String(a[k])).join(',');
+
+/** The screen box of a layout, as the box a root node aligns to. */
+function screenBox(screen: ScreenLayoutData): Box { return { left: screen.left, right: screen.right, bottom: screen.bottom, top: screen.top }; }
+
+function parentBox(world: World, entity: Entity, screen: ScreenLayoutData | null): Box | null {
+ const parent = world.tryGet(entity, Parent)?.entity;
+ const rect = parent ? world.tryGet(parent as Entity, ContentRect) : undefined;
+ if (rect) {
+ const left = -rect.pivot.x * rect.size.x;
+ const bottom = -rect.pivot.y * rect.size.y;
+ return { left, right: left + rect.size.x, bottom, top: bottom + rect.size.y };
+ }
+ return screen?.valid ? screenBox(screen) : null;
+}
+
+function depthOf(world: World, entity: Entity): number {
+ let d = 0;
+ for (let p = world.tryGet(entity, Parent)?.entity as Entity | undefined; p; p = world.tryGet(p, Parent)?.entity as Entity | undefined) d++;
+ return d;
+}
+
+/** Align one node now, whatever its mode. Answers whether it had a box to align to. */
+export function alignRectAnchorsNow(world: World, entity: Entity, screen: ScreenLayoutData | null): boolean {
+ const a = world.tryGet(entity, RectAnchors);
+ const t = world.tryGet(entity, Transform);
+ if (!a || !t) return false;
+ const box = parentBox(world, entity, screen);
+ if (!box) return false;
+ const rect = world.tryGet(entity, ContentRect);
+ const out = anchoredRect(
+ a, box,
+ { width: rect?.size.x ?? 0, height: rect?.size.y ?? 0, pivotX: rect?.pivot.x ?? 0.5, pivotY: rect?.pivot.y ?? 0.5 },
+ { x: t.scale.x, y: t.scale.y }, { x: t.position.x, y: t.position.y },
+ );
+ if (out.x !== t.position.x || out.y !== t.position.y) world.set(entity, Transform, { ...t, position: { x: out.x, y: out.y, z: t.position.z } });
+ if (rect && (out.width !== rect.size.x || out.height !== rect.size.y)) world.set(entity, ContentRect, { ...rect, size: { x: out.width, y: out.height } });
+ return true;
+}
+
+/**
+ * Align every node that is due, parents first. @p generation changes whenever the screen does.
+ */
+export function alignAllRectAnchors(world: World, screen: ScreenLayoutData | null, generation: number): void {
+ let seen = seenByWorld.get(world);
+ if (!seen) { seen = new Map(); seenByWorld.set(world, seen); }
+ const due: Array<{ entity: Entity; depth: number }> = [];
+ for (const entity of world.getEntitiesWithComponents([RectAnchors, Transform])) {
+ const a = world.get(entity, RectAnchors);
+ if (!a.enabled || a.alignFlags === 0 || !world.isEntityActive(entity)) continue;
+ const state = seen.get(entity);
+ const signature = signatureOf(a);
+ let isDue: boolean;
+ if (a.alignMode === AnchorMode.ALWAYS) isDue = true;
+ else if (!state || state.signature !== signature) isDue = true;
+ else if (a.alignMode === AnchorMode.ONCE) isDue = false;
+ else isDue = state.generation !== generation;
+ if (isDue) due.push({ entity, depth: depthOf(world, entity) });
+ }
+ due.sort((x, y) => x.depth - y.depth);
+ for (const { entity } of due) {
+ if (alignRectAnchorsNow(world, entity, screen)) {
+ seen.set(entity, { signature: signatureOf(world.get(entity, RectAnchors)), generation, once: true });
+ }
+ }
+}
+
+/** Forget what was aligned (a scene that is replaced; a test seam). */
+export function forgetRectAnchors(world: World): void { seenByWorld.delete(world); }
+
+let screenGeneration = 0;
+let lastScreenKey = '';
+
+export class RectAnchorsPlugin implements Plugin {
+ name = 'rectAnchors';
+
+ build(app: App): void {
+ registerComponent('RectAnchors', RectAnchors);
+ const world = app.world;
+ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(
+ [Res(ScreenLayout)],
+ (screen: ScreenLayoutData) => {
+ const key = screen?.valid ? `${screen.left},${screen.right},${screen.bottom},${screen.top}` : '';
+ if (key !== lastScreenKey) { lastScreenKey = key; screenGeneration++; }
+ alignAllRectAnchors(world, screen ?? null, screenGeneration);
+ },
+ { name: 'RectAnchorsSystem' },
+ ));
+ }
+}
+
+export const rectAnchorsPlugin = new RectAnchorsPlugin();
diff --git a/sdk/src/ui/ui-plugin.ts b/sdk/src/ui/ui-plugin.ts
index a2b1c750e..68882dcba 100644
--- a/sdk/src/ui/ui-plugin.ts
+++ b/sdk/src/ui/ui-plugin.ts
@@ -19,6 +19,7 @@ import type { Entity } from '../types';
import { uiLayoutPlugin } from './layout/layout';
import { uiMaskPlugin } from './render/mask';
import { contentRectPlugin } from './render/content-rect';
+import { rectAnchorsPlugin } from './layout/rect-anchors';
import { safeAreaPlugin } from './layout/safe-area';
import { textPlugin } from './text/plugin';
import { inlineImagePlugin } from './text/inline-image-plugin';
@@ -45,6 +46,7 @@ const SUB_PLUGINS: Plugin[] = [
uiLayoutPlugin,
uiMaskPlugin,
contentRectPlugin,
+ rectAnchorsPlugin,
safeAreaPlugin,
textPlugin,
inlineImagePlugin,
diff --git a/sdk/tests/cocos/import-contract-wasm.test.ts b/sdk/tests/cocos/import-contract-wasm.test.ts
index af94ba0d1..477526bfe 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: `ContentRect` (the engine's), `Cocos.Widget`,
+ * The importer (pipeline/src/import/cocos) and the layer agree on a contract by name only: `ContentRect` (the engine's), `RectAnchors`,
* `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.
*/
@@ -67,7 +67,7 @@ describe.skipIf(!HAS_WASM)('the importer\'s scene in the compatibility layer', (
{ id: 0, name: 'Canvas', parent: null, children: [1, 2], visible: true, components: [
transform,
{ 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 } },
+ { type: 'RectAnchors', 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,
@@ -91,7 +91,7 @@ describe.skipIf(!HAS_WASM)('the importer\'s scene in the compatibility layer', (
// geometry and alignment: the canvas was authored 10x10 and stretches to the visible area
const t = canvas.getComponent(UITransform)!;
expect([t.width, t.height]).toEqual([960, 640]);
- expect(canvas.position.x).toBe(480);
+ expect(canvas.position.x).toBe(0); // the screen is centred on the origin
// a script with its fields, node references mapped to the entities the loader made
const script = hud.getComponent('Hud') as unknown as Hud;
diff --git a/sdk/tests/cocos/widget-layout-wasm.test.ts b/sdk/tests/cocos/widget-layout-wasm.test.ts
index 345669f8d..47e980eb9 100644
--- a/sdk/tests/cocos/widget-layout-wasm.test.ts
+++ b/sdk/tests/cocos/widget-layout-wasm.test.ts
@@ -97,11 +97,11 @@ describe.skipIf(!HAS_WASM)('widgets and layouts on the engine', () => {
widget(canvas, (w) => { w.isAlignLeft = w.isAlignRight = w.isAlignTop = w.isAlignBottom = true; });
await frame();
expect(size(canvas)).toEqual([960, 640]);
- expect([canvas.position.x, canvas.position.y]).toEqual([480, 320]);
+ expect([canvas.position.x, canvas.position.y]).toEqual([0, 0]); // the screen is centred on the origin
setVisibleSize(1280, 720);
await frame();
expect(size(canvas)).toEqual([1280, 720]);
- expect(canvas.position.x).toBe(640);
+ expect(canvas.position.x).toBe(0);
});
it('aligns once and leaves the node to the script after, in ONCE mode; every frame, in ALWAYS mode', async () => {
diff --git a/sdk/tests/rect-anchors-wasm.test.ts b/sdk/tests/rect-anchors-wasm.test.ts
new file mode 100644
index 000000000..29967f40f
--- /dev/null
+++ b/sdk/tests/rect-anchors-wasm.test.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file RectAnchors: content pinned to its parent's rectangle, or to the screen, in the engine and not in a compatibility layer.
+ */
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import type { ESEngineModule } from '../src/wasm';
+import { World } from '../src/ecs/world';
+import { Transform, ensureBuiltinComponentsRegistered } from '../src/ecs/component';
+import { AppContext, setDefaultContext } from '../src/ecs/context';
+import { ContentRect } from '../src/ui/core/content-rect';
+import type { ScreenLayoutData } from '../src/ui/core/screen-layout';
+import { AnchorFlag, AnchorMode, RectAnchors, alignAllRectAnchors, anchoredRect, forgetRectAnchors } from '../src/ui/layout/rect-anchors';
+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+
+const defaults = { left: 0, right: 0, top: 0, bottom: 0, horizontalCenter: 0, verticalCenter: 0, isAbsLeft: true, isAbsRight: true, isAbsTop: true, isAbsBottom: true, isAbsHorizontalCenter: true, isAbsVerticalCenter: true, alignMode: AnchorMode.ON_RESIZE, enabled: true };
+const screen = (halfW: number, halfH: number): ScreenLayoutData => ({ valid: true, left: -halfW, right: halfW, bottom: -halfH, top: halfH, safeLeft: -halfW, safeRight: halfW, safeBottom: -halfH, safeTop: halfH, scale: 1, viewportW: halfW * 2, viewportH: halfH * 2 });
+
+describe('anchoredRect', () => {
+ const box = { left: 0, right: 100, bottom: 0, top: 50 };
+ const own = { width: 10, height: 10, pivotX: 0.5, pivotY: 0.5 };
+ const at = { x: 0, y: 0 };
+
+ it('stretches between two edges, with margins', () => {
+ const out = anchoredRect({ ...defaults, alignFlags: AnchorFlag.LEFT | AnchorFlag.RIGHT, left: 10, right: 20 }, box, own, { x: 1, y: 1 }, at);
+ expect(out.width).toBe(70);
+ expect(out.x).toBe(10 + 35);
+ });
+
+ it('pins to one edge, by its own pivot', () => {
+ expect(anchoredRect({ ...defaults, alignFlags: AnchorFlag.LEFT, left: 5 }, box, own, { x: 1, y: 1 }, at).x).toBe(5 + 5);
+ expect(anchoredRect({ ...defaults, alignFlags: AnchorFlag.RIGHT, right: 5 }, box, own, { x: 1, y: 1 }, at).x).toBe(95 - 5);
+ expect(anchoredRect({ ...defaults, alignFlags: AnchorFlag.TOP, top: 0 }, box, own, { x: 1, y: 1 }, at).y).toBe(45);
+ });
+
+ it('centres with an offset, in units or as a fraction of the parent', () => {
+ expect(anchoredRect({ ...defaults, alignFlags: AnchorFlag.CENTER, horizontalCenter: 4 }, box, own, { x: 1, y: 1 }, at).x).toBe(54);
+ expect(anchoredRect({ ...defaults, alignFlags: AnchorFlag.CENTER, horizontalCenter: 0.1, isAbsHorizontalCenter: false }, box, own, { x: 1, y: 1 }, at).x).toBe(60);
+ });
+
+ it('leaves an axis it does not pin alone', () => {
+ const out = anchoredRect({ ...defaults, alignFlags: AnchorFlag.LEFT }, box, own, { x: 1, y: 1 }, { x: 0, y: 33 });
+ expect(out.y).toBe(33);
+ });
+});
+
+describe.skipIf(!HAS_WASM)('the system', () => {
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let world: World | undefined;
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+ afterEach(() => { if (world) forgetRectAnchors(world); world?.disconnectCpp(); registry?.delete(); registry = undefined; world = undefined; });
+
+ function connect(): World {
+ setDefaultContext(new AppContext());
+ ensureBuiltinComponentsRegistered();
+ registry = new module.Registry();
+ world = new World();
+ world.connectCpp(registry, module);
+ return world;
+ }
+ const rect = (w: number, h: number) => ({ size: { x: w, y: h }, pivot: { x: 0.5, y: 0.5 } });
+
+ it('stretches a root to the screen and a child to its parent, parents first', () => {
+ const w = connect();
+ const root = w.spawn(), child = w.spawn();
+ w.insert(root, Transform); w.insert(root, ContentRect, rect(10, 10));
+ w.insert(root, RectAnchors, { ...defaults, alignFlags: AnchorFlag.HORIZONTAL & ~AnchorFlag.CENTER | AnchorFlag.VERTICAL & ~AnchorFlag.MID });
+ w.insert(child, Transform); w.insert(child, ContentRect, rect(1, 1));
+ w.insert(child, RectAnchors, { ...defaults, alignFlags: AnchorFlag.LEFT | AnchorFlag.RIGHT | AnchorFlag.TOP | AnchorFlag.BOTTOM, left: 10, right: 10, top: 20, bottom: 20 });
+ w.setParent(child, root);
+
+ alignAllRectAnchors(w, screen(540, 960), 1);
+
+ expect(w.get(root, ContentRect).size).toEqual({ x: 1080, y: 1920 });
+ expect(w.get(root, Transform).position.x).toBe(0);
+ expect(w.get(child, ContentRect).size).toEqual({ x: 1060, y: 1880 });
+ });
+
+ it('aligns again when the screen changes, and not when nothing did', () => {
+ const w = connect();
+ const e = w.spawn();
+ w.insert(e, Transform); w.insert(e, ContentRect, rect(10, 10));
+ w.insert(e, RectAnchors, { ...defaults, alignFlags: AnchorFlag.LEFT | AnchorFlag.RIGHT });
+ alignAllRectAnchors(w, screen(100, 100), 1);
+ expect(w.get(e, ContentRect).size.x).toBe(200);
+ w.set(e, ContentRect, rect(7, 10));
+ alignAllRectAnchors(w, screen(100, 100), 1); // same screen: left as it was set
+ expect(w.get(e, ContentRect).size.x).toBe(7);
+ alignAllRectAnchors(w, screen(50, 100), 2); // a new screen
+ expect(w.get(e, ContentRect).size.x).toBe(100);
+ });
+
+ it('does nothing for a node that is disabled or pins nothing', () => {
+ const w = connect();
+ const a = w.spawn(), b = w.spawn();
+ for (const e of [a, b]) { w.insert(e, Transform); w.insert(e, ContentRect, rect(10, 10)); }
+ w.insert(a, RectAnchors, { ...defaults, alignFlags: AnchorFlag.LEFT | AnchorFlag.RIGHT, enabled: false });
+ w.insert(b, RectAnchors, { ...defaults, alignFlags: 0 });
+ alignAllRectAnchors(w, screen(100, 100), 1);
+ expect(w.get(a, ContentRect).size.x).toBe(10);
+ expect(w.get(b, ContentRect).size.x).toBe(10);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 7d391d07a..5ee853a31 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(ui): RectAnchors pins world content to its parent rectangle or the screen in the engine, and the Cocos Widget is a view on it':
+ {"note":"RectAnchors: world content that follows its parent."},
'feat(cocos): a converted project keeps the Cocos fit width of its design, and cc.profiler exists in the compatibility layer':
{"note":"A converted Cocos project fits the screen as the game does."},
'fix(cocos): a renderer is put in the layer of its Cocos node, so a UI camera that culls by layer draws it':