World
Class of @v12-engine/engine
export declare class WorldThe simulation: the ground, entities, players, systems and rules of one game, stepped a tick at a time with step
Members
constructor beta
constructor(options: WorldOptions);Makes an empty world of the options' terrain, rules and players; a game makes one with createWorld or createWorldFromMap, which also place the map's things and start the rules
addSystem beta
addSystem(system: System): void;Adds a system to the running world, like a computer player. It takes its place by its phase, before and after
air beta
readonly air: Navigation;The air alone
areAllies
areAllies(a: PlayerId, b: PlayerId): boolean;Whether two players are on one side (sides.allies)
areas
readonly areas: Areas;The areas of the game, and who is in them
areEnemies
areEnemies(a: PlayerId, b: PlayerId): boolean;Whether two players fight each other (sides.enemies): asked of every target, every tick
caught beta
caught(error: unknown, where: ErrorSite): void;What a part of the game that threw comes to, by what the world says of errors (errorPolicy). It returns when the part is to be switched off or let go (disable): the caller does that, and goes on. It throws otherwise: the error itself (throw), or what leaves the tick of a game that ends there (end)
cheats beta
readonly cheats: {
noCooldowns: boolean;
noManaCosts: boolean;
invulnerable: boolean;
speed: number;
};Switches for trying things out. A game that is played for real leaves them off
checkpoint
checkpoint(label: MessageRef): void;Marks a moment to start again from, like the start of a wave, with what the player is told it is ("Wave 6"). A session keeps a save of the world as it is at the end of this tick, for "Retry from wave 6"
checks beta
checks: DebugChecks;The engine's checks on itself this world runs (DebugChecks): what it was made with (CreateWorldOptions.checks), the process's (setDebugChecks) when it says nothing. Slow: tests and development
clock beta
readonly clock: Clock;The time of day (Clock): the hour, night, turned forward or stopped
commandLimit beta
commandLimit: number;Commands a player may give between two ticks, at most (issue, from outside a tick): those past it are let go, and the tick says so once (commandRejected, reason tooManyCommands), and answers each the sender numbered, refused (commandHandled). A server's rate limit keeps far under it; this bounds what has none (a worker, a page's own host, a script gone wrong). The computer and scripts, which give theirs in a tick, are not counted. 100 when left out; Infinity for none
computers
readonly computers: Computers;The computer players: who is seated, kept in a save and seated again by a load (world.computers.seat)
damage
damage(target: Entity, amount: number, source?: Entity, options?: DamageOptions): void;Deals damage (life.damage): the hooks, armor and shields, health, death
debugPlayers beta
readonly debugPlayers: Set<number>;Players who may use the debug commands (debug.*, see debugCommands.ts): who a session lets, a seat in the page that asked, a server started to. Not in a save: whoever loads it says again
delayed beta
readonly delayed: Delayed[];Effects waiting for their time to come
dialog
readonly dialog: Dialog;What is said, by whom, to whom: world.dialog.say(player, line), or talk in a sequence
disable beta
disable(sites: Iterable<ErrorSite>): void;Switches off the parts a save says were (world.disabled): the same game goes on as the one that was saved
disabled beta
readonly disabled: Map<string, ErrorSite>;The parts switched off for having thrown (disable), by name (siteKey): kept in a save, and off again when it is loaded
dispose
dispose(): void;Frees what the world holds outside of JavaScript's memory: its navigation (a navmesh, its tiles and its crowd, in WebAssembly, which is never collected by itself). Whoever made the world disposes it once done with it: the session that owns it (LocalSession's ownsWorld), the host (SessionHost's), a test. Once is enough: again does nothing
disposed beta
get disposed(): boolean;Whether it was disposed: its navigation is freed, and it is not to be stepped again
dt beta
readonly dt: number;Seconds per tick
entities beta
readonly entities: Map<number, Entity>;Everything in the world, by id. Fallen heroes stay in here while they wait to be brought back
errorPolicy beta
errorPolicy?: ErrorPolicy;What becomes of a part of the game that throws: a hook's handler, a listener, a system, a timer, an order, a command (ErrorPolicy). The game's own (Rules.onError), or whoever runs the world's; with neither it throws, as it always did. A server and a launched game end the game where nothing is said (??= 'end')
events
readonly events: Emitter;What happened, for whoever watches: sessions, tests. Sent out at the end of each tick. Rules use hooks
failure beta
failure: WorldFailure | null;Why the game ended on an error, once it has (end): the world is not stepped again
find
find(filter?: {
owner?: PlayerId;
type?: string;
area?: string;
dead?: boolean;
}): Entity[];The entities that are all of what is asked, for scripts: whose they are, of which type, in which area. Only the living, unless asked. A new list: for what runs every tick, go through index or areas instead; by place and condition, query
fog beta
readonly fog: FogOfWar;What each team has seen and sees, per cell
fromMap beta
readonly fromMap: Map<number, number>;The entity each object of the map became, by the object's id (MapObject.id): what the map put down as the world was made of it (createWorldFromMap), and what the editor's Play here put down since (debug.mapObject), for the editor to find again what it moves and takes away (EQ10). Kept in a save
fx beta
fx(fx: string, options?: FxOptions): number;Plays one of the view's fx (GameView.fx.defs) on the screens of the players who see where it is, or those it is for (to): at a place (at), or on an entity (on, at a point of its model), with knobs (params). Its random parts go by a seed, the same on every screen. Nothing it does decides anything: it is not in the world's state, a save, or what a player who joins later is told. What it gives back stops it (stopFx)
get
get(id: EntityId | undefined): Entity | undefined;Living entity with this id
grid beta
readonly grid: BuildGrid;Which cells are taken by buildings and what can be built where
ground beta
ground?: GroundBase;The ground it started on, where it was made from a map (S36): what a save keeps only the changes of
handling beta
handling?: {
player: PlayerId;
refusal: Message | undefined;
};The command being carried out, to find out whether it was refused: see executeCommand
heal
heal(target: Entity, amount: number, source?: Entity): number;Heals (life.heal): how much it healed
hint beta
hint(player: PlayerId, message: MessageRef, options?: {
seconds?: number;
}): void;Gives a player a hint (campaign plan CP5): a message of the kind hint, shown for seconds (the screen's own time when left out), which a player who turned hints off in the settings does not see
hooks
readonly hooks: Hooks;Where game modules and mods take part in damage, deaths, orders and the like, see HookEvents
hour beta
get hour(): number;Hour of the day, 0..24. Noon in a game without days (clock.hour)
index beta
readonly index: EntityIndex;Entities by owner, heroes by owner, shops. For questions that would otherwise go through every entity
internals beta
internals(): WorldInternals;What a save needs that is the world's own business: id counters, the clock and the commands waiting for the next tick. For saveWorld and loadWorld only
issue
issue(command: IssuedCommand): void;Queues a player command. It is applied at the start of the next tick; talk (a command whose def says outsideTick: chat, a ping) given between ticks is carried out at once, a paused game's too (RV14)
isVisibleTo beta
isVisibleTo(entity: Entity, team: number): boolean;Whether a team currently sees the entity (sight.sees): asked of every entity, team and snapshot
items beta
readonly items: GroundItem[];Items lying on the ground
kill
kill(entity: Entity, killer?: Entity, attack?: boolean, reason?: DeathReason): void;Kills (life.kill)
life beta
readonly life: Life;How things are hurt, healed and die (Life)
log
readonly log: Logger;What this world says about what it does: world.log.warn('waves', 'nothing to send', { wave }). Each entry says the game and the tick it is from, and goes to whoever asked (world.log.to(sink)) and to the logger the world was made under. It changes nothing in the world, and is not in a save
made beta
made(id: EntityId): boolean;Whether an entity of this id was ever made here: one that died was, one of a number not yet given out never was
map
get map(): WorldMap;What the map this world was made from says that is not an entity: its name, and what the game kept with it (GameMap.data). Kept in the world, so a save has it. Empty for a world made without a map
mayCommand beta
mayCommand(player: PlayerId, entity: Entity): boolean;Whether a player may command an entity (sides.mayCommand): what every command is checked against
message
message(player: PlayerId, message: MessageRef, kind?: MessageKind): void;Tells a player something, like why what they asked for cannot be done. The world says which message, and the player's screen finds the words for it (see Message). A bare string is a key without params
missiles beta
readonly missiles: Missile[];The missiles in flight
named
named<Name extends string = string>(name: Name): Entity | undefined;The entity of this name, while it lives: one named on the map in the editor, or in code. Nothing once it is dead, or when there never was one. A game can say which names there are: world.named<RoadNames>('gate')
nameOf beta
nameOf(entity: Entity): string | undefined;The name an entity was given, if any
nav beta
readonly nav: Navigation;The ground and the air. Agents find their own layer, everything else is about the ground
navFor beta
navFor(entity: Entity): Navigation;The navigation an entity walks by: the air, the water or the ground, by its layer
neutral beta
get neutral(): PlayerId;The neutral player, who owns what belongs to nobody (a soul, a mine, a tree): the first of them, the game's MAP_NEUTRAL. Throws for a game that has none
newId beta
newId(): number;Unique id for orders, order groups and projectiles
night beta
get night(): boolean;Whether the sun is down (clock.night): asked for every unit's sight and stats, many times a tick
objectives
readonly objectives: Objectives;What each player is set to do, in a mission
obstaclesRefused beta
obstaclesRefused: number;Obstacles the navigation had no room for (RecastNavigationOptions.maxObstacles): what is put down past it does not block the way
place
place(entity: Entity, point: Vec2): void;Puts a unit somewhere else, where it stands: the way through is not its concern. Structures stay where they were built
player
player(id: PlayerId): Player;The player of this id; throws when there is none
players
readonly players: Map<number, Player>;Every player of the world, by id
projectiles beta
readonly projectiles: Projectile[];The shots in flight
query beta
query(query?: WorldQuery): Entity[];What in the world is all a query asks (WorldQuery): around a point or a unit (near, radius), in an area, of whom, of which type, kind and layer, what it carries and how hurt it is (UnitCondition), what a player sees, or code (where); in an order (sort: nearest, lowestHealthShare, random…), as many as limit says. A new list: world.query({ near: hero, radius: 8, is: 'enemy', healthBelow: 0.3, sort: 'nearest', limit: 3 })
redefine beta
redefine(kind: DataKind, id: string, values: DataValues): boolean;Changes a definition while the game runs (S61): a unit type's health, an ability's cooldown, as the editor's Data panel tries them. What is made of it from then on is made of the new one; a unit type's units already in the world take it at once, with as much of their health lost as before. Kept with the world and in its save, and said (definitionChanged). False for a definition the game does not have. Not held to what the game lets be changed (Rules.editable), as layData and a map's definitions are: any field is taken. The check is the command's that the Data panel sends (redefineCommand); code that calls this says what it allows itself
registry
readonly registry: Registry;The game's definitions: unit types, abilities, orders and the rest
removeSystem beta
removeSystem(name: string): boolean;Takes a system out by name. False when there is none of that name
reshapeGround beta
reshapeGround(patch: TerrainPatch): void;Reshapes a part of the ground as the game goes (TerrainPatch): its heights, cliffs, water, paint, what is kept off it and the game's layers of cells, all at once, as the editor's Play here pushes the map's ground into the game played (debug.ground, EQ10). What the rules go by follows: who sees whom from the levels, where can be built, and the ways, cut again of the ground as it is now (Navigation.reshape: on this thread, every machine the same; only the tiles of the ways the patch reaches, a few milliseconds for a field, where the ground is still cut on the same grid, else all of them, which is not for nothing on a big map). What stands on it stays where it is. Every player is told (a ground event), and saves keep it. Throws where the patch does not fit the ground (terrainPatchProblem)
restoreDead beta
restoreDead(ids: readonly EntityId[]): void;Puts back who died and waits to be taken out (WorldInternals.dead), once the entities are back. For loadWorld only
restoreInternals beta
restoreInternals(internals: WorldInternals): void;Puts back what internals gave, for loadWorld only
restoreSystems beta
restoreSystems(saved: Record<string, unknown>): void;Gives the systems what they kept in a save (see System.save): those there now, and those added later
reveal beta
reveal(team: number, point: Vec2, radius: number, seconds: number, options?: {
quiet?: boolean;
}): Reveal;Lets a team see a spot for a while, with nothing standing there
reveals beta
readonly reveals: Reveal[];Spots a team sees for a while without anything there to see them
rng
readonly rng: Rng;The world's seeded random generator; the only source of randomness the simulation uses
saved beta
saved(): void;A save of the world was taken, which put its crowd back (saveWorld): told to what watches it. The engine's
sceneryInSight beta
readonly sceneryInSight: Map<number, Set<Entity>>;The scenery each team sees right now, by team. Kept by the fog system whenever it works out what everyone sees: scenery never moves, so this only changes then. Lets a session describe what is in sight without testing every tree
scheduler beta
readonly scheduler: Scheduler;Runs the systems, in order, each as often as it asks
score beta
readonly score: Score;What the game counts of its players (RuleSettings.score): world.score.add(player, 'towersLost'), get, team. Counts nothing in a game that does not ask
seed beta
readonly seed: number;What the world's numbers started from (rng): 1 when none was given. A computer player's own numbers start from it and its player
sequences
readonly sequences: Sequences;Scripts of steps that run over time: world.sequences.start(briefing)
setCells beta
setCells(layer: string, cells: readonly number[] | AreaShape, value: number, options?: {
over?: number;
}): number[];Sets the cells of a cell layer, given as indices or an area, to a value 0..255, and returns the cells that changed. over: the seconds the screens that see them ease into the value over (grass growing back), told with the cells; a screen told of them later, as they come into its sight, eases in as it can
setEnvironment
setEnvironment(change: Partial<MapEnvironment>, options?: {
over?: number;
}): void;Changes what the map looks like beyond its ground, as the game goes: a storm rolling in (weather), night mist (fog), the sky going red. Over what it was, field by field; a field given as undefined goes back to none. Every player sees it (an environment event), a save keeps it, and a player who joins later is told it as it is.
over (seconds) has the screens ease into it, from what they show: the rain comes on, the wind gets up, the mist thickens. The world has the new look at once: a save or a player who joins sees it as it ends
setHidden beta
setHidden(entity: Entity, hidden: boolean, at?: Vec2): void;Takes a unit out of the world for a while, or puts it back: a worker inside a gold mine, a unit carried in something. While hidden it is not found, not seen and in nobody's way, and its orders wait. It comes back at at, or where it went in, on the nearest ground it can stand on. Structures cannot hide
setLifetime beta
setLifetime(entity: Entity, seconds: number | null): void;Gives an entity a time after which it is gone by itself, like a ward, or takes it away with null
setName beta
setName(entity: Entity, name: string | undefined): void;Names an entity, for the rules to find it by (named), or takes its name away with none. It has one name, and a name is one entity's: taking that of another that still lives throws. The name of the dead is free
setOwner
setOwner(entity: Entity, owner: PlayerId): void;Gives an entity to another player, from now on in everything: whose it is, whom it fights, what it counts for. What it was doing is called off, and what it was making is given back to the one it belonged to
setState
setState<T>(key: Component<T, unknown>, value: T): void;Sets the whole game's state for a component, replacing what state gives for it
settings
get settings(): Readonly<RuleSettings>;The game's numbers that are not about any one unit, like the supply cap (Rules.settings)
setTunable beta
setTunable(id: string, value: number): void;Tunes a number of the rules, within its bounds, and says so (tunableChanged)
sidePaths beta
readonly sidePaths?: SidePaths;The navigations the sides plan their routes on, of the buildings each knows (Rules.paths: 'seen'): routes of ground units are planned on their side's, and walked on nav. None where routes know everything
sides beta
readonly sides: Sides;Who is on whose side (Sides): teams, relations, shared vision and control
sight beta
readonly sight: Sight;What each team sees of the entities (Sight): the fog, what is invisible, the game's say
spatial beta
readonly spatial: SpatialIndex;Index of entities by position, for asking what is near a point.
Units are filed once a tick, where they stand as it starts (after the commands, before the systems: step). A unit that moves during the tick (the move phase) is still filed where it was until the next, so a query in resolve searches by where units started and checks distance against where they are now: a unit that walked into range this tick may be found only the next. Structures are filed where they stand, as they are made
spawn
spawn(typeId: string, options: SpawnAt): Entity;Puts a new entity of the unit type typeId into the world for owner at at, and returns it: world.spawn('footman', { at: { x: 10, z: 12 }, owner: 1 }), with the rest of what it may start with (SpawnOptions: facing, name, lifetime, data…) beside them
spawn
spawn(typeId: string, owner: PlayerId, position: Vec2, options?: SpawnOptions): Entity;Puts a new entity of the unit type typeId into the world for owner at position, and returns it
spawning beta
readonly spawning: Spawning;How entities come into the world and are moved about in it (Spawning)
spawnPrefab beta
spawnPrefab(prefab: PrefabDef | string, options: SpawnPrefabOptions): SpawnedPrefab;A prefab put down as one: its objects spawned for the owner given, its camps and areas with them, turned and sized around its middle (spawnPrefab)
state
state<T>(key: Component<T, unknown>): T;State of a game module or a mod for the whole game: made from the component's default when first asked for
states beta
readonly states: StateStore;State of game modules and mods for the whole game, see state
statsVersion beta
statsVersion: number;Moved on by invalidateStats without an entity: every entity's stats are added up again when next asked for
step
step(): void;Steps the world one tick; does nothing once the game failed. In this order:
- The commands sent since the last tick are carried out. 2. Units are filed by where they stand (
spatial). 3. The systems run, phase by phase (commands,decide,move,resolve,cleanup). 4. The dead are taken out of the world (removehook,entityRemoved). 5.tickgoes up by one. 6. The tick's events go out to listeners (world.events.on), held until now.
So a listener runs after the tick is over: world.tick is already the next one, and an entity that died this tick is no longer in world.entities (the event still carries it; a fallen hero waiting to be brought back stays). Hooks run at once, inside the tick, where what they are asked about happens
stopFx beta
stopFx(id: number, options?: {
fade?: number;
}): void;Stops an fx the rules played (fx) on every screen, as its own stop says, over fade seconds
systems beta
get systems(): readonly System[];The systems, in the order they run
terrain beta
readonly terrain: Terrain;The ground the world stands on
tick
tick: number;The tick number the world is at, from 0; it goes up by one for each step
tickRate
readonly tickRate: number;Simulation ticks per second
time
get time(): number;Seconds of game time that have passed: tick times dt
timers
readonly timers: Timers;What is set to go off later: world.timers.after(30, waveComes)
trace beta
trace: Trace | null;What the debug tools follow of the rules as they run: hooks and listeners. Null when nobody asks, see EventLog
tunable beta
tunable(id: string): number;A number of the rules as it is tuned now (TunableDef): what it was set to while playing, or its default
units
readonly units: Map<number, Entity>;The entities that act: the ones that move, fight, build or change by themselves, which is everything but scenery. Systems that run every tick go through these instead of entities, which on a big map is mostly trees.
In the order each became a unit, which is the order of ids except for scenery woken later (Spawning.wake: a tree given a buff), which comes last, after units made before it. A save keeps this order, so a loaded world walks it the same. A component's index (EntityIndex, SystemDef.over) walks in id order instead, so code that picks the first of equals breaks the tie by id, not by which it met first, to stay the same either way
wake beta
wake(entity: Entity): void;Turns scenery into an actor, for good: something gave it a reason to be looked at every tick, like a buff that has to run out. Whatever does that to an entity calls this; the debug checks catch what forgets to.
watch beta
watch(watcher: WorldWatcher): () => void;Watches the world from outside, for what records it (a replay of commands, recordGame): each command a player gives it, each save taken of it, each tick. Changes nothing. Gives what stops watching
winner
winner: number | null;Team that won, once the game is decided
zones beta
readonly zones: Zone[];The zones that are working on the ground now