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: particle size-over-life curves (Phase 2, end to end)
esenginedba13c19b4f6
diff --git a/desktop/electron/extractSchemas.ts b/desktop/electron/extractSchemas.tsindex d17b2222d..9889521fe 100644--- a/desktop/electron/extractSchemas.ts+++ b/desktop/electron/extractSchemas.ts@@ -66,6 +66,7 @@ export interface SerializedFieldMeta {flags?: Array<{ label: string; value: number }>;bitmask?: { bits?: number; source?: string };gradient?: boolean;+ curve?: boolean;min?: number;max?: number;step?: number;@@ -214,6 +215,7 @@ function pickFieldMeta(if (meta.flags && meta.flags.length) m.flags = meta.flags.map((o) => ({ ...o }));if (meta.bitmask) m.bitmask = { ...meta.bitmask };if (meta.gradient) m.gradient = true;+ if (meta.curve) m.curve = true;if (meta.min != null) m.min = meta.min;if (meta.max != null) m.max = meta.max;if (meta.step != null) m.step = meta.step;diff --git a/desktop/package.json b/desktop/package.jsonindex 6efe82f14..85bc0f0d7 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -16,6 +16,7 @@"verify:render:spine": "vite build && ESTELLA_VERIFY_SCENE=/scenes/spine-test.esscene ESTELLA_VERIFY_MANIFEST=/scenes/spine-test.textures.json electron scripts/headless-verify.mjs","verify:render:particles": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/particle-demo.esscene ESTELLA_VERIFY_MANIFEST=/scenes/particle-demo.textures.json ESTELLA_VERIFY_STEPS=90 electron scripts/headless-verify.mjs","verify:render:particles:gradient": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/particle-gradient.esscene ESTELLA_VERIFY_MANIFEST=/scenes/particle-gradient.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=20 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":90}]\" electron scripts/headless-verify.mjs",+ "verify:render:particles:sizecurve": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/particle-sizecurve.esscene ESTELLA_VERIFY_MANIFEST=/scenes/particle-sizecurve.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=20 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":110},{\\\"x\\\":0.28,\\\"y\\\":0.5,\\\"rgb\\\":[0,0,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs","verify:render:postprocess": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/postprocess-effects.esscene ESTELLA_VERIFY_MANIFEST=/scenes/postprocess-effects.textures.json ESTELLA_VERIFY_STEPS=30 electron scripts/headless-verify.mjs","verify:render:text": "vite build && ESTELLA_VERIFY_SCENE=/scenes/ui-text-sdf.esscene ESTELLA_VERIFY_MANIFEST=/scenes/ui-text-sdf.textures.json electron scripts/headless-verify.mjs","verify:render:text:rect": "vite build && ESTELLA_VERIFY_SCENE=/scenes/ui-text-rect.esscene ESTELLA_VERIFY_MANIFEST=/scenes/ui-text-sdf.textures.json electron scripts/headless-verify.mjs",diff --git a/desktop/public/scenes/particle-sizecurve.esscene b/desktop/public/scenes/particle-sizecurve.esscenenew file mode 100644index 000000000..aa763e4ec--- /dev/null+++ b/desktop/public/scenes/particle-sizecurve.esscene@@ -0,0 +1,58 @@+{+ "version": "1.0",+ "name": "ParticleSizeCurve",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 100, "isActive": true, "priority": 0 } }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "SizeGrad",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },+ { "type": "ParticleEmitter", "data": {+ "rate": 0,+ "burstCount": 1,+ "burstInterval": 1000,+ "maxParticles": 1,+ "lifetimeMin": 10,+ "lifetimeMax": 10,+ "shape": 0,+ "speedMin": 0,+ "speedMax": 0,+ "startSizeMin": 120,+ "startSizeMax": 120,+ "endSizeMin": 120,+ "endSizeMax": 120,+ "gravity": { "x": 0, "y": 0 },+ "damping": 0,+ "simulationSpace": 0,+ "looping": false,+ "playOnStart": true,+ "startColor": { "r": 1, "g": 0, "b": 0, "a": 1 },+ "endColor": { "r": 1, "g": 0, "b": 0, "a": 1 },+ "texture": "@uuid:24cb4e0f-7c75-4df4-9a4d-58480ee405c0",+ "colorGradient": { "stops": [+ { "t": 0, "color": { "r": 0, "g": 1, "b": 0, "a": 1 } },+ { "t": 1, "color": { "r": 0, "g": 1, "b": 0, "a": 1 } }+ ] },+ "sizeCurve": { "keys": [+ { "t": 0, "v": 0.4 },+ { "t": 1, "v": 0.4 }+ ] }+ }}+ ],+ "visible": true+ }+ ]+}diff --git a/desktop/public/scenes/particle-sizecurve.textures.json b/desktop/public/scenes/particle-sizecurve.textures.jsonnew file mode 100644index 000000000..0acb647eb--- /dev/null+++ b/desktop/public/scenes/particle-sizecurve.textures.json@@ -0,0 +1,3 @@+{+ "24cb4e0f-7c75-4df4-9a4d-58480ee405c0": "/scenes/particle-demo/textures/particle.png"+}diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 1464f17ac..c61a596fe 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -100,7 +100,8 @@ export function toModelValue(// The hex carries alpha (#rrggbbaa), so it fully describes RGBA.return { ...(cur[key] as object), ...hexToRgba(String(value)) };case 'gradient':- return value; // a structural { stops: [...] } object — stored as-is+ case 'curve':+ return value; // a structural { stops/keys: [...] } object — stored as-isdefault:return value;}diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex b9ffd3b91..e20ff03b4 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -2,7 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { getAllRegisteredComponents, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentFieldMeta } from 'esengine';import type { App, SceneData } from 'esengine';-import type { NodeKind, InspectorField, EnumOption, GradientValue } from '@/types';+import type { NodeKind, InspectorField, EnumOption, GradientValue, CurveValue } from '@/types';type SceneEntityLike = SceneData['entities'][number];@@ -192,6 +192,7 @@ export interface UserFieldMeta {flags?: EnumOption[];bitmask?: { bits?: number; source?: string };gradient?: boolean;+ curve?: boolean;min?: number;max?: number;step?: number;@@ -270,6 +271,7 @@ export function fieldMetaFor(compType: string, key: string): UserFieldMeta | nulflags: fromDef.flags?.map((o) => ({ label: o.label, value: o.value })),bitmask: fromDef.bitmask,gradient: fromDef.gradient,+ curve: fromDef.curve,min: fromDef.min,max: fromDef.max,step: fromDef.step,@@ -336,6 +338,9 @@ function fieldFor(} else if (meta?.gradient) {const g = value && typeof value === 'object' && Array.isArray((value as GradientValue).stops) ? (value as GradientValue) : { stops: [] };field = { key, label: prettyLabel(key), type: 'gradient', value: g };+ } else if (meta?.curve) {+ const c = value && typeof value === 'object' && Array.isArray((value as CurveValue).keys) ? (value as CurveValue) : { keys: [] };+ field = { key, label: prettyLabel(key), type: 'curve', value: c };} else if (meta?.bitmask) {field = { key, label: prettyLabel(key), type: 'flags', value: Number(value) || 0, options: bitmaskOptions(meta.bitmask) };} else if (meta?.flags && meta.flags.length) {diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex cd66a5f0f..602a253af 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -42,7 +42,7 @@ import { ProjectStore } from '@/project/ProjectStore';import { ContextMenu } from '@/components/Menu';import { Popover, usePopover } from '@/components/Popover';import { AddComponentMenu } from '@/components/AddComponentMenu';-import type { InspectorComponent, InspectorField, InspectorFieldValue, EntityId, NodeKind, EnumOption, AssetType, GradientValue, GradientStop } from '@/types';+import type { InspectorComponent, InspectorField, InspectorFieldValue, EntityId, NodeKind, EnumOption, AssetType, GradientValue, GradientStop, CurveValue, CurveKey } from '@/types';const AXES = ['x', 'y', 'z'];const fmt = (n: number) => String(Math.round(n * 1000) / 1000);@@ -788,6 +788,95 @@ function GradientControl({);}+// A scalar over-life curve editor (size-over-life = a multiplier × start size):+// draggable keys on a [0,1]×[0,1] graph, click to add, select to delete. Piecewise+// linear (matches the runtime bake). Empty ⇒ the particle falls back to start/end.+function CurveControl({+ value,+ onBegin,+ onEnd,+ onChange,+}: ControlGesture & { value: CurveValue; onChange: (v: CurveValue) => void }) {+ const graph = useRef<HTMLDivElement>(null);+ const drag = useRef<number | null>(null);+ const [sel, setSel] = useState(0);+ const keys = value.keys ?? [];+ const ordered = [...keys].sort((a, b) => a.t - b.t);+ const line = ordered.map((k) => `${k.t * 100},${(1 - Math.max(0, Math.min(1, k.v))) * 100}`).join(' ');+ const posFromEvent = (e: React.PointerEvent) => {+ const r = graph.current?.getBoundingClientRect();+ if (!r) return { t: 0, v: 0 };+ return { t: Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)), v: Math.max(0, Math.min(1, 1 - (e.clientY - r.top) / r.height)) };+ };+ const commit = (next: CurveKey[]) => onChange({ keys: next });++ return (+ <div className="curve">+ <div+ ref={graph}+ className="curve-graph"+ onPointerDown={(e) => {+ if ((e.target as HTMLElement).classList.contains('curve-pt')) return;+ const p = posFromEvent(e);+ onBegin?.();+ const next = [...keys, { t: p.t, v: p.v }];+ commit(next);+ setSel(next.length - 1);+ onEnd?.();+ }}+ >+ <svg className="curve-svg" viewBox="0 0 100 100" preserveAspectRatio="none">+ {keys.length > 0 && <polyline className="curve-line" points={line} vectorEffect="non-scaling-stroke" />}+ </svg>+ {keys.map((k, i) => (+ <span+ key={i}+ className={`curve-pt${i === sel ? ' on' : ''}`}+ style={{ left: `${k.t * 100}%`, top: `${(1 - Math.max(0, Math.min(1, k.v))) * 100}%` }}+ onPointerDown={(e) => {+ e.stopPropagation();+ setSel(i);+ drag.current = i;+ onBegin?.();+ e.currentTarget.setPointerCapture(e.pointerId);+ }}+ onPointerMove={(e) => {+ if (drag.current !== i) return;+ const p = posFromEvent(e);+ commit(keys.map((kk, j) => (j === i ? { t: p.t, v: p.v } : kk)));+ }}+ onPointerUp={(e) => {+ if (drag.current !== i) return;+ drag.current = null;+ e.currentTarget.releasePointerCapture?.(e.pointerId);+ onEnd?.();+ }}+ />+ ))}+ </div>+ {keys[sel] && (+ <div className="curve-edit">+ <span className="curve-kv">t {fmt(keys[sel].t)}</span>+ <span className="curve-kv">× {fmt(keys[sel].v)}</span>+ <button+ type="button"+ className="grad-del"+ title="Remove key"+ onClick={() => {+ onBegin?.();+ commit(keys.filter((_, j) => j !== sel));+ setSel(0);+ onEnd?.();+ }}+ >+ <X size={11} strokeWidth={2} />+ </button>+ </div>+ )}+ </div>+ );+}+const isImageAsset = (t: AssetType): boolean => t === 'texture' || t === 'sprite';// An asset-ref field: a drop target showing the bound asset, PLUS a pick popover@@ -914,7 +1003,7 @@ function AssetControl({// A field write override (the live "Game" inspector routes edits to the realm// instead of the undoable SceneCommands path). When set, gestures are no-ops.-type FieldWrite = (key: string, type: InspectorField['type'], value: number | boolean | string | number[] | GradientValue) => void;+type FieldWrite = (key: string, type: InspectorField['type'], value: number | boolean | string | number[] | GradientValue | CurveValue) => void;function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp: string; field: InspectorField; write?: FieldWrite }) {const ranged = field.min != null || field.max != null;@@ -927,7 +1016,7 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp};// An edit fans out to every selected entity (the open gesture coalesces them// into one undo step); the live "Game" inspector routes to the realm instead.- const apply = (value: number | boolean | string | number[] | GradientValue) => {+ const apply = (value: number | boolean | string | number[] | GradientValue | CurveValue) => {const v = ranged && typeof value === 'number' ? clamp(value) : value;if (write) return write(field.key, field.type, v);for (const e of entities) SceneCommands.setField(e, comp, field.key, field.type, v as never);@@ -1005,6 +1094,9 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; compcase 'gradient':control = <GradientControl value={field.value as GradientValue} onBegin={begin} onEnd={end} onChange={apply} />;break;+ case 'curve':+ control = <CurveControl value={field.value as CurveValue} onBegin={begin} onEnd={end} onChange={apply} />;+ break;case 'asset':control = (<AssetControldiff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.cssindex a32f0d75f..075fdc19b 100644--- a/desktop/src/theme/inspector.css+++ b/desktop/src/theme/inspector.css@@ -146,6 +146,17 @@.grad-edit { display: flex; align-items: center; gap: 6px; }.grad-del { width: 22px; height: 22px; display: grid; place-items: center; color: var(--text-mute); border: 1px solid var(--border-line); border-radius: var(--r-sm); flex-shrink: 0; transition: color var(--t-fast), border-color var(--t-fast); }.grad-del:hover { color: var(--error); border-color: var(--error); }++/* scalar over-life curve editor (size-over-life): a [0,1]×[0,1] graph of keys */+.curve { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }+.curve-graph { position: relative; height: 56px; border-radius: var(--r-sm); border: 1px solid var(--border); background: var(--inset); cursor: copy; overflow: hidden; }+.curve-svg { position: absolute; inset: 0; width: 100%; height: 100%; }+.curve-line { fill: none; stroke: var(--acc); stroke-width: 1.5px; }+.curve-pt { position: absolute; width: 9px; height: 9px; border-radius: 50%; background: var(--text); border: 2px solid var(--srf-2); transform: translate(-50%, -50%); cursor: grab; box-shadow: 0 0 0 1px rgba(0,0,0,.4); }+.curve-pt.on { background: var(--acc-hi); }+.curve-edit { display: flex; align-items: center; gap: 10px; font-size: var(--fs-xs); color: var(--text-dim); }+.curve-kv { font-family: var(--mono); }+.curve-edit .grad-del { margin-left: auto; }.slider { flex: 1; height: 6px; background: var(--inset); border-radius: var(--r-pill); position: relative; cursor: ew-resize; touch-action: none; }.slider .fill { position: absolute; left: 0; top: 0; bottom: 0; background: var(--acc); border-radius: var(--r-pill); }.slider .thumb { position: absolute; top: 50%; width: 11px; height: 11px; border-radius: 50%; background: var(--text); transform: translate(-50%,-50%); box-shadow: var(--shadow-1); }diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 3c44779e5..fe1ffc860 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -38,6 +38,7 @@ export type InspectorFieldType =| 'enum' // an int field with named options, shown as a dropdown| 'flags' // an int bitmask, shown as a multi-select of its bits| 'gradient' // a color-over-life gradient ({ stops: [...] })+ | 'curve' // a scalar over-life curve ({ keys: [...] })| 'asset'; // a texture/material/font/... ref (@uuid: string, or 0 for none)/** A dropdown option for an `enum` field: the label shown, the int stored. */@@ -56,13 +57,24 @@ export interface GradientValue {stops: GradientStop[];}+/** One key of a `curve` field: a 0..1 position + a scalar value. */+export interface CurveKey {+ t: number;+ v: number;+}+/** A `curve` field's value — scalar keys over [0,1] (piecewise-linear). */+export interface CurveValue {+ keys: CurveKey[];+}+export type InspectorFieldValue =| number| boolean| string| [number, number]| [number, number, number]- | GradientValue;+ | GradientValue+ | CurveValue;export interface InspectorField {/** key in the component data object */diff --git a/desktop/tests/inspector-model.test.ts b/desktop/tests/inspector-model.test.tsindex 174ddc58f..bdc903429 100644--- a/desktop/tests/inspector-model.test.ts+++ b/desktop/tests/inspector-model.test.ts@@ -318,6 +318,28 @@ describe('Color gradient field (particle color-over-life)', () => {expect(after.stops[0].t).toBe(0.5);});+ it("renders ParticleEmitter.sizeCurve as a 'curve' field that round-trips", () => {+ const curve = { keys: [{ t: 0, v: 1 }, { t: 1, v: 0 }] };+ const S = EditorSession.create();+ S.model.adopt(+ {+ version: '1.0',+ name: 'p',+ entities: [{ id: 1, name: 'P', parent: null, children: [], components: [{ type: 'ParticleEmitter', data: { sizeCurve: curve } }] }],+ } as unknown as SceneData,+ new Map([[1, 1]]),+ );+ const field = () =>+ S.query.readInspector(1).find((c) => c.name === 'ParticleEmitter')!.fields.find((f) => f.key === 'sizeCurve')!;+ const c = field();+ expect(c.type).toBe('curve');+ expect((c.value as { keys: unknown[] }).keys.length).toBe(2);++ S.commands.setField(1, 'ParticleEmitter', 'sizeCurve', 'curve', { keys: [{ t: 0.5, v: 0.25 }] } as never);+ const after = field().value as { keys: { t: number; v: number }[] };+ expect(after.keys).toEqual([{ t: 0.5, v: 0.25 }]);+ });+it('an empty gradient field reads as empty stops (sim falls back to start/end)', () => {const S = EditorSession.create();S.model.adopt(diff --git a/sdk/src/component.ts b/sdk/src/component.tsindex 89384b4fa..c6b50b1c2 100644--- a/sdk/src/component.ts+++ b/sdk/src/component.ts@@ -44,6 +44,8 @@ export interface FieldMeta {flags?: ReadonlyArray<{ label: string; value: number }>;/** Render as a color-gradient editor (the field value is `{ stops: [...] }`). */gradient?: boolean;+ /** Render as a scalar over-life curve editor (the field value is `{ keys: [...] }`). */+ curve?: boolean;/*** Render as a bitmask whose bit LABELS are resolved by the editor (e.g. named* collision layers from project settings) rather than fixed here. `bits` is the@@ -757,10 +759,16 @@ export interface ParticleEmitterData {* samples (see particlePlugin's scene codec). Empty ⇒ start/end fallback.*/colorGradient: { stops: { t: number; color: Color }[] };+ /**+ * Size-over-life curve (a multiplier × start size, keys over [0,1]). When it+ * has keys it overrides startSize/endSize + sizeEasing. Out-of-band like+ * colorGradient. Empty ⇒ start/end fallback.+ */+ sizeCurve: { keys: { t: number; v: number }[] };}export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitter',- metaDefaults<ParticleEmitterData>('ParticleEmitter', { colorGradient: { stops: [] } }),+ metaDefaults<ParticleEmitterData>('ParticleEmitter', { colorGradient: { stops: [] }, sizeCurve: { keys: [] } }),{// A large component — organized into UE-style property categories.fields: {@@ -783,6 +791,7 @@ export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmittangleSpreadMax: { unit: '°', category: 'Velocity' },gravity: { category: 'Velocity' },damping: { min: 0, category: 'Velocity' },+ sizeCurve: { curve: true, category: 'Size' },startSizeMin: { min: 0, category: 'Size' },startSizeMax: { min: 0, category: 'Size' },endSizeMin: { min: 0, category: 'Size' },diff --git a/sdk/src/particle/ParticleAPI.ts b/sdk/src/particle/ParticleAPI.tsindex 10ea38986..991159004 100644--- a/sdk/src/particle/ParticleAPI.ts+++ b/sdk/src/particle/ParticleAPI.ts@@ -47,19 +47,34 @@ export class ParticleAPI {* data is copied into the wasm heap for the call, then freed.*/setColorLut(entity: Entity, lut: Float32Array | null): void {- const m = this.module_;- if (!m.particle_set_color_lut) return;+ this.uploadLut(this.module_.particle_set_color_lut, entity, lut, 4);+ }++ /** Upload an entity's baked size-over-life multiplier LUT (an N-scalar+ * Float32Array), or null to clear. */+ setSizeLut(entity: Entity, lut: Float32Array | null): void {+ this.uploadLut(this.module_.particle_set_size_lut, entity, lut, 1);+ }++ // Copy a Float32Array into the wasm heap and hand its pointer + element count+ // (length / `stride`) to the C++ setter, then free; null/empty clears.+ private uploadLut(+ fn: ((entity: number, ptr: number, count: number) => void) | undefined,+ entity: Entity,+ lut: Float32Array | null,+ stride: number,+ ): void {+ if (!fn) return;if (!lut || lut.length === 0) {- m.particle_set_color_lut(entity as number, 0, 0);+ fn(entity as number, 0, 0);return;}- const bytes = lut.length * 4;- const ptr = m._malloc(bytes);+ const ptr = this.module_._malloc(lut.length * 4);try {- m.HEAPF32.set(lut, ptr / 4);- m.particle_set_color_lut(entity as number, ptr, lut.length / 4);+ this.module_.HEAPF32.set(lut, ptr / 4);+ fn(entity as number, ptr, lut.length / stride);} finally {- m._free(ptr);+ this.module_._free(ptr);}}}diff --git a/sdk/src/particle/ParticlePlugin.ts b/sdk/src/particle/ParticlePlugin.tsindex b9f757784..88d6873e4 100644--- a/sdk/src/particle/ParticlePlugin.ts+++ b/sdk/src/particle/ParticlePlugin.ts@@ -9,12 +9,15 @@ import type { ESEngineModule, CppRegistry } from '../wasm';import { registerSceneComponentCodec } from '../scene';import { Particle, ParticleAPI } from './ParticleAPI';import { bakeGradient, type Gradient } from './gradient';+import { bakeCurve, type Curve } from './curve';export class ParticlePlugin implements Plugin {name = 'particle';/** Entity → authored color-over-life gradient (out-of-band; baked to the C++ LUT). */private readonly gradients_ = new Map<number, Gradient>();+ /** Entity → authored size-over-life curve (out-of-band; baked to the C++ LUT). */+ private readonly sizeCurves_ = new Map<number, Curve>();build(app: App): void {const module = app.wasmModule as ESEngineModule;@@ -25,17 +28,25 @@ export class ParticlePlugin implements Plugin {// The color gradient is authored as stops in the component data but isn't a// C++ field — carry it out-of-band and bake it into the sim's LUT on load.const gradients = this.gradients_;+ const sizeCurves = this.sizeCurves_;registerSceneComponentCodec('ParticleEmitter', {- outOfBandFields: ['colorGradient'],+ outOfBandFields: ['colorGradient', 'sizeCurve'],importData: (entity, outOfBand) => {const g = outOfBand.colorGradient as Gradient | undefined;api.setColorLut(entity, bakeGradient(g));if (g?.stops?.length) gradients.set(entity, g);else gradients.delete(entity);++ const c = outOfBand.sizeCurve as Curve | undefined;+ api.setSizeLut(entity, bakeCurve(c));+ if (c?.keys?.length) sizeCurves.set(entity, c);+ else sizeCurves.delete(entity);},exportData: (entity, data) => {const g = gradients.get(entity);if (g) data.colorGradient = g;+ const c = sizeCurves.get(entity);+ if (c) data.sizeCurve = c;},});diff --git a/sdk/src/particle/curve.ts b/sdk/src/particle/curve.tsnew file mode 100644index 000000000..7f15522e6--- /dev/null+++ b/sdk/src/particle/curve.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file curve.ts+ * @brief Scalar over-life curve + LUT baking (the size-over-life sibling of+ * gradient.ts). The editor authors a curve (points over [0,1]); this+ * bakes it to a fixed scalar lookup table the C++ particle sim samples by+ * normalized particle age. Same "TS bakes, C++ samples" keystone.+ */+import { GRADIENT_LUT_SIZE } from './gradient';++export interface CurveKey {+ /** Position along life, 0..1. */+ t: number;+ /** Value at this key (size-over-life: a multiplier of the particle's start size). */+ v: number;+}++export interface Curve {+ keys: CurveKey[];+}++function sampleCurve(sorted: CurveKey[], t: number): number {+ const first = sorted[0];+ if (t <= first.t) return first.v;+ const last = sorted[sorted.length - 1];+ if (t >= last.t) return last.v;+ for (let i = 0; i < sorted.length - 1; i++) {+ const a = sorted[i];+ const b = sorted[i + 1];+ if (t >= a.t && t <= b.t) {+ const span = b.t - a.t;+ const f = span > 1e-6 ? (t - a.t) / span : 0;+ return a.v + (b.v - a.v) * f;+ }+ }+ return last.v;+}++/**+ * Bake a curve into an `n`-sample scalar table over [0,1] (piecewise linear).+ * Returns null for an empty/absent curve — the caller clears the LUT so the sim+ * falls back to start/end size + easing.+ */+export function bakeCurve(curve: Curve | null | undefined, n = GRADIENT_LUT_SIZE): Float32Array | null {+ const keys = curve?.keys;+ if (!keys || keys.length === 0) return null;+ const sorted = [...keys].sort((a, b) => a.t - b.t);+ const out = new Float32Array(n);+ for (let i = 0; i < n; i++) out[i] = sampleCurve(sorted, n > 1 ? i / (n - 1) : 0);+ return out;+}diff --git a/sdk/src/particle/index.ts b/sdk/src/particle/index.tsindex f99cd5599..46b70dfba 100644--- a/sdk/src/particle/index.ts+++ b/sdk/src/particle/index.ts@@ -3,3 +3,4 @@export { Particle, ParticleAPI } from './ParticleAPI';export { ParticlePlugin, particlePlugin } from './ParticlePlugin';export { bakeGradient, GRADIENT_LUT_SIZE, type Gradient, type GradientStop } from './gradient';+export { bakeCurve, type Curve, type CurveKey } from './curve';diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 9c39b7857..7a555d049 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -250,6 +250,8 @@ export interface ESEngineModule {particle_getAliveCount?(entity: number): number;/** Upload (count = LUT size) or clear (count = 0) an entity's baked color-over-life LUT. */particle_set_color_lut?(entity: number, ptr: number, count: number): void;+ /** Upload/clear an entity's baked size-over-life multiplier LUT. */+ particle_set_size_lut?(entity: number, ptr: number, count: number): void;// Tilemap APItilemap_initLayer?(entity: number, width: number, height: number,diff --git a/sdk/tests/curve.test.ts b/sdk/tests/curve.test.tsnew file mode 100644index 000000000..f88d332c5--- /dev/null+++ b/sdk/tests/curve.test.ts@@ -0,0 +1,26 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { bakeCurve } from '../src/particle/curve';+import { GRADIENT_LUT_SIZE } from '../src/particle/gradient';++describe('bakeCurve', () => {+ it('returns null for an empty or absent curve (sim falls back to start/end)', () => {+ expect(bakeCurve(null)).toBeNull();+ expect(bakeCurve({ keys: [] })).toBeNull();+ });++ it('bakes N scalar samples, piecewise-linear between keys', () => {+ const lut = bakeCurve({ keys: [{ t: 0, v: 1 }, { t: 1, v: 0 }] })!;+ expect(lut.length).toBe(GRADIENT_LUT_SIZE);+ expect(lut[0]).toBeCloseTo(1, 5); // v=1 at t=0+ expect(lut[GRADIENT_LUT_SIZE - 1]).toBeCloseTo(0, 5); // v=0 at t=1+ expect(lut[Math.round((GRADIENT_LUT_SIZE - 1) / 2)]).toBeCloseTo(0.5, 1); // midpoint+ });++ it('clamps before the first key / after the last + sorts unordered keys', () => {+ const lut = bakeCurve({ keys: [{ t: 1, v: 0.2 }, { t: 0.5, v: 1 }] })!;+ expect(lut[0]).toBeCloseTo(1, 5); // before the first sorted key (t=0.5) holds its value+ expect(lut[GRADIENT_LUT_SIZE - 1]).toBeCloseTo(0.2, 5);+ });+});diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex 31c034f0a..a14eb16d7 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -335,6 +335,11 @@ void particle_set_color_lut(u32 entity, uintptr_t ptr, i32 count) {if (!g_particleSystem) return;g_particleSystem->setColorLut(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);}++void particle_set_size_lut(u32 entity, uintptr_t ptr, i32 count) {+ if (!g_particleSystem) return;+ g_particleSystem->setSizeLut(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);+}#endifvoid renderer_setStage(i32 stage) {diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 0913d60b5..38acfb8a3 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -90,6 +90,7 @@ void particle_stop(ecs::Registry& registry, Entity entity);void particle_reset(ecs::Registry& registry, Entity entity);u32 particle_getAliveCount(Entity entity);void particle_set_color_lut(u32 entity, uintptr_t ptr, i32 count);+void particle_set_size_lut(u32 entity, uintptr_t ptr, i32 count);#endifvoid renderer_setStage(i32 stage);u32 renderer_createTarget(u32 width, u32 height, i32 flags);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex baa34c9f9..0a99da79d 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -464,6 +464,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("particle_reset", &esengine::particle_reset);emscripten::function("particle_getAliveCount", &esengine::particle_getAliveCount);emscripten::function("particle_set_color_lut", &esengine::particle_set_color_lut);+ emscripten::function("particle_set_size_lut", &esengine::particle_set_size_lut);#endifemscripten::function("renderer_setStage", &esengine::renderer_setStage);emscripten::function("renderer_createTarget", &esengine::renderer_createTarget);diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cppindex 27ffcf0d1..0a24c7603 100644--- a/src/esengine/particle/ParticleSystem.cpp+++ b/src/esengine/particle/ParticleSystem.cpp@@ -16,6 +16,7 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {destroyConn_ = registry.onDestroyScoped([this](Entity entity) {states_.erase(entity);colorLuts_.erase(entity);+ sizeLuts_.erase(entity);});}@@ -75,7 +76,10 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {}auto lutIt = colorLuts_.find(entity);- updateParticles(emitter, state, dt, lutIt != colorLuts_.end() ? &lutIt->second : nullptr);+ auto sizeIt = sizeLuts_.find(entity);+ updateParticles(emitter, state, dt,+ lutIt != colorLuts_.end() ? &lutIt->second : nullptr,+ sizeIt != sizeLuts_.end() ? &sizeIt->second : nullptr);}}@@ -116,6 +120,15 @@ void ParticleSystem::setColorLut(Entity entity, const f32* rgba, i32 count) {}}+void ParticleSystem::setSizeLut(Entity entity, const f32* values, i32 count) {+ if (count != kColorLutSize || values == nullptr) {+ sizeLuts_.erase(entity);+ return;+ }+ SizeLut& lut = sizeLuts_[entity];+ for (std::size_t i = 0; i < kColorLutSize; ++i) lut[i] = values[i];+}+u32 ParticleSystem::aliveCount(Entity entity) const {auto it = states_.find(entity);if (it != states_.end()) {@@ -238,9 +251,16 @@ static glm::vec4 sampleColorLut(const ColorLut& lut, f32 t) {return math::lerp(lut[i], lut[j], f - static_cast<f32>(i));}+static f32 sampleSizeLut(const SizeLut& lut, f32 t) {+ f32 f = std::clamp(t, 0.0f, 1.0f) * static_cast<f32>(kColorLutSize - 1);+ auto i = static_cast<std::size_t>(f);+ std::size_t j = std::min(i + 1, static_cast<std::size_t>(kColorLutSize - 1));+ return math::lerp(lut[i], lut[j], f - static_cast<f32>(i));+}+void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,EmitterState& state, f32 dt,- const ColorLut* colorLut) {+ const ColorLut* colorLut, const SizeLut* sizeLut) {auto sizeEasing = static_cast<EasingType>(emitter.sizeEasing);auto colorEasing = static_cast<EasingType>(emitter.colorEasing);i32 totalFrames = emitter.spriteColumns * emitter.spriteRows;@@ -266,8 +286,12 @@ void ParticleSystem::updateParticles(const ecs::ParticleEmitter& emitter,p.rotation += p.angular_velocity * dt;- f32 sizeT = applyEasing(sizeEasing, t);- p.size = math::lerp(p.start_size, p.end_size, sizeT);+ if (sizeLut) {+ p.size = p.start_size * sampleSizeLut(*sizeLut, t);+ } else {+ f32 sizeT = applyEasing(sizeEasing, t);+ p.size = math::lerp(p.start_size, p.end_size, sizeT);+ }if (colorLut) {p.color = sampleColorLut(*colorLut, t);diff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hppindex 9577ff937..b3897394c 100644--- a/src/esengine/particle/ParticleSystem.hpp+++ b/src/esengine/particle/ParticleSystem.hpp@@ -17,10 +17,12 @@namespace esengine::particle {-// Resolution of the per-emitter color-over-life lookup table (baked in TS from a-// gradient, sampled here per particle). 32 keeps gradients smooth and small.+// Resolution of the per-emitter over-life lookup tables (baked in TS from a+// gradient/curve, sampled here per particle). 32 keeps them smooth and small.inline constexpr int kColorLutSize = 32;using ColorLut = std::array<glm::vec4, kColorLutSize>;+// Size-over-life: a scalar multiplier curve × the particle's start size.+using SizeLut = std::array<f32, kColorLutSize>;struct EmitterState {ParticlePool pool;@@ -54,6 +56,8 @@ public:/** Set (count == kColorLutSize) or clear (count == 0) an entity's color-over-life* LUT. When set, particle color is sampled from it instead of start/end+easing. */void setColorLut(Entity entity, const f32* rgba, i32 count);+ /** Set/clear an entity's size-over-life multiplier LUT (× the particle's start size). */+ void setSizeLut(Entity entity, const f32* values, i32 count);private:void emitParticles(const ecs::ParticleEmitter& emitter,@@ -61,13 +65,14 @@ private:EmitterState& state, u32 count);void updateParticles(const ecs::ParticleEmitter& emitter, EmitterState& state, f32 dt,- const ColorLut* colorLut);+ const ColorLut* colorLut, const SizeLut* sizeLut);f32 randomRange(f32 min, f32 max);glm::vec2 randomDirection(f32 angleMin, f32 angleMax);glm::vec2 randomShapeOffset(const ecs::ParticleEmitter& emitter);std::unordered_map<Entity, EmitterState> states_;std::unordered_map<Entity, ColorLut> colorLuts_;+ std::unordered_map<Entity, SizeLut> sizeLuts_;std::mt19937 rng_;std::vector<u32> dead_particle_indices_;// RAII: auto-unregisters from the registry's onDestroy when this system is