class_name MazeTubeRouter extends RefCounted # Lays tubes into a carved maze, routed with AStarGrid2D (random weights so # they wander): long tubes between regions and across screens, "open" tubes # that run through open air (halls, wide corridors) where the slime can still # get round them, and short "wall pipes" through a single wall. # Tubes may cross another tube of the same kind at a straight tile, making a # cross tile: auto and one-way tubes go straight through it (two separate # rides), manual and goo tubes join into one network you steer through. # Otherwise tubes never share a tile, and their openings only face their own # tiles, so they can't join by accident. # # One-way tubes move the slime by themselves: the tile in front of the # entrance sucks it in, and the blow zone in front of the exit # (OneWayTube.blow_zone) blows it away. These "forced" tiles can't be stood on # or crossed. A one-way tube only goes where MazeValidator's movement model can # tell what happens, and where forced tiles can't cut a region in two: # - the exit never blows up (the slime could bounce in place), # - the zone and the tile past it ("landing") are air, # - sideways: zone and landing are 1 tile tall, so the slime slides along a floor, # - down: the slime falls from the landing onto a floor, through no forced tile, # - the region's air minus all forced tiles is still one connected piece, # - no other mouth opens onto a forced tile. const MOUTH_CHOICES = 10 # Of the spots for a mouth nearest the other end, how many we pick from. const ROUTE_TRIES = 16 # Pairs of mouth spots to try before giving up on a tube. const CROSSING_RETRIES = 4 # Re-routes when a path uses a tube tile it can't cross. const WALL_PIPE_TRIES = 30 const MIN_SHORTCUT = 8 # A wall pipe must save at least this many tiles of corridor. # Extra cost for routing through the walls inside a region rather than the # rock between regions. In a 1-tile-wall maze the walls form a tree, and a tube # through it cuts off the rock beyond, so later tubes couldn't get through. # (Mouths also sit next to that rock or open air, see _touches_channel.) const INTERIOR_COST = 12.0 const OPEN_AIR_COST = 0.6 # Open air is cheap: tubes there are seen and ridden past. const CROSSING_COST = 3.0 var mouthFronts := {} # Air tile in front of a mouth -> true. var forcedCells := {} # Air tile the air moves the slime off (blow zones, entrance tiles) -> true. var _keepFree := {} # Air tiles a blown slime lands on or falls through: never forced or covered. var _layer: TileMapLayer var _tiles: MazeTiles var _random: RandomNumberGenerator var _bounds: Rect2i var _pathfinder := AStarGrid2D.new() var _winding := 0.0 var _interiors: Array[Rect2i] = [] # Where the corridors and their walls are. var _regionAir: Array[Dictionary] = [] # Per region: its air tiles (shared with MazeCarver). var _openAir := {} # Air tiles tubes may run through. var _tubeKinds := {} # Tube tile -> its kind. func _init(layer: TileMapLayer, tiles: MazeTiles, random: RandomNumberGenerator, bounds: Rect2i, winding: float, interiors: Array[Rect2i], regionAir: Array[Dictionary], openAir: Dictionary) -> void: _layer = layer _tiles = tiles _random = random _bounds = bounds _winding = winding _interiors = interiors _regionAir = regionAir _openAir = openAir _pathfinder.region = bounds _pathfinder.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER _pathfinder.default_compute_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN _pathfinder.update() # Routes a tube from region `fromAir` (mouth near `fromTowards`) to region # `toAir` (near `toTowards`); the regions may be the same. A one-way tube with # nowhere safe for its ends becomes `fallbackKind`. Fails if no route at least # `minLength` tiles long fits. func route(fromAir: Dictionary, fromTowards: Vector2, toAir: Dictionary, toTowards: Vector2, kind: StringName, fallbackKind: StringName, minLength := 1) -> bool: _prepare_pathfinder(kind) var isOneWay := kind == MazeGraph.ONE_WAY var fromMouths := _mouth_spots(fromAir, fromTowards, &"entrance" if isOneWay else &"") var toMouths := _mouth_spots(toAir, toTowards, &"exit" if isOneWay else &"") if isOneWay and (fromMouths.is_empty() or toMouths.is_empty()): kind = fallbackKind _prepare_pathfinder(kind) fromMouths = _mouth_spots(fromAir, fromTowards, &"") toMouths = _mouth_spots(toAir, toTowards, &"") for attempt in ROUTE_TRIES: if fromMouths.is_empty() or toMouths.is_empty(): return false var fromMouth: Dictionary = fromMouths[_random.randi_range(0, fromMouths.size() - 1)] var toMouth: Dictionary = toMouths[_random.randi_range(0, toMouths.size() - 1)] if fromMouth.spot == toMouth.spot: continue # Both ends in one region: they mustn't get in each other's way. if kind == MazeGraph.ONE_WAY and fromAir == toAir \ and not _is_one_way_safe(fromAir, fromMouth.spot, fromMouth.outward, toMouth.spot, toMouth.outward): continue var path := _find_path(fromMouth, toMouth, kind) if path.size() < minLength or not _fits(path, fromMouth, toMouth, kind): continue _put_tube(path, fromMouth.outward, toMouth.outward, kind) return true return false # Adds a short tube through one wall tile inside region `air` (a set of its # air tiles), joining two corridors that are far apart the long way round. func add_wall_pipe(air: Dictionary, kind: StringName, fallbackKind: StringName) -> bool: var tiles: Array = air.keys() if tiles.is_empty(): return false for attempt in WALL_PIPE_TRIES: var wall: Vector2i = tiles[_random.randi_range(0, tiles.size() - 1)] + MazeCorridors.STEPS[_random.randi_range(0, 3)] if not _bounds.grow(-1).has_point(wall) or _tubeKinds.has(wall) or _is_air(wall): continue for step: Vector2i in [Vector2i.RIGHT, Vector2i.DOWN]: var sideA := wall + step var sideB := wall - step if not air.has(sideA) or not air.has(sideB): continue if _is_blocked_front(sideA) or _is_blocked_front(sideB): continue if _distance(air, sideA, sideB) < MIN_SHORTCUT: continue var pipeKind := kind var outwardIn := step # Mouth into sideA faces `step`. var outwardOut := -step if kind == MazeGraph.ONE_WAY: if _is_one_way_safe(air, wall, step, wall, -step): outwardIn = step outwardOut = -step elif _is_one_way_safe(air, wall, -step, wall, step): outwardIn = -step outwardOut = step else: pipeKind = fallbackKind var path: Array[Vector2i] = [wall] _put_tube(path, outwardIn, outwardOut, pipeKind) return true return false # ---- Routing ---- # Sets which tiles a `kind` tube may go through, and random weights. func _prepare_pathfinder(kind: StringName) -> void: 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 var weight := 1.0 + _random.randf() * _winding var isSolid := isEdge if _tubeKinds.has(cell): isSolid = isSolid or not _can_cross(cell, kind) weight *= CROSSING_COST elif _is_air(cell): isSolid = isSolid or not _openAir.has(cell) or _is_protected(cell) weight *= OPEN_AIR_COST elif _is_interior(cell): weight *= INTERIOR_COST _pathfinder.set_point_solid(cell, isSolid) _pathfinder.set_point_weight_scale(cell, weight) # Whether a new `kind` tube may cross the tube tile at `cell`: same kind, a # straight tile (it then goes straight across it), and not a mouth. func _can_cross(cell: Vector2i, kind: StringName) -> bool: if _tubeKinds[cell] != kind: return false var openings := TubeSteer.get_openings(_layer, cell) if openings != 5 and openings != 10: return false for step in MazeCorridors.STEPS: if openings & TubeSteer.side_bit(step) and _is_air(cell + step): return false return true # A path between two mouth spots that crosses tubes only straight across. func _find_path(fromMouth: Dictionary, toMouth: Dictionary, kind: StringName) -> Array[Vector2i]: var blocked: Array[Vector2i] = [fromMouth.spot + fromMouth.outward, toMouth.spot + toMouth.outward] for tile in blocked: _pathfinder.set_point_solid(tile) var path: Array[Vector2i] = [] for attempt in CROSSING_RETRIES: path = _pathfinder.get_id_path(fromMouth.spot, toMouth.spot) var badCrossing := _bad_crossing(path) if badCrossing == Vector2i(-1, -1): break _pathfinder.set_point_solid(badCrossing) blocked.append(badCrossing) path = [] for tile in blocked: _pathfinder.set_point_solid(tile, _tubeKinds.has(tile) and not _can_cross(tile, kind) or (_is_air(tile) and (not _openAir.has(tile) or _is_protected(tile)))) return path # The first tube tile `path` uses without going straight across it, or (-1, -1). func _bad_crossing(path: Array[Vector2i]) -> Vector2i: for i in path.size(): var cell := path[i] if not _tubeKinds.has(cell): continue if i == 0 or i == path.size() - 1: return cell var across := path[i + 1] - path[i - 1] var openings := TubeSteer.get_openings(_layer, cell) var isStraightAcross := (across.x != 0 and openings == 5) or (across.y != 0 and openings == 10) if not isStraightAcross: return cell return Vector2i(-1, -1) # Whether laying `path` keeps the rules: its own mouth fronts and air moves # stay clear, and every region it covers air in stays in one piece. func _fits(path: Array[Vector2i], fromMouth: Dictionary, toMouth: Dictionary, kind: StringName) -> bool: var own := {fromMouth.spot + fromMouth.outward: true, toMouth.spot + toMouth.outward: true} if kind == MazeGraph.ONE_WAY: for tile in _blow_landing_tiles(toMouth.spot, toMouth.outward): own[tile] = true for tile in OneWayTube.blow_zone(_layer, toMouth.spot, toMouth.outward): own[tile] = true var covered := {} # Region -> air tiles the path covers. for tile in path: if own.has(tile): return false if _is_air(tile): var region := _region_of(tile) if not covered.has(region): covered[region] = [] covered[region].append(tile) for region: int in covered: if not _stays_connected(_regionAir[region], covered[region]): return false return true func _region_of(tile: Vector2i) -> int: for region in _regionAir.size(): if _regionAir[region].has(tile): return region return -1 func _is_protected(tile: Vector2i) -> bool: return mouthFronts.has(tile) or forcedCells.has(tile) or _keepFree.has(tile) # ---- Mouths ---- # Rock tiles beside the region's air where a mouth can go: # [{spot, outward}], the MOUTH_CHOICES nearest `towards`. `oneWayEnd`: # &"entrance" or &"exit" for only spots that end of a one-way tube may use. func _mouth_spots(air: Dictionary, towards: Vector2, oneWayEnd: StringName) -> Array[Dictionary]: var spots: Array[Dictionary] = [] for tile: Vector2i in air: if _is_blocked_front(tile): continue for step in MazeCorridors.STEPS: var spot: Vector2i = tile - step # The mouth faces `step`, onto `tile`. if not _is_air(spot) and not _tubeKinds.has(spot) and not _pathfinder.is_point_solid(spot) \ and _touches_channel(spot, step): spots.append({spot = spot, outward = step}) spots.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: return Vector2(a.spot).distance_squared_to(towards) < Vector2(b.spot).distance_squared_to(towards)) # The safety check floods the region, so only check spots until we have enough. var chosen: Array[Dictionary] = [] for spot in spots: if chosen.size() >= MOUTH_CHOICES: break if oneWayEnd == &"entrance" and not _is_one_way_safe(air, spot.spot, spot.outward, Vector2i.ZERO, Vector2i.ZERO): continue if oneWayEnd == &"exit" and not _is_one_way_safe(air, Vector2i.ZERO, Vector2i.ZERO, spot.spot, spot.outward): continue chosen.append(spot) return chosen # Whether `spot` (a mouth facing `outward`) is next to free rock between # regions or open air, so its tube can run there without going through (and # cutting up) the walls inside a region. func _touches_channel(spot: Vector2i, outward: Vector2i) -> bool: for step in MazeCorridors.STEPS: var next := spot + step if step != outward and not _pathfinder.is_point_solid(next) and (not _is_interior(next) or _is_air(next)): return true return false func _is_blocked_front(tile: Vector2i) -> bool: return forcedCells.has(tile) # Whether a one-way tube's entrance (at `entranceSpot`, facing # `entranceOutward`) and exit (likewise) follow the rules at the top of this # file in region `air`. An outward of ZERO leaves that end out (it's in # another region). func _is_one_way_safe(air: Dictionary, entranceSpot: Vector2i, entranceOutward: Vector2i, exitSpot: Vector2i, exitOutward: Vector2i) -> bool: var newForced: Array[Vector2i] = [] var landing := Vector2i.ZERO if entranceOutward != Vector2i.ZERO: var front := entranceSpot + entranceOutward if not air.has(front) or forcedCells.has(front) or mouthFronts.has(front) or _keepFree.has(front): return false newForced.append(front) if exitOutward != Vector2i.ZERO: if exitOutward == Vector2i.UP: return false var zone: Array[Vector2i] = [] for step in range(1, OneWayTube.BLOW_RANGE + 1): zone.append(exitSpot + exitOutward * step) landing = exitSpot + exitOutward * (OneWayTube.BLOW_RANGE + 1) for tile in zone + [landing]: if not air.has(tile) or forcedCells.has(tile) or newForced.has(tile): return false for tile in zone: if _keepFree.has(tile): return false for tile in zone + [landing]: if exitOutward.y == 0 and (_is_air(tile + Vector2i.UP) or _is_air(tile + Vector2i.DOWN)): return false for tile in zone: if mouthFronts.has(tile): return false newForced.append_array(zone) if exitOutward == Vector2i.DOWN: var fall := landing while _is_air(fall + Vector2i.DOWN): fall += Vector2i.DOWN if forcedCells.has(fall) or newForced.has(fall): return false return _stays_connected(air, newForced) # Whether the region's air, minus every forced tile and `newForced`, is one # piece. func _stays_connected(air: Dictionary, newForced: Array) -> bool: var open := {} for tile: Vector2i in air: if not forcedCells.has(tile) and not newForced.has(tile): open[tile] = true if open.is_empty(): return false var first: Vector2i = open.keys()[0] var seen := {first: true} var queue: Array[Vector2i] = [first] while not queue.is_empty(): var tile: Vector2i = queue.pop_back() for step in MazeCorridors.STEPS: var next := tile + step if open.has(next) and not seen.has(next): seen[next] = true queue.append(next) return seen.size() == open.size() # Tiles of corridor between two air tiles of a region (a large number if # they aren't joined). static func _distance(air: Dictionary, from: Vector2i, to: Vector2i) -> int: var distances := {from: 0} var queue: Array[Vector2i] = [from] while not queue.is_empty(): var tile: Vector2i = queue.pop_front() if tile == to: return distances[tile] for step in MazeCorridors.STEPS: var next := tile + step if air.has(next) and not distances.has(next): distances[next] = distances[tile] + 1 queue.append(next) return 1 << 30 # ---- Laying tiles ---- # Lays tube tiles along `path`. Its first tile's mouth faces `outwardIn`, its # last tile's `outwardOut`. A one-way tube goes in at the first mouth. Tube # tiles it goes straight across become cross tiles; air it covers stops being # air. func _put_tube(path: Array[Vector2i], outwardIn: Vector2i, outwardOut: Vector2i, kind: StringName) -> void: var last := path.size() - 1 for i in path.size(): var cell := path[i] if _is_air(cell): _regionAir[_region_of(cell)].erase(cell) _openAir.erase(cell) if _tubeKinds.has(cell): _tiles.set_tile(_layer, cell, 15, kind) # Straight across another tube. continue var back := outwardIn if i == 0 else path[i - 1] - cell var ahead := outwardOut if i == last else path[i + 1] - cell var openings := TubeSteer.side_bit(back) | TubeSteer.side_bit(ahead) var entrySide := TubeSteer.side_bit(back) if kind == MazeGraph.ONE_WAY and i == 0 else 0 _tiles.set_tile(_layer, cell, openings, kind, entrySide) _tubeKinds[cell] = kind mouthFronts[path[0] + outwardIn] = true mouthFronts[path[last] + outwardOut] = true if kind == MazeGraph.ONE_WAY: forcedCells[path[0] + outwardIn] = true for tile in OneWayTube.blow_zone(_layer, path[last], outwardOut): forcedCells[tile] = true for tile in _blow_landing_tiles(path[last], outwardOut): _keepFree[tile] = true # Where a blow out of the exit at `spot` facing `outward` drops the slime: the # landing tile, the one after (a sideways blow can slide it on) and, blowing # down, the fall below. func _blow_landing_tiles(spot: Vector2i, outward: Vector2i) -> Array[Vector2i]: var landing := spot + outward * (OneWayTube.BLOW_RANGE + 1) var tiles: Array[Vector2i] = [landing, landing + outward] while outward == Vector2i.DOWN and _is_air(landing + Vector2i.DOWN): landing += Vector2i.DOWN tiles.append(landing) return tiles func _is_interior(cell: Vector2i) -> bool: for rect in _interiors: if rect.has_point(cell): return true return false func _is_air(cell: Vector2i) -> bool: return _layer.get_cell_source_id(cell) == -1 static func middle(air: Dictionary) -> Vector2: var total := Vector2.ZERO for tile: Vector2i in air: total += Vector2(tile) return total / maxf(air.size(), 1.0)