Prediction

Without prediction the player’s key press goes to the server, the server moves the ship, and the new position comes back. With a 100 ms round trip the ship starts to move 100 ms after the press, plus the time the server buffers the input. Every control feels late.

With prediction the client runs the same movement code on its own ship at once, with the same input. The server still runs it too, and its result wins: when the two differ, the client takes the server’s state. Most of the time they agree, so the player sees an instant response and the server stays the authority.

A [predicted] node does this for you. You write the input ([controls]) and how it moves the node (on_step); the engine sends, buffers, compares and corrects.

A predicted ship

// shared script: dedicated.das and main.das both require it
[controls]
struct ShipInput {
    thrust : float
    turn : float
}

[predicted(controls = ShipInput, sync = (RigidBody, Collider))]
class Ship : Component {
    // owner only, once per fixed tick: read the devices here
    def on_collect(var input : ShipInput) {
        input.thrust = get_action_axis("thrust")
        input.turn = get_action_axis("turn")
    }

    // server, owner and offline: move the node by the input
    def on_step(input : ShipInput; dt : float) {
        get_component(nodeId) <| $(var body : RigidBody?) {
            apply_force(body, nodeId.localRotation * float3(0, 1, 0) * (14.0 * clamp(input.thrust, -1.0, 1.0)))
            body.angularVelocity = float3(0, 0, -3.5 * clamp(input.turn, -1.0, 1.0))
        }
    }
}

// dedicated.das
[net_event_handler(client_connected)]
def spawn_ship_for(conn : ConnectionId; userId : uint64; name : string) {
    let node = create_node(NodeData(name = "ship"))
    add_component(node, new Ship())
    add_component(node, new Collider(shape = sphere_shape(radius = 0.9)))
    add_component(node, new RigidBody(mass = 1.0, useGravity = false))
    set_node_owner(node, conn)
}

Call set_physics_fps with the same value on both sides. The same code runs offline after set_node_owner(node, LOCAL_PLAYER). One node holds one [predicted] component.

A body that nobody drives needs no controls: every client simulates it, the server corrects it:

[predicted(sync = (RigidBody, Collider))]
class Asteroid : Component {}

How it works

../../_images/prediction_flow.png
  • A tick whose input did not arrive repeats the last input.

  • A correction comes about one round trip late. set_replication_fps finds it sooner, but does not make the round trip shorter.

How a correction is applied

When state T differs from record T, the client is wrong since tick T, and it is already some ticks further. There are two ways to fix that, and the engine uses one for each kind of node.

A node without a RigidBody: rewind and replay. The node goes back to the server’s state at T, and on_step runs again with the inputs recorded for T + 1 up to now. The result is exact: the node is where the server will put it, if no new input differs.

A node with a RigidBody: shift, do not replay. A replay of a body needs the physics to step again for every tick since T. The physics engine steps the whole world, not one body, so an exact replay is a re-simulation of all bodies over the lag (up to 0.375 s) on each correction, and the world must be saved and loaded for every tick. We do not do that. Instead the node takes the difference at T as it is:

// what the engine does, in short
pos    += server.pos    - record_T.pos
rot     = rot * inverse(record_T.rot) * server.rot
vel    += server.vel    - record_T.vel
angVel += server.angVel - record_T.angVel
// and drops every record made before this moment

The records made before the correction are dropped, not shifted: the next correction compares only what the node did after this one. This costs nothing and needs no physics rewind, but it is approximate:

  • A difference in velocity takes about two corrections, one lag apart, to meet the server.

  • A replicated field that on_step changes on every step (fuel, a timer) takes the server’s value for T and then stays behind by the lag, so the body keeps taking corrections. Keep such a field on a node without a body.

Either way the node takes the correction at once, and the visual fades it out (see the view below).

The view: how a client draws the node

A view is an ordinary Component that draws a predicted node: meshes, effects, sounds. It lives only on clients. view = ShipView in [predicted] tells the engine to add a ShipView to every Ship node on a client:

class ShipView : Component { // declare it before Ship
    private blink : float // client-only state: never sent, never corrected

