A blended engine loop: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: bands (line 24), update (line 58), loudness (line 80).
1/// Several loops of the same engine, recorded at different revs, crossfaded
2/// by one number so the change from one recording to the next is not heard.
3///
4/// Quoted by `blended_engine_loop.md` and shown whole in the Source tab.
5library;
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_audio/flutter3d_audio.dart';
9import 'package:flutter3d_showcase/src/demo/demo.dart';
11/// The `blended-engine-loop` page: an engine of three loops crossfaded by
12/// revs. Its check is that the bands always add up to full loudness.
13final class BlendedEngineLoopDemo extends ShowcaseDemo {
14 /// The engine's revs, 0 to 1.2 of the range the loops were recorded over.
15 double revs = 0.5;
17 late final AudioScene _scene;
18 late final BlendedLoop _engine;
21 Scene build(DemoContext context) {
22 _scene = AudioScene(backend: SilentBackend());
24 _engine = BlendedLoop(
25 scene: _scene,
26 bands: <LoopBand>[
27 LoopBand(
28 sound: const SoundDef(name: 'idle', asset: 'idle.wav', loop: true),
29 center: 0.2,
30 ),
31 LoopBand(
32 sound: const SoundDef(name: 'mid', asset: 'mid.wav', loop: true),
33 center: 0.6,
34 ),
35 LoopBand(
36 sound: const SoundDef(name: 'high', asset: 'high.wav', loop: true),
37 center: 1.0,
38 ),
39 ],
40 );
42 final material = RenderMaterial(
43 name: 'engine',
44 baseColor: LinearColor.fromSrgb(0.8, 0.3, 0.2, 1.0),
45 );
46 final node = MeshNode(
47 DeviceMesh.upload(context.device, SphereShape(segments: 16).build()),
48 material,
49 );
50 return Scene()
51 ..add(node)
52 ..add(
53 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
54 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
55 );
56 }
59 void update(DemoContext context, double dt) {
60 _engine.update(revs);
61 _scene.update(AudioListener());
62 }
65 List<DemoControl> controls(DemoContext context) => <DemoControl>[
66 SliderControl(
67 'Engine revs',
68 min: 0.0,
69 max: 1.2,
70 value: () => revs,
71 onChanged: (double v) => revs = v,
72 ),
73 ];
76 void verify(Scene scene, FrameResult frame) {
77 if (frame.drawCalls < 1) {
78 throw StateError('the engine marker was not drawn');
79 }
80 // The bands are normalised, so the total weight is one wherever the
81 // revs sit, including exactly between two bands.
82 revs = 0.4;
83 _engine.update(revs);
84 var total = 0.0;
85 for (var i = 0; i < 3; i++) {
86 total += _engine.gainOf(i);
87 }
88 if ((total - 1.0).abs() > 1e-6) {
89 throw StateError(
90 'the bands should always sum to full loudness, '
91 'summed to $total',
92 );
93 }
94 }
95}