flutter3d
Showcase Changelog 62 packages API reference

One key, read by both engines: the source

since 0.7.0 The Flame bridge

Regions the guide quotes: live (line 103), walk (line 149), shared (line 188), press (line 202), reactions (line 213).

1/// `FlameInputBridge` translating a Flame keyboard event into the same
2/// `Bindings`/`InputState` pair `flutter3d_game`'s own desktop input writes
3/// into.
4///
5/// Quoted by `flame_input_bridge.md` and shown whole in the Source tab.
6library;
7
8import 'package:flame/components.dart';
9import 'package:flame/events.dart' show HasKeyboardHandlerComponents;
10import 'package:flame_flutter3d/flame_flutter3d.dart';
11import 'package:flutter/services.dart';
12import 'package:flutter/widgets.dart';
13import 'package:flutter3d_game/flutter3d_game.dart';
14import 'package:flutter3d_showcase/src/demo/demo.dart';
15import 'package:flutter3d_showcase/src/demo/flame_layer.dart';
17/// A Flame game that hands keyboard events to the components that ask.
18final class _InputGame extends TransparentFlameGame
19 with HasKeyboardHandlerComponents {}
21/// The `flame-input-bridge` page: a walker on a floor moved by keys that
22/// reach it through Flame. Its check is that a bound key is consumed, that
23/// the flutter3d side reads the same `InputState`, and that the walker moved.
24final class FlameInputBridgeDemo extends ShowcaseDemo {
25 late final String _report;
26 late final bool _consumed;
27 late final bool _heldByTheSharedState;
28 late final double _actorX;
30 /// Holds D for anyone without a keyboard to hand.
31 bool holdD = false;
33 late final DemoContext _context;
34 late final Scene _scene;
35 late final MeshNode _walker;
36 late final _InputGame _game;
37 late final FlameInputBridge _bridge;
38 late final InputState _input;
39 late final Widget _body = flameOrbit(
40 _context,
41 Flutter3dFlameWidget(
42 game: _game,
43 camera: _context.camera,
44 existing: BorrowedRenderer(
45 device: _context.device,
46 renderer: _context.renderer,
47 ),
48 buildScene: (GraphicsDevice device) => _scene,
49 ),
50 );
51 bool _syntheticDown = false;
53 static const double _speed = 3.0;
55 @override
56 void configureView(DemoContext context) {
57 context.orbit
58 ..distance = 8.0
59 ..pitch = 0.7
60 ..yaw = 0.0;
61 context.orbit.target.setValues(0.0, 0.0, 0.0);
62 }
64 @override
65 Scene build(DemoContext context) {
66 _context = context;
67 final (String report, bool consumed, bool held, double actorX) = _run();
68 _report = report;
69 _consumed = consumed;
70 _heldByTheSharedState = held;
71 _actorX = actorX;
73 _walker = MeshNode(
74 DeviceMesh.upload(context.device, SphereShape(segments: 24).build()),
75 RenderMaterial(
76 name: 'walker',
77 baseColor: LinearColor.fromSrgb(0.5, 0.7, 0.9, 1.0),
78 ),
79 name: 'walker',
80 )..setPosition(0.0, 0.5, 0.0);
81 _scene = Scene()
82 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
83 ..ambientIntensity = 0.3 * LightNode.legacyUnit
84 ..add(
85 MeshNode(
86 DeviceMesh.upload(
87 context.device,
88 CuboidShape(size: Vector3(8.0, 0.1, 8.0)).build(),
89 ),
90 RenderMaterial(
91 name: 'floor',
92 baseColor: LinearColor.fromSrgb(0.36, 0.4, 0.38, 1.0),
93 ),
94 name: 'floor',
95 )..setPosition(0.0, -0.05, 0.0),
96 )
97 ..add(_walker)
98 ..add(
99 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
100 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
101 );
103 // Four keys in the one table both engines read. The Flame side is a
104 // component that hands each key event to the bridge; it draws four
105 // keycaps that light while their action is held. The flutter3d side is
106 // `update` below, which reads the same state and walks the sphere.
107 final Bindings bindings = Bindings()
108 ..bind(
109 InputSource.key(LogicalKeyboardKey.keyW.keyId),
110 GameAction.moveForward,
111 )
112 ..bind(
113 InputSource.key(LogicalKeyboardKey.keyA.keyId),
114 GameAction.moveLeft,
115 )
116 ..bind(
117 InputSource.key(LogicalKeyboardKey.keyS.keyId),
118 GameAction.moveBack,
119 )
120 ..bind(
121 InputSource.key(LogicalKeyboardKey.keyD.keyId),
122 GameAction.moveRight,
123 );
124 _input = InputState();
125 _bridge = FlameInputBridge(
126 actions: ActionMap(actions: ActionSet.common, buttons: bindings),
127 inputState: _input,
128 );
129 _game = _InputGame()
130 ..add(_Keys(_bridge))
131 ..add(_KeyCap('W', GameAction.moveForward, _input, Vector2(56.0, 72.0)))
132 ..add(_KeyCap('A', GameAction.moveLeft, _input, Vector2(16.0, 112.0)))
133 ..add(_KeyCap('S', GameAction.moveBack, _input, Vector2(56.0, 112.0)))
134 ..add(_KeyCap('D', GameAction.moveRight, _input, Vector2(96.0, 112.0)));
135 _game
136 ..add(flameCaption('click the scene, then press W A S D'))
137 ..add(flameCaption(_report, at: Vector2(16.0, 40.0)));
138 return _scene;
139 }
141 @override
142 void update(DemoContext context, double dt) {
143 context.orbit.syncProjectionDepth(context.camera);
144 // For anyone without a keyboard: the same event a real D press makes.
145 if (holdD != _syntheticDown) {
146 _syntheticDown = holdD;
147 _sendD(holdD);
148 }
149 // The flutter3d side of the same key: it reads the state Flame wrote.
150 final Vector2 axis = _input.moveAxis;
151 final Vector3 at = _walker.readPosition();
152 _walker.setPosition(
153 (at.x + axis.x * _speed * dt).clamp(-3.5, 3.5),
154 at.y,
155 (at.z - axis.y * _speed * dt).clamp(-3.5, 3.5),
156 );
157 }
159 void _sendD(bool down) {
160 const PhysicalKeyboardKey physical = PhysicalKeyboardKey.keyD;
161 const LogicalKeyboardKey logical = LogicalKeyboardKey.keyD;
162 _bridge.onKeyEvent(
163 down
164 ? const KeyDownEvent(
165 physicalKey: physical,
166 logicalKey: logical,
167 timeStamp: Duration.zero,
168 )
169 : const KeyUpEvent(
170 physicalKey: physical,
171 logicalKey: logical,
172 timeStamp: Duration.zero,
173 ),
174 const <LogicalKeyboardKey>{},
175 );
176 }
178 @override
179 List<DemoControl> controls(DemoContext context) => <DemoControl>[
180 ToggleControl(
181 'Hold D for me',
182 value: () => holdD,
183 onChanged: (bool v) => holdD = v,
184 ),
185 ];
187 static (String, bool, bool, double) _run() {
188 // The same table and the same state a rebind screen edits and
189 // `DesktopInput` reads natively — a bridged game and a native one share
190 // one rebinding UI and one saved binding file, not two.
191 final bindings = Bindings()
192 ..bind(
193 InputSource.key(LogicalKeyboardKey.keyD.keyId),
194 GameAction.moveRight,
195 );
196 final inputState = InputState();
197 final bridge = FlameInputBridge(
198 actions: ActionMap(actions: ActionSet.common, buttons: bindings),
199 inputState: inputState,
200 );
202 // `onKeyEvent` returns false when it consumed the key, matching
203 // `KeyboardHandler`'s own polarity.
204 final bool consumed = !bridge.onKeyEvent(
205 const KeyDownEvent(
206 physicalKey: PhysicalKeyboardKey.keyD,
207 logicalKey: LogicalKeyboardKey.keyD,
208 timeStamp: Duration.zero,
209 ),
210 const <LogicalKeyboardKey>{},
211 );
213 // The Flame side already knows it consumed the key; the flutter3d side
214 // reads the very same `InputState` the press just wrote into, the way an
215 // actor's own movement would.
216 final bool held = inputState.held(GameAction.moveRight);
217 final double actorX = held ? 1.5 : 0.0;
219 return (
220 'the Flame key handler consumed the press: $consumed; the flutter3d '
221 'side reads the same action held: $held',
222 consumed,
223 held,
224 actorX,
225 );
226 }
228 /// The Flame game the page runs, for a test that steps it without a window.
229 @visibleForTesting
230 TransparentFlameGame get game => _game;
232 @override
233 Widget? customBody(BuildContext buildContext, DemoContext context) => _body;
235 @override
236 void verify(Scene scene, FrameResult frame) {
237 if (frame.drawCalls < 1) {
238 throw StateError('the walker marker was not drawn');
239 }
240 // Compared as booleans, not read back out of `_report`: see
241 // `sim_audio_xr/actors.dart` for why.
242 if (!_consumed) {
243 throw StateError('a bound key should be consumed, not passed through');
244 }
245 if (!_heldByTheSharedState) {
246 throw StateError(
247 'the flutter3d side should read the same InputState the Flame '
248 'bridge just pressed',
249 );
250 }
251 if (_actorX != 1.5) {
252 throw StateError('the flutter3d-side reaction should have moved');
253 }
254 }
257/// Hands every key event Flame sees to the bridge, which answers false when it
258/// consumed the key.
259final class _Keys extends Component with KeyboardHandler {
260 _Keys(this._bridge);
262 final FlameInputBridge _bridge;
264 @override
265 bool onKeyEvent(KeyEvent event, Set<LogicalKeyboardKey> keysPressed) =>
266 _bridge.onKeyEvent(event, keysPressed);
269/// A key drawn on Flame's side, lit while the shared state holds its action.
270final class _KeyCap extends PositionComponent {
271 _KeyCap(this._label, this._action, this._state, Vector2 at)
272 : super(position: at, size: Vector2.all(36.0));
274 final String _label;
275 final GameAction _action;
276 final InputState _state;
278 @override
279 void render(Canvas canvas) {
280 final bool held = _state.held(_action);
281 canvas.drawRRect(
282 RRect.fromRectAndRadius(size.toRect(), const Radius.circular(6.0)),
283 Paint()..color = held ? const Color(0xFFE8A33D) : const Color(0xAA14161A),
284 );
285 TextPaint(
286 style: TextStyle(
287 color: held ? const Color(0xFF14161A) : const Color(0xFFE8E8EC),
288 fontSize: 18.0,
289 fontWeight: FontWeight.bold,
290 ),
291 ).render(canvas, _label, Vector2(11.0, 8.0));
292 }