Convex shapes and mesh floors
Open the live demo · Read the source · View on GitHub
The physics core has more shapes than a box, a ball and a capsule. It has cylinders and cones, convex hulls built from a list of points, and any of these rounded by a radius. For level geometry it has triangle meshes, which only fixed bodies can be. This page drops one of each on a mesh: a cylinder rolls down a ramp, a cone and a rock land and stay put, and a rounded box is thrown spinning and tumbles before it settles.
These shapes exist only on the core. Where the core will not start, the page shows the ground and says why beside the viewport.
Step 1: The ground is a triangle mesh #
A mesh is a list of vertices and three indices for each triangle. Each triangle is wound counter-clockwise when seen from the side bodies touch, because a mesh has only that one side. The ramp and the floor share the two vertices at the foot of the ramp. That shared edge is internal, and a body crosses it without catching on the seam.
/// The ground as one triangle mesh: a ramp from x = −6, 1.5 m up, down
/// to x = −3, and the floor from there to x = 6, four metres wide. Four
/// triangles, wound counter-clockwise seen from above, the side bodies
/// touch. The ramp and the floor share the vertices at its foot, so that
/// edge is internal and a body rolls over it without a bump.
static final List<Vector3> _groundPoints = <Vector3>[
Vector3(-6.0, 1.5, -2.0),
Vector3(-6.0, 1.5, 2.0),
Vector3(-3.0, 0.0, -2.0),
Vector3(-3.0, 0.0, 2.0),
Vector3(6.0, 0.0, -2.0),
Vector3(6.0, 0.0, 2.0),
];
static const List<int> _groundTriangles = <int>[
0, 1, 2, 2, 1, 3, //
2, 3, 4, 4, 3, 5,
];
createMesh keeps the mesh in the world, and setMesh gives it to a fixed
body. One mesh can shape many bodies.
// The world keeps the mesh; a fixed body is shaped as it.
final NativeMesh mesh = w.createMesh(_groundPoints, _groundTriangles);
final NativeBody ground = w.addBody(
position: Vector3.zero(),
type: NativeBodyType.fixed,
mass: 0.0,
);
w.setMesh(ground, mesh);
Step 2: A cylinder on the ramp #
NativeShape.cylinder(radius, halfHeight) stands along its body's y axis.
Turned a quarter turn about x, it lies across the ramp and rolls down it.
Nothing in the core resists rolling, so on the level floor it would roll all
the way to the end. Damping its spin is a simple stand-in for rolling
resistance.
// A cylinder stands along its body's y. Turned a quarter about x, it
// lies across the ramp, set a little above the slope near the top.
final double slope = math.atan2(1.5, 3.0);
final Vector3 up = Vector3(math.sin(slope), math.cos(slope), 0.0);
final NativeBody cylinder = w.addBody(
position: Vector3(-5.5, 1.25, -1.2) + up * (_cylinderRadius + 0.02),
mass: 3.0,
);
w
..setShape(
cylinder,
const NativeShape.cylinder(_cylinderRadius, _cylinderHalf),
)
..setOrientation(
cylinder,
Quaternion.axisAngle(Vector3(1.0, 0.0, 0.0), math.pi / 2),
)
// Nothing here resists rolling, so a cylinder on a level floor would
// roll on to its end. Damping its spin stands in for that.
..setDamping(cylinder, angular: 1.5);
Step 3: A cone #
NativeShape.cone(radius, height) has its apex up along y. Its origin is its
centre of mass, which is a quarter of its height above its base, not
halfway.
// A cone's origin is its centre of mass, a quarter of its height above
// its base.
final NativeBody cone = w.addBody(
position: Vector3(0.0, 0.6, 0.8),
mass: 2.0,
);
w.setShape(cone, const NativeShape.cone(_coneRadius, _coneHeight));
Step 4: A hull of six points #
createHull takes the points and builds the convex hull around them. The
core weighs the hull as a solid and moves it so that its centre of mass is
the body's origin. hullOffset says by how much. Its corners are four
points round the middle and one above and one below, so its faces are easy
to write down: eight triangles from the top and the bottom to the edges of
the middle.
/// A rock of six points: four round its middle in a level plane, one
/// above it and one below, not quite over each other. Its faces are the
/// eight triangles from the top and the bottom to each edge of the
/// middle; the core finds the same hull from the points alone.
static final List<Vector3> _rockPoints = <Vector3>[
Vector3(0.08, 0.4, 0.05),
Vector3(-0.05, -0.3, 0.02),
Vector3(0.5, 0.0, 0.05),
Vector3(0.05, 0.0, 0.4),
Vector3(-0.45, 0.0, 0.0),
Vector3(0.0, 0.0, -0.35),
];
static const List<int> _rockTriangles = <int>[
0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 2, //
1, 3, 2, 1, 4, 3, 1, 5, 4, 1, 2, 5,
];
// The hull is built from the points and moved so its centre of mass is
// the body's origin; hullOffset says by how much, and the mesh drawn
// for it has to be moved by the same.
final NativeHull hull = w.createHull(_rockPoints);
final NativeBody rock = w.addBody(
position: Vector3(2.0, 1.0, 0.5),
mass: 3.0,
);
w
..setHull(rock, hull)
..setOrientation(
rock,
Quaternion.axisAngle(Vector3(1.0, 0.0, 1.0).normalized(), 0.7),
);
Step 5: A rounded box #
setRounding grows any shape by a ball of the given radius. A box of half
size 0.25 rounded by 0.08 has round edges and corners and is 0.33 from its
centre to each face. Rounding makes a box roll over its edges more smoothly
and rest on a face as before.
// A box rounded by eight centimetres: the box grown by a ball, so its
// edges and corners are round and it stands 0.33 m from its centre to
// each face. Thrown spinning, it tumbles before it settles.
final NativeBody box = w.addBody(
position: Vector3(4.0, 1.2, -0.5),
mass: 2.0,
);
w
..setShape(box, NativeShape.box(Vector3.all(_boxHalf)))
..setRounding(box, _rounding)
..setAngularVelocity(box, Vector3(3.0, 1.0, 5.0))
..setVelocity(box, Vector3(-1.0, 0.0, 0.0));
Step 6: Draw them as the core has them #
Each body is drawn at its position and orientation. Two need care. The cone's mesh has its middle at its origin, so it is held a quarter of its height up inside a node at the body. The rock's mesh is its points less the hull's offset, so that it turns about the same point as the body.
// The cone's mesh has its middle at its origin, half its height above
// the base; the body's origin is a quarter above it. A node at the body
// holds the mesh a quarter of the height up.
final cone = SceneNode(name: 'cone')
..add(
MeshNode(
upload(
const ConeShape(radius: _coneRadius, height: _coneHeight).build(),
),
paint('cone', 0.8, 0.6, 0.3),
name: 'cone mesh',
)..setPosition(0.0, _coneHeight / 4, 0.0),
);
// The rock's mesh is its points less the offset the hull was moved by.
final Vector3 offset = _bodies?.rockOffset ?? Vector3.zero();
final List<Vector3> moved = <Vector3>[
for (final Vector3 p in _rockPoints) p - offset,
];
final Vector3 middle =
moved.fold(Vector3.zero(), (Vector3 sum, Vector3 p) => sum + p) /
moved.length.toDouble();
_nodes.addAll(<SceneNode>[
MeshNode(
upload(
const CylinderShape(
radiusTop: _cylinderRadius,
radiusBottom: _cylinderRadius,
height: 2 * _cylinderHalf,
).build(),
),
paint('cylinder', 0.35, 0.55, 0.8),
name: 'cylinder',
),
cone,
MeshNode(
upload(_faceted(moved, _rockTriangles, inside: middle)),
paint('rock', 0.55, 0.5, 0.45),
name: 'rock',
),
// Drawn as a plain cube of the rounded box's outer size.
MeshNode(
upload(
CuboidShape(size: Vector3.all(2 * (_boxHalf + _rounding))).build(),
),
paint('rounded box', 0.75, 0.4, 0.45),
name: 'rounded box',
),
]);
Step 7: Where each one has to end #
After ten seconds the cylinder has to be off the ramp and at least a metre past its foot, lying on its side, its centre one radius above the floor. The cone has to stand on its base with its centre a quarter of its height up. The rock's lowest corner has to be on the floor. The rounded box has to lie on a face, 0.33 up. Every height has to be within a centimetre. The cone, the rock and the box also have to be asleep.
// Ten seconds from the drop.
_restart();
final _Bodies b = _bodies!;
final NativeWorld w = b.world;
for (var i = 0; i < 600; i++) {
w.step(_step);
}
Vector3 axisOf(NativeBody body) =>
w.orientationOf(body).asRotationMatrix().transformed(Vector3(0, 1, 0));
void rests(String what, double height, double at) {
if ((height - at).abs() > 0.01) {
throw StateError('$what rests at $height m, not $at');
}
}
// The cylinder rolled off the ramp, at least a metre past its foot,
// and lies on its side, its axis level and its centre a radius up.
final Vector3 cylinder = w.localPositionOf(b.cylinder);
if (cylinder.x < -2.0) throw StateError('the cylinder stayed on the ramp');
if (axisOf(b.cylinder).y.abs() > 0.02) {
throw StateError('the cylinder is not on its side');
}
rests('the cylinder', cylinder.y, _cylinderRadius);
// The cone stands on its base, its centre of mass a quarter of its
// height up.
if (axisOf(b.cone).y < 0.999) throw StateError('the cone fell over');
rests('the cone', w.localPositionOf(b.cone).y, _coneHeight / 4);
// The rock rests on a face: its lowest corner on the floor.
final Matrix3 turn = w.orientationOf(b.rock).asRotationMatrix();
final Vector3 at = w.localPositionOf(b.rock);
final double lowest = _rockPoints
.map((Vector3 p) => (at + turn.transformed(p - b.rockOffset)).y)
.reduce(math.min);
rests('the rock\'s lowest corner', lowest, 0.0);
// The rounded box lies on a face, its half size plus the rounding up.
rests('the rounded box', w.localPositionOf(b.box).y, _boxHalf + _rounding);
for (final NativeBody body in <NativeBody>[b.cone, b.rock, b.box]) {
if (!w.isAsleep(body)) throw StateError('a shape never came to rest');
}
Note. Every shape here rests a few millimetres lower than its size says: the cylinder 5 mm, the cone 3 mm, the rock 6 mm. That is how far the contacts are allowed to overlap. The rounded box is drawn as a plain cube of its outer size, so its corners on screen are sharper than the ones it collides with. A mesh is one-sided, and only fixed bodies can be meshes. A moving body made of several shapes is a compound (
createCompound).