class_name MazeCarver extends RefCounted # Turns a MazeGraph into tiles: rock everywhere, a rectangle of air for each # chamber, and each tube routed through the rock between its two chambers. # # Each screen (one RoomCamera room) is split into a grid of regions, one per # chamber. A chamber is a random rectangle inside its region with at least a # tile of rock all round, so chambers never touch and never cross a screen # border. Tubes are routed with AStarGrid2D over the rock, with random weights # so they wander; tubes never share a tile, so they can't join by accident. # # Air blows out of one-way tubes' exits (OneWayTube.blow_zone). No other mouth # opens into a blow zone, and Start and End aren't in one, so the slime is never # blown away from something it needs. (MazeGraph keeps it to one blower per # chamber; MazeValidator checks all of this again.) const MIN_CHAMBER_SIZE = 3 # Tiles of air across and down, at least. const MIN_ROCK = 3 # Rock left in a region beside its chamber, across and down, at least (when there's room). const MOUTH_CHOICES = 4 # Of the spots for a mouth nearest the other chamber, how many we pick from. const ROUTE_TRIES = 8 # Pairs of mouth spots to try before giving up on a tube. var chamberRects: Array[Rect2i] = [] var bounds := Rect2i() # The whole maze, in tiles. var startCell := Vector2i.ZERO # The air tile Start sits on (on a chamber's floor). var endCell := Vector2i.ZERO var isComplete := false # Whether every tube the maze needs got a route. var routedTubeCount := 0 var _layer: TileMapLayer var _tiles: MazeTiles var _random: RandomNumberGenerator var _pathfinder := AStarGrid2D.new() var _winding := 0.0 var _mouthFronts := {} # Air tile in front of a mouth -> true. var _blowCells := {} # Air tile in a blow zone -> true. func _init(graph: MazeGraph, screens: Vector2i, layer: TileMapLayer, random: RandomNumberGenerator, winding: float) -> void: _layer = layer _tiles = MazeTiles.new(layer.tile_set) _random = random _winding = winding var screenTiles := Vector2i(RoomCamera.ROOM_SIZE) / layer.tile_set.tile_size bounds = Rect2i(Vector2i.ZERO, screenTiles * screens) _fill_rock() _carve_chambers(graph, screenTiles) _setup_pathfinder() isComplete = true for tube in graph.tubes: if _carve_tube(tube): routedTubeCount += 1 elif tube.isRequired: isComplete = false return startCell = _floor_cell(chamberRects[graph.start]) endCell = _floor_cell(chamberRects[graph.end]) func _fill_rock() -> void: _layer.clear() for y in range(bounds.position.y, bounds.end.y): for x in range(bounds.position.x, bounds.end.x): _tiles.set_tile(_layer, Vector2i(x, y), 0, MazeTiles.ROCK) func _carve_chambers(graph: MazeGraph, screenTiles: Vector2i) -> void: var split: Vector2i = graph.gridSize / (bounds.size / screenTiles) for chamber in graph.chamber_count(): var region := _region(graph.grid_cell(chamber), split, screenTiles) var size := Vector2i(_random_size(region.size.x), _random_size(region.size.y)) var corner := Vector2i(_random.randi_range(region.position.x + 1, region.end.x - 1 - size.x), _random.randi_range(region.position.y + 1, region.end.y - 1 - size.y)) var rect := Rect2i(corner, size) chamberRects.append(rect) for y in range(rect.position.y, rect.end.y): for x in range(rect.position.x, rect.end.x): _layer.erase_cell(Vector2i(x, y)) # The tiles a chamber's region covers. The last region in each screen row or # column takes what's left over. static func _region(gridCell: Vector2i, split: Vector2i, screenTiles: Vector2i) -> Rect2i: var screen := gridCell / split var inScreen := gridCell % split var regionSize := screenTiles / split var position := screen * screenTiles + inScreen * regionSize var size := regionSize if inScreen.x == split.x - 1: size.x = screenTiles.x - inScreen.x * regionSize.x if inScreen.y == split.y - 1: size.y = screenTiles.y - inScreen.y * regionSize.y return Rect2i(position, size) # A chamber size for a region `regionSize` tiles long: room for MIN_ROCK # beside it if possible, and always a tile of rock each side. func _random_size(regionSize: int) -> int: var largest := maxi(regionSize - MIN_ROCK, MIN_CHAMBER_SIZE) return mini(_random.randi_range(MIN_CHAMBER_SIZE, largest), regionSize - 2) # A random tile along the bottom row of a chamber, out of any blow zone (one # blower can't cover a whole row: chambers are wider than its reach). func _floor_cell(rect: Rect2i) -> Vector2i: var cells: Array[Vector2i] = [] for x in range(rect.position.x, rect.end.x): if not _blowCells.has(Vector2i(x, rect.end.y - 1)): cells.append(Vector2i(x, rect.end.y - 1)) return cells[_random.randi_range(0, cells.size() - 1)] # ---- Tubes ---- func _setup_pathfinder() -> void: _pathfinder.region = bounds _pathfinder.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER _pathfinder.default_compute_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN _pathfinder.update() # Tubes go through rock only, and never through the maze's outer edge. for y in range(bounds.position.y, bounds.end.y): for x in range(bounds.position.x, bounds.end.x): var cell := Vector2i(x, y) var isEdge := x == bounds.position.x or y == bounds.position.y or x == bounds.end.x - 1 or y == bounds.end.y - 1 _pathfinder.set_point_solid(cell, isEdge or _layer.get_cell_source_id(cell) == -1) # Routes `tube` and puts its tiles down. False if there's no way through. func _carve_tube(tube: Dictionary) -> bool: var fromRect := chamberRects[tube.from] var toRect := chamberRects[tube.to] _randomize_weights() var fromMouths := _mouth_spots(fromRect, toRect, false) var toMouths := _mouth_spots(toRect, fromRect, tube.kind == MazeGraph.ONE_WAY) for attempt in ROUTE_TRIES: if fromMouths.is_empty() or toMouths.is_empty(): return false var fromMouth: Vector2i = fromMouths[_random.randi_range(0, fromMouths.size() - 1)] var toMouth: Vector2i = toMouths[_random.randi_range(0, toMouths.size() - 1)] var path := _pathfinder.get_id_path(fromMouth, toMouth) if path.is_empty(): continue _put_tube_tiles(path, fromRect, toRect, tube.kind) _mouthFronts[fromMouth + _side_towards(fromMouth, fromRect)] = true _mouthFronts[toMouth + _side_towards(toMouth, toRect)] = true if tube.kind == MazeGraph.ONE_WAY: for zoneCell in OneWayTube.blow_zone(_layer, toMouth, _side_towards(toMouth, toRect)): _blowCells[zoneCell] = true return true return false # Random extra cost on every tile, so routes wander instead of always taking # the shortest way. func _randomize_weights() -> void: for y in range(bounds.position.y, bounds.end.y): for x in range(bounds.position.x, bounds.end.x): _pathfinder.set_point_weight_scale(Vector2i(x, y), 1.0 + _random.randf() * _winding) # Free rock tiles touching `rect`'s sides, where a mouth into it can go: the # MOUTH_CHOICES nearest `towards`. None open into a blow zone, and if the mouth # `isBlowing` (a one-way exit), its blow zone has no other mouth in it. func _mouth_spots(rect: Rect2i, towards: Rect2i, isBlowing: bool) -> Array[Vector2i]: var spots: Array[Vector2i] = [] for x in range(rect.position.x, rect.end.x): spots.append(Vector2i(x, rect.position.y - 1)) spots.append(Vector2i(x, rect.end.y)) for y in range(rect.position.y, rect.end.y): spots.append(Vector2i(rect.position.x - 1, y)) spots.append(Vector2i(rect.end.x, y)) spots = spots.filter(func(spot: Vector2i) -> bool: return _is_mouth_spot_free(spot, rect, isBlowing)) var target := Vector2(towards.get_center()) spots.sort_custom(func(a: Vector2i, b: Vector2i) -> bool: return Vector2(a).distance_squared_to(target) < Vector2(b).distance_squared_to(target)) return spots.slice(0, MOUTH_CHOICES) func _is_mouth_spot_free(spot: Vector2i, rect: Rect2i, isBlowing: bool) -> bool: if _pathfinder.is_point_solid(spot): return false var outward := _side_towards(spot, rect) if _blowCells.has(spot + outward): return false if isBlowing: for zoneCell in OneWayTube.blow_zone(_layer, spot, outward): if _mouthFronts.has(zoneCell): return false return true # Lays tube tiles along `path`, from a mouth into `fromRect` to one into `toRect`. func _put_tube_tiles(path: Array[Vector2i], fromRect: Rect2i, toRect: Rect2i, kind: StringName) -> void: var last := path.size() - 1 for i in path.size(): var cell := path[i] var back := _side_towards(cell, fromRect) if i == 0 else path[i - 1] - cell var ahead := _side_towards(cell, toRect) if i == last else path[i + 1] - cell var openings := TubeSteer.side_bit(back) | TubeSteer.side_bit(ahead) # A one-way tube's way in is its mouth into `fromRect`. var entrySide := TubeSteer.side_bit(back) if kind == MazeGraph.ONE_WAY and i == 0 else 0 _tiles.set_tile(_layer, cell, openings, kind, entrySide) _pathfinder.set_point_solid(cell) # Which way from `cell` (just outside `rect`) the rect is. static func _side_towards(cell: Vector2i, rect: Rect2i) -> Vector2i: for direction in TubeSteer.DIRECTIONS: if rect.has_point(cell + direction): return direction return Vector2i.ZERO