flutter3d
Showcase Changelog 62 packages API reference

Playtest heatmaps: the source

since 1.0.0-rc.1 Simulation, audio and XR

Regions the guide quotes: game (line 14), record (line 115), heatmap (line 146), draw (line 279), check (line 331).

1/// Where a level's players went and where they were lost, read off their
2/// tapes rather than off anything their games reported: each run played
3/// again through the same simulation, its trail binned into a heatmap, and
4/// the heatmap drawn over the level.
5///
6/// Quoted by `playtest_heatmaps.md` and shown whole in the Source tab.
7library;
8
9import 'package:flutter3d/flutter3d.dart';
10import 'package:flutter3d_physics/flutter3d_physics.dart';
11import 'package:flutter3d_showcase/src/demo/demo.dart';
12import 'package:flutter3d_sim/flutter3d_sim.dart';
14/// A walker crossing a yard, steered by the stick. Stepping into the pit
15/// loses the run, and the walker stays where it fell — as a player sits on
16/// the "you died" screen — until the tape runs out.
17final class _Walk extends HeadlessRun {
18 _Walk(this.input, this.pit);
20 final InputState input;
22 /// The pit's corners on the ground, `(minX, minZ, maxX, maxZ)`.
23 final (double, double, double, double) pit;
24 final Vector3 _at = Vector3.zero();
26 @override
27 RunOutcome outcome = RunOutcome.playing;
29 @override
30 void step(double dt) {
31 if (outcome.isOver) return;
32 _at
33 ..x += input.moveAxis.x * 3.0 * dt
34 ..z += input.moveAxis.y * 3.0 * dt;
35 final (double x0, double z0, double x1, double z1) = pit;
36 if (_at.x >= x0 && _at.x < x1 && _at.z >= z0 && _at.z < z1) {
37 outcome = RunOutcome.lost;
38 }
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)}, ${outcome.name}';
60 @override
61 Map<String, Object?> get reading => <String, Object?>{'x': _at.x};
64/// The game, as `resimulate` starts it: the pit is the level's brush made
65/// of `pit`, so a level with the pit moved is another level.
66final class _WalkGame extends HeadlessGame {
67 const _WalkGame();
69 @override
70 String get name => 'yard';
72 @override
73 Map<String, GameAction> get buttons => const <String, GameAction>{};
75 @override
76 EntityRegistry registry() => EntityRegistry(const <EntityKind>[]);
78 @override
79 HeadlessRun start(HeadlessStart start) {
80 final level = start.level;
81 final input = start.input;
82 final Brush pit = level.brushes.firstWhere((b) => b.material == 'pit');
83 final Vector3 half = pit.size * 0.5;
84 return _Walk(input, (
85 pit.center.x - half.x,
86 pit.center.z - half.z,
87 pit.center.x + half.x,
88 pit.center.z + half.z,
89 ));
90 }
93Level _yard() => Level(
94 name: 'yard',
95 materials: <String, LevelMaterial>{
96 'stone': LevelMaterial(),
97 'pit': LevelMaterial(),
98 },
99 brushes: <Brush>[
100 Brush(
101 center: WorldPosition(6.5, -0.5, 0.0),
102 size: Vector3(15.0, 1.0, 6.0),
103 material: 'stone',
104 ),
105 // One metre square, a cell of the heatmap exactly.
106 Brush(
107 center: WorldPosition(5.5, 0.0, -0.5),
108 size: Vector3(1.0, 0.1, 1.0),
109 material: 'pit',
110 solid: false,
111 ),
112 ],
113);
115/// One player's tape: six seconds walking across the yard, drifting to one
116/// side by however much [seed] says. Written down as a game does — the tape
117/// before each step, a checkpoint after it.
118Demo _record(Level level, int seed) {
119 final input = InputState();
120 final run = const _WalkGame().start(
121 HeadlessStart(level: level, world: CollisionWorld(), input: input),
122 );
123 final start = run.save();
124 // Spread evenly over the yard's width, tape by tape, by the golden ratio.
125 final drift = (seed * 0.6180339887) % 1.0 * 0.7 - 0.35;
126 final recorder = InputTapeRecorder(seed: seed);
127 final trace = DigestTrace(every: 30);
128 for (var step = 1; step <= 360; step++) {
129 input.setStickAxis(0.75, drift);
130 recorder.record(input);
131 input.beginStep();
132 run.step(1.0 / 60.0);
133 trace.observe(step, run.save().toJson());
134 input.endStep();
135 }
136 return Demo(
137 level: 'levels/yard.json',
138 levelHash: level.digestHex,
139 start: start,
140 tape: recorder.tape,
141 buildStamp: 'showcase',
142 checkpoints: trace,
143 );
146/// Every tape played again into [level], and the trails of those that
147/// retraced their checkpoints binned into metre cells. A tape that parted
148/// from its own checkpoints, or was recorded in another level, gives no
149/// trail at all; [refused] counts them.
150({Heatmap map, int refused}) _heatmap(Level level, List<Demo> tapes) {
151 final trails = <HeatmapTrail>[];
152 var refused = 0;
153 for (var i = 0; i < tapes.length; i++) {
154 switch (resimulate(game: const _WalkGame(), level: level, demo: tapes[i])) {
155 case ResimulationRetraced(:final trail, :final outcome, :final steps):
156 trails.add(
157 HeatmapTrail(
158 run: i,
159 steps: steps,
160 outcome: outcome.name,
161 positions: trail,
162 endedBadly: outcome == RunOutcome.lost,
163 ),
164 );
165 case _:
166 refused++;
167 }
168 }
169 return (
170 map: Heatmap.bin(
171 trails,
172 outcomeNames: <String>[for (final o in RunOutcome.values) o.name],
173 ),
174 refused: refused,
175 );
178/// The `playtest-heatmaps` page: recorded runs replayed into a yard and
179/// binned into a heatmap of where players went and were lost. Its check is
180/// that every tape replays, runs are lost in the pit, a tape refuses a level
181/// it was not recorded in, and the heatmap is drawn.
182final class PlaytestHeatmapsDemo extends ShowcaseDemo {
183 /// How many tapes are recorded and replayed, from 4 up, in whole steps.
184 double tapes = 16;
186 late final Level _level;
187 late Heatmap _map;
188 late int _refused;
189 final Map<(int, int), MeshNode> _tiles = <(int, int), MeshNode>{};
190 final List<MeshNode> _deaths = <MeshNode>[];
192 static const int _most = 32;
194 @override
195 void configureView(DemoContext context) {
196 context.orbit
197 ..distance = 17.0
198 ..pitch = 0.95
199 ..yaw = 0.0;
200 context.orbit.target.setValues(6.5, 0.0, 0.0);
201 }
203 @override
204 Scene build(DemoContext context) {
205 _level = _yard();
206 final Scene scene = Scene()
207 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
208 ..ambientIntensity = 0.5 * LightNode.legacyUnit
209 ..add(
210 LightNode(name: 'sun', intensity: 2.2 * LightNode.legacyUnit)
211 ..setLocalForward(Vector3(-0.2, -1.0, -0.3)),
212 );
213 for (final Brush brush in _level.brushes) {
214 final bool pit = brush.material == 'pit';
215 scene.add(
216 MeshNode(
217 DeviceMesh.upload(
218 context.device,
219 CuboidShape(size: brush.size).build(),
220 ),
221 RenderMaterial(
222 name: brush.material,
223 baseColor: pit
224 ? LinearColor.fromSrgb(0.05, 0.05, 0.06, 1.0)
225 : LinearColor.fromSrgb(0.3, 0.32, 0.34, 1.0),
226 ),
227 name: brush.material,
228 )..setPositionFrom(
229 brush.center.toVector3Relative(WorldPosition.origin),
230 ),
231 );
232 }
233 // One flat tile a cell over the yard, coloured by the heatmap.
234 final DeviceMesh tile = DeviceMesh.upload(
235 context.device,
236 CuboidShape(size: Vector3(0.92, 0.04, 0.92)).build(),
237 );
238 for (var x = -1; x < 14; x++) {
239 for (var z = -3; z < 3; z++) {
240 final node = MeshNode(
241 tile,
242 RenderMaterial(name: 'cell $x,$z', lighting: LightingModel.unlit),
243 name: 'cell $x,$z',
244 )..setPosition(x + 0.5, 0.08, z + 0.5);
245 _tiles[(x, z)] = node;
246 scene.add(node);
247 }
248 }
249 final DeviceMesh ball = DeviceMesh.upload(
250 context.device,
251 SphereShape(segments: 12, rings: 6, radius: 0.12).build(),
252 );
253 for (var i = 0; i < _most; i++) {
254 final node = MeshNode(
255 ball,
256 RenderMaterial(
257 name: 'death',
258 baseColor: LinearColor.fromSrgb(1.0, 0.15, 0.1, 1.0),
259 ),
260 name: 'death $i',
261 );
262 _deaths.add(node);
263 scene.add(node);
264 }
265 _measure();
266 return scene;
267 }
269 void _measure() {
270 final List<Demo> recorded = <Demo>[
271 for (var seed = 1; seed <= tapes.round(); seed++) _record(_level, seed),
272 ];
273 final (:map, :refused) = _heatmap(_level, recorded);
274 _map = map;
275 _refused = refused;
276 _draw();
277 }
279 /// Each cell from cold to hot by how many samples landed in it, against
280 /// the hottest; a cell nobody walked through is not drawn. A red ball
281 /// where each run was lost.
282 void _draw() {
283 final int hottest = _hottest(_map).samples;
284 for (final MeshNode node in _tiles.values) {
285 node.isVisible = false;
286 }
287 for (final HeatmapCell cell in _map.cells) {
288 final MeshNode? node = _tiles[(cell.x, cell.z)];
289 if (node == null) continue;
290 final double t = cell.samples / hottest;
291 node
292 ..isVisible = true
293 ..material.baseColor = LinearColor.fromSrgb(
294 (t * 2.0).clamp(0.0, 1.0),
295 (1.0 - (t - 0.5).abs() * 2.0).clamp(0.15, 1.0),
296 (1.0 - t * 2.0).clamp(0.0, 1.0),
297 1.0,
298 );
299 }
300 for (var i = 0; i < _deaths.length; i++) {
301 final bool shown = i < _map.ends.length;
302 _deaths[i].isVisible = shown;
303 if (shown) {
304 _deaths[i].setPosition(_map.ends[i].x, 0.25, _map.ends[i].z);
305 }
306 }
307 }
309 static HeatmapCell _hottest(Heatmap map) => map.cells.reduce(
310 (HeatmapCell a, HeatmapCell b) => b.samples > a.samples ? b : a,
311 );
313 @override
314 List<DemoControl> controls(DemoContext context) => <DemoControl>[
315 SliderControl(
316 'Tapes (${_map.outcomes['lost']} lost, $_refused refused)',
317 min: 4,
318 max: _most.toDouble(),
319 divisions: _most - 4,
320 value: () => tapes,
321 onChanged: (double v) {
322 tapes = v;
323 _measure();
324 },
325 format: (double v) => v.round().toString(),
326 ),
327 ];
329 @override
330 void verify(Scene scene, FrameResult frame) {
331 // Every tape retraced its own checkpoints, and some were lost.
332 if (_refused != 0 || _map.runs != tapes.round()) {
333 throw StateError('$_refused of the tapes did not replay');
334 }
335 if (_map.ends.length < 3) {
336 throw StateError('only ${_map.ends.length} runs were lost in the pit');
337 }
338 // The hottest cell is the one every run was lost in: a player who fell
339 // stays there, sample after sample.
340 final HeatmapCell hottest = _hottest(_map);
341 for (final HeatmapEnd end in _map.ends) {
342 if ((end.x.floor(), end.z.floor()) != (hottest.x, hottest.z)) {
343 throw StateError(
344 'run ${end.run} was lost at (${end.x}, ${end.z}), and the hottest '
345 'cell is (${hottest.x}, ${hottest.z})',
346 );
347 }
348 }
349 // The same tapes in a yard with the pit moved are another level's runs.
350 final Level moved = Level.fromJson(_yard().toJson());
351 final Brush pit = moved.brushes.last;
352 moved.brushes.last = Brush.fromJson(<String, Object?>{
353 ...pit.toJson(),
354 'at': <double>[pit.center.x + 1.0, pit.center.y, pit.center.z],
355 });
356 if (resimulate(
357 game: const _WalkGame(),
358 level: moved,
359 demo: _record(_level, 1),
360 )
361 is! ResimulationLevelChanged) {
362 throw StateError('a tape replayed into a level it was not recorded in');
363 }
364 if (frame.drawCalls < 3) throw StateError('the heatmap was not drawn');
365 }