flutter3d
Showcase Changelog 62 packages API reference

A world of blocks

since 1.0.0-rc.1 Simulation, audio and XR

A sandbox's state is its blocks, and there are a lot of them: this small world is thirty-two by sixteen by thirty-two, sixteen thousand voxels. Saving every one of them would be wasteful when almost all of them are still what the terrain put there. So a VoxelWorld keeps the terrain as a seed and a few numbers, and the edits as a list of the voxels that differ from it.

Step 1: Ground from a seed #

The world is cut into chunks sixteen voxels on a side, a byte a voxel. VoxelTerrain draws rolling ground from a GameRandom stream, mixed with nothing but adding and multiplying, so two machines given seed 7 draw the same ground bit for bit. The save taken here, before anything is edited, holds the world's size, the terrain's numbers and an empty list of edits.

// Two chunks by one by two: 32 by 16 by 32 voxels of rolling ground,
// drawn from seed 7 and nothing else.
_voxels = VoxelWorld(
  chunksX: 2,
  chunksY: 1,
  chunksZ: 2,
  terrain: const VoxelTerrain(seed: 7),
);
// Taken before any edit: the terrain's few numbers and no edits at all.
_save = _voxels.toJson();

Step 2: Boxes to collide with #

VoxelCollision covers each chunk's solid voxels with as few boxes as it can find and puts them in an ordinary CollisionWorld. Nothing in the physics knows about voxels. The world is attached to the run's physics, so on the native core the same boxes are mirrored there by revision.

// The chunks as boxes in an ordinary collision world, on the run's
// physics.
_world = onRunPhysics(CollisionWorld());
_collision = VoxelCollision(_voxels, _world);
_world.update();

Step 3: Faces as greedy meshes #

meshChunk draws a face only where a block meets air, and merges the faces of one slice that look the same way and are the same material into the fewest rectangles. A flat patch of grass sixteen voxels square is two triangles, not five hundred. It reads across chunk borders, so a wall running over one has no seam. One mesh comes back per material, and each becomes a node here.

/// [chunk]'s faces, a greedy mesh per material, in place of what it had.
void _mesh(ChunkKey chunk) {
  for (final MeshNode old in _nodes.remove(chunk) ?? const <MeshNode>[]) {
    _scene.remove(old);
  }
  final List<MeshNode> nodes = <MeshNode>[
    for (final MapEntry(key: material, value: data) in meshChunk(
      _voxels,
      chunk,
    ).entries)
      MeshNode(
        DeviceMesh.upload(_device, data),
        RenderMaterial(
          name: 'voxel $material',
          baseColor: _fromSrgb(_colorOf(material)),
          roughness: 0.9,
        ),
        name: 'chunk ${chunk.x} ${chunk.z} material $material',
      ),
  ];
  nodes.forEach(_scene.add);
  _nodes[chunk] = nodes;
}

Step 4: An edit costs its chunk #

edit changes one voxel and remembers which chunks it touched. drainChanges hands those over: surfaces are the chunks whose faces may have changed, which includes a neighbour when the voxel sits on a border, and chunks are the ones whose boxes did. Nothing else is meshed or rebuilt.

The page digs a pit five blocks wide and four deep in the middle, a block at a time, then builds a tower of brick, a material the terrain never lays. Turn off Dig and build to stop it.

/// What an edit costs: the chunks whose faces it touched are meshed again,
/// and the chunks it changed get new boxes.
void _apply() {
  final VoxelChanges changes = _voxels.drainChanges();
  if (changes.isEmpty) return;
  changes.surfaces.forEach(_mesh);
  _collision.refresh(changes.chunks);
  _world.update();
}

Step 5: Put the save back #

restoreEdits takes a save and touches only the voxels that differ from it. Restoring the save from Step 1 fills the pit and takes the tower down, then the page starts digging again. Put back the save does it at once.

/// Back to the save taken at the start: only the voxels that differ from
/// it are touched.
void _restore() {
  _voxels.restoreEdits(_save);
  _next = 0;
}

Step 6: What the page checks #

A ray down onto the boxes finds the top of a column; after its top block is dug out the ray finds the block under it, and the chunk's mesh has changed. Edited back to what the terrain had, the voxel is no edit at all. A world read back from its save has the same digest as the one that wrote it, and after the first save is restored the world is the terrain again.

// A column well away from the pit: dig its top block out.
const int x = 4, z = 26;
const ChunkKey chunk = ChunkKey(x: 0, y: 0, z: 1);
final int top = _top(x, z);
final int edits = _voxels.editCount;
final int before = _triangles(chunk);
if ((_groundAt(x, z) - top).abs() > 1e-3) {
  throw StateError('the boxes should stand as high as the blocks');
}
_voxels.edit(x, top - 1, z, Voxels.empty);
_apply();
if ((_groundAt(x, z) - (top - 1)).abs() > 1e-3) {
  throw StateError('the dug block should be gone from the collision too');
}
if (_triangles(chunk) == before) {
  throw StateError('the dug block should change the chunk\'s mesh');
}
// Put back what the terrain had, and it is no edit at all.
_voxels.edit(x, top - 1, z, _voxels.baseAt(x, top - 1, z));
_apply();
if (_voxels.editCount != edits) {
  throw StateError('a block edited back to the terrain is still an edit');
}

// A save is the terrain and the edits; read back, it is the same world.
_voxels.edit(x, top, z, Voxels.firstPlaced);
final VoxelWorld copy = VoxelWorld.fromJson(_voxels.toJson());
if (copy.digest != _voxels.digest) {
  throw StateError('the world read back from its save is another world');
}
_restore();
_apply();
if (_voxels.editCount != 0 ||
    _voxels.digest !=
        VoxelWorld(
          chunksX: 2,
          chunksY: 1,
          chunksZ: 2,
          terrain: const VoxelTerrain(seed: 7),
        ).digest) {
  throw StateError('restoring the first save should leave the terrain');
}

Note. raycast on the world picks a block through the grid rather than the merged boxes, since a box says where a ray stopped but not which voxel it was, and before on the hit is where a placed block goes. VoxelNavigation keeps a navigation mesh in step with the digging, baking again only the tiles an edit reaches.