flutter3d
Showcase Changelog 62 packages API reference

The physics core: the source

since 1.0.0-rc.1 Physics and particles

Regions the guide quotes: backends (line 64), drop (line 84), step (line 194), check (line 243).

1/// The same drop twice, side by side: the left pile stepped by the Dart
2/// reference, the right one by the physics core in C. Both are the same
3/// `RigidBody` objects on the same kind of `CollisionWorld`; only the
4/// backend that steps them differs.
5///
6/// Quoted by `physics_core.md` and shown whole in the Source tab.
7library;
8
9import 'dart:math' as math;
11import 'package:flutter/foundation.dart' show visibleForTesting;
12import 'package:flutter3d/flutter3d.dart';
13import 'package:flutter3d_physics/flutter3d_physics.dart';
14import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
15import 'package:flutter3d_showcase/src/demo/demo.dart';
17/// One pile: its world, what steps it and the crates in it.
18final class _Pile {
19 _Pile(this.world, this.dynamics, this.crates);
21 final CollisionWorld world;
22 final RigidDynamics dynamics;
23 final List<RigidBody> crates;
26/// The `physics-core` page: the same pile of crates stepped by the Dart
27/// reference on the left and the physics core on the right. Its check is
28/// that both piles rest on their floors and agree.
29final class PhysicsCoreDemo extends ShowcaseDemo {
30 late _Pile _left;
31 late _Pile _right;
32 final List<MeshNode> _leftMeshes = <MeshNode>[];
33 final List<MeshNode> _rightMeshes = <MeshNode>[];
35 /// Whether the right pile asks for the core. Off, both piles are the
36 /// reference, and they move as one.
37 bool onCore = true;
39 /// Why the right pile is on the reference although it asked for the core,
40 /// or null when it is not.
41 String? fallback;
43 double _age = 0.0;
45 static const int _count = 6;
46 static const double _step = 1 / 60;
48 /// How far apart the two piles stand, in metres along x.
49 static const double _apart = 2.6;
51 /// The right pile's dynamics, for a test that checks what steps it.
52 @visibleForTesting
53 RigidDynamics get rightDynamics => _right.dynamics;
55 @override
56 void configureView(DemoContext context) {
57 context.orbit
58 ..distance = 10.0
59 ..pitch = 0.3
60 ..yaw = 0.0;
61 context.orbit.target.setValues(0.0, 1.2, 0.0);
62 }
64 /// The backend the right pile is stepped by: the core where it starts,
65 /// the reference where it does not, and the reason kept to say so.
66 PhysicsBackend _rightBackend() {
67 fallback = null;
68 if (!onCore) return const DartPhysics();
69 if (!physicsCoreLoaded) {
70 fallback = 'the core is not loaded in this browser yet';
71 return const DartPhysics();
72 }
73 try {
74 // Made and freed at once: the first call that would find a missing
75 // library or bindings for another ABI.
76 NativeWorld().dispose();
77 return NativePhysics();
78 } on Object catch (e) {
79 fallback = '$e';
80 return const DartPhysics();
81 }
82 }
84 /// A floor and six crates over it, nearly in a column, on [backend]. Both
85 /// piles are built by this, with the same numbers, so any difference
86 /// between them is the backend's.
87 static _Pile _drop(PhysicsBackend backend) {
88 final world = CollisionWorld()
89 ..addBox(Vector3(0.0, -0.5, 0.0), Vector3(2.4, 1.0, 2.4));
90 final RigidDynamics dynamics = backend.dynamics(DynamicsRequest(world));
91 final crates = <RigidBody>[
92 for (var i = 0; i < _count; i++)
93 dynamics.add(
94 RigidBody(
95 world: world,
96 shape: CollisionBox(Vector3.all(0.3)),
97 position: Vector3(
98 0.12 * math.sin(i * 2.4),
99 1.0 + i * 0.9,
100 0.12 * math.cos(i * 1.9),
101 ),
102 mass: 2.0,
103 friction: 0.7,
104 ),
105 ),
106 ];
107 return _Pile(world, dynamics, crates);
108 }
110 void _release(_Pile pile) {
111 if (pile.dynamics case final NativeDynamics core) core.dispose();
112 }
114 void _restart() {
115 _release(_left);
116 _release(_right);
117 _left = _drop(const DartPhysics());
118 _right = _drop(_rightBackend());
119 _age = 0.0;
120 }
122 @override
123 void dispose() {
124 _release(_left);
125 _release(_right);
126 }
128 @override
129 Scene build(DemoContext context) {
130 _left = _drop(const DartPhysics());
131 _right = _drop(_rightBackend());
133 final Scene scene = Scene()
134 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
135 ..ambientIntensity = 0.25 * LightNode.legacyUnit
136 ..add(
137 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
138 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
139 );
140 for (final (double x, String side, Vector4 color)
141 in <(double, String, Vector4)>[
142 (-_apart, 'reference', Vector4(0.45, 0.47, 0.5, 1.0)),
143 (_apart, 'core', Vector4(0.42, 0.5, 0.43, 1.0)),
144 ]) {
145 scene.add(
146 MeshNode(
147 DeviceMesh.upload(
148 context.device,
149 CuboidShape(size: Vector3(2.4, 1.0, 2.4)).build(),
150 ),
151 RenderMaterial(name: 'floor $side', baseColor: _fromSrgb(color)),
152 name: 'floor $side',
153 )..setPosition(x, -0.5, 0.0),
154 );
155 }
156 final DeviceMesh crate = DeviceMesh.upload(
157 context.device,
158 CuboidShape(size: Vector3.all(0.6)).build(),
159 );
160 for (var i = 0; i < _count; i++) {
161 final material = RenderMaterial(
162 name: 'crate $i',
163 baseColor: LinearColor.fromSrgb(
164 0.55 + 0.4 * math.sin(i * 0.9),
165 0.5 + 0.3 * math.sin(i * 1.7 + 1.0),
166 0.35 + 0.3 * math.sin(i * 2.3 + 2.0),
167 1.0,
168 ),
169 roughness: 0.7,
170 );
171 final left = MeshNode(crate, material, name: 'reference crate $i');
172 final right = MeshNode(crate, material, name: 'core crate $i');
173 _leftMeshes.add(left);
174 _rightMeshes.add(right);
175 scene
176 ..add(left)
177 ..add(right);
178 }
179 _place();
180 return scene;
181 }
183 void _place() {
184 for (var i = 0; i < _count; i++) {
185 final Vector3 l = _left.crates[i].position;
186 final Vector3 r = _right.crates[i].position;
187 _leftMeshes[i].setPosition(l.x - _apart, l.y, l.z);
188 _rightMeshes[i].setPosition(r.x + _apart, r.y, r.z);
189 }
190 }
192 @override
193 void update(DemoContext context, double dt) {
194 // One step of each, the same sixtieth of a second.
195 _left.dynamics.step(_step);
196 _right.dynamics.step(_step);
197 _age += dt;
198 if (_age > 6.0) _restart();
199 _place();
200 }
202 @override
203 List<DemoControl> controls(DemoContext context) => <DemoControl>[
204 ToggleControl(
205 fallback == null
206 ? 'Right pile on the core'
207 : 'Right pile on the core (unavailable: $fallback)',
208 value: () => onCore && fallback == null,
209 onChanged: (bool v) {
210 onCore = v;
211 _restart();
212 },
213 ),
214 ToggleControl(
215 'Drop again',
216 value: () => false,
217 onChanged: (bool v) {
218 if (v) _restart();
219 },
220 ),
221 ];
223 /// The furthest a crate of one pile ends from the same crate of the
224 /// other, in metres, once both have settled.
225 @visibleForTesting
226 double settledGap() {
227 for (var i = 0; i < 400; i++) {
228 _left.dynamics.step(_step);
229 _right.dynamics.step(_step);
230 }
231 var gap = 0.0;
232 for (var i = 0; i < _count; i++) {
233 gap = math.max(
234 gap,
235 (_left.crates[i].position - _right.crates[i].position).length,
236 );
237 }
238 return gap;
239 }
241 @override
242 void verify(Scene scene, FrameResult frame) {
243 // On a machine where the core starts, the right pile has to be on it.
244 if (fallback == null && _right.dynamics is! NativeDynamics) {
245 throw StateError('the right pile is not on the core');
246 }
247 final double gap = settledGap();
248 for (final _Pile pile in <_Pile>[_left, _right]) {
249 for (final RigidBody c in pile.crates) {
250 if (c.position.y < 0.25) {
251 throw StateError('a crate fell through the floor: ${c.position}');
252 }
253 if (!c.isAsleep) throw StateError('a crate never came to rest');
254 }
255 }
256 // The core is not the reference to the bit, but this tower ends where
257 // the reference's does to within three centimetres (one and a half,
258 // measured, on macOS).
259 if (gap > 0.03) {
260 throw StateError('the two piles part by ${gap.toStringAsFixed(3)} m');
261 }
262 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
263 }
266/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
267LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);