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): PageView, PageViewIndicator, ScrollBar, SafeArea and WebView components, and the importer maps SpriteRenderer, Spine skeletons, ParticleSystem2D, Terrain and the players and animators whose clip or graph is missing
yhh8cc310d6b9cb
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.tsindex 72b53bfcf..187c590bc 100644--- a/pipeline/src/import/cocos/components.ts+++ b/pipeline/src/import/cocos/components.ts@@ -12,7 +12,8 @@* 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 { curveRange, particleSystem } from './particle';+import { readFileSync } from 'node:fs';+import { curveRange, particleSystem, particleSystem2D } from './particle';import type { CocosAssetEntry, CocosAssetIndex } from './assets';import { type CocosComponent, type CocosNode } from './document';import type { ImportReport } from './report';@@ -72,6 +73,8 @@ export interface ComponentContext {* project's. A graph that plays clips of a model is written once for each skeleton it is put on.*/animatorController?(graphUuid: string, paths: Map<string, string>, where: string): { ref: string; complete: boolean } | null;+ /** The skeleton and atlas files of a Spine data asset, copied into the project (project-relative), or null when the project does not have them. */+ spineAssets?(uuid: string): { skeleton: string; atlas: string } | null;/** The timeline a Cocos `.anim` clip is converted to (project-relative), or null when the clip is not one of the project's. */animationClip?(clipUuid: string, where: string): string | null;/** The joints, by name, a skinned part of a model is bound to, in the order its vertices index them. */@@ -130,7 +133,7 @@ function uiBox(node: CocosNode): UiBox | null {return { width: num(s.width, 100), height: num(s.height, 100), ax: num(a.x, 0.5), ay: num(a.y, 0.5) };}-function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, where: string): ComponentData | null {+function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, where: string, as: 'cc.Sprite' | 'cc.SpriteRenderer' = 'cc.Sprite'): ComponentData | null {const frameUuid = uuidOf(c.data._spriteFrame);const data: Raw = { color: color(c.data._color), enabled: c.enabled };if (box) {@@ -138,7 +141,7 @@ function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, whedata.pivot = { x: box.ax, y: box.ay };}if (!frameUuid) {- ctx.report.component('cc.Sprite', 'partial');+ ctx.report.component(as, 'partial');ctx.report.note('sprite-no-frame', where);return { type: 'Sprite', data };}@@ -147,7 +150,7 @@ function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, wheif (!entry || !sub || entry.importer !== 'image' || sub.importer !== 'sprite-frame') {// 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.component(as, 'partial');ctx.report.note(entry ? 'sprite-frame-not-from-image' : 'sprite-frame-missing', where);if (!entry) ctx.report.missingAsset(frameUuid);return { type: 'Sprite', data: { ...data, enabled: false } };@@ -197,7 +200,7 @@ function sprite(c: CocosComponent, box: UiBox | null, ctx: ComponentContext, whestatus = 'partial';ctx.report.note('sprite-grayscale', where);}- ctx.report.component('cc.Sprite', status);+ ctx.report.component(as, status);return { type: 'Sprite', data };}@@ -521,7 +524,12 @@ function animation(c: CocosComponent, node: CocosNode, ctx: ComponentContext, whconst wanted = uuidOf(c.data._defaultClip) || clips[0] || '';// a clip of the project's own, or one that lives in a model file and animates the bones below this nodeconst ref = wanted ? ctx.animationClip?.(wanted, where) ?? ctx.clipOn?.(wanted, namePaths(node, ctx), where) : null;- if (!ref) return null;+ if (!ref) {+ ctx.report.note(wanted ? 'animation-clip-not-found' : 'animation-no-clip', `${where}: ${wanted}`);+ // no clip yet (a script gives it one), or one the project does not have: the player stays, empty, so a script that sets a clip finds it+ ctx.report.component('cc.Animation', wanted ? 'partial' : 'mapped');+ return { type: 'TimelinePlayer', data: { timeline: '', playing: false, speed: 1, wrapMode: '' } };+ }if (clips.length > 1) ctx.report.note('animation-several-clips', where);ctx.report.component('cc.Animation', clips.length > 1 ? 'partial' : 'mapped');return { type: 'TimelinePlayer', data: { timeline: ref, playing: c.data.playOnLoad === true, speed: 1, wrapMode: '' } };@@ -531,7 +539,12 @@ function animation(c: CocosComponent, node: CocosNode, ctx: ComponentContext, whfunction animationController(c: CocosComponent, node: CocosNode, ctx: ComponentContext, where: string): ComponentData | null {const graph = uuidOf(c.data._graph) || uuidOf(c.data.graph);const made = graph ? ctx.animatorController?.(graph, namePaths(node, ctx), where) : null;- if (!made) return null;+ if (!made) {+ // a graph the project does not have: the Animator stays with no controller, for a script that sets one+ ctx.report.note('animator-graph-not-found', `${where}: ${graph}`);+ ctx.report.component('cc.animation.AnimationController', 'partial');+ return { type: 'Animator', data: { controller: '', enabled: c.enabled } };+ }ctx.report.component('cc.animation.AnimationController', made.complete ? 'mapped' : 'partial');return { type: 'Animator', data: { controller: made.ref, enabled: c.enabled } };}@@ -541,7 +554,12 @@ function skeletalAnimation(c: CocosComponent, node: CocosNode, ctx: ComponentConconst clips = (Array.isArray(c.data._clips) ? c.data._clips : []).map(uuidOf).filter(Boolean);const wanted = uuidOf(c.data._defaultClip) || clips[0] || '';const ref = wanted ? ctx.clipOn?.(wanted, namePaths(node, ctx), where) : null;- if (!ref) return null;+ if (!ref) {+ // no clip, or one this node has no bones for: the player stays, empty, for a script that gives it one+ ctx.report.note(wanted ? 'skeletal-clip-not-found' : 'skeletal-no-clip', `${where}: ${wanted}`);+ ctx.report.component('cc.SkeletalAnimation', wanted ? 'partial' : 'mapped');+ return { type: 'TimelinePlayer', data: { timeline: '', playing: false, speed: 1, wrapMode: '' } };+ }if (clips.length > 1) ctx.report.note('animation-several-clips', where);ctx.report.component('cc.SkeletalAnimation', clips.length > 1 ? 'partial' : 'mapped');return { type: 'TimelinePlayer', data: { timeline: ref, playing: c.data.playOnLoad === true, speed: 1, wrapMode: '' } };@@ -607,8 +625,12 @@ function meshRenderer(c: CocosComponent, ctx: ComponentContext, where: string):}const found = meshUuid ? ctx.modelMesh?.(meshUuid) : null;if (!found) {+ // The renderer stays, with no mesh: a script that assigns one finds the component, and a mesh the project does not have draws nothing in+ // Cocos either. A renderer that never had a mesh lost nothing; one whose mesh is missing did.ctx.report.note(meshUuid ? 'mesh-model-part-not-found' : 'mesh-none', `${where}: ${meshUuid}`);- return null;+ const data: Raw = { enabled: c.enabled };+ const applied = applyMaterial(data, c, ctx, where);+ return { component: { type: 'MeshRenderer', data }, partial: meshUuid !== '' || !applied.exact && hasMaterial };}const materials = (Array.isArray(c.data._materials) ? c.data._materials : []).map(uuidOf).filter(Boolean);let partial = false;@@ -660,6 +682,32 @@ function line(c: CocosComponent, ctx: ComponentContext, where: string): Componen};}+/** `sp.Skeleton`: a Spine skeleton, played from its default animation. The skeleton, its atlas and the atlas's images come with it. */+function spineSkeleton(c: CocosComponent, ctx: ComponentContext, where: string): ComponentData | null {+ const d = c.data;+ const files = ctx.spineAssets?.(uuidOf(d._skeletonData));+ if (!files) {+ ctx.report.note('spine-data-missing', where);+ return null;+ }+ const animation = typeof d.defaultAnimation === 'string' ? d.defaultAnimation : '';+ ctx.report.component('sp.Skeleton', 'mapped');+ return {+ type: 'SpineAnimation',+ data: {+ skeletonPath: files.skeleton,+ atlasPath: files.atlas,+ skin: typeof d.defaultSkin === 'string' ? d.defaultSkin : 'default',+ animation,+ timeScale: num(d._timeScale, 1),+ loop: d.loop !== false,+ playing: animation !== '',+ color: color(d._color),+ enabled: c.enabled,+ },+ };+}+/*** `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@@ -680,6 +728,41 @@ function boxCollider(c: CocosComponent, node: CocosNode, ctx: ComponentContext,return { type: 'BoxCollider3D', data: { halfExtents: { x: half('x'), y: half('y'), z: half('z') }, isSensor: c.data._isTrigger === true, enabled: c.enabled } };}+/** `cc.PageView`: a scroll view whose content is pages, and the page it settles on. */+function pageView(c: CocosComponent, ctx: ComponentContext): ComponentData {+ const scroll = scrollView(c, ctx).data;+ const direction = num(c.data._direction, 0);+ return {+ type: `${LAYER}PageView`,+ data: {+ ...scroll,+ ...renamed(c, { _sizeMode: 'sizeMode', _direction: 'direction', autoPageTurningThreshold: 'autoPageTurningThreshold', pageTurningSpeed: 'pageTurningSpeed', _indicator: 'indicator' }),+ horizontal: direction === 0,+ vertical: direction === 1,+ ...handlerLists(c.data.pageEvents, 'page', ctx),+ },+ };+}++/** `cc.Terrain`: the ground's size, from the header of the terrain file. The heights and the painted layers inside it are not read. */+function terrain(c: CocosComponent, ctx: ComponentContext, where: string): ComponentData | null {+ const asset = uuidOf(c.data.__asset);+ const entry = asset ? ctx.assets.byUuid.get(asset) : undefined;+ let size = 256;+ if (entry) {+ try {+ const head = readFileSync(entry.file).subarray(0, 20);+ const tile = head.readDoubleLE(4), blocksX = head.readInt32LE(12), blocksY = head.readInt32LE(16);+ if (tile > 0 && blocksX > 0 && blocksY > 0 && blocksX < 256 && blocksY < 256) size = Math.max(blocksX, blocksY) * 64 * tile;+ } catch {+ // an unreadable file keeps the default size and is counted below+ }+ }+ ctx.report.component('cc.Terrain', 'partial');+ ctx.report.note('terrain-heights-not-carried', where);+ return { type: 'Terrain', data: { extent: 0, sizeX: size, sizeZ: size, height: 0, collision: false } };+}+/** `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 {@@ -726,7 +809,7 @@ function script(c: CocosComponent, ctx: ComponentContext): ComponentData | null}/** Components that are folded into another, or carry nothing of their own. */-const FOLDED = new Set(['cc.UITransform', 'cc.LabelOutline', 'cc.LabelShadow', 'cc.Canvas', 'cc.UIMeshRenderer']);+const FOLDED = new Set(['cc.UITransform', 'cc.LabelOutline', 'cc.LabelShadow', 'cc.Canvas', 'cc.UIMeshRenderer', 'cc.RenderRoot2D']);export interface ConvertedNode {components: ComponentData[];@@ -752,6 +835,13 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strincase 'cc.Sprite':out = sprite(c, box, ctx, where);break;+ case 'cc.SpriteRenderer': {+ // a sprite standing in the 3D world: the same picture and tint, with no rectangle of its own, so the frame's size is the size+ out = sprite({ ...c, data: { ...c.data, _type: 0 } }, null, ctx, where, 'cc.SpriteRenderer');+ if (out && c.data._flipX === true) out.data.flipX = true;+ if (out && c.data._flipY === true) out.data.flipY = true;+ break;+ }case 'cc.Label':out = label(c, node.components, box, ctx, where);break;@@ -820,12 +910,36 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strincase 'cc.SkeletalAnimation':out = skeletalAnimation(c, node, ctx, where);break;+ case 'sp.Skeleton':+ out = spineSkeleton(c, 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.PageView':+ out = pageView(c, ctx);+ break;+ case 'cc.PageViewIndicator':+ out = { type: `${LAYER}PageViewIndicator`, data: { ...renamed(c, { spacing: 'spacing', _direction: 'direction' }), cellSize: isObj(c.data._cellSize) ? { width: num(c.data._cellSize.width, 20), height: num(c.data._cellSize.height, 20) } : { width: 20, height: 20 } } };+ break;+ case 'cc.ScrollBar':+ out = { type: `${LAYER}ScrollBar`, data: renamed(c, { _scrollView: 'scrollView', _handle: 'handle', _direction: 'direction', _enableAutoHide: 'enableAutoHide', _autoHideTime: 'autoHideTime' }) };+ break;+ case 'cc.SafeArea':+ out = { type: `${LAYER}SafeArea`, data: { enabled: c.enabled } };+ break;+ case 'cc.WebView':+ out = { type: `${LAYER}WebView`, data: { enabled: c.enabled, url: typeof c.data._url === 'string' ? c.data._url : '', ...handlerLists(c.data.webviewEvents, 'webview', ctx) } };+ break;+ case 'cc.ParticleSystem2D':+ out = particleSystem2D(c, { report: ctx.report, assetRef: ctx.assetRef, frame: (uuid) => { const e = ctx.assets.byUuid.get(uuid.split('@')[0]!); return e ? ctx.assetRef(e) : null; } }, where);+ break;+ case 'cc.Terrain':+ out = terrain(c, ctx, where);+ break;case 'cc.EditBox':out = editBox(c, ctx);break;@@ -852,7 +966,7 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strin}if (FOLDED.has(c.type)) {// A canvas carries nothing of its own here: the design resolution is the scene's, and its camera is a component of its own.- const host = c.type === 'cc.UITransform' || c.type === 'cc.Canvas' || c.type === 'cc.UIMeshRenderer' ? true : node.components.some((s) => s.type === 'cc.Label');+ const host = c.type === 'cc.UITransform' || c.type === 'cc.Canvas' || c.type === 'cc.UIMeshRenderer' || c.type === 'cc.RenderRoot2D' ? true : node.components.some((s) => s.type === 'cc.Label');if (host) {ctx.report.component(c.type, 'mapped');continue;diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsindex d65bd2a53..f6830ea56 100644--- a/pipeline/src/import/cocos/importProject.ts+++ b/pipeline/src/import/cocos/importProject.ts@@ -133,6 +133,7 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impoconst models = new CocosModels(index, out, into, opts.dryRun === true);const clips = new Map<string, string | null>();+ const spines = new Map<string, { skeleton: string; atlas: string } | null>();const scripts = buildScriptIndex(index);/** The scripts a converted document refers to, which the project has to bundle for those components to exist. */const usedScripts = new Set<string>();@@ -176,6 +177,38 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impoif (own) return own;return m.use.skin.size === 1 ? [...m.use.skin.values()][0]! : null;},+ spineAssets(uuid) {+ const entry = index.byUuid.get(uuid);+ if (!entry || !/\.(skel|json)$/i.test(entry.rel)) return null;+ const key = entry.file;+ if (spines.has(key)) return spines.get(key) ?? null;+ let found: { skeleton: string; atlas: string } | null = null;+ try {+ const dir = path.dirname(entry.file);+ const stem = path.basename(entry.file).replace(/\.[^.]+$/, '');+ const atlasFile = readdirSync(dir).find((f) => f.toLowerCase() === `${stem.toLowerCase()}.atlas`) ?? readdirSync(dir).find((f) => f.toLowerCase().endsWith('.atlas'));+ if (atlasFile) {+ const toRef = (name: string): string => outRef(norm(path.relative(assetsDir, path.join(dir, name))));+ // the images the atlas names (a page is a line that ends in an image extension) travel with it+ const pages = readFileSync(path.join(dir, atlasFile), 'utf8').split(/\r?\n/).map((l) => l.trim()).filter((l) => /\.(png|jpg|jpeg|webp)$/i.test(l));+ if (!opts.dryRun) {+ for (const name of [path.basename(entry.file), atlasFile, ...pages]) {+ const from = path.join(dir, name);+ if (!existsSync(from)) continue;+ const to = path.join(out, toRef(name));+ mkdirSync(path.dirname(to), { recursive: true });+ copyFileSync(from, to);+ mintSidecar(to);+ }+ }+ found = { skeleton: toRef(path.basename(entry.file)), atlas: toRef(atlasFile) };+ }+ } catch {+ found = null;+ }+ spines.set(key, found);+ return found;+ },animationClip(clipUuid, where) {const entry = index.byUuid.get(clipUuid.split('@')[0]!);if (!entry || !entry.rel.endsWith('.anim')) return null;@@ -233,7 +266,8 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impoif (!ref) return null;if (opts.dryRun) return ref;const key = createHash('sha1').update(JSON.stringify([...paths].sort())).digest('hex').slice(0, 8);- const copy = retargetClip(out, ref, paths, key, clipPlayOf(sub?.userData));+ // a node with no bones of its own (a prefab that only holds a clip) gets the clip as it was written+ const copy = retargetClip(out, ref, paths, key, clipPlayOf(sub?.userData)) ?? (paths.size === 0 ? retargetClip(out, ref, null, 'free', clipPlayOf(sub?.userData)) : null);if (!copy) {report.note('animation-no-matching-bones', where);return null;diff --git a/pipeline/src/import/cocos/models.ts b/pipeline/src/import/cocos/models.tsindex 45ba0557b..ffbb2754f 100644--- a/pipeline/src/import/cocos/models.ts+++ b/pipeline/src/import/cocos/models.ts@@ -202,7 +202,7 @@ interface Key { time: number; [k: string]: unknown }** @returns the project-relative path of the copy, or null when no track found its node.*/-export function retargetClip(out: string, clipRef: string, paths: Map<string, string>, key: string, play: ClipPlay = {}): { ref: string; dropped: number } | null {+export function retargetClip(out: string, clipRef: string, paths: Map<string, string> | null, key: string, play: ClipPlay = {}): { ref: string; dropped: number } | null {const abs = path.join(out, clipRef);const doc = JSON.parse(readFileSync(abs, 'utf8')) as { tracks?: Raw[]; duration?: number; wrapMode?: string };const span = play.span;@@ -213,13 +213,14 @@ export function retargetClip(out: string, clipRef: string, paths: Map<string, stconst loose = new Set<string>();for (const track of doc.tracks ?? []) {const cp = typeof track.childPath === 'string' ? track.childPath : '';- if (cp !== '' && !cp.includes('/') && !paths.has(cp)) loose.add(cp);+ if (paths !== null && cp !== '' && !cp.includes('/') && !paths.has(cp)) loose.add(cp);}const host = loose.size === 1 && (doc.tracks ?? []).every((t) => t.childPath === [...loose][0]) ? [...loose][0]! : null;for (const track of doc.tracks ?? []) {const childPath = typeof track.childPath === 'string' ? track.childPath : '';const name = childPath.split('/').pop() ?? '';- const target = childPath === '' || (host !== null && childPath === host) ? '' : paths.get(name);+ // with no skeleton to follow, the clip keeps the paths it was written with: it is the holder of a clip, to be played on a skeleton later+ const target = paths === null ? childPath : childPath === '' || (host !== null && childPath === host) ? '' : paths.get(name);if (target === undefined) {dropped++;continue;@@ -231,7 +232,7 @@ export function retargetClip(out: string, clipRef: string, paths: Map<string, streturn { ...channel, keyframes: inside };}).filter((channel) => (channel.keyframes as unknown[]).length > 0);if (channels.length === 0) continue;- tracks.push({ ...track, childPath: target, name: target.split('/').pop() || track.name, channels });+ tracks.push({ ...track, childPath: target, name: (target.split('/').pop() ?? '') || track.name, channels });}if (tracks.length === 0) return null;const tag = [key, span ? `${span.from}-${span.to}` : '', play.wrapMode ?? ''].filter(Boolean).join('_').replace(/[^A-Za-z0-9]+/g, '_');diff --git a/pipeline/src/import/cocos/particle.ts b/pipeline/src/import/cocos/particle.tsindex dad86a522..0cf670f6d 100644--- a/pipeline/src/import/cocos/particle.ts+++ b/pipeline/src/import/cocos/particle.ts@@ -314,3 +314,64 @@ export function particleSystem(c: { enabled: boolean; data: Raw }, ctx: Particlectx.report.component('cc.ParticleSystem', partial ? 'partial' : 'mapped');return { type: 'ParticleEmitter', data: out };}++export interface Particle2DContext extends ParticleContext {+ /** The image of a sprite frame, as a project path. */+ frame?(uuid: string): string | null;+}++/**+ * `cc.ParticleSystem2D`: the 2D particle model of the older engine, a start and an end for size, spin and colour, each with a variance, and either+ * gravity or a ring that the particles circle. The emitter's start and end ranges are the same idea; the gravity model maps, a radial one is counted.+ */+export function particleSystem2D(c: { enabled: boolean; data: Raw }, ctx: Particle2DContext, where: string): { type: string; data: Raw } {+ const d = c.data;+ let partial = false;+ const lose = (code: string): void => { partial = true; ctx.report.note(code, where); };+ const life = num(d.life, 1), lifeVar = num(d.lifeVar, 0);+ const speed = num(d.speed, 0), speedVar = num(d.speedVar, 0);+ const angle = num(d.angle, 90), angleVar = num(d.angleVar, 0);+ const startSize = num(d.startSize, 50), startSizeVar = num(d.startSizeVar, 0);+ const endSize = num(d.endSize, 0), endSizeVar = num(d.endSizeVar, 0);+ // a colour and its variance: the middle of the range it can start at (the variance is a spread around the colour)+ const colour = (value: unknown): Rgba => colorOf(value);+ const start = colour(d._startColor), end = colour(d._endColor);+ const out: Raw = {+ enabled: c.enabled,+ looping: num(d.duration, -1) < 0,+ playOnStart: d.playOnLoad !== false,+ duration: num(d.duration, -1) < 0 ? 5 : num(d.duration, 5),+ maxParticles: Math.max(1, Math.trunc(num(d._totalParticles, 150))),+ rate: num(d.emissionRate, 100),+ lifetimeMin: Math.max(0, life - lifeVar), lifetimeMax: life + lifeVar,+ shape: 0, // Point: the position variance is a small box in the old model+ angleSpreadMin: angle - angleVar, angleSpreadMax: angle + angleVar,+ speedMin: Math.max(0, speed - speedVar), speedMax: speed + speedVar,+ startSizeMin: Math.max(0, startSize - startSizeVar), startSizeMax: startSize + startSizeVar,+ endSizeMin: Math.max(0, endSize - endSizeVar), endSizeMax: endSize + endSizeVar,+ rotationMin: num(d.startSpin, 0) - num(d.startSpinVar, 0), rotationMax: num(d.startSpin, 0) + num(d.startSpinVar, 0),+ startColor: { r: start[0], g: start[1], b: start[2], a: start[3] },+ endColor: { r: end[0], g: end[1], b: end[2], a: end[3] },+ simulationSpace: num(d._positionType, 0) === 0 ? 0 : 1, // free is the world's, relative and grouped follow the emitter+ blendMode: num(d._dstBlendFactor, 1) === 1 ? 1 : 0,+ };+ // the spin that changes over a life is a steady turn from the start spin to the end spin+ const spinChange = (num(d.endSpin, 0) - num(d.startSpin, 0)) / Math.max(life, 0.0001);+ out.angularVelocityMin = spinChange - num(d.endSpinVar, 0) / Math.max(life, 0.0001);+ out.angularVelocityMax = spinChange + num(d.endSpinVar, 0) / Math.max(life, 0.0001);+ if (num(d.emitterMode, 0) === 0) {+ const g = isObj(d.gravity) ? d.gravity : {};+ out.gravity = { x: num(g.x, 0), y: num(g.y, 0), z: 0 };+ if (num(d.tangentialAccel, 0) !== 0 || num(d.radialAccel, 0) !== 0) lose('particle2d-accel');+ } else {+ lose('particle2d-radius-mode');+ }+ const pos = isObj(d.posVar) ? d.posVar : {};+ if (num(pos.x, 0) !== 0 || num(pos.y, 0) !== 0) lose('particle2d-position-variance');+ const frameUuid = isObj(d._spriteFrame) && typeof d._spriteFrame.__uuid__ === 'string' ? d._spriteFrame.__uuid__ : '';+ const texture = frameUuid ? ctx.frame?.(frameUuid) : null;+ if (texture) out.texture = texture;+ else lose('particle2d-no-texture');+ ctx.report.component('cc.ParticleSystem2D', partial ? 'partial' : 'mapped');+ return { type: 'ParticleEmitter', data: out };+}diff --git a/pipeline/tests/cocos-particle.test.ts b/pipeline/tests/cocos-particle.test.tsindex 6cddc0fe9..db18005cc 100644--- a/pipeline/tests/cocos-particle.test.ts+++ b/pipeline/tests/cocos-particle.test.ts@@ -9,7 +9,7 @@import { beforeAll, describe, expect, it } from 'vitest';import path from 'node:path';import { ImportReport } from '../src/import/cocos/report';-import { curveRange, particleSystem, type ParticleContext } from '../src/import/cocos/particle';+import { curveRange, particleSystem, particleSystem2D, type ParticleContext } from '../src/import/cocos/particle';const SDK = path.resolve(__dirname, '../../sdk/src');type Validate = (name: string, defaults: unknown, data: unknown, assetFields?: unknown) => { field: string; expected: string; value: unknown }[];@@ -163,3 +163,43 @@ describe('a curve range', () => {expect(curveRange(curve([[0, 0], [1, 10]], 2), 0.5).min).toBeCloseTo(10, 5);});});++describe('a 2D particle system', () => {+ const color = (r: number, g: number, b: number, a: number) => ({ __type__: 'cc.Color', r, g, b, a });+ const convert2D = (over: Record<string, unknown> = {}) => {+ const report = new ImportReport();+ const out = particleSystem2D({+ enabled: true,+ data: {+ duration: -1, emissionRate: 50, life: 1, lifeVar: 0.25, angle: 90, angleVar: 10, speed: 100, speedVar: 20, startSize: 30, startSizeVar: 10, endSize: 5, endSizeVar: 0,+ startSpin: 0, endSpin: 90, emitterMode: 0, gravity: { x: 0, y: -50 }, _totalParticles: 200, _dstBlendFactor: 1, _positionType: 0,+ _startColor: color(255, 128, 0, 255), _endColor: color(255, 0, 0, 0), _spriteFrame: { __uuid__: 'frame@f9941' }, ...over,+ },+ }, { report, assetRef: () => 'x', frame: () => 'assets/cocos/spark.png' }, 'fx.scene');+ return { out, report: report.toJSON() };+ };++ it('maps the start and end ranges, the gravity, the colour and the picture, and validates', () => {+ const { out, report } = convert2D();+ const d = out.data as Record<string, any>;+ expect([d.lifetimeMin, d.lifetimeMax]).toEqual([0.75, 1.25]);+ expect([d.speedMin, d.speedMax]).toEqual([80, 120]);+ expect([d.angleSpreadMin, d.angleSpreadMax]).toEqual([80, 100]);+ expect([d.startSizeMin, d.startSizeMax, d.endSizeMin]).toEqual([20, 40, 5]);+ expect(d.looping).toBe(true);+ expect(d.gravity).toEqual({ x: 0, y: -50, z: 0 });+ expect(d.endColor.a).toBe(0);+ expect(d.texture).toBe('assets/cocos/spark.png');+ expect(d.angularVelocityMin).toBeCloseTo(90, 3);+ expect(report.components['cc.ParticleSystem2D']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });+ const def = registry.ParticleEmitter!;+ expect(validate('ParticleEmitter', def._default, d, def.assetFields)).toEqual([]);+ });++ it('counts the radius mode and the accelerations the emitter has no model for', () => {+ const radius = convert2D({ emitterMode: 1 });+ expect(radius.report.notes['particle2d-radius-mode']?.count).toBe(1);+ const accel = convert2D({ radialAccel: -100 });+ expect(accel.report.notes['particle2d-accel']?.count).toBe(1);+ });+});diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.tsindex 912adaf19..3ac785417 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, Line, 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, PageView, PageViewIndicator, ScrollBar, SafeArea, WebView, 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/index.ts b/sdk/src/cocos/ui/index.tsindex 48fe4d61c..09e784162 100644--- a/sdk/src/cocos/ui/index.ts+++ b/sdk/src/cocos/ui/index.ts@@ -18,3 +18,5 @@ export { RichText } from './richText';export { Mask } from './mask';export { Graphics, Line } from './graphics';export { EditBox } from './editBox';+export { PageView, PageViewIndicator, ScrollBar } from './pages';+export { SafeArea, WebView } from './misc';diff --git a/sdk/src/cocos/ui/misc.ts b/sdk/src/cocos/ui/misc.tsnew file mode 100644index 000000000..7c53acabb--- /dev/null+++ b/sdk/src/cocos/ui/misc.ts@@ -0,0 +1,78 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cocos/ui/misc.ts+ * @brief `SafeArea` and `WebView`.+ *+ * A safe area keeps a node inside the part of the screen a notch or a home bar leaves free: it is a widget whose margins are the screen's safe+ * insets. A web view needs a surface the host provides; none is wired in, so the component keeps its address and events and says once that+ * nothing is shown.+ */+import { Component } from '../component';+import { Node } from '../node';+import { declareClass } from '../host';+import { log } from '../../util/logger';+import { Widget } from './widget';+import { getSafeInsets } from './screen';+import { EventHandler, joinHandlers } from './button';++type Handlers = Array<{ component: string; handler: string; customEventData: string }>;++export class SafeArea extends Component {+ private seen_ = '';++ onEnable(): void { this.seen_ = ''; }++ update(): void {+ const { left, right, top, bottom } = getSafeInsets();+ const key = `${left},${right},${top},${bottom}`;+ if (key === this.seen_) return;+ this.seen_ = key;+ const widget = this.node.getComponent(Widget) ?? this.node.addComponent(Widget)!;+ const flags = Widget.AlignFlags;+ widget.alignFlags |= flags.LEFT | flags.RIGHT | flags.TOP | flags.BOT;+ widget.isAbsLeft = widget.isAbsRight = widget.isAbsTop = widget.isAbsBottom = true;+ widget.left = left;+ widget.right = right;+ widget.top = top;+ widget.bottom = bottom;+ }+}++const WebViewEvent = Object.freeze({ LOADING: 0, LOADED: 1, ERROR: 2 });++export class WebView extends Component {+ static readonly EventType = WebViewEvent;+ url = '';+ webviewTargets: Array<Node | null> = [];+ webviewHandlers: Handlers = [];+ webviewEvents: EventHandler[] = [];+ private warned_ = false;++ onLoad(): void {+ if (this.webviewEvents.length === 0) this.webviewEvents = joinHandlers(this.webviewTargets, this.webviewHandlers);+ }++ onEnable(): void { this.explain_(); }++ /** Ask for an address. There is no web surface to show it on, so it is only kept. */+ loadURL(url: string): void { this.url = url; this.explain_(); }+ setJavascriptInterfaceScheme(_scheme: string): void { /* no page to talk to */ }+ setOnJSCallback(_callback: (view: WebView, url: string) => void): void { /* no page to talk to */ }+ evaluateJS(_code: string): void { /* no page to run it in */ }++ private explain_(): void {+ if (this.warned_ || !this.url) return;+ this.warned_ = true;+ log.warn('cocos', `WebView (${this.node.name}) shows nothing here: this host has no web surface for ${this.url}`);+ }+}++export function declareMisc(): void {+ declareClass(SafeArea as never, 'SafeArea', []);+ declareClass(WebView as never, 'WebView', [+ { name: 'url', kind: 'string' },+ { name: 'webviewTargets', kind: 'node', array: true },+ { name: 'webviewHandlers', kind: 'json' },+ ]);+}diff --git a/sdk/src/cocos/ui/pages.ts b/sdk/src/cocos/ui/pages.tsnew file mode 100644index 000000000..f670a0d77--- /dev/null+++ b/sdk/src/cocos/ui/pages.ts@@ -0,0 +1,208 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cocos/ui/pages.ts+ * @brief `PageView`, `PageViewIndicator` and `ScrollBar`: what sits on top of a `ScrollView`.+ *+ * A page view is a scroll view whose content is a row (or column) of pages, which settles on one when the finger lifts. A scroll bar is a handle+ * that shows where the view is along its content. Both read the scroll view's own offset, so they follow whatever moved it.+ */+import { Component } from '../component';+import { Node } from '../node';+import { Vec2 } from '../math';+import { declareClass } from '../host';+import { ScrollView } from './scrollView';+import { UITransform } from './uiTransform';+import { EventHandler, joinHandlers } from './button';++type Handlers = Array<{ component: string; handler: string; customEventData: string }>;++const PageViewEvent = Object.freeze({ PAGE_TURNING: 'page-turning' });++export class PageView extends ScrollView {+ static readonly SizeMode = Object.freeze({ Unified: 0, Free: 1 });+ static readonly Direction = Object.freeze({ Horizontal: 0, Vertical: 1 });+ static readonly EventType = Object.freeze({ ...ScrollView.EventType, ...PageViewEvent });++ sizeMode = 1;+ direction = 0;+ /** The distance a drag must cover to turn the page, in canvas units. */+ autoPageTurningThreshold = 100;+ /** Seconds a settle takes. */+ pageTurningSpeed = 0.3;+ indicator: PageViewIndicator | null = null;+ pageTargets: Array<Node | null> = [];+ pageHandlers: Handlers = [];+ pageEvents: EventHandler[] = [];++ private page_ = 0;+ private from_ = 0;++ onLoad(): void {+ super.onLoad();+ if (this.pageEvents.length === 0) this.pageEvents = joinHandlers(this.pageTargets, this.pageHandlers);+ this.horizontal = this.direction === 0;+ this.vertical = this.direction === 1;+ }++ onEnable(): void {+ super.onEnable();+ this.node.on(ScrollView.EventType.SCROLL_BEGAN, this.onBegan_, this);+ this.node.on(ScrollView.EventType.TOUCH_UP, this.onLifted_, this);+ this.indicator?.setPageView(this);+ }++ onDisable(): void {+ this.node.off(ScrollView.EventType.SCROLL_BEGAN, this.onBegan_, this);+ this.node.off(ScrollView.EventType.TOUCH_UP, this.onLifted_, this);+ super.onDisable();+ }++ getPages(): Node[] { return this.content?.children ?? []; }+ getCurrentPageIndex(): number { return this.page_; }+ setCurrentPageIndex(index: number): void { this.scrollToPage(index, 0); }++ addPage(page: Node): void { this.content?.addChild(page); this.indicator?.refresh(); }+ insertPage(page: Node, index: number): void { this.content?.addChild(page); page.setSiblingIndex(index); this.indicator?.refresh(); }+ removePage(page: Node): void { if (page.parent === this.content) page.removeFromParent(); this.indicator?.refresh(); }+ removePageAtIndex(index: number): void { const page = this.getPages()[index]; if (page) this.removePage(page); }+ removeAllPages(): void { this.content?.removeAllChildren(); this.indicator?.refresh(); }++ /** Settle on page @p index over @p timeInSecond. */+ scrollToPage(index: number, timeInSecond = this.pageTurningSpeed): void {+ const pages = this.getPages();+ if (pages.length === 0) return;+ const target = Math.min(pages.length - 1, Math.max(0, Math.trunc(index)));+ const offset = this.offsetOf_(pages[target]!);+ if (!offset) return;+ const turned = target !== this.page_;+ this.page_ = target;+ this.scrollToOffset(offset, timeInSecond);+ if (turned) {+ EventHandler.emitEvents(this.pageEvents, this, PageViewEvent.PAGE_TURNING);+ this.node.emit(PageViewEvent.PAGE_TURNING, this);+ this.indicator?.refresh();+ }+ }++ /** The scroll offset that brings @p page to the middle of the view. */+ private offsetOf_(page: Node): Vec2 | null {+ const content = this.content;+ const view = content?.parent?.getComponent(UITransform);+ const size = content?.getComponent(UITransform);+ if (!content || !view || !size) return null;+ const max = this.getMaxScrollOffset();+ const p = page.position;+ const x = p.x + size.width * size.anchorX - view.width / 2;+ const y = size.height * (1 - size.anchorY) - p.y - view.height / 2;+ return new Vec2(Math.min(max.x, Math.max(0, x)), Math.min(max.y, Math.max(0, y)));+ }++ private axis_(offset: Vec2): number { return this.direction === 0 ? offset.x : offset.y; }++ private onBegan_(): void { this.from_ = this.axis_(this.getScrollOffset()); }++ /** On lifting the finger: a drag longer than the threshold turns the page in its direction; a shorter one settles on the nearest. */+ private onLifted_(): void {+ const pages = this.getPages();+ if (pages.length === 0) return;+ const now = this.axis_(this.getScrollOffset());+ const moved = now - this.from_;+ const offsets = pages.map((p) => this.offsetOf_(p)).map((o) => (o ? this.axis_(o) : 0));+ let nearest = 0;+ for (let i = 1; i < offsets.length; i++) if (Math.abs(offsets[i]! - now) < Math.abs(offsets[nearest]! - now)) nearest = i;+ let target = nearest;+ if (Math.abs(moved) >= this.autoPageTurningThreshold && nearest === this.page_) target = this.page_ + (moved > 0 ? 1 : -1);+ this.stopAutoScroll();+ this.scrollToPage(target);+ }+}++/** The dots under a page view. Their number follows the pages and the lit one the current page; drawing them is the scene's own sprites. */+export class PageViewIndicator extends Component {+ static readonly Direction = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1 });+ spacing = 0;+ direction = 0;+ cellSize: { width: number; height: number } = { width: 20, height: 20 };+ private view_: PageView | null = null;++ setPageView(view: PageView | null): void { this.view_ = view; this.refresh(); }+ /** How many pages there are and which one is current. */+ get pageCount(): number { return this.view_?.getPages().length ?? 0; }+ get currentPage(): number { return this.view_?.getCurrentPageIndex() ?? 0; }+ refresh(): void { /* the dots are the scene's own nodes: the count and the lit one are read from pageCount and currentPage */ }+}++export class ScrollBar extends Component {+ static readonly Direction = Object.freeze({ HORIZONTAL: 0, VERTICAL: 1 });+ scrollView: ScrollView | null = null;+ /** The node that slides along the bar. */+ handle: Node | null = null;+ direction = 1;+ enableAutoHide = false;+ autoHideTime = 1;+ private idle_ = 0;++ update(dt: number): void {+ const view = this.scrollView, handle = this.handle;+ if (!view || !handle) return;+ const track = this.node.getComponent(UITransform);+ const content = view.content?.getComponent(UITransform);+ const port = view.content?.parent?.getComponent(UITransform);+ const knob = handle.getComponent(UITransform);+ if (!track || !content || !port || !knob) return;+ const horizontal = this.direction === 0;+ const trackLength = horizontal ? track.width : track.height;+ const contentLength = horizontal ? content.width : content.height;+ const viewLength = horizontal ? port.width : port.height;+ const offset = view.getScrollOffset();+ const max = view.getMaxScrollOffset();+ const travel = horizontal ? max.x : max.y;+ const ratio = travel > 0 ? (horizontal ? offset.x : offset.y) / travel : 0;+ const length = Math.min(trackLength, Math.max(10, contentLength > 0 ? (trackLength * viewLength) / contentLength : trackLength));+ if (horizontal) knob.width = length; else knob.height = length;+ const along = Math.min(1, Math.max(0, ratio)) * (trackLength - length);+ const p = handle.position;+ if (horizontal) handle.setPosition(-trackLength / 2 + length / 2 + along, p.y, p.z);+ else handle.setPosition(p.x, trackLength / 2 - length / 2 - along, p.z);+ // a bar that hides itself shows only while its view moves+ if (this.enableAutoHide) {+ this.idle_ = view.isScrolling() ? 0 : this.idle_ + dt;+ this.node.active = this.idle_ < this.autoHideTime || travel <= 0 ? this.idle_ < this.autoHideTime : false;+ }+ }+}++export function declarePages(): void {+ declareClass(PageView as never, 'PageView', [+ { name: 'content', kind: 'node' },+ { name: 'horizontal', kind: 'boolean' },+ { name: 'vertical', kind: 'boolean' },+ { name: 'inertia', kind: 'boolean' },+ { name: 'brake', kind: 'number' },+ { name: 'elastic', kind: 'boolean' },+ { name: 'bounceDuration', kind: 'number' },+ { name: 'cancelInnerEvents', kind: 'boolean' },+ { name: 'scrollTargets', kind: 'node', array: true },+ { name: 'scrollHandlers', kind: 'json' },+ { name: 'sizeMode', kind: 'number' },+ { name: 'direction', kind: 'number' },+ { name: 'autoPageTurningThreshold', kind: 'number' },+ { name: 'pageTurningSpeed', kind: 'number' },+ { name: 'indicator', kind: 'component', type: PageViewIndicator },+ { name: 'pageTargets', kind: 'node', array: true },+ { name: 'pageHandlers', kind: 'json' },+ ]);+ declareClass(PageViewIndicator as never, 'PageViewIndicator', [+ { name: 'spacing', kind: 'number' },+ { name: 'direction', kind: 'number' },+ { name: 'cellSize', kind: 'json' },+ ]);+ declareClass(ScrollBar as never, 'ScrollBar', [+ { name: 'scrollView', kind: 'component', type: ScrollView },+ { name: 'handle', kind: 'node' },+ { name: 'direction', kind: 'number' },+ { name: 'enableAutoHide', kind: 'boolean' },+ { name: 'autoHideTime', kind: 'number' },+ ]);+}diff --git a/sdk/src/cocos/ui/pass.ts b/sdk/src/cocos/ui/pass.tsindex 5743f8627..a77d6f93b 100644--- a/sdk/src/cocos/ui/pass.ts+++ b/sdk/src/cocos/ui/pass.ts@@ -19,7 +19,9 @@ import { declareControls } from './controls';import { declareGraphics } from './graphics';import { declareEditBox } from './editBox';import { declareScrollView } from './scrollView';-import { setUiCameraData, setVisibleSize, setWindowPixels } from './screen';+import { setSafeInsets, setUiCameraData, setVisibleSize, setWindowPixels } from './screen';+import { declarePages } from './pages';+import { declareMisc } from './misc';export function declareUiPass(): void {declareWidget();@@ -27,6 +29,8 @@ export function declareUiPass(): void {declareControls();declareGraphics();declareEditBox();+ declarePages();+ declareMisc();declareScrollView();const system = defineSystem([Res(UICameraInfo), Res(ScreenLayout), GetWorld()],@@ -37,6 +41,9 @@ export function declareUiPass(): void {if (screen?.valid) {setVisibleSize(screen.right - screen.left, screen.top - screen.bottom);setWindowPixels(screen.viewportW, screen.viewportH);+ setSafeInsets(+ Math.max(0, screen.safeLeft - screen.left), Math.max(0, screen.right - screen.safeRight),+ Math.max(0, screen.top - screen.safeTop), Math.max(0, screen.safeBottom - screen.bottom));}const previous = setCurrentWorld(world);try {diff --git a/sdk/src/cocos/ui/screen.ts b/sdk/src/cocos/ui/screen.tsindex 0b8b6eee1..2a7fd3546 100644--- a/sdk/src/cocos/ui/screen.ts+++ b/sdk/src/cocos/ui/screen.ts@@ -16,6 +16,10 @@ let uiCamera: UICameraData | null = null;let width = 960;let height = 640;let generation = 0;+let safeLeft = 0;+let safeRight = 0;+let safeTop = 0;+let safeBottom = 0;let windowW = 960;let windowH = 640;const listeners: Array<(kind: 'visible' | 'window') => void> = [];@@ -23,6 +27,18 @@ const listeners: Array<(kind: 'visible' | 'window') => void> = [];/** The visible area's size, in the canvas units scripts see. */export function getVisibleSize(): { width: number; height: number } { return { width, height }; }+/** How far in from each edge of the visible area the safe area starts (a notch, a rounded corner, a home bar), in canvas units. */+export function getSafeInsets(): { left: number; right: number; top: number; bottom: number } {+ return { left: safeLeft, right: safeRight, top: safeTop, bottom: safeBottom };+}++export function setSafeInsets(left: number, right: number, top: number, bottom: number): void {+ if (left === safeLeft && right === safeRight && top === safeTop && bottom === safeBottom) return;+ safeLeft = left; safeRight = right; safeTop = top; safeBottom = bottom;+ generation++;+ for (const l of [...listeners]) l('visible');+}+/** Tell the layer the visible area changed; widgets set to follow the window re-align. */export function setVisibleSize(w: number, h: number): void {if (w === width && h === height) return;diff --git a/sdk/tests/cocos/pages-wasm.test.ts b/sdk/tests/cocos/pages-wasm.test.tsnew file mode 100644index 000000000..1413cf4ff--- /dev/null+++ b/sdk/tests/cocos/pages-wasm.test.ts@@ -0,0 +1,113 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file PageView, ScrollBar, SafeArea and WebView.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import type { ESEngineModule } from '../../src/wasm';+import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';+import { Node, PageView, SafeArea, ScrollBar, UITransform, Vec2, WebView, Widget } from '../../src/cocos';+import { setSafeInsets } from '../../src/cocos/ui/screen';+import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';+import { pointerApp, type PointerApp } from './helpers/pointerApp';++describe.skipIf(!HAS_WASM)('pages, bars, safe area and web view', () => {+ let module: ESEngineModule;+ let P: PointerApp | undefined;++ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });+ afterEach(() => { setSafeInsets(0, 0, 0, 0); P?.dispose(); P = undefined; });++ function box(name: string, x: number, y: number, w: number, h: number, parent?: Node, anchor = new Vec2(0.5, 0.5)): Node {+ const n = new Node(name);+ P!.app.world.insert(n._entity, Transform);+ const t = n.addComponent(UITransform)!;+ t.setContentSize(w, h);+ t.anchorX = anchor.x;+ t.anchorY = anchor.y;+ n.setPosition(x, y, 0);+ parent?.addChild(n);+ return n;+ }++ /** A 200 x 100 view over a row of three 200 x 100 pages, content anchored at its left. */+ async function pager(): Promise<{ view: PageView; pages: Node[] }> {+ P = pointerApp(module);+ const host = box('view', 300, 300, 200, 100);+ const content = box('content', -100, 0, 600, 100, host, new Vec2(0, 0.5));+ const pages = [0, 1, 2].map((i) => box(`page${i}`, 100 + i * 200, 0, 200, 100, content));+ const view = host.addComponent<PageView>('PageView')!;+ view.content = content;+ view.direction = PageView.Direction.Horizontal;+ await P.frame(2);+ return { view, pages };+ }++ it('settles on a page it is asked for, and says it turned', async () => {+ const { view } = await pager();+ const turned: number[] = [];+ view.node.on(PageView.EventType.PAGE_TURNING, (v: PageView) => turned.push(v.getCurrentPageIndex()));+ expect(view.getPages()).toHaveLength(3);+ view.scrollToPage(2, 0);+ await P!.frame(2);+ expect(view.getCurrentPageIndex()).toBe(2);+ expect(view.getScrollOffset().x).toBeCloseTo(400, 3);+ view.setCurrentPageIndex(0);+ await P!.frame(2);+ expect(view.getScrollOffset().x).toBeCloseTo(0, 3);+ expect(turned).toEqual([2, 0]);+ });++ it('keeps the page inside the pages there are', async () => {+ const { view } = await pager();+ view.scrollToPage(9, 0);+ expect(view.getCurrentPageIndex()).toBe(2);+ view.scrollToPage(-4, 0);+ expect(view.getCurrentPageIndex()).toBe(0);+ });++ it('moves a scroll bar\'s handle along its track as the view scrolls, and sizes it to the share of the content in view', async () => {+ P = pointerApp(module);+ const host = box('scroll', 300, 300, 100, 100);+ const content = box('content', 0, 50, 100, 400, host, new Vec2(0.5, 1));+ const track = box('track', 60, 0, 10, 100, host);+ const handle = box('handle', 0, 0, 10, 100, track);+ const { ScrollView } = await import('../../src/cocos');+ const view = host.addComponent<InstanceType<typeof ScrollView>>('ScrollView')!;+ view.content = content;+ const bar = track.addComponent<ScrollBar>('ScrollBar')!;+ bar.scrollView = view;+ bar.handle = handle;+ bar.direction = ScrollBar.Direction.VERTICAL;+ await P.frame(2);+ const knob = handle.getComponent(UITransform)!;+ expect(knob.height).toBeCloseTo(25, 3); // a quarter of the content is in view+ expect(handle.position.y).toBeCloseTo(50 - 12.5, 3); // at the top of the track+ view.scrollToBottom(0);+ await P.frame(2);+ expect(handle.position.y).toBeCloseTo(-50 + 12.5, 3); // at the bottom+ });++ it('keeps a node inside the safe area: a widget whose margins are the insets', async () => {+ P = pointerApp(module);+ const node = box('hud', 480, 320, 100, 100);+ node.addComponent<SafeArea>('SafeArea');+ setSafeInsets(44, 0, 30, 20);+ await P.frame(2);+ const widget = node.getComponent(Widget)!;+ expect([widget.left, widget.right, widget.top, widget.bottom]).toEqual([44, 0, 30, 20]);+ expect(widget.isAlignLeft && widget.isAlignRight && widget.isAlignTop && widget.isAlignBottom).toBe(true);+ setSafeInsets(0, 0, 0, 0);+ await P.frame(2);+ expect(widget.left).toBe(0);+ });++ it('keeps a web view\'s address and answers its calls without a surface', async () => {+ P = pointerApp(module);+ const node = box('web', 100, 100, 100, 100);+ const web = node.addComponent<WebView>('WebView')!;+ web.loadURL('https://example.com');+ expect(web.url).toBe('https://example.com');+ expect(() => { web.evaluateJS('1'); web.setJavascriptInterfaceScheme('x'); }).not.toThrow();+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex ee9364f37..cb902d833 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): PageView, PageViewIndicator, ScrollBar, SafeArea and WebView components, and the importer maps SpriteRenderer, Spine skeletons, ParticleSystem2D, Terrain and the players and animators whose clip or graph is missing':+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},'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':