multiplayer
Multiplayer sync state and operations — connection, peers, ownership, rooms, undo/redo.
require("@builtin::modules.api.engine.multiplayer") -- multiplayer (also available as global 'multiplayer')
The multiplayer namespace: 112 functions.
globals/multiplayer/avatarEmote
multiplayer.avatarEmote(entityId: (string | entityRef), id: number, startAt: number?) -> number
Play an emote on an avatar this peer owns: id (an integer 0 to
65535 the avatar's animator names) starting at the session time
startAt (sessionTime() seconds; now when left out). It rides every
frame of the avatar's channel for half a second, so a lost datagram
does not lose it, and every peer lists it in avatarState(e).emotes
with that start time, so each plays it in phase
(sessionTime() - startedAt is how far in it is).
Parameters
entityId(string | entityRef)— An avatar on the channel.idnumber— The emote, 0 to 65535.startAtnumber(optional) — The session time it starts at; now when left out.
Returns number — The session time the emote starts at, in seconds.
local startedAt = multiplayer.avatarEmote(self.entity, 3)
globals/multiplayer/avatarState
multiplayer.avatarState(entityId: (string | entityRef)) -> AvatarReading?
Read an avatar on the channel as this peer last drew or sent it, or
nil for an entity with no channel open or nothing drawn or sent yet.
owned is true on the peer that owns and states it. moment is the
session time drawn (a frame's stamp on the owner); velocity (m/s),
gait and grounded are the locomotion at that moment; parameters
the declared parameters by name as every peer reads them;
parametersAt the session time each of those took its value, the stamp
of the first frame that carried it, which every peer that took that frame
reads alike (on the owner, the frame it went out in); targets the
IK targets by name in the root's frame; emotes those started within
the last 10 s as { id, startedAt } in the order they arrived; view
the direction the owner's viewer looks. traffic counts what this peer
sent (owned) or received (remote) of the avatar: frames and bytes a
second over the last 2 s and running totals. On a receiver stream
holds the frames received, those reordered on the way, parameter
blocks packed under another declaration than this peer's
(layoutMismatches, each unread), the interarrival jitterMs and the
frames buffered. The root pose is the entity's own transform;
smoothing(entityId).stream says how it is drawn.
Parameters
entityId(string | entityRef)— An avatar on the channel.
Returns AvatarReading? — The avatar as last drawn or sent, or nil.
local a = multiplayer.avatarState(other); if a then print(a.gait, a.parameters.Smile) end
globals/multiplayer/beginOperation
multiplayer.beginOperation(description: string)
Begin recording an undoable operation. All mutations until
commitOperation() are grouped into one undo entry.
Parameters
descriptionstring— Human-readable label.
multiplayer.beginOperation("move cube")
globals/multiplayer/canRedo
multiplayer.canRedo() -> boolean
Check if this client has any redoable operations.
Returns boolean — True if redo is available.
globals/multiplayer/canUndo
multiplayer.canUndo() -> boolean
Check if this client has any undoable operations.
Returns boolean — True if undo is available.
globals/multiplayer/cancelOperation
multiplayer.cancelOperation()
Cancel the current operation and restore all properties to their values at begin time.
multiplayer.cancelOperation()
globals/multiplayer/childPoseFromOwner
multiplayer.childPoseFromOwner(entityId: (string | entityRef)) -> boolean
Whether this peer drew the entity's local pose, on the last frame,
from what the peer that owns its parent states of it: a child
syncChildPose names under a synced entity another peer publishes. A
component that turns or moves a child on its own (a character's facing
derived from its motion) leaves a child this answers true for to its
owner. False on the peer that owns the parent, offline, and for any
other entity.
Parameters
entityId(string | entityRef)— The child to ask about.
Returns boolean — True while the child is drawn from its owner.
if not multiplayer.childPoseFromOwner(turretId) then aimTurret() end
globals/multiplayer/claimOwnership
multiplayer.claimOwnership(entityId: (string | entityRef)?) -> boolean
Request ownership of an entity. The relay grants a claim on
an entity no peer owns (never claimed, or released by its owner)
and tells every peer; an entity another peer owns stays theirs, and
the refusal is counted in getDiagnostics().refusals and named by
lastRefusal. The owner hands an entity on by releasing it.
Parameters
entityId(string | entityRef)(optional) — Entity id or proxy to claim.
Returns boolean — True once the claim is on its way to the relay.
globals/multiplayer/clearHistory
multiplayer.clearHistory()
Drop this client's whole undo/redo history — for boundaries where old edits stop being meaningful (a scene load, a test rig reset).
multiplayer.clearHistory()
globals/multiplayer/commitOperation
multiplayer.commitOperation()
Finalize the current operation and push it onto the undo stack. Only changes that actually differ from the start state are recorded.
multiplayer.commitOperation()
globals/multiplayer/connect
multiplayer.connect(relayUrl: string)
Connect to a multiplayer relay server for the current world.
Uses the loaded world's world_id as the room prefix for scene
isolation. A world must be loaded before connecting.
Parameters
relayUrlstring— Relay server URL.
multiplayer.connect("https://relay.example.com")
globals/multiplayer/disconnect
multiplayer.disconnect()
Disconnect from the multiplayer relay server.
multiplayer.disconnect()
globals/multiplayer/explain
multiplayer.explain(entityId: (string | entityRef), componentType: string, property: string) -> DeliveryVerdict
Why a synced property is not reaching the peers this client shares its entity's room with. Answers from the engine's own registry, so a name the component never registered is reported as such instead of inferred from a second client's silence.
Parameters
entityId(string | entityRef)— Entity id or proxy.componentTypestring— Component type name, e.g. "Health".propertystring— Property name as written in the component'ssync {}block.
Returns DeliveryVerdict — arriving true when the property is on its way; otherwise reason names the cause and property carries the registry's record of it when one exists.
local v = multiplayer.explain(player, "Health", "hp")
if not v.arriving then print(v.reason) end
globals/multiplayer/getDiagnostics
multiplayer.getDiagnostics() -> SyncDiagnostics
Get sync diagnostics — traffic counts, bandwidth, link quality,
peer count. The counts — bytesSent/Received,
datagramsSent/Received, rpcsSent/Received, ownershipChanges,
refusals — are running totals for the session, so a sparse event
stays readable long after it happened; subtract two samples for the
rate over the interval between them. refusals counts the messages
of this session's the relay refused (a claim on an entity another
peer owns, a change to one, a room outside the world the connection
was admitted to), and lastRefusal names the latest in the relay's
words once there is one. bytesSentPerSec / bytesReceivedPerSec are
averages over the last completed ~1 second window.
rttMs is the smoothed round-trip time to the relay and
packetLoss the fraction (0..1) of packets lost over the last 5
seconds; both read 0 until the transport has sampled a live
connection. messagesAwaitingEntity counts the sync messages this
peer is holding for an entity it has not received yet — each waits
for the spawn that names it, applies the moment it arrives, and is
released once its wait runs out. reliableInFlight counts the
reliable messages this peer has sent that the relay has not yet taken:
it reads near 0 while the link keeps up with what this peer sends, and
a count that grows names a link carrying less than that, every
reliable change sent behind it (a Sync field, a spawn) waiting with it.
Returns SyncDiagnostics — Diagnostics table.
local d = multiplayer.getDiagnostics()
if d.packetLoss > 0.05 then log.warn(("unstable connection, %d ms round trip"):format(d.rttMs)) end
print(d.messagesAwaitingEntity .. " message(s) waiting for their entity")
globals/multiplayer/getPeerId
multiplayer.getPeerId() -> number?
Get the peer ID the relay issued this client's connection.
Returns number? — Local peer ID, or nil exactly when isConnected() is false: while dialing, before the relay names the connection, and after it drops.
globals/multiplayer/getPeers
multiplayer.getPeers() -> { PeerInfo }
Get a list of all connected peers in the current session.
Returns { PeerInfo } — Array of peer info tables.
for _, p in ipairs(multiplayer.getPeers()) do print(p.name) end
globals/multiplayer/getRoomPeers
multiplayer.getRoomPeers(roomKey: string) -> { PeerInfo }
Get the peers this client shares the given room with, ordered by
peer id. getPeers answers for the whole session — the union of every
room this client is in — while this answers for one room, so a peer
that leaves this room while staying in another disappears from here
and remains in getPeers.
Parameters
roomKeystring— Fully-qualified room key ({worldGuid}/{profile}/{branch}/{mode}/{sceneGuid}).
Returns { PeerInfo } — Array of peer info tables for that room.
for _, p in ipairs(multiplayer.getRoomPeers(key)) do print(p.id) end
globals/multiplayer/getRooms
multiplayer.getRooms() -> { string }
The relay rooms this client has joined, sorted. A broadcast reaches
only the peers that share one of these. They are the rooms of
observe() as of the last frame, read from the rooms the session
publishes every frame, so a component can ask every frame.
Returns { string } — Room keys.
for _, key in ipairs(multiplayer.getRooms()) do print(key) end
globals/multiplayer/getTickRate
multiplayer.getTickRate() -> number
Get the current sync tick rate (network updates per second).
Returns number — Sync ticks per second (default 20).
globals/multiplayer/heldMessages
multiplayer.heldMessages() -> { HeldMessage }
The sync messages this peer is holding for entities it has not
received — what getDiagnostics().messagesAwaitingEntity counts, one
entry each, with the entity sync id it names, its age and the grace it
is held against.
Returns { HeldMessage } — Held messages.
for _, m in ipairs(multiplayer.heldMessages()) do print(m.kind, m.ageMs) end
globals/multiplayer/holdRoom
multiplayer.holdRoom(scene: string, held: boolean)
Keep this client in the relay room of a scene while its layer unloads and loads again, as a rebuild in place does. A held room is left only once it is released and its scene is no longer loaded.
Parameters
scenestring— The scene guid.heldboolean— True to hold the room, false to release it.
multiplayer.holdRoom(layers.active.guid, true)
globals/multiplayer/isConnected
multiplayer.isConnected() -> boolean
Check if a multiplayer session is connected to a relay and the
relay has named this client. True exactly when getPeerId() answers
an id.
Returns boolean — True if connected under the peer id the relay issued.
globals/multiplayer/isHost
multiplayer.isHost() -> boolean
Whether THIS client is the host (authoritative owner) of the
current scene's play room — the relay room CREATOR, or offline /
single-player. Host code spawns the shared synced world (via
entity.spawnSynced or a scene's onHostLoad) and runs authoritative
simulation; a non-host (JOINER) receives that content from the relay
snapshot and must NOT re-create it. Gate ANY code that spawns synced
entities or owns shared state with this so it runs on exactly one
client — running it on every peer is the double-spawn 'explosion'.
Returns boolean — True on the host / offline / single-player; false on a confirmed joiner. Defaults to true when the role isn't known yet (degrade to host so single-player and pre-join code still run) — pair with a scene's onHostLoad hook when exact one-shot timing matters.
if multiplayer.isHost() then enemy = entity.spawnSynced("enemy") end
globals/multiplayer/isOperationOpen
multiplayer.isOperationOpen() -> boolean
Whether an operation is open: true between beginOperation and
its commitOperation or cancelOperation. A caller that records file
writes reads the file's prior contents only while one is open.
Returns boolean — True while an operation is open.
if multiplayer.isOperationOpen() then before = vfs.read(p) end
globals/multiplayer/isOwner
multiplayer.isOwner(entityId: (string | entityRef)?) -> boolean
Check if the local client owns the given entity (or the current entity if called from a component). Only the owner can modify synced properties directly.
Parameters
entityId(string | entityRef)(optional) — Entity id or proxy to check (defaults toself.entityIdin component context).
Returns boolean — True if the local client is the owner.
globals/multiplayer/isRoomCreator
multiplayer.isRoomCreator(roomKey: string) -> boolean?
Whether this client created the given room — it was the FIRST peer to join it (race-free; the relay assigns it on join). In play mode the creator instantiates the scene's entities (synced) and every other joiner receives them from the relay snapshot, so the scene is never double-instantiated.
Parameters
roomKeystring— Fully-qualified room key ({worldGuid}/{profile}/{branch}/{mode}/{sceneGuid}).
Returns boolean? — True if this client created the room, false if it joined an existing one, nil if the relay hasn't reported a role yet (offline / not joined).
if multiplayer.isRoomCreator(key) ~= false then layers.load(scene) end
globals/multiplayer/joinRoom
multiplayer.joinRoom(roomKey: string)
Join a relay room. Room keys are built as
{worldGuid}/{profile}/{branch}/{mode}/{sceneGuid} — five segments, the
{profile} one keeping a runtime peer (published content) and an
editor peer (live content) in separate rooms even when both are in
play mode. Rooms partition the relay's fan-out: only peers in the
same room receive each other's broadcasts. getRooms() reports the
keys this client is already in and roomFor(entity) the one an
entity broadcasts into, so a key can be read rather than rebuilt.
A relay that verifies its peers holds each connection to the world
it was admitted to: a key whose first segment names another world
is refused, and getDiagnostics().refusals counts the refusal and
lastRefusal names it. No-op when not connected or already joined.
Parameters
roomKeystring— Fully-qualified room key.
multiplayer.joinRoom(multiplayer.roomKeyFor(sceneGuid, "play"))
globals/multiplayer/leaveRoom
multiplayer.leaveRoom(roomKey: string)
Leave a relay room. The key is reported under
observe().withdrawnRooms until joinRoom names it again. No-op
when not connected or not joined.
Parameters
roomKeystring— Fully-qualified room key.
globals/multiplayer/loopback
multiplayer.loopback() -> { [string]: any }
Loopback testing harness. Returns a table with enable(),
disable(), flush(), receive() methods for testing sync
without a relay server.
Returns { [string]: any } — Loopback API table.
globals/multiplayer/observe
multiplayer.observe() -> ReplicationObservation
Report what this peer is replicating and why a property is not
arriving. Carries the rooms this client joined, one record per entity
with a sync id — its owner, the room it broadcasts into, how many
other peers share that room, and every REGISTERED synced component
with its declared property names, wire indices, public/private table
and dirty bits — the messages held for entities that have not arrived,
and the registry's totals. Every property carries notArriving: one
name from reasons, or nil when it is on its way. Answers in edit
mode as well as play mode, for what the relay carries in each: in
edit mode scene content is left out of the sync-id pass, so its
changes travel to the other clients with the source they are
written into and it reads entityNotSynced here. The document
describes the session as of the last frame: when no frame has
assembled one since the surface was last read, the call waits for the
next frame to assemble it, and a caller that cannot yield receives the
one published last.
Returns ReplicationObservation — The engine's current replication observation.
local o = multiplayer.observe()
print(#o.entities .. " entities, " .. o.totals.properties .. " synced properties")
globals/multiplayer/observeComponent
multiplayer.observeComponent(entityId: (string | entityRef), componentType: string) -> SyncedComponent?
The registered synced component of the named type on an entity's
record. Matches a fully-qualified type (@builtin::components.Model)
and the leaf name it ends in (Model) alike.
Parameters
entityId(string | entityRef)— Entity id or proxy.componentTypestring— Component type name or its leaf.
Returns SyncedComponent? — The registered component instance, or nil when none of that type is registered on the entity.
local c = multiplayer.observeComponent(player, "Health")
print(#c.properties .. " declared properties")
globals/multiplayer/observeEntity
multiplayer.observeEntity(entityId: (string | entityRef)) -> EntityReplication?
The replication record for one entity — its sync id, owner, room, and the synced components registered on it.
Parameters
entityId(string | entityRef)— Entity id or proxy.
Returns EntityReplication? — The entity's record, or nil when the engine holds no sync record for it.
local r = multiplayer.observeEntity(e)
for _, c in ipairs(r.components) do print(c.componentType) end
globals/multiplayer/on
multiplayer.on(channel: string, callback: (number, ...any) -> ())
Subscribe to a custom message channel. The callback runs as
callback(fromPeerId, ...args) whenever another peer calls
multiplayer.send(channel, ...). Multiple callbacks per channel fire
in registration order.
Parameters
channelstring— Channel name to listen on.callback(number, ...any) -> ()—function(fromPeerId: number, ...)— the sender's peer id then the sent args.
globals/multiplayer/poseFrame
multiplayer.poseFrame(entityId: (string | entityRef)) -> string?
The entity a synced entity's pose is stated relative to: on the peer
that publishes it, the frame setPoseFrame named; on every other peer,
the frame entity it was drawn in on the last frame, the one its owner
stated its pose in. Nil for an entity stated in the world.
Parameters
entityId(string | entityRef)— The entity to ask about.
Returns string? — The frame entity's id, or nil.
if multiplayer.poseFrame(player) == deck.id then print("riding the deck") end
globals/multiplayer/recordFileWrite
multiplayer.recordFileWrite(path: string, before: string?, after: string?) -> boolean
Record a file write into the open operation. Undoing the
operation writes before back through the VFS (removing the file when
before is nil), which runs the owning asset type's onChange as the
original write did; redoing writes after. The path is resolved and held
to the rules vfs.write applies, so a sidecar (.meta, .refs), an
install's own entry or an asset root no script may write raises. A step's files
are put back all together or not at all: each file is checked (its asset
exists, and it holds what the step being reversed left in it) before any
is written and again immediately before it is written; when a check or a
write fails partway, the files the step already wrote go back to what
they held, and a notice names each file of the step and what happened to
it. Several writes of one path in an
operation undo to the first before. Records nothing and returns false
when no operation is open.
Parameters
pathstring— VFS path of the written file.beforestring(optional) — The file's contents before the write, nil when it did not exist.afterstring(optional) — The file's contents after the write, nil when the write removed it.
Returns boolean — True when the write was recorded.
local before = vfs.read(p); vfs.write(p, body); multiplayer.recordFileWrite(p, before, body)
globals/multiplayer/recordSpawn
multiplayer.recordSpawn(entityId: string)
Adopt an existing entity into the open operation as its spawn — for flows that create an entity before the operation opens (a drag preview adopted on drop). Undoing the operation despawns it.
Parameters
entityIdstring— Entity id to record as spawned by this operation.
multiplayer.recordSpawn(id)
globals/multiplayer/redo
multiplayer.redo() -> boolean
Redo this client's last undone operation.
Returns boolean — True if an operation was redone.
globals/multiplayer/releaseOwnership
multiplayer.releaseOwnership(entityId: (string | entityRef)?) -> boolean
Release ownership of an entity, leaving it unowned so another peer's claim takes it. Only the owner releases an entity.
Parameters
entityId(string | entityRef)(optional) — Entity id or proxy to release.
Returns boolean — True if ownership was released.
globals/multiplayer/roomFor
multiplayer.roomFor(entityId: (string | entityRef)) -> string?
The room key an entity's spawns and property deltas broadcast into:
the room of its observeEntity record as of the last frame, read from
the rooms the session publishes every frame, so a component can ask
every frame.
Parameters
entityId(string | entityRef)— Entity id or proxy.
Returns string? — The room key, or nil when the engine has established no scene context for the entity.
local key = multiplayer.roomFor(player)
if key then multiplayer.joinRoom(key) end
globals/multiplayer/roomHeld
multiplayer.roomHeld(scene: string) -> boolean
Whether the room of a scene is held.
Parameters
scenestring— The scene guid.
Returns boolean — True while holdRoom holds it.
local held = multiplayer.roomHeld(layers.active.guid)
globals/multiplayer/roomKey
multiplayer.roomKey() -> string?
The relay room key of the root scene in the engine's current mode:
the room this client's entities for that scene broadcast into. nil
while no root scene is loaded.
Returns string? — The room key, or nil.
print(multiplayer.roomKey())
globals/multiplayer/roomKeyFor
multiplayer.roomKeyFor(sceneGuid: string, mode: string?) -> string
The relay room key of a scene in a mode: {worldGuid}/{profile}/{branch}/{mode}/{sceneGuid},
built the way the engine keys every room, so two clients on different
branches are in different rooms. The branch segment spells % as %25
and / as %2F.
Parameters
sceneGuidstring— The scene's guid.modestring(optional) —"edit"or"play"; the engine's current mode when omitted.
Returns string — The room key.
local key = multiplayer.roomKeyFor(layers.active.guid, "play")
globals/multiplayer/roomStartedAt
multiplayer.roomStartedAt(roomKey: string) -> number?
When the given room began, in seconds on this engine's clock (the
clock time.time() reads): the moment its first peer joined, as the relay
states it on this client's join, less half the link's round trip. Every
client of the room reads the same moment on its own clock. A room that
empties and is joined again begins again.
Parameters
roomKeystring— Fully-qualified room key ({worldGuid}/{profile}/{branch}/{mode}/{sceneGuid}).
Returns number? — The room's start in seconds, or nil while the relay has stated none (offline, not joined, or a relay that states no start).
local started = multiplayer.roomStartedAt(multiplayer.roomKey() or "")
globals/multiplayer/roomTime
multiplayer.roomTime() -> number
Seconds since the current room began, the same on every client of the
session. The clock follows the room of the root scene in the current mode
(multiplayer.roomKey()): it begins when the room's first peer joins and
begins again when the room empties and is joined again, and play and edit
are different rooms. Offline, in a world with no relay, with a relay that
states no start, or before this client's join is answered, it counts from
this engine's own start, recorded the first time it is read; once the
room's start arrives it counts from that. It runs in real seconds:
engine.paused and time.timeScale() do not reach it, so a reader that
holds still while paused keeps its own value while paused. Anything that
must agree across clients without sending a value every frame reads it: a
day cycle, a wind, a schedule.
Returns number — Seconds since the current room began.
local hour = (start + multiplayer.roomTime() * speed / 3600) % 24
globals/multiplayer/send
multiplayer.send(channel: string, ...: any?)
Broadcast a message on a named channel to every OTHER peer in the
room. The relay forwards it without reading its arguments and names this
peer as its sender; peers receive it via multiplayer.on. The relay holds
every peer to a message rate, a byte rate and a longest message: a message
past them reaches no peer, and multiplayer.getDiagnostics().refusals
counts the relay's answer. The arguments are delivered to listeners in order,
each one arriving as what it is, at the top level and at every depth
of a table:
nil, a boolean, a number and a string arrive as themselves.- A
vectorarrives as avector. - The proxy of a synced entity arrives as the receiving peer's proxy for that entity; the proxy of an entity no peer shares, as its id string.
- A synced component (its proxy, or the
componentRefenvelope naming it) arrives as that component on the receiving peer; the proxy of a component that holds no sync id, as the envelope{ __ref, entity, componentType }naming it. - A transform vector an entity hands out (
e.position,e.rotation,e.localScale, ...) arrives as the table of its components,{ x, y, z }or{ x, y, z, w }. - Every other table is data and arrives as a new table holding the same
keys, each key and each value carried by these same rules:
{ x = 5, kind = "coin" }arrives as{ x = 5, kind = "coin" },{ who = e, n = 1 }witht.whothe receiver's proxy fore,{ [5] = "a" }witht[5] == "a",{ 1, 2, label = "m" }with its list and itslabel,{ [true] = "yes" }witht[true] == "yes", and a list with anilin it with every entry after thenilat the index it was written under. A number inside a table arrives as that number,math.hugeand NaN included. - A value no peer can hold (a function, a thread, a buffer) arrives as
nil, and so does a table entry whose key is one; the sender logs a
warning naming the key's type.
The same rules carry the arguments of a
declare.syncedFunctionsmethod, the payload of aSyncevent and a synced table-valued field. No-op when not connected.
Parameters
channelstring— Channel name listeners subscribe to viamultiplayer.on....any(optional) — Zero or more values delivered to each listener after the sender's peer id.
globals/multiplayer/sessionClock
multiplayer.sessionClock() -> SessionClock
Read the session clock with what is known about it. time is
sessionTime(). synced is true once the relay has answered a clock
request, and stays true across a re-dial or a world swap while the clock
keeps counting this machine's clock. accuracyMs bounds how far time
lies from the relay's clock: half the round trip of the answer it
follows, the drift of this machine's clock since (0.1 ms a second) and
any correction still being worked off; nil while unsynced. Two peers
agree to within the sum of their accuracyMs. rttMs is that answer's
round trip and sampleAgeMs how long ago it arrived. wallOffsetMs is
time less this machine's wall clock: how far this machine's clock is
set from the session's.
Returns SessionClock — The session time and its accuracy.
local c = multiplayer.sessionClock(); if c.synced then print(c.accuracyMs) end
globals/multiplayer/sessionTime
multiplayer.sessionTime() -> number
The session time, in seconds since the Unix epoch: one timeline every
participant of a multiplayer session reads alike, placed on the relay's
clock with the round trip to it taken out. Use it wherever peers must act
in step (a shared countdown, a synchronised emote or animation, a high
five both sides start together, a looping effect in phase, a day/night
cycle, a beat): share a start time a little in the future (a Sync field,
an event or multiplayer.send) and let every peer compute
multiplayer.sessionTime() - start. It reads the moment it is called,
never decreases once synced, and corrects itself by running up to 10%
fast or slow rather than jumping (it jumps forward only when it trails
by more than a quarter second). Before the relay first answers, and with
no relay, it reads this machine's own wall clock; sessionClock() says
which and how accurate the reading is. ClipPlayer.startedAt takes such
a time to play a clip in phase on every peer.
Returns number — Seconds since the Unix epoch on the session timeline.
local startAt = multiplayer.sessionTime() + 0.5 -- share it, then on every peer:
local elapsed = multiplayer.sessionTime() - startAt
globals/multiplayer/setAvatarChannel
multiplayer.setAvatarChannel(entityId: (string | entityRef), channel: AvatarChannel?) -> boolean
Put a synced avatar on the avatar channel: the compact datagram
stream an avatar's motion and state travel on in place of generic
transform deltas. A frame is about 40 bytes, sent 20 times a second
while the avatar moves or changes (a walking avatar with changing
parameters costs under 1 KB/s) and once a second while it stands. Every
peer calls it for the avatar with the same channel (an avatar
component's start does). The peer that owns the avatar states it: its
root from the entity's transform, the velocity measured from it, and
what setAvatarState and avatarEmote state. Every other peer draws
it on the session clock, the root a short delay behind the newest frame
and interpolated through jitter and lost datagrams (smoothing tunes
it), and reads the rest with avatarState.
parameters declares the avatar's parameters in order, each
{ name, type } with type "bool" (1 bit), "int" (0 to 255) or
"float" (-1 to 1, 8 bits each), 256 bits in all at most; a peer reads a
parameter block only under the same declaration. rate (1 to 30,
default 20), parameterRate (at most 10, the default) and targetRate
(at most rate) say how many times a second it states the avatar,
changed parameters and changed IK targets. The relay takes the frames
from the avatar's owner alone, and forwards a peer every frame while
the avatar is within 10 m of an avatar that peer states (its own, or
any other it owns), about 10 a second further away inside its view and
about 2 a second behind it; a frame carrying a parameter block or an
emote a peer does not hold yet goes to that peer at once. nil closes
the channel and the entity goes back to generic transform sync.
Parameters
entityId(string | entityRef)— The avatar's synced root entity.channelAvatarChannel(optional) — The declared parameters and rates; nil closes the channel.
Returns boolean — False, opening nothing, for an entity that is not synced.
multiplayer.setAvatarChannel(self.entity, { parameters = {
{ name = "Smile", type = "float" }, { name = "Gesture", type = "int" },
{ name = "Seated", type = "bool" } } })
globals/multiplayer/setAvatarState
multiplayer.setAvatarState(entityId: (string | entityRef), state: AvatarStateInput) -> boolean
State what the avatar channel carries of an avatar this peer owns,
beside the root pose read from the entity's transform: any of gait
(the locomotion state the avatar's animator names, an integer 0 to
127), grounded, parameters (declared names to values: a boolean, an
integer 0 to 255 or a number -1 to 1 by declared type) and targets
(IK targets in the root's own frame by name: head, leftHand, rightHand,
hips, leftFoot, rightFoot; each { position, rotation? }, or false to
clear it). A field left out keeps its value. Call it whenever the state
changes: the channel sends a change at its rate and coalesces parameter
changes to its parameterRate. Raises for an entity with no channel
open, an undeclared parameter or a value of the wrong type, naming it.
Parameters
entityId(string | entityRef)— An avatar on the channel.stateAvatarStateInput— What to state.
Returns boolean — True once stated.
multiplayer.setAvatarState(self.entity, { gait = 1, grounded = true, parameters = { Smile = 0.6 } })
globals/multiplayer/setNeedsRebuild
multiplayer.setNeedsRebuild(scene: string, reason: string?, sinceMs: number?)
State the scene rebuild this client owes, for clients.<id>.content.needsRebuild
in the engine state. Called with only a scene it states that scene owes
none. Every client rebuilds from its own marks, so each states its own.
Parameters
scenestring— The scene guid.reasonstring(optional) — What changed.sinceMsnumber(optional) — When the change arrived, in milliseconds since the Unix epoch.
multiplayer.setNeedsRebuild(layers.active.guid, "PlayerSpawn moved", os.time() * 1000)
globals/multiplayer/setPoseFrame
multiplayer.setPoseFrame(entityId: (string | entityRef), frameEntityId: (string | entityRef)?) -> boolean
State a synced entity's pose relative to another synced entity it
rides (a character on a moving deck, a passenger in a car, a crate on a
ship), or in the world again with no frame. The peer that publishes the
entity states where it stands in the frame entity's space and how it is
turned there, and every other peer draws it where that peer draws the
frame entity, so the rider moves in step with the body it rides on
every screen however far behind each owner a peer draws the two. The
frame is the nearest synced entity at or above the one named (a
collider on a child of a synced ship names the ship). An entity whose
frame is not a synced entity in the world, or is the entity itself or
under it, is stated in the world. The name lasts until it is changed or
the entity leaves the world. A CharacterController names the moving
body it stands on by itself.
Parameters
entityId(string | entityRef)— The synced entity whose pose is stated.frameEntityId(string | entityRef)(optional) — The entity it rides; nil states it in the world.
Returns boolean — False, naming nothing, for an entity named as its own frame.
multiplayer.setPoseFrame(crate, ship)
multiplayer.setPoseFrame(crate, nil)
globals/multiplayer/setSmoothing
multiplayer.setSmoothing(entityId: (string | entityRef), values: SmoothingSettings?) -> boolean
Set how this peer draws one synced entity another peer simulates,
in place of the world's settings: any of enabled (false draws the
entity at the newest pose received), delay and extrapolation
(seconds, 0 to 2) and teleportSpeed (metres per second). A value left
out is the world's, and nil or an empty table hands the entity back to
them. The setting is this peer's own and lasts while the entity exists.
delay = 0 draws the newest pose delivered, which trails the owner by
the network transit; see smoothing for what is drawn and when.
smoothing(entityId) reads it back.
Parameters
entityId(string | entityRef)— Synced entity to set.valuesSmoothingSettings(optional) — The values to use for this entity; nil hands it back to the world's.
Returns boolean — False, setting nothing, for an entity that is not synced.
multiplayer.setSmoothing(projectile, { delay = 0.05, teleportSpeed = 600 })
multiplayer.setSmoothing(car, nil) -- back to the world's settings
globals/multiplayer/smoothing
multiplayer.smoothing(entityId: (string | entityRef)?) -> Smoothing
How this peer draws the remote entities other peers simulate. A
body another peer simulates is drawn a short delay behind the newest
pose received for it, interpolated between the poses either side of
that moment, so it moves smoothly whatever the frame rate on either
side and the jitter between them, and a pose that arrives after a newer
one never moves it back. When poses stop arriving it carries on along
its last motion for up to extrapolation seconds, then holds. When
they arrive again it catches up with them rather than jumping: each
frame it moves up to a quarter more (or less) than they move, plus
1 m/s, or a frame's share of the distance left over one second when
that is more, so a gap is made up within a couple of seconds. A body
carried past its poses slows onto them, and steps back only when it
stands farther ahead of them than they move in a second or they move
slower than 4/3 m/s. A distance
larger than teleportSpeed covers in a second is a cut. A step
faster than teleportSpeed (metres per second) is a teleport and is
drawn as a cut; a step across poses lost on the way, or across a stall
of the sender, is measured from the nearest point between where the
entity stood and where the motion before it carried it, so such a body
is caught up with. A stream whose sender
changes (an ownership
handover) starts over from its first pose. The owner's own view is
untouched. The moment drawn is the owner's now less the network transit
less delay; the transit stays in, so delay = 0 draws the newest pose
delivered and still trails the owner by it. A body that stops dead is
carried past its stop until the pose it rests at arrives, about 0.1 s
after it stops, when delay is shorter than that.
The settings come from the world's settings sync.interpolation
(boolean), sync.interpolation_delay, sync.extrapolation_limit
(seconds) and sync.teleport_speed, with this peer's setSmoothing
values for the entity in their place (overridden). For an entity
whose poses this peer receives, stream holds the poses buffered, how
far the newest stands ahead of the moment drawn (lag, seconds,
negative while extrapolating), whether the sender stamps its poses with
the session clock, the moment last drawn on the session clock and this
peer's clock it was drawn at (drawnAt), both in seconds so two reads
subtract into how far the drawn moment moved over how much time, how
far (correction, metres) the body is drawn from where its poses put
it while it catches up with them, and
the running counts of poses received, dropped as stale, stream
restarts and teleports. Reading asks the coming
frames to publish the streams, so the first read of one answers on the
next frame.
Parameters
entityId(string | entityRef)(optional) — Entity to read; omit for the world's settings.
Returns Smoothing — The settings in effect and, for a remote entity, its stream.
local s = multiplayer.smoothing(car); print(s.delay, s.stream and s.stream.lag)
settings.set("sync.interpolation_delay", "0.15") -- every remote entity, world-wide
globals/multiplayer/syncChildPose
multiplayer.syncChildPose(entityId: (string | entityRef), childName: string, on: boolean?) -> boolean
Name a direct child of a synced entity whose local pose (position
and rotation) travels with the entity. The peer that publishes the
entity states it whenever it changes, stamped on the session clock as
the entity's own pose is, and every other peer draws its own child of
that name there: a short delay behind the newest pose, interpolated on
the timeline the entity is drawn on (smoothing tunes both), so a
child turned at once is drawn turned within that delay and a peer that
joins later reads the pose it stands at. Every peer builds the entities
under a synced entity on its own, so each names the same children (a
component's start does), and a peer draws from its owner only the
children it names itself; an entity named before it is synced states
its children once it is. A child drawn this way reads true from
childPoseFromOwner, and what turns or moves it on its own leaves it
to its owner. A name lasts while the entity exists; on = false stops
naming it, and a child its owner stops naming is each peer's own to
pose again. Up to 16 children an entity, each name up to 64 bytes.
Parameters
entityId(string | entityRef)— The synced entity.childNamestring— The name of the direct child whose local pose travels.onboolean(optional) — false stops naming the child; true when left out.
Returns boolean — False, naming nothing, for an empty or longer name or a 17th child.
multiplayer.syncChildPose(self.entity, "turret")
globals/multiplayer/syncTotals
multiplayer.syncTotals() -> SyncTotals
What the sync registry holds across every entity: entities with a
registered synced component, component instances, declared properties,
declared functions, the component instances holding a dirty
property this tick, and the component instances whose ComponentAdd has
yet to go out (addsWaiting: queued for the next frame, or waiting for
their entity to be announced).
Returns SyncTotals — The registry totals.
print(multiplayer.syncTotals().properties .. " synced properties registered")
globals/multiplayer/undo
multiplayer.undo() -> boolean
Undo this client's last edit-mode operation.
Returns boolean — True if an operation was undone.
typed/builtin//modules/api/engine/multiplayer/multiplayer/avatarEmote
multiplayer.avatarEmote(entityId: (string | entityRef), id: number, startAt: number?) -> number
Play an emote on an avatar this peer owns: id (an integer 0 to
65535 the avatar's animator names) starting at the session time
startAt (sessionTime() seconds; now when left out). It rides every
frame of the avatar's channel for half a second, so a lost datagram
does not lose it, and every peer lists it in avatarState(e).emotes
with that start time, so each plays it in phase
(sessionTime() - startedAt is how far in it is).
Parameters
entityId(string | entityRef)— An avatar on the channel.idnumber— The emote, 0 to 65535.startAtnumber(optional) — The session time it starts at; now when left out.
Returns number — The session time the emote starts at, in seconds.
local startedAt = multiplayer.avatarEmote(self.entity, 3)
typed/builtin//modules/api/engine/multiplayer/multiplayer/avatarState
multiplayer.avatarState(entityId: (string | entityRef)) -> AvatarReading?
Read an avatar on the channel as this peer last drew or sent it, or
nil for an entity with no channel open or nothing drawn or sent yet.
owned is true on the peer that owns and states it. moment is the
session time drawn (a frame's stamp on the owner); velocity (m/s),
gait and grounded are the locomotion at that moment; parameters
the declared parameters by name as every peer reads them;
parametersAt the session time each of those took its value, the stamp
of the first frame that carried it, which every peer that took that frame
reads alike (on the owner, the frame it went out in); targets the
IK targets by name in the root's frame; emotes those started within
the last 10 s as { id, startedAt } in the order they arrived; view
the direction the owner's viewer looks. traffic counts what this peer
sent (owned) or received (remote) of the avatar: frames and bytes a
second over the last 2 s and running totals. On a receiver stream
holds the frames received, those reordered on the way, parameter
blocks packed under another declaration than this peer's
(layoutMismatches, each unread), the interarrival jitterMs and the
frames buffered. The root pose is the entity's own transform;
smoothing(entityId).stream says how it is drawn.
Parameters
entityId(string | entityRef)— An avatar on the channel.
Returns AvatarReading? — The avatar as last drawn or sent, or nil.
local a = multiplayer.avatarState(other); if a then print(a.gait, a.parameters.Smile) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/beginOperation
multiplayer.beginOperation(description: string)
Begin recording an undoable operation. All mutations until
commitOperation() are grouped into one undo entry.
Parameters
descriptionstring— Human-readable label.
multiplayer.beginOperation("move cube")
typed/builtin//modules/api/engine/multiplayer/multiplayer/canRedo
multiplayer.canRedo() -> boolean
Check if this client has any redoable operations.
Returns boolean — True if redo is available.
typed/builtin//modules/api/engine/multiplayer/multiplayer/canUndo
multiplayer.canUndo() -> boolean
Check if this client has any undoable operations.
Returns boolean — True if undo is available.
typed/builtin//modules/api/engine/multiplayer/multiplayer/cancelOperation
multiplayer.cancelOperation()
Cancel the current operation and restore all properties to their values at begin time.
multiplayer.cancelOperation()
typed/builtin//modules/api/engine/multiplayer/multiplayer/childPoseFromOwner
multiplayer.childPoseFromOwner(entityId: (string | entityRef)) -> boolean
Whether this peer drew the entity's local pose, on the last frame,
from what the peer that owns its parent states of it: a child
syncChildPose names under a synced entity another peer publishes. A
component that turns or moves a child on its own (a character's facing
derived from its motion) leaves a child this answers true for to its
owner. False on the peer that owns the parent, offline, and for any
other entity.
Parameters
entityId(string | entityRef)— The child to ask about.
Returns boolean — True while the child is drawn from its owner.
if not multiplayer.childPoseFromOwner(turretId) then aimTurret() end
typed/builtin//modules/api/engine/multiplayer/multiplayer/claimOwnership
multiplayer.claimOwnership(entityId: (string | entityRef)?) -> boolean
Request ownership of an entity. The relay grants a claim on
an entity no peer owns (never claimed, or released by its owner)
and tells every peer; an entity another peer owns stays theirs, and
the refusal is counted in getDiagnostics().refusals and named by
lastRefusal. The owner hands an entity on by releasing it.
Parameters
entityId(string | entityRef)(optional) — Entity id or proxy to claim.
Returns boolean — True once the claim is on its way to the relay.
typed/builtin//modules/api/engine/multiplayer/multiplayer/clearHistory
multiplayer.clearHistory()
Drop this client's whole undo/redo history — for boundaries where old edits stop being meaningful (a scene load, a test rig reset).
multiplayer.clearHistory()
typed/builtin//modules/api/engine/multiplayer/multiplayer/commitOperation
multiplayer.commitOperation()
Finalize the current operation and push it onto the undo stack. Only changes that actually differ from the start state are recorded.
multiplayer.commitOperation()
typed/builtin//modules/api/engine/multiplayer/multiplayer/connect
multiplayer.connect(relayUrl: string)
Connect to a multiplayer relay server for the current world.
Uses the loaded world's world_id as the room prefix for scene
isolation. A world must be loaded before connecting.
Parameters
relayUrlstring— Relay server URL.
multiplayer.connect("https://relay.example.com")
typed/builtin//modules/api/engine/multiplayer/multiplayer/disconnect
multiplayer.disconnect()
Disconnect from the multiplayer relay server.
multiplayer.disconnect()
typed/builtin//modules/api/engine/multiplayer/multiplayer/explain
multiplayer.explain(entityId: (string | entityRef), componentType: string, property: string) -> DeliveryVerdict
Why a synced property is not reaching the peers this client shares its entity's room with. Answers from the engine's own registry, so a name the component never registered is reported as such instead of inferred from a second client's silence.
Parameters
entityId(string | entityRef)— Entity id or proxy.componentTypestring— Component type name, e.g. "Health".propertystring— Property name as written in the component'ssync {}block.
Returns DeliveryVerdict — arriving true when the property is on its way; otherwise reason names the cause and property carries the registry's record of it when one exists.
local v = multiplayer.explain(player, "Health", "hp")
if not v.arriving then print(v.reason) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/getDiagnostics
multiplayer.getDiagnostics() -> SyncDiagnostics
Get sync diagnostics — traffic counts, bandwidth, link quality,
peer count. The counts — bytesSent/Received,
datagramsSent/Received, rpcsSent/Received, ownershipChanges,
refusals — are running totals for the session, so a sparse event
stays readable long after it happened; subtract two samples for the
rate over the interval between them. refusals counts the messages
of this session's the relay refused (a claim on an entity another
peer owns, a change to one, a room outside the world the connection
was admitted to), and lastRefusal names the latest in the relay's
words once there is one. bytesSentPerSec / bytesReceivedPerSec are
averages over the last completed ~1 second window.
rttMs is the smoothed round-trip time to the relay and
packetLoss the fraction (0..1) of packets lost over the last 5
seconds; both read 0 until the transport has sampled a live
connection. messagesAwaitingEntity counts the sync messages this
peer is holding for an entity it has not received yet — each waits
for the spawn that names it, applies the moment it arrives, and is
released once its wait runs out. reliableInFlight counts the
reliable messages this peer has sent that the relay has not yet taken:
it reads near 0 while the link keeps up with what this peer sends, and
a count that grows names a link carrying less than that, every
reliable change sent behind it (a Sync field, a spawn) waiting with it.
Returns SyncDiagnostics — Diagnostics table.
local d = multiplayer.getDiagnostics()
if d.packetLoss > 0.05 then log.warn(("unstable connection, %d ms round trip"):format(d.rttMs)) end
print(d.messagesAwaitingEntity .. " message(s) waiting for their entity")
typed/builtin//modules/api/engine/multiplayer/multiplayer/getPeerId
multiplayer.getPeerId() -> number?
Get the peer ID the relay issued this client's connection.
Returns number? — Local peer ID, or nil exactly when isConnected() is false: while dialing, before the relay names the connection, and after it drops.
typed/builtin//modules/api/engine/multiplayer/multiplayer/getPeers
multiplayer.getPeers() -> { PeerInfo }
Get a list of all connected peers in the current session.
Returns { PeerInfo } — Array of peer info tables.
for _, p in ipairs(multiplayer.getPeers()) do print(p.name) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/getRoomPeers
multiplayer.getRoomPeers(roomKey: string) -> { PeerInfo }
Get the peers this client shares the given room with, ordered by
peer id. getPeers answers for the whole session — the union of every
room this client is in — while this answers for one room, so a peer
that leaves this room while staying in another disappears from here
and remains in getPeers.
Parameters
roomKeystring— Fully-qualified room key ({worldGuid}/{profile}/{branch}/{mode}/{sceneGuid}).
Returns { PeerInfo } — Array of peer info tables for that room.
for _, p in ipairs(multiplayer.getRoomPeers(key)) do print(p.id) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/getRooms
multiplayer.getRooms() -> { string }
The relay rooms this client has joined, sorted. A broadcast reaches
only the peers that share one of these. They are the rooms of
observe() as of the last frame, read from the rooms the session
publishes every frame, so a component can ask every frame.
Returns { string } — Room keys.
for _, key in ipairs(multiplayer.getRooms()) do print(key) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/getTickRate
multiplayer.getTickRate() -> number
Get the current sync tick rate (network updates per second).
Returns number — Sync ticks per second (default 20).
typed/builtin//modules/api/engine/multiplayer/multiplayer/heldMessages
multiplayer.heldMessages() -> { HeldMessage }
The sync messages this peer is holding for entities it has not
received — what getDiagnostics().messagesAwaitingEntity counts, one
entry each, with the entity sync id it names, its age and the grace it
is held against.
Returns { HeldMessage } — Held messages.
for _, m in ipairs(multiplayer.heldMessages()) do print(m.kind, m.ageMs) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/holdRoom
multiplayer.holdRoom(scene: string, held: boolean)
Keep this client in the relay room of a scene while its layer unloads and loads again, as a rebuild in place does. A held room is left only once it is released and its scene is no longer loaded.
Parameters
scenestring— The scene guid.heldboolean— True to hold the room, false to release it.
multiplayer.holdRoom(layers.active.guid, true)
typed/builtin//modules/api/engine/multiplayer/multiplayer/isConnected
multiplayer.isConnected() -> boolean
Check if a multiplayer session is connected to a relay and the
relay has named this client. True exactly when getPeerId() answers
an id.
Returns boolean — True if connected under the peer id the relay issued.
typed/builtin//modules/api/engine/multiplayer/multiplayer/isHost
multiplayer.isHost() -> boolean
Whether THIS client is the host (authoritative owner) of the
current scene's play room — the relay room CREATOR, or offline /
single-player. Host code spawns the shared synced world (via
entity.spawnSynced or a scene's onHostLoad) and runs authoritative
simulation; a non-host (JOINER) receives that content from the relay
snapshot and must NOT re-create it. Gate ANY code that spawns synced
entities or owns shared state with this so it runs on exactly one
client — running it on every peer is the double-spawn 'explosion'.
Returns boolean — True on the host / offline / single-player; false on a confirmed joiner. Defaults to true when the role isn't known yet (degrade to host so single-player and pre-join code still run) — pair with a scene's onHostLoad hook when exact one-shot timing matters.
if multiplayer.isHost() then enemy = entity.spawnSynced("enemy") end
typed/builtin//modules/api/engine/multiplayer/multiplayer/isOperationOpen
multiplayer.isOperationOpen() -> boolean
Whether an operation is open: true between beginOperation and
its commitOperation or cancelOperation. A caller that records file
writes reads the file's prior contents only while one is open.
Returns boolean — True while an operation is open.
if multiplayer.isOperationOpen() then before = vfs.read(p) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/isOwner
multiplayer.isOwner(entityId: (string | entityRef)?) -> boolean
Check if the local client owns the given entity (or the current entity if called from a component). Only the owner can modify synced properties directly.
Parameters
entityId(string | entityRef)(optional) — Entity id or proxy to check (defaults toself.entityIdin component context).
Returns boolean — True if the local client is the owner.
typed/builtin//modules/api/engine/multiplayer/multiplayer/isRoomCreator
multiplayer.isRoomCreator(roomKey: string) -> boolean?
Whether this client created the given room — it was the FIRST peer to join it (race-free; the relay assigns it on join). In play mode the creator instantiates the scene's entities (synced) and every other joiner receives them from the relay snapshot, so the scene is never double-instantiated.
Parameters
roomKeystring— Fully-qualified room key ({worldGuid}/{profile}/{branch}/{mode}/{sceneGuid}).
Returns boolean? — True if this client created the room, false if it joined an existing one, nil if the relay hasn't reported a role yet (offline / not joined).
if multiplayer.isRoomCreator(key) ~= false then layers.load(scene) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/joinRoom
multiplayer.joinRoom(roomKey: string)
Join a relay room. Room keys are built as
{worldGuid}/{profile}/{branch}/{mode}/{sceneGuid} — five segments, the
{profile} one keeping a runtime peer (published content) and an
editor peer (live content) in separate rooms even when both are in
play mode. Rooms partition the relay's fan-out: only peers in the
same room receive each other's broadcasts. getRooms() reports the
keys this client is already in and roomFor(entity) the one an
entity broadcasts into, so a key can be read rather than rebuilt.
A relay that verifies its peers holds each connection to the world
it was admitted to: a key whose first segment names another world
is refused, and getDiagnostics().refusals counts the refusal and
lastRefusal names it. No-op when not connected or already joined.
Parameters
roomKeystring— Fully-qualified room key.
multiplayer.joinRoom(multiplayer.roomKeyFor(sceneGuid, "play"))
typed/builtin//modules/api/engine/multiplayer/multiplayer/leaveRoom
multiplayer.leaveRoom(roomKey: string)
Leave a relay room. The key is reported under
observe().withdrawnRooms until joinRoom names it again. No-op
when not connected or not joined.
Parameters
roomKeystring— Fully-qualified room key.
typed/builtin//modules/api/engine/multiplayer/multiplayer/loopback
multiplayer.loopback() -> { [string]: any }
Loopback testing harness. Returns a table with enable(),
disable(), flush(), receive() methods for testing sync
without a relay server.
Returns { [string]: any } — Loopback API table.
typed/builtin//modules/api/engine/multiplayer/multiplayer/observe
multiplayer.observe() -> ReplicationObservation
Report what this peer is replicating and why a property is not
arriving. Carries the rooms this client joined, one record per entity
with a sync id — its owner, the room it broadcasts into, how many
other peers share that room, and every REGISTERED synced component
with its declared property names, wire indices, public/private table
and dirty bits — the messages held for entities that have not arrived,
and the registry's totals. Every property carries notArriving: one
name from reasons, or nil when it is on its way. Answers in edit
mode as well as play mode, for what the relay carries in each: in
edit mode scene content is left out of the sync-id pass, so its
changes travel to the other clients with the source they are
written into and it reads entityNotSynced here. The document
describes the session as of the last frame: when no frame has
assembled one since the surface was last read, the call waits for the
next frame to assemble it, and a caller that cannot yield receives the
one published last.
Returns ReplicationObservation — The engine's current replication observation.
local o = multiplayer.observe()
print(#o.entities .. " entities, " .. o.totals.properties .. " synced properties")
typed/builtin//modules/api/engine/multiplayer/multiplayer/observeComponent
multiplayer.observeComponent(entityId: (string | entityRef), componentType: string) -> SyncedComponent?
The registered synced component of the named type on an entity's
record. Matches a fully-qualified type (@builtin::components.Model)
and the leaf name it ends in (Model) alike.
Parameters
entityId(string | entityRef)— Entity id or proxy.componentTypestring— Component type name or its leaf.
Returns SyncedComponent? — The registered component instance, or nil when none of that type is registered on the entity.
local c = multiplayer.observeComponent(player, "Health")
print(#c.properties .. " declared properties")
typed/builtin//modules/api/engine/multiplayer/multiplayer/observeEntity
multiplayer.observeEntity(entityId: (string | entityRef)) -> EntityReplication?
The replication record for one entity — its sync id, owner, room, and the synced components registered on it.
Parameters
entityId(string | entityRef)— Entity id or proxy.
Returns EntityReplication? — The entity's record, or nil when the engine holds no sync record for it.
local r = multiplayer.observeEntity(e)
for _, c in ipairs(r.components) do print(c.componentType) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/on
multiplayer.on(channel: string, callback: (number, ...any) -> ())
Subscribe to a custom message channel. The callback runs as
callback(fromPeerId, ...args) whenever another peer calls
multiplayer.send(channel, ...). Multiple callbacks per channel fire
in registration order.
Parameters
channelstring— Channel name to listen on.callback(number, ...any) -> ()—function(fromPeerId: number, ...)— the sender's peer id then the sent args.
typed/builtin//modules/api/engine/multiplayer/multiplayer/poseFrame
multiplayer.poseFrame(entityId: (string | entityRef)) -> string?
The entity a synced entity's pose is stated relative to: on the peer
that publishes it, the frame setPoseFrame named; on every other peer,
the frame entity it was drawn in on the last frame, the one its owner
stated its pose in. Nil for an entity stated in the world.
Parameters
entityId(string | entityRef)— The entity to ask about.
Returns string? — The frame entity's id, or nil.
if multiplayer.poseFrame(player) == deck.id then print("riding the deck") end
typed/builtin//modules/api/engine/multiplayer/multiplayer/recordFileWrite
multiplayer.recordFileWrite(path: string, before: string?, after: string?) -> boolean
Record a file write into the open operation. Undoing the
operation writes before back through the VFS (removing the file when
before is nil), which runs the owning asset type's onChange as the
original write did; redoing writes after. The path is resolved and held
to the rules vfs.write applies, so a sidecar (.meta, .refs), an
install's own entry or an asset root no script may write raises. A step's files
are put back all together or not at all: each file is checked (its asset
exists, and it holds what the step being reversed left in it) before any
is written and again immediately before it is written; when a check or a
write fails partway, the files the step already wrote go back to what
they held, and a notice names each file of the step and what happened to
it. Several writes of one path in an
operation undo to the first before. Records nothing and returns false
when no operation is open.
Parameters
pathstring— VFS path of the written file.beforestring(optional) — The file's contents before the write, nil when it did not exist.afterstring(optional) — The file's contents after the write, nil when the write removed it.
Returns boolean — True when the write was recorded.
local before = vfs.read(p); vfs.write(p, body); multiplayer.recordFileWrite(p, before, body)
typed/builtin//modules/api/engine/multiplayer/multiplayer/recordSpawn
multiplayer.recordSpawn(entityId: string)
Adopt an existing entity into the open operation as its spawn — for flows that create an entity before the operation opens (a drag preview adopted on drop). Undoing the operation despawns it.
Parameters
entityIdstring— Entity id to record as spawned by this operation.
multiplayer.recordSpawn(id)
typed/builtin//modules/api/engine/multiplayer/multiplayer/redo
multiplayer.redo() -> boolean
Redo this client's last undone operation.
Returns boolean — True if an operation was redone.
typed/builtin//modules/api/engine/multiplayer/multiplayer/releaseOwnership
multiplayer.releaseOwnership(entityId: (string | entityRef)?) -> boolean
Release ownership of an entity, leaving it unowned so another peer's claim takes it. Only the owner releases an entity.
Parameters
entityId(string | entityRef)(optional) — Entity id or proxy to release.
Returns boolean — True if ownership was released.
typed/builtin//modules/api/engine/multiplayer/multiplayer/roomFor
multiplayer.roomFor(entityId: (string | entityRef)) -> string?
The room key an entity's spawns and property deltas broadcast into:
the room of its observeEntity record as of the last frame, read from
the rooms the session publishes every frame, so a component can ask
every frame.
Parameters
entityId(string | entityRef)— Entity id or proxy.
Returns string? — The room key, or nil when the engine has established no scene context for the entity.
local key = multiplayer.roomFor(player)
if key then multiplayer.joinRoom(key) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/roomHeld
multiplayer.roomHeld(scene: string) -> boolean
Whether the room of a scene is held.
Parameters
scenestring— The scene guid.
Returns boolean — True while holdRoom holds it.
local held = multiplayer.roomHeld(layers.active.guid)
typed/builtin//modules/api/engine/multiplayer/multiplayer/roomKey
multiplayer.roomKey() -> string?
The relay room key of the root scene in the engine's current mode:
the room this client's entities for that scene broadcast into. nil
while no root scene is loaded.
Returns string? — The room key, or nil.
print(multiplayer.roomKey())
typed/builtin//modules/api/engine/multiplayer/multiplayer/roomKeyFor
multiplayer.roomKeyFor(sceneGuid: string, mode: string?) -> string
The relay room key of a scene in a mode: {worldGuid}/{profile}/{branch}/{mode}/{sceneGuid},
built the way the engine keys every room, so two clients on different
branches are in different rooms. The branch segment spells % as %25
and / as %2F.
Parameters
sceneGuidstring— The scene's guid.modestring(optional) —"edit"or"play"; the engine's current mode when omitted.
Returns string — The room key.
local key = multiplayer.roomKeyFor(layers.active.guid, "play")
typed/builtin//modules/api/engine/multiplayer/multiplayer/roomStartedAt
multiplayer.roomStartedAt(roomKey: string) -> number?
When the given room began, in seconds on this engine's clock (the
clock time.time() reads): the moment its first peer joined, as the relay
states it on this client's join, less half the link's round trip. Every
client of the room reads the same moment on its own clock. A room that
empties and is joined again begins again.
Parameters
roomKeystring— Fully-qualified room key ({worldGuid}/{profile}/{branch}/{mode}/{sceneGuid}).
Returns number? — The room's start in seconds, or nil while the relay has stated none (offline, not joined, or a relay that states no start).
local started = multiplayer.roomStartedAt(multiplayer.roomKey() or "")
typed/builtin//modules/api/engine/multiplayer/multiplayer/roomTime
multiplayer.roomTime() -> number
Seconds since the current room began, the same on every client of the
session. The clock follows the room of the root scene in the current mode
(multiplayer.roomKey()): it begins when the room's first peer joins and
begins again when the room empties and is joined again, and play and edit
are different rooms. Offline, in a world with no relay, with a relay that
states no start, or before this client's join is answered, it counts from
this engine's own start, recorded the first time it is read; once the
room's start arrives it counts from that. It runs in real seconds:
engine.paused and time.timeScale() do not reach it, so a reader that
holds still while paused keeps its own value while paused. Anything that
must agree across clients without sending a value every frame reads it: a
day cycle, a wind, a schedule.
Returns number — Seconds since the current room began.
local hour = (start + multiplayer.roomTime() * speed / 3600) % 24
typed/builtin//modules/api/engine/multiplayer/multiplayer/send
multiplayer.send(channel: string, ...: any?)
Broadcast a message on a named channel to every OTHER peer in the
room. The relay forwards it without reading its arguments and names this
peer as its sender; peers receive it via multiplayer.on. The relay holds
every peer to a message rate, a byte rate and a longest message: a message
past them reaches no peer, and multiplayer.getDiagnostics().refusals
counts the relay's answer. The arguments are delivered to listeners in order,
each one arriving as what it is, at the top level and at every depth
of a table:
nil, a boolean, a number and a string arrive as themselves.- A
vectorarrives as avector. - The proxy of a synced entity arrives as the receiving peer's proxy for that entity; the proxy of an entity no peer shares, as its id string.
- A synced component (its proxy, or the
componentRefenvelope naming it) arrives as that component on the receiving peer; the proxy of a component that holds no sync id, as the envelope{ __ref, entity, componentType }naming it. - A transform vector an entity hands out (
e.position,e.rotation,e.localScale, ...) arrives as the table of its components,{ x, y, z }or{ x, y, z, w }. - Every other table is data and arrives as a new table holding the same
keys, each key and each value carried by these same rules:
{ x = 5, kind = "coin" }arrives as{ x = 5, kind = "coin" },{ who = e, n = 1 }witht.whothe receiver's proxy fore,{ [5] = "a" }witht[5] == "a",{ 1, 2, label = "m" }with its list and itslabel,{ [true] = "yes" }witht[true] == "yes", and a list with anilin it with every entry after thenilat the index it was written under. A number inside a table arrives as that number,math.hugeand NaN included. - A value no peer can hold (a function, a thread, a buffer) arrives as
nil, and so does a table entry whose key is one; the sender logs a
warning naming the key's type.
The same rules carry the arguments of a
declare.syncedFunctionsmethod, the payload of aSyncevent and a synced table-valued field. No-op when not connected.
Parameters
channelstring— Channel name listeners subscribe to viamultiplayer.on....any(optional) — Zero or more values delivered to each listener after the sender's peer id.
typed/builtin//modules/api/engine/multiplayer/multiplayer/sessionClock
multiplayer.sessionClock() -> SessionClock
Read the session clock with what is known about it. time is
sessionTime(). synced is true once the relay has answered a clock
request, and stays true across a re-dial or a world swap while the clock
keeps counting this machine's clock. accuracyMs bounds how far time
lies from the relay's clock: half the round trip of the answer it
follows, the drift of this machine's clock since (0.1 ms a second) and
any correction still being worked off; nil while unsynced. Two peers
agree to within the sum of their accuracyMs. rttMs is that answer's
round trip and sampleAgeMs how long ago it arrived. wallOffsetMs is
time less this machine's wall clock: how far this machine's clock is
set from the session's.
Returns SessionClock — The session time and its accuracy.
local c = multiplayer.sessionClock(); if c.synced then print(c.accuracyMs) end
typed/builtin//modules/api/engine/multiplayer/multiplayer/sessionTime
multiplayer.sessionTime() -> number
The session time, in seconds since the Unix epoch: one timeline every
participant of a multiplayer session reads alike, placed on the relay's
clock with the round trip to it taken out. Use it wherever peers must act
in step (a shared countdown, a synchronised emote or animation, a high
five both sides start together, a looping effect in phase, a day/night
cycle, a beat): share a start time a little in the future (a Sync field,
an event or multiplayer.send) and let every peer compute
multiplayer.sessionTime() - start. It reads the moment it is called,
never decreases once synced, and corrects itself by running up to 10%
fast or slow rather than jumping (it jumps forward only when it trails
by more than a quarter second). Before the relay first answers, and with
no relay, it reads this machine's own wall clock; sessionClock() says
which and how accurate the reading is. ClipPlayer.startedAt takes such
a time to play a clip in phase on every peer.
Returns number — Seconds since the Unix epoch on the session timeline.
local startAt = multiplayer.sessionTime() + 0.5 -- share it, then on every peer:
local elapsed = multiplayer.sessionTime() - startAt
typed/builtin//modules/api/engine/multiplayer/multiplayer/setAvatarChannel
multiplayer.setAvatarChannel(entityId: (string | entityRef), channel: AvatarChannel?) -> boolean
Put a synced avatar on the avatar channel: the compact datagram
stream an avatar's motion and state travel on in place of generic
transform deltas. A frame is about 40 bytes, sent 20 times a second
while the avatar moves or changes (a walking avatar with changing
parameters costs under 1 KB/s) and once a second while it stands. Every
peer calls it for the avatar with the same channel (an avatar
component's start does). The peer that owns the avatar states it: its
root from the entity's transform, the velocity measured from it, and
what setAvatarState and avatarEmote state. Every other peer draws
it on the session clock, the root a short delay behind the newest frame
and interpolated through jitter and lost datagrams (smoothing tunes
it), and reads the rest with avatarState.
parameters declares the avatar's parameters in order, each
{ name, type } with type "bool" (1 bit), "int" (0 to 255) or
"float" (-1 to 1, 8 bits each), 256 bits in all at most; a peer reads a
parameter block only under the same declaration. rate (1 to 30,
default 20), parameterRate (at most 10, the default) and targetRate
(at most rate) say how many times a second it states the avatar,
changed parameters and changed IK targets. The relay takes the frames
from the avatar's owner alone, and forwards a peer every frame while
the avatar is within 10 m of an avatar that peer states (its own, or
any other it owns), about 10 a second further away inside its view and
about 2 a second behind it; a frame carrying a parameter block or an
emote a peer does not hold yet goes to that peer at once. nil closes
the channel and the entity goes back to generic transform sync.
Parameters
entityId(string | entityRef)— The avatar's synced root entity.channelAvatarChannel(optional) — The declared parameters and rates; nil closes the channel.
Returns boolean — False, opening nothing, for an entity that is not synced.
multiplayer.setAvatarChannel(self.entity, { parameters = {
{ name = "Smile", type = "float" }, { name = "Gesture", type = "int" },
{ name = "Seated", type = "bool" } } })
typed/builtin//modules/api/engine/multiplayer/multiplayer/setAvatarState
multiplayer.setAvatarState(entityId: (string | entityRef), state: AvatarStateInput) -> boolean
State what the avatar channel carries of an avatar this peer owns,
beside the root pose read from the entity's transform: any of gait
(the locomotion state the avatar's animator names, an integer 0 to
127), grounded, parameters (declared names to values: a boolean, an
integer 0 to 255 or a number -1 to 1 by declared type) and targets
(IK targets in the root's own frame by name: head, leftHand, rightHand,
hips, leftFoot, rightFoot; each { position, rotation? }, or false to
clear it). A field left out keeps its value. Call it whenever the state
changes: the channel sends a change at its rate and coalesces parameter
changes to its parameterRate. Raises for an entity with no channel
open, an undeclared parameter or a value of the wrong type, naming it.
Parameters
entityId(string | entityRef)— An avatar on the channel.stateAvatarStateInput— What to state.
Returns boolean — True once stated.
multiplayer.setAvatarState(self.entity, { gait = 1, grounded = true, parameters = { Smile = 0.6 } })
typed/builtin//modules/api/engine/multiplayer/multiplayer/setNeedsRebuild
multiplayer.setNeedsRebuild(scene: string, reason: string?, sinceMs: number?)
State the scene rebuild this client owes, for clients.<id>.content.needsRebuild
in the engine state. Called with only a scene it states that scene owes
none. Every client rebuilds from its own marks, so each states its own.
Parameters
scenestring— The scene guid.reasonstring(optional) — What changed.sinceMsnumber(optional) — When the change arrived, in milliseconds since the Unix epoch.
multiplayer.setNeedsRebuild(layers.active.guid, "PlayerSpawn moved", os.time() * 1000)
typed/builtin//modules/api/engine/multiplayer/multiplayer/setPoseFrame
multiplayer.setPoseFrame(entityId: (string | entityRef), frameEntityId: (string | entityRef)?) -> boolean
State a synced entity's pose relative to another synced entity it
rides (a character on a moving deck, a passenger in a car, a crate on a
ship), or in the world again with no frame. The peer that publishes the
entity states where it stands in the frame entity's space and how it is
turned there, and every other peer draws it where that peer draws the
frame entity, so the rider moves in step with the body it rides on
every screen however far behind each owner a peer draws the two. The
frame is the nearest synced entity at or above the one named (a
collider on a child of a synced ship names the ship). An entity whose
frame is not a synced entity in the world, or is the entity itself or
under it, is stated in the world. The name lasts until it is changed or
the entity leaves the world. A CharacterController names the moving
body it stands on by itself.
Parameters
entityId(string | entityRef)— The synced entity whose pose is stated.frameEntityId(string | entityRef)(optional) — The entity it rides; nil states it in the world.
Returns boolean — False, naming nothing, for an entity named as its own frame.
multiplayer.setPoseFrame(crate, ship)
multiplayer.setPoseFrame(crate, nil)
typed/builtin//modules/api/engine/multiplayer/multiplayer/setSmoothing
multiplayer.setSmoothing(entityId: (string | entityRef), values: SmoothingSettings?) -> boolean
Set how this peer draws one synced entity another peer simulates,
in place of the world's settings: any of enabled (false draws the
entity at the newest pose received), delay and extrapolation
(seconds, 0 to 2) and teleportSpeed (metres per second). A value left
out is the world's, and nil or an empty table hands the entity back to
them. The setting is this peer's own and lasts while the entity exists.
delay = 0 draws the newest pose delivered, which trails the owner by
the network transit; see smoothing for what is drawn and when.
smoothing(entityId) reads it back.
Parameters
entityId(string | entityRef)— Synced entity to set.valuesSmoothingSettings(optional) — The values to use for this entity; nil hands it back to the world's.
Returns boolean — False, setting nothing, for an entity that is not synced.
multiplayer.setSmoothing(projectile, { delay = 0.05, teleportSpeed = 600 })
multiplayer.setSmoothing(car, nil) -- back to the world's settings
typed/builtin//modules/api/engine/multiplayer/multiplayer/smoothing
multiplayer.smoothing(entityId: (string | entityRef)?) -> Smoothing
How this peer draws the remote entities other peers simulate. A
body another peer simulates is drawn a short delay behind the newest
pose received for it, interpolated between the poses either side of
that moment, so it moves smoothly whatever the frame rate on either
side and the jitter between them, and a pose that arrives after a newer
one never moves it back. When poses stop arriving it carries on along
its last motion for up to extrapolation seconds, then holds. When
they arrive again it catches up with them rather than jumping: each
frame it moves up to a quarter more (or less) than they move, plus
1 m/s, or a frame's share of the distance left over one second when
that is more, so a gap is made up within a couple of seconds. A body
carried past its poses slows onto them, and steps back only when it
stands farther ahead of them than they move in a second or they move
slower than 4/3 m/s. A distance
larger than teleportSpeed covers in a second is a cut. A step
faster than teleportSpeed (metres per second) is a teleport and is
drawn as a cut; a step across poses lost on the way, or across a stall
of the sender, is measured from the nearest point between where the
entity stood and where the motion before it carried it, so such a body
is caught up with. A stream whose sender
changes (an ownership
handover) starts over from its first pose. The owner's own view is
untouched. The moment drawn is the owner's now less the network transit
less delay; the transit stays in, so delay = 0 draws the newest pose
delivered and still trails the owner by it. A body that stops dead is
carried past its stop until the pose it rests at arrives, about 0.1 s
after it stops, when delay is shorter than that.
The settings come from the world's settings sync.interpolation
(boolean), sync.interpolation_delay, sync.extrapolation_limit
(seconds) and sync.teleport_speed, with this peer's setSmoothing
values for the entity in their place (overridden). For an entity
whose poses this peer receives, stream holds the poses buffered, how
far the newest stands ahead of the moment drawn (lag, seconds,
negative while extrapolating), whether the sender stamps its poses with
the session clock, the moment last drawn on the session clock and this
peer's clock it was drawn at (drawnAt), both in seconds so two reads
subtract into how far the drawn moment moved over how much time, how
far (correction, metres) the body is drawn from where its poses put
it while it catches up with them, and
the running counts of poses received, dropped as stale, stream
restarts and teleports. Reading asks the coming
frames to publish the streams, so the first read of one answers on the
next frame.
Parameters
entityId(string | entityRef)(optional) — Entity to read; omit for the world's settings.
Returns Smoothing — The settings in effect and, for a remote entity, its stream.
local s = multiplayer.smoothing(car); print(s.delay, s.stream and s.stream.lag)
settings.set("sync.interpolation_delay", "0.15") -- every remote entity, world-wide
typed/builtin//modules/api/engine/multiplayer/multiplayer/syncChildPose
multiplayer.syncChildPose(entityId: (string | entityRef), childName: string, on: boolean?) -> boolean
Name a direct child of a synced entity whose local pose (position
and rotation) travels with the entity. The peer that publishes the
entity states it whenever it changes, stamped on the session clock as
the entity's own pose is, and every other peer draws its own child of
that name there: a short delay behind the newest pose, interpolated on
the timeline the entity is drawn on (smoothing tunes both), so a
child turned at once is drawn turned within that delay and a peer that
joins later reads the pose it stands at. Every peer builds the entities
under a synced entity on its own, so each names the same children (a
component's start does), and a peer draws from its owner only the
children it names itself; an entity named before it is synced states
its children once it is. A child drawn this way reads true from
childPoseFromOwner, and what turns or moves it on its own leaves it
to its owner. A name lasts while the entity exists; on = false stops
naming it, and a child its owner stops naming is each peer's own to
pose again. Up to 16 children an entity, each name up to 64 bytes.
Parameters
entityId(string | entityRef)— The synced entity.childNamestring— The name of the direct child whose local pose travels.onboolean(optional) — false stops naming the child; true when left out.
Returns boolean — False, naming nothing, for an empty or longer name or a 17th child.
multiplayer.syncChildPose(self.entity, "turret")
typed/builtin//modules/api/engine/multiplayer/multiplayer/syncTotals
multiplayer.syncTotals() -> SyncTotals
What the sync registry holds across every entity: entities with a
registered synced component, component instances, declared properties,
declared functions, the component instances holding a dirty
property this tick, and the component instances whose ComponentAdd has
yet to go out (addsWaiting: queued for the next frame, or waiting for
their entity to be announced).
Returns SyncTotals — The registry totals.
print(multiplayer.syncTotals().properties .. " synced properties registered")
typed/builtin//modules/api/engine/multiplayer/multiplayer/undo
multiplayer.undo() -> boolean
Undo this client's last edit-mode operation.
Returns boolean — True if an operation was undone.