flutter3d
Showcase Changelog 62 packages API reference

Bridging a flutter3d_sim actor: the source

since 0.7.0 The Flame bridge

Regions the guide quotes: brain (line 17), live (line 95), system (line 160), actor (line 164), bridge (line 174), step (line 194).

1/// `ActorComponent` and `ActorSystemComponent` bridging a `flutter3d_sim`
2/// `Actor`'s own body onto a Flame position and a flutter3d mesh.
3///
4/// Quoted by `flame_ecs_bridge.md` and shown whole in the Source tab.
5library;
6
7import 'package:flame/components.dart' show Component;
8import 'package:flame_flutter3d/flame_flutter3d.dart';
9import 'package:flutter/widgets.dart';
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_physics/flutter3d_physics.dart';
12import 'package:flutter3d_showcase/src/demo/demo.dart';
13import 'package:flutter3d_showcase/src/demo/flame_layer.dart';
14import 'package:flutter3d_showcase/src/demo/run_physics.dart';
15import 'package:flutter3d_sim/flutter3d_sim.dart';
17/// Walks straight towards +x, every step, for as long as it lives.
18final class _WalkBrain extends Brain {
19 @override
20 void act(Mind it) => it.steer(Vector3(1.0, 0.0, 0.0));
23/// The `flame-ecs-bridge` page: goblin actors walking on a floor, stepped by
24/// an `ActorSystemComponent`, one of them bridged to a Flame position. Its
25/// check is that the goblin walked forward and that the Flame position
26/// tracks its body exactly.
27final class FlameEcsBridgeDemo extends ShowcaseDemo {
28 late final String _report;
29 late final double _actorX;
30 late final double _flameX;
32 late final DemoContext _context;
33 late final Scene _scene;
34 late final TransparentFlameGame _game;
35 late final Widget _body = flameOrbit(
36 _context,
37 Flutter3dFlameWidget(
38 game: _game,
39 camera: _context.camera,
40 existing: BorrowedRenderer(
41 device: _context.device,
42 renderer: _context.renderer,
43 ),
44 buildScene: (GraphicsDevice device) => _scene,
45 ),
46 );
48 static const List<Color> _colors = <Color>[
49 Color(0xFF80CC4D),
50 Color(0xFF80B3E6),
51 Color(0xFFE6994D),
52 ];
54 /// Where the walkers wrap round, on x.
55 static const double _edge = 4.5;
57 @override
58 void configureView(DemoContext context) {
59 context.orbit
60 ..distance = 10.0
61 ..pitch = 0.8
62 ..yaw = 0.4;
63 context.orbit.target.setValues(0.0, 0.0, 0.0);
64 }
66 @override
67 Scene build(DemoContext context) {
68 _context = context;
69 final (String report, double actorX, double flameX) = _run(context.device);
70 _report = report;
71 _actorX = actorX;
72 _flameX = flameX;
74 _scene = Scene()
75 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
76 ..ambientIntensity = 0.3 * LightNode.legacyUnit
77 ..add(
78 MeshNode(
79 DeviceMesh.upload(
80 context.device,
81 CuboidShape(size: Vector3(12.0, 0.1, 12.0)).build(),
82 ),
83 RenderMaterial(
84 name: 'floor',
85 baseColor: LinearColor.fromSrgb(0.36, 0.4, 0.38, 1.0),
86 ),
87 name: 'floor',
88 )..setPosition(0.0, -0.05, 0.0),
89 )
90 ..add(
91 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
92 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
93 );
95 // Three goblins in one shared system, each with a bridge component that
96 // copies its body onto its node and, through the plane, onto a Flame
97 // position. One `ActorSystemComponent` steps the system, once a frame; the
98 // map's dots are those Flame positions.
99 final CollisionWorld world = onRunPhysics(CollisionWorld())
100 ..addBox(Vector3(0.0, -0.5, 0.0), Vector3(20.0, 1.0, 20.0));
101 final ActorSystem system = ActorSystem(world: world, random: GameRandom(1));
102 final FlameMinimap map = FlameMinimap();
103 final List<Component> bridges = <Component>[];
104 final List<CharacterController> bodies = <CharacterController>[];
105 for (var i = 0; i < 3; i++) {
106 final CharacterController body = CharacterController(
107 world: world,
108 position: Vector3(-_edge + i * 1.5, 1.0, (i - 1) * 2.0),
109 );
110 bodies.add(body);
111 final Actor goblin = system.spawn(
112 body: body,
113 brain: _WalkBrain(),
114 name: 'goblin $i',
115 );
116 final MeshNode node = MeshNode(
117 DeviceMesh.upload(
118 context.device,
119 SphereShape(segments: 24, radius: 0.4).build(),
120 ),
121 RenderMaterial(
122 name: 'goblin $i',
123 baseColor: LinearColor.fromSrgb(
124 _colors[i].r,
125 _colors[i].g,
126 _colors[i].b,
127 1.0,
128 ),
129 ),
130 name: 'goblin $i',
131 );
132 _scene.add(node);
133 bridges.add(
134 ActorComponent(
135 actor: goblin,
136 node: node,
137 scene: _scene,
138 plane: BridgePlane.ground(),
139 )..add(flameDot(_colors[i])),
140 );
141 }
142 map.world.addAll(bridges);
143 _game = TransparentFlameGame()
144 ..add(ActorSystemComponent(system: system, focus: Vector3.zero))
145 // After the system, so the bodies have moved by the time they are read.
146 ..add(_Wrap(bodies))
147 ..add(map);
148 _game
149 ..add(flameCaption('the dots: Flame positions read off the actors'))
150 ..add(flameCaption(_report, at: Vector2(16.0, 40.0)));
151 return _scene;
152 }
154 @override
155 void update(DemoContext context, double dt) {
156 context.orbit.syncProjectionDepth(context.camera);
157 }
159 static (String, double, double) _run(GraphicsDevice device) {
160 final world = onRunPhysics(CollisionWorld());
161 world.addBox(Vector3(0.0, -0.5, 0.0), Vector3(20.0, 1.0, 20.0));
162 final system = ActorSystem(world: world, random: GameRandom(1));
164 final controller = CharacterController(
165 world: world,
166 position: Vector3(0.0, 3.0, 0.0),
167 );
168 final goblin = system.spawn(
169 body: controller,
170 brain: _WalkBrain(),
171 name: 'goblin',
172 );
174 final scene = Scene();
175 final node = MeshNode(
176 DeviceMesh.upload(device, SphereShape(segments: 16).build()),
177 RenderMaterial(
178 name: 'bridged-goblin',
179 baseColor: LinearColor.fromSrgb(0.5, 0.7, 0.3, 1.0),
180 ),
181 );
182 scene.add(node);
183 final actorComponent = ActorComponent(
184 actor: goblin,
185 node: node,
186 scene: scene,
187 plane: BridgePlane.ground(),
188 );
189 final systemComponent = ActorSystemComponent(
190 system: system,
191 focus: Vector3.zero,
192 );
194 // The system decides where the goblin's body goes; the actor component
195 // copies that body's position onto the node, then the plane it shares
196 // carries it onto the Flame side — the same seam `Object3dComponent`
197 // gives every other bridged transform.
198 for (var i = 0; i < 90; i++) {
199 systemComponent.update(1 / 60);
200 actorComponent.update(1 / 60);
201 }
203 final double actorX = goblin.body!.position.x;
204 final double flameX = actorComponent.position.x;
205 return (
206 'the goblin walked to x=${actorX.toStringAsFixed(2)}; the Flame '
207 'position reads x=${flameX.toStringAsFixed(2)}',
208 actorX,
209 flameX,
210 );
211 }
213 /// The Flame game the page runs, for a test that steps it without a window.
214 @visibleForTesting
215 TransparentFlameGame get game => _game;
217 @override
218 Widget? customBody(BuildContext buildContext, DemoContext context) => _body;
220 @override
221 void verify(Scene scene, FrameResult frame) {
222 if (frame.drawCalls < 1) {
223 throw StateError('the goblin marker was not drawn');
224 }
225 // Compared as numbers, not read back out of `_report`: see
226 // `sim_audio_xr/actors.dart` for why a formatted string is the wrong
227 // thing to assert a double against.
228 if (_actorX < 0.5) {
229 throw StateError(
230 'the goblin should have walked forward under the system, got '
231 'x=$_actorX',
232 );
233 }
234 if (_flameX != _actorX) {
235 throw StateError(
236 'the bridged Flame position should track the actor body exactly on '
237 'a ground plane, got flame x=$_flameX vs body x=$_actorX',
238 );
239 }
240 }
243/// Sends a goblin that has walked off the far edge back to the near one.
244final class _Wrap extends Component {
245 _Wrap(this._bodies);
247 final List<CharacterController> _bodies;
249 @override
250 void update(double dt) {
251 super.update(dt);
252 for (final CharacterController body in _bodies) {
253 if (body.position.x > FlameEcsBridgeDemo._edge) {
254 body.position.x = -FlameEcsBridgeDemo._edge;
255 }
256 }
257 }