Skip to content

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 ​

ts
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.dt

Every 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 ​

ts
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 ​

ts
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 ​

ts
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 brain

Change who owns a unit, move it, hide it ​

ts
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 entirely

Fields 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 ​

ts
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 ​

ts
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 ​

ts
invalidateStats(world, entity) // or invalidateStats(world) for everyone

Spawn a group of things: a prefab ​

ts
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 } }]
	}
})
ts
// 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 neutral

Give a component a field in the map editor ​

ts
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 ​

ts
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 in

Designers 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 ​

ts
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 ​

  1. Select a placed thing; fields from components with a field appear in the Inspector.
  2. Place › Prefabs lists the game's prefabs beside the designer's (read-only).
  3. 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 changeUse
Who owns itworld.setOwner(entity, player)
Where a unit standsworld.place(entity, point)
In or out of the worldworld.setHidden(entity, hidden, at?)
How long it lastsworld.setLifetime(entity, seconds)
A rush or a leapstartDash(world, entity, dash)
What it ismorph(world, entity, type)
BuffsapplyBuff, removeBuff
Healthworld.damage, world.heal
Whether it livesworld.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) ​

OptionWhat it does
idPrefix it with your game's ('td.waves'); the engine's are core.. Redefining an id is fine
defaultMade the first time world.state or player.state reads it
replicateSend 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
indextrue 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 ​

  • contents is data, or (at, world) => ... for one made for its place.
  • spawnPrefab turns 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). without leaves parts out by index; names are made unique.
  • Nested: contents.prefabs lists others by id with x, z, facing, scale; without: { prefabs: [0] }. A prefab inside itself spawns once.
  • prefabsFrom(files) reads the editor's prefabs/<name>.prefab.json files (with an optional prefix); scenery, points and paths are left out. Variants and nesting resolve as in the editor (nestedPartId).
  • debug.spawnPrefab spawns one from the console or a test.

Rules in code ​

WhatAPI
Formulas (Rules.settings.combat)mitigation (armour and magic resist), clampStats, cooldown (ability haste)
StatsCoreStats; 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 placeRuleSettings.movement.moveSpeed(world, entity, speed)
InvisibilityA buff's invisible (a function for one moment)
Morphmorph(world, entity, type) keeps what the new type is given (Component.onSpawn) and runs the morphed hook ({ entity, from })
Economy and heroesRuleSettings.supply.of(world, unit), economy.upkeep(world, player), heroes.pointsForLevel(level), production.buildRate(world, structure, builders)
ResearchUpgradeDef.apply(world, entity, level); an effect's units may be a function of the type
Lootdrops: (world, entity, killer) => itemIds; map item tables (GameMap.itemTables) by item, { level, weight } or { class }. Items have level, class and their own saved data
AbilitiesautoAim(world, caster, state), rangeOf, castTimeOf, channel: { duration, every, effects, run, interrupted }, defineEffect<{ bounces: number }>({ type: ... }) with params
BuffsperStack, 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 unitsThe 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.