    def override on_initialize {
        var color = float4(1)
        get_component(nodeId) <| $(var ship : Ship?) {
            color = ship.color // Ship is already initialized here
        }
        let visual = create_node(NodeData(name = "visual", parent = nodeId))
        add_component(visual, new Mesh(meshId = CUBE_MESH_ID, color = color))
        set_prediction_visual(nodeId, visual)
        set_prediction_smoothing(nodeId, 0.15) // the default; 0 = no fade
    }
}

[predicted(controls = ShipInput, sync = (RigidBody, Collider), view = ShipView)]
class Ship : Component {
    color : float4 = float4(1)
    ...
}

Why the drawing is a separate component and not part of Ship:

  • The server draws nothing. Ship runs on the server too; a dedicated server adds no views, so no meshes or effects are made there.

  • The drawing state stays out of the prediction. The public fields of Ship go on the wire and are corrected; a private field of Ship breaks the corrections (see below). A blink timer or a shown color is the client’s own business: keep it in the view.

  • The node is the body. The physics reads the node’s pose every frame, and a correction moves the node at once. The meshes hang on a child, the visual, and the engine draws the visual at the node plus what is left of the correction, so the jump fades out. The view makes that child and names it with set_prediction_visual.

Why name the view in [predicted], and not add it from game code:

  • Mirrors arrive by themselves. The server makes the nodes; a client gets them as mirrors at any frame. With view = the engine adds the view to each one, the player’s own node and every other player’s node, offline too. Without it the client must look for new nodes every frame:

    // what view = ShipView saves you from writing
    [export]
    def on_update {
        for (ship in find_components(type<Ship>)) {
            if (!has_component(ship.nodeId, type<ShipView>)) {
                add_component(ship.nodeId, new ShipView())
            }
        }
    }
    
  • The order is right. The engine adds the view after Ship is initialized, so the view reads its replicated fields in on_initialize.

  • No visual, no smoothing. A node without set_prediction_visual shows every correction as a jump.

A jump past 3 m or 1 rad shows at once. get_prediction_offset(node) gives what is left of the fade, for debugging.

Writing on_step

The server and the owner must get the same result, else every state is a correction:

// WRONG: the server has no keyboard, and random values differ on each peer
def on_step(input : ShipInput; dt : float) {
    nodeId.localPosition += float3(get_action_axis("thrust") + random_float(), 0, 0) * dt
}

// RIGHT: only the arguments, values clamped
def on_step(input : ShipInput; dt : float) {
    nodeId.localPosition += float3(clamp(input.thrust, -1.0, 1.0) * 5.0 * dt, 0, 0)
}

Keep the state of on_step in public (replicated) fields: a correction restores them, but not private ones:

[controls]
struct WalkerInput {
    run : bool
}

[predicted(controls = WalkerInput)]
class Walker : Component {
    stamina : float = 1.0 // RIGHT: corrected with the node
    private boost : float // WRONG for on_step: the server never sends it

    def on_step(input : WalkerInput; dt : float) {
        let run = input.run && stamina > 0.0
        stamina = clamp(stamina + (run ? -0.5 : 0.2) * dt, 0.0, 1.0)
        nodeId.localPosition += nodeId.localRotation * float3(0, 0, run ? 6.0 : 3.0) * dt
    }
}

Do not add or remove predicted nodes in on_step; do it in on_update or a message handler.

Input: counters, not pulses

The engine calls on_collect once per fixed tick, so a short press between two ticks is lost. Send a counter:

[controls]
struct GunInput {
    @compressed shots : int
}

var private shotsPressed = 0

[export]
def on_update {
    if (is_action_just_pressed("fire")) {
        shotsPressed++
    }
}

[predicted(controls = GunInput)]
class Gun : Component {
    shotsHandled : int = 0

    def on_collect(var input : GunInput) {
        input.shots = shotsPressed
    }

    def on_step(input : GunInput; dt : float) {
        if (input.shots != shotsHandled) {
            shotsHandled = input.shots
            // fire: recoil, cooldown, ammo
        }
    }
}

Actions that are not movement (buy, use, throw) stay reliable [net_command] messages.

When the input stops

The server holds the last input; get_controls_age says how old it is:

let held = get_controls_age(nodeId) > 0.35 ? ShipInput() : input // coast after 0.35 s

A node with no input at all (no owner, its player away) steps with the default ShipInput().

Other players

Other players’ nodes are ordinary mirrors: the client has no input for them. They are behind the server, your own node is ahead, and a push between two players comes as a correction.