flutter3d
Showcase Changelog 62 packages API reference

Joints and motors: the source

since 1.0.0-rc.1 Physics and particles

Regions the guide quotes: hinge (line 83), slider (line 105), ball (line 138), distance (line 161), step (line 354), check (line 380).

1/// The core's joints in a row: a hinge swinging into its limits, a slider
2/// driven by a motor, a ball joint held in a cone, and one distance joint
3/// three ways, as a rod, a spring and a rope.
4///
5/// Quoted by `joints_and_motors.md` and shown whole in the Source tab.
6library;
7
8import 'dart:math' as math;
9
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
12import 'package:flutter3d_showcase/src/demo/demo.dart';
14/// Everything the row is made of in one world: the joints, and the bodies
15/// they hold, in the order the scene draws them.
16final class _Row {
17 _Row(this.world);
19 final NativeWorld world;
20 late final NativeJoint hinge, slider, ball, rod, spring, rope;
21 late final NativeBody arm, cart, limb, rodWeight, springWeight, ropeWeight;
23 List<NativeBody> get moving => <NativeBody>[
24 arm,
25 cart,
26 limb,
27 rodWeight,
28 springWeight,
29 ropeWeight,
30 ];
33/// The `joints-and-motors` page: a hinge, a motor-driven slider, a ball
34/// joint in a cone and a distance joint as rod, spring and rope, stepped on
35/// the physics core.
36final class JointsAndMotorsDemo extends ShowcaseDemo {
37 _Row? _row;
39 /// Why nothing moves: the core would not start. Null when it did.
40 String? unavailable;
42 final List<MeshNode> _meshes = <MeshNode>[];
43 final List<MeshNode> _cords = <MeshNode>[];
44 double _age = 0.0;
45 double _speed = 0.6;
47 static const double _step = 1 / 60;
49 /// Where each station's fixed point is.
50 static Vector3 get _hingeAt => Vector3(-5.0, 3.0, 0.0);
51 static Vector3 get _railAt => Vector3(-3.0, 1.5, 0.0);
52 static Vector3 get _shoulderAt => Vector3(-1.0, 3.0, 0.0);
53 static final List<Vector3> _hooks = <Vector3>[
54 Vector3(1.0, 3.0, 0.0),
55 Vector3(3.0, 3.0, 0.0),
56 Vector3(5.0, 3.0, 0.0),
57 ];
59 static const double _limit = 0.5;
60 static const double _travel = 0.8;
61 static const double _cone = 0.6;
62 static const double _twist = 0.3;
63 static const double _rodLength = 1.5;
64 static const double _ropeLength = 1.5;
65 static const ({double length, double least, double most}) _springLength = (
66 length: 1.2,
67 least: 0.6,
68 most: 1.8,
69 );
71 @override
72 void configureView(DemoContext context) {
73 context.orbit
74 ..distance = 13.0
75 ..pitch = 0.15
76 ..yaw = 0.0;
77 context.orbit.target.setValues(0.0, 2.0, 0.0);
78 }
80 static NativeBody _fixed(NativeWorld w, Vector3 at) =>
81 w.addBody(position: at, type: NativeBodyType.fixed, mass: 0.0);
83 /// A bar hung from a pin, free to turn about z but only half a radian
84 /// either way, and started swinging hard enough to reach both stops.
85 static void _hinge(_Row row) {
86 final NativeWorld w = row.world;
87 final NativeBody pin = _fixed(w, _hingeAt);
88 row.arm = w.addBody(position: _hingeAt - Vector3(0.0, 0.6, 0.0), mass: 2.0);
89 w.setShape(row.arm, NativeShape.box(Vector3(0.06, 0.6, 0.06)));
90 row.hinge = w.createJoint(
91 NativeJointType.revolute,
92 pin,
93 row.arm,
94 anchor: _hingeAt,
95 axis: Vector3(0.0, 0.0, 1.0),
96 );
97 w
98 ..setJointLimits(row.hinge, JointLimits(lower: -_limit, upper: _limit))
99 // Five radians a second about the pin; its centre, 0.6 m below,
100 // moves at three metres a second.
101 ..setAngularVelocity(row.arm, Vector3(0.0, 0.0, 5.0))
102 ..setVelocity(row.arm, Vector3(3.0, 0.0, 0.0));
103 }
105 /// A carriage on a rail along x, its travel limited to 0.8 m each way
106 /// and a motor driving it at [speed] with at most forty newtons.
107 static void _slider(_Row row, double speed) {
108 final NativeWorld w = row.world;
109 final NativeBody rail = _fixed(w, _railAt);
110 row.cart = w.addBody(position: _railAt.clone(), mass: 1.0);
111 w.setShape(row.cart, NativeShape.box(Vector3(0.15, 0.1, 0.15)));
112 row.slider = w.createJoint(
113 NativeJointType.prismatic,
114 rail,
115 row.cart,
116 anchor: _railAt,
117 axis: Vector3(1.0, 0.0, 0.0),
118 );
119 w
120 ..setJointLimits(row.slider, JointLimits(lower: -_travel, upper: _travel))
121 ..setJointMotor(row.slider, JointMotor(speed: speed, maxForce: 40.0));
122 }
124 /// Turns the motor round at either end of the rail, so the carriage runs
125 /// back and forth.
126 void _drive(_Row row) {
127 final double at = row.world.jointValue(row.slider);
128 if (at > _travel - 0.05 && _speed > 0 ||
129 at < -_travel + 0.05 && _speed < 0) {
130 _speed = -_speed;
131 row.world.setJointMotor(
132 row.slider,
133 JointMotor(speed: _speed, maxForce: 40.0),
134 );
135 }
136 }
138 /// A limb hung from a ball joint: it swings any way, but its axis stays
139 /// within 0.6 rad of straight down, its twist about itself within ±0.3,
140 /// and a little friction lets it settle.
141 static void _ball(_Row row) {
142 final NativeWorld w = row.world;
143 final NativeBody shoulder = _fixed(w, _shoulderAt);
144 row.limb = w.addBody(position: _shoulderAt - Vector3(0.0, 0.5, 0.0));
145 w.setShape(row.limb, NativeShape.box(Vector3(0.05, 0.5, 0.05)));
146 row.ball = w.createJoint(
147 NativeJointType.spherical,
148 shoulder,
149 row.limb,
150 anchor: _shoulderAt,
151 axis: Vector3(0.0, -1.0, 0.0),
152 );
153 w
154 ..setJointCone(row.ball, _cone)
155 ..setJointLimits(row.ball, JointLimits(lower: -_twist, upper: _twist))
156 ..setJointFriction(row.ball, 0.2)
157 ..setVelocity(row.limb, Vector3(4.0, 0.0, 2.0))
158 ..setAngularVelocity(row.limb, Vector3(-4.0, 8.0, 8.0));
159 }
161 /// One distance joint, made three ways. It is made at the length between
162 /// its two points now, which is a rod. A spring is the same joint with a
163 /// rest length, a least and a most, and a frequency. A rope is a spring
164 /// of nought hertz that may be anything from nought to its most: slack
165 /// until it is taut.
166 static void _distances(_Row row) {
167 final NativeWorld w = row.world;
168 NativeJoint hang(Vector3 hook, NativeBody weight) => w.createDistanceJoint(
169 _fixed(w, hook),
170 weight,
171 anchorA: hook,
172 anchorB: w.localPositionOf(weight),
173 );
174 NativeBody weight(Vector3 at) {
175 final NativeBody b = w.addBody(position: at);
176 w.setShape(b, const NativeShape.sphere(0.15));
177 return b;
178 }
180 // A rod 1.5 m long, the weight pushed sideways.
181 row.rodWeight = weight(_hooks[0] - Vector3(0.0, _rodLength, 0.0));
182 row.rod = hang(_hooks[0], row.rodWeight);
183 w.setVelocity(row.rodWeight, Vector3(3.0, 0.0, 0.0));
185 // A spring that rests at 1.2 m, let go stretched to 1.5.
186 row.springWeight = weight(_hooks[1] - Vector3(0.0, 1.5, 0.0));
187 row.spring = hang(_hooks[1], row.springWeight);
188 w
189 ..setJointLength(
190 row.spring,
191 length: _springLength.length,
192 least: _springLength.least,
193 most: _springLength.most,
194 )
195 ..setJointSpring(row.spring, JointSpring(hertz: 1.2, damping: 0.05));
197 // A rope 1.5 m long, its weight let go beside the hook: it falls
198 // slack until the rope catches it.
199 row.ropeWeight = weight(_hooks[2] + Vector3(0.3, -0.2, 0.0));
200 row.rope = hang(_hooks[2], row.ropeWeight);
201 w
202 ..setJointLength(
203 row.rope,
204 length: _ropeLength,
205 least: 0.0,
206 most: _ropeLength,
207 )
208 ..setJointSpring(row.rope, JointSpring(hertz: 0.0, damping: 0.0))
209 ..setVelocity(row.ropeWeight, Vector3(1.0, 0.0, 0.0));
210 }
212 /// A new world with the whole row in it, or null when the core will not
213 /// start, with the reason kept in [unavailable].
214 _Row? _build() {
215 unavailable = null;
216 if (!physicsCoreLoaded) {
217 unavailable = 'the core is not loaded in this browser yet';
218 return null;
219 }
220 final NativeWorld world;
221 try {
222 world = NativeWorld();
223 } on Object catch (e) {
224 unavailable = '$e';
225 return null;
226 }
227 _speed = 0.6;
228 final row = _Row(world);
229 _hinge(row);
230 _slider(row, _speed);
231 _ball(row);
232 _distances(row);
233 return row;
234 }
236 void _restart() {
237 _row?.world.dispose();
238 _row = _build();
239 _age = 0.0;
240 }
242 @override
243 void dispose() => _row?.world.dispose();
245 @override
246 Scene build(DemoContext context) {
247 _row = _build();
248 final Scene scene = Scene()
249 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
250 ..ambientIntensity = 0.3 * LightNode.legacyUnit
251 ..add(
252 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
253 ..setLocalForward(Vector3(-0.3, -0.6, -0.5)),
254 );
255 DeviceMesh upload(MeshData data) => DeviceMesh.upload(context.device, data);
256 RenderMaterial paint(String name, double r, double g, double b) =>
257 RenderMaterial(
258 name: name,
259 baseColor: LinearColor.fromSrgb(r, g, b, 1.0),
260 roughness: 0.6,
261 );
263 scene.add(
264 MeshNode(
265 upload(CuboidShape(size: Vector3(13.0, 0.1, 3.0)).build()),
266 paint('floor', 0.42, 0.44, 0.47),
267 name: 'floor',
268 )..setPosition(0.0, -0.05, 0.0),
269 );
270 // The fixed points: a pin, a rail, a shoulder and three hooks.
271 final DeviceMesh pin = upload(const SphereShape(radius: 0.07).build());
272 final RenderMaterial steel = paint('steel', 0.3, 0.32, 0.36);
273 for (final Vector3 at in <Vector3>[_hingeAt, _shoulderAt, ..._hooks]) {
274 scene.add(MeshNode(pin, steel, name: 'pin')..setPositionFrom(at));
275 }
276 scene.add(
277 MeshNode(
278 upload(
279 CuboidShape(size: Vector3(2 * _travel + 0.3, 0.04, 0.04)).build(),
280 ),
281 steel,
282 name: 'rail',
283 )..setPosition(_railAt.x, _railAt.y - 0.12, _railAt.z),
284 );
285 // The moving bodies, in the order [_Row.moving] gives them.
286 final DeviceMesh ball = upload(const SphereShape(radius: 0.15).build());
287 _meshes.addAll(<MeshNode>[
288 MeshNode(
289 upload(CuboidShape(size: Vector3(0.12, 1.2, 0.12)).build()),
290 paint('hinged bar', 0.8, 0.55, 0.3),
291 name: 'hinged bar',
292 ),
293 MeshNode(
294 upload(CuboidShape(size: Vector3(0.3, 0.2, 0.3)).build()),
295 paint('carriage', 0.35, 0.6, 0.8),
296 name: 'carriage',
297 ),
298 MeshNode(
299 upload(CuboidShape(size: Vector3(0.1, 1.0, 0.1)).build()),
300 paint('limb', 0.75, 0.45, 0.55),
301 name: 'limb',
302 ),
303 MeshNode(ball, paint('rod weight', 0.55, 0.55, 0.6), name: 'rod weight'),
304 MeshNode(ball, paint('spring weight', 0.4, 0.7, 0.4), name: 'spring'),
305 MeshNode(ball, paint('rope weight', 0.8, 0.7, 0.35), name: 'rope weight'),
306 ]);
307 // A cord from each hook to its weight, a unit cylinder stretched.
308 final DeviceMesh cord = upload(
309 const CylinderShape(
310 radiusTop: 0.02,
311 radiusBottom: 0.02,
312 height: 1.0,
313 ).build(),
314 );
315 _cords.addAll(<MeshNode>[
316 MeshNode(cord, steel, name: 'rod'),
317 MeshNode(cord, paint('spring', 0.3, 0.6, 0.3), name: 'spring'),
318 MeshNode(cord, paint('rope', 0.6, 0.5, 0.3), name: 'rope'),
319 ]);
320 _meshes.forEach(scene.add);
321 _cords.forEach(scene.add);
322 _place();
323 return scene;
324 }
326 /// Every mesh where its body is, and every cord from its hook to its
327 /// weight.
328 void _place() {
329 final _Row? row = _row;
330 if (row == null) return;
331 final List<NativeBody> moving = row.moving;
332 for (var i = 0; i < moving.length; i++) {
333 _meshes[i]
334 ..setPositionFrom(row.world.localPositionOf(moving[i]))
335 ..setRotation(row.world.orientationOf(moving[i]));
336 }
337 final List<NativeBody> weights = moving.sublist(3);
338 for (var i = 0; i < _cords.length; i++) {
339 final Vector3 to = row.world.localPositionOf(weights[i]);
340 final Vector3 along = to - _hooks[i];
341 _cords[i]
342 ..setPositionFrom((to + _hooks[i]) * 0.5)
343 ..setRotation(
344 Quaternion.fromTwoVectors(Vector3(0.0, 1.0, 0.0), along.normalized()),
345 )
346 ..setScale(1.0, along.length, 1.0);
347 }
348 }
350 @override
351 void update(DemoContext context, double dt) {
352 final _Row? row = _row;
353 if (row == null) return;
354 _drive(row);
355 row.world.step(_step);
356 _age += dt;
357 if (_age > 12.0) _restart();
358 _place();
359 }
361 @override
362 List<DemoControl> controls(DemoContext context) => <DemoControl>[
363 ToggleControl(
364 unavailable == null
365 ? 'Start again'
366 : 'Start again (the core is unavailable: $unavailable)',
367 value: () => false,
368 onChanged: (bool v) {
369 if (v) _restart();
370 },
371 ),
372 ];
374 @override
375 void verify(Scene scene, FrameResult frame) {
376 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
377 // Where the core does not start there is nothing to hold it to; the
378 // control says why.
379 if (unavailable != null) return;
380 // Six seconds from the start, every joint read after every step.
381 _restart();
382 final _Row row = _row!;
383 final NativeWorld w = row.world;
384 var hinge = 0.0, swing = 0.0, twist = 0.0, rod = 0.0;
385 var ropeLeast = double.infinity, ropeMost = 0.0;
386 var springLeast = double.infinity, springMost = 0.0;
387 var cartSpeed = 0.0;
388 for (var i = 0; i < 360; i++) {
389 _drive(row);
390 w.step(_step);
391 hinge = math.max(hinge, w.jointValue(row.hinge).abs());
392 swing = math.max(swing, w.jointSwing(row.ball));
393 twist = math.max(twist, w.jointValue(row.ball).abs());
394 rod = math.max(rod, (w.jointValue(row.rod) - _rodLength).abs());
395 ropeLeast = math.min(ropeLeast, w.jointValue(row.rope));
396 ropeMost = math.max(ropeMost, w.jointValue(row.rope));
397 springLeast = math.min(springLeast, w.jointValue(row.spring));
398 springMost = math.max(springMost, w.jointValue(row.spring));
399 // Two thirds of a second in, the carriage is halfway along the rail.
400 if (i == 40) cartSpeed = w.velocityOf(row.cart).x;
401 }
402 void claim(bool holds, String what) {
403 if (!holds) throw StateError(what);
404 }
406 // The hinge reaches its stops and never goes more than 2° past them.
407 claim(hinge > _limit - 0.1, 'the hinge never reached its limits: $hinge');
408 claim(hinge < _limit + 0.035, 'the hinge went past its limits: $hinge');
409 // The slider runs at the motor's speed.
410 claim((cartSpeed - 0.6).abs() < 0.01, 'the slider ran at $cartSpeed m/s');
411 // The ball joint swings out to its cone and stays in it, and its twist
412 // in its limits.
413 claim(swing > _cone - 0.15 && swing < _cone + 0.05, 'swing $swing');
414 claim(twist > _twist - 0.1 && twist < _twist + 0.05, 'twist $twist');
415 // The rod holds its length to 5 mm; the rope is slack, then taut, and
416 // never longer than itself; the spring stays between its least and most.
417 claim(rod < 0.005, 'the rod changed length by $rod m');
418 claim(ropeLeast < 1.0, 'the rope was never slack: $ropeLeast');
419 claim(ropeMost > _ropeLength - 0.01, 'the rope never went taut');
420 claim(ropeMost < _ropeLength + 0.005, 'the rope stretched to $ropeMost');
421 claim(
422 springLeast >= _springLength.least && springMost <= _springLength.most,
423 'the spring went from $springLeast to $springMost m',
424 );
425 claim(springMost - springLeast > 0.1, 'the spring never moved');
426 }