flutter3d
Showcase Changelog 62 packages API reference

Levels from a seed

since 1.0.0-rc.1 Simulation, audio and XR

A level drawn by hand is one level. A generator makes a new one from a number, and the same number makes the same level again, which is what lets a run be replayed, a bug report name its level in one integer, and a server check a score against the map it was set on.

generateLevel lays a grid of cells out by wave function collapse. Each cell is a room with a doorway on some of its four sides, or nothing, and a doorway has to meet a doorway in the next cell, so every way out of a room leads somewhere. The largest group of rooms that join up is the level; the player starts in its first room and the exit goes in the room farthest from it.

Step 1: The rules #

LevelRules() with nothing changed is already a playable level: four cells across and three down, sixteen metres each, a ten-metre room in a cell that gets one, and corridors three metres wide. This page changes only density, how likely a cell is to be a room rather than empty ground.

/// Four cells across and three down, sixteen metres each, a room of ten
/// in each cell the seed makes a room, and corridors three metres wide.
LevelRules get _rules => LevelRules(density: density);

Step 2: A seed in, a level out #

Everything chance decides comes from GameRandom seeded with the number given. A grid that comes out with fewer than two joined rooms is no level, so the generator tries the next seed, up to thirty-two of them, and the answer names the seed that worked. That seed alone makes the level again.

Before a level is handed back it is checked against ExitReachable: the navigation mesh is baked and a route asked for from the player's start to the exit. A doorway a step too high would fail here, not in the player's hands.

/// The level [seed] makes. When a seed makes nothing playable, the next is
/// tried, and [Generated.seed] says which one it was.
Generated _make(int seed) => generateLevel(_rules, seed: seed);

Step 3: Draw it #

The rooms and corridors arrive as recipes, so a level saved to a file stays short. expandRecipes turns them into the brushes a game loads. This page draws each brush as a box, leaves the ceilings out so the camera can look in, and puts a green ball on the player's start and a red one on the exit.

Drag Seed and the layout changes; drag it back and the same layout returns. Lower Room density and the level shrinks to a few rooms in a line; raise it and most cells are rooms with doorways on several sides.

// The rooms and corridors are recipes; `expandRecipes` turns them into
// the brushes everything that uses a level reads. The ceilings are left
// out so the camera sees in.
for (final Brush brush in expandRecipes(level).brushes) {
  if (brush.material == 'ceiling') continue;
  final bool floor = brush.material == 'floor';
  _rooms.add(
    MeshNode(
        _cube,
        RenderMaterial(
          name: brush.material,
          baseColor: floor
              ? LinearColor.fromSrgb(0.42, 0.44, 0.47, 1.0)
              : LinearColor.fromSrgb(0.72, 0.66, 0.56, 1.0),
          roughness: 0.85,
        ),
        name: brush.material,
      )
      ..setPositionFrom(
        brush.center.toVector3Relative(WorldPosition.origin),
      )
      ..setScale(brush.size.x, brush.size.y, brush.size.z),
  );
}
_player.setPositionFrom(
  level
          .ofType('player_spawn')
          .first
          .position
          .toVector3Relative(WorldPosition.origin) +
      Vector3(0, 1.2, 0),
);
_exit.setPositionFrom(
  level
          .ofType('exit')
          .first
          .position
          .toVector3Relative(WorldPosition.origin) +
      Vector3(0, 1.2, 0),
);

Step 4: What the page checks #

Two calls with the same seed have to write the same document, byte for byte, and the exit has to be reachable when the rule is asked again from outside the generator.

final Generated first = _make(seed.round());
final Generated again = _make(seed.round());
final Level level = first.level!;
if (jsonEncode(level.toJson()) != jsonEncode(again.level!.toJson())) {
  throw StateError('the same seed should make the same level');
}
// The generator held the level to this rule already; asking again is
// what any game that loads a level can do.
final List<LevelIssue> issues = <LevelIssue>[];
const ExitReachable().check(LevelCheck(level: level, out: issues));
if (issues.any((LevelIssue i) => i.isError)) {
  throw StateError('the exit cannot be walked to: $issues');
}

Note. generateLevelOffThread does the same work in an isolate, so a game can make the next level while the player finishes this one. In the browser it runs in place. erodeThermally and erodeHydraulically belong to the same set of tools and shape a Heightfield rather than rooms; this page does not show them.