flutter3d
Showcase Changelog 62 packages API reference

Joints that break: the source

since 1.0.0-rc.1 Physics and particles

Regions the guide quotes: hang (line 58), tick (line 90), show (line 198), check (line 273).

1/// A shelf hung on a wall by two brackets that break, and crates set on it
2/// one at a time until a bracket lets go. Stepped by the physics core: the
3/// brackets are fixed joints with a force they give way past.
4///
5/// Quoted by `breakable_joints.md` and shown whole in the Source tab.
6library;
7
8import 'dart:math' as math;
9
10import 'package:flutter/foundation.dart' show visibleForTesting;
11import 'package:flutter3d/flutter3d.dart';
12import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
13import 'package:flutter3d_showcase/src/demo/demo.dart';
15/// The `breakable-joints` page: a shelf on two breakable brackets, loaded
16/// one crate at a time on the physics core. Its check is that the brackets
17/// hold four crates, let go under five, and report the break.
18final class BreakableJointsDemo extends ShowcaseDemo {
19 NativeWorld? _world;
20 late NativeBody _wall;
21 late NativeBody _shelf;
22 List<NativeJoint> _brackets = const <NativeJoint>[];
23 final List<NativeBody> _crates = <NativeBody>[];
25 /// Every `jointBroken` event the steps raised since the drop began.
26 @visibleForTesting
27 final List<NativeEvent> broken = <NativeEvent>[];
29 late SceneNode _shelfNode;
30 final List<MeshNode> _bracketNodes = <MeshNode>[];
31 final List<MeshNode> _crateNodes = <MeshNode>[];
33 /// Why nothing moves, or null when the core is running.
34 String? unavailable;
36 /// What each bracket holds before it lets go, N.
37 double breakForce = 150.0;
39 int _steps = 0;
41 static const double _step = 1 / 60;
43 /// Where a crate is set down, one every fifty steps.
44 static const List<double> _slots = <double>[0.28, -0.28, 0.56, 0.0, -0.56];
46 /// Where the brackets hold the shelf, along x.
47 static const List<double> _bracketsAt = <double>[-0.6, 0.6];
49 @override
50 void configureView(DemoContext context) {
51 context.orbit
52 ..distance = 5.5
53 ..pitch = 0.3
54 ..yaw = 0.45;
55 context.orbit.target.setValues(0.0, 0.9, 0.0);
56 }
58 /// A floor, a wall, and a four-kilogram shelf held to the wall by two
59 /// fixed joints. Each joint gives way once it holds the shelf with more
60 /// than [breakForce] newtons.
61 void _hang(NativeWorld world) {
62 final NativeBody floor = world.addBody(
63 position: Vector3(0.0, -0.5, 0.0),
64 type: NativeBodyType.fixed,
65 mass: 0.0,
66 );
67 world.setShape(floor, NativeShape.box(Vector3(3.0, 0.5, 2.0)));
68 _wall = world.addBody(
69 position: Vector3(0.0, 1.2, -0.35),
70 type: NativeBodyType.fixed,
71 mass: 0.0,
72 );
73 world.setShape(_wall, NativeShape.box(Vector3(1.2, 1.2, 0.1)));
74 _shelf = world.addBody(position: Vector3(0.0, 1.4, 0.0), mass: 4.0);
75 world.setShape(_shelf, NativeShape.box(Vector3(0.7, 0.03, 0.22)));
76 _brackets = <NativeJoint>[
77 for (final double x in _bracketsAt)
78 world.createJoint(
79 NativeJointType.fixed,
80 _wall,
81 _shelf,
82 anchor: Vector3(x, 1.4, -0.22),
83 ),
84 ];
85 for (final NativeJoint bracket in _brackets) {
86 world.setJointBreak(bracket, force: breakForce);
87 }
88 }
90 /// One step: a three-kilogram crate set down five centimetres over the
91 /// shelf every fifty steps, the world stepped, and the breaks it raised
92 /// kept. The other events are read and let go, so none pile up.
93 void _tick(NativeWorld world) {
94 if (_steps % 50 == 20 && _crates.length < _slots.length) {
95 final NativeBody crate = world.addBody(
96 position: Vector3(_slots[_crates.length], 1.6, 0.02),
97 mass: 3.0,
98 );
99 world
100 ..setShape(crate, NativeShape.box(Vector3.all(0.12)))
101 ..setFriction(crate, 0.8);
102 _crates.add(crate);
103 }
104 world.step(_step);
105 _steps++;
106 broken.addAll(
107 world.readEvents().where((e) => e.kind == NativeEventKind.jointBroken),
108 );
109 }
111 /// Starts the core and hangs the shelf again, or keeps the reason the core
112 /// would not start.
113 void _start() {
114 _world?.dispose();
115 _world = null;
116 _crates.clear();
117 broken.clear();
118 _steps = 0;
119 if (!physicsCoreLoaded) {
120 unavailable = 'the core is not loaded in this browser yet';
121 return;
122 }
123 try {
124 final world = NativeWorld();
125 _hang(world);
126 _world = world;
127 unavailable = null;
128 } on Object catch (e) {
129 unavailable = '$e';
130 }
131 }
133 @override
134 void dispose() {
135 _world?.dispose();
136 _world = null;
137 }
139 @override
140 Scene build(DemoContext context) {
141 _start();
142 MeshNode box(String name, Vector3 size, Vector4 color) => MeshNode(
143 DeviceMesh.upload(context.device, CuboidShape(size: size).build()),
144 RenderMaterial(name: name, baseColor: _fromSrgb(color), roughness: 0.7),
145 name: name,
146 );
147 _shelfNode = SceneNode(name: 'shelf')
148 ..add(
149 box(
150 'shelf board',
151 Vector3(1.4, 0.06, 0.44),
152 Vector4(0.62, 0.45, 0.3, 1),
153 ),
154 );
155 final Scene scene = Scene()
156 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
157 ..ambientIntensity = 0.25 * LightNode.legacyUnit
158 ..add(
159 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
160 ..setLocalForward(Vector3(-0.3, -0.7, -0.5)),
161 )
162 ..add(
163 box('floor', Vector3(6.0, 1.0, 4.0), Vector4(0.42, 0.45, 0.48, 1))
164 ..setPosition(0.0, -0.5, 0.0),
165 )
166 ..add(
167 box('wall', Vector3(2.4, 2.4, 0.2), Vector4(0.7, 0.68, 0.62, 1))
168 ..setPosition(0.0, 1.2, -0.35),
169 )
170 ..add(_shelfNode);
171 for (final (int i, double x) in _bracketsAt.indexed) {
172 final MeshNode bracket = box(
173 'bracket $i',
174 Vector3(0.06, 0.16, 0.08),
175 Vector4(0.25, 0.27, 0.3, 1),
176 )..setPosition(x, 1.35, -0.21);
177 _bracketNodes.add(bracket);
178 scene.add(bracket);
179 }
180 for (var i = 0; i < _slots.length; i++) {
181 final MeshNode crate = box(
182 'crate $i',
183 Vector3.all(0.24),
184 Vector4(
185 0.55 + 0.35 * math.sin(i * 1.1),
186 0.5 + 0.3 * math.sin(i * 1.9 + 1.0),
187 0.35 + 0.25 * math.sin(i * 2.7 + 2.0),
188 1,
189 ),
190 );
191 _crateNodes.add(crate);
192 scene.add(crate);
193 }
194 _place();
195 return scene;
196 }
198 /// The shelf and the crates where the core has them; a bracket drawn for
199 /// as long as its joint is still in the world.
200 void _place() {
201 final NativeWorld? world = _world;
202 for (final (int i, MeshNode node) in _crateNodes.indexed) {
203 node.isVisible = world != null && i < _crates.length;
204 if (node.isVisible) {
205 node
206 ..setPositionFrom(world!.localPositionOf(_crates[i]))
207 ..setRotation(world.orientationOf(_crates[i]));
208 }
209 }
210 if (world == null) {
211 _shelfNode.setPosition(0.0, 1.4, 0.0);
212 return;
213 }
214 _shelfNode
215 ..setPositionFrom(world.localPositionOf(_shelf))
216 ..setRotation(world.orientationOf(_shelf));
217 for (final (int i, NativeJoint bracket) in _brackets.indexed) {
218 _bracketNodes[i].isVisible = world.containsJoint(bracket);
219 }
220 }
222 @override
223 void update(DemoContext context, double dt) {
224 final NativeWorld? world = _world;
225 if (world == null) return;
226 _tick(world);
227 if (_steps > 420) _start();
228 _place();
229 }
231 @override
232 List<DemoControl> controls(DemoContext context) => <DemoControl>[
233 SliderControl(
234 'Bracket breaks past',
235 min: 60.0,
236 max: 250.0,
237 divisions: 19,
238 value: () => breakForce,
239 onChanged: (double v) {
240 breakForce = v;
241 _start();
242 },
243 format: (double v) => '${v.round()} N',
244 ),
245 ToggleControl(
246 unavailable == null
247 ? 'Hang it again'
248 : 'Hang it again (unavailable: $unavailable)',
249 value: () => false,
250 onChanged: (bool v) {
251 if (v) _start();
252 },
253 ),
254 ];
256 /// Steps the drop on until [steps] steps have been taken since it began.
257 @visibleForTesting
258 void runTo(int steps) {
259 final NativeWorld world = _world!;
260 while (_steps < steps) {
261 _tick(world);
262 }
263 }
265 @override
266 void verify(Scene scene, FrameResult frame) {
267 if (unavailable != null) {
268 throw StateError('the core did not start: $unavailable');
269 }
270 breakForce = 150.0;
271 _start();
272 final NativeWorld world = _world!;
273 // Four crates on: 16 kg, held half by each bracket, 78.5 N apiece, and
274 // under the 150 they break past.
275 runTo(210);
276 for (final NativeJoint bracket in _brackets) {
277 if (!world.containsJoint(bracket)) {
278 throw StateError('a bracket let go under four crates');
279 }
280 final double held = world.jointForce(bracket).y;
281 if ((held - 78.5).abs() > 1.5) {
282 throw StateError('a bracket holds ${held.toStringAsFixed(1)} N');
283 }
284 }
285 // The fifth crate's landing takes both past it. Each break is an event
286 // that names the wall and the shelf, and the shelf ends on the floor.
287 runTo(300);
288 if (_brackets.any(world.containsJoint)) {
289 throw StateError('a bracket held under five crates');
290 }
291 if (broken.length != 2 ||
292 broken.any((e) => e.body != _wall || e.other != _shelf)) {
293 throw StateError('the breaks were told as $broken');
294 }
295 final double shelfAt = world.localPositionOf(_shelf).y;
296 if (shelfAt > 0.1) {
297 throw StateError('the shelf hangs at $shelfAt m with no brackets');
298 }
299 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
300 }
303/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
304LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);