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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(cocos): BoxCollider maps to the engine box collider with a static body, Line is a component over the engine vector path, Graphics builds its mesh with it (polygon fills, joins and caps), and a sprite whose frame is missing stays, switched off
yhh755289ac6921
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.tsindex 5bcb125a4..72b53bfcf 100644--- a/pipeline/src/import/cocos/components.ts+++ b/pipeline/src/import/cocos/components.ts@@ -12,7 +12,7 @@* That is a world-space `Sprite`/`Text` with a pivot, not a flex box, so* UI maps there and `UITransform` is folded into it.*/-import { particleSystem } from './particle';+import { curveRange, particleSystem } from './particle';import type { CocosAssetEntry, CocosAssetIndex } from './assets';import { type CocosComponent, type CocosNode } from './document';import type { ImportReport } from './report';@@ -145,10 +145,12 @@ function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, wheconst entry = ctx.assets.byUuid.get(frameUuid);const sub = entry?.subs.get(frameUuid);if (!entry || !sub || entry.importer !== 'image' || sub.importer !== 'sprite-frame') {- ctx.report.component('cc.Sprite', 'unmapped');+ // A frame the project does not have draws nothing in Cocos either. The sprite stays, switched off, so a script that sets its frame later+ // finds the component, and a white quad does not stand where a picture was meant.+ ctx.report.component('cc.Sprite', 'partial');ctx.report.note(entry ? 'sprite-frame-not-from-image' : 'sprite-frame-missing', where);if (!entry) ctx.report.missingAsset(frameUuid);- return null;+ return { type: 'Sprite', data: { ...data, enabled: false } };}const ud = sub.userData;@@ -638,6 +640,46 @@ function graphics(c: CocosComponent): ComponentData {};}+/** `cc.Line`: a polyline of a width and a colour. The width is a curve in Cocos and a number here, read at the start; the colour is the gradient's first. */+function line(c: CocosComponent, ctx: ComponentContext, where: string): ComponentData {+ const d = c.data;+ const width = curveRange(d._width, 0, 1);+ const gradient = isObj(d._color) ? d._color : {};+ const first = isObj(gradient.color) ? gradient.color : { r: 255, g: 255, b: 255, a: 255 };+ if (isObj(d._width) && num(d._width.mode, 0) !== 0 && width.min !== width.max) ctx.report.note('line-width-curve', where);+ if (num(gradient._mode, 0) !== 0) ctx.report.note('line-color-gradient', where);+ return {+ type: `${LAYER}Line`,+ data: {+ enabled: c.enabled,+ worldSpace: d._worldSpace !== false,+ width: (width.min + width.max) / 2,+ color: { r: num(first.r, 255), g: num(first.g, 255), b: num(first.b, 255), a: num(first.a, 255) },+ positions: (Array.isArray(d._positions) ? d._positions : []).filter(isObj).map((p) => ({ x: num(p.x, 0), y: num(p.y, 0), z: num(p.z, 0) })),+ },+ };+}++/**+ * `cc.BoxCollider`: the engine's box, half the node-scaled size on each side. A Cocos collider with no rigid body is a static one, which the engine+ * spells as a static body beside the box. The engine's box is centred on the entity, so a collider that sits off-centre keeps its size and loses+ * where it stood, which is counted.+ */+function boxCollider(c: CocosComponent, node: CocosNode, ctx: ComponentContext, where: string, extra: ComponentData[]): ComponentData {+ const size = isObj(c.data._size) ? c.data._size : {};+ const center = isObj(c.data._center) ? c.data._center : {};+ const half = (axis: 'x' | 'y' | 'z'): number => Math.abs(num(size[axis], 1) * (node.scale[axis] ?? 1)) / 2;+ const off = Math.abs(num(center.x, 0)) + Math.abs(num(center.y, 0)) + Math.abs(num(center.z, 0));+ if (off > 1e-6) {+ ctx.report.component('cc.BoxCollider', 'partial');+ ctx.report.note('collider-center-dropped', where);+ } else {+ ctx.report.component('cc.BoxCollider', 'mapped');+ }+ if (!node.components.some((n) => n.type === 'cc.RigidBody') && !extra.some((e) => e.type === 'RigidBody3D')) extra.push({ type: 'RigidBody3D', data: { bodyType: 0 } });+ return { type: 'BoxCollider3D', data: { halfExtents: { x: half('x'), y: half('y'), z: half('z') }, isSensor: c.data._isTrigger === true, enabled: c.enabled } };+}+/** `cc.EditBox`: the box and its two labels are the scene's own nodes; what is typed goes through the platform's text editor. */function editBox(c: CocosComponent, ctx: ComponentContext): ComponentData {return {@@ -778,6 +820,12 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strincase 'cc.SkeletalAnimation':out = skeletalAnimation(c, node, ctx, where);break;+ case 'cc.Line':+ out = line(c, ctx, where);+ break;+ case 'cc.BoxCollider':+ out = boxCollider(c, node, ctx, where, extra);+ break;case 'cc.EditBox':out = editBox(c, ctx);break;diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.tsindex 8431b25c4..912adaf19 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, Mask, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, Graphics, EditBox, getVisibleSize, setVisibleSize } from './ui';+export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, Camera, RichText, Mask, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, Graphics, Line, EditBox, getVisibleSize, setVisibleSize } from './ui';export { Touch, EventTouch } from './input';export { tween, Tween, tweenUtil, easing, updateTweens } from './tween';export { instantiate, loadPrefab, providePrefab } from './prefabs';diff --git a/sdk/src/cocos/ui/graphics.ts b/sdk/src/cocos/ui/graphics.tsindex fe12069d7..69a7418a7 100644--- a/sdk/src/cocos/ui/graphics.ts+++ b/sdk/src/cocos/ui/graphics.ts@@ -2,39 +2,46 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file cocos/ui/graphics.ts- * @brief `Graphics`: the path-drawing component, over the engine's immediate `Draw`.+ * @brief `Graphics` and `Line`: path-drawing components, over the engine's vector paths.** A scene stores only a Graphics' style (line width, colours); its picture is what scripts draw with `moveTo`, `lineTo`, `rect`, `circle`,- * `stroke` and `fill`, and Cocos keeps that picture until `clear()`. So this keeps the recorded drawing and plays it into the engine's `Draw`- * every frame, in the node's place. What `Draw` can paint, this paints: lines at a width, filled rectangles and circles. A filled path of any other- * shape is counted (and said once), not drawn — the engine has no polygon fill, and guessing one would draw the wrong thing.+ * `stroke` and `fill`, and Cocos keeps that picture until `clear()`. So this records the drawing and turns it into the geometry of the node's own+ * `MeshRenderer` (the engine's `buildPathGeometry`: ear-clipped fills, strokes with the line join and cap Cocos names), which is retained,+ * sorted and batched like any mesh and moves with the node. Nothing is redrawn per frame; the geometry is rebuilt on the frame after a change.*/import { Component } from '../component';import { Color, Vec2 } from '../math';import { declareClass } from '../host';-import { Draw } from '../../render/draw';-import { registerScopedDrawCallback, unregisterDrawCallback } from '../../render/customDraw';-import type { CppRegistry } from '../../wasm';-import { log } from '../../util/logger';+import { Schedule, defineSystem, addSystemToSchedule } from '../../ecs/system';+import { Res } from '../../ecs/resource';+import { MeshRenderer } from '../../ecs/component';+import { MeshRenderers, type MeshRendererAPI } from '../../render/meshRenderer';+import { buildPathGeometry, mergeGeometry, type LineCap, type LineJoin, type PathColor } from '../../render/vectorPath';+import type { MeshRendererGeometry } from '../../ecs/component';interface Subpath {points: Vec2[];closed: boolean;- /** Set when the subpath is exactly a rectangle or a circle, which can be filled. */- shape?: { kind: 'rect'; x: number; y: number; w: number; h: number } | { kind: 'circle'; x: number; y: number; r: number };}interface Op {kind: 'stroke' | 'fill';paths: Subpath[];- color: Color;+ color: PathColor;width: number;+ join: LineJoin;+ cap: LineCap;+ miterLimit: number;}const SEGMENTS_PER_CURVE = 16;-let ids = 0;+const JOINS: LineJoin[] = ['bevel', 'round', 'miter'];+const CAPS: LineCap[] = ['butt', 'round', 'square'];-const toEngine = (c: Color): { r: number; g: number; b: number; a: number } => ({ r: c.r / 255, g: c.g / 255, b: c.b / 255, a: c.a / 255 });+const toColor = (c: Color): PathColor => [c.r / 255, c.g / 255, c.b / 255, c.a / 255];++/** The engine's geometry API, handed over by the frame (a component has no app to ask). */+let meshApi: MeshRendererAPI | null = null;export class Graphics extends Component {static readonly LineJoin = Object.freeze({ BEVEL: 0, ROUND: 1, MITER: 2 });@@ -51,16 +58,19 @@ export class Graphics extends Component {private cursor_: Vec2 | null = null;private drawn_ = false;private ops_: Op[] = [];- private callback_: string | null = null;- private warned_ = false;+ private dirty_ = false;// ---- building a path ---------------------------------------------------------------------------------------------- private current_(): Subpath {- // A path begun after something was drawn is a new one: the earlier shapes are on the canvas, not in the path.+ /** A path begun after something was drawn is a new one: the earlier shapes are on the canvas, not in the path. */+ private fresh_(): void {if (this.drawn_) { this.path_ = []; this.drawn_ = false; }+ }++ private current_(): Subpath {+ this.fresh_();let sub = this.path_[this.path_.length - 1];- if (!sub || sub.closed || sub.shape) {+ if (!sub || sub.closed) {sub = { points: this.cursor_ ? [this.cursor_] : [], closed: false };this.path_.push(sub);}@@ -68,7 +78,7 @@ export class Graphics extends Component {}moveTo(x: number, y: number): void {- if (this.drawn_) { this.path_ = []; this.drawn_ = false; }+ this.fresh_();this.cursor_ = new Vec2(x, y);this.path_.push({ points: [this.cursor_], closed: false });}@@ -114,19 +124,19 @@ export class Graphics extends Component {this.cursor_ = sub.points[sub.points.length - 1]!;}- private shape_(points: Vec2[], shape: Subpath['shape']): void {- if (this.drawn_) { this.path_ = []; this.drawn_ = false; }- this.path_.push({ points, closed: true, shape });+ private closedShape_(points: Vec2[]): void {+ this.fresh_();+ this.path_.push({ points, closed: true });this.cursor_ = points[0] ?? null;}rect(x: number, y: number, w: number, h: number): void {- this.shape_([new Vec2(x, y), new Vec2(x + w, y), new Vec2(x + w, y + h), new Vec2(x, y + h)], { kind: 'rect', x, y, w, h });+ this.closedShape_([new Vec2(x, y), new Vec2(x + w, y), new Vec2(x + w, y + h), new Vec2(x, y + h)]);}- /** A rounded rectangle is drawn as its outline of arcs, and filled as the rectangle it rounds: the engine fills no rounded corner here. */roundRect(x: number, y: number, w: number, h: number, r: number): void {const radius = Math.min(Math.abs(r), Math.abs(w) / 2, Math.abs(h) / 2);+ if (radius === 0) { this.rect(x, y, w, h); return; }const pts: Vec2[] = [];const corner = (cx: number, cy: number, from: number): void => {for (let i = 0; i <= 8; i++) {@@ -138,7 +148,7 @@ export class Graphics extends Component {corner(x + w - radius, y + h - radius, 0);corner(x + radius, y + h - radius, Math.PI / 2);corner(x + radius, y + radius, Math.PI);- this.shape_(pts, radius === 0 ? { kind: 'rect', x, y, w, h } : undefined);+ this.closedShape_(pts);}fillRect(x: number, y: number, w: number, h: number): void {@@ -146,37 +156,39 @@ export class Graphics extends Component {this.fill();}- circle(cx: number, cy: number, r: number): void {- const pts: Vec2[] = [];- for (let i = 0; i < 48; i++) pts.push(new Vec2(cx + Math.cos((i / 48) * Math.PI * 2) * r, cy + Math.sin((i / 48) * Math.PI * 2) * r));- this.shape_(pts, { kind: 'circle', x: cx, y: cy, r });- }+ circle(cx: number, cy: number, r: number): void { this.ellipse(cx, cy, r, r); }ellipse(cx: number, cy: number, rx: number, ry: number): void {+ const n = Math.max(24, Math.min(96, Math.ceil(Math.max(Math.abs(rx), Math.abs(ry)) / 2)));const pts: Vec2[] = [];- for (let i = 0; i < 48; i++) pts.push(new Vec2(cx + Math.cos((i / 48) * Math.PI * 2) * rx, cy + Math.sin((i / 48) * Math.PI * 2) * ry));- this.shape_(pts, rx === ry ? { kind: 'circle', x: cx, y: cy, r: rx } : undefined);+ for (let i = 0; i < n; i++) pts.push(new Vec2(cx + Math.cos((i / n) * Math.PI * 2) * rx, cy + Math.sin((i / n) * Math.PI * 2) * ry));+ this.closedShape_(pts);}close(): void {const sub = this.path_[this.path_.length - 1];- if (sub && !sub.shape) { sub.closed = true; this.cursor_ = sub.points[0] ?? null; }+ if (sub) { sub.closed = true; this.cursor_ = sub.points[0] ?? null; }}// ---- painting it ---------------------------------------------------------------------------------------------------private snapshot_(): Subpath[] {- return this.path_.filter((p) => p.points.length > 0).map((p) => ({ ...p, points: p.points.map((v) => v.clone()) }));+ return this.path_.filter((p) => p.points.length > 0).map((p) => ({ closed: p.closed, points: p.points.map((v) => v.clone()) }));}stroke(): void {- this.ops_.push({ kind: 'stroke', paths: this.snapshot_(), color: this.strokeColor.clone(), width: this.lineWidth });+ this.ops_.push({+ kind: 'stroke', paths: this.snapshot_(), color: toColor(this.strokeColor), width: this.lineWidth,+ join: JOINS[this.lineJoin] ?? 'miter', cap: CAPS[this.lineCap] ?? 'butt', miterLimit: this.miterLimit,+ });this.drawn_ = true;+ this.dirty_ = true;}fill(): void {- this.ops_.push({ kind: 'fill', paths: this.snapshot_(), color: this.fillColor.clone(), width: 0 });+ this.ops_.push({ kind: 'fill', paths: this.snapshot_(), color: toColor(this.fillColor), width: 0, join: 'miter', cap: 'butt', miterLimit: 4 });this.drawn_ = true;+ this.dirty_ = true;}clear(): void {@@ -184,57 +196,100 @@ export class Graphics extends Component {this.path_ = [];this.cursor_ = null;this.drawn_ = false;+ this.dirty_ = true;}- // ---- into the frame --------------------------------------------------------------------------------------------------+ // ---- into the engine -------------------------------------------------------------------------------------------------- onEnable(): void {- const registry = this._world.getCppRegistry() as CppRegistry | null;- if (!registry || this.callback_) return;- this.callback_ = `cocos-graphics:${++ids}`;- registerScopedDrawCallback(this.callback_, registry, () => this.paint_());+ update(): void {+ if (this.dirty_ && meshApi) this.upload_(meshApi);}onDisable(): void {- if (this.callback_) unregisterDrawCallback(this.callback_);- this.callback_ = null;- }-- private paint_(): void {- if (this.ops_.length === 0) return;- const node = this.node;- const p = node.worldPosition, s = node.worldScale, q = node.worldRotation;- // the node's turn about Z, which is all a drawing on a flat scene has- const angle = 2 * Math.atan2(q.z, q.w);- const cos = Math.cos(angle), sin = Math.sin(angle);- const place = (v: Vec2): { x: number; y: number } => {- const x = v.x * s.x, y = v.y * s.y;- return { x: p.x + x * cos - y * sin, y: p.y + x * sin + y * cos };- };- const scale = (Math.abs(s.x) + Math.abs(s.y)) / 2;+ // a Graphics that is off draws nothing; its picture is kept and comes back when it is on+ meshApi?.clearGeometry(this.node._entity);+ this.dirty_ = true;+ }++ private upload_(api: MeshRendererAPI): void {+ this.dirty_ = false;+ putGeometry(this, api, this.geometry());+ }++ /** What the recorded drawing is as geometry, in this node's own space. */+ geometry(): MeshRendererGeometry {+ const parts: MeshRendererGeometry[] = [];for (const op of this.ops_) {- const color = toEngine(op.color);- if (color.a <= 0) continue;for (const sub of op.paths) {- if (op.kind === 'stroke') {- const pts = sub.points.map(place);- const thickness = Math.max(op.width * scale, 1);- for (let i = 1; i < pts.length; i++) Draw.line(pts[i - 1]!, pts[i]!, color, thickness);- if (sub.closed && pts.length > 2) Draw.line(pts[pts.length - 1]!, pts[0]!, color, thickness);- } else if (sub.shape?.kind === 'rect' && Math.abs(angle) < 1e-4) {- const a = place(new Vec2(sub.shape.x, sub.shape.y)), b = place(new Vec2(sub.shape.x + sub.shape.w, sub.shape.y + sub.shape.h));- Draw.rect({ x: Math.min(a.x, b.x), y: Math.min(a.y, b.y) }, { x: Math.abs(b.x - a.x), y: Math.abs(b.y - a.y) }, color, true);- } else if (sub.shape?.kind === 'circle') {- Draw.circle(place(new Vec2(sub.shape.x, sub.shape.y)), sub.shape.r * scale, color, true, 32);- } else if (!this.warned_) {- this.warned_ = true;- log.warn('cocos', `Graphics.fill() of a path that is not a rectangle or a circle is not drawn (${this.node.name})`);+ const points = sub.points;+ if (op.kind === 'fill') {+ if (points.length >= 3) parts.push(buildPathGeometry(points, { fill: { color: op.color }, closed: true }));+ } else if (points.length >= 2) {+ parts.push(buildPathGeometry(points, {+ stroke: { color: op.color, width: op.width, join: op.join, cap: op.cap, miterLimit: op.miterLimit }, closed: sub.closed,+ }));}}}+ return mergeGeometry(parts);+ }+}++/** Give a component's node the geometry as its mesh, or take its mesh away when there is none. */+function putGeometry(component: Component, api: MeshRendererAPI, geometry: MeshRendererGeometry): void {+ const entity = component.node._entity;+ if (geometry.indices.length === 0) { api.clearGeometry(entity); return; }+ if (!component._world.has(entity, MeshRenderer)) component._world.insert(entity, MeshRenderer, { enabled: true });+ api.setGeometry(entity, geometry);+}++// ---------------------------------------------------------------------------------------------------------------------+// Line+// ---------------------------------------------------------------------------------------------------------------------++/** `Line`: a polyline of a width and a colour. Its points are the world's (`worldSpace`) or the node's own. */+export class Line extends Component {+ private positions_: Array<{ x: number; y: number; z: number }> = [];+ worldSpace = true;+ width = 1;+ color: Color = new Color(255, 255, 255, 255);+ private dirty_ = true;++ get positions(): Array<{ x: number; y: number; z: number }> { return this.positions_; }+ set positions(value: Array<{ x: number; y: number; z: number }>) { this.positions_ = value; this.dirty_ = true; }++ update(): void {+ if (!this.dirty_ || !meshApi) return;+ this.dirty_ = false;+ putGeometry(this, meshApi, this.geometry());+ }++ onDisable(): void {+ meshApi?.clearGeometry(this.node._entity);+ this.dirty_ = true;+ }++ /** The polyline as geometry in the node's space: a world-space line is carried back through the node's place. */+ geometry(): MeshRendererGeometry {+ if (this.positions_.length < 2) return { positions: [], colors: [], indices: [] };+ let points: Vec2[] = this.positions_.map((p) => new Vec2(p.x, p.y));+ if (this.worldSpace) {+ const node = this.node;+ const p = node.worldPosition, s = node.worldScale, q = node.worldRotation;+ const angle = 2 * Math.atan2(q.z, q.w);+ const cos = Math.cos(-angle), sin = Math.sin(-angle);+ points = points.map((v) => {+ const x = v.x - p.x, y = v.y - p.y;+ return new Vec2((x * cos - y * sin) / (s.x || 1), (x * sin + y * cos) / (s.y || 1));+ });+ }+ return buildPathGeometry(points, { stroke: { color: toColor(this.color), width: this.width, join: 'round', cap: 'butt' } });}}+/** Test seam: the geometry API the frame would hand over. */+export function setGraphicsMeshApi(api: MeshRendererAPI | null): void { meshApi = api; }+export function declareGraphics(): void {declareClass(Graphics as never, 'Graphics', [{ name: 'lineWidth', kind: 'number' },@@ -244,4 +299,16 @@ export function declareGraphics(): void {{ name: 'strokeColor', kind: 'color' },{ name: 'fillColor', kind: 'color' },]);+ declareClass(Line as never, 'Line', [+ { name: 'worldSpace', kind: 'boolean' },+ { name: 'width', kind: 'number' },+ { name: 'color', kind: 'color' },+ { name: 'positions', kind: 'json' },+ ]);+ // The geometry API lives on the app; a component has no way to ask for it, so a system hands it over each frame.+ addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(MeshRenderers)],+ (api) => { if (api) meshApi = api; },+ { name: 'Cocos:GraphicsApi', touches: { opaque: true } },+ ));}diff --git a/sdk/src/cocos/ui/index.ts b/sdk/src/cocos/ui/index.tsindex 2986eb8c3..48fe4d61c 100644--- a/sdk/src/cocos/ui/index.ts+++ b/sdk/src/cocos/ui/index.ts@@ -16,5 +16,5 @@ export { getVisibleSize, setVisibleSize } from './screen';export { Camera } from './camera';export { RichText } from './richText';export { Mask } from './mask';-export { Graphics } from './graphics';+export { Graphics, Line } from './graphics';export { EditBox } from './editBox';diff --git a/sdk/tests/cocos/graphics-wasm.test.ts b/sdk/tests/cocos/graphics-wasm.test.tsindex 4922babf9..bf7fc581c 100644--- a/sdk/tests/cocos/graphics-wasm.test.ts+++ b/sdk/tests/cocos/graphics-wasm.test.ts@@ -1,112 +1,160 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file Graphics: a script draws a path and keeps it until `clear()`; each frame it is played into the engine's `Draw`, in the node's place.+ * @file Graphics: a script draws a path and keeps it until `clear()`; it becomes the geometry of the node's own mesh renderer, in the node's space.*/-import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';import type { ESEngineModule } from '../../src/wasm';-import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';-import { Color, Graphics, Node, Vec3 } from '../../src/cocos';-import { clearDrawCallbacks, getDrawCallbacks } from '../../src/render/customDraw';+import { MeshRenderer, Transform, ensureBuiltinComponentsRegistered, type MeshRendererGeometry } from '../../src/ecs/component';+import type { MeshRendererAPI } from '../../src/render/meshRenderer';+import { Color, Graphics, Line, Node, Vec3 } from '../../src/cocos';+import { setGraphicsMeshApi } from '../../src/cocos/ui/graphics';import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';import { pointerApp, type PointerApp } from './helpers/pointerApp';-const calls: Array<{ op: string; args: any[] }> = [];-vi.mock('../../src/render/draw', () => ({- Draw: new Proxy({}, { get: (_t, op: string) => (...args: unknown[]) => { calls.push({ op, args }); } }),-}));+/** The geometry API, recording what a Graphics hands it. */+class FakeMeshApi {+ geometry = new Map<number, MeshRendererGeometry>();+ setGeometry(entity: number, g: MeshRendererGeometry): void { this.geometry.set(entity, g); }+ clearGeometry(entity: number): void { this.geometry.delete(entity); }+}describe.skipIf(!HAS_WASM)('Graphics', () => {let module: ESEngineModule;let P: PointerApp | undefined;+ let api: FakeMeshApi;beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });- beforeEach(() => { calls.length = 0; });- afterEach(() => { clearDrawCallbacks(); P?.dispose(); P = undefined; });+ beforeEach(() => { api = new FakeMeshApi(); setGraphicsMeshApi(api as unknown as MeshRendererAPI); });+ afterEach(() => { setGraphicsMeshApi(null); P?.dispose(); P = undefined; });- async function graphics(x = 0, y = 0, scale = 1): Promise<{ node: Node; g: Graphics }> {+ async function graphics(): Promise<{ node: Node; g: Graphics }> {P = pointerApp(module);const node = new Node('g');P.app.world.insert(node._entity, Transform);- node.setPosition(x, y, 0);- node.setScale(new Vec3(scale, scale, 1));const g = node.addComponent<Graphics>('Graphics')!;await P.frame(1);return { node, g };}- /** Play the frame's draw callbacks, as the renderer does. */- const paint = (): void => { calls.length = 0; for (const entry of getDrawCallbacks().values()) entry.fn(); };+ const shown = (node: Node): MeshRendererGeometry | undefined => api.geometry.get(node._entity as number);+ const bounds = (g: MeshRendererGeometry) => {+ const xs = g.positions.filter((_, i) => i % 2 === 0), ys = g.positions.filter((_, i) => i % 2 === 1);+ return { minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys) };+ };- it('fills a rectangle where its node is', async () => {- const { g } = await graphics(100, 50);+ it('fills a rectangle as the triangles of its corners, in the fill colour, on the node\'s own mesh', async () => {+ const { node, g } = await graphics();g.fillColor = new Color(255, 0, 0, 255);- g.rect(0, 0, 20, 10);+ g.rect(10, 20, 30, 40);g.fill();- paint();- expect(calls).toHaveLength(1);- expect(calls[0]!.op).toBe('rect');- expect(calls[0]!.args[0]).toEqual({ x: 100, y: 50 });- expect(calls[0]!.args[1]).toEqual({ x: 20, y: 10 });- expect(calls[0]!.args[2]).toMatchObject({ r: 1, g: 0, b: 0, a: 1 });+ await P!.frame(1);+ const geometry = shown(node)!;+ expect(geometry.indices).toHaveLength(6);+ expect(bounds(geometry)).toEqual({ minX: 10, maxX: 40, minY: 20, maxY: 60 });+ expect(geometry.colors!.slice(0, 4)).toEqual([1, 0, 0, 1]);+ expect(P!.app.world.has(node._entity, MeshRenderer)).toBe(true);});- it('keeps what it drew until it is cleared, and draws it again every frame', async () => {- const { g } = await graphics();- g.circle(0, 0, 10);+ it('fills a path that is not a rectangle: a triangle, a rounded rectangle, a circle', async () => {+ const { node, g } = await graphics();+ g.moveTo(0, 0);+ g.lineTo(10, 0);+ g.lineTo(5, 8);+ g.close();g.fill();- paint();- paint();- expect(calls.map((c) => c.op)).toEqual(['circle']);+ await P!.frame(1);+ expect(shown(node)!.indices).toHaveLength(3);+g.clear();- paint();- expect(calls).toEqual([]);+ g.roundRect(0, 0, 40, 20, 6);+ g.fill();+ await P!.frame(1);+ expect(shown(node)!.indices.length).toBeGreaterThan(30);++ g.clear();+ g.circle(0, 0, 10);+ g.fill();+ await P!.frame(1);+ const b = bounds(shown(node)!);+ expect(b.maxX).toBeCloseTo(10, 4);+ expect(b.minY).toBeCloseTo(-10, 0);});- it('strokes a path as lines of the stroke colour and width, scaled with the node', async () => {- const { g } = await graphics(0, 0, 2);- g.lineWidth = 3;+ it('strokes a path at the line width, in the stroke colour', async () => {+ const { node, g } = await graphics();+ g.lineWidth = 4;g.strokeColor = new Color(0, 255, 0, 255);g.moveTo(0, 0);- g.lineTo(10, 0);- g.lineTo(10, 10);+ g.lineTo(100, 0);g.stroke();- paint();- expect(calls.map((c) => c.op)).toEqual(['line', 'line']);- expect(calls[0]!.args[1]).toEqual({ x: 20, y: 0 });- expect(calls[0]!.args[3]).toBe(6);- expect(calls[1]!.args[1]).toEqual({ x: 20, y: 20 });+ await P!.frame(1);+ const geometry = shown(node)!;+ const b = bounds(geometry);+ expect(b.maxX - b.minX).toBeGreaterThanOrEqual(100);+ expect(b.maxY - b.minY).toBeCloseTo(4, 4); // butt caps: as wide as the line+ expect(geometry.colors!.slice(0, 4)).toEqual([0, 1, 0, 1]);});- it('closes a path back to its start', async () => {- const { g } = await graphics();+ it('rounds the ends of a stroke when the cap is round', async () => {+ const { node, g } = await graphics();+ g.lineWidth = 10;+ g.lineCap = Graphics.LineCap.ROUND;g.moveTo(0, 0);- g.lineTo(10, 0);- g.lineTo(0, 10);- g.close();+ g.lineTo(100, 0);g.stroke();- paint();- expect(calls).toHaveLength(3);+ await P!.frame(1);+ const b = bounds(shown(node)!);+ expect(b.minX).toBeCloseTo(-5, 1); // the cap is a round of short flat pieces+ expect(b.maxX).toBeCloseTo(105, 1);});- it('starts a new path after something was drawn, so earlier shapes are not drawn again', async () => {- const { g } = await graphics();+ it('keeps what was drawn until it is cleared, and a path begun after a draw starts afresh', async () => {+ const { node, g } = await graphics();g.rect(0, 0, 5, 5);g.fill();g.rect(20, 0, 5, 5);g.fill();- paint();- expect(calls.map((c) => c.op)).toEqual(['rect', 'rect']);- expect(calls[1]!.args[0]).toEqual({ x: 20, y: 0 });+ await P!.frame(1);+ expect(shown(node)!.indices).toHaveLength(12); // two rectangles, the first not drawn a second time+ g.clear();+ await P!.frame(1);+ expect(shown(node)).toBeUndefined();});- it('stops drawing when it is disabled', async () => {- const { g } = await graphics();+ it('draws nothing while it is disabled and comes back when it is enabled', async () => {+ const { node, g } = await graphics();g.rect(0, 0, 5, 5);g.fill();+ await P!.frame(1);g.enabled = false;- await P!.frame(1); // the lifecycle runs with the frame- paint();- expect(calls).toEqual([]);+ await P!.frame(1);+ expect(shown(node)).toBeUndefined();+ g.enabled = true;+ await P!.frame(2);+ expect(shown(node)).toBeDefined();+ });++ it('draws a Line as a stroked polyline, carrying a world-space line back through its node', async () => {+ P = pointerApp(module);+ const node = new Node('line');+ P.app.world.insert(node._entity, Transform);+ node.setPosition(100, 50, 0);+ node.setScale(new Vec3(2, 2, 1));+ const line = node.addComponent<Line>('Line')!;+ line.width = 4;+ line.color = new Color(0, 0, 255, 255);+ line.worldSpace = true;+ line.positions = [{ x: 100, y: 50, z: 0 }, { x: 140, y: 50, z: 0 }]; // 40 along in the world: 20 in the node's own scaled space+ await P.frame(2);+ const geometry = api.geometry.get(node._entity as number)!;+ const b = bounds(geometry);+ expect(b.minX).toBeCloseTo(0, 3);+ expect(b.maxX).toBeCloseTo(20, 3);+ expect(geometry.colors!.slice(0, 4)).toEqual([0, 0, 1, 1]);+ line.worldSpace = false;+ line.positions = [{ x: 0, y: 0, z: 0 }, { x: 10, y: 0, z: 0 }];+ await P.frame(2);+ expect(bounds(api.geometry.get(node._entity as number)!).maxX).toBeCloseTo(10, 3);});});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 6c300712b..ee9364f37 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(cocos): BoxCollider maps to the engine box collider with a static body, Line is a component over the engine vector path, Graphics builds its mesh with it (polygon fills, joins and caps), and a sprite whose frame is missing stays, switched off':+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},'feat(cocos): EditBox is a component over the platform text editor (mode and length rules, hint, password bullets, the four editing events), and the importer maps it':{"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},'feat(cocos): Graphics is a component over the engine Draw (rect, circle and stroked paths kept until clear), UIMeshRenderer folds into its host, and a Node has worldScale and worldRotation':