flutter3d
Showcase Changelog 62 packages API reference

Two layouts, and whoever presses first is player one: the source

since 0.8.4 The Flame bridge

Regions the guide quotes: layouts (line 16), claim (line 59), lobby (line 177), seat (line 221).

1/// `PlayerSeats` over two keyboard layouts: nobody plays until they press
2/// their join key, and the first to press is player one.
3///
4/// Quoted by `flame_seats.md` and shown whole in the Source tab.
5library;
6
7import 'package:flame/components.dart';
8import 'package:flame/game.dart';
9import 'package:flame_flutter3d/flame_flutter3d.dart';
10import 'package:flutter/services.dart';
11import 'package:flutter/widgets.dart';
12import 'package:flutter3d_game/flutter3d_game.dart';
13import 'package:flutter3d_showcase/src/demo/demo.dart';
14import 'package:flutter3d_showcase/src/demo/flame_layer.dart';
16/// What a layout presses to join, and to do nothing else yet.
17const GameAction join = GameAction('join');
19/// One way of holding the game: four keys to walk and one to join, in a
20/// table and a state of its own.
21FlameInputBridge _layout(
22 LogicalKeyboardKey up,
23 LogicalKeyboardKey left,
24 LogicalKeyboardKey down,
25 LogicalKeyboardKey right,
26 LogicalKeyboardKey joins,
27) => FlameInputBridge(
28 actions: ActionMap(
29 actions: ActionSet.common,
30 buttons: Bindings()
31 ..bind(InputSource.key(up.keyId), GameAction.moveForward)
32 ..bind(InputSource.key(left.keyId), GameAction.moveLeft)
33 ..bind(InputSource.key(down.keyId), GameAction.moveBack)
34 ..bind(InputSource.key(right.keyId), GameAction.moveRight)
35 ..bind(InputSource.key(joins.keyId), join),
36 ),
37 inputState: InputState(),
38);
40/// WASD and Space on the left of the keyboard, the arrows and Slash on the
41/// right: two players at one keyboard, neither of them a player yet.
42PlayerSeats _twoLayouts() => PlayerSeats(<FlameInputBridge>[
43 _layout(
44 LogicalKeyboardKey.keyW,
45 LogicalKeyboardKey.keyA,
46 LogicalKeyboardKey.keyS,
47 LogicalKeyboardKey.keyD,
48 LogicalKeyboardKey.space,
49 ),
50 _layout(
51 LogicalKeyboardKey.arrowUp,
52 LogicalKeyboardKey.arrowLeft,
53 LogicalKeyboardKey.arrowDown,
54 LogicalKeyboardKey.arrowRight,
55 LogicalKeyboardKey.slash,
56 ),
57]);
59/// Seats every free layout whose join key went down this step, in the order
60/// the seats have them, and answers the ones it seated.
61List<FlameInputBridge> seatNewcomers(PlayerSeats seats) => <FlameInputBridge>[
62 for (final FlameInputBridge layout in seats.free.toList())
63 if (layout.inputState.pressed(join) && seats.claim(layout)) layout,
64];
66/// The `flame-seats` page: two keyboard layouts over one floor, a player
67/// taking a seat when its join key is pressed. Its check is that the layout
68/// that pressed first became player one.
69final class FlameSeatsDemo extends ShowcaseDemo {
70 late final DemoContext _context;
71 late final Scene _scene;
72 late final _Lobby _game;
73 late final Widget _body = flameOrbit(
74 _context,
75 Flutter3dFlameWidget(
76 game: _game,
77 existing: BorrowedRenderer(
78 device: _context.device,
79 renderer: _context.renderer,
80 ),
81 ),
82 );
84 late final bool _secondFirst;
86 @override
87 void configureView(DemoContext context) {
88 context.orbit
89 ..distance = 9.0
90 ..pitch = 0.8
91 ..yaw = 0.0;
92 context.orbit.target.setValues(0.0, 0.0, 0.0);
93 }
95 @override
96 Scene build(DemoContext context) {
97 _context = context;
98 _secondFirst = _run();
99 _scene = Scene()
100 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
101 ..ambientIntensity = 0.3 * LightNode.legacyUnit
102 ..add(
103 MeshNode(
104 DeviceMesh.upload(
105 context.device,
106 CuboidShape(size: Vector3(9.0, 0.1, 9.0)).build(),
107 ),
108 RenderMaterial(
109 name: 'floor',
110 baseColor: LinearColor.fromSrgb(0.36, 0.4, 0.38, 1.0),
111 ),
112 name: 'floor',
113 )..setPosition(0.0, -0.05, 0.0),
114 )
115 ..add(
116 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
117 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
118 );
119 _game = _Lobby(context.camera, _twoLayouts())
120 ..open3d(context.device, scene: _scene);
121 return _scene;
122 }
124 @override
125 void update(DemoContext context, double dt) =>
126 context.orbit.syncProjectionDepth(context.camera);
128 /// Checks, with no window, that the second layout pressing first is
129 /// player one: seats go in the order people join, not the order listed.
130 static bool _run() {
131 final PlayerSeats seats = _twoLayouts();
132 final FlameInputBridge arrows = seats.candidates[1];
133 arrows.onKeyEvent(
134 const KeyDownEvent(
135 physicalKey: PhysicalKeyboardKey.slash,
136 logicalKey: LogicalKeyboardKey.slash,
137 timeStamp: Duration.zero,
138 ),
139 const <LogicalKeyboardKey>{},
140 );
141 seatNewcomers(seats);
142 return seats.seated.length == 1 && identical(seats.seated.first, arrows);
143 }
145 /// The Flame game the page runs, for a test that steps it without a window.
146 @visibleForTesting
147 FlameGame get game => _game;
149 /// Who holds what, for a test that presses keys.
150 @visibleForTesting
151 PlayerSeats get seats => _game.seats;
153 /// The marker each layout walks, in the order the seats list the layouts.
154 @visibleForTesting
155 List<MeshNode> get markers => _game.markers;
157 @override
158 Widget? customBody(BuildContext buildContext, DemoContext context) => _body;
160 @override
161 void verify(Scene scene, FrameResult frame) {
162 if (frame.drawCalls < 1) throw StateError('the floor was not drawn');
163 if (!_secondFirst) {
164 throw StateError(
165 'the arrows pressed Slash first and should have been player one',
166 );
167 }
168 }
171/// The colour of each seat, player one first.
172final List<Vector4> _seatColours = <Vector4>[
173 Vector4(0.95, 0.65, 0.2, 1.0),
174 Vector4(0.3, 0.75, 0.95, 1.0),
175];
177/// The game: every layout fed from the keyboard itself and closed after each
178/// frame, a marker for each, hidden until its layout joins.
179final class _Lobby extends FlameGame with HasFlutter3d {
180 _Lobby(this._eye, this.seats);
182 final CameraNode _eye;
183 final PlayerSeats seats;
184 final List<MeshNode> markers = <MeshNode>[];
185 late final TextComponent _caption = flameCaption(
186 'Space joins WASD, / joins the arrows',
187 );
189 @override
190 CameraNode createCamera3d() => _eye;
192 @override
193 void onOpen3d() {
194 final DeviceMesh cube = DeviceMesh.upload(
195 device,
196 CuboidShape(size: Vector3.all(0.8)).build(),
197 );
198 for (var i = 0; i < seats.candidates.length; i++) {
199 final MeshNode marker =
200 MeshNode(
201 cube,
202 RenderMaterial(name: 'player', baseColor: LinearColor.white),
203 name: 'layout $i',
204 )
205 ..setPosition(-1.5 + 3.0 * i, 0.4, 0.0)
206 ..isVisible = false;
207 markers.add(marker);
208 scene.add(marker);
209 }
210 addAll(<Component>[
211 // From `HardwareKeyboard`, wherever the focus is.
212 seats.listenToKeyboard(),
213 _Seating(this),
214 // Every layout's step closed, the free ones too, so a press made to
215 // join is seen once.
216 ...seats.stepEnds(),
217 _caption,
218 ]);
219 }
221 /// A layout that has just joined shows its marker in its seat's colour;
222 /// every seated layout walks its own.
223 void seatAndWalk(double dt) {
224 for (final FlameInputBridge joined in seatNewcomers(seats)) {
225 final int seat = seats.seated.indexOf(joined);
226 final MeshNode marker = markers[seats.candidates.indexOf(joined)];
227 marker
228 ..material.baseColor = _fromSrgb(_seatColours[seat])
229 ..isVisible = true;
230 }
231 for (final FlameInputBridge player in seats.seated) {
232 final Vector2 axis = player.inputState.moveAxis;
233 final MeshNode marker = markers[seats.candidates.indexOf(player)];
234 final Vector3 at = marker.readPosition();
235 marker.setPosition(
236 (at.x + axis.x * 3.0 * dt).clamp(-4.0, 4.0),
237 at.y,
238 (at.z - axis.y * 3.0 * dt).clamp(-4.0, 4.0),
239 );
240 }
241 _caption.text = switch (seats.seated.length) {
242 0 => 'Space joins WASD, / joins the arrows',
243 1 => 'player one is in; the other layout can still join',
244 _ => 'two players, in the order they pressed',
245 };
246 }
249/// Seats and walks between the keyboard's feed and the steps' ends, so a
250/// join press is read in the frame it came in.
251final class _Seating extends Component {
252 _Seating(this._lobby);
254 final _Lobby _lobby;
256 @override
257 void update(double dt) {
258 super.update(dt);
259 _lobby.seatAndWalk(dt);
260 }
263/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
264LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);