flutter3d
Showcase Changelog 62 packages API reference

Portable determinism: the source

since 0.5.1 Simulation, audio and XR

Regions the guide quotes: live (line 110), trig (line 168), roll (line 173), resume (line 178).

1/// Determinism in a step: transcendental functions computed the same way on
2/// every platform, and a random generator whose state can be written down and
3/// restored to continue the same sequence.
4///
5/// Quoted by `portable_math.md` and shown whole in the Source tab.
6library;
7
8import 'dart:math' as math;
9
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_foundation/flutter3d_foundation.dart';
12import 'package:flutter3d_showcase/src/demo/demo.dart';
13import 'package:flutter3d_showcase/src/demo/scene_kit.dart';
14import 'package:flutter3d_sim/flutter3d_sim.dart';
16/// The `portable-math` page: a die rolled by a `GameRandom`. Its check is
17/// that two generators seeded alike roll the same sequence.
18final class PortableMathDemo extends ShowcaseDemo {
19 late final String _report;
21 /// Whether the die keeps rolling, 24 rolls a second.
22 bool rolling = true;
23 bool _rollAsked = false;
25 late GameRandom _dice;
26 late GameRandom _resumed;
27 final List<int> _seen = List<int>.filled(6, 0);
28 final List<int> _seenAgain = List<int>.filled(6, 0);
29 late final List<BarGauge> _bars;
30 late final List<BarGauge> _barsAgain;
31 late final MeshNode _hand;
32 late final MeshNode _lamp;
33 double _clock = 0.0;
34 double _owed = 0.0;
35 bool _agree = true;
37 static const int _dots = 16;
39 @override
40 void configureView(DemoContext context) {
41 context.orbit
42 ..distance = 13.0
43 ..pitch = 0.6
44 ..yaw = 0.0;
45 context.orbit.target.setValues(0.0, 0.5, 1.0);
46 }
48 @override
49 Scene build(DemoContext context) {
50 _report = _run();
51 _reseed();
52 BarGauge bar(String name, Vector4 ink, double x, double z) => BarGauge(
53 context,
54 name,
55 ink,
56 Vector3(x, 0.0, z),
57 height: 3.0,
58 width: 0.6,
59 vertical: true,
60 );
61 _bars = <BarGauge>[
62 for (var i = 0; i < 6; i++)
63 bar(
64 'face ${i + 1}',
65 Vector4(0.45, 0.65, 0.95, 1.0),
66 -2.5 + i * 1.0,
67 3.2,
68 ),
69 ];
70 _barsAgain = <BarGauge>[
71 for (var i = 0; i < 6; i++)
72 bar(
73 'again ${i + 1}',
74 Vector4(0.95, 0.65, 0.3, 1.0),
75 -2.5 + i * 1.0 + 0.35,
76 3.2,
77 ),
78 ];
79 _hand = ballNode(context, 'hand', 0.3, Vector4(0.95, 0.75, 0.3, 1.0));
80 _lamp = ballNode(
81 context,
82 'lamp',
83 0.3,
84 Vector4(0.35, 0.85, 0.4, 1.0),
85 at: Vector3(0.0, 0.3, 5.5),
86 );
87 return sceneOf(<SceneNode>[
88 floorNode(context, width: 12.0, depth: 12.0),
89 // A ring of points placed by `Portable`, and a hand that goes round it.
90 for (var i = 0; i < _dots; i++)
91 ballNode(
92 context,
93 'dot $i',
94 0.12,
95 Vector4(0.6, 0.65, 0.75, 1.0),
96 at: Vector3(
97 2.5 * Portable.sinCos(i * 2 * math.pi / _dots).cos,
98 0.12,
99 -1.5 + 2.5 * Portable.sinCos(i * 2 * math.pi / _dots).sin,
100 ),
101 ),
102 _hand,
103 _lamp,
104 for (final BarGauge g in _bars) ...g.nodes,
105 for (final BarGauge g in _barsAgain) ...g.nodes,
106 ]);
107 }
109 void _reseed() {
110 // One generator, and a second that is handed the first's state: from
111 // here the two must roll the same numbers for as long as anyone asks.
112 _dice = GameRandom(1234);
113 _resumed = GameRandom(1)..state = _dice.state;
114 _seen.fillRange(0, 6, 0);
115 _seenAgain.fillRange(0, 6, 0);
116 _agree = true;
117 }
119 @override
120 void update(DemoContext context, double dt) {
121 _clock += dt;
122 if (rolling) _owed += dt * 24.0;
123 if (_rollAsked) {
124 _rollAsked = false;
125 _owed += 30.0;
126 }
127 while (_owed >= 1.0) {
128 _owed -= 1.0;
129 final int a = _dice.nextInt(6);
130 final int b = _resumed.nextInt(6);
131 _seen[a]++;
132 _seenAgain[b]++;
133 if (a != b) _agree = false;
134 if (_seen.reduce(math.max) > 40) _reseed();
135 }
136 // The hand goes round the ring through `Portable`, not `dart:math`.
137 final SinCos at = Portable.sinCos(_clock);
138 _hand.setPosition(2.5 * at.cos, 0.3, -1.5 + 2.5 * at.sin);
139 for (var i = 0; i < 6; i++) {
140 _bars[i].set(_seen[i] / 40.0);
141 _barsAgain[i].set(_seenAgain[i] / 40.0);
142 }
143 _lamp.material.baseColor = LinearColor.fromSrgb(
144 _agree ? 0.35 : 0.9,
145 _agree ? 0.85 : 0.3,
146 _agree ? 0.4 : 0.3,
147 1.0,
148 );
149 }
151 @override
152 List<DemoControl> controls(DemoContext context) => <DemoControl>[
153 ToggleControl(
154 'Keep rolling',
155 value: () => rolling,
156 onChanged: (bool v) => rolling = v,
157 ),
158 ToggleControl(
159 'Roll thirty more',
160 value: () => false,
161 onChanged: (bool v) {
162 if (v) _rollAsked = true;
163 },
164 ),
165 ];
167 static String _run() {
168 // `Portable.sinCos` places a point on a circle without ever calling
169 // `dart:math`, whose trig is a platform's own library and disagrees
170 // between the Dart VM and a browser in the last few bits.
171 final direction = Portable.sinCos(0.7853981633974483); // pi / 4
173 final dice = GameRandom(1234);
174 final firstRoll = dice.nextInt(6) + 1;
175 final secondRoll = dice.nextInt(6) + 1;
176 final savedState = dice.state;
178 // A fresh generator given the saved state continues the exact same
179 // sequence, which is what lets a snapshot carry a simulation's dice
180 // forward across a save and a load.
181 final resumed = GameRandom(1)..state = savedState;
182 final thirdRoll = dice.nextInt(6) + 1;
183 final resumedRoll = resumed.nextInt(6) + 1;
185 return 'sin/cos of pi/4: ${direction.sin.toStringAsFixed(4)}, '
186 '${direction.cos.toStringAsFixed(4)}\n'
187 'rolls: $firstRoll, $secondRoll, then $thirdRoll\n'
188 'a generator resumed from the saved state rolls $resumedRoll next, '
189 'matching the original\'s $thirdRoll';
190 }
192 @override
193 void verify(Scene scene, FrameResult frame) {
194 if (frame.drawCalls < 1) {
195 throw StateError('the die was not drawn');
196 }
197 final dice = GameRandom(1234);
198 final expectedThird = () {
199 dice.nextInt(6);
200 dice.nextInt(6);
201 return dice.nextInt(6) + 1;
202 }();
203 if (!_report.contains('then $expectedThird')) {
204 throw StateError(
205 'a GameRandom seeded the same way should roll the '
206 'same sequence',
207 );
208 }
209 }