Changing a running game's assets: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: files (line 28), tunable (line 48), decoders (line 64), register (line 117), swap (line 157), material (line 164), step (line 222), check (line 297).
1/// What a hot reload does to a running world: a texture and a model whose
2/// files changed are put in place of the old ones in the nodes already on
3/// screen, a material's fields are set from outside and survive the next
4/// swap, and a tunable changes through the input. The "files" are bytes this
5/// page holds, read through the same injected readers a game's assets are.
6///
7/// Quoted by `hot_swap.md` and shown whole in the Source tab.
8library;
10import 'dart:typed_data';
12import 'package:flutter3d/flutter3d.dart';
13import 'package:flutter3d_app/flutter3d_app.dart';
14import 'package:flutter3d_showcase/src/demo/demo.dart';
15import 'package:flutter3d_sim/flutter3d_sim.dart';
17/// The `hot-swap` page: a poster and a hull whose files are swapped while
18/// they are on screen. Its check is that both files are taken, the model is
19/// adopted into its node, and paint set from outside survives the swap.
20final class HotSwapDemo extends ShowcaseDemo {
21 /// The coordinator every `SceneSurface` registers with. It holds nothing
22 /// outside a debug build.
23 final HotSwap _hot = HotSwap.instance;
25 static const String _posterPath = 'assets/poster.png';
26 static const String _hullPath = 'assets_src/hull.glb';
28 /// The poster's "file": three bytes, the colour it decodes to.
29 Uint8List _posterFile = Uint8List.fromList(<int>[220, 40, 30]);
31 /// The model's "file": one byte, 1 red, 2 green, 3 blue.
32 Uint8List _hullFile = Uint8List.fromList(<int>[1]);
34 late final Scene _scene;
35 late final SwappableTexture _poster;
36 late final SwappableModel _hull;
37 late final ModelInstance _ship;
39 /// What the last swap did, for the line beside the viewport.
40 String _said = 'nothing swapped yet';
42 /// The two pixels [verify] reads, before and after each change.
43 final List<(List<int>, List<int>)> _shots = <(List<int>, List<int>)>[];
44 HotSwapReport? _firstSwap;
45 int _overridden = 0;
46 late final MeshNode _shipMeshBefore;
48 /// A number the game lets somebody change while it runs. It arrives
49 /// through the input, so a recorded run changes it at the same step.
50 final Tunables _tunables = Tunables(<String, double>{'spin': 0.6});
51 final InputState _input = InputState();
53 static const int _probeWidth = 96;
54 static const int _probeHeight = 64;
57 void configureView(DemoContext context) {
58 context.orbit
59 ..distance = 4.0
60 ..pitch = 0.1
61 ..yaw = 0.0;
62 }
64 /// What the texture file decodes to: a small square of its colour.
65 static TextureHandle? _decodePoster(GraphicsDevice device, Uint8List bytes) {
66 if (bytes.length != 3) return null;
67 final ByteData pixels = ByteData(4 * 4 * 4);
68 for (var i = 0; i < 16; i++) {
69 pixels
70 ..setUint8(i * 4, bytes[0])
71 ..setUint8(i * 4 + 1, bytes[1])
72 ..setUint8(i * 4 + 2, bytes[2])
73 ..setUint8(i * 4 + 3, 255);
74 }
75 return device.createTextureFromPixels(
76 width: 4,
77 height: 4,
78 format: TextureFormat.r8g8b8a8UNormInt,
79 pixels: pixels,
80 );
81 }
83 /// What the model file builds: one box called `hull`, in a material
84 /// called `hull paint` of the colour its byte names.
85 static Future<ModelAsset> _buildHull(GraphicsDevice device, Uint8List bytes) {
86 if (bytes.isEmpty || bytes.first < 1 || bytes.first > 3) {
87 throw const FormatException('not a model');
88 }
89 final Vector4 color = Vector4(0.08, 0.08, 0.08, 1.0)
90 ..[bytes.first - 1] = 0.9;
91 return ModelAsset.fromDocument(
92 PlainModelDocument(
93 surfaces: <ModelSurface>[
94 ModelSurface(
95 mesh: CuboidShape(size: Vector3.all(1.0)).build(),
96 materialIndex: 0,
97 ),
98 ],
99 materials: <SurfaceMaterial>[
100 SurfaceMaterial(
101 baseColor: _fromSrgb(color),
102 unlit: true,
103 name: 'hull paint',
104 ),
105 ],
106 nodes: <ModelNode>[
107 ModelNode(name: 'hull', surfaces: <int>[0]),
108 ],
109 ),
110 device: device,
111 );
112 }
115 Future<void> prepare(DemoContext context) async {
116 final GraphicsDevice device = context.device;
117 final TextureHandle first = _decodePoster(device, _posterFile)!;
118 _poster = _hot.registerTexture(
119 _posterPath,
120 first,
121 read: () async => _posterFile,
122 build: (Uint8List bytes) async => _decodePoster(device, bytes),
123 loadedFrom: _posterFile,
124 );
125 _hull = _hot.registerModel(
126 _hullPath,
127 await _buildHull(device, _hullFile),
128 read: () async => _hullFile,
129 build: (Uint8List bytes) => _buildHull(device, bytes),
130 device: device,
131 loadedFrom: _hullFile,
132 );
133 _scene = Scene()
134 ..add(
135 MeshNode(
136 DeviceMesh.upload(
137 device,
138 CuboidShape(size: Vector3(1.2, 1.2, 0.05)).build(),
139 ),
140 RenderMaterial(name: 'poster', lighting: LightingModel.unlit)
141 ..albedo = first,
142 name: 'poster',
143 )..setPosition(-0.9, 0.0, 0.0),
144 );
145 _ship = _hull.instantiate(_scene);
146 _ship.root.setPosition(0.9, 0.0, 0.0);
147 // What a `SceneSurface` registers for itself.
148 _hot
149 ..registerScene(_scene)
150 ..registerRenderer(context.renderer);
151 if (!_hot.enabled) {
152 _said = 'hot swap is off outside a debug build';
153 return;
154 }
155 _shipMeshBefore = _ship.meshes.single;
157 _shots.add(await _shoot(context));
158 // Both files change on "disk", and a hot reload runs the swap.
159 _posterFile = Uint8List.fromList(<int>[30, 60, 230]);
160 _hullFile = Uint8List.fromList(<int>[2]);
161 _firstSwap = await _hot.swap();
162 _shots.add(await _shoot(context));
164 // An inspector drags the paint to yellow, then the model is saved again:
165 // the override is put back on the material the new file brought.
166 _overridden = _hot.setMaterial('hull paint', <String, Object?>{
167 'baseColor': <double>[0.9, 0.8, 0.1, 1.0],
168 });
169 _hullFile = Uint8List.fromList(<int>[3]);
170 await _hot.swap();
171 _shots.add(await _shoot(context));
172 _said = _describe(_firstSwap!);
173 }
175 static String _describe(HotSwapReport report) =>
176 'textures ${report.textures}, models '
177 '${<String>[for (final ModelSwapReport m in report.models) '${m.path} in ${m.instances}']}'
178 '${report.refused.isEmpty ? '' : ', refused ${report.refused}'}';
180 /// The poster's and the hull's middle pixel, drawn through a camera of
181 /// the page's own.
182 Future<(List<int>, List<int>)> _shoot(DemoContext context) async {
183 final CameraNode eye =
184 CameraNode(projection: const PerspectiveProjection(fieldOfView: 0.8))
185 ..setPosition(0.0, 0.0, 4.0)
186 ..lookAt(Vector3.zero());
187 _scene.add(eye);
188 final FrameResult frame = context.renderer.render(
189 width: _probeWidth,
190 height: _probeHeight,
191 scene: _scene,
192 views: <CameraView>[CameraView(camera: eye)],
193 );
194 eye.removeFromParent();
195 final ByteData read = await context.device.readback(frame.frame);
196 final Matrix4 vp = eye.viewProjection(_probeWidth / _probeHeight);
197 List<int> at(Vector3 world) {
198 final Vector4 clip = vp.transformed(
199 Vector4(world.x, world.y, world.z, 1.0),
200 );
201 final int x = ((clip.x / clip.w + 1.0) * 0.5 * _probeWidth).floor();
202 final int y = ((1.0 - clip.y / clip.w) * 0.5 * _probeHeight).floor();
203 final int i = (y * _probeWidth + x) * 4;
204 return <int>[
205 read.getUint8(i),
206 read.getUint8(i + 1),
207 read.getUint8(i + 2),
208 ];
209 }
211 return (at(Vector3(-0.9, 0.0, 0.03)), at(Vector3(0.9, 0.0, 0.5)));
212 }
215 Scene build(DemoContext context) {
216 _scene
217 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
218 ..ambientIntensity = 0.3 * LightNode.legacyUnit;
219 return _scene;
220 }
223 void update(DemoContext context, double dt) {
224 _tunables.readFrom(_input);
225 _yaw += _tunables['spin'] * dt;
226 _ship.root.setRotationYawPitchRoll(_yaw, 0.0, 0.0);
227 _input.endStep();
228 }
230 double _yaw = 0.0;
233 void dispose() {
234 _hot
235 ..forgetTexture(_poster)
236 ..clearMaterial(name: 'hull paint');
237 }
239 Future<void> _swapNow() async {
240 _said = _describe(await _hot.swap());
241 }
244 List<DemoControl> controls(DemoContext context) => <DemoControl>[
245 ToggleControl(
246 'Repaint the poster file — $_said',
247 value: () => false,
248 onChanged: (bool v) {
249 final int r = _posterFile[0];
250 _posterFile = Uint8List.fromList(<int>[
251 _posterFile[2],
252 r,
253 _posterFile[1],
254 ]);
255 _swapNow();
256 },
257 ),
258 ToggleControl(
259 'Save the model in its next colour',
260 value: () => false,
261 onChanged: (bool v) {
262 _hullFile = Uint8List.fromList(<int>[_hullFile.first % 3 + 1]);
263 _swapNow();
264 },
265 ),
266 ToggleControl(
267 'Paint dragged to yellow (material.set)',
268 value: () => _overridden > 0,
269 onChanged: (bool v) {
270 if (v) {
271 _overridden = _hot.setMaterial('hull paint', <String, Object?>{
272 'baseColor': <double>[0.9, 0.8, 0.1, 1.0],
273 });
274 } else {
275 // The material keeps the yellow until its file is loaded again.
276 _hot.clearMaterial(name: 'hull paint');
277 _overridden = 0;
278 _hullFile = Uint8List.fromList(<int>[_hullFile.first % 3 + 1]);
279 _swapNow();
280 }
281 },
282 ),
283 SliderControl(
284 'Spin (a tunable)',
285 min: 0.0,
286 max: 3.0,
287 value: () => _tunables['spin'],
288 onChanged: (double v) => _input.tune('spin', v),
289 ),
290 ];
292 static int _strongest(List<int> rgb) =>
293 rgb.indexOf(rgb.reduce((int a, int b) => a > b ? a : b));
296 void verify(Scene scene, FrameResult frame) {
297 if (!_hot.enabled) throw StateError(_said);
298 final [(posterA, hullA), (posterB, hullB), (_, hullC)] = _shots;
299 // Before: a red poster and a red hull.
300 if (_strongest(posterA) != 0 || _strongest(hullA) != 0) {
301 throw StateError('before the swap: $posterA, $hullA');
302 }
303 // After one swap: the new texture in the poster's material, the new
304 // model in the node the scene already had.
305 final HotSwapReport report = _firstSwap!;
306 if (!report.textures.contains(_posterPath) ||
307 report.models.single.instances != 1) {
308 throw StateError('the swap did not take both files: $report');
309 }
310 if (_strongest(posterB) != 2 || _strongest(hullB) != 1) {
311 throw StateError('after the swap: $posterB, $hullB');
312 }
313 if (!identical(_ship.meshes.single, _shipMeshBefore)) {
314 throw StateError('the model was drawn in a new node, not adopted');
315 }
316 // The override outlived the next save of the model: yellow, not blue.
317 if (_overridden != 1 || hullC[0] <= hullC[2] || hullC[1] <= hullC[2]) {
318 throw StateError('the dragged paint did not survive the swap: $hullC');
319 }
320 // A tunable set through the input is read by the step that takes it.
321 _input.tune('spin', 2.0);
322 _tunables.readFrom(_input);
323 _input.endStep();
324 if (_tunables['spin'] != 2.0 || _tunables.toJson()['spin'] != 2.0) {
325 throw StateError('the tunable did not change: ${_tunables.values}');
326 }
327 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
328 }
329}
331/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
332LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);