flutter3d
Showcase Changelog 62 packages API reference

Sharing runs and racing ghosts: the source

since 1.0.0-rc.1 Simulation, audio and XR

Regions the guide quotes: game (line 20), record (line 82), service (line 114), ghost (line 152), share (line 236), refuse (line 257), check (line 375).

1/// A run shared behind a short code and opened again as a ghost to race:
2/// the level, its hash and the run go into a bundle, the bundle goes through
3/// a sharing service, and what comes back is played to a pose track.
4///
5/// **The service is a map in this process.** `RunService` takes the
6/// function that carries its requests, so this page hands it one that
7/// answers the `v1/shares` routes from memory, in the shapes the reference
8/// server in `cloud/server` answers them. Nothing leaves the machine.
9///
10/// Quoted by `sharing_ghosts.md` and shown whole in the Source tab.
11library;
13import 'dart:convert';
14import 'dart:math' as math;
16import 'package:flutter3d/flutter3d.dart';
17import 'package:flutter3d_showcase/src/demo/demo.dart';
18import 'package:flutter3d_sim/flutter3d_sim.dart';
20/// A runner on a strip, steered by the stick. The run is won past the far
21/// end of the level's track, so the level is part of the run.
22final class _Runner extends HeadlessRun {
23 _Runner(this.input, this.finish);
25 final InputState input;
26 final double finish;
27 final Vector3 _at = Vector3.zero();
29 @override
30 RunOutcome outcome = RunOutcome.playing;
32 @override
33 void step(double dt) {
34 if (outcome.isOver) return;
35 _at
36 ..x += input.moveAxis.x * 4.0 * dt
37 ..z += input.moveAxis.y * 4.0 * dt;
38 if (_at.x >= finish) outcome = RunOutcome.won;
39 }
41 @override
42 Snapshot save() => Snapshot(<String, Object?>{
43 'x': _at.x,
44 'z': _at.z,
45 'outcome': outcome.name,
46 });
48 @override
49 WorldPosition get position => _at.toWorldPosition();
51 @override
52 WorldPosition get eye => _at.toWorldPosition();
54 @override
55 void aim(Vector3 out) => out.setValues(1.0, 0.0, 0.0);
57 @override
58 String get summary => 'at ${_at.x.toStringAsFixed(2)}';
60 @override
61 Map<String, Object?> get reading => <String, Object?>{'x': _at.x};
64/// The track, as a level document: one brush, whose far end is the finish.
65Level _track({double length = 16.0}) => Level(
66 name: 'strip',
67 materials: <String, LevelMaterial>{'stone': LevelMaterial()},
68 brushes: <Brush>[
69 Brush(
70 center: WorldPosition(length / 2, -0.25, 0.0),
71 size: Vector3(length, 0.5, 4.0),
72 material: 'stone',
73 ),
74 ],
75);
77_Runner _start(Level level, InputState input) {
78 final Brush strip = level.brushes.first;
79 return _Runner(input, strip.center.x + strip.size.x / 2);
82/// Plays [level] the way a person might — weaving down the strip — and
83/// writes it down as a game does: the tape before each step, a checkpoint
84/// after it. [steps] gets where the runner was after each step.
85Demo _record(Level level, List<Vector3> steps) {
86 final input = InputState();
87 final run = _start(level, input);
88 final start = run.save();
89 final recorder = InputTapeRecorder(seed: 1);
90 final trace = DigestTrace(every: 10);
91 steps.add(run.position.toVector3Relative(WorldPosition.origin));
92 for (var step = 1; !run.outcome.isOver; step++) {
93 // Inside the unit circle, so the input never rescales the stick and
94 // the tape holds exactly what the step read.
95 input.setStickAxis(0.8, 0.55 * math.sin(step * 0.06));
96 recorder.record(input);
97 input.beginStep();
98 run.step(1.0 / 60.0);
99 trace.observe(step, run.save().toJson());
100 input.endStep();
101 steps.add(run.position.toVector3Relative(WorldPosition.origin));
102 }
103 return Demo(
104 level: 'levels/strip.json',
105 levelHash: level.digestHex,
106 start: start,
107 tape: recorder.tape,
108 buildStamp: 'showcase',
109 checkpoints: trace,
110 simulation: SimulationVersion.engineOnly,
111 );
114/// The `v1/shares` routes, answered from a map: a bundle filed under a code
115/// made from its bytes, and opened by that code.
116RunTransport _inMemory(Map<String, Map<String, Object?>> store) =>
117 (RunRequest request) async {
118 final List<String> path = request.uri.pathSegments;
119 if (request.method == 'POST' && path.last == 'shares') {
120 final json = jsonDecode(request.body!) as Map<String, Object?>;
121 try {
122 // The server reads the bundle the way the client wrote it, and
123 // refuses one whose run is for another level just the same.
124 ShareBundle.fromJson(json);
125 } on ShareFormatException catch (e) {
126 return RunResponse(422, jsonEncode({'message': e.message}));
127 }
128 final String address = contentDigestHex(json);
129 final String code = address.substring(0, 6).toUpperCase();
130 store[code] = json;
131 return RunResponse(
132 201,
133 jsonEncode({
134 'code': code,
135 'address': address,
136 'status': ShareStatus.published.name,
137 }),
138 );
139 }
140 if (request.method == 'GET' && path.length >= 2) {
141 final Map<String, Object?>? bundle = store[path.last];
142 return bundle == null
143 ? RunResponse(
144 404,
145 jsonEncode({'message': 'no share "${path.last}"'}),
146 )
147 : RunResponse(200, jsonEncode({'bundle': bundle}));
148 }
149 return const RunResponse(404, '{"message":"no such route"}');
150 };
152/// Where the runner of a shared run was: [demo]'s tape played into a fresh
153/// run of [level], the position written down as it goes. Refused, with the
154/// reason, when the run was recorded in another version of the level.
155({GhostTape? ghost, String says}) _ghostOf(Level level, Demo demo) {
156 if (demo.levelHash != level.digestHex) {
157 return (
158 ghost: null,
159 says: 'the run was made in another version of this level',
160 );
161 }
162 final input = InputState();
163 final run = _start(level, input);
164 final recorder = GhostRecorder(hz: 30.0);
165 const dt = 1.0 / 60.0;
166 final String? refused = demo.refusalOn(SimulationVersion.engineOnly);
167 if (refused != null) return (ghost: null, says: refused);
168 final playback = InputTapePlayback(
169 demo,
170 simulation: SimulationVersion.engineOnly,
171 );
172 var step = 0;
173 recorder.record(
174 0.0,
175 position: run.position.toVector3Relative(WorldPosition.origin),
176 yaw: 0.0,
177 );
178 while (!playback.isFinished) {
179 playback.applyTo(input);
180 input.beginStep();
181 run.step(dt);
182 input.endStep();
183 step++;
184 recorder.record(
185 step * dt,
186 position: run.position.toVector3Relative(WorldPosition.origin),
187 yaw: 0.0,
188 );
189 }
190 return (
191 ghost: recorder.finish(step * dt),
192 says: 'a ghost of ${(step * dt).toStringAsFixed(1)} s',
193 );
196/// The `sharing-ghosts` page: a run shared behind a code and raced as a
197/// ghost. Its check is that the run comes back as a ghost that follows it to
198/// the finish and that an edited level is refused.
199final class SharingGhostsDemo extends ShowcaseDemo {
200 final List<Vector3> _original = <Vector3>[];
201 final Map<String, Map<String, Object?>> _store =
202 <String, Map<String, Object?>>{};
203 late final Level _level;
204 late final Level _edited;
205 String _code = '';
206 GhostTape? _ghost;
207 String _ghostSays = '';
208 String _bundleRefused = '';
209 String _editedSays = '';
211 /// Open the shared run in a version of the level with a longer track.
212 bool edited = false;
214 late final MeshNode _ghostNode;
215 late final MeshNode _you;
216 final GhostFrame _at = GhostFrame();
217 double _clock = 0.0;
218 late _Runner _live;
219 late InputState _liveInput;
221 @override
222 void configureView(DemoContext context) {
223 context.orbit
224 ..distance = 20.0
225 ..pitch = 0.55
226 ..yaw = 0.25;
227 context.orbit.target.setValues(8.0, 0.0, 0.0);
228 }
230 @override
231 Future<void> prepare(DemoContext context) async {
232 _level = _track();
233 _edited = _track(length: 18.0);
234 final Demo run = _record(_level, _original);
236 final service = RunService(
237 base: Uri.parse('https://shares.invalid/'),
238 transport: _inMemory(_store),
239 );
240 final ServiceAnswer<SharedBundle> filed = await service.share(
241 ShareBundle(game: 'showcase-strip', level: _level.toJson(), run: run),
242 );
243 if (filed case ServiceDone(value: final SharedBundle shared)) {
244 _code = shared.code;
245 }
246 // A friend types the code in.
247 final ServiceAnswer<ShareBundle> opened = await service.open(_code);
248 if (opened case ServiceDone(value: final ShareBundle bundle)) {
249 final (:ghost, :says) = _ghostOf(
250 Level.fromJson(bundle.level),
251 bundle.run!,
252 );
253 _ghost = ghost;
254 _ghostSays = says;
255 }
257 // The same run with the track made longer: refused before it leaves,
258 // and refused again by whoever opens it in that level.
259 try {
260 ShareBundle(game: 'showcase-strip', level: _edited.toJson(), run: run);
261 } on ShareFormatException catch (e) {
262 _bundleRefused = e.message;
263 }
264 _editedSays = _ghostOf(_edited, run).says;
265 }
267 @override
268 Scene build(DemoContext context) {
269 _ghostNode = MeshNode(
270 DeviceMesh.upload(
271 context.device,
272 SphereShape(segments: 20, rings: 10, radius: 0.45).build(),
273 ),
274 RenderMaterial(
275 name: 'ghost',
276 baseColor: LinearColor.fromSrgb(0.65, 0.85, 1.0, 0.4),
277 alphaMode: MaterialAlphaMode.blend,
278 depthWrite: false,
279 lighting: LightingModel.unlit,
280 ),
281 name: 'ghost',
282 );
283 _you = MeshNode(
284 DeviceMesh.upload(
285 context.device,
286 SphereShape(segments: 20, rings: 10, radius: 0.45).build(),
287 ),
288 RenderMaterial(
289 name: 'you',
290 baseColor: LinearColor.fromSrgb(0.9, 0.55, 0.25, 1.0),
291 ),
292 name: 'you',
293 );
294 _restart();
295 final Brush strip = _level.brushes.first;
296 return Scene()
297 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
298 ..ambientIntensity = 0.35 * LightNode.legacyUnit
299 ..add(
300 MeshNode(
301 DeviceMesh.upload(
302 context.device,
303 CuboidShape(size: strip.size).build(),
304 ),
305 RenderMaterial(
306 name: 'track',
307 baseColor: LinearColor.fromSrgb(0.4, 0.42, 0.45, 1.0),
308 ),
309 name: 'track',
310 )..setPositionFrom(
311 strip.center.toVector3Relative(WorldPosition.origin),
312 ),
313 )
314 ..add(
315 MeshNode(
316 DeviceMesh.upload(
317 context.device,
318 CuboidShape(size: Vector3(0.2, 0.05, 4.0)).build(),
319 ),
320 RenderMaterial(
321 name: 'finish',
322 baseColor: LinearColor.fromSrgb(0.9, 0.9, 0.9, 1.0),
323 ),
324 name: 'finish',
325 )..setPosition(strip.center.x + strip.size.x / 2 - 0.1, 0.02, 0.0),
326 )
327 ..add(_you)
328 ..add(_ghostNode)
329 ..add(
330 LightNode(name: 'sun', intensity: 2.6 * LightNode.legacyUnit)
331 ..setLocalForward(Vector3(-0.35, -1.0, -0.45)),
332 );
333 }
335 void _restart() {
336 _clock = 0.0;
337 _liveInput = InputState();
338 _live = _start(_level, _liveInput);
339 }
341 @override
342 void update(DemoContext context, double dt) {
343 _clock += dt;
344 // You run straight, and a little slower than the weaving ghost.
345 _liveInput.setStickAxis(0.75, 0.0);
346 _live.step(dt);
347 _you.setPosition(_live.position.x, 0.45, _live.position.z + 1.0);
348 final GhostTape? ghost = edited ? null : _ghost;
349 if (ghost != null && GhostPlayback(ghost).sampleAt(_clock, _at)) {
350 _ghostNode
351 ..isVisible = true
352 ..setPosition(_at.position.x, 0.45, _at.position.z - 1.0);
353 } else {
354 _ghostNode.isVisible = false;
355 }
356 if (_clock > 6.0) _restart();
357 }
359 @override
360 List<DemoControl> controls(DemoContext context) => <DemoControl>[
361 ToggleControl(
362 edited
363 ? 'Open it in the longer track: $_editedSays'
364 : 'Open it in the longer track (code $_code: $_ghostSays)',
365 value: () => edited,
366 onChanged: (bool v) {
367 edited = v;
368 _restart();
369 },
370 ),
371 ];
373 @override
374 void verify(Scene scene, FrameResult frame) {
375 // Filed, opened by its code, and played to a ghost.
376 final GhostTape? ghost = _ghost;
377 if (_code.length != 6 || ghost == null) {
378 throw StateError('the run did not come back as a ghost: "$_ghostSays"');
379 }
380 // A run for another version of the level is refused, both ways.
381 if (!_bundleRefused.contains('another version of the level') ||
382 !_editedSays.contains('another version')) {
383 throw StateError('the edited level was not refused');
384 }
385 // The ghost is where the original runner was, to the bit, at every
386 // sample, and it ends where the run ended.
387 for (final GhostFrame pose in ghost.poses) {
388 final Vector3 was = _original[(pose.timeSeconds * 60.0).round()];
389 if (pose.position != was) {
390 throw StateError(
391 'at ${pose.timeSeconds} s the ghost is at ${pose.position}, '
392 'the run was at $was',
393 );
394 }
395 }
396 // Thirty samples a second, so the last is within a step of the line.
397 if (ghost.poses.last.position.x < 15.9) {
398 throw StateError('the ghost did not reach the finish');
399 }
400 if (frame.drawCalls < 3) throw StateError('the race was not drawn');
401 }