Cloth: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: cloth (line 57), live (line 158), check (line 202).
1/// A sheet pinned along its top edge, stepped live: a ball swings through it
2/// and a gust of wind comes and goes, and the sheet drapes, is pushed, and
3/// swings back under gravity.
4///
5/// Quoted by `xpbd_cloth.md` and shown whole in the Source tab.
6library;
8import 'dart:math' as math;
9import 'dart:typed_data';
11import 'package:flutter3d/flutter3d.dart';
12import 'package:flutter3d_physics/flutter3d_physics.dart';
13import 'package:flutter3d_physics_native/flutter3d_physics_native.dart'
14 show usePhysics;
15import 'package:flutter3d_showcase/src/demo/demo.dart';
17/// The `xpbd-cloth` page: a sheet pinned along its top, a ball swinging
18/// through it and wind gusting on it. Its check is that the pinned row stays,
19/// the free edge hangs, and no particle ends inside the ball.
20final class XpbdClothDemo extends ShowcaseDemo {
21 /// The peak of the gusting wind along +z, in m/s, 0 to 6; the gust swings
22 /// between half of it and all of it.
23 double wind = 1.5;
25 /// Whether the ball swings through the sheet.
26 bool swingBall = true;
28 late final ClothMesh _cloth;
29 ClothSimulation? _simulation;
30 late final ClothObstacle _obstacle;
31 late final MeshNode _sheet;
32 late final MeshNode _ball;
33 late final DeviceMesh Function() _upload;
34 double _clock = 0.0;
36 static const int _cols = 16;
37 static const int _rows = 16;
38 static const double _spacing = 0.09;
39 static const double _hangs = 1.7;
40 static const double _ballRadius = 0.2;
41 static const double _step = 1 / 60;
44 void configureView(DemoContext context) {
45 context.orbit
46 ..distance = 3.0
47 ..pitch = 0.15
48 ..yaw = 0.7;
49 context.orbit.target.setValues(0.68, 1.0, 0.0);
50 }
53 void dispose() => _simulation?.dispose();
56 Scene build(DemoContext context) {
57 // Row zero is pinned, which is what stops the sheet falling forever:
58 // everything else hangs from it.
59 _cloth = ClothMesh.grid(
60 cols: _cols,
61 rows: _rows,
62 spacing: _spacing,
63 height: _hangs,
64 );
65 // Stepped on the run's physics: the core, or the Dart reference where
66 // the core cannot start. Either way it moves `_cloth` itself.
67 _simulation = usePhysics().cloth(_cloth);
68 _obstacle = ClothObstacle(
69 CollisionSphere(_ballRadius),
70 Vector3(0.68, 1.0, 0.6),
71 );
73 _upload = () => DeviceMesh.upload(context.device, _mesh());
74 _sheet = MeshNode(
75 _upload(),
76 RenderMaterial(
77 name: 'cloth',
78 baseColor: LinearColor.fromSrgb(0.8, 0.3, 0.35, 1.0),
79 roughness: 0.8,
80 doubleSided: true,
81 ),
82 name: 'cloth',
83 );
84 _ball = MeshNode(
85 DeviceMesh.upload(
86 context.device,
87 SphereShape(segments: 24, rings: 12, radius: _ballRadius).build(),
88 ),
89 RenderMaterial(
90 name: 'ball',
91 baseColor: LinearColor.fromSrgb(0.4, 0.5, 0.7, 1.0),
92 ),
93 name: 'ball',
94 )..setPositionFrom(_obstacle.position);
96 return Scene()
97 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
98 ..ambientIntensity = 0.3 * LightNode.legacyUnit
99 ..add(_sheet)
100 ..add(_ball)
101 ..add(
102 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
103 ..setLocalForward(Vector3(-0.3, -0.5, -0.6)),
104 );
105 }
107 /// A mesh from the particle positions and the triangles `ClothMesh.grid`
108 /// laid out for them, with a normal at each particle from the triangles
109 /// that meet there. Nothing here draws a `ClothMesh` for you; that is the
110 /// same gap the heightfield page's own terrain fills.
111 MeshData _mesh() {
112 final Float64List p = _cloth.positions;
113 final List<Vector3> normals = List<Vector3>.generate(
114 _cloth.particleCount,
115 (int _) => Vector3.zero(),
116 );
117 Vector3 at(int i) => Vector3(p[3 * i], p[3 * i + 1], p[3 * i + 2]);
118 for (var i = 0; i + 2 < _cloth.triangles.length; i += 3) {
119 final int a = _cloth.triangles[i];
120 final int b = _cloth.triangles[i + 1];
121 final int c = _cloth.triangles[i + 2];
122 final Vector3 face = (at(b) - at(a)).cross(at(c) - at(a));
123 normals[a].add(face);
124 normals[b].add(face);
125 normals[c].add(face);
126 }
127 final MeshBuilder builder = MeshBuilder(VertexLayout.standard);
128 for (var i = 0; i < _cloth.particleCount; i++) {
129 builder.addVertex(
130 position: at(i),
131 normal: normals[i].length2 == 0.0
132 ? Vector3(0.0, 0.0, 1.0)
133 : (normals[i]..normalize()),
134 );
135 }
136 for (var i = 0; i + 2 < _cloth.triangles.length; i += 3) {
137 builder.addTriangle(
138 _cloth.triangles[i],
139 _cloth.triangles[i + 1],
140 _cloth.triangles[i + 2],
141 );
142 }
143 return builder.build();
144 }
147 void update(DemoContext context, double dt) {
148 _clock += _step;
149 if (swingBall) {
150 // Through the sheet and out the other side, and around again.
151 _obstacle.position.setValues(
152 0.68 + 0.3 * math.sin(_clock * 0.9),
153 1.0 + 0.15 * math.sin(_clock * 1.3),
154 0.55 * math.sin(_clock * 1.1),
155 );
156 }
158 // A gust that rises and falls, blowing the sheet towards the viewer.
159 final double gust = wind * (0.5 + 0.5 * math.sin(_clock * 0.7));
160 _simulation!.step(
161 ClothStep(
162 // The sheet hangs in a world: its gravity, and its wind blowing in
163 // its air. Drag 4, not 0.3: until 0.7.4 the wind was added as a
164 // velocity, which made 0.3 several hundred times stronger than its
165 // value.
166 settings: ClothSettings.of(WorldProperties.standard)
167 .copyWith(
168 wind: WindSettings(
169 drag: 4.0,
170 airDensity: WorldProperties.standard.airDensity,
171 ),
172 )
173 .inWorld(WorldProperties(wind: Vector3(0.0, 0.0, gust))),
174 dt: _step,
175 obstacles: <ClothObstacle>[_obstacle],
176 ),
177 );
179 _ball.setPositionFrom(_obstacle.position);
180 _sheet.mesh = _upload();
181 }
184 List<DemoControl> controls(DemoContext context) => <DemoControl>[
185 SliderControl(
186 'Wind',
187 min: 0,
188 max: 6,
189 value: () => wind,
190 onChanged: (double v) => wind = v,
191 format: (double v) => v.toStringAsFixed(1),
192 ),
193 ToggleControl(
194 'Swing the ball',
195 value: () => swingBall,
196 onChanged: (bool v) => swingBall = v,
197 ),
198 ];
201 void verify(Scene scene, FrameResult frame) {
202 // The pinned row never moves: its inverse mass is zero, so no force and
203 // no correction ever reaches it.
204 if (_cloth.positions[1] != _hangs) {
205 throw StateError('the pinned row should not have moved');
206 }
207 // Left alone with the ball out of the way, the free edge has to sag
208 // well below the row it hangs from.
209 _obstacle.position.setValues(5.0, 5.0, 5.0);
210 for (var i = 0; i < 300; i++) {
211 _simulation!.step(
212 ClothStep(
213 settings: ClothSettings.of(WorldProperties.standard),
214 dt: _step,
215 ),
216 );
217 }
218 final int lastRow = (_rows - 1) * _cols;
219 for (var col = 0; col < _cols; col++) {
220 final double y = _cloth.positions[3 * (lastRow + col) + 1];
221 if (y > _hangs - 0.5 * (_rows - 1) * _spacing) {
222 throw StateError('the free edge should have hung below its start');
223 }
224 }
225 // And a ball pushed into the sheet must never end up inside it.
226 _obstacle.position.setValues(0.68, 1.0, 0.0);
227 for (var i = 0; i < 120; i++) {
228 _simulation!.step(
229 ClothStep(
230 settings: ClothSettings.of(WorldProperties.standard),
231 dt: _step,
232 obstacles: <ClothObstacle>[_obstacle],
233 ),
234 );
235 }
236 for (var i = 0; i < _cloth.particleCount; i++) {
237 final Vector3 at = Vector3(
238 _cloth.positions[3 * i],
239 _cloth.positions[3 * i + 1],
240 _cloth.positions[3 * i + 2],
241 );
242 if (at.distanceTo(_obstacle.position) < _ballRadius - 0.03) {
243 throw StateError('a particle passed through the ball');
244 }
245 }
246 if (frame.drawCalls < 2) {
247 throw StateError('the cloth and the ball did not both reach the frame');
248 }
249 }
250}