Components and world state
Keep state of your own on entities, players or the whole game (components), change the world safely from code, spawn groups of things at once (prefabs), and read your own kinds of map things.
Quick start
import { defineComponent } from '@v12-engine/engine'
const burning = defineComponent<{ seconds: number }>({ id: 'mymod.burning', replicate: 'everyone' })
export const rules: Rules = { ...game, components: [burning] }
entity.set(burning, { seconds: 3 })
entity.get(burning)?.seconds
for (const each of world.index.with(burning)) each.get(burning)!.seconds -= world.dtEvery entity can now carry a burning value. It is saved, and everyone who sees the entity gets it in their snapshot.
Common tasks
State for the whole game or each player
const waves = defineComponent<WaveState>({ id: 'td.waves', default: () => ({ wave: 0, phase: 'waiting' }) })
world.state(waves).wave++ // made from the default the first time
player.state(waves)Keep state in a faster form while the game runs
const heat = defineComponent<Uint8Array>({
id: 'mygame.heat',
default: () => new Uint8Array(256 * 256),
save: (cells) => Object.fromEntries([...cells.entries()].filter(([, value]) => value > 0)), // plain data in the save
load: (saved) => {
const cells = new Uint8Array(256 * 256)
for (const [at, value] of Object.entries(saved as Record<number, number>)) cells[Number(at)] = value
return cells
}
})A save takes save's plain data and gives it back to load, for a component on an entity, on a player or on the whole game. Without them the value itself is saved, and has to be plain data.
Send part of a component to the screen
const mana = defineComponent<{ value: number; secret: number }>({
id: 'mygame.mana',
replicate: 'owner',
snapshot: (value, entity, view) => ({ value: Math.round(value.value) }) // view says own, ally or observer
})
snapshotOf(state, mana) // read it typed, on a screen or in a brainChange who owns a unit, move it, hide it
world.setOwner(entity, player)
world.place(entity, point)
world.setHidden(entity, true) // a worker inside a mine
world.setLifetime(entity, 30)
morph(world, entity, 'demonForm') // a different type entirelyFields kept in step with the navigation and lookups are readonly; change them through these calls only (see the table). Anything else (health, mana, cooldowns, buff stacks) you may set directly.
Make two players allies mid-game
world.sides.setRelation(a, b, 'ally') // 'enemy', 'neutral', or null for their teams' say
world.sides.setTeam(player, team)
world.sides.shareVision(from, to, true)Add a stat
export const stats = [{ id: 'spellPower', name: 'Spell power', default: 5, max: 60, format: 'number' }]Put it in Rules.stats. Every unit has it; buffs, items, upgrades and hero growth change it; abilities scale with it (scaling: { spellPower: 0.5 }).
Recompute stats after your own code changes something
invalidateStats(world, entity) // or invalidateStats(world) for everyoneSpawn a group of things: a prefab
import { definePrefab } from '@v12-engine/engine'
const outpost = definePrefab({
id: 'td.outpost',
contents: {
objects: [
{ type: 'tower', x: -3, z: 0 },
{ type: 'tower', x: 3, z: 0 },
{ type: 'knight', x: 0, z: 2, owner: 'owner' }
],
camps: [{ x: 0, z: 8, units: ['gnoll', 'gnoll'] }],
areas: [{ id: 'td.yard', shape: { kind: 'circle', x: 0, z: 0, radius: 6 } }]
}
})// in the rules: prefabs: [outpost, ...prefabsFrom(import.meta.glob('./prefabs/*.prefab.json', { eager: true }))]
const made = world.spawnPrefab('td.outpost', { at: { x: 30, z: 30 }, owner: player, facing: Math.PI / 2 })
made.entities // the towers and the knight; the knight is the player's, the rest neutralGive a component a field in the map editor
const patrolRoute = defineComponent<string>({ id: 'td.route', field: { name: 'Route', kind: 'path', for: ['guard'], default: '' } })Placed things start with the component set to the field's value, and the Inspector shows it.
Read your own kinds of map things
world.map.things('td.clearings') // every one: id, x, z, facing, name, and your fields as data
world.map.things('td.clearings', fields) // with the fields' defaults filled inDesigners place them in the editor (Kinds of thing of a game's own); the td starter's src/td/road.ts reads them.
Tell the editor where your data names things
export const editor: Rules['editor'] = {
references: (ref: MapRef, map): MapRefUse[] => {
if (!('type' in ref)) return []
return wavesOf(map)
.filter((wave) => wave.types.includes(ref.type))
.map((wave) => ({ what: 'wave', where: `wave ${wave.number}` }))
}
}Now Find references and Replace with… in the editor include your waves. In code: editor.find(ref), editor.showReferences(ref), editor.replaceWith({ type: 'footman' }, 'knight', 'everywhere').
Editor
- Select a placed thing; fields from components with a
fieldappear in the Inspector. - Place › Prefabs lists the game's prefabs beside the designer's (read-only).
- Find references (also
?in the search,uses:in the Hierarchy, Used by in the Inspector) shows where a type, model, prefab, region, point, path or file is used.
Reference
Changing the world
| To change | Use |
|---|---|
| Who owns it | world.setOwner(entity, player) |
| Where a unit stands | world.place(entity, point) |
| In or out of the world | world.setHidden(entity, hidden, at?) |
| How long it lasts | world.setLifetime(entity, seconds) |
| A rush or a leap | startDash(world, entity, dash) |
| What it is | morph(world, entity, type) |
| Buffs | applyBuff, removeBuff |
| Health | world.damage, world.heal |
| Whether it lives | world.kill |
Structures refuse place, setHidden and startDash. A passive is told how long each run covers (interval); multiply per-second amounts by it.
defineComponent<T>(options)
| Option | What it does |
|---|---|
id | Prefix it with your game's ('td.waves'); the engine's are core.. Redefining an id is fine |
default | Made the first time world.state or player.state reads it |
replicate | Send it to the owner, allies or everyone who sees the entity (EntityState.components) |
snapshot(value, entity, view) | Shape what each player gets (view: own, ally, observer, and world) |
same(a, b) | Tell the delta two snapshots match, when comparing text would cost |
index | true keeps world.index.with(key); 'owner' also with(key, player) |
field | { name, kind, for, default… }: a map editor field |
List every component in Rules.components (or game.components.add in a mod); one used unlisted throws UnlistedError. An event of your own must be in Rules.events. An app's own components go in CreateWorldOptions.components. The engine's parts are components too (shopStock, entity.get(shopStock)). On an entity: get, set, has, remove.
Prefabs
contentsis data, or(at, world) => ...for one made for its place.spawnPrefabturns and sizes it around its middle (facing,scale), spawns objects (owner'owner','neutral','creeps', or a player id), camps, and areas with ids of their own (td.yard#1).withoutleaves parts out by index; names are made unique.- Nested:
contents.prefabslists others by id withx,z,facing,scale;without: { prefabs: [0] }. A prefab inside itself spawns once. prefabsFrom(files)reads the editor'sprefabs/<name>.prefab.jsonfiles (with an optionalprefix); scenery, points and paths are left out. Variants and nesting resolve as in the editor (nestedPartId).debug.spawnPrefabspawns one from the console or a test.
Rules in code
| What | API |
|---|---|
Formulas (Rules.settings.combat) | mitigation (armour and magic resist), clampStats, cooldown (ability haste) |
| Stats | CoreStats; a stat the game lacks makes building the game throw. The stats hook (event.add({ stats: { armor: 2 } })); a buff's change(world, carrier, instance). Debug checks throw on stale stats |
| Speed by place | RuleSettings.movement.moveSpeed(world, entity, speed) |
| Invisibility | A buff's invisible (a function for one moment) |
| Morph | morph(world, entity, type) keeps what the new type is given (Component.onSpawn) and runs the morphed hook ({ entity, from }) |
| Economy and heroes | RuleSettings.supply.of(world, unit), economy.upkeep(world, player), heroes.pointsForLevel(level), production.buildRate(world, structure, builders) |
| Research | UpgradeDef.apply(world, entity, level); an effect's units may be a function of the type |
| Loot | drops: (world, entity, killer) => itemIds; map item tables (GameMap.itemTables) by item, { level, weight } or { class }. Items have level, class and their own saved data |
| Abilities | autoAim(world, caster, state), rangeOf, castTimeOf, channel: { duration, every, effects, run, interrupted }, defineEffect<{ bounces: number }>({ type: ... }) with params |
| Buffs | perStack, stacking ('strongest', 'refresh', 'perSource', 'independent', or a function), onApply, onTick: { every, effects, run }, onRemove(world, carrier, instance, expired), stun/root as functions, silence per ability, instance.data |
| Idle units | The idle hook gives units with nothing to do something else to do |
Map things of your own
world.map.things(kind) returns MapThings (id, x, z, facing, name, data). The engine does nothing else with them; your hooks give them meaning (keepClearingsFree in the td starter).
References
A use (MapRefUse) says what names the thing and where; with a target (an object, camp, region, point, path, doodad or thing, by id) clicking it in the editor selects it. The editor reads the map, prefabs and cinematics itself; editor.references adds what your data names.