Loading a level: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: document (line 18), build (line 30), shared (line 36).
1/// Reading a level document into something playable: brushes become mesh
2/// nodes, lights become light nodes, and a shared mesh cache uploads each
3/// repeated shape once.
4///
5/// Quoted by `level_loader.md` and shown whole in the Source tab.
6library;
8import 'package:flutter3d/flutter3d.dart';
9import 'package:flutter3d_app/flutter3d_app.dart';
10import 'package:flutter3d_showcase/src/demo/demo.dart';
11import 'package:flutter3d_sim/flutter3d_sim.dart';
12import 'package:vector_math/vector_math.dart';
14final class LevelLoaderDemo extends ShowcaseDemo {
15 late LoadedLevel _loaded;
16 late SharedMeshes _shared;
18 static Level _document() => Level(
19 name: 'room',
20 brushes: <Brush>[
21 Brush(centre: Vector3(0, -0.5, 0), size: Vector3(4, 1, 4)),
22 ],
23 lights: <LevelLight>[
24 LevelLight(position: Vector3(0, 3, 0), intensity: 5.0, range: 10.0),
25 ],
26 );
29 Future<void> prepare(DemoContext context) async {
30 _loaded = await const LevelLoader().build(
31 _document(),
32 device: context.device,
33 registry: EntityRegistry(const <EntityKind>[]),
34 );
36 // Three torch posts that all ask the cache for the same box, uploaded
37 // once and reused by all three nodes.
38 _shared = SharedMeshes(context.device);
39 for (var i = 0; i < 3; i++) {
40 final mesh = _shared.box(Vector3(0.2, 1.0, 0.2));
41 final post = MeshNode(
42 mesh,
43 Material(name: 'post', baseColor: Vector4(0.4, 0.3, 0.2, 1.0)),
44 )..setPosition(-1.0 + i.toDouble(), 0.0, 1.5);
45 _loaded.scene.add(post);
46 }
47 }
50 Scene build(DemoContext context) => _loaded.scene;
53 void verify(Scene scene, FrameResult frame) {
54 if (frame.drawCalls < 1) {
55 throw StateError('the loaded level was not drawn');
56 }
57 if (_loaded.brushNodes.length != 1) {
58 throw StateError(
59 'the one brush in the document should become one '
60 'mesh node',
61 );
62 }
63 if (_loaded.issues.isNotEmpty) {
64 throw StateError(
65 'a clean document should load with no issues, got '
66 '${_loaded.issues}',
67 );
68 }
69 }
70}