A ragdoll: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: figure (line 48), world (line 192), push (line 224), bones (line 270), check (line 342).
1/// A ragdoll of eleven capsules on ten joints, standing at the top of a
2/// short flight of stairs and pushed down it.
3///
4/// Quoted by `ragdoll.md` and shown whole in the Source tab.
5library;
7import 'dart:math' as math;
9import 'package:flutter3d/flutter3d.dart';
10import 'package:flutter3d_physics/flutter3d_physics.dart'
11 show SegmentMassShares, referenceBodyMass;
12import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
13import 'package:flutter3d_showcase/src/demo/demo.dart';
15/// The `ragdoll` page: eleven capsules on ten joints pushed down a flight of
16/// stairs. Its check is that it goes down, comes to rest with its joints
17/// closed, and leaves no bone in the floor.
18final class RagdollDemo extends ShowcaseDemo {
19 NativeWorld? _world;
20 NativeRagdoll? _doll;
22 /// Why nothing moves: the core would not start. Null when it did.
23 String? unavailable;
25 final List<MeshNode> _bones = <MeshNode>[];
26 double _age = 0.0;
28 static const double _step = 1 / 60;
30 /// The stairs: four steps of [_rise] up and [_run] deep, the top one a
31 /// landing that reaches back to x = −1.5.
32 static const int _steps = 4;
33 static const double _rise = 0.25;
34 static const double _run = 0.45;
36 /// Where the figure's feet stand: on the landing, a centimetre above it.
37 static Vector3 get _feet => Vector3(-0.4, _steps * _rise + 0.01, 0.0);
40 void configureView(DemoContext context) {
41 context.orbit
42 ..distance = 6.0
43 ..pitch = 0.35
44 ..yaw = 0.6;
45 context.orbit.target.setValues(0.5, 0.7, 0.0);
46 }
48 /// A figure standing with its feet at [o]: hips, chest, head, two arms
49 /// and two legs, each bone from its head (where it meets its parent) to
50 /// its tail, with a radius and a mass — the reference man's 73 kg shared
51 /// as de Leva measured (`SegmentMassShares`), a forearm with its hand and a
52 /// shin with its foot. Its spine and neck are ball joints
53 /// in a narrow cone, the shoulders and hips wide ones, the elbows and
54 /// knees hinges that bend one way.
55 static List<RagdollBone> _figure(Vector3 o) {
56 const spine = RagdollBall(cone: 0.5, twistLower: -0.4, twistUpper: 0.4);
57 const shoulder = RagdollBall(cone: 1.5, twistLower: -1.0, twistUpper: 1.0);
58 const hip = RagdollBall(cone: 1.2, twistLower: -0.5, twistUpper: 0.5);
59 final elbow = RagdollHinge(axis: Vector3(1, 0, 0), lower: 0, upper: 2.4);
60 final knee = RagdollHinge(axis: Vector3(1, 0, 0), lower: -2.4, upper: 0);
61 double kg(double share) => referenceBodyMass * share;
62 RagdollBone bone(
63 String name,
64 int parent,
65 (double, double, double) head,
66 (double, double, double) tail,
67 double radius,
68 double mass, [
69 RagdollJoint? joint,
70 ]) => RagdollBone(
71 name: name,
72 parent: parent,
73 head: o + Vector3(head.$1, head.$2, head.$3),
74 tail: o + Vector3(tail.$1, tail.$2, tail.$3),
75 orientation: Quaternion.identity(),
76 radius: radius,
77 mass: mass,
78 joint: joint,
79 );
80 return <RagdollBone>[
81 bone(
82 'hips',
83 -1,
84 (0, 0.92, 0),
85 (0, 1.1, 0),
86 0.13,
87 kg(SegmentMassShares.lowerTrunk),
88 ),
89 bone(
90 'chest',
91 0,
92 (0, 1.1, 0),
93 (0, 1.55, 0),
94 0.15,
95 kg(SegmentMassShares.upperTrunk + SegmentMassShares.middleTrunk),
96 spine,
97 ),
98 bone(
99 'head',
100 1,
101 (0, 1.58, 0),
102 (0, 1.82, 0),
103 0.11,
104 kg(SegmentMassShares.head),
105 spine,
106 ),
107 bone(
108 'arm.L',
109 1,
110 (-0.25, 1.5, 0),
111 (-0.25, 1.2, 0),
112 0.05,
113 kg(SegmentMassShares.upperArm),
114 shoulder,
115 ),
116 bone(
117 'arm.R',
118 1,
119 (0.25, 1.5, 0),
120 (0.25, 1.2, 0),
121 0.05,
122 kg(SegmentMassShares.upperArm),
123 shoulder,
124 ),
125 bone(
126 'forearm.L',
127 3,
128 (-0.25, 1.2, 0),
129 (-0.25, 0.92, 0),
130 0.045,
131 kg(SegmentMassShares.forearm + SegmentMassShares.hand),
132 elbow,
133 ),
134 bone(
135 'forearm.R',
136 4,
137 (0.25, 1.2, 0),
138 (0.25, 0.92, 0),
139 0.045,
140 kg(SegmentMassShares.forearm + SegmentMassShares.hand),
141 elbow,
142 ),
143 bone(
144 'thigh.L',
145 0,
146 (-0.1, 0.92, 0),
147 (-0.1, 0.5, 0),
148 0.07,
149 kg(SegmentMassShares.thigh),
150 hip,
151 ),
152 bone(
153 'thigh.R',
154 0,
155 (0.1, 0.92, 0),
156 (0.1, 0.5, 0),
157 0.07,
158 kg(SegmentMassShares.thigh),
159 hip,
160 ),
161 bone(
162 'shin.L',
163 7,
164 (-0.1, 0.5, 0),
165 (-0.1, 0.06, 0),
166 0.055,
167 kg(SegmentMassShares.shank + SegmentMassShares.foot),
168 knee,
169 ),
170 bone(
171 'shin.R',
172 8,
173 (0.1, 0.5, 0),
174 (0.1, 0.06, 0),
175 0.055,
176 kg(SegmentMassShares.shank + SegmentMassShares.foot),
177 knee,
178 ),
179 ];
180 }
182 /// The floor's and each step's box, as centre and half extents.
183 static List<(Vector3, Vector3)> get _blocks => <(Vector3, Vector3)>[
184 (Vector3(0.0, -0.5, 0.0), Vector3(6.0, 0.5, 3.0)),
185 for (var i = 0; i < _steps; i++)
186 (
187 Vector3((-1.5 + (i + 1) * _run) / 2, (_steps - i) * _rise / 2, 0.0),
188 Vector3(((i + 1) * _run + 1.5) / 2, (_steps - i) * _rise / 2, 1.2),
189 ),
190 ];
192 /// A world with the floor and the stairs as fixed boxes, and the figure
193 /// standing on the landing. Eight substeps a step, not four: at four, a
194 /// limb struck on a stair's edge can swing past its cone for a step.
195 void _build() {
196 unavailable = null;
197 _world = null;
198 _doll = null;
199 if (!physicsCoreLoaded) {
200 unavailable = 'the core is not loaded in this browser yet';
201 return;
202 }
203 final NativeWorld world;
204 try {
205 world = NativeWorld()..substeps = 8;
206 } on Object catch (e) {
207 unavailable = '$e';
208 return;
209 }
210 for (final (Vector3 center, Vector3 half) in _blocks) {
211 final NativeBody block = world.addBody(
212 position: center,
213 type: NativeBodyType.fixed,
214 mass: 0.0,
215 );
216 world.setShape(block, NativeShape.box(half));
217 }
218 _world = world;
219 // Every joint's tissue damps its turning, the default; without it a
220 // ragdoll on the floor never comes to rest.
221 _doll = NativeRagdoll(world, _figure(_feet));
222 }
224 /// A shove to the chest, forward and a little to the side: ninety-five
225 /// newton seconds on its 23.6 kilograms, four metres a second.
226 void _push() {
227 final NativeRagdoll? doll = _doll;
228 if (doll == null) return;
229 _world!.applyImpulse(doll.bodyOf(1), Vector3(95.0, 0.0, 12.5));
230 }
232 void _restart() {
233 _world?.dispose();
234 _build();
235 _push();
236 _age = 0.0;
237 }
240 void dispose() => _world?.dispose();
243 Scene build(DemoContext context) {
244 _build();
245 _push();
246 final Scene scene = Scene()
247 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
248 ..ambientIntensity = 0.3 * LightNode.legacyUnit
249 ..add(
250 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
251 ..setLocalForward(Vector3(-0.4, -0.7, -0.3)),
252 );
253 final stone = RenderMaterial(
254 name: 'stone',
255 baseColor: LinearColor.fromSrgb(0.5, 0.5, 0.52, 1.0),
256 roughness: 0.8,
257 );
258 for (final (Vector3 center, Vector3 half) in _blocks) {
259 scene.add(
260 MeshNode(
261 DeviceMesh.upload(
262 context.device,
263 CuboidShape(size: half * 2.0).build(),
264 ),
265 stone,
266 name: 'block',
267 )..setPositionFrom(center),
268 );
269 }
270 // Each bone drawn as the capsule its body is: along the body's own y,
271 // its straight part as long as the bone less its two rounded ends.
272 final cloth = RenderMaterial(
273 name: 'ragdoll',
274 baseColor: LinearColor.fromSrgb(0.8, 0.55, 0.35, 1.0),
275 roughness: 0.6,
276 );
277 for (final RagdollBone bone in _figure(_feet)) {
278 final double length = bone.head.distanceTo(bone.tail);
279 final double straight = math.max(0.02, length - 2 * bone.radius);
280 final node = MeshNode(
281 DeviceMesh.upload(
282 context.device,
283 CapsuleShape(radius: bone.radius, height: straight).build(),
284 ),
285 cloth,
286 name: bone.name,
287 );
288 _bones.add(node);
289 scene.add(node);
290 }
291 _place();
292 return scene;
293 }
295 void _place() {
296 final NativeRagdoll? doll = _doll;
297 if (doll == null) return;
298 for (var i = 0; i < _bones.length; i++) {
299 final NativeBody body = doll.bodyOf(i);
300 _bones[i]
301 ..setPositionFrom(doll.world.localPositionOf(body))
302 ..setRotation(doll.world.orientationOf(body));
303 }
304 }
307 void update(DemoContext context, double dt) {
308 final NativeWorld? world = _world;
309 if (world == null) return;
310 world.step(_step);
311 _age += dt;
312 if (_age > 8.0) _restart();
313 _place();
314 }
317 List<DemoControl> controls(DemoContext context) => <DemoControl>[
318 ToggleControl(
319 unavailable == null
320 ? 'Push it again'
321 : 'Push it again (the core is unavailable: $unavailable)',
322 value: () => false,
323 onChanged: (bool v) {
324 if (!v) return;
325 _push();
326 _age = 0.0;
327 },
328 ),
329 ToggleControl(
330 'Stand it up again',
331 value: () => false,
332 onChanged: (bool v) {
333 if (v) _restart();
334 },
335 ),
336 ];
339 void verify(Scene scene, FrameResult frame) {
340 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
341 if (unavailable != null) return;
342 // From the push until it sleeps, each bone's head read against its
343 // parent's after every step: how far apart they are against how far
344 // apart they were built.
345 _restart();
346 final NativeRagdoll doll = _doll!;
347 final List<RagdollBone> bones = doll.bones;
348 final double hipsFrom = doll.poseOf(0).position.y;
349 var stretched = 0.0;
350 var steps = 0;
351 while (!doll.isAsleep && steps < 900) {
352 _world!.step(_step);
353 steps++;
354 for (var i = 1; i < bones.length; i++) {
355 final RagdollBone b = bones[i];
356 final double built = b.head.distanceTo(bones[b.parent].head);
357 final double now = doll
358 .poseOf(i)
359 .position
360 .distanceTo(doll.poseOf(b.parent).position);
361 stretched = math.max(stretched, (now - built).abs());
362 }
363 }
364 if (!doll.isAsleep) throw StateError('it never came to rest');
365 // No joint opens by more than 3 cm on the way down.
366 if (stretched > 0.03) {
367 throw StateError('a joint opened by ${stretched.toStringAsFixed(3)} m');
368 }
369 // It came down the stairs, and nothing ended inside the floor: a
370 // capsule lying on it has its centre a radius up.
371 if (doll.poseOf(0).position.y > hipsFrom - 0.5) {
372 throw StateError('it never went down the stairs');
373 }
374 for (var i = 0; i < bones.length; i++) {
375 final double y = _world!.localPositionOf(doll.bodyOf(i)).y;
376 if (y < bones[i].radius - 0.01) {
377 throw StateError('${bones[i].name} ended in the floor at $y');
378 }
379 }
380 }
381}