flutter3d
Showcase Changelog 62 packages API reference

Additive layers: the source

since 0.7.0 Animation

Regions the guide quotes: clips (line 85), additive (line 176), live (line 194), check (line 240).

1/// Three heads turn at the same steady rate. Every couple of seconds the
2/// middle and right ones are nudged with the same quick nod: laid on top of
3/// the turn additively on the middle head, replacing it on the right one —
4/// `AnimationBlend.additive` and `AnimationClip.referenceTime`.
5///
6/// Quoted by `additive_blend.md` and shown whole in the Source tab.
7library;
8
9import 'dart:math' as math;
10import 'dart:typed_data';
12import 'package:flutter3d/flutter3d.dart';
13import 'package:flutter3d_showcase/src/demo/demo.dart';
15/// The `additive-blend` page: one turn clip on three heads, and the nod laid
16/// over two of them every 2.2 seconds. Its check fails unless the middle head
17/// reads as the turn with the nod on top and the right one as the nod alone.
18final class AdditiveBlendDemo extends ShowcaseDemo {
19 late final AnimationTrack _turnTrack;
20 late final AnimationTrack _nodTrack;
21 late final AnimationPlayer _plain;
22 late final AnimationPlayer _additive;
23 late final AnimationPlayer _override;
24 late final MeshNode _additiveHead;
25 late final MeshNode _overrideHead;
26 AnimationLayer? _additiveNod;
27 AnimationLayer? _overrideNod;
29 /// How fast the three heads turn, as a multiple of the turn clip's own speed:
30 /// 0 stops them, 2 is twice as fast. The "Turn speed" slider writes it, and
31 /// the nod keeps its own pace whatever it is.
32 double turnSpeed = 1.0;
33 double _sinceNod = 0.0;
35 /// How often the nod is played again, in seconds of the demo's own clock.
36 static const double _period = 2.2;
38 @override
39 void configureView(DemoContext context) {
40 context.orbit
41 ..distance = 7.0
42 ..pitch = 0.25
43 ..yaw = 0.0;
44 }
46 @override
47 Scene build(DemoContext context) {
48 final DeviceMesh box = DeviceMesh.upload(
49 context.device,
50 CuboidShape(size: Vector3(1.0, 1.0, 1.0)).build(),
51 );
52 final DeviceMesh nose = DeviceMesh.upload(
53 context.device,
54 CuboidShape(size: Vector3(0.3, 0.3, 0.5)).build(),
55 );
56 MeshNode head(String name, Vector4 color, double x) {
57 final MeshNode node = MeshNode(
58 box,
59 RenderMaterial(name: name, baseColor: _fromSrgb(color), roughness: 0.6),
60 name: name,
61 )..setPosition(x, 0.0, 0.0);
62 // A face, so a turn and a nod each read as one: a plain cube looks
63 // the same after a quarter turn.
64 node.add(
65 MeshNode(
66 nose,
67 RenderMaterial(
68 name: '$name nose',
69 baseColor: LinearColor.fromSrgb(0.95, 0.9, 0.8, 1.0),
70 ),
71 name: '$name nose',
72 )..setPosition(0.0, 0.0, 0.7),
73 );
74 return node;
75 }
77 final MeshNode plainHead = head(
78 'turn only',
79 Vector4(0.6, 0.6, 0.65, 1),
80 -2.2,
81 );
82 _additiveHead = head('additive', Vector4(0.35, 0.75, 0.45, 1), 0.0);
83 _overrideHead = head('override', Vector4(0.9, 0.5, 0.3, 1), 2.2);
85 _turnTrack = _turnAroundY();
86 final AnimationClip turn = AnimationClip(
87 name: 'turn',
88 tracks: <AnimationTrack>[_turnTrack],
89 );
90 _nodTrack = _nodAroundX();
91 final AnimationClip nod = AnimationClip(
92 name: 'nod',
93 tracks: <AnimationTrack>[_nodTrack],
94 // The rest pose the nod is a difference from: at time zero it asks
95 // for nothing, so laid on top of a turn it leaves the turn alone.
96 referenceSeconds: 0.0,
97 );
99 AnimationPlayer playerFor(MeshNode node) => AnimationPlayer(
100 clips: <AnimationClip>[turn, nod],
101 targets: <AnimationTarget?>[node],
102 )..play(index: 0);
103 _plain = playerFor(plainHead);
104 _additive = playerFor(_additiveHead);
105 _override = playerFor(_overrideHead);
107 _nodBoth();
108 // Start a fifth of a second in, with the nod at its deepest, so the
109 // first frame already shows the difference between the two blends.
110 for (final AnimationPlayer player in <AnimationPlayer>[
111 _plain,
112 _additive,
113 _override,
114 ]) {
115 player.advance(0.2);
116 }
117 _sinceNod = 0.2;
119 return Scene()
120 ..add(plainHead)
121 ..add(_additiveHead)
122 ..add(_overrideHead)
123 ..add(
124 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
125 ..setLocalForward(Vector3(-0.3, -0.7, -0.5)),
126 );
127 }
129 /// A full turn about Y in quarter turns, a keyframe each: a single
130 /// keyframe pair from zero to a full turn would interpolate along the
131 /// shortest path, which is no turn at all.
132 static AnimationTrack _turnAroundY() {
133 const int keys = 5;
134 final Float32List values = Float32List(keys * 4);
135 for (var i = 0; i < keys; i++) {
136 final Quaternion q = Quaternion.axisAngle(
137 Vector3(0.0, 1.0, 0.0),
138 i * math.pi / 2,
139 );
140 values.setRange(i * 4, i * 4 + 4, <double>[q.x, q.y, q.z, q.w]);
141 }
142 return AnimationTrack(
143 nodeIndex: 0,
144 path: AnimationPath.rotation,
145 interpolation: AnimationInterpolation.linear,
146 times: Float32List.fromList(<double>[0.0, 1.5, 3.0, 4.5, 6.0]),
147 values: values,
148 componentCount: 4,
149 );
150 }
152 /// Nothing, a nod forward, nothing again, over four tenths of a second.
153 static AnimationTrack _nodAroundX() {
154 final List<double> angles = <double>[0.0, 0.7, 0.0];
155 final Float32List values = Float32List(angles.length * 4);
156 for (var i = 0; i < angles.length; i++) {
157 final Quaternion q = Quaternion.axisAngle(
158 Vector3(1.0, 0.0, 0.0),
159 angles[i],
160 );
161 values.setRange(i * 4, i * 4 + 4, <double>[q.x, q.y, q.z, q.w]);
162 }
163 return AnimationTrack(
164 nodeIndex: 0,
165 path: AnimationPath.rotation,
166 interpolation: AnimationInterpolation.linear,
167 times: Float32List.fromList(<double>[0.0, 0.2, 0.4]),
168 values: values,
169 componentCount: 4,
170 );
171 }
173 /// Plays the nod once on the two heads that get one, each in its own blend
174 /// mode, taking away the previous nod first.
175 void _nodBoth() {
176 if (_additiveNod != null) _additive.layers.remove(_additiveNod);
177 _additiveNod = _additive.playLayer(
178 1,
179 wrap: AnimationWrap.once,
180 fade: Duration.zero,
181 blend: AnimationBlend.additive,
182 );
183 if (_overrideNod != null) _override.layers.remove(_overrideNod);
184 _overrideNod = _override.playLayer(
185 1,
186 wrap: AnimationWrap.once,
187 fade: Duration.zero,
188 blend: AnimationBlend.override,
189 );
190 }
192 @override
193 void update(DemoContext context, double dt) {
194 _sinceNod += dt;
195 if (_sinceNod >= _period) {
196 _sinceNod -= _period;
197 _nodBoth();
198 }
199 for (final AnimationPlayer player in <AnimationPlayer>[
200 _plain,
201 _additive,
202 _override,
203 ]) {
204 player.speed = turnSpeed;
205 }
206 _plain.advance(dt);
207 _additive.advance(dt);
208 _override.advance(dt);
209 // A finished override layer would go on holding its last pose, which is
210 // the head facing dead ahead: taking it off is what lets the turn resume.
211 final AnimationLayer? finished = _overrideNod;
212 if (finished != null && finished.isFinished) {
213 _override.layers.remove(finished);
214 _overrideNod = null;
215 }
216 }
218 @override
219 List<DemoControl> controls(DemoContext context) => <DemoControl>[
220 SliderControl(
221 'Turn speed',
222 min: 0,
223 max: 2,
224 value: () => turnSpeed,
225 onChanged: (double v) => turnSpeed = v,
226 ),
227 ];
229 Quaternion _sample(AnimationTrack track, double time) {
230 final Float32List out = Float32List(4);
231 track.sample(time, out);
232 return Quaternion(out[0], out[1], out[2], out[3]);
233 }
235 static double _dot(Quaternion a, Quaternion b) =>
236 (a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w).abs();
238 @override
239 void verify(Scene scene, FrameResult frame) {
240 final AnimationLayer? nod = _additiveNod;
241 if (nod == null) throw StateError('the additive head has no nod playing');
243 final Quaternion turn = _sample(_turnTrack, _additive.timeSeconds);
244 final Quaternion delta =
245 (_sample(_nodTrack, 0.0).conjugated() *
246 _sample(_nodTrack, nod.timeSeconds))
247 ..normalize();
248 if ((delta.w - 1.0).abs() < 1e-3) {
249 throw StateError('the nod has not moved yet; nothing to add');
250 }
252 Quaternion rotationOf(MeshNode head) =>
253 Quaternion.fromRotation(head.sceneMatrix.getRotation());
254 final Quaternion added = rotationOf(_additiveHead);
255 if (_dot(added, (turn * delta)..normalize()) < 0.999) {
256 throw StateError('the middle head is not the turn with the nod on top');
257 }
258 if (_dot(added, rotationOf(_overrideHead)) > 0.999) {
259 throw StateError(
260 'the right head should have had its turn replaced by the nod, and '
261 'looks the same as the one that kept it',
262 );
263 }
264 if (frame.drawCalls < 1) throw StateError('the heads were not drawn');
265 }
268/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
269LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);