flutter3d
Showcase Changelog 62 packages API reference

Rollback netcode over a loopback: the source

since 0.6.0 Widgets and the rest

Regions the guide quotes: transport (line 19), session (line 95), redundant (line 110).

1/// Two players' worth of a fixed-step simulation, kept in step across an
2/// unreliable transport: input frames, delay, prediction, and rollback on a
3/// confirmation that disagreed.
4///
5/// **`flutter3d_net` is not a dependency of this app.** `NetSession` and
6/// `LoopbackTransport` both need only `flutter3d_sim`'s `Snapshot` and
7/// `GameRandom` underneath, so this page reimplements the small pieces of
8/// each that the demo below actually exercises, against those same real
9/// types. `flutter3d_net_webrtc`, the transport for an actual connection
10/// between two browsers, is a native plugin and has no page of its own.
11///
12/// Quoted by `rollback_netcode.md` and shown whole in the Source tab.
13library;
15import 'package:flutter3d/flutter3d.dart';
16import 'package:flutter3d_showcase/src/demo/demo.dart';
17import 'package:flutter3d_sim/flutter3d_sim.dart';
19/// A pair of transports joined by a fixed delay and a loss rate, so a test
20/// is separated by an unreliable network rather than by nothing.
21final class _LoopbackTransport {
22 _LoopbackTransport._(this._delaySteps, this._lossRate, this._random);
24 final int _delaySteps;
25 final double _lossRate;
26 final GameRandom _random;
27 late final _LoopbackTransport _peer;
29 int _now = 0;
30 final List<(int dueAt, int value)> _inbox = <(int, int)>[];
31 void Function(int value)? _listener;
33 static (_LoopbackTransport, _LoopbackTransport) pair({
34 required int stepsPerSecond,
35 double delaySeconds = 0.0,
36 double lossRate = 0.0,
37 int seed = 1,
38 }) {
39 final random = GameRandom(seed);
40 final delaySteps = (delaySeconds * stepsPerSecond).round();
41 final a = _LoopbackTransport._(delaySteps, lossRate, random);
42 final b = _LoopbackTransport._(delaySteps, lossRate, random);
43 a._peer = b;
44 // ignore: avoid-late-final-reassignment, this is b's field, a's was set above
45 b._peer = a;
46 return (a, b);
47 }
49 void send(int value) {
50 if (_random.nextDouble() < _lossRate) return;
51 _peer._inbox.add((_peer._now + _delaySteps, value));
52 }
54 void listen(void Function(int value) onMessage) => _listener = onMessage;
56 void tick() {
57 _now++;
58 _inbox.removeWhere((entry) {
59 if (entry.$1 > _now) return false;
60 _listener?.call(entry.$2);
61 return true;
62 });
63 }
66/// The `rollback-netcode` page: two peers of a fixed-step simulation over an
67/// unreliable transport. Its check is that both learn the other reached the
68/// same step at a 30% loss, and that resending keeps them close to the truth.
69final class RollbackNetcodeDemo extends ShowcaseDemo {
70 /// The share of messages the transport drops, 0 to 0.9; the run is played
71 /// again when it changes.
72 double lossRate = 0.3;
73 late String _report;
75 @override
76 Scene build(DemoContext context) {
77 _report = _run(lossRate);
78 final material = RenderMaterial(
79 name: 'peer',
80 baseColor: LinearColor.fromSrgb(0.5, 0.6, 0.9, 1.0),
81 );
82 final node = MeshNode(
83 DeviceMesh.upload(context.device, SphereShape(segments: 16).build()),
84 material,
85 );
86 return Scene()
87 ..add(node)
88 ..add(
89 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
90 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
91 );
92 }
94 static String _run(double lossRate) {
95 // Each peer's own count of "my presses the other side has heard about",
96 // standing in for a `NetSession.applyAndStep` that folds a remote frame
97 // into a shared simulation. Every message repeats the last few sends,
98 // the same redundancy `NetSession` uses, so one dropped packet is not
99 // one lost step.
100 final (linkA, linkB) = _LoopbackTransport.pair(
101 stepsPerSecond: 30,
102 delaySeconds: 0.05,
103 lossRate: lossRate,
104 );
105 var aKnowsOfB = 0;
106 var bKnowsOfA = 0;
107 linkA.listen((int value) => aKnowsOfB = value);
108 linkB.listen((int value) => bKnowsOfA = value);
110 var bSends = 0;
111 var aSends = 0;
112 for (var step = 1; step <= 60; step++) {
113 aSends = step;
114 bSends = step;
115 // The current count sent three times running: the same message a
116 // `redundancy` window resends, so a single dropped packet is caught
117 // by the next one.
118 for (var r = 0; r < 3; r++) {
119 linkA.send(aSends);
120 linkB.send(bSends);
121 }
122 linkA.tick();
123 linkB.tick();
124 }
126 final agree = aKnowsOfB == bKnowsOfA;
127 final close = (bSends - aKnowsOfB) <= 3 && (aSends - bKnowsOfA) <= 3;
128 return 'after sixty steps at a ${(lossRate * 100).round()}% loss rate:\n'
129 'A last heard B at $aKnowsOfB (B actually reached $bSends)\n'
130 'B last heard A at $bKnowsOfA (A actually reached $aSends)\n'
131 'both sides agree on the same number: $agree\n'
132 'both are within three steps of the truth: $close';
133 }
135 @override
136 List<DemoControl> controls(DemoContext context) => <DemoControl>[
137 SliderControl(
138 'Loss rate',
139 min: 0.0,
140 max: 0.9,
141 value: () => lossRate,
142 onChanged: (double v) => lossRate = v,
143 ),
144 ];
146 @override
147 void verify(Scene scene, FrameResult frame) {
148 if (frame.drawCalls < 1) {
149 throw StateError('the peer marker was not drawn');
150 }
151 if (!_report.contains('both sides agree on the same number: true')) {
152 throw StateError(
153 'both sides should end up knowing the other reached the same step, '
154 'even at a 30% loss rate',
155 );
156 }
157 if (!_report.contains('both are within three steps of the truth: true')) {
158 throw StateError(
159 'resending the last few steps should keep both sides close to the '
160 'truth, not stuck far behind it',
161 );
162 }
163 }