flutter3d
Showcase Changelog 62 packages API reference

Loading into a scene: the source

since 0.4.0 or earlier Formats and I/O

Regions the guide quotes: document (line 17), upload (line 41), instantiate (line 49), check (line 65).

1/// Uploading a decoded document with `ModelAsset.fromDocument`, then
2/// placing it in a scene with `instantiate`.
3///
4/// Quoted by `model_asset.md` and shown whole in the Source tab.
5library;
6
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
9
10/// The `model-asset` page: a decoded document uploaded as a `ModelAsset` and
11/// placed with `instantiate`. Its check is that the upload carried vertices
12/// and the instance added a mesh that is drawn.
13final class ModelAssetDemo extends ShowcaseDemo {
14 late final ModelAsset _asset;
15 ModelInstance? _instance;
17 // A decoded document, the shape every format in this package produces.
18 // `ModelAsset.fromDocument` does not care which one wrote it.
19 final _document = PlainModelDocument(
20 surfaces: <ModelSurface>[
21 ModelSurface(
22 mesh: SphereShape(segments: 32, rings: 16).build(),
23 materialIndex: 0,
24 ),
25 ],
26 materials: <SurfaceMaterial>[
27 SurfaceMaterial(
28 name: 'shell',
29 baseColor: LinearColor.fromSrgb(0.75, 0.4, 0.6, 1.0),
30 metallic: 0.2,
31 roughness: 0.4,
32 ),
33 ],
34 nodes: <ModelNode>[
35 ModelNode(surfaces: <int>[0]),
36 ],
37 );
39 @override
40 Future<void> prepare(DemoContext context) async {
41 // Meshes and images are uploaded once, deduplicated by identity; a
42 // document's materials become the engine's own `RenderMaterial`, ready to be
43 // placed as many times as a scene wants.
44 _asset = await ModelAsset.fromDocument(_document, device: context.device);
45 }
47 @override
48 Scene build(DemoContext context) {
49 // `instantiate` rebuilds the asset's hierarchy as scene nodes and
50 // returns a `ModelInstance`: the node it hangs from, one scene node a
51 // decoded node, and a skeleton or an animation player when the asset
52 // carries one.
53 final scene = Scene();
54 _instance = _asset.instantiate(scene);
56 scene.add(
57 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
58 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
59 );
60 return scene;
61 }
63 @override
64 void verify(Scene scene, FrameResult frame) {
65 if (_asset.vertexCount == 0) {
66 throw StateError('the asset uploaded no vertices');
67 }
68 if (_instance == null || _instance!.meshes.isEmpty) {
69 throw StateError('instantiate did not add a mesh to the scene');
70 }
71 if (frame.drawCalls < 1) {
72 throw StateError('the instance was not drawn');
73 }
74 }