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.

fix(ecs)!: a component name is claimed once, and a second claim with other fields is refused

esenginecc7db2719d6d
diff --git a/examples/celestial-heights/assets/prefabs/wisp.esprefab b/examples/celestial-heights/assets/prefabs/wisp.esprefab
index 4443eee7b..e2f49a027 100644
--- a/examples/celestial-heights/assets/prefabs/wisp.esprefab
+++ b/examples/celestial-heights/assets/prefabs/wisp.esprefab
@@ -51,7 +51,7 @@
}
},
{
- "type": "Health",
+ "type": "Vitality",
"data": {
"current": 45,
"max": 45,
@@ -60,7 +60,7 @@
}
},
{
- "type": "MeleeAttack",
+ "type": "Swing",
"data": {
"damage": 10,
"reach": 76,
diff --git a/examples/celestial-heights/assets/scenes/main.esscene b/examples/celestial-heights/assets/scenes/main.esscene
index 5e00a90b9..63b483241 100644
--- a/examples/celestial-heights/assets/scenes/main.esscene
+++ b/examples/celestial-heights/assets/scenes/main.esscene
@@ -218,7 +218,7 @@
}
},
{
- "type": "Health",
+ "type": "Vitality",
"data": {
"current": 120,
"max": 120,
@@ -227,7 +227,7 @@
}
},
{
- "type": "MeleeAttack",
+ "type": "Swing",
"data": {
"damage": 30,
"reach": 110,
diff --git a/examples/celestial-heights/assets/scenes/moonlit-gallery.esscene b/examples/celestial-heights/assets/scenes/moonlit-gallery.esscene
index 61c572e08..afd07784c 100644
--- a/examples/celestial-heights/assets/scenes/moonlit-gallery.esscene
+++ b/examples/celestial-heights/assets/scenes/moonlit-gallery.esscene
@@ -218,7 +218,7 @@
}
},
{
- "type": "Health",
+ "type": "Vitality",
"data": {
"current": 120,
"max": 120,
@@ -227,7 +227,7 @@
}
},
{
- "type": "MeleeAttack",
+ "type": "Swing",
"data": {
"damage": 30,
"reach": 110,
diff --git a/examples/celestial-heights/assets/scenes/spire.esscene b/examples/celestial-heights/assets/scenes/spire.esscene
index ae8e7bd8d..445776d14 100644
--- a/examples/celestial-heights/assets/scenes/spire.esscene
+++ b/examples/celestial-heights/assets/scenes/spire.esscene
@@ -345,7 +345,7 @@
}
},
{
- "type": "Health",
+ "type": "Vitality",
"data": {
"current": 120,
"max": 120,
@@ -354,7 +354,7 @@
}
},
{
- "type": "MeleeAttack",
+ "type": "Swing",
"data": {
"damage": 30,
"reach": 110,
@@ -455,7 +455,7 @@
}
},
{
- "type": "Health",
+ "type": "Vitality",
"data": {
"current": 480,
"max": 480,
@@ -464,7 +464,7 @@
}
},
{
- "type": "MeleeAttack",
+ "type": "Swing",
"data": {
"damage": 20,
"reach": 150,
diff --git a/examples/celestial-heights/src/ai/wisp.ts b/examples/celestial-heights/src/ai/wisp.ts
index 1affa5d51..893e588f3 100644
--- a/examples/celestial-heights/src/ai/wisp.ts
+++ b/examples/celestial-heights/src/ai/wisp.ts
@@ -3,7 +3,7 @@ import {
registerAction, registerCondition, setNavDestination,
Perception, Status,
} from 'esengine';
-import { Facing, MeleeAttack } from '../components';
+import { Facing, Swing } from '../components';
// Leaves for assets/ai/wisp.esbt. The tree is authored as data and resolves
// these names from the engine's AI registry, so the brain's shape is editable
@@ -12,16 +12,16 @@ import { Facing, MeleeAttack } from '../components';
registerCondition('seesPlayer', (ctx) => ctx.has(Perception) && ctx.get(Perception).visible);
registerCondition('inStrikeRange', (ctx) => {
- if (!ctx.has(Perception) || !ctx.has(MeleeAttack)) return false;
+ if (!ctx.has(Perception) || !ctx.has(Swing)) return false;
const perception = ctx.get(Perception);
// Short of the full reach, so the wisp closes in rather than poking from the
// edge of its own arc.
- return perception.visible && perception.distance <= ctx.get(MeleeAttack).reach * 0.75;
+ return perception.visible && perception.distance <= ctx.get(Swing).reach * 0.75;
});
registerAction('strike', (ctx) => {
- if (!ctx.has(MeleeAttack)) return Status.Failure;
- ctx.set(MeleeAttack, { ...ctx.get(MeleeAttack), pending: true });
+ if (!ctx.has(Swing)) return Status.Failure;
+ ctx.set(Swing, { ...ctx.get(Swing), pending: true });
return Status.Success;
});
diff --git a/examples/celestial-heights/src/components.ts b/examples/celestial-heights/src/components.ts
index ea3928cb7..091f36b25 100644
--- a/examples/celestial-heights/src/components.ts
+++ b/examples/celestial-heights/src/components.ts
@@ -150,7 +150,7 @@ export const Facing = defineComponent('Facing', {
y: 0,
});
-export const Health = defineComponent('Health', {
+export const Vitality = defineComponent('Vitality', {
current: 100,
max: 100,
/** Seconds of invulnerability a hit grants, so one swing lands once. */
@@ -174,7 +174,7 @@ export const HealthBarFill = defineComponent('HealthBarFill', {
* arc test and damage — so `hits`, the mask of what a swing can reach, is the
* only thing separating Lyra's sword from a wisp's touch.
*/
-export const MeleeAttack = defineComponent('MeleeAttack', {
+export const Swing = defineComponent('Swing', {
damage: 25,
/** Swing radius in world units. */
reach: 96,
diff --git a/examples/celestial-heights/src/systems/boss.ts b/examples/celestial-heights/src/systems/boss.ts
index 6dd4b652e..58e7ad509 100644
--- a/examples/celestial-heights/src/systems/boss.ts
+++ b/examples/celestial-heights/src/systems/boss.ts
@@ -4,7 +4,7 @@ import {
NavAgent, setNavDestination, stopNavAgent,
} from 'esengine';
import type { Entity } from 'esengine';
-import { Boss, Charge, Facing, Health, Summoner } from '../components';
+import { Boss, Charge, Facing, Vitality, Summoner } from '../components';
/**
* Vesper's phase, read off her health. Deriving it rather than advancing it on
@@ -12,7 +12,7 @@ import { Boss, Charge, Facing, Health, Summoner } from '../components';
* brain, the HUD bar and this system never disagree about which fight is on.
*/
export const bossPhaseSystem = defineSystem(
- [Query(Mut(Boss), Health)],
+ [Query(Mut(Boss), Vitality)],
(bosses) => {
for (const [, boss, health] of bosses) {
const fraction = health.max > 0 ? health.current / health.max : 0;
diff --git a/examples/celestial-heights/src/systems/combat.ts b/examples/celestial-heights/src/systems/combat.ts
index 2e9f71f36..6f4047acd 100644
--- a/examples/celestial-heights/src/systems/combat.ts
+++ b/examples/celestial-heights/src/systems/combat.ts
@@ -2,7 +2,7 @@ import {
defineSystem, Query, Mut, Res, Time, Transform, Physics2D, Commands,
EventWriter, EventReader, GetWorld,
} from 'esengine';
-import { Facing, Health, MeleeAttack, Player } from '../components';
+import { Facing, Vitality, Swing, Player } from '../components';
import { DamageDealt, Died } from '../events';
import { POINT_BLANK } from '../config';
@@ -15,7 +15,7 @@ const DEG = Math.PI / 180;
*/
export const meleeResolveSystem = defineSystem(
[
- Query(Transform, Facing, Mut(MeleeAttack)),
+ Query(Transform, Facing, Mut(Swing)),
Res(Time), Res(Physics2D), GetWorld(), EventWriter(DamageDealt),
],
(attackers, time, physics, world, damage) => {
@@ -47,11 +47,11 @@ export const damageSystem = defineSystem(
[EventReader(DamageDealt), GetWorld(), EventWriter(Died)],
(blows, world, died) => {
for (const blow of blows) {
- if (!world.has(blow.target, Health)) continue;
- const health = world.get(blow.target, Health);
+ if (!world.has(blow.target, Vitality)) continue;
+ const health = world.get(blow.target, Vitality);
if (health.invulnerable > 0 || health.current <= 0) continue;
let killed = false;
- world.update(blow.target, Health, (h) => {
+ world.update(blow.target, Vitality, (h) => {
h.current -= blow.amount;
h.invulnerable = h.invulnerability;
if (h.current <= 0) {
@@ -66,7 +66,7 @@ export const damageSystem = defineSystem(
);
export const invulnerabilitySystem = defineSystem(
- [Query(Mut(Health)), Res(Time)],
+ [Query(Mut(Vitality)), Res(Time)],
(bodies, time) => {
for (const [, health] of bodies) {
if (health.invulnerable > 0) health.invulnerable -= time.delta;
diff --git a/examples/celestial-heights/src/systems/feedback.ts b/examples/celestial-heights/src/systems/feedback.ts
index 555f1a542..16d418b56 100644
--- a/examples/celestial-heights/src/systems/feedback.ts
+++ b/examples/celestial-heights/src/systems/feedback.ts
@@ -2,7 +2,7 @@ import {
defineSystem, Query, Mut, Transform, Sprite, Parent, GetWorld, UIVisual, UINode, UIDisplay,
} from 'esengine';
import {
- Boss, BossMeter, BossPanel, Health, HealthBarFill, Player, VitalityMeter,
+ Boss, BossMeter, BossPanel, Vitality, HealthBarFill, Player, VitalityMeter,
} from '../components';
/**
@@ -14,8 +14,8 @@ export const healthBarSystem = defineSystem(
[Query(Mut(Transform), Mut(Sprite), HealthBarFill, Parent), GetWorld()],
(bars, world) => {
for (const [, transform, sprite, bar, parent] of bars) {
- if (!world.has(parent.entity, Health)) continue;
- const health = world.get(parent.entity, Health);
+ if (!world.has(parent.entity, Vitality)) continue;
+ const health = world.get(parent.entity, Vitality);
const fraction = health.max > 0 ? Math.max(0, health.current / health.max) : 0;
const width = bar.width * fraction;
sprite.size.x = width;
@@ -30,7 +30,7 @@ export const healthBarSystem = defineSystem(
* the amount is the whole state — no geometry to keep in step with a layout.
*/
export const vitalityMeterSystem = defineSystem(
- [Query(Mut(UIVisual), VitalityMeter), Query(Health, Player)],
+ [Query(Mut(UIVisual), VitalityMeter), Query(Vitality, Player)],
(meters, players) => {
for (const [, visual] of meters) {
for (const [, health] of players) {
@@ -48,7 +48,7 @@ export const vitalityMeterSystem = defineSystem(
* whether it is on screen — not which scene is loaded.
*/
export const bossMeterSystem = defineSystem(
- [Query(Mut(UIVisual), BossMeter), Query(Mut(UINode), BossPanel), Query(Health, Boss)],
+ [Query(Mut(UIVisual), BossMeter), Query(Mut(UINode), BossPanel), Query(Vitality, Boss)],
(meters, panels, bosses) => {
let fraction = -1;
for (const [, health] of bosses) {
@@ -67,7 +67,7 @@ export const bossMeterSystem = defineSystem(
/** Blinks whoever is in invulnerability frames, so a hit is visible at all. */
export const hitFlashSystem = defineSystem(
- [Query(Mut(Sprite), Health)],
+ [Query(Mut(Sprite), Vitality)],
(bodies) => {
for (const [, sprite, health] of bodies) {
sprite.color.a = health.invulnerable > 0
diff --git a/examples/celestial-heights/src/systems/player.ts b/examples/celestial-heights/src/systems/player.ts
index eec925419..b15762cc6 100644
--- a/examples/celestial-heights/src/systems/player.ts
+++ b/examples/celestial-heights/src/systems/player.ts
@@ -1,5 +1,5 @@
import { defineSystem, Query, Mut, CharacterController2D } from 'esengine';
-import { Player, Facing, MeleeAttack } from '../components';
+import { Player, Facing, Swing } from '../components';
import { Actions } from '../actions';
import { DEPTH_FORESHORTEN } from '../config';
@@ -35,7 +35,7 @@ export const playerMoveSystem = defineSystem(
/** Turns the attack key into the same `pending` flag the wisps' brain sets. */
export const playerAttackSystem = defineSystem(
- [Query(Mut(MeleeAttack), Player)],
+ [Query(Mut(Swing), Player)],
(players) => {
if (!Actions.pressed('Attack')) return;
for (const [, attack] of players) attack.pending = true;
diff --git a/examples/celestial-heights/src/systems/save.ts b/examples/celestial-heights/src/systems/save.ts
index 15ead7a7c..4cddf7c00 100644
--- a/examples/celestial-heights/src/systems/save.ts
+++ b/examples/celestial-heights/src/systems/save.ts
@@ -2,13 +2,13 @@ import {
defineSystem, Query, Mut, Res, Commands, GetWorld,
Transform, Name, SceneManager, Localization, transitionTo,
} from 'esengine';
-import { Enemy, Health, Player } from '../components';
+import { Enemy, Vitality, Player } from '../components';
import { saves, SLOT, type RunState } from '../save';
import { Actions } from '../actions';
import { session } from '../state';
export const saveRunSystem = defineSystem(
- [Query(Transform, Health, Player), Query(Name, Enemy), Res(SceneManager), Res(Localization)],
+ [Query(Transform, Vitality, Player), Query(Name, Enemy), Res(SceneManager), Res(Localization)],
(players, living, scenes, i18n) => {
if (!Actions.pressed('Save')) return;
const area = scenes.getActive();
@@ -55,7 +55,7 @@ export const loadRunSystem = defineSystem(
* than being written into whichever one happened to be up.
*/
export const applyRestoreSystem = defineSystem(
- [Query(Mut(Transform), Mut(Health), Player), Query(Name, Enemy), Res(SceneManager), Commands(), GetWorld()],
+ [Query(Mut(Transform), Mut(Vitality), Player), Query(Name, Enemy), Res(SceneManager), Commands(), GetWorld()],
(players, living, scenes, commands, world) => {
const run = session.restore;
if (!run || scenes.getActive() !== run.area || scenes.isTransitioning()) return;
@@ -86,7 +86,7 @@ export const applyRestoreSystem = defineSystem(
let lastArea = '';
export const vitalitySystem = defineSystem(
- [Query(Mut(Health), Player), Res(SceneManager)],
+ [Query(Mut(Vitality), Player), Res(SceneManager)],
(players, scenes) => {
const area = scenes.getActive();
if (!area || scenes.isTransitioning()) return;
diff --git a/examples/space-shooter/assets/scenes/main.esscene b/examples/space-shooter/assets/scenes/main.esscene
index 68a0d0f7e..9fa6d09b8 100644
--- a/examples/space-shooter/assets/scenes/main.esscene
+++ b/examples/space-shooter/assets/scenes/main.esscene
@@ -93,7 +93,7 @@
}
},
{
- "type": "Health",
+ "type": "Hull",
"data": {
"value": 3,
"maxValue": 3
diff --git a/examples/space-shooter/src/components.ts b/examples/space-shooter/src/components.ts
index 401c5241d..b0e6c473b 100644
--- a/examples/space-shooter/src/components.ts
+++ b/examples/space-shooter/src/components.ts
@@ -25,7 +25,7 @@ export const Explosion = defineComponent('Explosion', {
timer: 0.3,
});
-export const Health = defineComponent('Health', {
+export const Hull = defineComponent('Hull', {
value: 3,
maxValue: 3,
});
diff --git a/examples/space-shooter/src/systems/collision.ts b/examples/space-shooter/src/systems/collision.ts
index 911d454be..957868b07 100644
--- a/examples/space-shooter/src/systems/collision.ts
+++ b/examples/space-shooter/src/systems/collision.ts
@@ -2,7 +2,7 @@ import {
defineSystem, Query, Mut, ResMut, Res, Commands,
Transform, Prefabs, type Entity,
} from 'esengine';
-import { Bullet, Enemy, Player, Health } from '../components';
+import { Bullet, Enemy, Player, Hull } from '../components';
import {
GameState, PREFAB_EXPLOSION, positionOverride,
ENEMY_A_SIZE, ENEMY_B_SIZE, PLAYER_SIZE,
@@ -25,7 +25,7 @@ export const collisionSystem = defineSystem(
Res(Prefabs),
Query(Transform, Bullet),
Query(Transform, Enemy),
- Query(Transform, Mut(Health), Player),
+ Query(Transform, Mut(Hull), Player),
],
(cmds, stateMut, prefabServer, bulletQuery, enemyQuery, playerQuery) => {
const state = stateMut.get();
diff --git a/examples/space-shooter/src/systems/hud.ts b/examples/space-shooter/src/systems/hud.ts
index 45b8d6cb8..a764d8126 100644
--- a/examples/space-shooter/src/systems/hud.ts
+++ b/examples/space-shooter/src/systems/hud.ts
@@ -2,11 +2,11 @@ import {
defineSystem, Query, Mut, Res, ResMut, Commands,
Input, Text, UIVisual, Transform,
} from 'esengine';
-import { Player, Health, ScoreDisplay, HealthHeart, GameOverScreen, Enemy, Bullet, Explosion } from '../components';
+import { Player, Hull, ScoreDisplay, HealthHeart, GameOverScreen, Enemy, Bullet, Explosion } from '../components';
import { GameState, PLAYER_START_Y } from '../resources';
export const hudSystem = defineSystem(
- [Res(GameState), Query(Mut(Text), ScoreDisplay), Query(Health, Player), Query(Mut(UIVisual), HealthHeart)],
+ [Res(GameState), Query(Mut(Text), ScoreDisplay), Query(Hull, Player), Query(Mut(UIVisual), HealthHeart)],
(state, scoreQuery, playerQuery, heartQuery) => {
for (const [_entity, text] of scoreQuery) {
text.content = `SCORE: ${state.score}`;
@@ -28,7 +28,7 @@ export const hudSystem = defineSystem(
export const gameOverSystem = defineSystem(
[
Res(Input), ResMut(GameState), Commands(),
- Query(Mut(Transform), Mut(Health), Player),
+ Query(Mut(Transform), Mut(Hull), Player),
Query(Mut(Text), GameOverScreen),
Query(Enemy),
Query(Bullet),
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index 1d0bb18aa..c3617c1ff 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -388,7 +388,21 @@ export function defineComponent<T extends object>(
metadata?: ComponentMetadata,
): ComponentDef<T> {
const existing = userComponents().get(name);
- if (existing) return existing as ComponentDef<T>;
+ if (existing) {
+ // Same fields is one declaration reached twice (two import paths, a hot
+ // reload). DIFFERENT fields is two components claiming one name, and the
+ // loser's fields are dropped from every scene that carries them.
+ const had = Object.keys(existing._default as object).sort();
+ const wants = Object.keys(defaults).sort();
+ if (had.length !== wants.length || had.some((k, i) => k !== wants[i])) {
+ throw new Error(
+ `Component name collision: "${name}" is already defined with fields `
+ + `[${had.join(', ')}], and this declaration has [${wants.join(', ')}]. `
+ + 'One of them loses its fields wherever a scene carries them — rename one.',
+ );
+ }
+ return existing as ComponentDef<T>;
+ }
if (builtinRegistry.has(name)) {
throw new Error(
diff --git a/sdk/tests/component.test.ts b/sdk/tests/component.test.ts
index 05870540d..c44ff3e68 100644
--- a/sdk/tests/component.test.ts
+++ b/sdk/tests/component.test.ts
@@ -49,12 +49,19 @@ describe('Component Registry', () => {
expect(retrieved).toBe(Custom);
});
- it('should reuse existing component on duplicate names', () => {
+ it('reuses the definition when a name is declared twice with the same fields', () => {
const comp1 = defineComponent('Duplicate', { a: 1 });
- const comp2 = defineComponent('Duplicate', { b: 2 });
+ const comp2 = defineComponent('Duplicate', { a: 1 });
expect(comp1).toBe(comp2);
});
+
+ it('refuses a second component that claims a taken name with other fields', () => {
+ defineComponent('Contested', { a: 1 });
+
+ expect(() => defineComponent('Contested', { b: 2 }))
+ .toThrow(/Component name collision: "Contested"/);
+ });
});
describe('defineTag', () => {
@@ -137,7 +144,7 @@ describe('Component Registry', () => {
describe('component reuse', () => {
it('should reuse component on duplicate names', () => {
const comp1 = defineComponent('Reusable', { x: 1 });
- const comp2 = defineComponent('Reusable', { y: 2 });
+ const comp2 = defineComponent('Reusable', { x: 1 });
expect(comp1).toBe(comp2);
});