flutter3d
Showcase Changelog 62 packages API reference

Cutscenes: the source

since 1.0.0-rc.1 Simulation, audio and XR

Regions the guide quotes: answer (line 23), document (line 72), read (line 131), bus (line 149), step (line 223), skip (line 228), camera (line 247), fade (line 264), check (line 291).

1/// A short cutscene as a document: the camera on a curve through four keys,
2/// two subtitles, a fade in from near black, and two signals the game answers by
3/// lighting a lamp and raising a gate. Skipped, it ends where watching it
4/// ends.
5///
6/// Quoted by `cutscenes.md` and shown whole in the Source tab.
7library;
8
9import 'dart:math' as math;
11import 'package:flutter/foundation.dart' show listEquals, visibleForTesting;
12import 'package:flutter3d/flutter3d.dart';
13import 'package:flutter3d_camera/flutter3d_camera.dart' show SequenceView;
14import 'package:flutter3d_showcase/src/demo/demo.dart';
15import 'package:flutter3d_sim/flutter3d_sim.dart';
17/// What the cutscene changes in the game: what its signals did.
18final class _Stage {
19 bool lampLit = false;
20 double gateHeight = 0.0;
21 final List<String> heard = <String>[];
23 /// The game's answer to each signal, subscribed on the bus the cutscene
24 /// publishes onto: heard in order, on the step it fired.
25 Registration listenTo(EventRegistry bus) => bus.onStep<SequenceSignal>(
26 'cutscenes.answer',
27 (Delivered<SequenceSignal> delivered) {
28 final SequenceSignal signal = delivered.event;
29 heard.add(signal.signal);
30 switch (signal.signal) {
31 case 'lamp':
32 lampLit = true;
33 case 'gate':
34 gateHeight = (signal.data['height'] as num?)?.toDouble() ?? 2.0;
35 }
36 },
37 );
39 bool sameAs(_Stage other) =>
40 lampLit == other.lampLit &&
41 gateHeight == other.gateHeight &&
42 listEquals(heard, other.heard);
44 @override
45 String toString() => 'lamp $lampLit, gate $gateHeight, heard $heard';
48/// The `cutscenes` page: a cutscene read from a document, with a lamp and a
49/// gate the game raises on its signals. Its check is that skipping ends where
50/// watching ends, the signals are answered, a restore fires nothing again,
51/// and the camera and the fade end where written.
52final class CutscenesDemo extends ShowcaseDemo {
53 late final Sequence _sequence;
55 /// What the cutscene shows: the camera, the fade and the subtitle of a
56 /// frame, read off the player the step moves.
57 late final SequenceView _view;
58 late SequencePlayer _player;
59 late _Stage _stage;
61 late final LightNode _lamp;
62 late final MeshNode _gate;
63 late final MeshNode _flame;
65 double _carry = 0.0;
66 double _after = 0.0;
68 /// The subtitle showing, for whoever draws text over the picture.
69 @visibleForTesting
70 String? get subtitle => _view.subtitleOf(_player);
72 /// Seconds in the document; every moment is turned into the step it
73 /// falls on at the game's rate when it is read.
74 static const Map<String, Object?> document = <String, Object?>{
75 'seconds': 8,
76 'camera': <String, Object?>{
77 'ease': true,
78 'keys': <Object?>[
79 <String, Object?>{
80 't': 0,
81 'at': <double>[0, 3, 13],
82 'look': <double>[0, 1, 0],
83 },
84 <String, Object?>{
85 't': 3,
86 'at': <double>[7, 2.5, 5],
87 'look': <double>[0, 1, -1],
88 },
89 <String, Object?>{
90 't': 5.5,
91 'at': <double>[4, 1.8, -1],
92 'look': <double>[0, 1.2, -4],
93 },
94 <String, Object?>{
95 't': 8,
96 'at': <double>[1.5, 2.2, 3],
97 'look': <double>[0, 1.4, -4],
98 'fov': 38,
99 },
100 ],
101 },
102 'subtitles': <Object?>[
103 <String, Object?>{
104 'from': 0.5,
105 'to': 3,
106 'text': 'The hall has been dark a long time.',
107 },
108 <String, Object?>{
109 'from': 3.5,
110 'to': 6.5,
111 'text': 'Something at the altar is waking.',
112 },
113 ],
114 'fade': <Object?>[
115 <String, Object?>{'t': 0, 'value': 0.8},
116 <String, Object?>{'t': 1.5, 'value': 0},
117 ],
118 'signals': <Object?>[
119 <String, Object?>{'t': 3, 'name': 'lamp'},
120 <String, Object?>{
121 't': 5.5,
122 'name': 'gate',
123 'data': <String, Object?>{'height': 2.5},
124 },
125 ],
126 };
128 /// The rate the cutscene is read and stepped at.
129 static const int stepsPerSecond = 60;
131 /// The page's document read into a [Sequence] at [stepsPerSecond]. Throws a
132 /// [FormatException] listing the problems when it does not read.
133 static Sequence readSequence() {
134 final SequenceRead read = Sequence.read(
135 document,
136 stepsPerSecond: stepsPerSecond,
137 );
138 final Sequence? sequence = read.sequence;
139 if (sequence == null) throw FormatException(read.problems.join('\n'));
140 return sequence;
141 }
143 void _start() {
144 _stage = _Stage();
145 _player = _playedTo(_sequence, _stage);
146 _after = 0.0;
147 }
149 /// A player whose signals [stage] answers: they are published onto a bus
150 /// [stage] listens on. A game stepped by an `EngineLoop` hands its own;
151 /// this page steps the cutscene by hand, so a [DirectBus] does.
152 static SequencePlayer _playedTo(Sequence sequence, _Stage stage) {
153 final DirectBus bus = DirectBus();
154 stage.listenTo(bus);
155 return SequencePlayer(sequence, events: bus);
156 }
158 @override
159 Scene build(DemoContext context) {
160 _sequence = readSequence();
161 _view = SequenceView(_sequence);
162 _start();
163 MeshNode box(Vector3 at, Vector3 size, Vector4 color, String name) =>
164 MeshNode(
165 DeviceMesh.upload(context.device, CuboidShape(size: size).build()),
166 RenderMaterial(name: name, baseColor: _fromSrgb(color)),
167 name: name,
168 )..setPosition(at.x, at.y, at.z);
169 _lamp = LightNode(name: 'altar lamp', type: LightType.point, intensity: 0.0)
170 ..setPosition(0.0, 2.2, -4.0);
171 _gate = box(
172 Vector3(0.0, 1.5, -7.0),
173 Vector3(4.0, 3.0, 0.3),
174 Vector4(0.35, 0.33, 0.3, 1.0),
175 'gate',
176 );
177 _flame = box(
178 Vector3(0.0, 1.45, -4.0),
179 Vector3.all(0.3),
180 Vector4(0.3, 0.3, 0.3, 1.0),
181 'flame',
182 );
183 _show();
184 return Scene()
185 ..ambientIntensity = 0.25 * LightNode.legacyUnit
186 ..add(
187 LightNode(name: 'moon', intensity: 1.2 * LightNode.legacyUnit)
188 ..setLocalForward(Vector3(-0.2, -0.8, -0.5)),
189 )
190 ..add(_lamp)
191 ..add(
192 box(
193 Vector3(0.0, -0.5, -2.0),
194 Vector3(14.0, 1.0, 14.0),
195 Vector4(0.4, 0.4, 0.42, 1.0),
196 'floor',
197 ),
198 )
199 ..add(
200 box(
201 Vector3(0.0, 0.65, -4.0),
202 Vector3(1.6, 1.3, 1.0),
203 Vector4(0.6, 0.56, 0.48, 1.0),
204 'altar',
205 ),
206 )
207 ..add(_flame)
208 ..add(_gate);
209 }
211 /// The game's state drawn: the lamp, the flame on the altar and the gate.
212 void _show() {
213 _lamp.intensity = _stage.lampLit ? 30.0 * LightNode.legacyUnit : 0.0;
214 _flame.material.baseColor = LinearColor.fromSrgb(
215 _stage.lampLit ? 1.0 : 0.3,
216 _stage.lampLit ? 0.7 : 0.3,
217 _stage.lampLit ? 0.2 : 0.3,
218 1.0,
219 );
220 _gate.setPosition(0.0, 1.5 + _stage.gateHeight, -7.0);
221 }
223 /// One fixed step of the game while the cutscene plays: the player moves
224 /// on a step and publishes what it reaches, and the game's subscriber
225 /// answers.
226 static void _stepOnce(SequencePlayer player) => player.advance();
228 /// A skip is the rest of the cutscene stepped without being drawn: every
229 /// signal still fires, in order, so the game ends where watching it ends.
230 static void _skip(SequencePlayer player) {
231 while (!player.isFinished) {
232 _stepOnce(player);
233 }
234 }
236 @override
237 void update(DemoContext context, double dt) {
238 _carry += dt.clamp(0.0, 0.1);
239 while (_carry >= 1 / stepsPerSecond) {
240 _carry -= 1 / stepsPerSecond;
241 _stepOnce(_player);
242 }
243 if (_player.isFinished) {
244 _after += dt;
245 if (_after > 3.0) _start();
246 }
247 // Drawn between two steps: alpha is how far the frame is past the last.
248 final double alpha = _carry * stepsPerSecond;
249 final Vector3 eye = Vector3.zero(), look = Vector3.zero();
250 final double? fieldOfView = _view.cameraOf(
251 _player,
252 eye,
253 look,
254 alpha: alpha,
255 );
256 if (fieldOfView != null) {
257 context.camera
258 ..setPosition(eye.x, eye.y, eye.z)
259 ..lookAt(look);
260 }
261 _show();
262 }
264 /// The fade darkens the whole picture: a fade of one is black.
265 @override
266 RenderSettings settings(DemoContext context) => RenderSettings(
267 exposure: RenderSettings.defaultExposure * (1.0 - _view.fadeOf(_player)),
268 );
270 @override
271 List<DemoControl> controls(DemoContext context) => <DemoControl>[
272 ToggleControl(
273 'Skip to the end',
274 value: () => false,
275 onChanged: (bool v) {
276 if (v) _skip(_player);
277 },
278 ),
279 ToggleControl(
280 'Play again',
281 value: () => false,
282 onChanged: (bool v) {
283 if (v) _start();
284 },
285 ),
286 ];
288 @override
289 void verify(Scene scene, FrameResult frame) {
290 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
291 final Sequence sequence = readSequence();
292 final SequenceView view = SequenceView(sequence);
293 // Watched: one step a frame to the end.
294 final _Stage seen = _Stage();
295 final SequencePlayer watched = _playedTo(sequence, seen);
296 while (!watched.isFinished) {
297 _stepOnce(watched);
298 }
299 // Skipped a second and a half in, before either signal.
300 final _Stage hurried = _Stage();
301 final SequencePlayer skipped = _playedTo(sequence, hurried);
302 for (var i = 0; i < 90; i++) {
303 _stepOnce(skipped);
304 }
305 _skip(skipped);
306 if (!seen.sameAs(hurried) || skipped.step != watched.step) {
307 throw StateError('skipped: $hurried; watched: $seen');
308 }
309 if (!listEquals(seen.heard, <String>['lamp', 'gate']) ||
310 seen.gateHeight != 2.5) {
311 throw StateError('the signals were not answered: $seen');
312 }
313 // Restored past the lamp, the lamp does not fire a second time.
314 final _Stage later = _Stage();
315 final SequencePlayer restored = _playedTo(sequence, later)
316 ..restore(<String, Object?>{'step': 4 * stepsPerSecond});
317 _skip(restored);
318 if (!listEquals(later.heard, <String>['gate'])) {
319 throw StateError('a restore fired ${later.heard}');
320 }
321 // The camera ends on its last key, the fade on clear.
322 final Vector3 eye = Vector3.zero(), look = Vector3.zero();
323 if (view.cameraOf(skipped, eye, look) != 38.0 * math.pi / 180.0 ||
324 eye.distanceTo(Vector3(1.5, 2.2, 3.0)) > 1e-6 ||
325 view.fadeOf(skipped) != 0.0) {
326 throw StateError('the camera or the fade did not end where written');
327 }
328 }
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);