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): cc.js, ccenum and NodePool exist in the compatibility layer
yhhc1aeb3625deb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 04fe83002..b0b77f222 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.+- **More of `cc`.** `js` (class names and lookup, `isChildClassOf`, `mixin`, `addon`, property definers), `ccenum` and `NodePool` (put a node away, get it back, with the handler component told `unuse` and `reuse`) are in the Cocos compatibility layer.- **The script bundle is not rebuilt for nothing.** The project-script bundle is stamped with every file it read (size and modification time) and the build tool that made it, and Play builds it again only when one of those changed: a project of thousands of scripts goes from a multi-second build at every Play to a check of a few hundred milliseconds.- **Two Cocos classes with one name.** Cocos tells classes apart by their script, so two scripts may write the same `@ccclass` name. The converted project gives the second its own component name (`Name_2`, in path order), writes which script that was beside the entry, and the bundler writes the new name into that script decorator.- **Large projects open faster.** The asset dependency scan no longer asks the path index about every string in every document (names, types and labels cannot be paths), which took the open of a 5000-document project from 17 s to under 5 s, and the Cocos script rewrite makes two passes over a file instead of one per declaration.diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.tsindex 7d7e302e8..bfd7157cd 100644--- a/sdk/src/cocos/index.ts+++ b/sdk/src/cocos/index.ts@@ -27,6 +27,7 @@ export {} from './assets';export { registerBuiltinComponent, type BuiltinAdapter } from './builtins';export { unsupported } from './unsupported';+export { ccenum, js, NodePool } from './misc';export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, Camera, RichText, Mask, Toggle, ToggleContainer, ProgressBar, Slider, BlockInputEvents, ScrollView, Graphics, Line, EditBox, PageView, PageViewIndicator, ScrollBar, SafeArea, WebView, getVisibleSize, setVisibleSize } from './ui';export { Touch, EventTouch } from './input';export { tween, Tween, tweenUtil, easing, updateTweens } from './tween';diff --git a/sdk/src/cocos/misc.ts b/sdk/src/cocos/misc.tsnew file mode 100644index 000000000..ec51f7e41--- /dev/null+++ b/sdk/src/cocos/misc.ts@@ -0,0 +1,101 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cocos/misc.ts+ * @brief Small parts of `cc` that need no engine behind them: `ccenum`, the `js` helpers and `NodePool`.+ */+import type { Component } from './component';+import type { Node } from './node';+import { classInfoNamed, classInfoOf } from './registry';++/** `ccenum(MyEnum)`: Cocos marks an enum so its inspector shows a dropdown. The layer's `@property` reads a TypeScript enum as it is. */+export function ccenum<T extends object>(enumObject: T): T {+ return enumObject;+}++/** The parts of `cc.js` scripts call: class names and lookup, and the property helpers. */+export const js = {+ /** The name a class or an instance's class goes by: the `@ccclass` name when it has one, else its own. */+ getClassName(objOrCtor: unknown): string {+ if (objOrCtor === null || objOrCtor === undefined) return '';+ const ctor = typeof objOrCtor === 'function' ? objOrCtor : (objOrCtor as { constructor?: Function }).constructor;+ if (!ctor) return '';+ return classInfoOf(ctor)?.name ?? ctor.name ?? '';+ },+ /** A script class by the name it was declared under. */+ getClassByName(name: string): Function | undefined {+ return classInfoNamed(name)?.ctor;+ },+ getSuper(ctor: Function): Function | undefined {+ const proto = Object.getPrototypeOf(ctor.prototype);+ return proto && proto.constructor !== Object ? proto.constructor : undefined;+ },+ isChildClassOf(subclass: Function | undefined, superclass: Function | undefined): boolean {+ if (!subclass || !superclass) return false;+ if (subclass === superclass) return true;+ for (let c: Function | undefined = js.getSuper(subclass); c; c = js.getSuper(c)) if (c === superclass) return true;+ return false;+ },+ /** Copy the properties of the sources onto the target, replacing what it has. */+ mixin<T extends object>(target: T, ...sources: object[]): T {+ for (const source of sources) for (const key of Object.getOwnPropertyNames(source)) {+ const descriptor = Object.getOwnPropertyDescriptor(source, key);+ if (descriptor) Object.defineProperty(target, key, descriptor);+ }+ return target;+ },+ /** Copy the properties of the sources the target does not have. */+ addon<T extends object>(target: T, ...sources: object[]): T {+ for (const source of sources) for (const key of Object.getOwnPropertyNames(source)) {+ if (key in target) continue;+ const descriptor = Object.getOwnPropertyDescriptor(source, key);+ if (descriptor) Object.defineProperty(target, key, descriptor);+ }+ return target;+ },+ value(object: object, name: string, value: unknown, writable = false, enumerable = false): void {+ Object.defineProperty(object, name, { value, writable, enumerable, configurable: true });+ },+ get(object: object, name: string, getter: () => unknown, enumerable = false): void {+ Object.defineProperty(object, name, { get: getter, enumerable, configurable: true });+ },+ getset(object: object, name: string, getter: () => unknown, setter?: (value: unknown) => void, enumerable = false): void {+ Object.defineProperty(object, name, { get: getter, set: setter, enumerable, configurable: true });+ },+};++/**+ * `NodePool`: nodes kept to be used again. `put` takes a node out of the scene and keeps it; `get` hands one back (or null when none is+ * kept). A node whose pool names a handler component is told `unuse()` as it goes in and `reuse(...args)` as it comes out.+ */+export class NodePool {+ private readonly nodes_: Node[] = [];++ constructor(private readonly handler_?: string | (abstract new () => Component)) {}++ size(): number {+ return this.nodes_.length;+ }++ clear(): void {+ for (const node of this.nodes_.splice(0)) node.destroy();+ }++ put(node: Node): void {+ if (!node || this.nodes_.includes(node)) return;+ node.removeFromParent();+ this.handler(node)?.unuse?.();+ this.nodes_.push(node);+ }++ get(...args: unknown[]): Node | null {+ const node = this.nodes_.pop() ?? null;+ if (node) this.handler(node)?.reuse?.(args);+ return node;+ }++ private handler(node: Node): { unuse?(): void; reuse?(args: unknown[]): void } | null {+ if (!this.handler_) return null;+ return node.getComponent(this.handler_ as never) as unknown as { unuse?(): void; reuse?(args: unknown[]): void } | null;+ }+}diff --git a/sdk/tests/cocos/misc.test.ts b/sdk/tests/cocos/misc.test.tsnew file mode 100644index 000000000..ae665821c--- /dev/null+++ b/sdk/tests/cocos/misc.test.ts@@ -0,0 +1,72 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { NodePool, ccenum, js } from '../../src/cocos/misc';+import type { Node } from '../../src/cocos/node';++/** The parts of a node a pool touches. */+function fakeNode(handler?: { unuse(): void; reuse(args: unknown[]): void }) {+ const log: string[] = [];+ const node = {+ removeFromParent: () => log.push('removed'),+ destroy: () => { log.push('destroyed'); return true; },+ getComponent: () => handler ?? null,+ };+ return { node: node as unknown as Node, log };+}++describe('NodePool', () => {+ it('keeps what is put in, hands it back newest first, and says null when empty', () => {+ const pool = new NodePool();+ const a = fakeNode(), b = fakeNode();+ pool.put(a.node);+ pool.put(b.node);+ pool.put(b.node); // the same node is not kept twice+ expect(pool.size()).toBe(2);+ expect(a.log).toEqual(['removed']);+ expect(pool.get()).toBe(b.node);+ expect(pool.get()).toBe(a.node);+ expect(pool.get()).toBeNull();+ });++ it('tells a handler component it is put away and brought back', () => {+ const calls: string[] = [];+ const handler = { unuse: () => calls.push('unuse'), reuse: (args: unknown[]) => calls.push(`reuse ${args.join(',')}`) };+ const pool = new NodePool('Bullet');+ pool.put(fakeNode(handler).node);+ pool.get(1, 2);+ expect(calls).toEqual(['unuse', 'reuse 1,2']);+ });++ it('destroys what it holds when cleared', () => {+ const pool = new NodePool();+ const a = fakeNode();+ pool.put(a.node);+ pool.clear();+ expect(pool.size()).toBe(0);+ expect(a.log).toContain('destroyed');+ });+});++describe('js and ccenum', () => {+ it('names a class and its instances, and knows a subclass', () => {+ class Base { }+ class Child extends Base { }+ expect(js.getClassName(Child)).toBe('Child');+ expect(js.getClassName(new Child())).toBe('Child');+ expect(js.getClassName(null)).toBe('');+ expect(js.isChildClassOf(Child, Base)).toBe(true);+ expect(js.isChildClassOf(Base, Child)).toBe(false);+ expect(js.getSuper(Child)).toBe(Base);+ });++ it('mixes in everything, or only what is missing', () => {+ expect(js.mixin({ a: 1 }, { a: 2, b: 3 })).toEqual({ a: 2, b: 3 });+ expect(js.addon({ a: 1 }, { a: 2, b: 3 })).toEqual({ a: 1, b: 3 });+ });++ it('hands an enum back as it is', () => {+ enum Mode { A, B }+ expect(ccenum(Mode)).toBe(Mode);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 171431788..1b0195b18 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): cc.js, ccenum and NodePool exist in the compatibility layer':+ {"note":"More of cc."},'feat(bundle): the project script bundle is built again only when a file it read changed, and Cocos scripts that write the same class name each get a component of their own':{"note":"The script bundle is not rebuilt for nothing."},'fix(editor): opening a large project no longer spends seconds on strings that cannot be paths, a model texture the project lacks is left off instead of dangling, and an unlit mesh variant with tangents links':