Variants and animation pointers: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: materials (line 36), variants (line 65), clip (line 82), roundtrip (line 114), bind (line 159), play (line 172), select (line 181), tick (line 201), check (line 231).
1/// A model that changes its look by name, and a clip that animates a material
2/// and a light, both written into a GLB and read back.
3///
4/// Quoted by `variants_and_pointers.md` and shown whole in the Source tab.
5library;
7import 'dart:typed_data';
9import 'package:flutter3d/flutter3d.dart';
10import 'package:flutter3d_showcase/src/demo/demo.dart';
12/// The `variants-and-pointers` page: a model with named material variants
13/// and a clip that animates a material and the sun, through a GLB. Its check
14/// is that each surface wears its variant's material and that the intensity
15/// track moved the sun.
16final class VariantsAndPointersDemo extends ShowcaseDemo {
17 /// 0 is the default look, then one option for each of the file's variants.
18 int variant = 1;
20 late final GltfAsset _readBack;
21 late final ModelAsset _asset;
22 late final ModelInstance _instance;
23 late final AnimationPlayer _player;
24 late final LightNode _sun;
27 void configureView(DemoContext context) {
28 context.orbit
29 ..distance = 4.5
30 ..pitch = 0.35
31 ..yaw = 0.6;
32 }
35 Future<void> prepare(DemoContext context) async {
36 // Five materials. The body wears the first and the ball the second
37 // unless a variant says otherwise; the other three are only ever worn
38 // through a variant.
39 final List<SurfaceMaterial> materials = <SurfaceMaterial>[
40 SurfaceMaterial(
41 name: 'red paint',
42 baseColor: LinearColor.fromSrgb(0.6, 0.2, 0.15, 1),
43 ),
44 SurfaceMaterial(
45 name: 'cream',
46 baseColor: LinearColor.fromSrgb(0.6, 0.55, 0.45, 1),
47 roughness: 0.6,
48 ),
49 SurfaceMaterial(
50 name: 'teal paint',
51 baseColor: LinearColor.fromSrgb(0.12, 0.45, 0.42, 1),
52 ),
53 SurfaceMaterial(
54 name: 'graphite',
55 baseColor: LinearColor.fromSrgb(0.2, 0.2, 0.22, 1),
56 roughness: 0.35,
57 ),
58 SurfaceMaterial(
59 name: 'chalk',
60 baseColor: LinearColor.fromSrgb(0.55, 0.55, 0.55, 1),
61 roughness: 0.8,
62 ),
63 ];
65 // `variantMaterials` maps a variant, by its index in `variants`, to the
66 // material the surface wears in it. The body changes in both variants;
67 // the ball only in "graphite".
68 final List<ModelSurface> surfaces = <ModelSurface>[
69 ModelSurface(
70 mesh: CuboidShape(size: Vector3(1.2, 0.8, 0.8)).build(),
71 materialIndex: 0,
72 variantMaterials: const <int, int>{0: 2, 1: 3},
73 ),
74 ModelSurface(
75 mesh: SphereShape(radius: 0.4, segments: 32, rings: 16).build(),
76 materialIndex: 1,
77 variantMaterials: const <int, int>{1: 4},
78 ),
79 ];
80 const List<String> variants = <String>['teal', 'graphite'];
82 // Two pointer tracks and no node track. One warms the ball's material
83 // (index 1) from cream to amber and back; the other dims the file's
84 // light (index 0) from 110 lux to 45 and back. Colour keys are linear,
85 // as glTF keeps them; the first is the cream above.
86 AnimationTrack track(AnimationPointer pointer, List<double> values) =>
87 AnimationTrack(
88 nodeIndex: -1,
89 path: AnimationPath.pointer,
90 interpolation: AnimationInterpolation.linear,
91 times: Float32List.fromList(<double>[0.0, 1.5, 3.0]),
92 values: Float32List.fromList(values),
93 componentCount: pointer.property.componentCount,
94 pointer: pointer,
95 );
96 final AnimationClip evening = AnimationClip(
97 name: 'evening',
98 tracks: <AnimationTrack>[
99 track(
100 AnimationPointer.of(AnimationPointerProperty.baseColor, 1),
101 <double>[
102 0.319, 0.262, 0.171, 1, //
103 0.32, 0.09, 0.02, 1, //
104 0.319, 0.262, 0.171, 1,
105 ],
106 ),
107 track(
108 AnimationPointer.of(AnimationPointerProperty.lightIntensity, 0),
109 <double>[110, 45, 110],
110 ),
111 ],
112 );
114 final PlainModelDocument document = PlainModelDocument(
115 surfaces: surfaces,
116 materials: materials,
117 lights: <ModelLight>[
118 ModelLight(type: LightType.directional, intensity: 110),
119 ],
120 nodes: <ModelNode>[
121 ModelNode(
122 name: 'body',
123 surfaces: <int>[0],
124 translation: Vector3(0, 0.4, 0),
125 ),
126 ModelNode(
127 name: 'ball',
128 surfaces: <int>[1],
129 translation: Vector3(0, 1.2, 0),
130 ),
131 ModelNode(name: 'sun', lightIndex: 0),
132 ],
133 variants: variants,
134 animations: <AnimationClip>[evening],
135 );
136 final Uint8List bytes = GltfWriter(document).writeGlb();
137 _readBack = await GltfLoader().load(bytes);
138 _asset = await ModelAsset.fromDocument(_readBack, device: context.device);
139 }
142 Scene build(DemoContext context) {
143 final Scene scene = Scene()
144 ..add(
145 MeshNode(
146 DeviceMesh.upload(
147 context.device,
148 const PlaneShape(width: 8, depth: 8).build(),
149 ),
150 RenderMaterial(
151 name: 'floor',
152 baseColor: LinearColor.fromSrgb(0.45, 0.45, 0.45, 1.0),
153 roughness: 0.9,
154 ),
155 name: 'floor',
156 ),
157 );
159 // Instantiating creates no lights, so the page places its own sun and
160 // hands it to the instance as the file's light 0. The intensity track
161 // reaches it through `pointerTargets`; the material tracks reach the
162 // asset's materials the same way, by their index in the file.
163 _instance = _asset.instantiate(scene);
164 final ModelLight light = _readBack.lights.single;
165 _sun = LightNode(
166 name: 'sun',
167 color: light.color,
168 intensity: light.intensity,
169 )..setLocalForward(Vector3(-0.5, -0.8, -0.4));
170 _instance.bindLight(0, _sun);
172 // The page opens halfway through the clip, where both tracks are
173 // furthest from what the file says, and plays on from there.
174 _player = _instance.player!
175 ..play(index: 0)
176 ..seek(1.5);
177 _wear(variant);
178 return scene..add(_sun);
179 }
181 void _wear(int option) {
182 variant = option;
183 _instance.selectVariant(option == 0 ? null : _asset.variants[option - 1]);
184 }
186 // The file's light is in lux, as glTF's is, and 110 lux is a lamp-lit
187 // room rather than the sun. So the camera is metered as it would be in
188 // one: for the light at its authored 110 lux plus the scene's flat
189 // ambient (in the engine's pre-1.0 unit), about EV100 7.5, and held there
190 // while the clip dims the light to 45 and back.
191 static final PhysicalCamera _camera = PhysicalCamera.metered(
192 110.0 + 0.06 * LightNode.legacyUnit,
193 );
196 RenderSettings settings(DemoContext context) =>
197 RenderSettings(camera: _camera);
200 void update(DemoContext context, double dt) {
201 _player.advance(dt);
202 }
205 List<DemoControl> controls(DemoContext context) => <DemoControl>[
206 ChoiceControl(
207 'Variant',
208 options: <String>['Default', ..._asset.variants],
209 index: () => variant,
210 onChanged: _wear,
211 ),
212 ToggleControl(
213 'Play clip',
214 value: () => _player.isPlaying,
215 onChanged: (bool v) => v ? _player.play() : _player.pause(),
216 ),
217 SliderControl(
218 'Time',
219 min: 0,
220 max: _player.durationSeconds,
221 value: () => _player.timeSeconds,
222 onChanged: (double v) => _player
223 ..pause()
224 ..seek(v),
225 format: (double v) => '${v.toStringAsFixed(2)} s',
226 ),
227 ];
230 void verify(Scene scene, FrameResult frame) {
231 // One mesh node a surface, in the order the nodes are walked: the body,
232 // then the ball. Each must point at the material the file gives it in
233 // the variant being worn, and that material is the asset's own.
234 final int worn = _instance.variant == null
235 ? -1
236 : _asset.variants.indexOf(_instance.variant!);
237 for (var i = 0; i < _readBack.surfaces.length; i++) {
238 final ModelSurface surface = _readBack.surfaces[i];
239 final int expected =
240 surface.variantMaterials[worn] ?? surface.materialIndex!;
241 if (!identical(
242 _instance.meshes[i].material,
243 _asset.materials[expected],
244 )) {
245 throw StateError(
246 'surface $i is not wearing material $expected, which '
247 '${_instance.variant ?? 'the default look'} gives it',
248 );
249 }
250 }
252 // The clip is past its first key, so both tracks have moved their
253 // targets away from what the file says.
254 final LinearColor authored = _readBack.materials[1].baseColor;
255 final LinearColor now = _asset.materials[1]!.baseColor;
256 if ((now.r - authored.r).abs() +
257 (now.g - authored.g).abs() +
258 (now.b - authored.b).abs() <
259 0.05) {
260 throw StateError("the colour track did not move the ball's material");
261 }
262 final double fileSun = _readBack.lights[0].intensity;
263 if ((_sun.intensity - fileSun).abs() < 0.1) {
264 throw StateError('the intensity track did not move the sun');
265 }
266 if (frame.drawCalls < 1) {
267 throw StateError('the model was not drawn');
268 }
269 }
270}