flutter3d
Showcase Changelog 62 packages API reference

Ninety-six monsters in one draw, chasing two players: the source

since 0.8.4 The Flame bridge

Regions the guide quotes: brain (line 23), batch (line 145), foci (line 188), spawn (line 199), monster (line 249).

1/// A horde of `flutter3d_sim` actors drawn as slots of one instanced batch,
2/// stepped by one `ActorSystemComponent` towards two players at once.
3///
4/// Quoted by `flame_horde.md` and shown whole in the Source tab.
5library;
6
7import 'dart:math' as math;
8
9import 'package:flame/components.dart' show Component;
10import 'package:flame/game.dart';
11import 'package:flame_flutter3d/flame_flutter3d.dart';
12import 'package:flutter/widgets.dart';
13import 'package:flutter3d/flutter3d.dart';
14import 'package:flutter3d_physics/flutter3d_physics.dart';
15import 'package:flutter3d_showcase/src/demo/demo.dart';
16import 'package:flutter3d_showcase/src/demo/flame_layer.dart';
17import 'package:flutter3d_showcase/src/demo/run_physics.dart';
18import 'package:flutter3d_sim/flutter3d_sim.dart';
20/// How many monsters there are: one draw for all of them.
21const int _monsters = 96;
23/// Walks at whichever player the system says it can reach first, and
24/// remembers which one that was.
25final class _Chase extends Brain {
26 int attended = -1;
28 @override
29 void act(Mind it) {
30 attended = it.focusIndex;
31 it.steerTowardsFocus();
32 }
35/// The `flame-horde` page: a horde of monster actors closing on two players,
36/// drawn as slots of one instanced batch. Its check is that the horde is a
37/// single batch.
38final class FlameHordeDemo extends ShowcaseDemo {
39 late final DemoContext _context;
40 late final Scene _scene;
41 late final _Horde _game;
42 late final Widget _body = flameOrbit(
43 _context,
44 Flutter3dFlameWidget(
45 game: _game,
46 existing: BorrowedRenderer(
47 device: _context.device,
48 renderer: _context.renderer,
49 ),
50 ),
51 );
53 @override
54 void configureView(DemoContext context) {
55 context.orbit
56 ..distance = 22.0
57 ..pitch = 0.95
58 ..yaw = 0.2;
59 context.orbit.target.setValues(0.0, 0.0, 0.0);
60 }
62 @override
63 Scene build(DemoContext context) {
64 _context = context;
65 _scene = Scene()
66 ..ambientColor = LinearColor(0.45, 0.5, 0.6)
67 ..ambientIntensity = 0.3 * LightNode.legacyUnit
68 ..add(
69 MeshNode(
70 DeviceMesh.upload(
71 context.device,
72 CuboidShape(size: Vector3(28.0, 0.1, 28.0)).build(),
73 ),
74 RenderMaterial(
75 name: 'floor',
76 baseColor: LinearColor.fromSrgb(0.34, 0.36, 0.33, 1.0),
77 ),
78 name: 'floor',
79 )..setPosition(0.0, -0.05, 0.0),
80 )
81 ..add(
82 LightNode(name: 'sun', intensity: 2.2 * LightNode.legacyUnit)
83 ..setLocalForward(Vector3(-0.3, -0.7, -0.4)),
84 );
85 _game = _Horde(context.camera)..open3d(context.device, scene: _scene);
86 // In the scene from the start, empty until the monsters take their slots.
87 _scene.add(_game.batch);
88 return _scene;
89 }
91 @override
92 void update(DemoContext context, double dt) =>
93 context.orbit.syncProjectionDepth(context.camera);
95 /// The Flame game the page runs, for a test that steps it without a window.
96 @visibleForTesting
97 FlameGame get game => _game;
99 /// The one batch every monster is drawn through.
100 @visibleForTesting
101 InstancedMeshNode get batch => _game.batch;
103 /// Every monster's body, and which player it went for on its last step.
104 @visibleForTesting
105 List<({Vector3 at, int attended})> get monsters =>
106 <({Vector3 at, int attended})>[
107 for (final (Actor actor, _Chase brain) in _game.monsters)
108 (at: actor.body!.position, attended: brain.attended),
109 ];
111 /// Where the two players are now.
112 @visibleForTesting
113 List<Vector3> get players => <Vector3>[
114 for (final MeshNode hero in _game.heroes) hero.readPosition(),
115 ];
117 @override
118 Widget? customBody(BuildContext buildContext, DemoContext context) => _body;
120 @override
121 void verify(Scene scene, FrameResult frame) {
122 if (frame.drawCalls < 1) throw StateError('the floor was not drawn');
123 final batches = scene.meshes.whereType<InstancedMeshNode>();
124 if (batches.length != 1) {
125 throw StateError(
126 'the horde should be one batch, found ${batches.length}',
127 );
128 }
129 }
132/// The colour a monster wears for the player it is after.
133final List<Vector4> _playerColours = <Vector4>[
134 Vector4(0.95, 0.55, 0.2, 1.0),
135 Vector4(0.3, 0.7, 0.95, 1.0),
136];
138final class _Horde extends FlameGame with HasFlutter3d {
139 _Horde(this._eye);
141 final CameraNode _eye;
142 final List<MeshNode> heroes = <MeshNode>[];
143 final List<(Actor, _Chase)> monsters = <(Actor, _Chase)>[];
145 /// Every monster's mesh and material, drawn in one call however many there
146 /// are; the colour is each slot's own.
147 late final InstancedMeshNode batch = InstancedMeshNode(
148 DeviceMesh.upload(
149 device,
150 CuboidShape(size: Vector3(0.6, 1.0, 0.6)).build(),
151 ),
152 RenderMaterial(name: 'monster', baseColor: LinearColor.white),
153 capacity: _monsters,
154 name: 'horde',
155 );
157 double _clock = 0.0;
159 @override
160 CameraNode createCamera3d() => _eye;
162 @override
163 void onOpen3d() {
164 final CollisionWorld world = onRunPhysics(CollisionWorld())
165 ..addBox(Vector3(0.0, -0.5, 0.0), Vector3(28.0, 1.0, 28.0))
166 ..update();
167 final ActorSystem system = ActorSystem(world: world, random: GameRandom(7));
168 final DeviceMesh ball = DeviceMesh.upload(
169 device,
170 SphereShape(segments: 24, radius: 0.5).build(),
171 );
172 for (var i = 0; i < 2; i++) {
173 final MeshNode hero = MeshNode(
174 ball,
175 RenderMaterial(
176 name: 'player $i',
177 baseColor: _fromSrgb(_playerColours[i]),
178 emissive: _playerColours[i].xyz.toLinearColor(),
179 emissiveStrength: 1.5 * RenderMaterial.defaultEmissiveStrength,
180 ),
181 name: 'player $i',
182 );
183 heroes.add(hero);
184 scene.add(hero);
185 }
186 _walkHeroes();
188 // One system, stepped towards both players: each monster goes for the
189 // one it can reach first. The system is a step clock too, and every
190 // monster is drawn between its last two steps by it.
191 final ActorSystemComponent stepper = ActorSystemComponent(
192 system: system,
193 foci: () => <FocusPoint>[
194 for (final MeshNode hero in heroes)
195 FocusPoint(at: hero.readPosition()..y = 0.9, body: null),
196 ],
197 );
199 // Two rings of monsters, each an actor in the system and a slot in the
200 // batch; no scene node of their own.
201 final List<Component> slots = <Component>[];
202 for (var i = 0; i < _monsters; i++) {
203 final double radius = i.isEven ? 9.0 : 11.0;
204 final double angle = i * 2.0 * math.pi / _monsters;
205 final _Chase brain = _Chase();
206 final Actor actor = system.spawn(
207 body: CharacterController(
208 world: world,
209 position: Vector3(
210 radius * math.cos(angle),
211 0.9,
212 radius * math.sin(angle),
213 ),
214 settings: const MovementSettings(walkSpeed: 2.2),
215 ),
216 brain: brain,
217 );
218 monsters.add((actor, brain));
219 slots.add(
220 _Monster(actor: actor, batch: batch, stepper: stepper, brain: brain),
221 );
222 }
223 addAll(<Component>[stepper, ...slots]);
224 add(flameCaption('one draw, two players: each monster wears its target'));
225 }
227 @override
228 void update(double dt) {
229 super.update(dt);
230 if (!has3d || heroes.isEmpty) return;
231 _clock += dt;
232 _walkHeroes();
233 }
235 /// Two players walking circles of their own on either side of the yard.
236 void _walkHeroes() {
237 for (var i = 0; i < heroes.length; i++) {
238 final double side = i == 0 ? -1.0 : 1.0;
239 final double turn = _clock * 0.5 + i * math.pi;
240 heroes[i].setPosition(
241 side * 3.5 + 2.5 * math.cos(turn),
242 0.5,
243 2.5 * math.sin(turn),
244 );
245 }
246 }
249/// A monster drawn through its slot, between its steps, in the colour of
250/// the player its brain went for.
251final class _Monster extends InstancedActorComponent {
252 _Monster({
253 required super.actor,
254 required super.batch,
255 required ActorSystemComponent super.stepper,
256 required this.brain,
257 }) : super(lift: -0.4);
259 final _Chase brain;
260 int _shown = -1;
262 @override
263 void update(double dt) {
264 super.update(dt);
265 final InstanceHandle? at = slot;
266 if (at == null || brain.attended == _shown || brain.attended < 0) return;
267 _shown = brain.attended;
268 at.setColor(_playerColours[_shown].toLinearColor());
269 }
272/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
273LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);