diff --git a/docs/engine/players.md b/docs/engine/players.md index 821a8aab..029d1090 100644 --- a/docs/engine/players.md +++ b/docs/engine/players.md @@ -62,8 +62,8 @@ objects, the player's view and lock, the clock's ticks and every effect under it effects the same way (`Drawn.Effects.show`), and takes single player's settings for how the game shows things (`World.showAs`). -An object is set up the same way whoever makes it, a mission's script on the host or a scene page -on a client (`create.madeInWorld`): a planet is lit by the planets' light alone and gets its +An object is set up the same way whoever makes it, a mission's script on the host or the host's +objects on a client (`create.madeInWorld`): a planet is lit by the planets' light alone and gets its atmosphere, a wreck burns, a gate opens its tunnel and the Dark Reign gets its hat. The flight asks drawing for the atmospheres through cues of its own, as the game frames do (`main.cues`). **Fix:** before, a client made these objects without setting them up, so a planet online was lit @@ -197,8 +197,8 @@ counted in steps could not go below, would add its 20 ms to every input. The host steps 50 times a second ([The step](loop.md#the-step)) and takes an input for every step. It sends the flight view of every second step, 25 a second (`server.sendsFlightView`), so its upload is what it was with the original's step. Each client flies the step between two views -itself. The scenery, the ordnance pages and the scene pages go out with the views, since a client -shows them as of its last view. The combat effects and the pilots' commands go out every step. An input repeats the six steps before it, and the host keeps 64 timed inputs for a pilot: +itself. The scenery, the ordnance pages and the mission's objects go out with the views, since a +client shows them as of its last view. The combat effects and the pilots' commands go out every step. An input repeats the six steps before it, and the host keeps 64 timed inputs for a pilot: the 120 ms and 1.28 seconds that three and 32 of the original's steps covered. A game a player hosts steps from its drawn frames. Each frame takes every step that is due @@ -217,16 +217,40 @@ of a second, so a ship never jumps, however far ahead the clock runs. Only a dif the ship's flight over that lead and three steps more, such as a ship back at a spawn point, moves the drawn ship at once. -A co-op mission's other objects, such as its AI fighters and capital ships, travel in scene pages -(`wire.ScenePage`). A page covers 16 of the 400 object slots, and the host sends three pages with -each view, so each object comes round a few times a second. A page gives each object its place, -its velocity and its turn for one step, with the host's mission clock. The client gives the -object no orders and moves it by that velocity and turn every step (`motion.move`), so it flies on -between its pages, and the lead aim box has a velocity to lead. The client matches each page -against where it carried the object at the page's clock, and the difference fades as a ship's -does (`FlightFrame.correctLane`). Only a difference beyond the object's flight between two of its -pages and three steps more moves it at once. Every object slot has a lane of its own, so pilots' -ships, an arena's rocks and a mission's objects are corrected by the same code. +A co-op mission's other objects, such as its AI fighters and capital ships, are copied to each +client slot for slot (`mirror`), so a client holds the same state of each object as the host: +its armour and shields, its flags, its orders, whom it attacks and the rest. The copied fields +follow from the engine's types. Every field of an object's slot (`create.Slot`) is either sent +or kept by each machine, and a field added to the slot fails the build until it is put in one of +the two. A machine keeps what points into its own memory, the object's model and how it is drawn, +and the current order's own state, which clients have no use for while they run no orders. + +The host takes the state of each object that changed with each view (`mirror.Sender.take`), and +sends each client what it doesn't hold yet, the nearest and the longest waiting objects first, in +up to three messages of 1,100 bytes per view (`mirror.Sender.page`). Each state goes as the change +from the last one the client said it holds, so an object that doesn't change costs nothing and +one whose armour drops costs a few bytes (Quake 3's snapshots, as Fiedler describes them in +"Snapshot Compression"). A state the client doesn't hold yet goes as the change from an object +whose bytes are all zero. Each input tells the host the serials of the last four messages the +client took (`wire.Input.mirror_acks`). When a change comes from a state the client no longer +holds, the client asks the host to start over (`wire.Input.mirror_lost`), and the host sends its +objects whole again, once for each request. The wing comes with the objects, and on each client +the pilot's own ship leads it, as `mission_start` puts the player's ship first, so the wing +window shows the same ships as in single player. + +An object's motion, its place, its facing, its velocity and its turn each tick, doesn't go in its +state but as a pose (`mirror.Pose`), with the facing in the precision of the pilots' ships. The +client moves the object by that velocity and turn every step (`motion.move`), so it flies on +between messages, and the lead aim box has a velocity to lead. The client matches each pose +against where it carried the object at the host's mission clock, and the difference fades as a +ship's does (`FlightFrame.correctLane`). Only a difference beyond the object's flight between two +of its poses and three steps more moves it at once. Every object slot has a lane of its own, so +pilots' ships, an arena's rocks and a mission's objects are corrected by the same code. + +Not done yet: the client runs none of the objects' orders, so it shows no explosion, spin-out or +cloak from them ([#1699](https://github.com/OpenReliant/openreliant/issues/1699)). Pilots' ships +and an arena's rocks still travel their own way, in the views +([#1700](https://github.com/OpenReliant/openreliant/issues/1700)). A view is one datagram (`wire.capacity`). A dying ship's spin-out adds nine bytes to its ship, so a full arena with most of its pilots dying at once can be more than a datagram holds. Such a view diff --git a/src/engine/game/create.zig b/src/engine/game/create.zig index bb0a352e..ae268fdb 100644 --- a/src/engine/game/create.zig +++ b/src/engine/game/create.zig @@ -1623,8 +1623,8 @@ fn standStill(object: *GameObject) void { const saladin_spin = "middle spin"; /// What an object needs once it is made where the world can see it, whoever made it: a mission's -/// script on the game's side (`executor.createShip`) or a host's scene page on a network client's -/// (`scene_page.Replica.apply`). Drawing hears of a planet for its atmosphere, and the planet, the +/// script on the game's side (`executor.createShip`), or a host's message of its objects on a +/// network client (`FlightFrame.presentMirror`). Drawing hears of a planet for its atmosphere, and the planet, the /// gate, the wreck or the Dark Reign's hat is set up as `create_object` sets it up (`planetMade`, /// `gateMade`, `wreckMade`, `extra.hatMade`). pub fn madeInWorld(world: gameobj.World, index: u16) void { diff --git a/src/openreliant/network/client.zig b/src/openreliant/network/client.zig index 190ec2b3..742d9d83 100644 --- a/src/openreliant/network/client.zig +++ b/src/openreliant/network/client.zig @@ -89,7 +89,8 @@ acked: ?i32 = null, weapons: ?wire.ordnance.Order = null, sent_aim: ?wire.ordnance.Aim = null, projectiles: [wire.ordnance.Page.pages]?wire.ordnance.Page = @splat(null), -scene: [wire.ScenePage.count]?wire.ScenePage = @splat(null), +/// The host's messages of the mission's objects, until the flight takes them. +mirror: wire.mirror.Inbox = .{}, gates: ?wire.GatesPage = null, jumps: ?wire.JumpPage = null, presses: Presses = .{}, @@ -216,7 +217,8 @@ pub const Event = union(enum) { wreck: wire.Wreck, combat: wire.Combat, projectiles, - scene_page, + /// A page of what a mission shows, or a message of its objects. + mission_page, scenery, campaign_line: wire.CampaignLine, /// What happened to the pilot's own ship, for the flight to show (`wire.Feedback`). @@ -280,6 +282,8 @@ fn sendInput(client: *Client, now: i64, command: flight.Command, tick: ?i32) !vo // A step with a tick carries its own presses and trigger. Without one, the trigger is // as it holds now, and the presses go by `flight_press` below. .step = if (tick != null) client.flown_step else .{ .fire = client.fire_primary }, + .mirror_acks = client.mirror.serials, + .mirror_lost = client.mirror.lost, }; // Each input carries the steps before it, so the host loses none to a dropped packet // (Overwatch GDC 2017). @@ -368,7 +372,7 @@ fn clearFlightView(client: *Client) void { client.pending_view = null; client.pilot_pages = @splat(null); client.projectiles = @splat(null); - client.scene = @splat(null); + client.mirror = .{}; client.gates = null; client.jumps = null; client.scenery = null; @@ -435,7 +439,7 @@ fn keepMissionPage(client: *Client, kept: anytype, page: @typeInfo(@TypeOf(kept. const view = &(client.latest orelse return .idle); if (client.leaving or view.mission == null or page.tick <= client.campaign_floor) return .idle; if (kept.* == null or page.tick > kept.*.?.tick) kept.* = page; - return .scene_page; + return .mission_page; } fn take(client: *Client, message: wire.Message, now: i64) !Event { @@ -497,13 +501,12 @@ fn take(client: *Client, message: wire.Message, now: i64) !Event { if (entry.* == null or page.tick > entry.*.?.tick) entry.* = page; return .projectiles; }, - .scene_page => |page| { + .mirror => |bytes| { const view = &(client.latest orelse return .idle); - // A reliable empty page can arrive before the matching pilot view. - if (client.leaving or view.mission == null or page.tick <= client.campaign_floor) return .idle; - const entry = &client.scene[page.number]; - if (entry.* == null or page.tick > entry.*.?.tick) entry.* = page; - return .scene_page; + const tick = wire.mirror.Header.tickOf(bytes) orelse return error.InvalidMirror; + if (client.leaving or view.mission == null or tick <= client.campaign_floor) return .idle; + client.mirror.keep(bytes); + return .mission_page; }, .gates_page => |page| return client.keepMissionPage(&client.gates, page), .jump_page => |page| return client.keepMissionPage(&client.jumps, page), @@ -818,7 +821,7 @@ pub fn drive(client: *Client, io: Io, controls: Controls, leave_after: ?u32) !vo switch (event) { .combat => std.debug.print("combat page\n", .{}), .projectiles => std.debug.print("projectiles page\n", .{}), - .idle, .taken, .scene_page, .scenery, .campaign_line, .hit_feedback => {}, + .idle, .taken, .mission_page, .scenery, .campaign_line, .hit_feedback => {}, .mission_music => |cue| { _ = client.music.take(); std.debug.print("mission music {s} {s}\n", .{ if (cue.now) "now" else "fade", cue.track.slice() }); diff --git a/src/openreliant/network/flight_frame.zig b/src/openreliant/network/flight_frame.zig index 542fcc55..ef24d210 100644 --- a/src/openreliant/network/flight_frame.zig +++ b/src/openreliant/network/flight_frame.zig @@ -91,9 +91,15 @@ owed_us: f32 = 0, lead: ?f32 = null, /// The real time of the last frame, in microseconds. frame_us: i64 = 0, -scene_replica: wire.ScenePage.Replica = .{}, -/// The mission clock of the last scene page taken up of each number. -scene_clocks: [wire.ScenePage.count]?i32 = @splat(null), +/// The host's mission objects, as its messages brought them (`mirror.Replica`). +mirror: *wire.mirror.Replica, +/// The host's reuse of each slot the client shows one of the host's objects in. +mirror_reuses: [lanes]?u32 = @splat(null), +/// The tick and the mission clock of the host's state each slot shows. +mirror_ticks: [lanes]u32 = @splat(0), +mirror_clocks: [lanes]?i32 = @splat(null), +/// The host's wing as it last came (`mirror.Replica.wingAt`). +mirror_wing: game.mission.WingSlots = @splat(null), lead_announced: bool = false, script_aim: u32 = 0, scanner_command: u32 = 0, @@ -318,6 +324,8 @@ pub fn watchNext(frame: *FlightFrame, own: u16) void { pub fn create(gpa: std.mem.Allocator, local: *const game.create.Objects, tables: *const game.create.Stats) !*FlightFrame { const frame = try gpa.create(FlightFrame); errdefer gpa.destroy(frame); + const mirrored = try wire.mirror.Replica.allocate(gpa); + errdefer gpa.destroy(mirrored); var random: engine.random.Random = .{}; const objects = try game.create.Objects.create(gpa, &random); objects.count = wire.slots; @@ -339,6 +347,7 @@ pub fn create(gpa: std.mem.Allocator, local: *const game.create.Objects, tables: .tables = tables.*, .random = random, .cues = .{ .gpa = gpa }, + .mirror = mirrored, }; // Drawing starts the flight as it starts a mission: without the last one's atmospheres. frame.cues.add(.mission_started); @@ -478,6 +487,7 @@ pub fn destroy(frame: *FlightFrame) void { if (frame.wall_mesh) |*mesh| mesh.deinit(gpa); frame.drawn.objects.destroy(); frame.drawn.arena.deinit(); + gpa.destroy(frame.mirror); gpa.destroy(frame); } @@ -600,7 +610,7 @@ pub fn weaponAim(frame: *FlightFrame) wire.ordnance.Aim { const target = entry.target.slotIn(all) orelse return aim; if (target != all.player and target < wire.slots and all.playerBinding(target) != null) aim.target = .{ .slot = target, .reuse = frame.host_ship_reuse[target] }; - if (frame.scene_replica.reuses[target]) |reuse| aim.target = .{ .slot = target, .reuse = reuse }; + if (frame.mirror_reuses[target]) |reuse| aim.target = .{ .slot = target, .reuse = reuse }; const component = entry.target.resolve(all).component; if (aim.target != null and component >= 0) aim.component = @intCast(component); return aim; @@ -610,7 +620,7 @@ fn seenObject(frame: *const FlightFrame, ref: ?game.gameobj.ObjectRef) ?u16 { const object = ref orelse return null; const all = frame.drawn.objects; if (!all.slots[object.slot].object.created) return null; - const reuse = if (object.slot < all.players) frame.host_ship_reuse[object.slot] else frame.scene_replica.reuses[object.slot]; + const reuse = if (object.slot < all.players) frame.host_ship_reuse[object.slot] else frame.mirror_reuses[object.slot]; return if (reuse == object.reuse) object.slot else null; } @@ -660,43 +670,77 @@ pub fn presentGuide(frame: *FlightFrame, guide: wire.MissionView.Guide) void { frame.landing_camera = game.camera.reliantLanding(landing.tube, carrier.drawn.orientation, ship.drawn.position, view); } -/// Takes up the host's scene pages once the client's views reach them. A page makes and removes -/// the mission's objects (`ScenePage.Replica`), and each object the client already has is -/// corrected as another pilot's ship is (`correctLane`): the client's simulation carries it by -/// the velocity and turn the host last sent, and the host's place is eased in, so it moves every -/// frame rather than only when its page comes round again. -pub fn presentScene(frame: *FlightFrame, pages: *const [wire.ScenePage.count]?wire.ScenePage, types: game.create.Types) !void { +/// Takes up the host's mission objects once the client's views reach them (`mirror.Replica`). +/// Each slot holds what the host's object holds (`mirror.Record`): its damage, its orders, its +/// flags and the rest. Where it is stays the client's: its simulation carries the object by the +/// velocity and turn the host last sent, and the host's place is eased in (`correctLane`), as +/// another pilot's ship is, so it moves every frame rather than only when a message comes. The +/// wing comes with the objects. +pub fn presentMirror(frame: *FlightFrame, inbox: *wire.mirror.Inbox, types: game.create.Types) !void { + try inbox.deliver(frame.mirror); const tick = frame.tick orelse return; var scene = frame.world(); scene.spawn = .{ .tables = &frame.tables, .types = types }; - for (pages, &frame.scene_clocks) |entry, *last| { - const page = entry orelse continue; - if (page.tick > tick) continue; - const made = try frame.scene_replica.apply(scene, &page) orelse continue; - const between: f32 = if (last.*) |clock| @floatFromInt(@divTrunc(@max(page.clock -% clock, 0), game.gameobj.ticks_per_step)) else 0; - last.* = page.clock; - frame.correctScene(&page, made, between); + const all = scene.objects; + if (frame.mirror.wingAt(tick)) |wing| if (!std.meta.eql(wing, frame.mirror_wing)) { + // The pilot's own ship leads the wing on each machine, as `mission_start` puts it there. + frame.mirror_wing = wing; + all.wing = wing; + all.slots[all.player].object.wing = .player; + game.main.startWing(all); + }; + for (all.players..lanes) |index| { + const held = frame.mirror.at(index, tick) orelse continue; + if (held.tick <= frame.mirror_ticks[index]) continue; + frame.mirror_ticks[index] = held.tick; + try frame.showMirrored(scene, @intCast(index), held); } } -/// Corrects the objects of `page` that it didn't make (`made`), each by its lane, and gives them -/// the turn the host's step gave them. -fn correctScene(frame: *FlightFrame, page: *const wire.ScenePage, made: wire.ScenePage.Mask, between: f32) void { - const all = frame.drawn.objects; - for (page.objects, page.first().., 0..) |entry, index, place| { - const seen = entry orelse continue; - if (index >= lanes or made >> @intCast(place) & 1 != 0) continue; - const slot = &all.slots[index]; - if (!slot.object.created) continue; - // The turn is taken at once. The velocity is eased in with the place. - slot.object.rotation = seen.rotation(); - frame.correctLane(@intCast(index), .{ - .position = seen.position, - .orientation = wire.unpackFacing(seen.angles), - .velocity = seen.velocity, - .clock = page.clock, - }, between); +/// Shows the host's state `held` in slot `index`: makes the object where the slot holds none +/// or another, removes it where the host's slot is empty, and otherwise takes the state in. +fn showMirrored(frame: *FlightFrame, scene: game.gameobj.World, index: u16, held: wire.mirror.Replica.Held) !void { + const all = scene.objects; + const shown = &frame.mirror_reuses[index]; + if (shown.* != null and shown.* != held.reuse) { + game.create.leavesWorld(scene, index); + game.create.resetSlot(.of(scene), index); + shown.* = null; + frame.mirror_clocks[index] = null; + } + if (held.reuse == 0) return; + const pose = held.pose; + const seen: Seen = .{ + .position = pose.position, + .orientation = pose.orientation(), + .velocity = pose.velocity, + .clock = held.clock, + }; + const slot = &all.slots[index]; + if (shown.* == null) { + const spawn = scene.spawn orelse return error.MissingSceneModels; + _ = try game.create.createObject(all, spawn.tables, spawn.types, index, held.record.object.type, 0, seen.position, scene.random); + all.count = @max(all.count, index + 1); + shown.* = held.reuse; + held.record.copyTo(slot); + all.reuses[index] = held.reuse; + game.objects.setPlace(&slot.object, &slot.drawn, .{ .position = seen.position, .orientation = seen.orientation }); + if (slot.model) |*model| model.place(slot.drawn.position, slot.drawn.orientation); + slot.motion = null; + slot.object.velocity = .of(seen.velocity); + slot.object.rotation = pose.rotation(); + game.create.madeInWorld(scene, index); + frame.mirror_clocks[index] = held.clock; + return; } + // The record leaves the place, the facing and the velocity the client's simulation carried + // the object to, and the host's are eased in. The turn is taken at once. + held.record.copyTo(slot); + slot.object.rotation = pose.rotation(); + const last = frame.mirror_clocks[index]; + frame.mirror_clocks[index] = held.clock; + const between: f32 = if (last) |clock| @floatFromInt(@divTrunc(@max(held.clock -% clock, 0), game.gameobj.ticks_per_step)) else 0; + frame.correctLane(index, seen, between); } /// Takes what the host's fixed gates show, which each frame gives the client's own tunnels @@ -2001,7 +2045,52 @@ test "the pilot's own ship flies the held command and takes up the host's state try std.testing.expect(math.length(frame.offsets[0].position) < owed / 10); } -test "a mission's object moves every step between its pages and takes up the next without a jump" { +test "a planet the host's objects bring is set up as a mission's script sets it up" { + const gpa = std.testing.allocator; + var random: engine.random.Random = .{}; + const local = try game.create.Objects.create(gpa, &random); + defer local.destroy(); + const tables = game.create.testing.tables(); + const frame = try create(gpa, local, &tables); + defer frame.destroy(); + const no_models = game.create.testing.no_models; + var snapshot: wire.Snapshot = .{ .tick = 1, .ships = @splat(null) }; + snapshot.ships[0] = .{ .generation = 1, .position = @splat(0) }; + try frame.present(&snapshot, .{ .slot = 0, .generation = 1 }, local, no_models, 0); + + var host: game.gameobj.testing.Mission = undefined; + try host.init(gpa); + defer host.deinit(); + const objects = host.objects; + objects.players = wire.slots; + const index = wire.slots; + _ = try game.create.createObject(objects, &host.tables, no_models, index, .of(.jupiter_hi), 0, .{ 100, 200, 300 }, &host.random); + objects.count = index + 1; + const sender = try wire.mirror.Sender.allocate(gpa); + defer gpa.destroy(sender); + var inbox: wire.mirror.Inbox = .{}; + var bytes: [wire.mirror.capacity]u8 = undefined; + sender.take(objects, 1, snapshot.clock); + inbox.keep((try sender.page(objects, 0, 1, snapshot.clock, &bytes)).?); + frame.cues.list.clearRetainingCapacity(); + try frame.presentMirror(&inbox, no_models); + const planet = &frame.drawn.objects.slots[index].object; + try std.testing.expect(planet.flags.frozen); + try std.testing.expect(planet.flags.no_collisions); + try std.testing.expectEqual(index, frame.cues.list.items[0].planet_made.slot); + + // Once the host's planet is gone, drawing hears of it. + objects.slots[index].object.created = false; + sender.ack(0, inbox.serials[0]); + sender.take(objects, 2, snapshot.clock); + snapshot.tick = 2; + try frame.present(&snapshot, .{ .slot = 0, .generation = 1 }, local, no_models, 5 * tick_us); + inbox.keep((try sender.page(objects, 0, 2, snapshot.clock, &bytes)).?); + try frame.presentMirror(&inbox, no_models); + try std.testing.expectEqual(index, frame.cues.list.items[1].planet_gone); +} + +test "a mission's object moves every step between the host's messages and takes up the next without a jump" { const gpa = std.testing.allocator; const math = engine.surrender.math; var random: engine.random.Random = .{}; @@ -2019,23 +2108,33 @@ test "a mission's object moves every step between its pages and takes up the nex try frame.present(&snapshot, admission, local, no_models, now); // The host's object flies along x. + var host: game.gameobj.testing.Mission = undefined; + try host.init(gpa); + defer host.deinit(); + const objects = host.objects; + objects.players = wire.slots; const index = wire.slots + 2; - var pages: [wire.ScenePage.count]?wire.ScenePage = @splat(null); - var page: wire.ScenePage = .{ .tick = 1, .clock = snapshot.clock, .number = 0 }; - page.objects[index] = .{ - .reuse = 1, - .kind = .of(.predator), - .position = .{ 0, 0, 0 }, - .angles = wire.packFacing(math.identity), - .velocity = .{ 100, 0, 0 }, - .flags = .{ .targetable = true, .exploding = false }, - }; - pages[0] = page; - try frame.presentScene(&pages, no_models); + _ = try game.create.createObject(objects, &host.tables, no_models, index, .of(.predator), 0, .{ 0, 0, 0 }, &host.random); + objects.count = index + 1; + const ship = &objects.slots[index].object; + ship.velocity = .of(.{ 100, 0, 0 }); + ship.armor = .all(30); + objects.wing = .{ 1, index, null, null, null, null }; + const sender = try wire.mirror.Sender.allocate(gpa); + defer gpa.destroy(sender); + var inbox: wire.mirror.Inbox = .{}; + var bytes: [wire.mirror.capacity]u8 = undefined; + sender.take(objects, 1, snapshot.clock); + inbox.keep((try sender.page(objects, 0, 1, snapshot.clock, &bytes)).?); + try frame.presentMirror(&inbox, no_models); const slot = &all.slots[index]; try std.testing.expect(slot.object.created); + try std.testing.expectEqual(30, slot.object.armor.fore); + try std.testing.expectEqual(objects.reuses[index], all.reuses[index]); + // The host's wing, with the pilot's own ship first. + try std.testing.expectEqual(game.mission.WingSlots{ all.player, index, null, null, null, null }, all.wing); - // Between pages, the client's simulation carries it on every step. + // Between messages, the client's simulation carries it on every step. var steps: usize = 0; var last = slot.object.root.next_position.vector()[0]; for (0..20) |_| { @@ -2047,25 +2146,37 @@ test "a mission's object moves every step between its pages and takes up the nex } try std.testing.expect(steps > 10); - // The next page has it a little off where the client carried it. It doesn't jump there: the - // difference is taken in over the steps that follow. + // The next message has it a little off where the client carried it, and damaged. The damage + // shows at once. The place doesn't jump: the difference is taken in over the steps that + // follow. const clock = frame.drawn.clock.mission_ticks - 2 * game.gameobj.ticks_per_step; const carried = frame.tracks[index].byTick(clock).?.position; snapshot.tick = 2; snapshot.clock = clock; try frame.present(&snapshot, admission, local, no_models, now); - page.tick = 2; - page.clock = clock; - page.objects[index].?.position = carried + Vector{ 0, 30, 0 }; - pages[0] = page; + game.objects.setPlace(ship, &objects.slots[index].drawn, .{ .position = carried + Vector{ 0, 30, 0 }, .orientation = math.identity }); + ship.armor.fore = 12; + sender.ack(0, inbox.serials[0]); + sender.take(objects, 2, clock); + inbox.keep((try sender.page(objects, 0, 2, snapshot.clock, &bytes)).?); const before = slot.object.root.next_position.vector(); - try frame.presentScene(&pages, no_models); + try frame.presentMirror(&inbox, no_models); try std.testing.expectEqual(before, slot.object.root.next_position.vector()); + try std.testing.expectEqual(12, slot.object.armor.fore); for (0..40) |_| { now += 5 * tick_us; try frame.present(&snapshot, admission, local, no_models, now); } try std.testing.expectApproxEqAbs(30, slot.object.root.next_position.vector()[1], 1); + + // Once the host's object is gone, so is the client's. + ship.created = false; + snapshot.tick = 3; + try frame.present(&snapshot, admission, local, no_models, now); + sender.take(objects, 3, clock); + inbox.keep((try sender.page(objects, 0, 3, snapshot.clock, &bytes)).?); + try frame.presentMirror(&inbox, no_models); + try std.testing.expect(!slot.object.created); } test "a remote ship sweeps smoothly under the client's own simulation" { diff --git a/src/openreliant/network/graphical.zig b/src/openreliant/network/graphical.zig index e75f9daf..d74f7488 100644 --- a/src/openreliant/network/graphical.zig +++ b/src/openreliant/network/graphical.zig @@ -637,7 +637,7 @@ pub fn update(pilot: *Graphical, io: std.Io, front: *engine.genilib.interf.Inter if (event == .taken) quiet += 1 else events += 1; switch (event) { .idle => break, - .taken, .projectiles, .scene_page, .scenery, .campaign_movie, .mission_music => {}, + .taken, .projectiles, .mission_page, .scenery, .campaign_movie, .mission_music => {}, .campaign_result => { const mission = client.latest.?.mission.?; if (mission.ending_scene != .none) { @@ -976,7 +976,7 @@ fn applyFrame(pilot: *Graphical, flight: *FlightFrame, local: *game.create.Objec try flight.presentScenery(scenery, types); } if (client.latest.?.mission) |mission| { - try flight.presentScene(&client.scene, types); + try flight.presentMirror(&client.mirror, types); if (client.gates) |*page| flight.presentGates(page); if (client.jumps) |*page| flight.presentJumps(page); flight.presentGuide(mission.guide); diff --git a/src/openreliant/network/mirror.zig b/src/openreliant/network/mirror.zig new file mode 100644 index 00000000..f059e44d --- /dev/null +++ b/src/openreliant/network/mirror.zig @@ -0,0 +1,1129 @@ +//! The host's mission objects as each client holds them. The client keeps a copy of each object's +//! slot, slot for slot: its `Record`, which holds every field that the engine's types say can +//! travel (`Codec`), and its `Pose`, which says where it is and how it moves. A pointer into a +//! machine's own memory never travels, and each machine moves the object between poses. Each +//! state goes as the change from the last one the client said it holds, so an object that doesn't +//! change costs nothing (Quake 3's snapshots, as Fiedler describes them in "Snapshot +//! Compression"). +//! +//! A message (`Header` and its entries) carries the host's tick and clock, a serial that the +//! client sends back with its input once it holds the message (`Replica.receive`), the mission's +//! wing, and the states the host chose for that client, the nearest and the longest waiting +//! objects first (`Sender.page`). +const std = @import("std"); +const assert = std.debug.assert; +const engine = @import("openreliant").engine; +const wire = @import("wire.zig"); +const game = engine.game; +const create = game.create; +const gameobj = game.gameobj; + +const max_objects = gameobj.max_objects; + +// --- What a slot copies ------------------------------------------------------------------------- + +/// The fields of a slot (`create.Slot`) that the host sends. The others are what each machine +/// keeps for itself: what its type gives the object, its model, its motion and how it is drawn. +/// The current order's own state stays too: which of its kinds it holds depends on the order, and +/// some kinds point at what a machine keeps for itself. Clients don't run orders yet +/// ([#1699](https://github.com/OpenReliant/openreliant/issues/1699)). +const copied = [_][]const u8{ "object", "landing", "specials", "orders", "last_attacker", "last_attacker_generation", "escort_target", "queued", "cloak" }; +const kept = [_][]const u8{ "state", "combat", "flight", "cloaking_parts", "type", "model", "motion", "motion_aside", "glide", "glided", "drawn_glide", "drawn", "riding", "guns", "gun_groups", "components", "shield", "smoke", "extra" }; + +/// The fields of an object that change as it moves. They don't travel in its record: its pose +/// carries them (`Pose`), and each machine's simulation moves the object between poses. +const motion_fields = [_][]const u8{ "root", "velocity", "rotation" }; + +comptime { + for (motion_fields) |name| assert(@hasField(gameobj.GameObject, name)); +} + +/// Whether the field `name` of `T` travels in a record. +fn travels(comptime T: type, comptime name: []const u8) bool { + @setEvalBranchQuota(10_000); + if (T != gameobj.GameObject) return true; + for (motion_fields) |moving| { + if (comptime std.mem.eql(u8, moving, name)) return false; + } + return true; +} + +/// Where an object is, which way it faces, its velocity and its turn each tick, as the host sends +/// them: its facing in the precision of the pilots' ships (`wire.Facing`), and its turn as angles. +pub const Pose = struct { + position: [3]f32, + facing: wire.Facing, + velocity: [3]f32, + turn: [3]f32, + + pub fn of(object: *const gameobj.GameObject) Pose { + return .{ + .position = object.nextPosition(), + .facing = wire.packFacing(object.root.next_orientation), + .velocity = object.velocity.vector(), + .turn = engine.surrender.math.angles(object.rotation), + }; + } + + pub fn orientation(pose: *const Pose) engine.surrender.math.Matrix { + return wire.unpackFacing(pose.facing); + } + + pub fn rotation(pose: *const Pose) engine.surrender.math.Matrix { + return engine.surrender.math.fromAngles(pose.turn[0], pose.turn[1], pose.turn[2]); + } + + fn finite(pose: *const Pose) bool { + for (pose.position ++ pose.velocity ++ pose.turn) |axis| { + if (!std.math.isFinite(axis)) return false; + } + return true; + } + + /// What a pose the client doesn't hold yet goes as the change from. + const still = std.mem.zeroes(Pose); +}; + +/// A slot's state as the host sends it: the fields of `copied`, as the slot has them. +pub const Record = struct { + object: gameobj.GameObject, + landing: @FieldType(create.Slot, "landing"), + specials: @FieldType(create.Slot, "specials"), + orders: @FieldType(create.Slot, "orders"), + last_attacker: @FieldType(create.Slot, "last_attacker"), + last_attacker_generation: @FieldType(create.Slot, "last_attacker_generation"), + escort_target: @FieldType(create.Slot, "escort_target"), + queued: @FieldType(create.Slot, "queued"), + cloak: @FieldType(create.Slot, "cloak"), + + /// A record whose bytes are all zero. A state the client doesn't hold yet goes as the change + /// from it: most of an object's fields are zero, so they cost a bit each. + fn zero(record: *Record) void { + @memset(std.mem.asBytes(record), 0); + } + + pub fn of(slot: *const create.Slot) Record { + var record: Record = undefined; + inline for (copied) |name| @field(record, name) = @field(slot, name); + return record; + } + + /// Writes the record into `slot`, but for the pointers it holds and the object's motion, which + /// stay the slot's own. + pub fn copyTo(record: *const Record, slot: *create.Slot) void { + inline for (copied) |name| Codec(@FieldType(Record, name)).copy(&@field(slot, name), &@field(record, name)); + } +}; + +comptime { + // Every field of a slot is either sent or kept, so a field added to it fails the build until + // it is put in one of the two. + @setEvalBranchQuota(20_000); + const names = @typeInfo(create.Slot).@"struct".field_names; + if (names.len != copied.len + kept.len) @compileError("create.Slot has fields the mirror neither sends nor keeps"); + for (names) |name| { + var found = 0; + for (copied ++ kept) |listed| { + if (std.mem.eql(u8, name, listed)) found += 1; + } + if (found != 1) @compileError("create.Slot." ++ name ++ " is neither sent nor kept by the mirror"); + } + assert(@typeInfo(Record).@"struct".field_names.len == copied.len); +} + +// --- Bits --------------------------------------------------------------------------------------- + +/// Packs values bit by bit into a fixed buffer, least significant bit first. +pub const Writer = struct { + bytes: []u8, + bit: usize = 0, + + pub fn bits(w: *Writer, value: u64, count: u7) error{NoSpaceLeft}!void { + if (w.bit + count > w.bytes.len * 8) return error.NoSpaceLeft; + var left = count; + var rest = value; + while (left > 0) { + const byte = w.bit / 8; + const shift: u3 = @intCast(w.bit % 8); + const take: u7 = @min(8 - @as(u7, shift), left); + const mask: u64 = (@as(u64, 1) << @intCast(take)) - 1; + if (shift == 0) w.bytes[byte] = 0; + w.bytes[byte] |= @intCast((rest & mask) << shift); + rest >>= @intCast(take); + left -= take; + w.bit += take; + } + } + + pub fn flag(w: *Writer, value: bool) error{NoSpaceLeft}!void { + return w.bits(@intFromBool(value), 1); + } + + /// A whole number, four bits at a time, each group followed by a bit saying whether more follow, + /// so that a small count costs five bits. + pub fn number(w: *Writer, value: u32) error{NoSpaceLeft}!void { + var rest = value; + while (true) { + try w.bits(rest & 0xF, 4); + rest >>= 4; + try w.flag(rest != 0); + if (rest == 0) return; + } + } + + /// The bytes written so far. + pub fn written(w: *const Writer) []const u8 { + return w.bytes[0 .. (w.bit + 7) / 8]; + } +}; + +pub const Reader = struct { + bytes: []const u8, + bit: usize = 0, + + pub fn bits(r: *Reader, count: u7) error{EndOfStream}!u64 { + if (r.bit + count > r.bytes.len * 8) return error.EndOfStream; + var value: u64 = 0; + var done: u7 = 0; + while (done < count) { + const byte = r.bytes[r.bit / 8]; + const shift: u3 = @intCast(r.bit % 8); + const take: u7 = @min(8 - @as(u7, shift), count - done); + const mask: u64 = (@as(u64, 1) << @intCast(take)) - 1; + value |= ((@as(u64, byte) >> shift) & mask) << @intCast(done); + done += take; + r.bit += take; + } + return value; + } + + pub fn flag(r: *Reader) error{EndOfStream}!bool { + return try r.bits(1) != 0; + } + + pub fn number(r: *Reader) Error!u32 { + var value: u64 = 0; + var shift: u6 = 0; + while (true) : (shift += 4) { + value |= try r.bits(4) << shift; + if (!try r.flag()) break; + if (shift == 28) return error.InvalidMirror; + } + return std.math.cast(u32, value) orelse error.InvalidMirror; + } +}; + +test "bits pack across bytes and read back" { + var buffer: [16]u8 = undefined; + var w: Writer = .{ .bytes = &buffer }; + try w.flag(true); + try w.bits(0x1234_5678_9ABC_DEF0, 64); + try w.bits(5, 3); + try std.testing.expectEqual(9, w.written().len); + var r: Reader = .{ .bytes = w.written() }; + try std.testing.expect(try r.flag()); + try std.testing.expectEqual(0x1234_5678_9ABC_DEF0, try r.bits(64)); + try std.testing.expectEqual(5, try r.bits(3)); + try std.testing.expectError(error.EndOfStream, r.bits(8)); + var full: Writer = .{ .bytes = buffer[0..1] }; + try std.testing.expectError(error.NoSpaceLeft, full.bits(0, 9)); + w = .{ .bytes = &buffer }; + try w.number(3); + try std.testing.expectEqual(5, w.bit); + try w.number(std.math.maxInt(u32)); + r = .{ .bytes = w.written() }; + try std.testing.expectEqual(3, try r.number()); + try std.testing.expectEqual(std.math.maxInt(u32), try r.number()); +} + +// --- The codec ---------------------------------------------------------------------------------- + +pub const Error = error{ EndOfStream, InvalidMirror }; + +/// Whether a value of `T` is something a machine keeps for itself: a pointer, or the address the +/// original kept in an object's record (`engine.Pointer`). It never travels, and a copy leaves the +/// receiver's own. +fn local(comptime T: type) bool { + return switch (@typeInfo(T)) { + .pointer, .@"opaque", .@"fn" => true, + .optional => |optional| @typeInfo(optional.child) == .pointer, + .@"enum" => @hasDecl(T, "Target") and T == engine.Pointer(T.Target), + else => false, + }; +} + +/// Whether `T` holds a local value anywhere in it. +fn holdsLocal(comptime T: type) bool { + @setEvalBranchQuota(100_000); + if (local(T)) return true; + return switch (@typeInfo(T)) { + .@"struct" => |info| for (info.field_types, info.field_attrs) |F, attrs| { + if (!attrs.@"comptime" and holdsLocal(F)) break true; + } else false, + .array => |array| holdsLocal(array.child), + .vector => |vector| holdsLocal(vector.child), + .optional => |optional| holdsLocal(optional.child), + .@"union" => |info| for (info.field_types) |F| { + if (holdsLocal(F)) break true; + } else false, + else => false, + }; +} + +/// Whether `T` holds an object, whose motion stays where it is copied to. +fn holdsMotion(comptime T: type) bool { + return switch (@typeInfo(T)) { + .@"struct" => T == gameobj.GameObject, + .array => |array| holdsMotion(array.child), + else => false, + }; +} + +/// How a value of `T` travels. With a base, the value the receiver already has, each part is +/// preceded by a bit saying whether it changed, and only what changed follows. Without one, +/// every part follows. +/// +/// - A bool is a bit, and a number, an enum or a packed struct its bits. A received value that +/// isn't one of an exhaustive enum's is refused, as anywhere in a packed struct. +/// - A struct, an array or a vector goes part by part. +/// - An optional is a bit for whether it holds a value, and the value. +/// - A tagged union is its tag and its value; an untagged one, the bytes of its fixed layout. +/// - A local value (`local`) doesn't travel at all, nor an object's motion (`motion_fields`). +pub fn Codec(comptime T: type) type { + return struct { + const info = @typeInfo(T); + + comptime { + // A local value inside an optional or a union would come from the sender when the + // receiver has none of its own to keep. + switch (info) { + .optional => |optional| if (!local(T) and holdsLocal(optional.child)) @compileError("a local value inside " ++ @typeName(T)), + .@"union" => if (holdsLocal(T)) @compileError("a local value inside " ++ @typeName(T)), + else => {}, + } + } + + pub fn encode(w: *Writer, value: *const T, base: ?*const T) error{NoSpaceLeft}!void { + if (comptime local(T)) return; + if (base) |held| { + const changed = !same(value, held); + try w.flag(changed); + if (!changed) return; + } + try encodeWhole(w, value, base); + } + + fn encodeWhole(w: *Writer, value: *const T, base: ?*const T) error{NoSpaceLeft}!void { + switch (info) { + .void => {}, + .bool => try w.flag(value.*), + .int, .float, .@"enum" => try w.bits(raw(value.*), @bitSizeOf(T)), + .@"struct" => |s| if (s.layout == .@"packed") { + try w.bits(raw(value.*), @bitSizeOf(T)); + } else inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| { + if (attrs.@"comptime" or comptime !travels(T, name)) continue; + try Codec(F).encode(w, &@field(value, name), if (base) |held| &@field(held, name) else null); + }, + .array, .vector => { + for (0..length) |at| { + const item: Child = value.*[at]; + const held: ?Child = if (base) |b| b.*[at] else null; + try Codec(Child).encode(w, &item, if (held) |*h| h else null); + } + }, + .optional => |optional| { + try w.flag(value.* != null); + const payload = if (value.*) |*held| held else return; + const before: ?*const optional.child = if (base) |b| (if (b.*) |*held| held else null) else null; + try Codec(optional.child).encode(w, payload, before); + }, + .@"union" => |u| if (u.tag_type) |Tag| { + const tag: Tag = value.*; + try Codec(Tag).encodeWhole(w, &tag, null); + switch (value.*) { + inline else => |*payload, active| { + const before = if (base) |b| (if (b.* == active) &@field(b.*, @tagName(active)) else null) else null; + try Codec(@TypeOf(payload.*)).encode(w, payload, before); + }, + } + } else { + try Codec([@sizeOf(T)]u8).encode(w, std.mem.asBytes(value), if (base) |b| std.mem.asBytes(b) else null); + }, + else => @compileError("the mirror can't send a " ++ @typeName(T)), + } + } + + pub fn decode(r: *Reader, out: *T, base: ?*const T) Error!void { + if (comptime local(T)) return; + if (base) |held| { + if (!try r.flag()) { + copy(out, held); + return; + } + } + try decodeWhole(r, out, base); + } + + fn decodeWhole(r: *Reader, out: *T, base: ?*const T) Error!void { + switch (info) { + .void => {}, + .bool => out.* = try r.flag(), + .int, .float => out.* = @bitCast(@as(Bits, @intCast(try r.bits(@bitSizeOf(T))))), + .@"enum" => out.* = try enumOf(try r.bits(@bitSizeOf(T))), + .@"struct" => |s| if (s.layout == .@"packed") { + const value: T = @bitCast(@as(Bits, @intCast(try r.bits(@bitSizeOf(T))))); + if (!valid(value)) return error.InvalidMirror; + out.* = value; + } else inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| { + if (attrs.@"comptime" or comptime !travels(T, name)) continue; + try Codec(F).decode(r, &@field(out, name), if (base) |held| &@field(held, name) else null); + }, + .array, .vector => { + for (0..length) |at| { + var item: Child = out.*[at]; + const held: ?Child = if (base) |b| b.*[at] else null; + try Codec(Child).decode(r, &item, if (held) |*h| h else null); + out.*[at] = item; + } + }, + .optional => |optional| { + if (!try r.flag()) { + out.* = null; + return; + } + const before: ?*const optional.child = if (base) |b| (if (b.*) |*held| held else null) else null; + var payload: optional.child = if (before) |held| held.* else undefined; + try Codec(optional.child).decode(r, &payload, before); + out.* = payload; + }, + .@"union" => |u| if (u.tag_type) |Tag| { + var tag: Tag = undefined; + try Codec(Tag).decodeWhole(r, &tag, null); + switch (tag) { + inline else => |active| { + const name = @tagName(active); + const Payload = @FieldType(T, name); + const before: ?*const Payload = if (base) |b| (if (b.* == active) &@field(b.*, name) else null) else null; + var payload: Payload = if (before) |held| held.* else undefined; + try Codec(Payload).decode(r, &payload, before); + out.* = @unionInit(T, name, payload); + }, + } + } else { + try Codec([@sizeOf(T)]u8).decode(r, std.mem.asBytes(out), if (base) |b| std.mem.asBytes(b) else null); + }, + else => @compileError("the mirror can't send a " ++ @typeName(T)), + } + } + + /// Whether `a` and `b` agree on everything that travels, number by number bit for bit. + pub fn same(a: *const T, b: *const T) bool { + if (comptime local(T)) return true; + switch (info) { + .void => return true, + .bool => return a.* == b.*, + .int, .float, .@"enum" => return raw(a.*) == raw(b.*), + .@"struct" => |s| { + if (s.layout == .@"packed") return raw(a.*) == raw(b.*); + inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| { + if (attrs.@"comptime" or comptime !travels(T, name)) continue; + if (!Codec(F).same(&@field(a, name), &@field(b, name))) return false; + } + return true; + }, + .array, .vector => { + for (0..length) |at| { + const left: Child = a.*[at]; + const right: Child = b.*[at]; + if (!Codec(Child).same(&left, &right)) return false; + } + return true; + }, + .optional => |optional| { + const left = if (a.*) |*held| held else return b.* == null; + const right = if (b.*) |*held| held else return false; + return Codec(optional.child).same(left, right); + }, + .@"union" => |u| { + if (u.tag_type == null) return std.mem.eql(u8, std.mem.asBytes(a), std.mem.asBytes(b)); + switch (a.*) { + inline else => |*payload, active| return b.* == active and Codec(@TypeOf(payload.*)).same(payload, &@field(b.*, @tagName(active))), + } + }, + else => @compileError("the mirror can't compare a " ++ @typeName(T)), + } + } + + /// Copies what travels of `from` into `into`, leaving the local values `into` has. + pub fn copy(into: *T, from: *const T) void { + if (comptime local(T)) return; + if (comptime !holdsLocal(T) and !holdsMotion(T)) { + into.* = from.*; + return; + } + switch (info) { + .@"struct" => |s| inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| { + if (attrs.@"comptime" or comptime !travels(T, name)) continue; + Codec(F).copy(&@field(into, name), &@field(from, name)); + }, + .array => |array| for (into, from) |*item, *held| Codec(array.child).copy(item, held), + else => unreachable, + } + } + + const Bits = @Int(.unsigned, @bitSizeOf(T)); + + const length = switch (info) { + .array => |array| array.len, + .vector => |vector| vector.len, + else => 0, + }; + + const Child = switch (info) { + .array => |array| array.child, + .vector => |vector| vector.child, + else => void, + }; + + fn raw(value: T) u64 { + return switch (info) { + .@"enum" => @as(Bits, @bitCast(@backingInt(value))), + else => @as(Bits, @bitCast(value)), + }; + } + + fn enumOf(bits: u64) error{InvalidMirror}!T { + const Backing = info.@"enum".tag_type; + const value: Backing = @bitCast(@as(Bits, @intCast(bits))); + return std.enums.fromInt(T, value) orelse error.InvalidMirror; + } + + /// Whether every enum in a packed struct holds one of its values. + fn valid(value: T) bool { + switch (info) { + .@"enum" => return std.enums.fromInt(T, @backingInt(value)) != null, + .@"struct" => |s| inline for (s.field_names, s.field_types) |name, F| { + if (!Codec(F).valid(@field(value, name))) return false; + }, + else => {}, + } + return true; + } + }; +} + +test "a value travels whole, then as what changed" { + const Sample = struct { + flags: packed struct(u8) { on: bool = false, off: bool = true, _: u6 = 0 } = .{}, + speed: f32 = 1, + count: [3]i16 = .{ 1, 2, 3 }, + kind: enum(u8) { one, two } = .one, + maybe: ?u32 = null, + choice: union(enum) { none, some: f32 } = .none, + address: engine.Pointer(u8) = .null, + }; + const C = Codec(Sample); + var buffer: [64]u8 = undefined; + + // Whole, a pointer left as the receiver has it. + const sent: Sample = .{ .speed = 2.5, .count = .{ 4, 5, 6 }, .kind = .two, .maybe = 7, .choice = .{ .some = 0.5 }, .address = @fromBackingInt(@intCast(9)) }; + var w: Writer = .{ .bytes = &buffer }; + try C.encode(&w, &sent, null); + var got: Sample = .{ .address = @fromBackingInt(@intCast(3)) }; + var r: Reader = .{ .bytes = w.written() }; + try C.decode(&r, &got, null); + try std.testing.expect(C.same(&sent, &got)); + try std.testing.expectEqual(@as(engine.Pointer(u8), @fromBackingInt(@intCast(3))), got.address); + + // Unchanged, it is a single bit. + w = .{ .bytes = &buffer }; + try C.encode(&w, &sent, &got); + try std.testing.expectEqual(1, w.bit); + + // One number changed costs its own bits and a bit for each part. + var next = sent; + next.count[1] = -8; + w = .{ .bytes = &buffer }; + try C.encode(&w, &next, &got); + try std.testing.expect(w.bit < 32); + var after = got; + r = .{ .bytes = w.written() }; + try C.decode(&r, &after, &got); + try std.testing.expectEqual(-8, after.count[1]); + try std.testing.expect(C.same(&next, &after)); + + // A value an exhaustive enum doesn't have is refused. + var bad: Writer = .{ .bytes = &buffer }; + try bad.bits(0, 8); + try bad.bits(0, 32); + try bad.bits(0, 48); + try bad.bits(5, 8); + r = .{ .bytes = bad.written() }; + try std.testing.expectError(error.InvalidMirror, C.decode(&r, &got, null)); +} + +// --- Messages ----------------------------------------------------------------------------------- + +/// How many states of each slot each side keeps to take the changes from. +pub const history_length = 8; +/// The most bytes a message holds, which keeps it, with the message's kind, in one datagram. +pub const capacity = 1100; +/// How many records a message carries at most. +pub const max_entries = 160; +/// How many of the latest messages' serials an input carries back. +pub const acks = 4; + +const Wing = game.mission.WingSlots; + +/// A message's header: the host's tick and mission clock when it was written, its serial, how many +/// times the host started over for the client (`Sender.Peer.epoch`), and the mission's wing. Each +/// entry's tick and clock go as how far they lie before these. +pub const Header = struct { + tick: u32, + clock: i32, + serial: u16, + epoch: u8, + wing: Wing, + + fn write(header: *const Header, w: *Writer) !void { + try w.bits(header.tick, 32); + try w.bits(@as(u32, @bitCast(header.clock)), 32); + try w.bits(header.serial, 16); + try w.bits(header.epoch, 8); + try Codec(Wing).encode(w, &header.wing, null); + } + + fn read(r: *Reader) Error!Header { + var header: Header = .{ + .tick = @intCast(try r.bits(32)), + .clock = @bitCast(@as(u32, @intCast(try r.bits(32)))), + .serial = @intCast(try r.bits(16)), + .epoch = @intCast(try r.bits(8)), + .wing = undefined, + }; + try Codec(Wing).decode(r, &header.wing, null); + if (header.tick == 0 or header.serial == 0) return error.InvalidMirror; + for (header.wing) |entry| if (entry) |slot| if (slot >= max_objects) return error.InvalidMirror; + return header; + } + + /// The host's tick a message was written at, or null for bytes too short to hold one. + pub fn tickOf(bytes: []const u8) ?u32 { + var r: Reader = .{ .bytes = bytes }; + return @intCast(r.bits(32) catch return null); + } +}; + +/// The states one side keeps of a slot, the newest last written. +const History = struct { + ticks: [history_length]u32 = @splat(0), + clocks: [history_length]i32 = @splat(0), + /// The host's reuse of the slot for each; 0 for a slot left empty. + reuses: [history_length]u32 = @splat(0), + records: [history_length]Record = undefined, + poses: [history_length]Pose = undefined, + newest: u8 = 0, + + /// Makes room for a new state and returns its place, whose record and pose the caller writes. + fn push(history: *History, tick: u32, clock: i32, reuse: u32) usize { + history.newest = @intCast((@as(usize, history.newest) + 1) % history_length); + history.ticks[history.newest] = tick; + history.clocks[history.newest] = clock; + history.reuses[history.newest] = reuse; + return history.newest; + } + + /// The place of the state taken at `tick` of the host's reuse `reuse`, if it is still kept. + fn find(history: *const History, tick: u32, reuse: u32) ?usize { + if (tick == 0) return null; + for (history.ticks, history.reuses, 0..) |at, held, place| { + if (at == tick and held == reuse) return place; + } + return null; + } + + fn newestTick(history: *const History) u32 { + return history.ticks[history.newest]; + } +}; + +/// Whether the host sends the object in `slot`: an object a mission made, there in the world. +fn shown(all: *const create.Objects, slot: usize) bool { + if (slot < all.players or slot >= all.count) return false; + const object = &all.slots[slot].object; + return object.created and !object.flags.outOfFrame() and !object.flags.hidden; +} + +const slot_bits = std.math.log2_int_ceil(usize, max_objects); + +// --- The host ----------------------------------------------------------------------------------- + +/// What the host keeps to send its objects: the states it last took of each slot, and for each +/// pilot what that pilot's client has said it holds. +pub const Sender = struct { + history: [max_objects]History, + blank: Record, + peers: [peer_count]Peer, + + const peer_count = wire.slots; + + pub const Peer = struct { + /// The tick and the host's reuse of the newest state of each slot the client holds; a + /// reuse of 0 for a slot the client holds empty, and a tick of 0 for none. + held: [max_objects]Held = @splat(.{}), + /// The ticks of the last states sent of each slot, newest last, so that a change is only + /// ever taken from a state the client can still have kept. + sent_ticks: [max_objects][history_length]u32 = @splat(@splat(0)), + /// How long each slot has waited, which decides what goes first. + waited: [max_objects]f32 = @splat(0), + /// The host's tick each slot was last sent at, so that the messages of one view don't + /// send it twice. + sent_at: [max_objects]u32 = @splat(0), + pages: [page_memory]Sent = @splat(.{}), + next_serial: u16 = 1, + /// How many times the host started over for this client, which the client sends back when + /// it asks to (`Replica.lost`), so that one request starts over once. + epoch: u8 = 0, + + const page_memory = 64; + + const Held = struct { tick: u32 = 0, reuse: u32 = 0 }; + + const Sent = struct { + serial: u16 = 0, + count: u16 = 0, + entries: [max_entries]Entry = undefined, + + const Entry = struct { slot: u16, tick: u32, reuse: u32 }; + }; + + const Base = struct { tick: u32, place: usize }; + + fn base(peer: *const Peer, history: *const History, slot: usize, reuse: u32) ?Base { + const held = peer.held[slot]; + if (held.tick == 0 or held.reuse != reuse) return null; + // Only the states sent since the one the client holds can have pushed it out of the + // client's own history. + var since: usize = 0; + for (peer.sent_ticks[slot]) |at| { + if (at > held.tick) since += 1; + } + if (since + 1 >= history_length) return null; + return .{ .tick = held.tick, .place = history.find(held.tick, reuse) orelse return null }; + } + + fn noteSent(peer: *Peer, slot: usize, tick: u32) void { + const ticks = &peer.sent_ticks[slot]; + std.mem.copyForwards(u32, ticks[0 .. history_length - 1], ticks[1..]); + ticks[history_length - 1] = tick; + } + }; + + pub fn allocate(gpa: std.mem.Allocator) !*Sender { + const sender = try gpa.create(Sender); + Record.zero(&sender.blank); + sender.reset(); + return sender; + } + + /// Forgets every state, as a mission starts. + pub fn reset(sender: *Sender) void { + for (&sender.history) |*history| history.* = .{}; + for (&sender.peers) |*peer| peer.* = .{}; + } + + /// Forgets what the client of pilot slot `index` holds, as the pilot joins or leaves. + pub fn forget(sender: *Sender, index: usize) void { + sender.peers[index] = .{}; + } + + /// Starts over for the client of pilot slot `index`, which lost track of the states the host + /// sends changes from, as of `epoch` (`Replica.lost`). The serials go on, so that the ones the + /// client still sends back don't name new messages. + pub fn startOver(sender: *Sender, index: usize, epoch: u8) void { + const peer = &sender.peers[index]; + if (epoch != peer.epoch) return; + peer.* = .{ .next_serial = peer.next_serial, .epoch = epoch +% 1 }; + } + + /// The client of pilot slot `index` holds the message `serial`. + pub fn ack(sender: *Sender, index: usize, serial: u16) void { + if (serial == 0) return; + const peer = &sender.peers[index]; + const page_sent = &peer.pages[serial % Peer.page_memory]; + if (page_sent.serial != serial) return; + for (page_sent.entries[0..page_sent.count]) |entry| { + const held = &peer.held[entry.slot]; + if (entry.tick > held.tick) held.* = .{ .tick = entry.tick, .reuse = entry.reuse }; + } + page_sent.serial = 0; + } + + /// Takes each slot's state at `tick`, where it changed since the last taken, once before the + /// messages of a view. A state's tick is the one it was taken at, and it holds until the next. + pub fn take(sender: *Sender, all: *const create.Objects, tick: u32, clock: i32) void { + for (&sender.history, 0..) |*history, slot| { + const newest = history.reuses[history.newest]; + if (!shown(all, slot)) { + if (newest != 0) _ = history.push(tick, clock, 0); + continue; + } + const now: Record = .of(&all.slots[slot]); + const pose: Pose = .of(&all.slots[slot].object); + if (newest == all.reuses[slot] and history.newestTick() != 0 and + Codec(Record).same(&now, &history.records[history.newest]) and + Codec(Pose).same(&pose, &history.poses[history.newest])) continue; + const place = history.push(tick, clock, all.reuses[slot]); + history.records[place] = now; + history.poses[place] = pose; + } + } + + /// Writes the next message for the client of pilot slot `index` into `buffer` and returns + /// its bytes, or null when the client holds every slot as the host last took it (`take`). + /// The slots go by how long each has waited, which grows faster the nearer it is to the + /// pilot's ship. + pub fn page(sender: *Sender, all: *const create.Objects, index: usize, tick: u32, clock: i32, buffer: []u8) error{NoSpaceLeft}!?[]const u8 { + const peer = &sender.peers[index]; + var order: [max_objects]u16 = undefined; + var waiting: usize = 0; + const from: ?engine.surrender.math.Vector = if (index < all.count and all.slots[index].object.created) all.slots[index].object.nextPosition() else null; + for (&sender.history, 0..) |*history, slot| { + const newest = history.newestTick(); + // A slot the host never had needs nothing, and nor does one the client holds as the + // host last took it. + if (newest == 0 or peer.held[slot].tick == newest or peer.sent_at[slot] == tick) continue; + const live = history.reuses[history.newest] != 0; + if (!live and peer.held[slot].tick == 0) continue; + peer.waited[slot] += if (live) weight(from, history.poses[history.newest].position) else nearest_weight; + order[waiting] = @intCast(slot); + waiting += 1; + } + if (waiting == 0) return null; + const Order = struct { + fn before(waited: *const [max_objects]f32, a: u16, b: u16) bool { + return waited[a] > waited[b]; + } + }; + std.mem.sort(u16, order[0..waiting], &peer.waited, Order.before); + + const serial = peer.next_serial; + var w: Writer = .{ .bytes = buffer }; + const header: Header = .{ .tick = tick, .clock = clock, .serial = serial, .epoch = peer.epoch, .wing = all.wing }; + try header.write(&w); + const memory = &peer.pages[serial % Peer.page_memory]; + memory.* = .{ .serial = serial }; + // The last bit of the buffer is kept for the end. + var entries: Writer = .{ .bytes = buffer, .bit = w.bit }; + for (order[0..waiting]) |slot| { + if (memory.count == max_entries) break; + const history = &sender.history[slot]; + const reuse = history.reuses[history.newest]; + const taken = history.newestTick(); + const mark = entries.bit; + sender.writeEntry(&entries, &header, history, peer, slot) catch { + entries.bit = mark; + break; + }; + if (entries.bit + 1 > buffer.len * 8) { + entries.bit = mark; + break; + } + peer.noteSent(slot, taken); + peer.sent_at[slot] = tick; + peer.waited[slot] = 0; + memory.entries[memory.count] = .{ .slot = slot, .tick = taken, .reuse = reuse }; + memory.count += 1; + } + if (memory.count == 0) { + memory.serial = 0; + return null; + } + try entries.flag(false); + peer.next_serial = if (serial == std.math.maxInt(u16)) 1 else serial + 1; + return entries.written(); + } + + /// An entry: the slot, how long before the message the state was taken, and whether the slot + /// is empty. A live slot's state then goes as the change from the state the client holds, if + /// the host still has it, or from a blank one, with the host's reuse of the slot. + fn writeEntry(sender: *const Sender, w: *Writer, header: *const Header, history: *const History, peer: *const Peer, slot: u16) error{NoSpaceLeft}!void { + const newest = history.newest; + const reuse = history.reuses[newest]; + const taken = history.ticks[newest]; + try w.flag(true); + try w.bits(slot, slot_bits); + try w.number(header.tick - taken); + try w.number(@bitCast(header.clock -% history.clocks[newest])); + try w.flag(reuse != 0); + if (reuse == 0) return; + const before = peer.base(history, slot, reuse); + try w.flag(before != null); + if (before) |held| try w.number(taken - held.tick) else try w.bits(reuse, 32); + try Codec(Record).encode(w, &history.records[newest], if (before) |held| &history.records[held.place] else &sender.blank); + try Codec(Pose).encode(w, &history.poses[newest], if (before) |held| &history.poses[held.place] else &Pose.still); + } + + /// How much a slot's wait grows each message: more the nearer the object is to the pilot's + /// ship, so that what the pilot sees close by moves on most often. + fn weight(from: ?engine.surrender.math.Vector, at: engine.surrender.math.Vector) f32 { + const pilot = from orelse return 1; + const apart = engine.surrender.math.distance(pilot, at); + return 1 + nearest_weight / (1 + apart / near); + } + + const nearest_weight: f32 = 4; + const near: f32 = 20000; +}; + +// --- The client --------------------------------------------------------------------------------- + +/// What a client keeps of the host's objects: the states the host sent of each slot, the +/// newest messages' serials to send back, and the wing. +pub const Replica = struct { + history: [max_objects]History, + /// The newest messages taken, which each input sends back (`wire.Input.mirror_acks`). + serials: [acks]u16, + /// The wings the latest messages carried, by tick. + wings: [history_length]Wings, + /// The host's epoch when a message held a change from a state the client no longer has. + /// Each input asks the host to start over (`Sender.startOver`) until a message of a later + /// epoch comes. + lost: ?u8, + blank: Record, + + const Wings = struct { tick: u32, wing: Wing }; + + pub fn allocate(gpa: std.mem.Allocator) !*Replica { + const replica = try gpa.create(Replica); + Record.zero(&replica.blank); + replica.reset(); + return replica; + } + + pub fn reset(replica: *Replica) void { + for (&replica.history) |*history| history.* = .{}; + replica.serials = @splat(0); + replica.wings = @splat(.{ .tick = 0, .wing = @splat(null) }); + replica.lost = null; + } + + /// Takes a message's states into the history, and notes its serial to send back. + pub fn receive(replica: *Replica, bytes: []const u8) Error!void { + var r: Reader = .{ .bytes = bytes }; + const header = try Header.read(&r); + if (replica.lost) |epoch| { + if (header.epoch == epoch) return; + replica.lost = null; + } + var oldest: usize = 0; + for (replica.wings, 0..) |entry, place| { + if (entry.tick < replica.wings[oldest].tick) oldest = place; + } + replica.wings[oldest] = .{ .tick = header.tick, .wing = header.wing }; + while (try r.flag()) { + const slot: usize = @intCast(try r.bits(slot_bits)); + if (slot >= max_objects) return error.InvalidMirror; + const before_message = try r.number(); + if (before_message >= header.tick) return error.InvalidMirror; + const taken = header.tick - before_message; + const clock = header.clock -% @as(i32, @bitCast(try r.number())); + const history = &replica.history[slot]; + const fresh = history.newestTick() < taken; + if (!try r.flag()) { + if (fresh) _ = history.push(taken, clock, 0); + continue; + } + var reuse: u32 = undefined; + var before: ?usize = null; + if (try r.flag()) { + const since = try r.number(); + if (since == 0 or since >= taken) return error.InvalidMirror; + const held = taken - since; + // The host takes the change from the reuse the client holds. + for (history.ticks, history.reuses, 0..) |kept_tick, kept_reuse, place| { + if (kept_tick == held and kept_reuse != 0) { + before = place; + reuse = kept_reuse; + } + } + if (before == null) { + // The change is from a state this client no longer has, so what follows + // can't be read: the client asks the host to start over. + replica.lost = header.epoch; + replica.serials = @splat(0); + return; + } + } else { + reuse = @intCast(try r.bits(32)); + if (reuse == 0) return error.InvalidMirror; + } + const from_record = if (before) |place| &history.records[place] else &replica.blank; + const from_pose = if (before) |place| &history.poses[place] else &Pose.still; + var record: Record = from_record.*; + try Codec(Record).decode(&r, &record, from_record); + var pose: Pose = from_pose.*; + try Codec(Pose).decode(&r, &pose, from_pose); + if (!pose.finite()) return error.InvalidMirror; + if (!fresh) continue; + const place = history.push(taken, clock, reuse); + history.records[place] = record; + history.poses[place] = pose; + } + std.mem.copyBackwards(u16, replica.serials[1..], replica.serials[0 .. acks - 1]); + replica.serials[0] = header.serial; + } + + pub const Held = struct { tick: u32, clock: i32, reuse: u32, record: *const Record, pose: *const Pose }; + + /// The newest state of `slot` the host sent at or before `tick`. + pub fn at(replica: *const Replica, slot: usize, tick: u32) ?Held { + const history = &replica.history[slot]; + var best: ?usize = null; + for (history.ticks, 0..) |taken, index| { + if (taken == 0 or taken > tick) continue; + if (best == null or taken > history.ticks[best.?]) best = index; + } + const index = best orelse return null; + return .{ .tick = history.ticks[index], .clock = history.clocks[index], .reuse = history.reuses[index], .record = &history.records[index], .pose = &history.poses[index] }; + } + + /// The newest wing sent at or before `tick`. + pub fn wingAt(replica: *const Replica, tick: u32) ?Wing { + var best: ?usize = null; + for (replica.wings, 0..) |entry, index| { + if (entry.tick == 0 or entry.tick > tick) continue; + if (best == null or entry.tick > replica.wings[best.?].tick) best = index; + } + return replica.wings[best orelse return null].wing; + } +}; + +/// What a client keeps between the host's messages and the flight that takes them +/// (`Replica.receive`), and what the client's inputs send back. +pub const Inbox = struct { + messages: [length][capacity]u8 = undefined, + lengths: [length]u16 = @splat(0), + count: u8 = 0, + /// The serials and the request to start over each input carries (`wire.Input`). + serials: [acks]u16 = @splat(0), + lost: ?u8 = null, + + const length = 16; + + /// Keeps a message until the flight takes it; with the inbox full, the oldest goes. + pub fn keep(inbox: *Inbox, bytes: []const u8) void { + if (bytes.len > capacity) return; + if (inbox.count == length) { + std.mem.copyForwards([capacity]u8, inbox.messages[0 .. length - 1], inbox.messages[1..]); + std.mem.copyForwards(u16, inbox.lengths[0 .. length - 1], inbox.lengths[1..]); + inbox.count -= 1; + } + @memcpy(inbox.messages[inbox.count][0..bytes.len], bytes); + inbox.lengths[inbox.count] = @intCast(bytes.len); + inbox.count += 1; + } + + /// Gives the kept messages to `replica`, and notes what the next inputs send back. + pub fn deliver(inbox: *Inbox, replica: *Replica) Error!void { + defer inbox.count = 0; + for (inbox.messages[0..inbox.count], inbox.lengths[0..inbox.count]) |*message, size| try replica.receive(message[0..size]); + inbox.serials = replica.serials; + inbox.lost = replica.lost; + } +}; + +test "a client holds what the host sends, and then takes only what changed" { + const gpa = std.testing.allocator; + var mission: gameobj.testing.Mission = undefined; + try mission.init(gpa); + defer mission.deinit(); + const all = mission.objects; + _ = try mission.add(.of(.predator), .{ 0, 0, 0 }); + all.players = 1; + const enemy = try mission.add(.of(.predator), .{ 100, 200, 300 }); + all.slots[enemy].object.armor = .all(40); + all.wing = .{ 0, enemy, null, null, null, null }; + + const sender = try Sender.allocate(gpa); + defer gpa.destroy(sender); + const replica = try Replica.allocate(gpa); + defer gpa.destroy(replica); + var buffer: [1400]u8 = undefined; + + // The first message carries the whole object. + sender.take(all, 10, 100); + const first = (try sender.page(all, 0, 10, 100, &buffer)).?; + const whole = first.len; + try replica.receive(first); + try std.testing.expectEqual(1, replica.serials[0]); + const held = replica.at(enemy, 10).?; + try std.testing.expectEqual(all.reuses[enemy], held.reuse); + try std.testing.expectEqual(40, held.record.object.armor.fore); + try std.testing.expectEqual(enemy, replica.wingAt(10).?[1].?); + + // Until the client says it holds it, the host sends it whole again. + all.slots[enemy].object.armor.fore = 25; + sender.take(all, 11, 110); + const again = (try sender.page(all, 0, 11, 110, &buffer)).?; + try std.testing.expect(again.len + 8 >= whole); + try replica.receive(again); + + // Once it does, only the change travels. + sender.ack(0, replica.serials[0]); + all.slots[enemy].object.armor.fore = 10; + sender.take(all, 12, 120); + const change = (try sender.page(all, 0, 12, 120, &buffer)).?; + try std.testing.expect(change.len < whole / 4); + try replica.receive(change); + try std.testing.expectEqual(10, replica.at(enemy, 12).?.record.object.armor.fore); + try std.testing.expectEqual(25, replica.at(enemy, 11).?.record.object.armor.fore); + + // An object that doesn't change isn't sent again. + sender.ack(0, replica.serials[0]); + sender.take(all, 13, 130); + try std.testing.expectEqual(null, try sender.page(all, 0, 13, 130, &buffer)); + + // An object gone from the host is gone from the client. + all.slots[enemy].object.created = false; + sender.take(all, 14, 140); + const gone = (try sender.page(all, 0, 14, 140, &buffer)).?; + try replica.receive(gone); + try std.testing.expectEqual(0, replica.at(enemy, 14).?.reuse); + sender.ack(0, replica.serials[0]); + sender.take(all, 15, 150); + try std.testing.expectEqual(null, try sender.page(all, 0, 15, 150, &buffer)); +} + +test "a change from a state the client no longer has asks the host to start over" { + const gpa = std.testing.allocator; + var mission: gameobj.testing.Mission = undefined; + try mission.init(gpa); + defer mission.deinit(); + const all = mission.objects; + _ = try mission.add(.of(.predator), .{ 0, 0, 0 }); + all.players = 1; + const enemy = try mission.add(.of(.predator), .{ 100, 0, 0 }); + const sender = try Sender.allocate(gpa); + defer gpa.destroy(sender); + const replica = try Replica.allocate(gpa); + defer gpa.destroy(replica); + var buffer: [1400]u8 = undefined; + sender.take(all, 10, 100); + try replica.receive((try sender.page(all, 0, 10, 100, &buffer)).?); + sender.ack(0, replica.serials[0]); + replica.reset(); + all.slots[enemy].object.armor.fore = 1; + sender.take(all, 11, 110); + try replica.receive((try sender.page(all, 0, 11, 110, &buffer)).?); + try std.testing.expectEqual(0, replica.lost); + try std.testing.expectEqual(0, replica.serials[0]); + // The host starts over once, however many inputs ask it to. + sender.startOver(0, replica.lost.?); + sender.startOver(0, replica.lost.?); + try std.testing.expectEqual(1, sender.peers[0].epoch); + sender.take(all, 12, 120); + try replica.receive((try sender.page(all, 0, 12, 120, &buffer)).?); + try std.testing.expectEqual(null, replica.lost); + try std.testing.expectEqual(1, replica.at(enemy, 12).?.record.object.armor.fore); +} diff --git a/src/openreliant/network/scene_page.zig b/src/openreliant/network/scene_page.zig deleted file mode 100644 index f7fbf119..00000000 --- a/src/openreliant/network/scene_page.zig +++ /dev/null @@ -1,257 +0,0 @@ -//! Bounded views of mission objects. A page covers the same slots for the whole session. -const std = @import("std"); -const engine = @import("openreliant").engine; -const game = engine.game; -const wire = @import("wire.zig"); -const Page = @This(); - -pub const Mask = u16; -pub const width = @bitSizeOf(Mask); -pub const count = std.math.divCeil(usize, game.gameobj.max_objects, width) catch unreachable; -pub const capacity = @sizeOf(u8) + @sizeOf(u32) + @sizeOf(i32) + @sizeOf(u8) + @sizeOf(Mask) + width * Pose.capacity; - -tick: u32, -/// The host's mission clock at the step the page was taken, which the client's tracks keep their -/// steps by. -clock: i32 = 0, -number: u8, -objects: [width]?Pose = @splat(null), - -pub const Pose = struct { - const capacity = @sizeOf(u32) + @sizeOf(u16) + 9 * @sizeOf(f32) + @sizeOf(wire.Facing) + @sizeOf(u8); - reuse: u32, - kind: game.gameobj.Type, - position: [3]f32, - angles: wire.Facing, - /// The object's velocity and its turn, as angles, for one original step: the client carries - /// the object by these between two pages, as the host's step moves it (`motion.move`). - velocity: [3]f32 = @splat(0), - turn: [3]f32 = @splat(0), - flags: Flags, - - /// The turn as the matrix `motion.move` turns the object by each step. - pub fn rotation(pose: *const Pose) engine.surrender.math.Matrix { - return engine.surrender.math.fromAngles(pose.turn[0], pose.turn[1], pose.turn[2]); - } -}; - -const Flags = packed struct(u8) { - targetable: bool, - exploding: bool, - reserved: u6 = 0, -}; - -pub fn first(page: *const Page) usize { - return @as(usize, page.number) * width; -} - -pub fn capture(all: *const game.create.Objects, tick: u32, clock: i32, number: u8) Page { - var page: Page = .{ .tick = tick, .clock = clock, .number = number }; - for (&page.objects, page.first()..) |*entry, slot| { - // The pilot snapshot already carries the occupied pilot slots. - if (slot < all.players or slot >= all.count) continue; - const object = &all.slots[slot].object; - if (!object.created or object.flags.outOfFrame() or object.flags.hidden) continue; - entry.* = .{ - .reuse = all.reuses[slot], - .kind = object.type, - .position = object.nextPosition(), - .angles = wire.packFacing(object.root.next_orientation), - .velocity = object.velocity.vector(), - .turn = engine.surrender.math.angles(object.rotation), - .flags = .{ .targetable = object.flags.targetable, .exploding = object.flags.exploding }, - }; - } - return page; -} - -pub fn mask(page: *const Page) Mask { - var found: Mask = 0; - for (page.objects, 0..) |entry, slot| { - if (entry != null) found |= bit(slot); - } - return found; -} - -fn bit(slot: usize) Mask { - return @as(Mask, 1) << @as(std.math.Log2Int(Mask), @intCast(slot)); -} - -pub fn write(page: *const Page, writer: *std.Io.Writer) !void { - try writer.writeInt(u32, page.tick, .little); - try writer.writeInt(i32, page.clock, .little); - try writer.writeByte(page.number); - try writer.writeInt(Mask, page.mask(), .little); - for (page.objects) |entry| { - const object = entry orelse continue; - try writer.writeInt(u32, object.reuse, .little); - if (object.kind.number() >= game.create.ship_type_count) return error.InvalidScenePage; - try writer.writeInt(u16, @intCast(object.kind.number()), .little); - for (object.position ++ object.velocity ++ object.turn) |axis| try writer.writeInt(u32, @bitCast(axis), .little); - try wire.writeFacing(writer, object.angles); - try writer.writeByte(@bitCast(object.flags)); - } -} - -pub fn read(reader: *std.Io.Reader) !Page { - var page: Page = .{ .tick = try reader.takeInt(u32, .little), .clock = try reader.takeInt(i32, .little), .number = try reader.takeByte() }; - if (page.tick == 0 or page.number >= count) return error.InvalidScenePage; - const present = try reader.takeInt(Mask, .little); - for (&page.objects, 0..) |*entry, slot| { - if (present & bit(slot) == 0) continue; - if (page.first() + slot >= game.gameobj.max_objects) return error.InvalidScenePage; - const reuse = try reader.takeInt(u32, .little); - const kind = try reader.takeInt(u16, .little); - if (kind >= game.create.ship_type_count) return error.InvalidScenePage; - var motion: [9]f32 = undefined; - for (&motion) |*axis| { - axis.* = @bitCast(try reader.takeInt(u32, .little)); - if (!std.math.isFinite(axis.*)) return error.InvalidScenePage; - } - const angles = try wire.readFacing(reader); - const flags: Flags = @bitCast(try reader.takeByte()); - if (flags.reserved != 0) return error.InvalidScenePage; - entry.* = .{ - .reuse = reuse, - .kind = @fromBackingInt(kind), - .position = motion[0..3].*, - .angles = angles, - .velocity = motion[3..6].*, - .turn = motion[6..9].*, - .flags = flags, - }; - } - return page; -} - -/// Keeps host reuse counts separate from local object references used by the HUD and scripts. -pub const Replica = struct { - ticks: [count]u32 = @splat(0), - reuses: [game.gameobj.max_objects]?u32 = @splat(null), - - /// Makes and removes the page's objects. A new object stands where the page has it and moves - /// by its velocity and turn. The client corrects one it already has by the page through its - /// own simulation (`FlightFrame.presentScene`), so that it never jumps. Returns the objects - /// the page made, by their place in it, or null for a page no newer than the last one with - /// its number. - pub fn apply(replica: *Replica, world: game.gameobj.World, page: *const Page) !?Mask { - const applied = &replica.ticks[page.number]; - if (page.tick <= applied.*) return null; - var made_objects: Mask = 0; - const spawn = world.spawn orelse return error.MissingSceneModels; - const all = world.objects; - for (page.objects, page.first()..) |entry, index| { - if (index < all.players or index >= all.slots.len) continue; - const slot: u16 = @intCast(index); - const place = index - page.first(); - const current = &replica.reuses[slot]; - if (current.* != null and (entry == null or current.* != entry.?.reuse)) { - game.create.leavesWorld(world, slot); - game.create.resetSlot(.of(world), slot); - current.* = null; - } - const seen = entry orelse continue; - var made = false; - if (current.* == null) { - _ = try game.create.createObject(all, spawn.tables, spawn.types, slot, seen.kind, 0, seen.position, world.random); - all.count = @max(all.count, slot + 1); - current.* = seen.reuse; - made = true; - } - const shown = &all.slots[slot]; - shown.object.flags.targetable = seen.flags.targetable; - shown.object.flags.exploding = seen.flags.exploding; - if (!made) continue; - made_objects |= bit(place); - game.objects.setPlace(&shown.object, &shown.drawn, .{ .position = seen.position, .orientation = wire.unpackFacing(seen.angles) }); - if (shown.model) |*model| model.place(shown.drawn.position, shown.drawn.orientation); - // The client gives the object no orders, so its flight model would only slow it - // down. It moves by what the host's step moved it by. - shown.motion = null; - shown.object.velocity = .of(seen.velocity); - shown.object.rotation = seen.rotation(); - // A planet, a gate or a wreck is set up where it stands, as a mission's script sets - // it up on the host. - game.create.madeInWorld(world, slot); - } - applied.* = page.tick; - return made_objects; - } -}; - -test "scene pages preserve a reused slot's new identity" { - var mission: game.gameobj.testing.Mission = undefined; - try mission.init(std.testing.allocator); - defer mission.deinit(); - mission.objects.players = 1; - mission.objects.count = width; - const slot = try mission.add(.of(.predator), .{ 100, 200, 300 }); - const previous = capture(mission.objects, 1, 1, 1); - game.create.resetSlot(mission.orders(), slot); - _ = try game.create.createObject(mission.objects, &mission.tables, game.create.testing.no_models, slot, .of(.shroud), 0, .{ 500, 600, 700 }, &mission.random); - mission.slot(slot).object.velocity = .of(.{ 1, 2, 3 }); - mission.slot(slot).object.rotation = engine.surrender.math.fromAngles(0.01, 0.02, 0); - const next = capture(mission.objects, 2, 2, 1); - try std.testing.expect(next.objects[0].?.reuse != previous.objects[0].?.reuse); - var buffer: [capacity]u8 = undefined; - const message: wire.Message = .{ .scene_page = next }; - const received = try wire.Message.decode(try message.encode(&buffer)); - try std.testing.expectEqualDeep(next, received.scene_page); - - var display: game.gameobj.testing.Mission = undefined; - try display.init(std.testing.allocator); - defer display.deinit(); - var world = display.world(); - world.spawn = display.spawn(game.create.testing.no_models); - var replica: Replica = .{}; - _ = try replica.apply(world, &previous); - const first_ship_ref: game.gameobj.ObjectRef = .of(display.objects, slot); - try std.testing.expectEqual(1, try replica.apply(world, &received.scene_page)); - // An older page than the last one with its number changes nothing. - try std.testing.expectEqual(null, try replica.apply(world, &previous)); - try std.testing.expectEqual(null, first_ship_ref.resolve(display.objects)); - try std.testing.expectEqual(game.gameobj.Type.of(.shroud), display.slot(slot).object.type); - try std.testing.expectEqual(next.objects[0].?.position, display.slot(slot).object.nextPosition()); - // The new object moves by the host's velocity and turn, not by a flight model. - try std.testing.expectEqual(next.objects[0].?.velocity, @as([3]f32, display.slot(slot).object.velocity.vector())); - try std.testing.expectEqual(null, display.slot(slot).motion); - - const empty: Page = .{ .tick = 3, .number = next.number }; - _ = try replica.apply(world, &empty); - _ = try replica.apply(world, &next); - try std.testing.expectEqual(null, replica.reuses[slot]); - try std.testing.expect(!display.slot(slot).object.created); -} - -test "a planet a scene page makes is set up as a mission's script sets it up" { - var mission: game.gameobj.testing.Mission = undefined; - try mission.init(std.testing.allocator); - defer mission.deinit(); - mission.objects.players = 1; - mission.objects.count = width; - const slot = try mission.add(.of(.jupiter_hi), .{ 100, 200, 300 }); - const page = capture(mission.objects, 1, 1, 1); - - var display: game.gameobj.testing.Mission = undefined; - try display.init(std.testing.allocator); - defer display.deinit(); - var cues: game.main.cues.Cues = .{ .gpa = std.testing.allocator }; - defer cues.deinit(); - var world = display.world(); - world.spawn = display.spawn(game.create.testing.no_models); - world.cues = &cues; - var replica: Replica = .{}; - _ = try replica.apply(world, &page); - // It stands still and collides with nothing (`create.planetMade`), and drawing hears of it - // for its atmosphere. - try std.testing.expect(display.slot(slot).object.flags.frozen); - try std.testing.expect(display.slot(slot).object.flags.no_collisions); - try std.testing.expectEqual(slot, cues.list.items[0].planet_made.slot); - // Applied again, the page makes nothing, so drawing hears nothing more. - _ = try replica.apply(world, &page); - try std.testing.expectEqual(1, cues.list.items.len); - // Drawing hears when it goes. - const empty: Page = .{ .tick = 2, .number = page.number }; - _ = try replica.apply(world, &empty); - try std.testing.expectEqual(slot, cues.list.items[1].planet_gone); -} diff --git a/src/openreliant/network/server.zig b/src/openreliant/network/server.zig index 9b675294..e7ab3196 100644 --- a/src/openreliant/network/server.zig +++ b/src/openreliant/network/server.zig @@ -47,7 +47,8 @@ const paused_roster_interval = std.time.us_per_s; // pause_screen_multiplayer (0x0048E62D) shows a drop control past 100 game ticks of round-trip time. const slow_round_trip = 100 * std.time.ms_per_s / game.main.ticks_per_second; const packets_per_tick = 4; -const scene_pages_per_view = 3; +/// The most object messages (`mirror.Sender.page`) each client gets with a view. +const mirror_messages_per_view = 3; const max_identity = 32; /// The most connections that may wait to be admitted at once. They wait apart from the pilots' /// slots, so a connection that never joins keeps no pilot out. @@ -137,8 +138,8 @@ paused: bool = false, paused_view_pending: bool = false, next_paused_roster: i64 = 0, projectile_pages: [ProjectilePage.pages]bool = @splat(false), -scene_pages: [wire.ScenePage.count]bool = @splat(false), -next_scene_page: u8 = 0, +/// The mission's objects as each client holds them, made with the first mission's view. +mirror: ?*wire.mirror.Sender = null, /// Whether the last gates page sent held a tunnel, so an empty one still has to go out. gates_sent: bool = false, /// Whether the last jump page sent held a jump, so an empty one still has to go out. @@ -209,6 +210,7 @@ fn remove(host: *Host, slot: u8, announce: bool, departure: Departure) void { host.roster_dirty = true; } host.peers[slot] = null; + if (host.mirror) |sender| sender.forget(slot); if (host.campaign_movie) |*movie| if (slot < wire.cooperative_slots) { movie.waiting.unset(slot); }; @@ -536,6 +538,10 @@ fn seatCampaignCrew(host: *Host) !void { host.arena.leave(@intCast(index)); host.peers[seat] = peer; host.peers[index] = null; + if (host.mirror) |sender| { + sender.forget(seat); + sender.forget(index); + } host.channel().send(peer.conn, .{ .campaign_seat = admission }) catch { host.release(seat); continue; @@ -761,6 +767,7 @@ fn admit(host: *Host, index: usize, message: wire.Message, time: i64) !enum { wa }; host.peers[slot] = peer.*; host.pending[index] = null; + if (host.mirror) |sender| sender.forget(slot); host.welcome(slot, admitted, time) catch |err| { log.warn("could not welcome the pilot in slot {d}: {t}", .{ slot, err }); host.remove(slot, false, .rejected); @@ -816,7 +823,10 @@ fn receive(host: *Host, slot: u8, peer: *Peer, message: wire.Message, time: i64) }; } switch (message) { - .input => |input| host.acceptInput(peer, input, time), + .input => |input| { + host.acceptInput(peer, input, time); + host.acceptMirrorAcks(slot, input); + }, .flight_press => |presses| if (host.acceptsFlight()) peer.presses.merge(presses), .weapon_order => |order| if (host.acceptsFlight()) { if (peer.weapons) |*pending| pending.merge(order) else peer.weapons = order; @@ -926,6 +936,15 @@ test "an input's margin is how long before its step it arrived" { try std.testing.expectEqual(std.math.maxInt(i8), arrivalMargin(due, 400, 4000, due)); } +/// Takes what an input says the pilot's client holds of the mission's objects +/// (`mirror.Sender.ack`), and starts over when it lost track of them. +fn acceptMirrorAcks(host: *const Host, slot: usize, input: wire.Input) void { + const sender = host.mirror orelse return; + if (input.arena_floor != host.arena_floor) return; + for (input.mirror_acks) |serial| sender.ack(slot, serial); + if (input.mirror_lost) |epoch| sender.startOver(slot, epoch); +} + fn acceptInput(host: *const Host, peer: *Peer, input: wire.Input, time: i64) void { if (!input.follows(peer.sequence)) return; peer.sequence = input.sequence; @@ -1109,8 +1128,8 @@ fn publishRoster(host: *Host) !void { /// the view of every second step, 25 a second as the original's steps came, so its upload stays /// what it was. Each client flies the steps between two views itself, from its own inputs and /// the others' last commands, by the same code (Rocket League GDC 2018). A paused, final or -/// debrief view is always sent. The scenery, the ordnance pages and the scene pages go with the -/// flight views, since a client shows them as of its last view (`FlightFrame.tick`). The combat +/// debrief view is always sent. The scenery, the ordnance pages and the mission's objects go with +/// the flight views, since a client shows them as of its last view (`FlightFrame.tick`). The combat /// effects and the pilots' commands go out every step. fn sendsFlightView(tick: u32) bool { return tick % steps_per_flight_view == 0; @@ -1421,6 +1440,10 @@ pub fn close(host: *Host) void { if (entry.*) |pilot| net.session_close(pilot.conn); entry.* = null; } + if (host.mirror) |sender| { + host.arena.mission.objects.gpa.destroy(sender); + host.mirror = null; + } if (host.listener != 0) { net.session_listen_close(host.listener); host.listener = 0; @@ -1652,9 +1675,8 @@ fn enterCampaignStage(host: *Host, staging: *Arena, time: i64, number: u16, seco host.beginBriefing(number, directory); host.campaign_start.?.second_part = second_part; host.campaign_briefing = !second_part; - host.scene_pages = @splat(false); + if (host.mirror) |sender| sender.reset(); host.projectile_pages = @splat(false); - host.next_scene_page = 0; host.gates_sent = false; host.jumps_sent = false; host.clearFlightControls(); @@ -1861,7 +1883,7 @@ pub fn pump(host: *Host) !Pumped { try host.broadcastScenery(); if (view.hasOrdnance()) try host.broadcastProjectiles(); if (view.mission != null) { - try host.broadcastScene(); + try host.sendMirror(); try host.broadcastGates(); try host.broadcastJumps(); } @@ -1930,29 +1952,26 @@ fn broadcastPage(host: *Host, message: wire.Message, active: bool, sent: *bool) sent.* = active or retry_clear; } -fn broadcastScene(host: *Host) !void { - var sent: usize = 0; +/// Sends each client the mission's objects it doesn't hold as the host has them +/// (`mirror.Sender`), with each view. +fn sendMirror(host: *Host) !void { + const all = host.arena.mission.objects; + const sender = host.mirror orelse made: { + const made = try wire.mirror.Sender.allocate(all.gpa); + host.mirror = made; + break :made made; + }; + sender.take(all, host.tick, host.arena.mission.clock.mission_ticks); var buffer: [wire.capacity]u8 = undefined; - for (0..wire.ScenePage.count) |_| { - const number = host.next_scene_page; - host.next_scene_page = @intCast((@as(usize, number) + 1) % wire.ScenePage.count); - const page = wire.ScenePage.capture(host.arena.mission.objects, host.tick, host.arena.mission.clock.mission_ticks, number); - const active = page.mask() != 0; - const previous = &host.scene_pages[number]; - if (!active and !previous.*) continue; - const bytes = try (wire.Message{ .scene_page = page }).encode(&buffer); - var retry_clear = false; - for (host.peers) |entry| { - const peer = entry orelse continue; - if (peer.state != .playing) continue; - // Keep the empty page if an unreliable final position is lost. - host.channel().sendBytes(peer.conn, bytes, !active) catch { - retry_clear = !active; - }; + var bytes: [wire.mirror.capacity]u8 = undefined; + for (host.peers, 0..) |entry, slot| { + const peer = entry orelse continue; + if (peer.state != .playing) continue; + for (0..mirror_messages_per_view) |_| { + const page = try sender.page(all, slot, host.tick, host.arena.mission.clock.mission_ticks, &bytes) orelse break; + const message = try (wire.Message{ .mirror = page }).encode(&buffer); + host.channel().sendBytes(peer.conn, message, false) catch break; } - previous.* = active or retry_clear; - sent += 1; - if (sent == scene_pages_per_view) break; } } diff --git a/src/openreliant/network/transport.zig b/src/openreliant/network/transport.zig index 6b191380..2f5435ad 100644 --- a/src/openreliant/network/transport.zig +++ b/src/openreliant/network/transport.zig @@ -57,7 +57,7 @@ pub const Channel = struct { var buf: [wire.capacity]u8 = undefined; const bytes = try message.encode(&buf); const reliable = switch (message) { - .input, .view, .combat, .projectiles, .scene_page, .gates_page, .jump_page, .pilot_page, .own_flight => false, + .input, .view, .combat, .projectiles, .mirror, .gates_page, .jump_page, .pilot_page, .own_flight => false, else => true, }; try channel.sendBytes(conn, bytes, reliable); diff --git a/src/openreliant/network/wire.zig b/src/openreliant/network/wire.zig index 49d5785a..09c4c0c8 100644 --- a/src/openreliant/network/wire.zig +++ b/src/openreliant/network/wire.zig @@ -4,7 +4,7 @@ const version = @import("version"); const flight_input = @import("flight_input.zig"); const engine = @import("openreliant").engine; pub const ordnance = @import("ordnance.zig"); -pub const ScenePage = @import("scene_page.zig"); +pub const mirror = @import("mirror.zig"); pub const GatesPage = @import("gates_page.zig"); pub const JumpPage = @import("jump_page.zig"); const flight = engine.input.flight; @@ -22,7 +22,7 @@ pub const Debrief = campaign.Debrief; pub const DebriefChoice = campaign.DebriefChoice; pub const NextMission = campaign.NextMission; pub const CampaignCheckpoint = campaign.Checkpoint; -pub const revision: u16 = 47; +pub const revision: u16 = 48; pub const Team = engine.game.players.ArenaTeam; fn readTeam(reader: *std.Io.Reader) !Team { @@ -58,7 +58,7 @@ const team_scores_capacity = 1 + std.enums.values(Team).len * (@sizeOf(i32) + @s const arena_capacity = snapshot_header + team_scores_capacity + @max(DarkReign.encoded_size, Blast.encoded_size) + power_capacity; const campaign_capacity = snapshot_header - (inline_pilots - cooperative_slots) * (Ship.encoded_size - @sizeOf(u64)) + MissionView.capacity + CampaignCheckpoint.capacity; const roster_capacity = 8 + @sizeOf(u32) + slots * (@sizeOf(u64) + 2 + @as(CallSign, .{}).bytes.len); -pub const capacity = @max(@max(beacon_snapshot_capacity, arena_capacity, campaign_capacity) + ordnance.Status.capacity, roster_capacity, PilotPage.capacity, Combat.capacity, ordnance.Page.capacity, ScenePage.capacity, GatesPage.capacity, JumpPage.capacity, Scenery.capacity, Commands.capacity); +pub const capacity = @max(@max(beacon_snapshot_capacity, arena_capacity, campaign_capacity) + ordnance.Status.capacity, roster_capacity, PilotPage.capacity, Combat.capacity, ordnance.Page.capacity, 1 + mirror.capacity, GatesPage.capacity, JumpPage.capacity, Scenery.capacity, Commands.capacity); comptime { std.debug.assert(capacity < 1200); std.debug.assert(slots <= PilotPage.width * (PilotPage.max_extra + 1)); @@ -89,6 +89,12 @@ pub const Input = struct { /// acknowledged). earlier: [max_earlier]Flown = @splat(.{ .tick = 0, .command = .{} }), earlier_count: u8 = 0, + /// The serials of the latest object messages the client holds, newest first, 0 for none + /// (`mirror.Replica.serials`). + mirror_acks: [mirror.acks]u16 = @splat(0), + /// The host's epoch at which the client lost track of the host's objects, which asks the + /// host to start over (`mirror.Replica.lost`). + mirror_lost: ?u8 = null, /// Six steps and sixteen in all: the 120 ms and 320 ms that three and eight of the original's /// steps covered. @@ -1239,7 +1245,8 @@ pub const Message = union(enum(u8)) { shadow_notice: ShadowNotice, vampires_notice: VampiresNotice, uber_kill: UberKillNotice, - scene_page: ScenePage, + /// The host's objects, for one client (`mirror.Sender.page`): the rest of the message. + mirror: []const u8, crew_jump: CrewRequest, crew_land: CrewRequest, crew_eject: CrewRequest, @@ -1298,6 +1305,9 @@ pub const Message = union(enum(u8)) { } try flight_input.write(&w, input.command); try w.writeByte(@bitCast(input.step)); + for (input.mirror_acks) |serial| try w.writeInt(u16, serial, .little); + try w.writeByte(@intFromBool(input.mirror_lost != null)); + if (input.mirror_lost) |epoch| try w.writeByte(epoch); if (input.fire_for) |reuse| try w.writeInt(u32, reuse, .little); }, .view, .finished, .campaign_result => |view| { @@ -1416,7 +1426,10 @@ pub const Message = union(enum(u8)) { .combat => |combat| try writeCombat(&w, &combat), .weapon_order => |order| try ordnance.writeOrder(&w, order), .projectiles => |page| try page.write(&w), - .scene_page => |*page| try page.write(&w), + .mirror => |bytes| { + if (bytes.len > mirror.capacity) return error.InvalidMirror; + try w.writeAll(bytes); + }, .crew_jump, .crew_land, .crew_eject => |request| { try w.writeInt(u32, request.view_tick, .little); try w.writeInt(u32, request.reuse, .little); @@ -1515,6 +1528,12 @@ pub const Message = union(enum(u8)) { input.step = try readStep(&r); // Only an input with a tick can be told from its repeat, so only it may carry presses. if (input.tick == null and input.step.pressed()) return error.InvalidInput; + for (&input.mirror_acks) |*serial| serial.* = try r.takeInt(u16, .little); + input.mirror_lost = switch (try r.takeByte()) { + 0 => null, + 1 => try r.takeByte(), + else => return error.InvalidInput, + }; input.fire_for = if (r.bufferedLen() == 0) null else try r.takeInt(u32, .little); break :input .{ .input = input }; }, @@ -1696,7 +1715,7 @@ pub const Message = union(enum(u8)) { .combat => .{ .combat = try readCombat(&r) }, .weapon_order => .{ .weapon_order = try ordnance.readOrder(&r, engine.game.gameobj.max_objects) }, .projectiles => .{ .projectiles = try ordnance.Page.read(&r) }, - .scene_page => .{ .scene_page = try ScenePage.read(&r) }, + .mirror => .{ .mirror = try r.take(r.bufferedLen()) }, .crew_jump => .{ .crew_jump = .{ .view_tick = try r.takeInt(u32, .little), .reuse = try r.takeInt(u32, .little) } }, .crew_land => .{ .crew_land = .{ .view_tick = try r.takeInt(u32, .little), .reuse = try r.takeInt(u32, .little) } }, .crew_eject => .{ .crew_eject = .{ .view_tick = try r.takeInt(u32, .little), .reuse = try r.takeInt(u32, .little) } }, @@ -1953,8 +1972,9 @@ test "a final receipt names the applied tick" { } test "flight updates fit the direct-IP payload budget" { - // The command, and a byte for the step's presses and trigger. - const input_bytes = 32; + // The command, a byte for the step's presses and trigger, and what the client holds of the + // mission's objects. + const input_bytes = 41; // A fighter byte and a ship reuse count distinguish a respawn from a new admission. const full_snapshot_bytes = 13 + 113 * inline_pilots; const objective_snapshot_budget = full_snapshot_bytes + 79;