flutter3d
Showcase Changelog 62 packages API reference

Parties of more than two: the source

since 1.0.0-rc.1 Widgets and the rest

Regions the guide quotes: game (line 20), machines (line 40), tick (line 103), check (line 240).

1/// Four machines playing one game over a late, lossy wire, each rolling back
2/// when a guess about another turns out wrong, and a fifth that only watches
3/// the steps they have settled.
4///
5/// **All five are in this process.** `LoopbackParty` is the wire a test
6/// gives a party: messages arrive a few steps late, some never, the same
7/// ones for the same seed. Over a network the same objects sit on
8/// `PeerWire.party` over a relay's party room instead.
9///
10/// Quoted by `parties.md` and shown whole in the Source tab.
11library;
13import 'package:flame_multiplayer/flame_multiplayer.dart';
14import 'package:flutter3d/flutter3d.dart';
15import 'package:flutter3d_showcase/src/demo/demo.dart';
16import 'package:flutter3d_sim/flutter3d_sim.dart' show StateDigest;
18const int _players = 4;
20/// The whole game: how far round the track each player is, in centimetres.
21/// Each step moves every player by its own frame, and drags the first one
22/// by the last one's position, so a wrong guess about anybody moves
23/// somebody else too.
24List<int> _step(List<int> at, Map<int, Map<String, Object?>> frames) {
25 final next = List<int>.of(at);
26 for (final MapEntry(:key, :value) in frames.entries) {
27 next[key] += (value['dx'] as int?) ?? 0;
28 }
29 next[0] += next.last % 3;
30 return next;
33/// What machine [slot] presses at its [n]th step: changing often, so that
34/// guessing it from the last one is often wrong.
35int _press(int slot, int n) => 2 + (n * 7 + slot * 13) % 5;
37/// Everything on one wire: the four players' machines, the host's tape for
38/// spectators, and a spectator.
39final class _Party {
40 _Party({required int delay, required double loss, required int seed})
41 : wire = LoopbackParty(
42 _players + 1,
43 delaySteps: delay,
44 lossRate: loss,
45 seed: seed,
46 ) {
47 tape = PartyTape<List<int>>(wire: wire.wire(0), encode: (s) => s);
48 for (var slot = 0; slot < _players; slot++) {
49 var captures = 0;
50 machines.add(
51 RollbackSession<List<int>>(
52 wire: wire.wire(slot),
53 players: _players,
54 inputDelay: 2,
55 maxRollbackFrames: 12,
56 captureLocalFrame: () => <String, Object?>{
57 'dx': pressing ? _press(slot, captures++) : 0,
58 },
59 applyAndStep: (step) =>
60 states[slot] = _step(states[slot], step.frames),
61 save: () => List<int>.of(states[slot]),
62 restore: (state) => states[slot] = List<int>.of(state),
63 // The host hands what settles to the tape, and hears who watches.
64 onSettled: (s) {
65 settled[slot][s.step + 1] = s.after;
66 if (slot == 0) tape.settled(s);
67 },
68 onMessage: slot == 0 ? tape.hear : null,
69 ),
70 );
71 }
72 // The fifth slot plays no part in the rollback: it only watches.
73 watcher = PartyTapeWatcher<List<int>>(
74 wire: wire.wire(_players),
75 decode: (encoded) => List<int>.from(encoded! as List<Object?>),
76 restore: (state) => watched = state,
77 applyAndStep: (step) => watched = _step(watched, step.frames),
78 );
79 }
81 final LoopbackParty wire;
82 late final PartyTape<List<int>> tape;
83 late final PartyTapeWatcher<List<int>> watcher;
84 final List<RollbackSession<List<int>>> machines =
85 <RollbackSession<List<int>>>[];
87 /// What each machine thinks the game is now, guesses and all.
88 final List<List<int>> states = List<List<int>>.generate(
89 _players,
90 (_) => List<int>.filled(_players, 0),
91 );
93 /// The states each machine settled, by step.
94 final List<Map<int, List<int>>> settled = List<Map<int, List<int>>>.generate(
95 _players,
96 (_) => <int, List<int>>{},
97 );
99 List<int> watched = List<int>.filled(_players, 0);
100 bool pressing = true;
101 int ticks = 0;
103 /// One step on every machine, the spectator's turn after a while, and
104 /// then whatever the wire has due arrives.
105 void tick() {
106 for (final machine in machines) {
107 machine.stepOnce();
108 }
109 if (ticks >= 40) {
110 watcher
111 ..ask()
112 ..step();
113 }
114 wire.step();
115 ticks++;
116 }
119/// The `parties` page: four machines and a spectator playing one game over a
120/// late, lossy loopback wire. Its check is that guesses were wrong and rolled
121/// back, the four agree on what happened, and the spectator is on the settled
122/// tape.
123final class PartiesDemo extends ShowcaseDemo {
124 /// How many steps late messages arrive, 0 to 10; changing it starts the
125 /// party again at a loss of 0.1.
126 double delay = 4;
127 late _Party _party;
129 /// A row of four balls per machine, and a fifth row for the spectator.
130 final List<List<MeshNode>> _rows = <List<MeshNode>>[];
131 double _due = 0.0;
133 @override
134 void configureView(DemoContext context) {
135 context.orbit
136 ..distance = 15.0
137 ..pitch = 0.9
138 ..yaw = 0.0;
139 context.orbit.target.setValues(6.0, 0.0, 3.2);
140 }
142 @override
143 Scene build(DemoContext context) {
144 _party = _Party(delay: delay.round(), loss: 0.1, seed: 5);
145 final DeviceMesh ball = DeviceMesh.upload(
146 context.device,
147 SphereShape(segments: 16, rings: 8, radius: 0.25).build(),
148 );
149 final List<Vector4> colors = <Vector4>[
150 Vector4(0.9, 0.35, 0.2, 1.0),
151 Vector4(0.25, 0.55, 0.9, 1.0),
152 Vector4(0.95, 0.8, 0.2, 1.0),
153 Vector4(0.4, 0.8, 0.45, 1.0),
154 ];
155 final Scene scene = Scene()
156 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
157 ..ambientIntensity = 0.4 * LightNode.legacyUnit
158 ..add(
159 LightNode(name: 'sun', intensity: 2.4 * LightNode.legacyUnit)
160 ..setLocalForward(Vector3(-0.3, -1.0, -0.4)),
161 );
162 for (var row = 0; row <= _players; row++) {
163 final bool spectator = row == _players;
164 scene.add(
165 MeshNode(
166 DeviceMesh.upload(
167 context.device,
168 CuboidShape(size: Vector3(12.6, 0.1, 1.2)).build(),
169 ),
170 RenderMaterial(
171 name: 'lane $row',
172 baseColor: spectator
173 ? LinearColor.fromSrgb(0.2, 0.2, 0.25, 1.0)
174 : LinearColor.fromSrgb(0.36, 0.38, 0.4, 1.0),
175 ),
176 name: spectator ? 'spectator' : 'machine $row',
177 )..setPosition(6.0, -0.05, row * 1.6),
178 );
179 _rows.add(<MeshNode>[
180 for (var p = 0; p < _players; p++)
181 MeshNode(
182 ball,
183 RenderMaterial(name: 'player $p', baseColor: _fromSrgb(colors[p])),
184 name: 'row $row player $p',
185 ),
186 ]);
187 _rows.last.forEach(scene.add);
188 }
189 _place();
190 return scene;
191 }
193 /// Each row as its machine has the game, each player along its lane at
194 /// its distance round a twelve-metre track.
195 void _place() {
196 for (var row = 0; row <= _players; row++) {
197 final List<int> at = row == _players
198 ? _party.watched
199 : _party.states[row];
200 for (var p = 0; p < _players; p++) {
201 _rows[row][p].setPosition(
202 (at[p] % 1200) / 100.0,
203 0.25,
204 row * 1.6 + (p - 1.5) * 0.25,
205 );
206 }
207 }
208 }
210 @override
211 void update(DemoContext context, double dt) {
212 // Thirty steps a second, so the rollbacks can be seen as jumps.
213 _due += dt;
214 while (_due >= 1 / 30) {
215 _due -= 1 / 30;
216 _party.tick();
217 }
218 _place();
219 }
221 @override
222 List<DemoControl> controls(DemoContext context) => <DemoControl>[
223 SliderControl(
224 'Steps late (${_party.machines.fold(0, (int a, m) => a + m.stepsRerun)} '
225 'rerun)',
226 min: 0,
227 max: 10,
228 divisions: 10,
229 value: () => delay,
230 onChanged: (double v) {
231 delay = v;
232 _party = _Party(delay: v.round(), loss: 0.1, seed: 5);
233 },
234 format: (double v) => v.round().toString(),
235 ),
236 ];
238 @override
239 void verify(Scene scene, FrameResult frame) {
240 // Four seconds of play four steps late, a tenth of the messages lost;
241 // then everybody lets go, and the wire is given time to catch up.
242 final party = _Party(delay: 4, loss: 0.1, seed: 5);
243 for (var i = 0; i < 240; i++) {
244 party.tick();
245 }
246 party.pressing = false;
247 for (var i = 0; i < 40; i++) {
248 party.tick();
249 }
250 final int reruns = party.machines.fold(0, (a, m) => a + m.stepsRerun);
251 if (reruns == 0) throw StateError('no guess was ever wrong');
252 final Set<int> digests = <int>{
253 for (final List<int> state in party.states) StateDigest.of(state),
254 };
255 if (digests.length != 1) {
256 throw StateError('the four machines ended on $digests');
257 }
258 // And that one is the game played on a wire that is never late and
259 // never loses anything.
260 final perfect = _Party(delay: 0, loss: 0.0, seed: 5);
261 for (var i = 0; i < 280; i++) {
262 if (i == 240) perfect.pressing = false;
263 perfect.tick();
264 }
265 if (StateDigest.of(perfect.states[0]) != digests.single) {
266 throw StateError('the four agree on something that never happened');
267 }
268 // Every step any two machines settled, they settled the same.
269 for (final MapEntry(key: step, value: state) in party.settled[0].entries) {
270 for (var slot = 1; slot < _players; slot++) {
271 final List<int>? other = party.settled[slot][step];
272 if (other != null && StateDigest.of(other) != StateDigest.of(state)) {
273 throw StateError('slot $slot settled step $step differently');
274 }
275 }
276 }
277 // The spectator, who came late, is where the players settled.
278 final int? next = party.watcher.next;
279 final List<int>? truth = next == null ? null : party.settled[0][next];
280 if (truth == null ||
281 StateDigest.of(party.watched) != StateDigest.of(truth)) {
282 throw StateError('the spectator is not on the settled tape');
283 }
284 if (frame.drawCalls < 5) throw StateError('the lanes were not drawn');
285 }
288/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
289LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);