flutter3d
Showcase Changelog 62 packages API reference

Rewinding: the source

since 0.7.0 Simulation, audio and XR

Regions the guide quotes: live (line 81), back (line 94), buffer (line 135), step (line 143), rewind (line 151).

1/// The last few seconds of a run, kept as one snapshot a second and the raw
2/// inputs between them, so a game can live them again for a kill camera or a
3/// rewind mechanic; and what each step of that run actually cost.
4///
5/// Quoted by `rewind.md` and shown whole in the Source tab.
6library;
7
8import 'dart:math' as math;
9
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_showcase/src/demo/demo.dart';
12import 'package:flutter3d_showcase/src/demo/scene_kit.dart';
13import 'package:flutter3d_sim/flutter3d_sim.dart';
15/// The `rewind` page: a runner whose last seconds are kept and lived again.
16/// Its check is that rewinding one second at ten steps a second lands on
17/// step 20 of a run at step 30.
18final class RewindDemo extends ShowcaseDemo {
19 late final String _report;
21 /// Whether the page rewinds by itself, four seconds after the last rewind.
22 bool automatic = true;
23 bool _rewindAsked = false;
25 late RewindBuffer _buffer;
26 late final MeshNode _runner;
27 late final MeshNode _ghost;
28 late final BarGauge _held;
29 double _x = 0.0;
30 double _owed = 0.0;
31 double _clock = 0.0;
32 double _sinceRewind = 0.0;
34 /// Metres to a unit of `x`.
35 static const double _scale = 0.25;
37 @override
38 void configureView(DemoContext context) {
39 context.orbit
40 ..distance = 12.0
41 ..pitch = 0.5
42 ..yaw = 0.0;
43 context.orbit.target.setValues(8.0, 0.0, 0.0);
44 }
46 @override
47 Scene build(DemoContext context) {
48 _report = _run();
49 _buffer = RewindBuffer(stepsPerSecond: 10, keyframeEvery: 5, history: 5);
50 _runner = ballNode(context, 'runner', 0.4, Vector4(0.5, 0.8, 0.6, 1.0));
51 _ghost = ballNode(context, 'ghost', 0.4, Vector4(0.45, 0.55, 0.95, 1.0));
52 _held = BarGauge(
53 context,
54 'history',
55 Vector4(0.7, 0.4, 0.8, 1.0),
56 Vector3(0.0, 0.0, 2.5),
57 height: 16.0,
58 );
59 return sceneOf(<SceneNode>[
60 blockNode(
61 context,
62 'track',
63 Vector3(18.0, 0.1, 3.0),
64 Vector4(0.34, 0.38, 0.36, 1.0),
65 at: Vector3(8.0, -0.05, 0.0),
66 ),
67 _runner,
68 _ghost,
69 ..._held.nodes,
70 ]);
71 }
73 @override
74 void update(DemoContext context, double dt) {
75 _clock += dt;
76 _sinceRewind += dt;
77 if (automatic && _sinceRewind > 4.0) _rewindAsked = true;
78 _owed += dt * 10.0;
79 while (_owed >= 1.0) {
80 _owed -= 1.0;
81 // One step: record the input, take a keyframe when one is due, run the
82 // step.
83 _buffer.recorder.tape.frames.add(InputFrame(stickX: 1.0));
84 if (_buffer.isKeyframeDue) {
85 _buffer.keyframe(Snapshot(<String, Object?>{'x': _x}));
86 }
87 _x += 1.0;
88 if (_x * _scale > 15.5) {
89 // Off the end of the track: start the run again.
90 _buffer.reset();
91 _x = 0.0;
92 }
93 }
94 // Where the run stood a second ago, and the way to get there: the state of
95 // the nearest keyframe, and the steps to play forward from it.
96 final RewindPoint? back = _buffer.rewindBy(1.0);
97 final double? then = back == null
98 ? null
99 : (back.snapshot.data['x']! as num).toDouble() + back.replayed;
100 if (_rewindAsked && back != null && then != null) {
101 _rewindAsked = false;
102 _sinceRewind = 0.0;
103 // Make that the present: what came after it is forgotten.
104 _buffer.cut(back);
105 _x = then;
106 }
107 _rewindAsked = false;
108 _runner.setPosition(
109 _x * _scale,
110 0.4 + 0.15 * (0.5 + 0.5 * math.sin(_clock * 12.0)),
111 0.0,
112 );
113 _ghost.isVisible = then != null;
114 if (then != null) _ghost.setPosition(then * _scale, 0.4, 1.2);
115 _held.set(_buffer.step / 160.0);
116 }
118 @override
119 List<DemoControl> controls(DemoContext context) => <DemoControl>[
120 ToggleControl(
121 'Rewind one second',
122 value: () => false,
123 onChanged: (bool v) {
124 if (v) _rewindAsked = true;
125 },
126 ),
127 ToggleControl(
128 'Rewind by itself',
129 value: () => automatic,
130 onChanged: (bool v) => automatic = v,
131 ),
132 ];
134 static String _run() {
135 final buffer = RewindBuffer(
136 stepsPerSecond: 10,
137 keyframeEvery: 5,
138 history: 5,
139 );
140 final timing = StepTimeTrace();
141 var x = 0.0;
143 for (var i = 0; i < 30; i++) {
144 buffer.recorder.tape.frames.add(InputFrame(stickX: 1.0));
145 if (buffer.isKeyframeDue) {
146 buffer.keyframe(Snapshot(<String, Object?>{'x': x}));
147 }
148 timing.record(buffer.step, () => x += 1.0);
149 }
151 // One second back from the present, thirty steps in at ten steps a
152 // second, lands on step 20.
153 final point = buffer.rewindBy(1.0)!;
155 return 'now at step ${buffer.step}, x=$x\n'
156 'one second back: step ${point.step}, '
157 'x=${point.snapshot.data['x']}, replaying ${point.replayed} inputs\n'
158 'mean step cost: '
159 '${timing.meanSeconds == null ? '-' : (timing.meanSeconds! * 1000.0).toStringAsFixed(3)} ms';
160 }
162 @override
163 void verify(Scene scene, FrameResult frame) {
164 if (frame.drawCalls < 1) {
165 throw StateError('the runner was not drawn');
166 }
167 if (!_report.contains('now at step 30') || !_report.contains('step 20')) {
168 throw StateError(
169 'a rewind of one second at ten steps a second should land on step 20 '
170 'of a run now at step 30',
171 );
172 }
173 }