![]() |
vkmEngine 1.0.15
A C++ game engine · vkmengine.com
|
Authoritative server with client-side prediction. One machine decides what is true; every other machine predicts its own player at once and is told about everything else a fraction of a second late. The same executables run a game networked or single-player, and a session nobody joined behaves exactly as no session.
The one idea: one predicate decides who moves what. simulates(scene, entity) answers yes to everything on a server and offline, and on a client for the character it plays, what that character is pushing, what the server never names and anything at or under a NetLocal. Props staying consistent, characters not being corrected every frame and single-player being unchanged all follow from that one answer.
project.json says how many players the game is for and its port:
--port overrides the port, and an address given with no port falls back to the project's. An unrecognised argument is refused before anything loads, so --conect 10.0.0.4 is an error, not a silent single-player game.
vkm_server is the only host, and it does not play. It owns no entity, so isMine() answers no everywhere, and every player is a client. To host and play on one machine, run vkm_server and join it with a second process (vkm run --players N builds and cooks the project, then starts a server and N players on it). The server opens no window and installs no render backend, but runs the runtime's system stack: an authority that simulated differently from its clients would not be one. It still needs the glfw shared library (building.md).
An optional module entry, beside vkmRegisterBehaviors and vkmBuildScene:
Without the entry a project runs single-player in the runtime and editor, and vkm_server refuses to serve it. Returning a null id refuses the join (NetRefusal::Declined) - how a game says "the match has started".
On Behavior, so a networked behavior reads like a single-player one:
| Ask | When | Offline |
|---|---|---|
| isSimulated() | before writing a transform, a velocity, anything the world can see | always true |
| isMine() | before touching the camera, the pointer, the HUD - anything about this player | always true |
| command() | instead of reading the device inside a fixed update | the local command |
| isReplaying() | before anything that presents - a clip, a sound, an effect | always false |
isSimulated() and isMine() differ: a server simulates every player and owns none of them. command() is the local input offline and on the owning client, and on a server what that entity's player sent, in order; an entity no player drives reads as nothing held.
Offline isSimulated() and isMine() answer yes for every character, so a scene authored with four would move all four from one keyboard. the_lab answers it with a question of its own (isOfflineSeat, examples/the_lab/src/lab_seat.h).
What a player says that must arrive - a move, a name, a choice in a lobby - is a message:
On the server each arrives at most once, in the order its player sent it, as a PlayerMessageEvent (net/player_message.h) at the event flush after it arrived. What was in flight when a player left goes with their seat.
Transform, Rigidbody, CharacterController, Ragdoll and NetSpawn are registered by the engine (registerEngineNetTypes).
A project adds its own from vkmSetupNetwork, and only there - the schema is rebuilt from nothing each time that entry runs, so a type registered from vkmRegisterBehaviors is wiped before play:
This needs free functions netEncode(const Health&, BitWriter&) and netDecode(Health&, BitReader&) visible beside the component; without them the registration line does not compile.
State the owner advances does not predict well. On the owner's own entity only Transform and Rigidbody are predicted (see Prediction and correction); every other replicated component takes the server's round-trip-old value at each snapshot. Harmless for a value the owner's systems recompute before anything reads it; wrong for a cooldown, a charge or a count, which steps back a round trip every snapshot. Keep such state out of the schema, or on the server alone and shown rather than predicted.
One rule: replicate causes, not effects. State every end recomputes from something already on the wire would arrive as a second writer for a value that already had one.
A spawned root's NetSpawn is sent even when silenced. netSilence asks the four for one entity (the editor's inspector shows it); a server classifies the world once per send round through the same rule (NetSilenceMap).
NetSession::spawn(scene, resources, prefab, at) builds a prefab on the server and on every client, including later joiners; offline it is an ordinary instantiate. On a client it is refused - the server would never hear of it - and a client's own entity is a plain Prefab::instantiate.
There is no despawn. Destroy the root with its subtree - HierarchyOperations::destroyHierarchy or Behavior::destroy - and clients drop it. Scene::destroyEntity on the root alone hands its children up to the top level, where they start to replicate as entities the client never built.
The server refuses, before building, what a client could not safely be told (isSayable, net/wire/codecs.h), and the decoder refuses the same: clients open the path on the server's word, so it must name a prefab inside the project - otherwise a hostile server names a network share and a Windows client hands it its login hash.
How it travels: the root gets a NetSpawn - the prefab path, the pose (unquantised, since a static body is never described again) and the slot each entity below it took (Prefab::BuiltSlots), for up to NET_SPAWN_MAX_SLOTS; a bigger instance is sent with none, so its slots can differ between the ends. The client builds the same file into those slots, so the subtree's state is never on the wire.
A player aims at what they saw, a moment already past. On the server, NetSession::Rewind puts every other player's past pose back for one query; the shooter stays in the present:
Read inside the braces, act outside: the end restores what it moved and discards anything written to it. Offline and on a client the scope does nothing. A nested scope changes nothing; the outermost one's end restores the present.
NetSession is owned by Engine by value and reached through FrameContext. It is not a System: it brackets the frame. NetServer holds the seats, the handshake, the command queues and outgoing snapshots; NetClient the connection, prediction, correction and interpolation; NetCore the socket, the buffers and what the two ends agreed. Both halves always exist; the role decides which one is asked.
An entity is named on the wire by its slot in the server's Scene. Both ends load the same scene file, which records the slot (SceneSerializer restores through createEntityAt), and the host tells the session the world it opened (NetSession::setWorld, from bootProjectWorld) before anything runs.
A client makes entities of its own freely (UI, effects), so it keeps a table of what the server's slots name here (NetNames). Whatever the server names that this end has not heard of is made at that same slot when free, elsewhere when the client's own entity holds it. Keeping the slot matters: the simulation walks entities in slot order, and a replay must visit predicted bodies in the server's order. When the session closes, what it made leaves with it; a session lost rather than closed keeps it, holding still.
A replicated component that names another entity sends the server's slot; ask NetSession::entityFor(scene, slot) what that names here (on a server and offline, the slot itself).
A snapshot carries a component only when its quantised bytes differ from what that connection has confirmed receiving - confirmed, not sent, or a client that missed a packet is never told again. The delta is on presence, never on values: every entry decodes from the packet alone. Joining and playing are one code path: a connection that has confirmed nothing gets the whole world. A settled world goes quiet.
Precision per field is in net/wire/quantize.h. Two properties are load-bearing: zero is exact for every signed field (Quantize::toSigned; an inexact zero tilts every unrotated body and drifts every resting one), and rotations are eleven bits a component, because a rotation error is an angle and lifts the far end of a long floor. A scale travels as three raw floats when not one, bounded on both ends by netScale (NET_MAX_SCALE); a server applies the bound to every Transform it describes before writing, so what it simulates is what clients are told.
A command packet carries every one of the newest NET_COMMAND_REDUNDANCY commands the server has not acknowledged, and before those any command no packet has carried yet (firstCommandToSend), up to NET_MAX_PACKET_COMMANDS a packet. Redundancy, not retransmission: pressed is true for one command only, so a lost datagram would lose that jump, and a retransmit would arrive after its tick.
The server runs one command per tick, in order, never twice. Commands are not addressed by tick number - the ends count ticks on separate clocks; the client's tick rides along and comes back in the snapshot so it knows which prediction was judged. The queue's edges:
Messages ride the command packet after the commands, in the room left (NetOutbox, net/transport/messages.h). Each is numbered; every packet carries every unacknowledged one that fits, oldest first, until a snapshot header's sixteen-bit number (the newest the server handed on) acknowledges it and all before it. The server's NetInbox hands on only the next in order - a copy is skipped, one past a gap waits - and at most a window's worth between two acknowledgements, so flooding costs the game nothing extra.
Two clocks at one nominal rate drift, and the server's command queue depth is that drift added up. So every snapshot says how low the queue ran (NetCommandBuffer::lowWater), and the client steers it toward a target by bending how fast its clock turns wall time into ticks, by at most NetPacing::MAX_DILATION either way (NetPacing). A jittery link keeps a deeper cushion.
Only the pacing bends. The step is Clock::getFixedStep() on every end, so a replay re-runs exactly what the server ran. Engine::run hands NetSession::pacing() to Clock::setPacing each frame; it is exactly one offline, on a server, while joining and once disconnected.
A client runs its own character at once and holds what it predicted for each tick. When a snapshot judges a tick, a position difference under CORRECTION_FLOOR (quantisation plus float noise) is ignored; above it the server's answer stands and every tick since is run again from it (Replay).
The simulation takes the correction at once; the picture does not. The jump becomes an offset that decays over a fraction of a second, applied inside NetSession::Drawn (around the systems that draw) and taken back off in its destructor, so no tick simulates from a position chosen to look nice. There is one offset per predicted body, so a leased crate and the character pushing it ease together.
Only Transform and Rigidbody of what this end predicts - its character and the bodies it leases - are set aside and restored when the prediction stands (holdPredicted / restoreHeld), and only the character's position decides; a disagreement elsewhere never causes a replay.
A replayed tick must be a function of the world and the command, and doing it twice must equal doing it once. System::isReplayed() says which systems are; only those run in the replay pass.
| Replayed | Not replayed |
|---|---|
| BehaviorSystem - turns a command into movement | AnimationSystem - a clip advanced twice gains a tick |
| PhysicsSystem | SkeletalAnimationSystem - a marker crossed twice is a footstep played for one step |
| CharacterControllerSystem | RagdollSystem - writes bone state from the pose, which both ends do for themselves |
The replay pass also runs no EventBus::flush() (it would deliver the live queue twice), no InputMap::beginTick() (the session hands over the original command) and reports no collision or trigger events (physics.md). Behaviors tick only for what this end simulates, and a body it does not decide is immovable for the pass. Unreplicated per-tick state - the controller's step latch and walkSpeed, animation, a behavior's members - is not rewound.
A client also simulates the bodies its character touches, and what those touch, so a push is not predicted as walking into a wall. PhysicsSystem computes the owned body's island over the tick's contacts and joints and reports it to the session:
A lease lasts LEASE_TICKS after it was last reported, so it does not lapse on each bounce. simulates() gates physics' gather and writeback, so the lease is one tick late. A leased body is corrected with the character - both predictions put back or neither.
What the client does not own is drawn between two poses the server gave, behind the newest news by a delay that grows with measured jitter (NetInterpolation, net/prediction/interpolation.h); the draw clock eases toward it rather than jumping, and never passes the newest sample, so a stall shows as the world pausing. What the server said is put back before each snapshot is read, or "unchanged" would mean unchanged from the smoothed value.
Every packet carries its sequence and acknowledges what came back; nothing is sent for acknowledgement and nothing is retransmitted (why UDP is a row in engine.md). Sequences are sixteen bits and wrap, so newer-than is a distance, not a > b. A packet older than one accepted is refused.
Snapshots (NET_SNAPSHOT_RATE) and commands (NET_COMMAND_RATE) go out 64 times a second by wall clock, at most one packet a frame; an overrun carries forward but never becomes a burst. Lowering NET_SNAPSHOT_RATE saves bandwidth and makes other players look later, since the interpolation delay is counted in snapshots.
Hello carries the schema fingerprint (the ordered replicated type names, folded with the quantiser's steps and widths), the action count, the action-slot fingerprint (InputMap::actionFingerprint), the entry scene's fingerprint (setWorld) and the tickRate. Commands carry actions by slot and entities are named by slot, so any difference is refused with NetRefusal::Mismatch, both ends printing what they hold; a fingerprint of zero (a generated world, or an end that has not ticked yet) is compared against nothing. A different tick rate is NetRefusal::TickRate. A full server (Full) and a game that declined (Declined) are refused the same way, with a reason a player can be shown. A message's header, the kinds Hello and Refuse and the refusal reasons are fixed across protocol versions, so another build's Hello gets Mismatch and anything else from it is dropped unread.
The client says hello from the frame loop, not connect(), because actions are defined in a behavior's onStart, inside the first tick; it repeats at the command rate until answered. Snapshots wait for the first Command. So a client's behaviors start before anything the server holds has arrived: one that acts on a replicated value changing takes the first value it sees as where it stands, or what the server counted before the join arrives as news.
Security. Every message carries a 64-bit token, and the token is the seat; a source address is trivially forged. A Hello without the right token gets a Challenge holding one and the server keeps nothing; only a Hello echoing it is seated and welcomed. The token is not a record but a keyed hash of the address and a time window (NetJoinCookie), so a flood of forged Hellos crowds out no real join. The token is checked before the connection sees the datagram, in both directions: accepting a packet moves the window and confirms its acknowledgements, so a forged one must never reach it.
Everything about a player - connection, baseline, command queue - is allocated and destroyed with them; reused per-seat state would hand the next player deltas against a world they never held. A player number is taken only by a join the game accepted, and is not reused while its player is seated.
The editor's session is Offline for the life of the process; it never hosts or joins (vkm_server boots project.entryScene from disk, the editor plays a scene in memory). File > Project > Settings... edits the player count and port, and its Multiplayer card shows the schema and fingerprint a refused join prints. The inspector's identity header shows the selected entity's wire slot and which components replicate, or which silence rule keeps it off the wire. Both build the schema through vkmSetupNetwork, on every module load and reload.