Skip to content

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.

refactor: self-describing component architecture with metadata codegen

esenginea2a8baecd4f3
diff --git a/sdk/src/animation/SpriteAnimator.ts b/sdk/src/animation/SpriteAnimator.ts
index fefc8b7fc..19d23aef2 100644
--- a/sdk/src/animation/SpriteAnimator.ts
+++ b/sdk/src/animation/SpriteAnimator.ts
@@ -70,6 +70,8 @@ export const SpriteAnimator: ComponentDef<SpriteAnimatorData> = defineComponent(
enabled: true,
currentFrame: 0,
frameTimer: 0,
+}, {
+ assetFields: [{ field: 'clip', type: 'anim-clip' }],
});
// =============================================================================
diff --git a/sdk/src/audio/AudioComponents.ts b/sdk/src/audio/AudioComponents.ts
index 77e11a475..6cbc82506 100644
--- a/sdk/src/audio/AudioComponents.ts
+++ b/sdk/src/audio/AudioComponents.ts
@@ -31,6 +31,8 @@ export const AudioSource = defineComponent<AudioSourceData>('AudioSource', {
rolloff: 1.0,
priority: 0,
enabled: true,
+}, {
+ assetFields: [{ field: 'clip', type: 'audio' }],
});
export interface AudioListenerData {
diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.ts
new file mode 100644
index 000000000..b33e96928
--- /dev/null
+++ b/sdk/src/component.generated.ts
@@ -0,0 +1,457 @@
+/**
+ * @file component.generated.ts
+ * @brief Auto-generated component metadata
+ * @details Generated by EHT - DO NOT EDIT
+ */
+
+import type { AssetFieldType } from './scene';
+
+export interface AssetFieldMeta {
+ field: string;
+ type: AssetFieldType;
+}
+
+export interface SpineFieldMeta {
+ skeletonField: string;
+ atlasField: string;
+}
+
+export interface ComponentMetaEntry {
+ defaults: Record<string, unknown>;
+ assetFields: AssetFieldMeta[];
+ spine?: SpineFieldMeta;
+ entityFields: string[];
+ colorFields: string[];
+ animatableFields: string[];
+}
+
+export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
+ UIRect: {
+ defaults: {
+ anchorMin: { x: 0.5, y: 0.5 },
+ anchorMax: { x: 0.5, y: 0.5 },
+ offsetMin: { x: 0, y: 0 },
+ offsetMax: { x: 0, y: 0 },
+ size: { x: 100, y: 100 },
+ pivot: { x: 0.5, y: 0.5 },
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: ['anchorMin.x', 'anchorMin.y', 'anchorMax.x', 'anchorMax.y', 'offsetMin.x', 'offsetMin.y', 'offsetMax.x', 'offsetMax.y', 'pivot.x', 'pivot.y'],
+ },
+ FlexItem: {
+ defaults: {
+ flexGrow: 0,
+ flexShrink: 1,
+ flexBasis: -1,
+ order: 0,
+ alignSelf: 0,
+ margin: { left: 0, top: 0, right: 0, bottom: 0 },
+ minWidth: -1,
+ minHeight: -1,
+ maxWidth: -1,
+ maxHeight: -1,
+ widthPercent: -1,
+ heightPercent: -1,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ BoxCollider: {
+ defaults: {
+ halfExtents: { x: 0.5, y: 0.5 },
+ offset: { x: 0, y: 0 },
+ density: 1,
+ friction: 0.3,
+ restitution: 0,
+ isSensor: false,
+ enabled: true,
+ categoryBits: 0,
+ maskBits: 0,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ CircleCollider: {
+ defaults: {
+ radius: 0.5,
+ offset: { x: 0, y: 0 },
+ density: 1,
+ friction: 0.3,
+ restitution: 0,
+ isSensor: false,
+ enabled: true,
+ categoryBits: 0,
+ maskBits: 0,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ CapsuleCollider: {
+ defaults: {
+ radius: 0.25,
+ halfHeight: 0.5,
+ offset: { x: 0, y: 0 },
+ density: 1,
+ friction: 0.3,
+ restitution: 0,
+ isSensor: false,
+ enabled: true,
+ categoryBits: 0,
+ maskBits: 0,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ SegmentCollider: {
+ defaults: {
+ point1: { x: -0.5, y: 0 },
+ point2: { x: 0.5, y: 0 },
+ density: 1,
+ friction: 0.3,
+ restitution: 0,
+ isSensor: false,
+ enabled: true,
+ categoryBits: 0,
+ maskBits: 0,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ FanLayout: {
+ defaults: {
+ radius: 600,
+ maxSpreadAngle: 30,
+ maxCardAngle: 8,
+ tiltFactor: 1,
+ cardSpacing: 0,
+ direction: 0,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ ParticleEmitter: {
+ defaults: {
+ rate: 10,
+ burstCount: 0,
+ burstInterval: 1,
+ duration: 5,
+ looping: true,
+ playOnStart: true,
+ maxParticles: 1000,
+ lifetimeMin: 5,
+ lifetimeMax: 5,
+ shape: 3,
+ shapeRadius: 100,
+ shapeSize: { x: 100, y: 100 },
+ shapeAngle: 25,
+ speedMin: 500,
+ speedMax: 500,
+ angleSpreadMin: 0,
+ angleSpreadMax: 360,
+ startSizeMin: 100,
+ startSizeMax: 100,
+ endSizeMin: 100,
+ endSizeMax: 100,
+ sizeEasing: 0,
+ startColor: { r: 1, g: 1, b: 1, a: 1 },
+ endColor: { r: 1, g: 1, b: 1, a: 0 },
+ colorEasing: 0,
+ rotationMin: 0,
+ rotationMax: 0,
+ angularVelocityMin: 0,
+ angularVelocityMax: 0,
+ gravity: { x: 0, y: 0 },
+ damping: 0,
+ texture: 0,
+ spriteColumns: 1,
+ spriteRows: 1,
+ spriteFPS: 10,
+ spriteLoop: true,
+ blendMode: 1,
+ layer: 0,
+ material: 0,
+ simulationSpace: 0,
+ enabled: true,
+ },
+ assetFields: [{ field: 'texture', type: 'texture' as AssetFieldType }, { field: 'material', type: 'material' as AssetFieldType }],
+ entityFields: [],
+ colorFields: ['startColor', 'endColor'],
+ animatableFields: [],
+ },
+ Transform: {
+ defaults: {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 0, y: 0, z: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ worldScale: { x: 1, y: 1, z: 1 },
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: ['position.x', 'position.y', 'position.z', 'rotation.z', 'scale.x', 'scale.y', 'scale.z'],
+ },
+ UIRenderer: {
+ defaults: {
+ visualType: 0,
+ texture: 0,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 },
+ sliceBorder: { x: 0, y: 0, z: 0, w: 0 },
+ material: 0,
+ enabled: true,
+ },
+ assetFields: [{ field: 'texture', type: 'texture' as AssetFieldType }, { field: 'material', type: 'material' as AssetFieldType }],
+ entityFields: [],
+ colorFields: ['color'],
+ animatableFields: ['color.r', 'color.g', 'color.b', 'color.a'],
+ },
+ GridLayout: {
+ defaults: {
+ direction: 0,
+ crossAxisCount: 3,
+ itemSize: { x: 100, y: 100 },
+ spacing: { x: 4, y: 4 },
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ Velocity: {
+ defaults: {
+ linear: { x: 0, y: 0, z: 0 },
+ angular: { x: 0, y: 0, z: 0 },
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ SpineAnimation: {
+ defaults: {
+ skeletonPath: '',
+ atlasPath: '',
+ skin: '',
+ animation: '',
+ timeScale: 1,
+ loop: true,
+ playing: true,
+ flipX: false,
+ flipY: false,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ layer: 0,
+ skeletonScale: 1,
+ material: 0,
+ enabled: true,
+ },
+ assetFields: [{ field: 'material', type: 'material' as AssetFieldType }],
+ spine: { skeletonField: 'skeletonPath', atlasField: 'atlasPath' },
+ entityFields: [],
+ colorFields: ['color'],
+ animatableFields: [],
+ },
+ Interactable: {
+ defaults: {
+ enabled: true,
+ blockRaycast: true,
+ raycastTarget: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ UIInteraction: {
+ defaults: {
+ hovered: false,
+ pressed: false,
+ justPressed: false,
+ justReleased: false,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ RigidBody: {
+ defaults: {
+ bodyType: 2,
+ gravityScale: 1,
+ linearDamping: 0,
+ angularDamping: 0,
+ fixedRotation: false,
+ bullet: false,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ BitmapText: {
+ defaults: {
+ text: '',
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ fontSize: 1,
+ align: 0,
+ spacing: 0,
+ layer: 0,
+ font: 0,
+ enabled: true,
+ },
+ assetFields: [{ field: 'font', type: 'font' as AssetFieldType }],
+ entityFields: [],
+ colorFields: ['color'],
+ animatableFields: ['color.r', 'color.g', 'color.b', 'color.a'],
+ },
+ Sprite: {
+ defaults: {
+ texture: 0,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ size: { x: 1, y: 1 },
+ pivot: { x: 0.5, y: 0.5 },
+ uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 },
+ layer: 0,
+ flipX: false,
+ flipY: false,
+ material: 0,
+ enabled: true,
+ },
+ assetFields: [{ field: 'texture', type: 'texture' as AssetFieldType }, { field: 'material', type: 'material' as AssetFieldType }],
+ entityFields: [],
+ colorFields: ['color'],
+ animatableFields: ['color.r', 'color.g', 'color.b', 'color.a', 'size.x', 'size.y'],
+ },
+ UIMask: {
+ defaults: {
+ enabled: true,
+ mode: 0,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ FlexContainer: {
+ defaults: {
+ direction: 0,
+ wrap: 0,
+ justifyContent: 0,
+ alignItems: 3,
+ alignContent: 0,
+ gap: { x: 0, y: 0 },
+ padding: { left: 0, top: 0, right: 0, bottom: 0 },
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ Parent: {
+ defaults: {
+ entity: 0,
+ },
+ assetFields: [],
+ entityFields: ['entity'],
+ colorFields: [],
+ animatableFields: [],
+ },
+ Children: {
+ defaults: {
+ entities: [],
+ },
+ assetFields: [],
+ entityFields: ['entities'],
+ colorFields: [],
+ animatableFields: [],
+ },
+ ShapeRenderer: {
+ defaults: {
+ shapeType: 0,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ size: { x: 100, y: 100 },
+ cornerRadius: 0,
+ layer: 0,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: ['color'],
+ animatableFields: [],
+ },
+ Selectable: {
+ defaults: {
+ selected: false,
+ group: 0,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ LayoutGroup: {
+ defaults: {
+ direction: 0,
+ spacing: 0,
+ padding: { left: 0, top: 0, right: 0, bottom: 0 },
+ childAlignment: 0,
+ reverseOrder: false,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ },
+ Canvas: {
+ defaults: {
+ designResolution: { x: 1920, y: 1080 },
+ pixelsPerUnit: 100,
+ scaleMode: 1,
+ matchWidthOrHeight: 0.5,
+ backgroundColor: { r: 0, g: 0, b: 0, a: 1 },
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: ['backgroundColor'],
+ animatableFields: [],
+ },
+ Camera: {
+ defaults: {
+ projectionType: 0,
+ fov: 60,
+ orthoSize: 5,
+ nearPlane: 0.1,
+ farPlane: 1000,
+ aspectRatio: 0,
+ isActive: false,
+ priority: 0,
+ viewportX: 0,
+ viewportY: 0,
+ viewportW: 1,
+ viewportH: 1,
+ clearFlags: 3,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: ['orthoSize'],
+ },
+};
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 67ba6f0d2..6597fd925 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -3,13 +3,29 @@
* @brief Component definition and builtin components
*/
-import { Entity, Vec2, Vec3, Color, Quat, INVALID_TEXTURE, INVALID_FONT } from './types';
+import { Entity, Vec2, Vec3, Color, Quat } from './types';
import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPRITE_SIZE } from './defaults';
-import { registerComponentEntityFields } from './componentEntityFields';
+import { COMPONENT_META, type AssetFieldMeta, type SpineFieldMeta } from './component.generated';
import type {
RigidBodyData, BoxColliderData, CircleColliderData, CapsuleColliderData,
} from './physics/PhysicsComponents';
+// =============================================================================
+// Self-Describing Component Types
+// =============================================================================
+
+export interface AssetRef {
+ type: string;
+ path: string;
+}
+
+export interface ComponentMetadata {
+ assetFields?: AssetFieldMeta[];
+ spineFields?: SpineFieldMeta;
+ entityFields?: string[];
+ discoverAssets?: (data: Record<string, unknown>) => AssetRef[];
+}
+
// =============================================================================
// Component Definition
// =============================================================================
@@ -19,6 +35,12 @@ export interface ComponentDef<T> {
readonly _name: string;
readonly _default: T;
readonly _builtin: false;
+ readonly assetFields: readonly AssetFieldMeta[];
+ readonly spineFields?: SpineFieldMeta;
+ readonly entityFields: readonly string[];
+ readonly colorKeys: readonly string[];
+ readonly animatableFields: readonly string[];
+ readonly discoverAssets?: (data: Record<string, unknown>) => AssetRef[];
create(data?: Partial<T>): T;
}
@@ -61,7 +83,8 @@ function classifyKeys(obj: object): { flatKeys: string[]; objectKeys: string[];
function createComponentDef<T extends object>(
name: string,
- defaults: T
+ defaults: T,
+ metadata?: ComponentMetadata,
): ComponentDef<T> {
const id = ++componentCounter;
const keyInfo = classifyKeys(defaults);
@@ -71,6 +94,12 @@ function createComponentDef<T extends object>(
_name: name,
_default: defaults,
_builtin: false as const,
+ assetFields: metadata?.assetFields ?? [],
+ spineFields: metadata?.spineFields,
+ entityFields: metadata?.entityFields ?? [],
+ colorKeys: detectColorKeys(defaults),
+ animatableFields: [],
+ discoverAssets: metadata?.discoverAssets,
create(data?: Partial<T>): T {
if (keyInfo) {
const result = { ...defaultsRec };
@@ -97,13 +126,10 @@ export function defineComponent<T extends object>(
const existing = componentRegistry.get(name) ?? getComponentRegistry().get(name);
if (existing) return existing as ComponentDef<T>;
- const def = createComponentDef(name, defaults);
+ const def = createComponentDef(name, defaults, metadata);
getComponentRegistry().set(name, def);
componentRegistry.set(name, def);
registerToEditor(name, defaults as Record<string, unknown>, false);
- if (metadata?.entityFields) {
- registerComponentEntityFields(name, metadata.entityFields);
- }
return def;
}
@@ -156,7 +182,12 @@ export interface BuiltinComponentDef<T> {
readonly _cppName: string;
readonly _builtin: true;
readonly _default: T;
- readonly _colorKeys: readonly string[];
+ readonly assetFields: readonly AssetFieldMeta[];
+ readonly spineFields?: SpineFieldMeta;
+ readonly entityFields: readonly string[];
+ readonly colorKeys: readonly string[];
+ readonly animatableFields: readonly string[];
+ readonly discoverAssets?: (data: Record<string, unknown>) => AssetRef[];
}
// =============================================================================
@@ -203,18 +234,21 @@ export interface ComponentMetadata {
}
export function defineBuiltin<T>(name: string, defaults: T, metadata?: ComponentMetadata): BuiltinComponentDef<T> {
+ const meta = COMPONENT_META[name];
const def: BuiltinComponentDef<T> = {
_id: Symbol(`Builtin_${name}`),
_name: name,
_cppName: name,
_builtin: true,
_default: defaults,
- _colorKeys: detectColorKeys(defaults),
+ assetFields: metadata?.assetFields ?? meta?.assetFields ?? [],
+ spineFields: metadata?.spineFields ?? meta?.spine,
+ entityFields: metadata?.entityFields ?? meta?.entityFields ?? [],
+ colorKeys: meta?.colorFields ?? detectColorKeys(defaults),
+ animatableFields: meta?.animatableFields ?? [],
+ discoverAssets: metadata?.discoverAssets,
};
componentRegistry.set(name, def);
- if (metadata?.entityFields) {
- registerComponentEntityFields(name, metadata.entityFields);
- }
return def;
}
@@ -375,105 +409,64 @@ export interface SceneOwnerData {
// Builtin Component Instances
// =============================================================================
-export const Transform = defineBuiltin<TransformData>('Transform', {
- position: { x: 0, y: 0, z: 0 },
- rotation: { w: 1, x: 0, y: 0, z: 0 },
- scale: { x: 1, y: 1, z: 1 },
- worldPosition: { x: 0, y: 0, z: 0 },
- worldRotation: { w: 1, x: 0, y: 0, z: 0 },
- worldScale: { x: 1, y: 1, z: 1 },
-});
+function metaDefaults<T>(name: string, overrides?: Partial<T>): T {
+ const base = COMPONENT_META[name]?.defaults ?? {};
+ return (overrides ? { ...base, ...overrides } : { ...base }) as T;
+}
+
+export const Transform = defineBuiltin<TransformData>('Transform',
+ metaDefaults<TransformData>('Transform')
+);
export const LocalTransform = Transform;
export const WorldTransform = Transform;
-export const Sprite = defineBuiltin<SpriteData>('Sprite', {
- texture: INVALID_TEXTURE,
- color: { r: 1, g: 1, b: 1, a: 1 },
- size: { x: DEFAULT_SPRITE_SIZE.x, y: DEFAULT_SPRITE_SIZE.y },
- pivot: { x: 0.5, y: 0.5 },
- uvOffset: { x: 0, y: 0 },
- uvScale: { x: 1, y: 1 },
- layer: 0,
- flipX: false,
- flipY: false,
- material: 0,
- enabled: true
-});
-
-export const ShapeRenderer = defineBuiltin<ShapeRendererData>('ShapeRenderer', {
- shapeType: ShapeType.Circle,
- color: { r: 1, g: 1, b: 1, a: 1 },
- size: { x: 100, y: 100 },
- cornerRadius: 0,
- layer: 0,
- enabled: true,
-});
-
-export const Camera = defineBuiltin<CameraData>('Camera', {
- projectionType: ProjectionType.Orthographic,
- fov: 60,
- orthoSize: 540,
- nearPlane: 0.1,
- farPlane: 1000,
- aspectRatio: 1.77,
- isActive: true,
- priority: 0,
- showFrustum: false,
- viewportX: 0,
- viewportY: 0,
- viewportW: 1,
- viewportH: 1,
- clearFlags: ClearFlags.ColorAndDepth,
-});
-
-export const Canvas = defineBuiltin<CanvasData>('Canvas', {
- designResolution: { x: DEFAULT_DESIGN_WIDTH, y: DEFAULT_DESIGN_HEIGHT },
- pixelsPerUnit: DEFAULT_PIXELS_PER_UNIT,
- scaleMode: ScaleMode.FixedHeight,
- matchWidthOrHeight: 0.5,
- backgroundColor: { r: 0, g: 0, b: 0, a: 1 }
-});
-
-export const Velocity = defineBuiltin<VelocityData>('Velocity', {
- linear: { x: 0, y: 0, z: 0 },
- angular: { x: 0, y: 0, z: 0 }
-});
-
-export const Parent = defineBuiltin<ParentData>('Parent', {
- entity: 0 as Entity
-});
-
-export const Children = defineBuiltin<ChildrenData>('Children', {
- entities: []
-});
-
-export const BitmapText = defineBuiltin<BitmapTextData>('BitmapText', {
- text: '',
- color: { r: 1, g: 1, b: 1, a: 1 },
- fontSize: 1.0,
- align: 0,
- spacing: 0,
- layer: 0,
- font: INVALID_FONT,
- enabled: true,
-});
-
-export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation', {
- skeletonPath: '',
- atlasPath: '',
- skin: '',
- animation: '',
- timeScale: 1.0,
- loop: true,
- playing: true,
- flipX: false,
- flipY: false,
- color: { r: 1, g: 1, b: 1, a: 1 },
- layer: 0,
- skeletonScale: 1.0,
- material: 0,
- enabled: true
-});
+export const Sprite = defineBuiltin<SpriteData>('Sprite',
+ metaDefaults<SpriteData>('Sprite', {
+ size: { x: DEFAULT_SPRITE_SIZE.x, y: DEFAULT_SPRITE_SIZE.y },
+ })
+);
+
+export const ShapeRenderer = defineBuiltin<ShapeRendererData>('ShapeRenderer',
+ metaDefaults<ShapeRendererData>('ShapeRenderer')
+);
+
+export const Camera = defineBuiltin<CameraData>('Camera',
+ metaDefaults<CameraData>('Camera', {
+ projectionType: ProjectionType.Orthographic,
+ orthoSize: 540,
+ aspectRatio: 1.77,
+ isActive: true,
+ showFrustum: false,
+ })
+);
+
+export const Canvas = defineBuiltin<CanvasData>('Canvas',
+ metaDefaults<CanvasData>('Canvas', {
+ designResolution: { x: DEFAULT_DESIGN_WIDTH, y: DEFAULT_DESIGN_HEIGHT },
+ pixelsPerUnit: DEFAULT_PIXELS_PER_UNIT,
+ scaleMode: ScaleMode.FixedHeight,
+ })
+);
+
+export const Velocity = defineBuiltin<VelocityData>('Velocity',
+ metaDefaults<VelocityData>('Velocity')
+);
+
+export const Parent = defineBuiltin<ParentData>('Parent',
+ metaDefaults<ParentData>('Parent')
+);
+
+export const Children = defineBuiltin<ChildrenData>('Children',
+ metaDefaults<ChildrenData>('Children')
+);
+
+export const BitmapText = defineBuiltin<BitmapTextData>('BitmapText',
+ metaDefaults<BitmapTextData>('BitmapText')
+);
+
+export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation',
+ metaDefaults<SpineAnimationData>('SpineAnimation')
+);
// =============================================================================
// ParticleEmitter Enums
@@ -552,49 +545,9 @@ export interface ParticleEmitterData {
enabled: boolean;
}
-export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitter', {
- rate: 10,
- burstCount: 0,
- burstInterval: 1,
- duration: 5,
- looping: true,
- playOnStart: true,
- maxParticles: 1000,
- lifetimeMin: 5,
- lifetimeMax: 5,
- shape: EmitterShape.Cone,
- shapeRadius: 100,
- shapeSize: { x: 100, y: 100 },
- shapeAngle: 25,
- speedMin: 500,
- speedMax: 500,
- angleSpreadMin: 0,
- angleSpreadMax: 360,
- startSizeMin: 100,
- startSizeMax: 100,
- endSizeMin: 100,
- endSizeMax: 100,
- sizeEasing: ParticleEasing.Linear,
- startColor: { r: 1, g: 1, b: 1, a: 1 },
- endColor: { r: 1, g: 1, b: 1, a: 0 },
- colorEasing: ParticleEasing.Linear,
- rotationMin: 0,
- rotationMax: 0,
- angularVelocityMin: 0,
- angularVelocityMax: 0,
- gravity: { x: 0, y: 0 },
- damping: 0,
- texture: INVALID_TEXTURE,
- spriteColumns: 1,
- spriteRows: 1,
- spriteFPS: 10,
- spriteLoop: true,
- blendMode: 1,
- layer: 0,
- material: 0,
- simulationSpace: SimulationSpace.World,
- enabled: true,
-});
+export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitter',
+ metaDefaults<ParticleEmitterData>('ParticleEmitter')
+);
export const Name = defineComponent<NameData>('Name', { value: '' });
diff --git a/sdk/src/componentEntityFields.ts b/sdk/src/componentEntityFields.ts
deleted file mode 100644
index f81c3380b..000000000
--- a/sdk/src/componentEntityFields.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-const COMPONENT_ENTITY_FIELDS = new Map<string, string[]>();
-
-export function registerComponentEntityFields(
- componentType: string,
- fields: string[]
-): void {
- COMPONENT_ENTITY_FIELDS.set(componentType, fields);
-}
-
-export function getComponentEntityFields(componentType: string): string[] | undefined {
- return COMPONENT_ENTITY_FIELDS.get(componentType);
-}
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 3a2010cd9..1d331a488 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -464,12 +464,9 @@ export {
remapEntityFields,
updateCameraAspectRatio,
findEntityByName,
- registerComponentAssetFields,
getComponentAssetFields,
getComponentAssetFieldDescriptors,
getComponentSpineFieldDescriptor,
- registerComponentEntityFields,
- getComponentEntityFields,
type AssetFieldType,
type SceneData,
type SceneEntityData,
diff --git a/sdk/src/prefab/entityRef.ts b/sdk/src/prefab/entityRef.ts
index e29c9d821..92de0b95b 100644
--- a/sdk/src/prefab/entityRef.ts
+++ b/sdk/src/prefab/entityRef.ts
@@ -1,14 +1,14 @@
import type { ComponentData } from './types';
-import { getComponentEntityFields } from '../scene';
+import { getComponent } from '../component';
export function remapComponentEntityRefs(
components: ComponentData[],
idMapping: Map<number, number>,
): void {
for (const comp of components) {
- const fields = getComponentEntityFields(comp.type);
- if (!fields) continue;
- for (const field of fields) {
+ const def = getComponent(comp.type);
+ if (!def || def.entityFields.length === 0) continue;
+ for (const field of def.entityFields) {
const value = comp.data[field];
if (typeof value === 'number' && value !== 0) {
const mapped = idMapping.get(value);
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 62f511b64..b9ba21053 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -68,109 +68,25 @@ export interface SceneLoadOptions {
}
// =============================================================================
-// Component Asset Field Registry
+// Asset Field Types
// =============================================================================
export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap' | 'timeline';
-interface AssetFieldDescriptor {
- field: string;
- type: AssetFieldType;
-}
-
-interface SpineFieldDescriptor {
- skeletonField: string;
- atlasField: string;
-}
-
-interface ComponentAssetFields {
- fields?: AssetFieldDescriptor[];
- spine?: SpineFieldDescriptor;
-}
-
-const COMPONENT_ASSET_FIELDS = new Map<string, ComponentAssetFields>([
- ['Sprite', {
- fields: [
- { field: 'texture', type: 'texture' },
- { field: 'material', type: 'material' },
- ],
- }],
- ['SpineAnimation', {
- spine: { skeletonField: 'skeletonPath', atlasField: 'atlasPath' },
- fields: [
- { field: 'material', type: 'material' },
- ],
- }],
- ['BitmapText', {
- fields: [
- { field: 'font', type: 'font' },
- ],
- }],
- ['Image', {
- fields: [
- { field: 'texture', type: 'texture' },
- { field: 'material', type: 'material' },
- ],
- }],
- ['UIRenderer', {
- fields: [
- { field: 'texture', type: 'texture' },
- { field: 'material', type: 'material' },
- ],
- }],
- ['SpriteAnimator', {
- fields: [
- { field: 'clip', type: 'anim-clip' },
- ],
- }],
- ['AudioSource', {
- fields: [
- { field: 'clip', type: 'audio' },
- ],
- }],
- ['ParticleEmitter', {
- fields: [
- { field: 'texture', type: 'texture' },
- { field: 'material', type: 'material' },
- ],
- }],
- ['Tilemap', {
- fields: [
- { field: 'source', type: 'tilemap' },
- ],
- }],
- ['TilemapLayer', {
- fields: [
- { field: 'texture', type: 'texture' },
- ],
- }],
- ['TimelinePlayer', {
- fields: [
- { field: 'timeline', type: 'timeline' },
- ],
- }],
-]);
-
-export function registerComponentAssetFields(
- componentType: string,
- config: ComponentAssetFields
-): void {
- COMPONENT_ASSET_FIELDS.set(componentType, config);
-}
+// =============================================================================
+// Component Query Helpers (read from self-describing ComponentDef)
+// =============================================================================
export function getComponentAssetFields(componentType: string): string[] {
- const config = COMPONENT_ASSET_FIELDS.get(componentType);
- if (!config) return [];
-
+ const comp = getComponent(componentType);
+ if (!comp) return [];
const fields: string[] = [];
- if (config.fields) {
- for (const { field } of config.fields) {
- fields.push(field);
- }
+ for (const { field } of comp.assetFields) {
+ fields.push(field);
}
- if (config.spine) {
- fields.push(config.spine.skeletonField);
- fields.push(config.spine.atlasField);
+ if (comp.spineFields) {
+ fields.push(comp.spineFields.skeletonField);
+ fields.push(comp.spineFields.atlasField);
}
return fields;
}
@@ -178,35 +94,24 @@ export function getComponentAssetFields(componentType: string): string[] {
export function getComponentAssetFieldDescriptors(
componentType: string,
): readonly { field: string; type: AssetFieldType }[] {
- return COMPONENT_ASSET_FIELDS.get(componentType)?.fields ?? [];
+ return getComponent(componentType)?.assetFields ?? [];
}
export function getComponentSpineFieldDescriptor(
componentType: string,
): { skeletonField: string; atlasField: string } | null {
- return COMPONENT_ASSET_FIELDS.get(componentType)?.spine ?? null;
-}
-
-export function getRegisteredAssetComponentTypes(): string[] {
- return Array.from(COMPONENT_ASSET_FIELDS.keys());
+ return getComponent(componentType)?.spineFields ?? null;
}
// =============================================================================
-// Component Entity Reference Fields Registry
+// Entity Reference Remapping
// =============================================================================
-export {
- registerComponentEntityFields,
- getComponentEntityFields,
-} from './componentEntityFields';
-
-import { getComponentEntityFields } from './componentEntityFields';
-
export function remapEntityFields(compData: SceneComponentData, entityMap: Map<number, Entity>): void {
- const fields = getComponentEntityFields(compData.type);
- if (!fields) return;
+ const comp = getComponent(compData.type);
+ if (!comp || comp.entityFields.length === 0) return;
const data = compData.data as Record<string, unknown>;
- for (const field of fields) {
+ for (const field of comp.entityFields) {
const editorId = data[field];
if (typeof editorId === 'number' && editorId !== INVALID_ENTITY) {
const runtimeId = entityMap.get(editorId);
@@ -522,25 +427,29 @@ async function preloadSceneAssets(
if (entityData.visible === false) continue;
for (const compData of entityData.components) {
- if (compData.type === 'StateMachine') {
- const smData = compData.data as { states?: Record<string, { timeline?: string }> };
- if (smData.states) {
- for (const state of Object.values(smData.states)) {
- if (typeof state.timeline === 'string' && state.timeline) {
- assetPaths.get('timeline')?.add(state.timeline);
- }
- }
+ const comp = getComponent(compData.type);
+ if (!comp) continue;
+
+ const data = compData.data as Record<string, unknown>;
+
+ // Strategy: component-defined complex asset discovery
+ if (comp.discoverAssets) {
+ for (const ref of comp.discoverAssets(data)) {
+ assetPaths.get(ref.type as AssetFieldType)?.add(ref.path);
}
}
- const config = COMPONENT_ASSET_FIELDS.get(compData.type);
- if (!config) continue;
-
- const data = compData.data as Record<string, unknown>;
+ // Declarative: simple field→type asset references
+ for (const desc of comp.assetFields) {
+ const value = data[desc.field];
+ if (typeof value !== 'string' || !value) continue;
+ assetPaths.get(desc.type)?.add(value);
+ }
- if (config.spine) {
- const skelPath = data[config.spine.skeletonField] as string;
- const atlasPath = data[config.spine.atlasField] as string;
+ // Spine: paired skeleton+atlas references
+ if (comp.spineFields) {
+ const skelPath = data[comp.spineFields.skeletonField] as string;
+ const atlasPath = data[comp.spineFields.atlasField] as string;
if (skelPath && atlasPath) {
const key = `${skelPath}:${atlasPath}`;
if (!spineKeys.has(key)) {
@@ -549,14 +458,6 @@ async function preloadSceneAssets(
}
}
}
-
- if (config.fields) {
- for (const desc of config.fields) {
- const value = data[desc.field];
- if (typeof value !== 'string' || !value) continue;
- assetPaths.get(desc.type)?.add(value);
- }
- }
}
}
@@ -600,11 +501,11 @@ async function preloadSceneAssets(
if (entityData.visible === false) continue;
for (const compData of entityData.components) {
- const config = COMPONENT_ASSET_FIELDS.get(compData.type);
- if (!config?.fields) continue;
+ const comp = getComponent(compData.type);
+ if (!comp || comp.assetFields.length === 0) continue;
const data = compData.data as Record<string, unknown>;
- for (const desc of config.fields) {
+ for (const desc of comp.assetFields) {
const handles = assetHandles.get(desc.type);
if (!handles) continue;
const value = data[desc.field];
@@ -619,22 +520,6 @@ async function preloadSceneAssets(
}
export function loadComponent(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void {
- if (compData.type === 'LocalTransform' || compData.type === 'WorldTransform') {
- compData.type = 'Transform';
- }
- if (compData.type === 'UIRect') {
- const rectData = compData.data as Record<string, unknown>;
- if (rectData.anchor && !rectData.anchorMin) {
- rectData.anchorMin = { ...(rectData.anchor as Record<string, unknown>) };
- rectData.anchorMax = { ...(rectData.anchor as Record<string, unknown>) };
- delete rectData.anchor;
- }
- }
- if (compData.type === 'UIMask') {
- const maskData = compData.data as Record<string, unknown>;
- if (maskData.mode === 'scissor') maskData.mode = 0;
- else if (maskData.mode === 'stencil') maskData.mode = 1;
- }
const comp = getComponent(compData.type);
if (comp) {
world.insert(entity, comp, compData.data);
diff --git a/sdk/src/tilemap/components.ts b/sdk/src/tilemap/components.ts
index 98264adfc..87c02d845 100644
--- a/sdk/src/tilemap/components.ts
+++ b/sdk/src/tilemap/components.ts
@@ -23,6 +23,8 @@ export interface TilemapLayerData {
export const Tilemap = defineComponent<TilemapData>('Tilemap', {
source: '',
+}, {
+ assetFields: [{ field: 'source', type: 'tilemap' }],
});
export const TilemapLayer = defineComponent<TilemapLayerData>('TilemapLayer', {
@@ -40,4 +42,6 @@ export const TilemapLayer = defineComponent<TilemapLayerData>('TilemapLayer', {
opacity: 1,
visible: true,
parallaxFactor: { x: 1, y: 1 },
+}, {
+ assetFields: [{ field: 'texture', type: 'texture' }],
});
diff --git a/sdk/src/timeline/TimelinePlugin.ts b/sdk/src/timeline/TimelinePlugin.ts
index 0f368850c..340e4f4eb 100644
--- a/sdk/src/timeline/TimelinePlugin.ts
+++ b/sdk/src/timeline/TimelinePlugin.ts
@@ -29,6 +29,8 @@ export const TimelinePlayer = defineComponent<TimelinePlayerData>('TimelinePlaye
playing: false,
speed: 1.0,
wrapMode: 'once',
+}, {
+ assetFields: [{ field: 'timeline', type: 'timeline' }],
});
const loadedAssets_ = new Map<string, TimelineAsset>();
diff --git a/sdk/src/ui/Image.ts b/sdk/src/ui/Image.ts
index a3101ddfb..ef7312a69 100644
--- a/sdk/src/ui/Image.ts
+++ b/sdk/src/ui/Image.ts
@@ -53,4 +53,9 @@ export const Image = defineComponent<ImageData>('Image', {
layer: 0,
material: 0,
enabled: true,
+}, {
+ assetFields: [
+ { field: 'texture', type: 'texture' },
+ { field: 'material', type: 'material' },
+ ],
});
diff --git a/sdk/src/ui/StateMachine.ts b/sdk/src/ui/StateMachine.ts
index 64c1f2028..7653d87a5 100644
--- a/sdk/src/ui/StateMachine.ts
+++ b/sdk/src/ui/StateMachine.ts
@@ -1,4 +1,4 @@
-import { defineComponent } from '../component';
+import { defineComponent, type AssetRef } from '../component';
export interface Condition {
inputName: string;
@@ -67,4 +67,17 @@ export const StateMachine = defineComponent<StateMachineData>('StateMachine', {
inputs: [],
listeners: [],
initialState: '',
+}, {
+ discoverAssets(data) {
+ const refs: AssetRef[] = [];
+ const states = data.states as Record<string, { timeline?: string }> | undefined;
+ if (states) {
+ for (const state of Object.values(states)) {
+ if (typeof state.timeline === 'string' && state.timeline) {
+ refs.push({ type: 'timeline', path: state.timeline });
+ }
+ }
+ }
+ return refs;
+ },
});
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index 61d8ddd20..be29985b1 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -543,7 +543,7 @@ export class World {
}
this.getBuiltinMethods(component._cppName).add(
entity,
- convertForWasm(wasmData, component._colorKeys)
+ convertForWasm(wasmData, component.colorKeys)
);
} catch (e) {
handleWasmError(e, `set(${component._name}, entity=${entity})`);
@@ -587,7 +587,7 @@ export class World {
if (!bset && !methods.has(entity)) return null;
return convertFromWasm(
methods.get(entity) as Record<string, unknown>,
- component._colorKeys,
+ component.colorKeys,
) as ComponentData<C>;
} catch (e) {
handleWasmError(e, `tryGet(${component._name}, entity=${entity})`);
@@ -673,7 +673,7 @@ export class World {
try {
const methods = this.getBuiltinMethods(component._cppName);
isNew = !methods.has(entity);
- methods.add(entity, convertForWasm(merged as Record<string, unknown>, component._colorKeys));
+ methods.add(entity, convertForWasm(merged as Record<string, unknown>, component.colorKeys));
} catch (e) {
handleWasmError(e, `insertBuiltin(${component._name}, entity=${entity})`);
}
@@ -702,7 +702,7 @@ export class World {
const raw = this.getBuiltinMethods(component._cppName).get(entity);
return convertFromWasm(
raw as Record<string, unknown>,
- component._colorKeys,
+ component.colorKeys,
) as T;
} catch (e) {
handleWasmError(e, `getBuiltin(${component._name}, entity=${entity})`);
@@ -857,7 +857,7 @@ export class World {
}
const methods = this.getBuiltinMethods(component._cppName);
- const colorKeys = component._colorKeys;
+ const colorKeys = component.colorKeys;
if (colorKeys.length === 0) {
return (e) => methods.get(e);
}
@@ -891,7 +891,7 @@ export class World {
}
const methods = this.getBuiltinMethods(component._cppName);
- const colorKeys = component._colorKeys;
+ const colorKeys = component.colorKeys;
if (colorKeys.length === 0) {
return (e, d) => methods.add(e, d);
}
diff --git a/src/esengine/core/Reflection.hpp b/src/esengine/core/Reflection.hpp
index a69b81d27..38a90bd59 100644
--- a/src/esengine/core/Reflection.hpp
+++ b/src/esengine/core/Reflection.hpp
@@ -40,8 +40,20 @@
* @details Properties marked with this macro will be accessible from
* JavaScript/TypeScript with automatic getter/setter generation.
* Only works inside ES_COMPONENT() marked types.
+ *
+ * Supports optional metadata annotations parsed by EHT:
+ * - asset=<type> : marks field as asset reference (texture, material, font, audio, etc.)
+ * - animatable : marks field as animatable via timeline
+ * - entity_ref : marks field as entity reference (for ID remapping)
+ * - anim_flag=<flag> : animation side-effect flag (e.g. ANIM_POS_X on UIRect)
+ *
+ * Examples:
+ * ES_PROPERTY(asset=texture)
+ * ES_PROPERTY(animatable)
+ * ES_PROPERTY(animatable, anim_flag=ANIM_POS_X)
+ * ES_PROPERTY(entity_ref)
*/
-#define ES_PROPERTY()
+#define ES_PROPERTY(...)
/**
* @brief Mark a method that should be exposed to scripts
diff --git a/src/esengine/ecs/components/BitmapText.hpp b/src/esengine/ecs/components/BitmapText.hpp
index 9fba9a1b2..cc03d406c 100644
--- a/src/esengine/ecs/components/BitmapText.hpp
+++ b/src/esengine/ecs/components/BitmapText.hpp
@@ -21,7 +21,7 @@ struct BitmapText {
ES_PROPERTY()
std::string text;
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec4 color{1.0f};
ES_PROPERTY()
@@ -36,7 +36,7 @@ struct BitmapText {
ES_PROPERTY()
i32 layer{0};
- ES_PROPERTY()
+ ES_PROPERTY(asset = font)
resource::BitmapFontHandle font;
ES_PROPERTY()
diff --git a/src/esengine/ecs/components/Camera.hpp b/src/esengine/ecs/components/Camera.hpp
index e9c81e5fb..9b9c09f5e 100644
--- a/src/esengine/ecs/components/Camera.hpp
+++ b/src/esengine/ecs/components/Camera.hpp
@@ -63,7 +63,7 @@ struct Camera {
f32 fov{60.0f};
/** @brief Orthographic size (half-height in world units) */
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
f32 orthoSize{5.0f};
/** @brief Near clipping plane distance */
diff --git a/src/esengine/ecs/components/Hierarchy.hpp b/src/esengine/ecs/components/Hierarchy.hpp
index 0d5178e5a..9642dcbac 100644
--- a/src/esengine/ecs/components/Hierarchy.hpp
+++ b/src/esengine/ecs/components/Hierarchy.hpp
@@ -43,7 +43,7 @@ namespace esengine::ecs {
ES_COMPONENT()
struct Parent {
/** @brief Parent entity ID */
- ES_PROPERTY()
+ ES_PROPERTY(entity_ref)
Entity entity = INVALID_ENTITY;
Parent() = default;
@@ -63,7 +63,7 @@ struct Parent {
ES_COMPONENT()
struct Children {
/** @brief List of child entity IDs */
- ES_PROPERTY()
+ ES_PROPERTY(entity_ref)
std::vector<Entity> entities;
Children() = default;
diff --git a/src/esengine/ecs/components/ParticleEmitter.hpp b/src/esengine/ecs/components/ParticleEmitter.hpp
index b1982a1a4..c1ef5cbb4 100644
--- a/src/esengine/ecs/components/ParticleEmitter.hpp
+++ b/src/esengine/ecs/components/ParticleEmitter.hpp
@@ -126,7 +126,7 @@ struct ParticleEmitter {
f32 damping{0.0f};
// Texture
- ES_PROPERTY()
+ ES_PROPERTY(asset = texture)
resource::TextureHandle texture;
ES_PROPERTY()
@@ -148,7 +148,7 @@ struct ParticleEmitter {
ES_PROPERTY()
i32 layer{0};
- ES_PROPERTY()
+ ES_PROPERTY(asset = material)
u32 material{0};
// Space
diff --git a/src/esengine/ecs/components/SpineAnimation.hpp b/src/esengine/ecs/components/SpineAnimation.hpp
index 4806d273b..f7c5bcac6 100644
--- a/src/esengine/ecs/components/SpineAnimation.hpp
+++ b/src/esengine/ecs/components/SpineAnimation.hpp
@@ -47,11 +47,11 @@ namespace esengine::ecs {
ES_COMPONENT()
struct SpineAnimation {
/** @brief Path to skeleton data file (.skel or .json) */
- ES_PROPERTY()
+ ES_PROPERTY(asset = spine_skeleton)
std::string skeletonPath;
/** @brief Path to atlas file (.atlas) */
- ES_PROPERTY()
+ ES_PROPERTY(asset = spine_atlas)
std::string atlasPath;
/** @brief Current skin name (empty for default) */
@@ -95,7 +95,7 @@ struct SpineAnimation {
f32 skeletonScale{1.0f};
/** @brief Custom material ID (0 = use default batch shader) */
- ES_PROPERTY()
+ ES_PROPERTY(asset = material)
u32 material{0};
ES_PROPERTY()
diff --git a/src/esengine/ecs/components/Sprite.hpp b/src/esengine/ecs/components/Sprite.hpp
index fc2331780..ee2a398e2 100644
--- a/src/esengine/ecs/components/Sprite.hpp
+++ b/src/esengine/ecs/components/Sprite.hpp
@@ -44,15 +44,15 @@ namespace esengine::ecs {
ES_COMPONENT()
struct Sprite {
/** @brief Texture resource handle (type-safe) */
- ES_PROPERTY()
+ ES_PROPERTY(asset = texture)
resource::TextureHandle texture;
/** @brief Color tint (RGBA, 0-1 range) */
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};
/** @brief Sprite size in world units */
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec2 size{1.0f, 1.0f};
/** @brief Pivot point (0,0 = bottom-left, 0.5,0.5 = center, 1,1 = top-right) */
@@ -80,7 +80,7 @@ struct Sprite {
bool flipY{false};
/** @brief Custom material ID (0 = use default batch shader) */
- ES_PROPERTY()
+ ES_PROPERTY(asset = material)
u32 material{0};
ES_PROPERTY()
diff --git a/src/esengine/ecs/components/Transform.hpp b/src/esengine/ecs/components/Transform.hpp
index 92583ab86..ae4804b30 100644
--- a/src/esengine/ecs/components/Transform.hpp
+++ b/src/esengine/ecs/components/Transform.hpp
@@ -38,13 +38,13 @@ namespace esengine::ecs {
*/
ES_COMPONENT()
struct Transform {
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec3 position{0.0f, 0.0f, 0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec3 scale{1.0f, 1.0f, 1.0f};
ES_PROPERTY()
diff --git a/src/esengine/ecs/components/UIRect.hpp b/src/esengine/ecs/components/UIRect.hpp
index 80f424b03..f17a55c8f 100644
--- a/src/esengine/ecs/components/UIRect.hpp
+++ b/src/esengine/ecs/components/UIRect.hpp
@@ -8,22 +8,22 @@ namespace esengine::ecs {
ES_COMPONENT()
struct UIRect {
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec2 anchorMin{0.5f, 0.5f};
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec2 anchorMax{0.5f, 0.5f};
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec2 offsetMin{0.0f, 0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec2 offsetMax{0.0f, 0.0f};
ES_PROPERTY()
glm::vec2 size{100.0f, 100.0f};
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec2 pivot{0.5f, 0.5f};
glm::vec2 computed_size_{0.0f};
diff --git a/src/esengine/ecs/components/UIRenderer.hpp b/src/esengine/ecs/components/UIRenderer.hpp
index e406f5485..b1a10a792 100644
--- a/src/esengine/ecs/components/UIRenderer.hpp
+++ b/src/esengine/ecs/components/UIRenderer.hpp
@@ -20,10 +20,10 @@ struct UIRenderer {
ES_PROPERTY()
UIVisualType visualType{UIVisualType::None};
- ES_PROPERTY()
+ ES_PROPERTY(asset = texture)
resource::TextureHandle texture;
- ES_PROPERTY()
+ ES_PROPERTY(animatable)
glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};
ES_PROPERTY()
@@ -35,7 +35,7 @@ struct UIRenderer {
ES_PROPERTY()
glm::vec4 sliceBorder{0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(asset = material)
u32 material{0};
ES_PROPERTY()
diff --git a/tools/eht.py b/tools/eht.py
index 356cddb78..abda90fe2 100644
--- a/tools/eht.py
+++ b/tools/eht.py
@@ -27,6 +27,7 @@ class Property:
name: str
cpp_type: str
default_value: Optional[str] = None
+ annotations: Dict[str, str] = field(default_factory=dict)
@dataclass
@@ -153,7 +154,7 @@ class CppParser:
RE_COMPONENT = re.compile(r'ES_COMPONENT\s*\(\s*\)\s*struct\s+(\w+)')
RE_ENUM = re.compile(r'ES_ENUM\s*\(\s*\)\s*enum\s+class\s+(\w+)(?:\s*:\s*(\w+))?')
RE_PROPERTY = re.compile(
- r'ES_PROPERTY\s*\(\s*\)\s*'
+ r'ES_PROPERTY\s*\(\s*([^)]*)\s*\)\s*'
r'([^;]+?)\s+(\w+)\s*'
r'(?:\{([^}]*)\}|=\s*([^;]+))?;'
)
@@ -213,16 +214,32 @@ class CppParser:
)
for prop_match in self.RE_PROPERTY.finditer(body):
- cpp_type = prop_match.group(1).strip()
- prop_name = prop_match.group(2).strip()
- default = prop_match.group(3) or prop_match.group(4)
+ annotations = self._parse_annotations(prop_match.group(1))
+ cpp_type = prop_match.group(2).strip()
+ prop_name = prop_match.group(3).strip()
+ default = prop_match.group(4) or prop_match.group(5)
component.properties.append(Property(
name=prop_name, cpp_type=cpp_type,
- default_value=default.strip() if default else None
+ default_value=default.strip() if default else None,
+ annotations=annotations
))
self.components.append(component)
+ @staticmethod
+ def _parse_annotations(raw: str) -> Dict[str, str]:
+ result: Dict[str, str] = {}
+ for token in raw.split(','):
+ token = token.strip()
+ if not token:
+ continue
+ if '=' in token:
+ key, value = token.split('=', 1)
+ result[key.strip()] = value.strip()
+ else:
+ result[token] = 'true'
+ return result
+
def parse_directory(self, dirpath: Path) -> None:
for filepath in dirpath.rglob('*.hpp'):
try:
@@ -634,6 +651,267 @@ class TypeScriptGenerator:
return lines
+# =============================================================================
+# Metadata Generator
+# =============================================================================
+
+class MetadataGenerator:
+ """Generates component.generated.ts with defaults and metadata."""
+
+ COLOR_FIELD_PATTERNS = {'color', 'Color', 'tint', 'Tint'}
+
+ def __init__(self, components: List[Component], enums: List[Enum]):
+ self.components = components
+ self.enums = enums
+ self.types = TypeSystem(enums)
+ self._enum_values = self._build_enum_value_map()
+
+ def _build_enum_value_map(self) -> Dict[str, Dict[str, int]]:
+ result: Dict[str, Dict[str, int]] = {}
+ for enum in self.enums:
+ vals: Dict[str, int] = {}
+ for i, v in enumerate(enum.values):
+ vals[v] = i
+ result[enum.name] = vals
+ if enum.namespace:
+ result[f'{enum.namespace}::{enum.name}'] = vals
+ return result
+
+ def _is_color_field(self, prop: Property) -> bool:
+ t = self.types.clean_type(prop.cpp_type)
+ if t != 'glm::vec4':
+ return False
+ return any(pat in prop.name for pat in self.COLOR_FIELD_PATTERNS)
+
+ def _convert_default(self, prop: Property) -> str:
+ t = self.types.clean_type(prop.cpp_type)
+ raw = prop.default_value
+
+ if self.types.is_handle(t):
+ return '0'
+ if t == 'std::string':
+ if raw and raw.startswith('"') and raw.endswith('"'):
+ return raw
+ return "''"
+ if t in self.types.VECTOR_TYPES:
+ return '[]'
+ if t == 'Padding':
+ return '{ left: 0, top: 0, right: 0, bottom: 0 }'
+ if raw and 'static_cast' in raw:
+ m = re.search(r'(\w+)::(\w+)', raw)
+ if m:
+ enum_name, val_name = m.group(1), m.group(2)
+ for key, vals in self._enum_values.items():
+ if key.endswith(enum_name) or key == enum_name:
+ if val_name in vals:
+ return str(vals[val_name])
+ if self.types.is_enum(t):
+ enum_short = t.split('::')[-1]
+ if raw and '::' in raw:
+ val_name = raw.split('::')[-1].strip()
+ for key, vals in self._enum_values.items():
+ if key.endswith(enum_short) or key == enum_short:
+ if val_name in vals:
+ return str(vals[val_name])
+ return '0'
+ if t == 'bool':
+ return 'true' if raw == 'true' else 'false'
+ if t == 'glm::quat':
+ vals = self._parse_float_list(raw, 4)
+ return f'{{ w: {vals[0]}, x: {vals[1]}, y: {vals[2]}, z: {vals[3]} }}'
+ if t == 'glm::vec2':
+ vals = self._parse_float_list(raw, 2)
+ return f'{{ x: {vals[0]}, y: {vals[1]} }}'
+ if t == 'glm::uvec2':
+ vals = self._parse_int_list(raw, 2)
+ return f'{{ x: {vals[0]}, y: {vals[1]} }}'
+ if t == 'glm::vec3':
+ vals = self._parse_float_list(raw, 3)
+ return f'{{ x: {vals[0]}, y: {vals[1]}, z: {vals[2]} }}'
+ if t == 'glm::vec4':
+ vals = self._parse_float_list(raw, 4)
+ if self._is_color_field(prop):
+ return f'{{ r: {vals[0]}, g: {vals[1]}, b: {vals[2]}, a: {vals[3]} }}'
+ return f'{{ x: {vals[0]}, y: {vals[1]}, z: {vals[2]}, w: {vals[3]} }}'
+ if t in TypeSystem.PRIMITIVE_TYPES:
+ return self._format_number(raw)
+ return '0'
+
+ @staticmethod
+ def _parse_float_list(raw: Optional[str], count: int) -> List[str]:
+ if not raw:
+ return ['0'] * count
+ raw = raw.strip()
+ parts = [p.strip().rstrip('fF') for p in raw.split(',')]
+ if len(parts) == 1:
+ val = MetadataGenerator._format_number(parts[0])
+ return [val] * count
+ result = [MetadataGenerator._format_number(p) for p in parts[:count]]
+ while len(result) < count:
+ result.append('0')
+ return result
+
+ @staticmethod
+ def _parse_int_list(raw: Optional[str], count: int) -> List[str]:
+ if not raw:
+ return ['0'] * count
+ parts = [p.strip() for p in raw.split(',')]
+ result = parts[:count]
+ while len(result) < count:
+ result.append('0')
+ return result
+
+ @staticmethod
+ def _format_number(raw: Optional[str]) -> str:
+ if not raw:
+ return '0'
+ raw = raw.strip().rstrip('fF')
+ try:
+ val = float(raw)
+ if val == int(val):
+ return str(int(val))
+ return str(val)
+ except (ValueError, OverflowError):
+ return '0'
+
+ def _get_asset_fields(self, comp: Component) -> List[Dict[str, str]]:
+ fields = []
+ for prop in comp.properties:
+ asset_type = prop.annotations.get('asset')
+ if asset_type and asset_type not in ('spine_skeleton', 'spine_atlas'):
+ fields.append({'field': prop.name, 'type': asset_type})
+ return fields
+
+ def _get_spine_descriptor(self, comp: Component) -> Optional[Dict[str, str]]:
+ skel_field = atlas_field = None
+ for prop in comp.properties:
+ asset_type = prop.annotations.get('asset')
+ if asset_type == 'spine_skeleton':
+ skel_field = prop.name
+ elif asset_type == 'spine_atlas':
+ atlas_field = prop.name
+ if skel_field and atlas_field:
+ return {'skeletonField': skel_field, 'atlasField': atlas_field}
+ return None
+
+ def _get_entity_fields(self, comp: Component) -> List[str]:
+ return [p.name for p in comp.properties if 'entity_ref' in p.annotations]
+
+ def _get_color_fields(self, comp: Component) -> List[str]:
+ return [p.name for p in comp.properties if self._is_color_field(p)]
+
+ def _get_animatable_fields(self, comp: Component) -> List[str]:
+ fields = []
+ for prop in comp.properties:
+ if 'animatable' not in prop.annotations:
+ continue
+ t = self.types.clean_type(prop.cpp_type)
+ if t == 'glm::vec2':
+ fields.extend([f'{prop.name}.x', f'{prop.name}.y'])
+ elif t == 'glm::vec3':
+ fields.extend([f'{prop.name}.x', f'{prop.name}.y', f'{prop.name}.z'])
+ elif t == 'glm::vec4':
+ if self._is_color_field(prop):
+ fields.extend([f'{prop.name}.r', f'{prop.name}.g', f'{prop.name}.b', f'{prop.name}.a'])
+ else:
+ fields.extend([f'{prop.name}.x', f'{prop.name}.y', f'{prop.name}.z', f'{prop.name}.w'])
+ elif t == 'glm::quat':
+ fields.append(f'{prop.name}.z')
+ else:
+ fields.append(prop.name)
+ return fields
+
+ def generate(self) -> str:
+ lines = [
+ '/**',
+ ' * @file component.generated.ts',
+ ' * @brief Auto-generated component metadata',
+ ' * @details Generated by EHT - DO NOT EDIT',
+ ' */',
+ '',
+ "import type { AssetFieldType } from './scene';",
+ '',
+ 'export interface AssetFieldMeta {',
+ ' field: string;',
+ ' type: AssetFieldType;',
+ '}',
+ '',
+ 'export interface SpineFieldMeta {',
+ ' skeletonField: string;',
+ ' atlasField: string;',
+ '}',
+ '',
+ 'export interface ComponentMetaEntry {',
+ ' defaults: Record<string, unknown>;',
+ ' assetFields: AssetFieldMeta[];',
+ ' spine?: SpineFieldMeta;',
+ ' entityFields: string[];',
+ ' colorFields: string[];',
+ ' animatableFields: string[];',
+ '}',
+ '',
+ 'export const COMPONENT_META: Record<string, ComponentMetaEntry> = {',
+ ]
+
+ for comp in self.components:
+ if not comp.properties:
+ continue
+
+ asset_fields = self._get_asset_fields(comp)
+ spine = self._get_spine_descriptor(comp)
+ entity_fields = self._get_entity_fields(comp)
+ color_fields = self._get_color_fields(comp)
+ animatable = self._get_animatable_fields(comp)
+
+ lines.append(f' {comp.name}: {{')
+ lines.append(' defaults: {')
+ for prop in comp.properties:
+ if self.types.is_skip(prop.cpp_type) and prop.cpp_type not in self.types.VECTOR_TYPES:
+ continue
+ val = self._convert_default(prop)
+ lines.append(f' {prop.name}: {val},')
+ lines.append(' },')
+
+ if asset_fields:
+ parts = ', '.join(
+ f"{{ field: '{f['field']}', type: '{f['type']}' as AssetFieldType }}"
+ for f in asset_fields
+ )
+ lines.append(f' assetFields: [{parts}],')
+ else:
+ lines.append(' assetFields: [],')
+
+ if spine:
+ lines.append(
+ f" spine: {{ skeletonField: '{spine['skeletonField']}', "
+ f"atlasField: '{spine['atlasField']}' }},"
+ )
+
+ if entity_fields:
+ parts = ', '.join(f"'{f}'" for f in entity_fields)
+ lines.append(f' entityFields: [{parts}],')
+ else:
+ lines.append(' entityFields: [],')
+
+ if color_fields:
+ parts = ', '.join(f"'{f}'" for f in color_fields)
+ lines.append(f' colorFields: [{parts}],')
+ else:
+ lines.append(' colorFields: [],')
+
+ if animatable:
+ parts = ', '.join(f"'{f}'" for f in animatable)
+ lines.append(f' animatableFields: [{parts}],')
+ else:
+ lines.append(' animatableFields: [],')
+
+ lines.append(' },')
+
+ lines.append('};')
+ lines.append('')
+ return '\n'.join(lines)
+
+
# =============================================================================
# Main
# =============================================================================
@@ -687,6 +965,14 @@ def main():
print(f"Generating: {ts_src_path}")
ts_src_path.write_text(ts_content, encoding='utf-8')
+ meta_gen = MetadataGenerator(cpp_parser.components, cpp_parser.enums)
+ meta_content = meta_gen.generate()
+
+ meta_path = args.ts_output / 'src' / 'component.generated.ts'
+ if meta_path.parent.exists():
+ print(f"Generating: {meta_path}")
+ meta_path.write_text(meta_content, encoding='utf-8')
+
print("[OK] Done!")
return 0