Heat and fire: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: bench (line 71), wind (line 143), douse (line 159), step (line 173), glow (line 262), flames (line 291), check (line 351).
1/// A wooden board and a steel one either side of a block of stone at a
2/// thousand degrees. The wood heats, catches, burns and loses mass; the
3/// steel heats as well and never catches; water put on the wood puts it
4/// out. The page steps the core's world itself; the effects package's
5/// elements, adopting it, draw the fire.
6///
7/// Quoted by `heat_and_fire.md` and shown whole in the Source tab.
8library;
10import 'dart:math' as math;
11import 'dart:typed_data';
13import 'package:flutter/foundation.dart' show visibleForTesting;
14import 'package:flutter/services.dart' show rootBundle;
15import 'package:flutter3d/flutter3d.dart';
16import 'package:flutter3d_effects/flutter3d_effects.dart';
17import 'package:flutter3d_elements/flutter3d_elements.dart';
18import 'package:flutter3d_matter/flutter3d_matter.dart';
19import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
20import 'package:flutter3d_showcase/src/demo/demo.dart';
22/// The `heat-and-fire` page: wood and steel boards beside a hot stone on
23/// the physics core. Its check is that the wood catches, burns mass and
24/// keeps burning, and that the steel warms.
25final class HeatAndFireDemo extends ShowcaseDemo {
26 NativeWorld? _world;
27 Elements? _elements;
28 Scene? _scene;
29 late TrackedBody _heaterBody, _woodBody, _steelBody;
30 NativeBody get _heater => _heaterBody.native;
31 NativeBody get _wood => _woodBody.native;
32 NativeBody get _steel => _steelBody.native;
34 /// Why there is no fire, or null when the core started.
35 String? fallback;
37 /// The uniform wind, m/s along x, on top of the grid's.
38 double wind = 0.0;
40 /// Seconds of the world since the boards were put up.
41 double _clock = 0.0;
43 /// When the wood caught, and when it was put out; null until then.
44 double? _caught;
45 double? _doused;
47 late RenderMaterial _steelLook;
48 late MeshNode _woodNode;
49 late MeshNode _steelNode;
51 /// Each frame steps the world by this much: twenty times as fast as the
52 /// clock on the wall, so a board takes seconds to catch and not minutes.
53 static const double _lapse = 1 / 3;
55 /// The heater's temperature, K: stone at a bright orange.
56 static const double _hot = 1300.0;
58 /// Half a board: twenty centimetres square and four thick.
59 static Vector3 get _board => Vector3(0.02, 0.1, 0.1);
60 static const double _apart = 0.3;
63 void configureView(DemoContext context) {
64 context.orbit
65 ..distance = 1.6
66 ..pitch = 0.35
67 ..yaw = 0.3;
68 context.orbit.target.setValues(0.0, 0.2, 0.0);
69 }
71 /// The world, once, and the elements that draw its fires, adopting it:
72 /// the page steps it itself, faster than the clock.
74 Future<void> prepare(DemoContext context) async {
75 try {
76 final world = NativeWorld();
77 _world = world;
78 final scene = _scene = Scene();
79 _elements = await Elements.adopt(
80 world,
81 device: context.device,
82 renderer: context.renderer,
83 scene: scene,
84 load: rootBundle.load,
85 quality: const ElementsQuality(
86 liquid: LiquidDetail.light,
87 fire: FireDetail.light,
88 ),
89 );
90 } on Object catch (e) {
91 _world?.dispose();
92 _world = null;
93 fallback = physicsCoreLoaded
94 ? '$e'
95 : 'the core is not loaded in this browser yet';
96 }
97 }
99 /// The heater and the two boards, all fixed: nothing here has to move to
100 /// burn. The heater has no mass, which makes it a reservoir: whatever it
101 /// gives, it stays at its temperature.
102 void _setUp() {
103 final elements = _elements!;
104 for (final TrackedBody body in _bodies) {
105 elements.remove(body);
106 }
107 _heaterBody = elements.addBody(
108 Solid.box(
109 Vector3.all(0.15),
110 material: NativeMaterial.stone(),
111 density: 0,
112 ),
113 at: Vector3(0.0, 0.15, 0.0),
114 type: NativeBodyType.fixed,
115 );
116 elements.world.setTemperature(_heater, _hot);
117 // A fixed body's mass is its thermal mass, and what burns away.
118 _woodBody = elements.addBody(
119 Solid.box(_board, material: NativeMaterial.wood(), density: 500.0),
120 at: Vector3(-_apart, 0.1, 0.0),
121 type: NativeBodyType.fixed,
122 look: _woodNode,
123 );
124 _steelBody = elements.addBody(
125 Solid.box(_board, material: NativeMaterial.steel(), density: 7800.0),
126 at: Vector3(_apart, 0.1, 0.0),
127 type: NativeBodyType.fixed,
128 look: _steelNode,
129 );
130 _bodies = <TrackedBody>[_heaterBody, _woodBody, _steelBody];
131 _setWind();
132 _clock = 0.0;
133 _caught = null;
134 _doused = null;
135 }
137 List<TrackedBody> _bodies = const <TrackedBody>[];
139 /// What the steps since the elements last drew said happened: the page
140 /// reads the world's events, and hands them on.
141 final List<NativeEvent> _said = <NativeEvent>[];
143 /// A breeze that grows with height, from still air at the floor to a
144 /// metre and a half a second a metre up, read trilinearly between the
145 /// grid's two samples; and the uniform [wind] added everywhere.
146 void _setWind() {
147 _world!
148 ..setWindGrid(
149 origin: Vector3.zero(),
150 cell: 1.0,
151 nx: 1,
152 ny: 2,
153 nz: 1,
154 velocities: Float32List.fromList(<double>[0, 0, 0, 1.5, 0, 0]),
155 )
156 ..wind = Vector3(wind, 0.0, 0.0);
157 }
159 /// Half a litre of water on the wood, and the heater let cool to the air.
160 /// The water holds the board at its boiling point, below where wood
161 /// burns, so the next step puts the fire out.
162 void _douse() {
163 final NativeWorld world = _world!;
164 world
165 ..addWater(_wood, 0.5)
166 ..setTemperature(_heater, world.airTemperature);
167 _doused = _clock;
168 }
170 /// One step of [dt]: the world on, and what it said happened. The core
171 /// passes the heater's radiation to the boards itself.
172 List<NativeEvent> _advance(double dt) {
173 _world!.step(dt);
174 final List<NativeEvent> said = _world!.readEvents();
175 _said.addAll(said);
176 final List<NativeEvent> fire = <NativeEvent>[
177 for (final NativeEvent e in said)
178 if (e.kind == NativeEventKind.ignited ||
179 e.kind == NativeEventKind.extinguished ||
180 e.kind == NativeEventKind.burntOut)
181 e,
182 ];
183 _clock += dt;
184 if (fire.any((e) => e.body == _wood && e.kind == NativeEventKind.ignited)) {
185 _caught ??= _clock;
186 }
187 return fire;
188 }
191 void dispose() {
192 // The elements adopted the world, and leave it to the page.
193 _elements?.dispose();
194 _world?.dispose();
195 }
198 Scene build(DemoContext context) {
199 final DeviceMesh board = DeviceMesh.upload(
200 context.device,
201 CuboidShape(size: _board * 2.0).build(),
202 );
203 _steelLook = RenderMaterial(
204 name: 'steel',
205 baseColor: LinearColor.fromSrgb(0.6, 0.62, 0.65, 1.0),
206 metallic: 0.8,
207 roughness: 0.4,
208 );
209 // The wood chars and glows as it burns, as the elements draw it.
210 _woodNode = MeshNode(
211 board,
212 RenderMaterial(
213 name: 'wood',
214 baseColor: LinearColor.fromSrgb(0.55, 0.36, 0.2, 1.0),
215 roughness: 0.8,
216 ),
217 name: 'wood',
218 )..setPosition(-_apart, 0.1, 0.0);
219 _steelNode = MeshNode(board, _steelLook, name: 'steel')
220 ..setPosition(_apart, 0.1, 0.0);
221 final Scene scene = (_scene ?? Scene())
222 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
223 ..ambientIntensity = 0.3 * LightNode.legacyUnit
224 ..add(
225 LightNode(name: 'sun', intensity: 2.0 * LightNode.legacyUnit)
226 ..setLocalForward(Vector3(-0.3, -0.7, -0.5)),
227 )
228 ..add(
229 MeshNode(
230 DeviceMesh.upload(
231 context.device,
232 CuboidShape(size: Vector3(1.2, 0.04, 0.6)).build(),
233 ),
234 RenderMaterial(
235 name: 'floor',
236 baseColor: LinearColor.fromSrgb(0.35, 0.35, 0.37, 1.0),
237 ),
238 name: 'floor',
239 )..setPosition(0.0, -0.02, 0.0),
240 )
241 ..add(
242 MeshNode(
243 DeviceMesh.upload(
244 context.device,
245 CuboidShape(size: Vector3.all(0.3)).build(),
246 ),
247 RenderMaterial(
248 name: 'heater',
249 baseColor: LinearColor.fromSrgb(0.4, 0.2, 0.15, 1.0),
250 emissive: LinearColor(1.0, 0.35, 0.08),
251 emissiveStrength: 2.0 * RenderMaterial.defaultEmissiveStrength,
252 ),
253 name: 'heater',
254 )..setPosition(0.0, 0.15, 0.0),
255 )
256 ..add(_woodNode)
257 ..add(_steelNode);
258 if (_elements != null) _setUp();
259 return scene;
260 }
262 /// The steel glows as hot metal does: a grey body at its surface's
263 /// temperature, ε·σT⁴·η(T)/π candela a square metre, η the lumens a
264 /// radiated watt is worth at T, in the renderer's units — nothing to see
265 /// at the room's temperature, a dull red past 800 K. Its surface's
266 /// temperature is what the core says, held at boiling while water is on
267 /// it.
268 void _look(RenderMaterial look, NativeBody body) {
269 final NativeWorld world = _world!;
270 final double t = world.surfaceTemperatureOf(body);
271 final double nits =
272 NativeMaterial.steel().emissivity *
273 stefanBoltzmann *
274 t *
275 t *
276 t *
277 t *
278 Blackbody.efficacy(t) /
279 math.pi;
280 final LinearColor color = Blackbody.color(t);
281 final double y = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
282 // Over `bulbAtOneMeter` and drawn at the default emissive strength: about 29 times the
283 // true luminance, the gain `FireView` draws its flames with, so the hot
284 // block glows beside them as it would beside a fire.
285 look.emissive = color.scaled(
286 y > 0.0 ? nits / Photometric.bulbAtOneMeter / y : 0.0,
287 );
288 look.emissiveStrength = 1.0 * RenderMaterial.defaultEmissiveStrength;
289 }
291 /// The fires drawn as the world has them: the elements adopted the world,
292 /// so they draw and do not step it. Each flame stands on the patch alight
293 /// and is as long as the core says, its smoke and embers carried by the
294 /// wind where it is, its light the radiant share of its heat.
295 void _flicker(double seconds, Vector3 eye) {
296 _elements?.update(seconds, eye: eye, events: List<NativeEvent>.of(_said));
297 _said.clear();
298 }
301 void update(DemoContext context, double dt) {
302 if (_world == null) return;
303 _advance(_lapse);
304 // Burnt for a minute, it is put out; half a minute later it all starts
305 // again.
306 final double? caught = _caught;
307 if (caught != null && _doused == null && _clock - caught > 60.0) _douse();
308 final double? doused = _doused;
309 if (doused != null && _clock - doused > 30.0) _setUp();
310 _look(_steelLook, _steel);
311 _flicker(dt, context.camera.readScenePosition());
312 }
315 List<DemoControl> controls(DemoContext context) => <DemoControl>[
316 SliderControl(
317 fallback == null ? 'Wind' : 'Wind (unavailable: $fallback)',
318 min: 0.0,
319 max: 8.0,
320 value: () => wind,
321 onChanged: (double v) {
322 wind = v;
323 if (_world != null) _setWind();
324 },
325 format: (double v) => '${v.toStringAsFixed(1)} m/s',
326 ),
327 ToggleControl(
328 'Water on the wood',
329 value: () => _doused != null,
330 onChanged: (bool v) {
331 if (v && _world != null && _doused == null) _douse();
332 },
333 ),
334 ToggleControl(
335 'Start again',
336 value: () => false,
337 onChanged: (bool v) {
338 if (v && _world != null) _setUp();
339 },
340 ),
341 ];
343 /// The wood's and the steel's temperatures, K, for a test that reads them.
345 (double wood, double steel) get temperatures =>
346 (_world!.temperatureOf(_wood), _world!.temperatureOf(_steel));
349 void verify(Scene scene, FrameResult frame) {
350 if (_world == null) throw StateError('the core did not start: $fallback');
351 // From cold, in still air but for the grid's breeze, a second a step.
352 wind = 0.0;
353 _setUp();
354 final NativeWorld world = _world!;
355 final List<NativeEvent> said = <NativeEvent>[];
356 var steps = 0;
357 while (_caught == null && steps < 600) {
358 said.addAll(_advance(1.0));
359 steps++;
360 }
361 if (_caught == null) throw StateError('the wood never caught');
362 // Burning, it loses what it gives off, over a patch that is still
363 // small twenty seconds after it caught.
364 final double atIgnition = world.massOf(_wood);
365 for (var i = 0; i < 20; i++) {
366 said.addAll(_advance(1.0));
367 }
368 if (!world.isBurning(_wood)) throw StateError('the wood went out');
369 if (world.massOf(_wood) >= atIgnition) {
370 throw StateError('the wood burnt nothing: ${world.massOf(_wood)} kg');
371 }
372 // The steel had the same heater, and was warmed by it, but never caught:
373 // with fifteen times the wood's mass it warms slowly, a few kelvin in
374 // the half minute the wood took to catch and burn.
375 if (world.temperatureOf(_steel) <= world.airTemperature + 1.0) {
376 throw StateError('the steel was never warmed');
377 }
378 if (world.isBurning(_steel) || said.any((e) => e.body == _steel)) {
379 throw StateError('the steel caught fire');
380 }
381 // Water puts the fire out on the next step, and says so.
382 _douse();
383 final List<NativeEvent> after = _advance(1.0);
384 if (world.isBurning(_wood) ||
385 !after.any(
386 (e) => e.body == _wood && e.kind == NativeEventKind.extinguished,
387 )) {
388 throw StateError('the water did not put the fire out');
389 }
390 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
391 }
392}