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(render): motion trails - TrailRenderer ribbon through the batch face
yhhf96623c511e0
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex a92164648..97918cada 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -254,6 +254,16 @@ jobs:ESTELLA_VERIFY_MANIFEST=/scenes/ysort.textures.json \ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 \'ESTELLA_VERIFY_EXPECT=[{"x":0.5,"y":0.5,"rgb":[255,0,0],"tol":30}]'+ # Motion trail: move a TrailRenderer entity across the frame in play mode,+ # asserting the ribbon rasterizes as a green band (head/mid/tail) with black+ # above it — the CPU-ribbon-through-the-batch-face path.+ run_scene trail \+ ESTELLA_VERIFY_PLAY=1 \+ ESTELLA_VERIFY_SCENE=/scenes/trail.esscene \+ ESTELLA_VERIFY_MANIFEST=/scenes/trail.textures.json \+ ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 \+ 'ESTELLA_VERIFY_TRAIL={"from":[-200,0],"to":[200,0],"steps":20}' \+ 'ESTELLA_VERIFY_EXPECT=[{"x":0.80,"y":0.5,"rgb":[0,255,0],"tol":50},{"x":0.5,"y":0.5,"rgb":[0,255,0],"tol":50},{"x":0.25,"y":0.5,"rgb":[0,255,0],"tol":60},{"x":0.5,"y":0.15,"rgb":[0,0,0],"tol":30}]'# The SAME pixel assertions on the WebGPU backend — Dawn renders through the# bundled SwiftShader Vulkan (--use-webgpu-adapter=swiftshader), so a GPU-less@@ -294,3 +304,10 @@ jobs:ESTELLA_VERIFY_MANIFEST=/scenes/ysort.textures.json \ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 \'ESTELLA_VERIFY_EXPECT=[{"x":0.5,"y":0.5,"rgb":[0,255,0],"tol":30},{"x":0.5,"y":0.25,"rgb":[255,0,0],"tol":30},{"x":0.5,"y":0.75,"rgb":[0,255,0],"tol":30}]'+ run_scene webgpu-trail \+ ESTELLA_VERIFY_PLAY=1 \+ ESTELLA_VERIFY_SCENE=/scenes/trail.esscene \+ ESTELLA_VERIFY_MANIFEST=/scenes/trail.textures.json \+ ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 \+ 'ESTELLA_VERIFY_TRAIL={"from":[-200,0],"to":[200,0],"steps":20}' \+ 'ESTELLA_VERIFY_EXPECT=[{"x":0.80,"y":0.5,"rgb":[0,255,0],"tol":50},{"x":0.5,"y":0.5,"rgb":[0,255,0],"tol":50},{"x":0.25,"y":0.5,"rgb":[0,255,0],"tol":60},{"x":0.5,"y":0.15,"rgb":[0,0,0],"tol":30}]'diff --git a/CMakeLists.txt b/CMakeLists.txtindex b60ce971c..14767130e 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -74,6 +74,8 @@ set(ESENGINE_SOURCESsrc/esengine/renderer/plugins/TextPlugin.cppsrc/esengine/renderer/plugins/ShapePlugin.cppsrc/esengine/renderer/plugins/MeshPlugin.cpp+ src/esengine/renderer/plugins/TrailPlugin.cpp+ src/esengine/trail/TrailSystem.cppsrc/esengine/platform/PathResolver.cppsrc/esengine/animation/TweenSystem.cppsrc/esengine/ecs/UILayoutSystem.cpp@@ -147,6 +149,9 @@ set(ESENGINE_HEADERSsrc/esengine/renderer/Framebuffer.hppsrc/esengine/renderer/RenderStage.hppsrc/esengine/renderer/RenderItem.hpp+ src/esengine/renderer/plugins/TrailPlugin.hpp+ src/esengine/trail/TrailSystem.hpp+ src/esengine/ecs/components/TrailRenderer.hppsrc/esengine/renderer/RenderTarget.hppsrc/esengine/renderer/RenderFrame.hppsrc/esengine/renderer/ImmediateDraw.hppdiff --git a/desktop/package.json b/desktop/package.jsonindex aad5736f9..71aa7aba8 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -58,6 +58,7 @@"verify:render:tilemap:hex": "vite build && ESTELLA_VERIFY_SCENE=/scenes/tilemap-hex.esscene ESTELLA_VERIFY_MANIFEST=/scenes/tilemap-hex.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=6 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.40,\\\"y\\\":0.40,\\\"rgb\\\":[255,0,0]},{\\\"x\\\":0.60,\\\"y\\\":0.40,\\\"rgb\\\":[0,255,0]},{\\\"x\\\":0.50,\\\"y\\\":0.55,\\\"rgb\\\":[0,0,255]},{\\\"x\\\":0.70,\\\"y\\\":0.55,\\\"rgb\\\":[255,255,0]}]\" electron scripts/headless-verify.mjs","verify:render:mesh2d": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mesh2d.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mesh2d.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=4 ESTELLA_VERIFY_EXPECT='[{\"x\":0.30,\"y\":0.556,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.70,\"y\":0.556,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.40,\"rgb\":[255,0,0],\"tol\":40}]' electron scripts/headless-verify.mjs","verify:render:parallax:shape": "vite build && ESTELLA_VERIFY_SCENE=/scenes/parallax-shape.esscene ESTELLA_VERIFY_MANIFEST=/scenes/parallax-shape.textures.json ESTELLA_VERIFY_STEPS=4 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":40},{\\\"x\\\":0.25,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs",+ "verify:render:trail": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/trail.esscene ESTELLA_VERIFY_MANIFEST=/scenes/trail.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_TRAIL='{\"from\":[-200,0],\"to\":[200,0],\"steps\":20}' ESTELLA_VERIFY_EXPECT='[{\"x\":0.80,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50},{\"x\":0.25,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":60},{\"x\":0.5,\"y\":0.15,\"rgb\":[0,0,0],\"tol\":30}]' electron scripts/headless-verify.mjs","verify:render:postprocess:lut": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/lut-grade.esscene ESTELLA_VERIFY_MANIFEST=/scenes/lut-grade.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=10 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.292,\\\"y\\\":0.5,\\\"rgb\\\":[0,0,255],\\\"tol\\\":40},{\\\"x\\\":0.708,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs"},"dependencies": {diff --git a/desktop/public/scenes/trail.esscene b/desktop/public/scenes/trail.esscenenew file mode 100644index 000000000..fa09e5b62--- /dev/null+++ b/desktop/public/scenes/trail.esscene@@ -0,0 +1,43 @@+{+ "version": "1.0",+ "name": "Trail",+ "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": 300, "isActive": true, "priority": 0 } }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Trailer",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": -200, "y": 0, "z": 0 } } },+ {+ "type": "TrailRenderer",+ "data": {+ "time": 1.0,+ "minVertexDistance": 5,+ "emitting": true,+ "startWidth": 50,+ "endWidth": 50,+ "startColor": { "r": 0, "g": 1, "b": 0, "a": 1 },+ "endColor": { "r": 0, "g": 1, "b": 0, "a": 1 },+ "blendMode": 0,+ "layer": 0,+ "material": 0,+ "enabled": true+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/desktop/public/scenes/trail.textures.json b/desktop/public/scenes/trail.textures.jsonnew file mode 100644index 000000000..0967ef424--- /dev/null+++ b/desktop/public/scenes/trail.textures.json@@ -0,0 +1 @@+{}diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjsindex e46e7dc1c..1bd1919a3 100644--- a/desktop/scripts/headless-verify.mjs+++ b/desktop/scripts/headless-verify.mjs@@ -131,7 +131,36 @@ app.whenReady().then(async () => {if (process.env.ESTELLA_VERIFY_YSORT) {await exec(`window.__estellaHeadless.api.setYSortLayers(${Number(process.env.ESTELLA_VERIFY_YSORT)})`);}- await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);+ // ESTELLA_VERIFY_TRAIL = {"from":[x,y],"to":[x,y],"steps":N}: move the entity+ // carrying a TrailRenderer along a world-space path, one frame per sample, so+ // the trail system records points — motion a static scene can't express.+ // Requires play mode (ESTELLA_VERIFY_PLAY=1) for the trail update to run.+ if (process.env.ESTELLA_VERIFY_TRAIL) {+ const trail = JSON.parse(process.env.ESTELLA_VERIFY_TRAIL);+ await exec(`(async () => {+ const cfg = ${JSON.stringify(trail)};+ const api = window.__estellaHeadless.api;+ const flat = [];+ const walk = (nodes) => { for (const n of nodes) { flat.push(n.id); if (n.children) walk(n.children); } };+ walk(api.getSceneTree());+ // getEntity().components returns humanized display names ("Trail Renderer"),+ // so compare with whitespace stripped.+ let target = null;+ for (const id of flat) {+ const e = api.getEntity(id);+ if (e && e.components && e.components.some((c) => c.replace(/\\s+/g, '') === 'TrailRenderer')) { target = id; break; }+ }+ if (target == null) throw new Error('no TrailRenderer entity in scene');+ const [fx, fy] = cfg.from, [tx, ty] = cfg.to, N = cfg.steps;+ for (let i = 0; i <= N; i++) {+ const t = N === 0 ? 1 : i / N;+ api.setEntityXY(target, fx + (tx - fx) * t, fy + (ty - fy) * t);+ await api.step(1, 1 / 60);+ }+ })()`);+ } else {+ await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);+ }// WebGPU: the engine has no synchronous readback (buffer maps are async)// and a hidden window never presents, so drawImage-style page readback isdiff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.tsindex 969f9e03d..ffe1a664a 100644--- a/sdk/src/component.generated.ts+++ b/sdk/src/component.generated.ts@@ -15,7 +15,7 @@ import type { Dimension, Padding, VisualState } from './wasm.generated';* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to* run on mismatch, because mismatched offsets read the wrong heap bytes.*/-export const ABI_LAYOUT_HASH = '89e3ae10e24e8bc9';+export const ABI_LAYOUT_HASH = '89ad72a9b853289f';export interface AssetFieldMeta {field: string;@@ -555,6 +555,39 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {opacity: { min: 0, max: 1, slider: true, tooltip: "Layer transparency (0 = invisible, 1 = opaque)." },},},+ TrailRenderer: {+ defaults: {+ time: 0.5,+ minVertexDistance: 5,+ emitting: true,+ startWidth: 20,+ endWidth: 0,+ startColor: { r: 1, g: 1, b: 1, a: 1 },+ endColor: { r: 1, g: 1, b: 1, a: 0 },+ texture: 0,+ blendMode: 0,+ layer: 0,+ material: 0,+ enabled: true,+ },+ assetFields: [{ field: 'texture', type: 'texture' as AssetFieldType }, { field: 'material', type: 'material' as AssetFieldType }],+ entityFields: [],+ colorFields: ['startColor', 'endColor'],+ animatableFields: ['startColor.r', 'startColor.g', 'startColor.b', 'startColor.a', 'endColor.r', 'endColor.g', 'endColor.b', 'endColor.a'],+ fields: {+ time: { min: 0, tooltip: "Seconds each trail point lives before it fades out of the tail.", category: "Trail" },+ minVertexDistance: { min: 0, tooltip: "Min world distance moved before a new trail point is recorded.", category: "Trail" },+ emitting: { tooltip: "Record new points. False = freeze and let the streak fade in place.", category: "Trail" },+ startWidth: { min: 0, tooltip: "Full ribbon width at the head (newest point).", category: "Width" },+ endWidth: { min: 0, tooltip: "Full ribbon width at the tail (oldest point).", category: "Width" },+ startColor: { tooltip: "Color at the head (newest point).", category: "Color" },+ endColor: { tooltip: "Color at the tail (oldest point) — usually alpha 0 to fade out.", category: "Color" },+ texture: { category: "Rendering" },+ blendMode: { tooltip: "Blend mode: 0 Normal, 1 Additive (glow), 2 Multiply, …", category: "Rendering" },+ layer: { step: 1, tooltip: "Sorting layer — controls draw order across renderables.", category: "Rendering", enumSource: "sortingLayers" },+ material: { category: "Rendering", advanced: true },+ },+ },Transform: {defaults: {position: { x: 0, y: 0, z: 0 },@@ -932,6 +965,21 @@ export interface TilemapLayerData {visible: boolean;}+export interface TrailRendererData {+ time: number;+ minVertexDistance: number;+ emitting: boolean;+ startWidth: number;+ endWidth: number;+ startColor: Color;+ endColor: Color;+ texture: number;+ blendMode: number;+ layer: number;+ material: number;+ enabled: boolean;+}+export interface TransformData {position: Vec3;rotation: Quat;diff --git a/sdk/src/component.ts b/sdk/src/component.tsindex a01907f71..82f6896e7 100644--- a/sdk/src/component.ts+++ b/sdk/src/component.ts@@ -14,7 +14,7 @@ import { COMPONENT_META, type AssetFieldMeta, type SpineFieldMeta } from './compimport type {TransformData, SpriteData, ShapeRendererData, Light2DData, ShadowCaster2DData,CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData,- TilemapLayerData, BitmapTextData,+ TilemapLayerData, BitmapTextData, TrailRendererData,CameraData as CameraDataCpp, ParticleEmitterData as ParticleEmitterDataCpp,Mesh2DData as Mesh2DDataCpp,} from './component.generated';@@ -592,7 +592,7 @@ export type ScaleMode = (typeof ScaleMode)[keyof typeof ScaleMode];export type {TransformData, SpriteData, ShapeRendererData, Light2DData, ShadowCaster2DData,CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData,- TilemapLayerData, BitmapTextData,+ TilemapLayerData, BitmapTextData, TrailRendererData,};export type LocalTransformData = TransformData;@@ -736,6 +736,12 @@ export const Mesh2D = defineBuiltin<Mesh2DData>('Mesh2D',metaDefaults<Mesh2DData>('Mesh2D', { geometry: { positions: [], indices: [] } }));+// Motion trail. Pure config — the point history is owned by the C++ TrailSystem and+// rendered as a ribbon by TrailPlugin; nothing crosses as a component field.+export const TrailRenderer = defineBuiltin<TrailRendererData>('TrailRenderer',+ metaDefaults<TrailRendererData>('TrailRenderer')+);+export const TilemapLayer = defineBuiltin<TilemapLayerData>('TilemapLayer',metaDefaults<TilemapLayerData>('TilemapLayer'),{diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 0f9944152..fbf2f8456 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -310,6 +310,17 @@ export {particlePlugin,} from './particle';+// =============================================================================+// Trail+// =============================================================================++export {+ Trail,+ TrailAPI,+ TrailPlugin,+ trailPlugin,+} from './trail';+// =============================================================================// Mesh2D// =============================================================================diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex b0f78b7d0..e6548dfd0 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -90,6 +90,7 @@ export {Light2D,Light2DType,ShadowCaster2D,+ TrailRenderer,Camera,Canvas,Velocity,@@ -117,6 +118,7 @@ export {type ParentData,type ChildrenData,type BitmapTextData,+ type TrailRendererData,type SpineAnimationData,type RigidBodyData,type BoxColliderData,diff --git a/sdk/src/ecs/ptrAccessors.generated.ts b/sdk/src/ecs/ptrAccessors.generated.tsindex b8f2a03b3..12ff9dbf4 100644--- a/sdk/src/ecs/ptrAccessors.generated.ts+++ b/sdk/src/ecs/ptrAccessors.generated.ts@@ -1085,6 +1085,74 @@ export function createTilemapLayerData(): TilemapLayerPtrData {};}+export interface TrailRendererPtrData {+ time: number;+ minVertexDistance: number;+ emitting: boolean;+ startWidth: number;+ endWidth: number;+ startColor: Color;+ endColor: Color;+ texture: number;+ blendMode: number;+ layer: number;+ material: number;+ enabled: boolean;+}++export function fillTrailRenderer(+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,+ ptr: number, out: TrailRendererPtrData,+): void {+ out.time = f32[ptr >> 2];+ out.minVertexDistance = f32[(ptr + 4) >> 2];+ out.emitting = u8[ptr + 8] !== 0;+ out.startWidth = f32[(ptr + 12) >> 2];+ out.endWidth = f32[(ptr + 16) >> 2];+ const startColor_ = out.startColor; startColor_.r = f32[(ptr + 20) >> 2]; startColor_.g = f32[((ptr + 20) >> 2) + 1]; startColor_.b = f32[((ptr + 20) >> 2) + 2]; startColor_.a = f32[((ptr + 20) >> 2) + 3];+ const endColor_ = out.endColor; endColor_.r = f32[(ptr + 36) >> 2]; endColor_.g = f32[((ptr + 36) >> 2) + 1]; endColor_.b = f32[((ptr + 36) >> 2) + 2]; endColor_.a = f32[((ptr + 36) >> 2) + 3];+ out.texture = u32[(ptr + 52) >> 2];+ out.blendMode = u32[(ptr + 56) >> 2] | 0;+ out.layer = u32[(ptr + 60) >> 2] | 0;+ out.material = u32[(ptr + 64) >> 2];+ out.enabled = u8[ptr + 68] !== 0;+}++export function writeTrailRenderer(+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,+ ptr: number, data: TrailRendererPtrData,+): void {+ f32[ptr >> 2] = data.time;+ f32[(ptr + 4) >> 2] = data.minVertexDistance;+ u8[ptr + 8] = data.emitting ? 1 : 0;+ f32[(ptr + 12) >> 2] = data.startWidth;+ f32[(ptr + 16) >> 2] = data.endWidth;+ f32[(ptr + 20) >> 2] = data.startColor.r; f32[((ptr + 20) >> 2) + 1] = data.startColor.g; f32[((ptr + 20) >> 2) + 2] = data.startColor.b; f32[((ptr + 20) >> 2) + 3] = data.startColor.a;+ f32[(ptr + 36) >> 2] = data.endColor.r; f32[((ptr + 36) >> 2) + 1] = data.endColor.g; f32[((ptr + 36) >> 2) + 2] = data.endColor.b; f32[((ptr + 36) >> 2) + 3] = data.endColor.a;+ u32[(ptr + 52) >> 2] = data.texture;+ u32[(ptr + 56) >> 2] = data.blendMode | 0;+ u32[(ptr + 60) >> 2] = data.layer | 0;+ u32[(ptr + 64) >> 2] = data.material;+ u8[ptr + 68] = data.enabled ? 1 : 0;+}++export function createTrailRendererData(): TrailRendererPtrData {+ return {+ time: 0,+ minVertexDistance: 0,+ emitting: false,+ startWidth: 0,+ endWidth: 0,+ startColor: { r: 0, g: 0, b: 0, a: 0 },+ endColor: { r: 0, g: 0, b: 0, a: 0 },+ texture: 0,+ blendMode: 0,+ layer: 0,+ material: 0,+ enabled: false,+ };+}+export interface TransformPtrData {position: Vec3;rotation: Vec4;@@ -1350,6 +1418,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {SpineAnimation: { fill: fillSpineAnimation, write: writeSpineAnimation, create: createSpineAnimationData },Sprite: { fill: fillSprite, write: writeSprite, create: createSpriteData },TilemapLayer: { fill: fillTilemapLayer, write: writeTilemapLayer, create: createTilemapLayerData },+ TrailRenderer: { fill: fillTrailRenderer, write: writeTrailRenderer, create: createTrailRendererData },Transform: { fill: fillTransform, write: writeTransform, create: createTransformData },UIInteraction: { fill: fillUIInteraction, write: writeUIInteraction, create: createUIInteractionData },UIMask: { fill: fillUIMask, write: writeUIMask, create: createUIMaskData },diff --git a/sdk/src/ptrLayouts.generated.ts b/sdk/src/ptrLayouts.generated.tsindex 7e4d88dbb..a5e2673aa 100644--- a/sdk/src/ptrLayouts.generated.ts+++ b/sdk/src/ptrLayouts.generated.ts@@ -287,6 +287,23 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {{ name: 'visible', type: 'bool', offset: 60 },],},+ TrailRenderer: {+ ptrFn: 'getTrailRendererPtr',+ fields: [+ { name: 'time', type: 'f32', offset: 0 },+ { name: 'minVertexDistance', type: 'f32', offset: 4 },+ { name: 'emitting', type: 'bool', offset: 8 },+ { name: 'startWidth', type: 'f32', offset: 12 },+ { name: 'endWidth', type: 'f32', offset: 16 },+ { name: 'startColor', type: 'color', offset: 20 },+ { name: 'endColor', type: 'color', offset: 36 },+ { name: 'texture', type: 'u32', offset: 52 },+ { name: 'blendMode', type: 'i32', offset: 56 },+ { name: 'layer', type: 'i32', offset: 60 },+ { name: 'material', type: 'u32', offset: 64 },+ { name: 'enabled', type: 'bool', offset: 68 },+ ],+ },Transform: {ptrFn: 'getTransformPtr',fields: [diff --git a/sdk/src/trail/TrailAPI.ts b/sdk/src/trail/TrailAPI.tsnew file mode 100644index 000000000..b659741fe--- /dev/null+++ b/sdk/src/trail/TrailAPI.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { ESEngineModule, CppRegistry } from '../wasm';+import type { Entity } from '../types';+import { defineResource } from '../resource';++/**+ * Per-app motion-trail API. Wraps the C++ registry-scoped trail system so two App+ * instances (e.g. editor tabs) drive independent trails without cross-talk.+ *+ * Consumed as a resource: declare `Res(Trail)` as a system param, or grab it with+ * `app.getResource(Trail)` outside ECS code.+ */+export class TrailAPI {+ private readonly module_: ESEngineModule;+ private readonly registry_: CppRegistry;++ constructor(module: ESEngineModule, registry: CppRegistry) {+ this.module_ = module;+ this.registry_ = registry;+ }++ /** Advance every trail: record points for moving emitters, age out old ones. */+ update(dt: number): void {+ this.module_.trail_update?.(this.registry_, dt);+ }++ /** Drop an entity's recorded history (the streak vanishes instantly). */+ clear(entity: Entity): void {+ this.module_.trail_clear?.(this.registry_, entity as number);+ }+}++/** Resource handle for the per-app trail API. */+export const Trail = defineResource<TrailAPI>(null!, 'Trail');diff --git a/sdk/src/trail/TrailPlugin.ts b/sdk/src/trail/TrailPlugin.tsnew file mode 100644index 000000000..0f581af45--- /dev/null+++ b/sdk/src/trail/TrailPlugin.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { App, Plugin } from '../app';+import { defineSystem, Schedule } from '../system';+import { Res } from '../resource';+import { Time, type TimeData } from '../resource';+import { playModeOnly } from '../env';+import type { ESEngineModule, CppRegistry } from '../wasm';+import { Trail, TrailAPI } from './TrailAPI';++export class TrailPlugin implements Plugin {+ name = 'trail';++ build(app: App): void {+ const module = app.wasmModule as ESEngineModule;+ const registry = app.world.getCppRegistry() as CppRegistry;+ const api = new TrailAPI(module, registry);+ app.insertResource(Trail, api);++ // Trail point recording is gameplay — frozen in editor edit mode, runs in+ // play mode / standalone runtime (matches particles/animation/physics).+ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Res(Time), Res(Trail)],+ (time: TimeData, trail: TrailAPI) => {+ trail.update(time.delta);+ },+ { name: 'TrailSystem' }+ ), { runIf: playModeOnly });+ }+}++export const trailPlugin = new TrailPlugin();diff --git a/sdk/src/trail/index.ts b/sdk/src/trail/index.tsnew file mode 100644index 000000000..3f865aadd--- /dev/null+++ b/sdk/src/trail/index.ts@@ -0,0 +1,4 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+export { TrailAPI, Trail } from './TrailAPI';+export { TrailPlugin, trailPlugin } from './TrailPlugin';diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.tsindex 0730cb2a8..d60dc38f8 100644--- a/sdk/src/wasm.generated.ts+++ b/sdk/src/wasm.generated.ts@@ -428,6 +428,21 @@ export interface TilemapLayer {visible: boolean;}+export interface TrailRenderer {+ time: number;+ minVertexDistance: number;+ emitting: boolean;+ startWidth: number;+ endWidth: number;+ startColor: Vec4;+ endColor: Vec4;+ texture: number;+ blendMode: number;+ layer: number;+ material: number;+ enabled: boolean;+}+export interface Transform {position: Vec3;rotation: Quat;@@ -586,6 +601,10 @@ export interface Registry {getTilemapLayer(entity: Entity): TilemapLayer;addTilemapLayer(entity: Entity, component: TilemapLayer): void;removeTilemapLayer(entity: Entity): void;+ hasTrailRenderer(entity: Entity): boolean;+ getTrailRenderer(entity: Entity): TrailRenderer;+ addTrailRenderer(entity: Entity, component: TrailRenderer): void;+ removeTrailRenderer(entity: Entity): void;hasTransform(entity: Entity): boolean;getTransform(entity: Entity): Transform;addTransform(entity: Entity, component: Transform): void;@@ -646,6 +665,7 @@ export interface ESEngineModule {StateMachine: new () => StateMachine;StateVisuals: new () => StateVisuals;TilemapLayer: new () => TilemapLayer;+ TrailRenderer: new () => TrailRenderer;Transform: new () => Transform;UIInteraction: new () => UIInteraction;UIMask: new () => UIMask;diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 0fe60b14d..f8bbf6fa5 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -306,6 +306,8 @@ export interface ESEngineModule {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;+ trail_update?(registry: CppRegistry, dt: number): void;+ trail_clear?(registry: CppRegistry, entity: number): void;// Tilemap APItilemap_initLayer?(entity: number, width: number, height: number,diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.tsindex 07e62dffb..b89780f36 100644--- a/sdk/src/webAppFactory.ts+++ b/sdk/src/webAppFactory.ts@@ -10,6 +10,7 @@ import { uiPlugins } from './uiPlugins';import { animationPlugin } from './animation';import { audioPlugin } from './audio';import { particlePlugin } from './particle';+import { trailPlugin } from './trail';import { mesh2dPlugin } from './mesh2d';import { tilemapPlugin } from './tilemap';import { postProcessPlugin } from './postprocess';@@ -40,6 +41,7 @@ export { PhysicsPlugin, PhysicsEvents, Physics, loadPhysicsModule } from './physexport { AnimationPlugin, animationPlugin } from './animation';export { AudioPlugin, audioPlugin } from './audio';export { ParticlePlugin, particlePlugin } from './particle';+export { TrailPlugin, trailPlugin } from './trail';export { Mesh2DPlugin, mesh2dPlugin } from './mesh2d';export { PostProcessPlugin, postProcessPlugin } from './postprocess';export { TimelinePlugin, timelinePlugin, registerTimelineAsset, parseTimelineAsset, Timeline, TimelineApi, TimelinePlayer, type TimelinePlayerData } from './timeline';@@ -64,7 +66,7 @@ export interface CreateWebAppOptions extends WebAppOptions {wasmBaseUrl?: string;}-const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, perceptionPlugin, fsmPlugin, btPlugin, navPlugin, replicationPlugin];+const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, perceptionPlugin, fsmPlugin, btPlugin, navPlugin, replicationPlugin];export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {const sideModules: SideModuleHost | undefined = options?.sideModulesdiff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snapindex d75eb8500..edc46c256 100644--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap@@ -548,6 +548,57 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"step": 1,},},+ "TrailRenderer": {+ "blendMode": {+ "category": "Rendering",+ "tooltip": "Blend mode: 0 Normal, 1 Additive (glow), 2 Multiply, …",+ },+ "emitting": {+ "category": "Trail",+ "tooltip": "Record new points. False = freeze and let the streak fade in place.",+ },+ "endColor": {+ "category": "Color",+ "tooltip": "Color at the tail (oldest point) — usually alpha 0 to fade out.",+ },+ "endWidth": {+ "category": "Width",+ "min": 0,+ "tooltip": "Full ribbon width at the tail (oldest point).",+ },+ "layer": {+ "category": "Rendering",+ "enumSource": "sortingLayers",+ "step": 1,+ "tooltip": "Sorting layer — controls draw order across renderables.",+ },+ "material": {+ "advanced": true,+ "category": "Rendering",+ },+ "minVertexDistance": {+ "category": "Trail",+ "min": 0,+ "tooltip": "Min world distance moved before a new trail point is recorded.",+ },+ "startColor": {+ "category": "Color",+ "tooltip": "Color at the head (newest point).",+ },+ "startWidth": {+ "category": "Width",+ "min": 0,+ "tooltip": "Full ribbon width at the head (newest point).",+ },+ "texture": {+ "category": "Rendering",+ },+ "time": {+ "category": "Trail",+ "min": 0,+ "tooltip": "Seconds each trail point lives before it fades out of the tail.",+ },+ },"Transform": {"position": {"tooltip": "Local position in world units, relative to the parent.",diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cppindex 3523530fe..f9114edbf 100644--- a/src/esengine/bindings/EditorAPI.generated.cpp+++ b/src/esengine/bindings/EditorAPI.generated.cpp@@ -2,10 +2,10 @@* @file EditorAPI.generated.cpp* @brief Auto-generated editor API with string-dispatched component access* @details Generated by EHT - DO NOT EDIT- * @schema_hash 9336a63ec9fd21a6+ * @schema_hash e7e95b1cb4e7766a*/-#define ES_EDITOR_API_SCHEMA_HASH "9336a63ec9fd21a6"+#define ES_EDITOR_API_SCHEMA_HASH "e7e95b1cb4e7766a"#include <emscripten/bind.h>#include <string>@@ -29,6 +29,7 @@#include "../ecs/components/StateMachine.hpp"#include "../ecs/components/StateVisuals.hpp"#include "../ecs/components/TilemapLayer.hpp"+#include "../ecs/components/TrailRenderer.hpp"#include "../ecs/components/Transform.hpp"#include "../ecs/components/UIInteraction.hpp"#include "../ecs/components/UIMask.hpp"@@ -76,6 +77,7 @@ std::vector<std::string> editor_getComponentNames() {"StateMachine","StateVisuals","TilemapLayer",+ "TrailRenderer","Transform","UIInteraction","UIMask",@@ -408,6 +410,27 @@ std::string editor_getComponentSchema(const std::string& name) {{"key":"parallaxFactor.y","type":"float","group":"TilemapLayer"},{"key":"visible","type":"bool","group":"TilemapLayer"}])JSON";+ } else if (name == "TrailRenderer") {+ return R"JSON([+ {"key":"time","type":"float","group":"TrailRenderer"},+ {"key":"minVertexDistance","type":"float","group":"TrailRenderer"},+ {"key":"emitting","type":"bool","group":"TrailRenderer"},+ {"key":"startWidth","type":"float","group":"TrailRenderer"},+ {"key":"endWidth","type":"float","group":"TrailRenderer"},+ {"key":"startColor.r","type":"color","group":"TrailRenderer"},+ {"key":"startColor.g","type":"color","group":"TrailRenderer"},+ {"key":"startColor.b","type":"color","group":"TrailRenderer"},+ {"key":"startColor.a","type":"color","group":"TrailRenderer"},+ {"key":"endColor.r","type":"color","group":"TrailRenderer"},+ {"key":"endColor.g","type":"color","group":"TrailRenderer"},+ {"key":"endColor.b","type":"color","group":"TrailRenderer"},+ {"key":"endColor.a","type":"color","group":"TrailRenderer"},+ {"key":"texture","type":"asset","group":"TrailRenderer"},+ {"key":"blendMode","type":"int","group":"TrailRenderer"},+ {"key":"layer","type":"int","group":"TrailRenderer"},+ {"key":"material","type":"asset","group":"TrailRenderer"},+ {"key":"enabled","type":"bool","group":"TrailRenderer"}+ ])JSON";} else if (name == "Transform") {return R"JSON([{"key":"position.x","type":"float","group":"Transform"},@@ -577,6 +600,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {} else if (name == "TilemapLayer") {if (!reg.has<esengine::ecs::TilemapLayer>(entity)) reg.emplace<esengine::ecs::TilemapLayer>(entity);return true;+ } else if (name == "TrailRenderer") {+ if (!reg.has<esengine::ecs::TrailRenderer>(entity)) reg.emplace<esengine::ecs::TrailRenderer>(entity);+ return true;} else if (name == "Transform") {if (!reg.has<esengine::ecs::Transform>(entity)) reg.emplace<esengine::ecs::Transform>(entity);return true;@@ -646,6 +672,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {if (reg.has<esengine::ecs::StateVisuals>(entity)) { reg.remove<esengine::ecs::StateVisuals>(entity); return true; }} else if (name == "TilemapLayer") {if (reg.has<esengine::ecs::TilemapLayer>(entity)) { reg.remove<esengine::ecs::TilemapLayer>(entity); return true; }+ } else if (name == "TrailRenderer") {+ if (reg.has<esengine::ecs::TrailRenderer>(entity)) { reg.remove<esengine::ecs::TrailRenderer>(entity); return true; }} else if (name == "Transform") {if (reg.has<esengine::ecs::Transform>(entity)) { reg.remove<esengine::ecs::Transform>(entity); return true; }} else if (name == "UIInteraction") {@@ -687,6 +715,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {if (name == "StateMachine") return reg.has<esengine::ecs::StateMachine>(entity);if (name == "StateVisuals") return reg.has<esengine::ecs::StateVisuals>(entity);if (name == "TilemapLayer") return reg.has<esengine::ecs::TilemapLayer>(entity);+ if (name == "TrailRenderer") return reg.has<esengine::ecs::TrailRenderer>(entity);if (name == "Transform") return reg.has<esengine::ecs::Transform>(entity);if (name == "UIInteraction") return reg.has<esengine::ecs::UIInteraction>(entity);if (name == "UIMask") return reg.has<esengine::ecs::UIMask>(entity);@@ -724,6 +753,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {if (reg.has<esengine::ecs::StateMachine>(entity)) result.push_back("StateMachine");if (reg.has<esengine::ecs::StateVisuals>(entity)) result.push_back("StateVisuals");if (reg.has<esengine::ecs::TilemapLayer>(entity)) result.push_back("TilemapLayer");+ if (reg.has<esengine::ecs::TrailRenderer>(entity)) result.push_back("TrailRenderer");if (reg.has<esengine::ecs::Transform>(entity)) result.push_back("Transform");if (reg.has<esengine::ecs::UIInteraction>(entity)) result.push_back("UIInteraction");if (reg.has<esengine::ecs::UIMask>(entity)) result.push_back("UIMask");@@ -985,6 +1015,23 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::selse if (field == "parallaxFactor.y") { c.parallaxFactor.y = value; }else { return false; }return true;+ } else if (comp == "TrailRenderer") {+ if (!reg.has<esengine::ecs::TrailRenderer>(entity)) return false;+ auto& c = reg.get<esengine::ecs::TrailRenderer>(entity);+ if (field == "time") { c.time = value; }+ else if (field == "minVertexDistance") { c.minVertexDistance = value; }+ else if (field == "startWidth") { c.startWidth = value; }+ else if (field == "endWidth") { c.endWidth = value; }+ else if (field == "startColor.r") { c.startColor.r = value; }+ else if (field == "startColor.g") { c.startColor.g = value; }+ else if (field == "startColor.b") { c.startColor.b = value; }+ else if (field == "startColor.a") { c.startColor.a = value; }+ else if (field == "endColor.r") { c.endColor.r = value; }+ else if (field == "endColor.g") { c.endColor.g = value; }+ else if (field == "endColor.b") { c.endColor.b = value; }+ else if (field == "endColor.a") { c.endColor.a = value; }+ else { return false; }+ return true;} else if (comp == "Transform") {if (!reg.has<esengine::ecs::Transform>(entity)) return false;auto& c = reg.get<esengine::ecs::Transform>(entity);@@ -1299,6 +1346,21 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::stelse if (field == "opacity") { return c.opacity; }else if (field == "parallaxFactor.x") { return c.parallaxFactor.x; }else if (field == "parallaxFactor.y") { return c.parallaxFactor.y; }+ } else if (comp == "TrailRenderer") {+ if (!reg.has<esengine::ecs::TrailRenderer>(entity)) return 0.0f;+ const auto& c = reg.get<esengine::ecs::TrailRenderer>(entity);+ if (field == "time") { return c.time; }+ else if (field == "minVertexDistance") { return c.minVertexDistance; }+ else if (field == "startWidth") { return c.startWidth; }+ else if (field == "endWidth") { return c.endWidth; }+ else if (field == "startColor.r") { return c.startColor.r; }+ else if (field == "startColor.g") { return c.startColor.g; }+ else if (field == "startColor.b") { return c.startColor.b; }+ else if (field == "startColor.a") { return c.startColor.a; }+ else if (field == "endColor.r") { return c.endColor.r; }+ else if (field == "endColor.g") { return c.endColor.g; }+ else if (field == "endColor.b") { return c.endColor.b; }+ else if (field == "endColor.a") { return c.endColor.a; }} else if (comp == "Transform") {if (!reg.has<esengine::ecs::Transform>(entity)) return 0.0f;const auto& c = reg.get<esengine::ecs::Transform>(entity);@@ -1523,6 +1585,15 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::strelse if (field == "renderLayer") { c.renderLayer = static_cast<i32>(value); }else { return false; }return true;+ } else if (comp == "TrailRenderer") {+ if (!reg.has<esengine::ecs::TrailRenderer>(entity)) return false;+ auto& c = reg.get<esengine::ecs::TrailRenderer>(entity);+ if (field == "texture") { c.texture = resource::TextureHandle(static_cast<u32>(value)); }+ else if (field == "blendMode") { c.blendMode = static_cast<i32>(value); }+ else if (field == "layer") { c.layer = static_cast<i32>(value); }+ else if (field == "material") { c.material = static_cast<u32>(value); }+ else { return false; }+ return true;} else if (comp == "UIMask") {if (!reg.has<esengine::ecs::UIMask>(entity)) return false;auto& c = reg.get<esengine::ecs::UIMask>(entity);@@ -1660,6 +1731,13 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::strielse if (field == "tilesetColumns") { return static_cast<i32>(c.tilesetColumns); }else if (field == "tilesetRows") { return static_cast<i32>(c.tilesetRows); }else if (field == "renderLayer") { return static_cast<i32>(c.renderLayer); }+ } else if (comp == "TrailRenderer") {+ if (!reg.has<esengine::ecs::TrailRenderer>(entity)) return 0;+ const auto& c = reg.get<esengine::ecs::TrailRenderer>(entity);+ if (field == "texture") { return static_cast<i32>(c.texture.id()); }+ else if (field == "blendMode") { return static_cast<i32>(c.blendMode); }+ else if (field == "layer") { return static_cast<i32>(c.layer); }+ else if (field == "material") { return static_cast<i32>(c.material); }} else if (comp == "UIMask") {if (!reg.has<esengine::ecs::UIMask>(entity)) return 0;const auto& c = reg.get<esengine::ecs::UIMask>(entity);@@ -1802,6 +1880,13 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::stif (field == "visible") { c.visible = value; }else { return false; }return true;+ } else if (comp == "TrailRenderer") {+ if (!reg.has<esengine::ecs::TrailRenderer>(entity)) return false;+ auto& c = reg.get<esengine::ecs::TrailRenderer>(entity);+ if (field == "emitting") { c.emitting = value; }+ else if (field == "enabled") { c.enabled = value; }+ else { return false; }+ return true;} else if (comp == "UIInteraction") {if (!reg.has<esengine::ecs::UIInteraction>(entity)) return false;auto& c = reg.get<esengine::ecs::UIInteraction>(entity);@@ -1916,6 +2001,11 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::stif (!reg.has<esengine::ecs::TilemapLayer>(entity)) return false;const auto& c = reg.get<esengine::ecs::TilemapLayer>(entity);if (field == "visible") { return c.visible; }+ } else if (comp == "TrailRenderer") {+ if (!reg.has<esengine::ecs::TrailRenderer>(entity)) return false;+ const auto& c = reg.get<esengine::ecs::TrailRenderer>(entity);+ if (field == "emitting") { return c.emitting; }+ else if (field == "enabled") { return c.enabled; }} else if (comp == "UIInteraction") {if (!reg.has<esengine::ecs::UIInteraction>(entity)) return false;const auto& c = reg.get<esengine::ecs::UIInteraction>(entity);diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex e9fa63d11..91db460a9 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -26,6 +26,7 @@#ifdef ES_ENABLE_PARTICLES#include "../particle/ParticleSystem.hpp"#endif+#include "../trail/TrailSystem.hpp"#include <emscripten/val.h>#include <glm/glm.hpp>@@ -46,6 +47,7 @@ static EstellaContext& ctx() { return activeCtx(); }#ifdef ES_ENABLE_PARTICLES#define g_particleSystem (ctx().tryGet<particle::ParticleSystem>())#endif+#define g_trailSystem (ctx().tryGet<trail::TrailSystem>())static u32 checkGLErrors(const char* context) {if (!g_glErrorCheckEnabled) return 0;@@ -429,6 +431,19 @@ void particle_set_size_lut(u32 entity, uintptr_t ptr, i32 count) {}#endif+void trail_update(ecs::Registry& registry, f32 dt) {+ if (!g_trailSystem) return;+ g_trailSystem->update(registry, dt);+}++// The entity crosses the wasm boundary as a raw u32 (Embind has no Entity binding);+// rebuild it C++-side, matching particle_play/stop above.+void trail_clear(ecs::Registry& registry, u32 entity) {+ if (!g_trailSystem) return;+ (void)registry;+ g_trailSystem->clear(Entity::fromRaw(entity));+}+void renderer_setStage(i32 stage) {if (!g_renderFrame) return;g_renderFrame->setStage(static_cast<RenderStage>(stage));diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 895b4267d..4c3d7dc2a 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -78,6 +78,8 @@ u32 particle_getAliveCount(u32 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);#endif+void trail_update(ecs::Registry& registry, f32 dt);+void trail_clear(ecs::Registry& registry, u32 entity);void renderer_setStage(i32 stage);u32 renderer_createTarget(u32 width, u32 height, i32 flags);u32 renderer_getTargetDepthTexture(u32 handle);diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex 8e5621598..00fd627ea 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -29,6 +29,7 @@#include "../ecs/components/StateMachine.hpp"#include "../ecs/components/StateVisuals.hpp"#include "../ecs/components/TilemapLayer.hpp"+#include "../ecs/components/TrailRenderer.hpp"#include "../ecs/components/Transform.hpp"#include "../ecs/components/UIInteraction.hpp"#include "../ecs/components/UIMask.hpp"@@ -738,6 +739,55 @@ TilemapLayerJS tilemaplayerToJS(const esengine::ecs::TilemapLayer& c) {return js;}+struct TrailRendererJS {+ f32 time;+ f32 minVertexDistance;+ bool emitting;+ f32 startWidth;+ f32 endWidth;+ glm::vec4 startColor;+ glm::vec4 endColor;+ u32 texture;+ i32 blendMode;+ i32 layer;+ u32 material;+ bool enabled;+};++esengine::ecs::TrailRenderer trailrendererFromJS(const TrailRendererJS& js) {+ esengine::ecs::TrailRenderer c;+ c.time = js.time;+ c.minVertexDistance = js.minVertexDistance;+ c.emitting = js.emitting;+ c.startWidth = js.startWidth;+ c.endWidth = js.endWidth;+ c.startColor = js.startColor;+ c.endColor = js.endColor;+ c.texture = resource::TextureHandle(js.texture);+ c.blendMode = js.blendMode;+ c.layer = js.layer;+ c.material = js.material;+ c.enabled = js.enabled;+ return c;+}++TrailRendererJS trailrendererToJS(const esengine::ecs::TrailRenderer& c) {+ TrailRendererJS js;+ js.time = c.time;+ js.minVertexDistance = c.minVertexDistance;+ js.emitting = c.emitting;+ js.startWidth = c.startWidth;+ js.endWidth = c.endWidth;+ js.startColor = c.startColor;+ js.endColor = c.endColor;+ js.texture = c.texture.id();+ js.blendMode = c.blendMode;+ js.layer = c.layer;+ js.material = c.material;+ js.enabled = c.enabled;+ return js;+}+struct UIMaskJS {bool enabled;i32 mode;@@ -1116,6 +1166,20 @@ EMSCRIPTEN_BINDINGS(esengine_components) {.field("parallaxFactor", &TilemapLayerJS::parallaxFactor).field("visible", &TilemapLayerJS::visible);+ value_object<TrailRendererJS>("TrailRenderer")+ .field("time", &TrailRendererJS::time)+ .field("minVertexDistance", &TrailRendererJS::minVertexDistance)+ .field("emitting", &TrailRendererJS::emitting)+ .field("startWidth", &TrailRendererJS::startWidth)+ .field("endWidth", &TrailRendererJS::endWidth)+ .field("startColor", &TrailRendererJS::startColor)+ .field("endColor", &TrailRendererJS::endColor)+ .field("texture", &TrailRendererJS::texture)+ .field("blendMode", &TrailRendererJS::blendMode)+ .field("layer", &TrailRendererJS::layer)+ .field("material", &TrailRendererJS::material)+ .field("enabled", &TrailRendererJS::enabled);+value_object<esengine::ecs::Transform>("Transform").field("position", &esengine::ecs::Transform::position).field("rotation", &esengine::ecs::Transform::rotation)@@ -1643,6 +1707,26 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {r.remove<esengine::ecs::TilemapLayer>(entity);}))+ // TrailRenderer+ .function("hasTrailRenderer", optional_override([](Registry& r, u32 e) {+ return r.has<esengine::ecs::TrailRenderer>(static_cast<Entity>(e));+ }))+ .function("getTrailRenderer", optional_override([](Registry& r, u32 e) {+ auto entity = static_cast<Entity>(e);+ if (!r.valid(entity) || !r.has<esengine::ecs::TrailRenderer>(entity)) return TrailRendererJS{};+ return trailrendererToJS(r.get<esengine::ecs::TrailRenderer>(entity));+ }))+ .function("addTrailRenderer", optional_override([](Registry& r, u32 e, const TrailRendererJS& js) {+ auto entity = static_cast<Entity>(e);+ if (!r.valid(entity)) return;+ r.emplaceOrReplace<esengine::ecs::TrailRenderer>(entity, trailrendererFromJS(js));+ }))+ .function("removeTrailRenderer", optional_override([](Registry& r, u32 e) {+ auto entity = static_cast<Entity>(e);+ if (!r.valid(entity) || !r.has<esengine::ecs::TrailRenderer>(entity)) return;+ r.remove<esengine::ecs::TrailRenderer>(entity);+ }))+// Transform.function("hasTransform", optional_override([](Registry& r, u32 e) {return r.has<esengine::ecs::Transform>(static_cast<Entity>(e));@@ -1806,6 +1890,7 @@ emscripten::val esengineGetBuiltinComponentNames() {arr.set(i++, val(std::string("StateMachine")));arr.set(i++, val(std::string("StateVisuals")));arr.set(i++, val(std::string("TilemapLayer")));+ arr.set(i++, val(std::string("TrailRenderer")));arr.set(i++, val(std::string("Transform")));arr.set(i++, val(std::string("UIInteraction")));arr.set(i++, val(std::string("UIMask")));@@ -2005,6 +2090,18 @@ static_assert(offsetof(esengine::ecs::TilemapLayer, tintColor) == 32, "ABI offsestatic_assert(offsetof(esengine::ecs::TilemapLayer, opacity) == 48, "ABI offset drift: esengine::ecs::TilemapLayer.opacity (EHT expected 48)");static_assert(offsetof(esengine::ecs::TilemapLayer, parallaxFactor) == 52, "ABI offset drift: esengine::ecs::TilemapLayer.parallaxFactor (EHT expected 52)");static_assert(offsetof(esengine::ecs::TilemapLayer, visible) == 60, "ABI offset drift: esengine::ecs::TilemapLayer.visible (EHT expected 60)");+static_assert(offsetof(esengine::ecs::TrailRenderer, time) == 0, "ABI offset drift: esengine::ecs::TrailRenderer.time (EHT expected 0)");+static_assert(offsetof(esengine::ecs::TrailRenderer, minVertexDistance) == 4, "ABI offset drift: esengine::ecs::TrailRenderer.minVertexDistance (EHT expected 4)");+static_assert(offsetof(esengine::ecs::TrailRenderer, emitting) == 8, "ABI offset drift: esengine::ecs::TrailRenderer.emitting (EHT expected 8)");+static_assert(offsetof(esengine::ecs::TrailRenderer, startWidth) == 12, "ABI offset drift: esengine::ecs::TrailRenderer.startWidth (EHT expected 12)");+static_assert(offsetof(esengine::ecs::TrailRenderer, endWidth) == 16, "ABI offset drift: esengine::ecs::TrailRenderer.endWidth (EHT expected 16)");+static_assert(offsetof(esengine::ecs::TrailRenderer, startColor) == 20, "ABI offset drift: esengine::ecs::TrailRenderer.startColor (EHT expected 20)");+static_assert(offsetof(esengine::ecs::TrailRenderer, endColor) == 36, "ABI offset drift: esengine::ecs::TrailRenderer.endColor (EHT expected 36)");+static_assert(offsetof(esengine::ecs::TrailRenderer, texture) == 52, "ABI offset drift: esengine::ecs::TrailRenderer.texture (EHT expected 52)");+static_assert(offsetof(esengine::ecs::TrailRenderer, blendMode) == 56, "ABI offset drift: esengine::ecs::TrailRenderer.blendMode (EHT expected 56)");+static_assert(offsetof(esengine::ecs::TrailRenderer, layer) == 60, "ABI offset drift: esengine::ecs::TrailRenderer.layer (EHT expected 60)");+static_assert(offsetof(esengine::ecs::TrailRenderer, material) == 64, "ABI offset drift: esengine::ecs::TrailRenderer.material (EHT expected 64)");+static_assert(offsetof(esengine::ecs::TrailRenderer, enabled) == 68, "ABI offset drift: esengine::ecs::TrailRenderer.enabled (EHT expected 68)");static_assert(offsetof(esengine::ecs::Transform, position) == 0, "ABI offset drift: esengine::ecs::Transform.position (EHT expected 0)");static_assert(offsetof(esengine::ecs::Transform, rotation) == 12, "ABI offset drift: esengine::ecs::Transform.rotation (EHT expected 12)");static_assert(offsetof(esengine::ecs::Transform, scale) == 28, "ABI offset drift: esengine::ecs::Transform.scale (EHT expected 28)");@@ -2041,7 +2138,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif// ABI Hash -- runtime handshake against the SDK bundle// =============================================================================-static const char* kEsAbiLayoutHash = "89e3ae10e24e8bc9";+static const char* kEsAbiLayoutHash = "89ad72a9b853289f";std::string esengineGetAbiLayoutHash() {return std::string(kEsAbiLayoutHash);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex c029b65cc..714ef0831 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -628,6 +628,8 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("particle_set_color_lut", &esengine::particle_set_color_lut);emscripten::function("particle_set_size_lut", &esengine::particle_set_size_lut);#endif+ emscripten::function("trail_update", &esengine::trail_update);+ emscripten::function("trail_clear", &esengine::trail_clear);emscripten::function("renderer_setStage", &esengine::renderer_setStage);emscripten::function("renderer_createTarget", &esengine::renderer_createTarget);emscripten::function("renderer_releaseTarget", &esengine::renderer_releaseTarget);diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cppindex ae4aa11b9..50451603b 100644--- a/src/esengine/core/EstellaContext.cpp+++ b/src/esengine/core/EstellaContext.cpp@@ -25,6 +25,8 @@#include "../renderer/plugins/ParticlePlugin.hpp"#include "../particle/ParticleSystem.hpp"#endif+#include "../renderer/plugins/TrailPlugin.hpp"+#include "../trail/TrailSystem.hpp"#ifdef ES_ENABLE_TILEMAP#include "../renderer/plugins/TilemapRenderPlugin.hpp"#include "../tilemap/TilemapSystem.hpp"@@ -131,6 +133,7 @@ void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {#ifdef ES_ENABLE_PARTICLESservices_.registerOwned<particle::ParticleSystem>(makeUnique<particle::ParticleSystem>());#endif+ services_.registerOwned<trail::TrailSystem>(makeUnique<trail::TrailSystem>());auto* rm = services_.getService<resource::ResourceManager>();auto* rc = services_.getService<RenderContext>();@@ -150,6 +153,11 @@ void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {renderFrame->addPlugin(std::make_unique<TextPlugin>());renderFrame->addPlugin(std::make_unique<ShapePlugin>());renderFrame->addPlugin(std::make_unique<MeshPlugin>());+ {+ auto trailPlugin = std::make_unique<TrailPlugin>();+ trailPlugin->setTrailSystem(services_.getService<trail::TrailSystem>());+ renderFrame->addPlugin(std::move(trailPlugin));+ }#ifdef ES_ENABLE_TILEMAP{diff --git a/src/esengine/ecs/components/TrailRenderer.hpp b/src/esengine/ecs/components/TrailRenderer.hppnew file mode 100644index 000000000..a8198369c--- /dev/null+++ b/src/esengine/ecs/components/TrailRenderer.hpp@@ -0,0 +1,98 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file TrailRenderer.hpp+ * @brief World-space motion trail renderable (sword swipes, projectile/dash+ * streaks, ribbon effects).+ * @details The trail records the entity's world position over time into a point+ * history owned by TrailSystem (per-frame gameplay sim, like the particle+ * system) — this component is PURE CONFIG. TrailPlugin turns that history+ * into a triangle-strip ribbon each frame and streams it through the unified+ * Batch face (CPU-generated verts, exactly like Mesh2D), so a trail sorts,+ * clips, and multi-texture-merges like every other 2D renderable. No new GPU+ * path, no line-strip topology — a ribbon is triangles.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "../../core/Types.hpp"+#include "../../core/Reflection.hpp"+#include "../../math/Math.hpp"+#include "../../resource/Handle.hpp"++namespace esengine::ecs {++// =============================================================================+// TrailRenderer Component+// =============================================================================++ES_COMPONENT()+struct TrailRenderer {+ // Trail — how long the streak lives and how densely it samples the path.+ /** @brief Seconds each recorded point persists before fading out of the tail. */+ ES_PROPERTY(min=0, category=Trail, tooltip="Seconds each trail point lives before it fades out of the tail.")+ f32 time{0.5f};++ /** @brief Minimum world distance the entity must move before a new point is+ * recorded (0 = record every frame; larger = coarser, cheaper trail). */+ ES_PROPERTY(min=0, category=Trail, tooltip="Min world distance moved before a new trail point is recorded.")+ f32 minVertexDistance{5.0f};++ /** @brief Record new points. Set false to freeze emission and let the existing+ * streak fade in place (the ribbon detaches from the entity). */+ ES_PROPERTY(category=Trail, tooltip="Record new points. False = freeze and let the streak fade in place.")+ bool emitting{true};++ // Width — full ribbon width tapered from the head (newest) to the tail (oldest).+ /** @brief Full ribbon width at the head (the newest point, glued to the entity). */+ ES_PROPERTY(min=0, category=Width, tooltip="Full ribbon width at the head (newest point).")+ f32 startWidth{20.0f};++ /** @brief Full ribbon width at the tail (the oldest point). 0 = taper to a line. */+ ES_PROPERTY(min=0, category=Width, tooltip="Full ribbon width at the tail (oldest point).")+ f32 endWidth{0.0f};++ // Color — lerped from head to tail; the alpha is the usual fade-out control.+ /** @brief Color at the head (newest). */+ ES_PROPERTY(animatable, category=Color, tooltip="Color at the head (newest point).")+ glm::vec4 startColor{1.0f, 1.0f, 1.0f, 1.0f};++ /** @brief Color at the tail (oldest) — typically the head color with alpha 0. */+ ES_PROPERTY(animatable, category=Color, tooltip="Color at the tail (oldest point) — usually alpha 0 to fade out.")+ glm::vec4 endColor{1.0f, 1.0f, 1.0f, 0.0f};++ // Rendering.+ /** @brief Texture sampled along the ribbon (U runs head→tail, V across the width).+ * Invalid = untextured (vertex colors only). */+ ES_PROPERTY(asset = texture, category=Rendering)+ resource::TextureHandle texture;++ /** @brief Blend mode (0 = Normal, 1 = Additive for glow, …). */+ ES_PROPERTY(category=Rendering, tooltip="Blend mode: 0 Normal, 1 Additive (glow), 2 Multiply, …")+ i32 blendMode{0};++ /** @brief Sorting layer (higher = rendered on top). */+ ES_PROPERTY(step=1, enum_source=sortingLayers, category=Rendering, tooltip="Sorting layer — controls draw order across renderables.")+ i32 layer{0};++ /** @brief Custom material ID (0 = default batch shader). */+ ES_PROPERTY(asset = material, advanced, category=Rendering)+ u32 material{0};++ // State.+ ES_PROPERTY()+ bool enabled{true};++ TrailRenderer() = default;+};++} // namespace esengine::ecsdiff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cppindex a2e3de106..79d3cf640 100644--- a/src/esengine/renderer/RenderFrame.cpp+++ b/src/esengine/renderer/RenderFrame.cpp@@ -294,6 +294,7 @@ void RenderFrame::flush() {case RenderType::Text: stats_.text += cmd.entity_count; break;case RenderType::Mesh:case RenderType::ExternalMesh:+ case RenderType::Trail:stats_.meshes += cmd.entity_count; break;#ifdef ES_ENABLE_PARTICLEScase RenderType::Particle: stats_.particles += cmd.entity_count; break;diff --git a/src/esengine/renderer/RenderItem.hpp b/src/esengine/renderer/RenderItem.hppindex 1f1b83558..c2bd4cfe1 100644--- a/src/esengine/renderer/RenderItem.hpp+++ b/src/esengine/renderer/RenderItem.hpp@@ -27,6 +27,7 @@ enum class RenderType : u8 {#endifShape = 6,UIElement = 7,+ Trail = 8,};} // namespace esenginediff --git a/src/esengine/renderer/plugins/TrailPlugin.cpp b/src/esengine/renderer/plugins/TrailPlugin.cppnew file mode 100644index 000000000..2d18b21de--- /dev/null+++ b/src/esengine/renderer/plugins/TrailPlugin.cpp@@ -0,0 +1,154 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#include "TrailPlugin.hpp"+#include "../BatchBuilder.hpp"+#include "../MaterialStore.hpp"+#include "../RenderFrame.hpp"+#include "../Texture.hpp"+#include "../../ecs/components/Transform.hpp"+#include "../../ecs/components/TrailRenderer.hpp"+#include "../../trail/TrailSystem.hpp"++#include <algorithm>+#include <cmath>+#include <limits>++namespace esengine {++void TrailPlugin::collect(RenderCollectContext& collect_ctx) {+ if (!trail_system_) return;++ auto& registry = collect_ctx.registry;+ auto& frustum = collect_ctx.frustum;+ auto& clips = collect_ctx.clip_state;+ auto& buffers = collect_ctx.buffer_pool;+ auto& draw_list = collect_ctx.draw_list;+ auto& ctx = collect_ctx.frame_context;++ const f32 now = trail_system_->now();++ auto view = registry.view<ecs::Transform, ecs::TrailRenderer>();+ for (auto entity : view) {+ const auto& trail = view.get<ecs::TrailRenderer>(entity);+ if (!trail.enabled) continue;++ const trail::TrailState* state = trail_system_->getState(entity);+ if (!state || state->points.empty()) continue;++ auto& transform = view.get<ecs::Transform>(entity);+ transform.ensureDecomposed();+ const glm::vec3 headWorld = transform.worldPosition;++ // --- Build the centerline: anchors (oldest→newest), then the live head. -----+ const f32 invTime = trail.time > 1e-6f ? 1.0f / trail.time : 0.0f;+ scratch_center_.clear();+ f32 minX = std::numeric_limits<f32>::max(), minY = minX;+ f32 maxX = std::numeric_limits<f32>::lowest(), maxY = maxX;+ auto extend = [&](const glm::vec2& p) {+ minX = std::min(minX, p.x); minY = std::min(minY, p.y);+ maxX = std::max(maxX, p.x); maxY = std::max(maxY, p.y);+ };++ for (const auto& pt : state->points) {+ f32 age01 = std::min(std::max((now - pt.birth_time) * invTime, 0.0f), 1.0f);+ scratch_center_.push_back({pt.position, age01});+ extend(pt.position);+ }+ // The live head glues the ribbon to the moving entity between recorded+ // anchors. Skip it when frozen (the streak fades where it was left) or when it+ // coincides with the newest anchor (avoids a degenerate zero-length segment).+ if (trail.emitting) {+ glm::vec2 head(headWorld.x, headWorld.y);+ glm::vec2 d = head - scratch_center_.back().pos;+ if (glm::dot(d, d) > 1e-4f) {+ scratch_center_.push_back({head, 0.0f});+ extend(head);+ } else {+ scratch_center_.back().age01 = 0.0f;+ }+ }++ const usize n = scratch_center_.size();+ if (n < 2) continue; // need at least one segment to form a ribbon++ // --- Cull against the frustum (centerline AABB padded by half the max width). -+ const f32 maxHalf = 0.5f * std::max(trail.startWidth, trail.endWidth);+ glm::vec3 aabbCenter((minX + maxX) * 0.5f, (minY + maxY) * 0.5f, headWorld.z);+ glm::vec3 halfExtents((maxX - minX) * 0.5f + maxHalf,+ (maxY - minY) * 0.5f + maxHalf, 0.0f);+ if (!frustum.intersectsAABB(aabbCenter, halfExtents)) continue;++ // --- Draw key (mirrors MeshPlugin: material owns shading when present). ------+ u32 textureId = ctx.white_texture_id;+ if (trail.texture.isValid()) {+ if (Texture* tex = ctx.resources.getTexture(trail.texture)) {+ textureId = tex->getId();+ }+ }++ BatchDrawKey key{+ .stage = ctx.current_stage,+ .layer = trail.layer,+ .shaderId = ctx.batch_shader_id,+ .blend = static_cast<BlendMode>(trail.blendMode),+ .textureId = textureId,+ .depth = headWorld.z,+ .y = headWorld.y,+ .entity = entity,+ .type = RenderType::Trail,+ };+ if (trail.material != 0) {+ if (const MaterialRecord* m = ctx.materials ? ctx.materials->find(trail.material) : nullptr) {+ key.shaderId = (m->shader != 0) ? m->shader : ctx.batch_shader_id;+ key.blend = m->blend;+ key.materialId = trail.material;+ key.depthTest = m->depthTest;+ key.depthWrite = m->depthWrite;+ key.cull = static_cast<u8>(m->cull);+ }+ }++ // --- Emit the ribbon: 2 verts per centerline point, 6 indices per segment. ---+ scratch_verts_.clear();+ scratch_verts_.reserve(n * 2);+ glm::vec2 lastTangent(1.0f, 0.0f);+ for (usize i = 0; i < n; ++i) {+ const TrailCenter& c = scratch_center_[i];+ // Central-difference tangent (forward/backward at the ends).+ const glm::vec2& a = scratch_center_[i == 0 ? 0 : i - 1].pos;+ const glm::vec2& b = scratch_center_[i + 1 == n ? i : i + 1].pos;+ glm::vec2 seg = b - a;+ f32 len = std::sqrt(seg.x * seg.x + seg.y * seg.y);+ glm::vec2 tangent = len > 1e-6f ? seg / len : lastTangent;+ lastTangent = tangent;+ glm::vec2 perp(-tangent.y, tangent.x);++ f32 halfW = 0.5f * (trail.startWidth + (trail.endWidth - trail.startWidth) * c.age01);+ u32 color = packColor(glm::mix(trail.startColor, trail.endColor, c.age01));+ f32 u = c.age01; // U runs head(0)→tail(1) along the ribbon++ glm::vec2 left = c.pos + perp * halfW;+ glm::vec2 right = c.pos - perp * halfW;+ scratch_verts_.push_back({left, color, glm::vec2(u, 0.0f)});+ scratch_verts_.push_back({right, color, glm::vec2(u, 1.0f)});+ }++ scratch_indices_.clear();+ scratch_indices_.reserve((n - 1) * 6);+ for (u32 i = 0; i + 1 < n; ++i) {+ u32 l0 = i * 2, r0 = l0 + 1, l1 = l0 + 2, r1 = l0 + 3;+ scratch_indices_.push_back(l0);+ scratch_indices_.push_back(r0);+ scratch_indices_.push_back(r1);+ scratch_indices_.push_back(l0);+ scratch_indices_.push_back(r1);+ scratch_indices_.push_back(l1);+ }++ appendIndexedBatch(buffers, draw_list, clips,+ scratch_verts_.data(), static_cast<u32>(scratch_verts_.size()),+ scratch_indices_.data(), static_cast<u32>(scratch_indices_.size()), key);+ }+}++} // namespace esenginediff --git a/src/esengine/renderer/plugins/TrailPlugin.hpp b/src/esengine/renderer/plugins/TrailPlugin.hppnew file mode 100644index 000000000..d3471bc29--- /dev/null+++ b/src/esengine/renderer/plugins/TrailPlugin.hpp@@ -0,0 +1,41 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#pragma once++#include "../RenderTypePlugin.hpp"+#include "../BatchVertex.hpp"++#include <vector>++namespace esengine {++namespace trail { class TrailSystem; }++/** @brief One centerline sample: world position + normalized age (0 head, 1 tail). */+struct TrailCenter {+ glm::vec2 pos{0.0f, 0.0f};+ f32 age01 = 0.0f;+};++/**+ * @brief Motion-trail renderer (TrailRenderer component).+ * @details Reads the per-entity point history from TrailSystem and turns it into a+ * tapered, fading triangle-strip ribbon streamed through the unified Batch+ * face each frame — CPU-generated verts, exactly like Mesh2D, so trails sort,+ * clip, and multi-texture-merge like sprites. The RHI is triangle-only, so a+ * ribbon (not a GPU line-strip) is the whole trick: no bottom-layer changes.+ */+class TrailPlugin : public RenderTypePlugin {+public:+ void setTrailSystem(trail::TrailSystem* system) { trail_system_ = system; }++ void collect(RenderCollectContext& ctx) override;++private:+ trail::TrailSystem* trail_system_ = nullptr;+ std::vector<TrailCenter> scratch_center_; ///< Reused centerline (anchors + live head).+ std::vector<BatchVertex> scratch_verts_; ///< Reused ribbon vertices (2 per centerline point).+ std::vector<u32> scratch_indices_; ///< Reused ribbon indices (6 per segment).+};++} // namespace esenginediff --git a/src/esengine/trail/TrailSystem.cpp b/src/esengine/trail/TrailSystem.cppnew file mode 100644index 000000000..ee75a767b--- /dev/null+++ b/src/esengine/trail/TrailSystem.cpp@@ -0,0 +1,65 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#include "TrailSystem.hpp"++namespace esengine::trail {++void TrailSystem::update(ecs::Registry& registry, f32 dt) {+ if (!destroyConn_.isConnected()) {+ destroyConn_ = registry.onDestroyScoped([this](Entity entity) {+ states_.erase(entity);+ });+ }++ time_ += dt;++ auto view = registry.view<ecs::Transform, ecs::TrailRenderer>();+ for (auto entity : view) {+ const auto& trail = view.get<ecs::TrailRenderer>(entity);+ // Frozen (disabled) trails keep their history so re-enabling resumes the+ // streak instead of restarting it.+ if (!trail.enabled) continue;++ auto& transform = view.get<ecs::Transform>(entity);+ transform.ensureDecomposed();+ glm::vec2 pos(transform.worldPosition.x, transform.worldPosition.y);++ auto& state = states_[entity];++ // Record a new anchor when the head has moved far enough (or the trail is+ // empty). The live head between anchors is added by the plugin from the+ // current transform, so a stationary emitter never accretes points.+ if (trail.emitting) {+ bool record = state.points.empty();+ if (!record) {+ glm::vec2 d = pos - state.points.back().position;+ f32 md = trail.minVertexDistance;+ record = glm::dot(d, d) >= md * md;+ }+ if (record) {+ state.points.push_back({pos, time_});+ }+ }++ // Age out points older than `time` from the tail (front = oldest).+ f32 cutoff = time_ - trail.time;+ while (!state.points.empty() && state.points.front().birth_time < cutoff) {+ state.points.pop_front();+ }++ if (state.points.empty()) {+ states_.erase(entity);+ }+ }+}++void TrailSystem::clear(Entity entity) {+ states_.erase(entity);+}++const TrailState* TrailSystem::getState(Entity entity) const {+ auto it = states_.find(entity);+ return it != states_.end() ? &it->second : nullptr;+}++} // namespace esengine::traildiff --git a/src/esengine/trail/TrailSystem.hpp b/src/esengine/trail/TrailSystem.hppnew file mode 100644index 000000000..81a60349c--- /dev/null+++ b/src/esengine/trail/TrailSystem.hpp@@ -0,0 +1,59 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file TrailSystem.hpp+ * @brief Per-App motion-trail simulation: records each TrailRenderer entity's world+ * position over time into a point history that TrailPlugin renders as a ribbon.+ * @details Runtime state lives HERE (keyed by entity), not on the component — same+ * split as ParticleSystem, so the component stays pure config and scene+ * serialization never sees the transient history. The render plugin reads+ * this history; it never writes it (RC5).+ */+#pragma once++#include "../core/Types.hpp"+#include "../math/Math.hpp"+#include "../ecs/Registry.hpp"+#include "../ecs/components/Transform.hpp"+#include "../ecs/components/TrailRenderer.hpp"++#include <deque>+#include <unordered_map>++namespace esengine::trail {++/** @brief One recorded trail sample: a world position stamped with the sim clock. */+struct TrailPoint {+ glm::vec2 position{0.0f, 0.0f};+ f32 birth_time = 0.0f; ///< Value of TrailSystem::now() when recorded.+};++/** @brief Per-entity point history. Front = oldest (tail), back = newest (near head). */+struct TrailState {+ std::deque<TrailPoint> points;+};++class TrailSystem {+public:+ TrailSystem() = default;++ /** Advance the sim: record new points for moving emitters, age out old ones. */+ void update(ecs::Registry& registry, f32 dt);++ /** Drop an entity's recorded history (the streak vanishes instantly). */+ void clear(Entity entity);++ /** The monotonic sim clock (seconds), the reference for every point's age. */+ f32 now() const { return time_; }++ const TrailState* getState(Entity entity) const;++private:+ f32 time_ = 0.0f; ///< Accumulated dt; the single time reference for point ages.+ std::unordered_map<Entity, TrailState> states_;+ // RAII: auto-unregisters from the registry's onDestroy when this system is torn+ // down, so a dead system never leaves a dangling `this` behind.+ Connection destroyConn_;+};++} // namespace esengine::trail