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): the importer maps ParticleSystem onto ParticleEmitter, and counts what the emitter has no field for
yhh90d03c59fe82
diff --git a/pipeline/src/import/cocos/components.ts b/pipeline/src/import/cocos/components.tsindex a983f1d80..9b307a6ba 100644--- a/pipeline/src/import/cocos/components.ts+++ b/pipeline/src/import/cocos/components.ts@@ -12,6 +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 type { CocosAssetEntry, CocosAssetIndex } from './assets';import { type CocosComponent, type CocosNode } from './document';import type { ImportReport } from './report';@@ -39,6 +40,8 @@ export interface ComponentContext {* outline's colour supplied at draw time. Such a font has to say so, in the channel flags BMFont gives that layout.*/drawsBakedOutline?(materialUuid: string): boolean;+ /** A material's main texture and whether it blends additively; null when the project has no such material. */+ material?(uuid: string): { texture: CocosAssetEntry | null; additive: boolean } | null;/** The script class a compressed class id names, when the project has that script. */scriptClass?(classId: string): { name: string } | undefined;/** The project-relative ref of a prefab, queuing it for conversion; null when the project does not have it. */@@ -507,6 +510,9 @@ export function convertNode(node: CocosNode, ctx: ComponentContext, where: strincase 'cc.ScrollView':out = scrollView(c, ctx);break;+ case 'cc.ParticleSystem':+ out = particleSystem(c, ctx, where);+ break;case 'cc.DirectionalLight':out = directionalLight(c, ctx, where);break;diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsindex 4efc659ba..9b52baa6d 100644--- a/pipeline/src/import/cocos/importProject.ts+++ b/pipeline/src/import/cocos/importProject.ts@@ -155,6 +155,9 @@ export function importCocosProject(opts: CocosImportOptions): ImportReportData {drawsBakedOutline(materialUuid) {return materialBakesOutline(materialUuid);},+ material(materialUuid) {+ return materialInfo(materialUuid);+ },loadPrefab(uuid) {const e = prefabEntry(uuid);return e ? loadDoc(e) : null;@@ -170,6 +173,30 @@ export function importCocosProject(opts: CocosImportOptions): ImportReportData {},};+ // What a particle material draws and how: its main texture (a sub-asset of an image) and whether the destination factor is One.+ const materials = new Map<string, { texture: CocosAssetEntry | null; additive: boolean } | null>();+ const materialInfo = (materialUuid: string): { texture: CocosAssetEntry | null; additive: boolean } | null => {+ if (materials.has(materialUuid)) return materials.get(materialUuid) ?? null;+ let info: { texture: CocosAssetEntry | null; additive: boolean } | null = null;+ try {+ const mat = index.byUuid.get(materialUuid);+ if (mat) {+ const json = JSON.parse(readFileSync(mat.file, 'utf8')) as {+ _props?: Array<{ mainTexture?: { __uuid__?: string } }>;+ _states?: Array<{ blendState?: { targets?: Array<{ blend?: boolean; blendDst?: number }> } }>;+ };+ const texUuid = json._props?.find((p) => p.mainTexture?.__uuid__)?.mainTexture?.__uuid__;+ const base = typeof texUuid === 'string' ? texUuid.split('@')[0]! : undefined;+ const target = json._states?.[0]?.blendState?.targets?.[0];+ info = { texture: base ? index.byUuid.get(base) ?? null : null, additive: target?.blend === true && target.blendDst === 1 };+ }+ } catch {+ info = null;+ }+ materials.set(materialUuid, info);+ return info;+ };+// A material says how its font page is read through the effect it uses; the outline effect mixes an outline colour in by the red channel.const bakes = new Map<string, boolean>();const materialBakesOutline = (materialUuid: string): boolean => {diff --git a/pipeline/src/import/cocos/particle.ts b/pipeline/src/import/cocos/particle.tsnew file mode 100644index 000000000..7330af849--- /dev/null+++ b/pipeline/src/import/cocos/particle.ts@@ -0,0 +1,246 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file `cc.ParticleSystem` as the engine's `ParticleEmitter`.+ *+ * Cocos describes a system as a main block plus optional modules (shape, size/colour/rotation over lifetime, texture animation, ...), each+ * value a range that is a constant, two constants, or a curve. The engine's emitter is flatter: one start and one end value per quantity,+ * linearly eased. What the two share is mapped; a curve is sampled at its two ends, so a fade that rises and falls keeps only its ends. What+ * the engine's emitter has no field for is counted, so the gap is a list.+ */+import type { CocosAssetEntry } from './assets';+import type { ImportReport } from './report';++type Raw = Record<string, unknown>;+const isObj = (v: unknown): v is Raw => typeof v === 'object' && v !== null && !Array.isArray(v);+const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d);++export interface ParticleContext {+ report: ImportReport;+ /** A material's main texture and whether it blends additively; null when the project has no such material. */+ material?(uuid: string): { texture: CocosAssetEntry | null; additive: boolean } | null;+ assetRef(entry: CocosAssetEntry): string;+}++export interface Range { min: number; max: number }++/** One keyframe track's value at time @p t (0..1), linear between the keys. */+function sampleKeys(keys: Array<{ time: number; value: number }>, t: number): number {+ if (keys.length === 0) return 0;+ const sorted = [...keys].sort((a, b) => a.time - b.time);+ if (t <= sorted[0]!.time) return sorted[0]!.value;+ const last = sorted[sorted.length - 1]!;+ if (t >= last.time) return last.value;+ for (let i = 1; i < sorted.length; i++) {+ const b = sorted[i]!;+ if (t <= b.time) {+ const a = sorted[i - 1]!;+ const f = b.time === a.time ? 0 : (t - a.time) / (b.time - a.time);+ return a.value + (b.value - a.value) * f;+ }+ }+ return last.value;+}++function splineAt(spline: unknown, t: number): number | null {+ if (!isObj(spline)) return null;+ const values = spline._values;+ if (!Array.isArray(values)) return null;+ const keys = values.filter(isObj).map((k) => ({ time: num(k.time, 0), value: num(k.value, 0) }));+ return keys.length ? sampleKeys(keys, t) : null;+}++/** A `cc.CurveRange` evaluated at time @p t of its domain (emission time for a start value, lifetime for an over-lifetime one). */+export function curveRange(v: unknown, t: number, fallback = 0): Range {+ if (!isObj(v)) return { min: fallback, max: fallback };+ const mult = num(v.multiplier, 1);+ switch (num(v.mode, 0)) {+ case 1: {+ const s = splineAt(v.spline, t);+ return s === null ? { min: fallback, max: fallback } : { min: s * mult, max: s * mult };+ }+ case 2: {+ const a = splineAt(v.splineMin, t);+ const b = splineAt(v.splineMax, t);+ return a === null || b === null ? { min: fallback, max: fallback } : { min: a * mult, max: b * mult };+ }+ case 3: {+ const lo = num(v.constantMin, fallback);+ const hi = num(v.constantMax, fallback);+ return { min: Math.min(lo, hi), max: Math.max(lo, hi) };+ }+ default: {+ const c = num(v.constant, fallback);+ return { min: c, max: c };+ }+ }+}++type Rgba = [number, number, number, number];++function colorOf(v: unknown): Rgba {+ const c = isObj(v) ? v : {};+ return [num(c.r, 255) / 255, num(c.g, 255) / 255, num(c.b, 255) / 255, num(c.a, 255) / 255];+}++/** A `cc.Gradient` at time @p t. Colour and alpha have their own keys. */+function gradientAt(g: unknown, t: number): Rgba {+ if (!isObj(g)) return [1, 1, 1, 1];+ const ck = (Array.isArray(g.colorKeys) ? g.colorKeys : []).filter(isObj).map((k) => ({ time: num(k.time, 0), c: colorOf(k.color) }));+ const ak = (Array.isArray(g.alphaKeys) ? g.alphaKeys : []).filter(isObj).map((k) => ({ time: num(k.time, 0), value: num(k.alpha, 255) / 255 }));+ const rgb: [number, number, number] = [1, 1, 1];+ for (let i = 0; i < 3; i++) rgb[i] = ck.length ? sampleKeys(ck.map((k) => ({ time: k.time, value: k.c[i]! })), t) : 1;+ return [rgb[0], rgb[1], rgb[2], ak.length ? sampleKeys(ak, t) : 1];+}++/** A `cc.GradientRange` at time @p t: a colour, or the gradient (or the first of a pair of them). */+function gradientRange(v: unknown, t: number): Rgba {+ if (!isObj(v)) return [1, 1, 1, 1];+ switch (num(v._mode, 0)) {+ case 1: return gradientAt(v.gradient, t);+ case 2: return colorOf(v.colorMin);+ case 3: return gradientAt(v.gradientMin, t);+ case 4: return gradientAt(v.gradient, t);+ default: return colorOf(v.color);+ }+}++const mid = (r: Range): number => (r.min + r.max) / 2;++/** How many distinct keys a gradient has between its ends: the engine's linear start-to-end ease cannot hold them. */+function interiorKeys(g: unknown): number {+ if (!isObj(g)) return 0;+ const count = (list: unknown): number => (Array.isArray(list) ? list.filter((k) => isObj(k) && num(k.time, 0) > 0.001 && num(k.time, 0) < 0.999).length : 0);+ return count(g.colorKeys) + count(g.alphaKeys);+}++/** Cocos's emitter shapes in the engine's numbering. */+const SHAPE: Record<number, number> = { 0: 2 /* Box */, 1: 1 /* Circle */, 2: 3 /* Cone */, 3: 4 /* Sphere */, 4: 5 /* Hemisphere */ };++export function particleSystem(c: { enabled: boolean; data: Raw }, ctx: ParticleContext, where: string): { type: string; data: Raw } {+ const d = c.data;+ const note = (code: string): void => ctx.report.note(code, where);+ let partial = false;+ const lose = (code: string): void => { partial = true; note(code); };++ const lifetime = curveRange(d.startLifetime, 0, 1);+ const speed = curveRange(d.startSpeed, 0, 0);+ const size = curveRange(d.startSize, 0, 1);+ const rotation = curveRange(d.startRotationZ ?? d.startRotation, 0, 0);+ const rate = curveRange(d.rateOverTime, 0, 0);+ const gravity = curveRange(d.gravityModifier, 0, 0);++ const out: Raw = {+ enabled: c.enabled,+ looping: d.loop === true,+ playOnStart: d.playOnAwake !== false,+ duration: num(d.duration, 5),+ maxParticles: Math.max(1, Math.trunc(num(d._capacity, 100))),+ rate: mid(rate),+ lifetimeMin: lifetime.min,+ lifetimeMax: lifetime.max,+ speedMin: speed.min,+ speedMax: speed.max,+ startSizeMin: size.min,+ startSizeMax: size.max,+ rotationMin: rotation.min,+ rotationMax: rotation.max,+ gravity: { x: 0, y: -9.8 * mid(gravity), z: 0 },+ simulationSpace: num(d._simulationSpace, 1) === 0 ? 1 /* Local */ : 0 /* World */,+ };+ if (num(d.simulationSpeed, 1) !== 1) lose('particle-simulation-speed');+ if (mid(curveRange(d.startDelay, 0, 0)) > 0) lose('particle-start-delay');+ if (mid(curveRange(d.rateOverDistance, 0, 0)) > 0) lose('particle-rate-over-distance');++ // colour: the start colour, eased to its value at the end of life by the over-lifetime gradient+ const start = gradientRange(d.startColor, 0);+ let first: Rgba = [1, 1, 1, 1];+ let last: Rgba = [1, 1, 1, 1];+ const colorModule = isObj(d._colorOverLifetimeModule) && d._colorOverLifetimeModule._enable === true ? d._colorOverLifetimeModule : null;+ if (colorModule) {+ first = gradientRange(colorModule.color, 0);+ last = gradientRange(colorModule.color, 1);+ const range = isObj(colorModule.color) ? colorModule.color : {};+ if (interiorKeys(range.gradient) + interiorKeys(range.gradientMin) > 0) lose('particle-color-keys');+ }+ const mul = (a: Rgba, b: Rgba): Raw => ({ r: a[0] * b[0], g: a[1] * b[1], b: a[2] * b[2], a: a[3] * b[3] });+ out.startColor = mul(start, first);+ out.endColor = mul(start, last);++ // size over lifetime scales the start size to the curve's value at the end+ const sizeModule = isObj(d._sizeOvertimeModule) && d._sizeOvertimeModule._enable === true ? d._sizeOvertimeModule : null;+ if (sizeModule) {+ const from = mid(curveRange(sizeModule.size, 0, 1));+ const to = mid(curveRange(sizeModule.size, 1, 1));+ const k = from === 0 ? 1 : to / from;+ out.endSizeMin = size.min * k;+ out.endSizeMax = size.max * k;+ if (isObj(sizeModule.size) && num(sizeModule.size.mode, 0) !== 0 && Math.abs(mid(curveRange(sizeModule.size, 0.5, from)) - (from + to) / 2) > 0.1 * Math.max(Math.abs(from), 0.0001)) {+ lose('particle-size-curve');+ }+ } else {+ out.endSizeMin = size.min;+ out.endSizeMax = size.max;+ }++ const rotationModule = isObj(d._rotationOvertimeModule) && d._rotationOvertimeModule._enable === true ? d._rotationOvertimeModule : null;+ if (rotationModule) {+ const spin = curveRange(rotationModule.z, 0, 0);+ out.angularVelocityMin = spin.min;+ out.angularVelocityMax = spin.max;+ }++ // where particles start+ const shape = isObj(d._shapeModule) && d._shapeModule._enable === true ? d._shapeModule : null;+ if (shape) {+ out.shape = SHAPE[num(shape._shapeType, 2)] ?? 3;+ out.shapeRadius = num(shape.radius, 1);+ out.shapeAngle = num(shape.angle, 25);+ const scale = isObj(shape._scale) ? shape._scale : isObj(shape.scale) ? shape.scale : null;+ if (scale) out.shapeSize = { x: num(scale.x, 1), y: num(scale.y, 1), z: num(scale.z, 1) };+ } else {+ out.shape = 0; // Point+ }++ // bursts: the engine repeats one burst on an interval+ const bursts = (Array.isArray(d.bursts) ? d.bursts : []).filter(isObj);+ if (bursts.length > 0) {+ const b = bursts[0]!;+ out.burstCount = Math.round(mid(curveRange(b.count, 0, 0)));+ out.burstInterval = Math.max(num(b.repeatInterval, 1), 0.01);+ if (bursts.length > 1 || num(b._time, 0) > 0) lose('particle-bursts');+ }++ // a sheet of frames played over a life+ const sheet = isObj(d._textureAnimationModule) && d._textureAnimationModule._enable === true ? d._textureAnimationModule : null;+ if (sheet) {+ const cols = Math.max(1, Math.trunc(num(sheet.numTilesX, 1)));+ const rows = Math.max(1, Math.trunc(num(sheet.numTilesY, 1)));+ out.spriteColumns = cols;+ out.spriteRows = rows;+ out.spriteFPS = (cols * rows * Math.max(1, num(sheet.cycleCount, 1))) / Math.max(mid(lifetime), 0.001);+ }++ // the material says what is drawn and how it blends+ const matUuid = ((Array.isArray(d._materials) ? d._materials[0] : undefined) as Raw | undefined)?.__uuid__;+ const material = typeof matUuid === 'string' ? ctx.material?.(matUuid) ?? null : null;+ if (material) {+ if (material.texture) out.texture = ctx.assetRef(material.texture);+ out.blendMode = material.additive ? 1 : 0;+ } else {+ lose('particle-no-material');+ }++ for (const [module, code] of [+ ['_velocityOvertimeModule', 'particle-velocity-over-time'], ['_forceOvertimeModule', 'particle-force-over-time'],+ ['_limitVelocityOvertimeModule', 'particle-limit-velocity'], ['_noiseModule', 'particle-noise'], ['_trailModule', 'particle-trail'],+ ] as const) {+ const m = d[module];+ if (isObj(m) && m._enable === true) lose(code);+ }+ const renderer = isObj(d.renderer) ? d.renderer : null;+ if (renderer && num(renderer._renderMode, 0) !== 0) lose('particle-render-mode');++ ctx.report.component('cc.ParticleSystem', partial ? 'partial' : 'mapped');+ return { type: 'ParticleEmitter', data: out };+}diff --git a/pipeline/tests/cocos-particle.test.ts b/pipeline/tests/cocos-particle.test.tsnew file mode 100644index 000000000..857814f9c--- /dev/null+++ b/pipeline/tests/cocos-particle.test.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A Cocos particle system as the engine's ParticleEmitter.+ *+ * The data below is the shape of a real system (a stun effect from the client project): constants, a burst, a cone, a colour fade and a size+ * curve. The output is checked against the engine's own validator, since the offline document validators do not look at field types.+ */+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';++const SDK = path.resolve(__dirname, '../../sdk/src');+type Validate = (name: string, defaults: unknown, data: unknown, assetFields?: unknown) => { field: string; expected: string; value: unknown }[];+let validate: Validate;+let registry: Record<string, { _default: unknown; assetFields?: unknown }>;++beforeAll(async () => {+ validate = (await import(/* @vite-ignore */ path.join(SDK, 'util/validation.ts'))).validateComponentData as Validate;+ registry = await import(/* @vite-ignore */ path.join(SDK, 'ecs/component.ts'));+});++const constant = (c: number) => ({ __type__: 'cc.CurveRange', mode: 0, constant: c, multiplier: 1 });+const between = (a: number, b: number) => ({ __type__: 'cc.CurveRange', mode: 3, constantMin: a, constantMax: b, multiplier: 1 });+const curve = (values: Array<[number, number]>, multiplier = 1) => ({+ __type__: 'cc.CurveRange', mode: 1, multiplier, spline: { _values: values.map(([time, value]) => ({ time, value })) },+});+const rgba = (r: number, g: number, b: number, a: number) => ({ __type__: 'cc.Color', r, g, b, a });++function system(over: Record<string, unknown> = {}) {+ return {+ enabled: true,+ data: {+ startColor: { _mode: 0, color: rgba(255, 191, 112, 255) },+ startSize: constant(0.6), startSpeed: between(1, 3), startRotationZ: constant(0), startLifetime: constant(1),+ duration: 1, loop: false, playOnAwake: true, gravityModifier: constant(0.5), rateOverTime: constant(0),+ bursts: [{ _time: 0, count: constant(12), repeatInterval: 0.5 }], _capacity: 30, _simulationSpace: 0,+ _shapeModule: { _enable: true, _shapeType: 2, radius: 0.5, angle: 20 },+ _colorOverLifetimeModule: {+ _enable: true,+ color: { _mode: 1, gradient: { colorKeys: [{ time: 0, color: rgba(255, 255, 255, 255) }, { time: 1, color: rgba(255, 128, 0, 255) }], alphaKeys: [{ time: 0, alpha: 255 }, { time: 1, alpha: 0 }] } },+ },+ _sizeOvertimeModule: { _enable: true, size: curve([[0, 1], [1, 0.5]]) },+ _materials: [{ __uuid__: 'mat' }],+ ...over,+ },+ };+}++function convert(over: Record<string, unknown> = {}) {+ const report = new ImportReport();+ const ctx: ParticleContext = {+ report,+ material: () => ({ texture: null, additive: true }),+ assetRef: () => 'assets/cocos/spark.png',+ };+ const out = particleSystem(system(over), ctx, 'fx.prefab');+ return { out, report: report.toJSON() };+}++describe('a particle system', () => {+ it('becomes an emitter with the data the engine accepts', () => {+ const { out } = convert();+ expect(out.type).toBe('ParticleEmitter');+ const def = registry.ParticleEmitter;+ expect(def).toBeDefined();+ const errors = validate('ParticleEmitter', def!._default, out.data, def!.assetFields);+ expect(errors).toEqual([]);+ });++ it('carries emission, lifetime, speed, size, gravity and space', () => {+ const d = convert().out.data as Record<string, any>;+ expect(d.maxParticles).toBe(30);+ expect(d.looping).toBe(false);+ expect(d.burstCount).toBe(12);+ expect(d.burstInterval).toBe(0.5);+ expect([d.speedMin, d.speedMax]).toEqual([1, 3]);+ expect(d.lifetimeMin).toBe(1);+ expect(d.gravity.y).toBeCloseTo(-4.9, 5);+ expect(d.simulationSpace).toBe(1); // Cocos Local is the engine's Local (1)+ expect(d.shape).toBe(3); // Cone+ expect(d.shapeRadius).toBe(0.5);+ expect(d.blendMode).toBe(1);+ });++ it('eases the colour and the size from their values at the two ends of a life', () => {+ const d = convert().out.data as Record<string, any>;+ expect(d.startColor.a).toBeCloseTo(1, 5);+ expect(d.endColor.a).toBeCloseTo(0, 5);+ expect(d.endColor.g).toBeCloseTo((191 / 255) * (128 / 255), 4);+ expect([d.startSizeMin, d.endSizeMin]).toEqual([0.6, 0.3]);+ });++ it('counts a fade that rises and falls as partial, since the engine eases between two ends', () => {+ const fade = { _mode: 1, gradient: { colorKeys: [], alphaKeys: [{ time: 0, alpha: 0 }, { time: 0.5, alpha: 255 }, { time: 1, alpha: 0 }] } };+ const { report } = convert({ _colorOverLifetimeModule: { _enable: true, color: fade } });+ expect(report.components['cc.ParticleSystem']).toEqual({ mapped: 0, partial: 1, unmapped: 0 });+ expect(report.notes['particle-color-keys']?.count).toBe(1);+ });++ it('counts the modules the emitter has no field for', () => {+ const { report } = convert({ _noiseModule: { _enable: true }, _trailModule: { _enable: true } });+ expect(report.notes['particle-noise']?.count).toBe(1);+ expect(report.notes['particle-trail']?.count).toBe(1);+ });++ it('is fully mapped when nothing was left out', () => {+ const { report } = convert();+ expect(report.components['cc.ParticleSystem']).toEqual({ mapped: 1, partial: 0, unmapped: 0 });+ });+});++describe('a curve range', () => {+ it('is read as a constant, two constants, or a curve at the asked time', () => {+ expect(curveRange(constant(2), 0)).toEqual({ min: 2, max: 2 });+ expect(curveRange(between(1, 3), 0)).toEqual({ min: 1, max: 3 });+ expect(curveRange(curve([[0, 0], [1, 10]], 2), 0.5).min).toBeCloseTo(10, 5);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex a59d6d388..17bedcede 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): the importer maps ParticleSystem onto ParticleEmitter, and counts what the emitter has no field for':+ {"internal":"The Cocos Creator compatibility layer and importer have not shipped; nothing a creator reaches without opting in."},'feat(2d): GroupOpacity fades an entity and everything under it; sprites, text, shapes, trails and tilemap layers multiply the opacities of the groups above them into their own alpha, and the Cocos UIOpacity is a view on it':{"note":"Fade a whole group of world content with one value: `GroupOpacity`."},'feat(cocos): the importer maps DirectionalLight, Sorting and Canvas':