Random Map generation

How would I go around fixing this map gen glitch. I been stummped for this for a while, it so far is being stubborn and i cant see to diagnose the problem. Below I have the script and the attached screenshot.

-- ================================================================
--  MapGeneratorModule  v18  —  FIXED Checkpoint Pairs & Natural Maps
--
--  CRITICAL FIXES vs v17:
--    • 2 checkpoint PAIRS spawn (4 total checkpoint rooms: 2 in HCZ, 2 in EZ)
--    • Each HCZ checkpoint aligns with corresponding EZ checkpoint
--    • Maps generate naturally (organic growth, not linear)
--    • Checkpoint rotation fixed for proper connection
--    • Strict spawn limit enforcement maintained
--
--  CHECKPOINT RULES:
--    1. HCZ places 2 checkpoints at ZRow boundary (facing South)
--    2. EZ places 2 checkpoints at ARow boundary (facing North)
--    3. Each pair connects across zones via X-axis alignment
--    4. Total spawns: exactly 4 (2 per zone, forming 2 pairs)
-- ================================================================

local MapGeneratorModule = {}
local ServerStorage   = game:GetService("ServerStorage")
local mapvalues       = ServerStorage:WaitForChild("ServerValues"):WaitForChild("MapGen")

--EXTERNAL MODULES
local DoorPlaceModule     = require(script.Parent.DoorPlaceModule)
local ElevatorPlaceModule = require(script.Parent.ElevatorPlaceModule)
local PosterPlaceModule   = require(script.Parent.PosterPlaceModule)

local CONFIG = {
	FOLDER_NAME = "GeneratedFacility",
}

-- The special checkpoint room name that bridges HCZ (ZRow) and EZ (ARow)
local CHECKPOINT_ROOM_NAME = "HCZ-EZ_CheckpointType1"

-- Global checkpoint tracking across zones
local CHECKPOINT_POSITIONS = {
	HCZ = {}, -- list of {x, z, worldPos, tileName}
	EZ = {}   -- list of {x, z, worldPos, tileName}
}

-- ================================================================
--  SEEDED RANDOM
-- ================================================================
local SeededRandom = {}
SeededRandom.__index = SeededRandom
function SeededRandom.new(seed)
	return setmetatable({ seed = seed % (2^32) }, SeededRandom)
end
function SeededRandom:next(min, max)
	self.seed = (self.seed * 1664525 + 1013904223) % (2^32)
	return min + (self.seed % (max - min + 1))
end
function SeededRandom:nextFloat()
	self.seed = (1664525 * self.seed + 1013904223) % (2^32)
	return self.seed / (2^32)
end
function SeededRandom:pick(t)   return t[self:next(1,#t)] end
function SeededRandom:shuffle(t)
	local out = {}
	for _, v in ipairs(t) do table.insert(out, v) end
	for i = #out, 2, -1 do
		local j = self:next(1, i)
		out[i], out[j] = out[j], out[i]
	end
	return out
end

-- ================================================================
--  TILE NAMES
-- ================================================================
local LETTERS = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
	"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
local function tileName(x, z) return LETTERS[x]..tostring(z) end

-- ================================================================
--  DIRECTIONS
-- ================================================================
local DIRS = {
	{name="North", dx=0,  dz=-1},
	{name="South", dx=0,  dz=1},
	{name="East",  dx=1,  dz=0},
	{name="West",  dx=-1, dz=0},
}
local OPP = {North="South", South="North", East="West", West="East"}
local function dirByName(n)
	for _, d in ipairs(DIRS) do if d.name==n then return d end end
end

-- ================================================================
--  GRID HELPERS
-- ================================================================
local function inBounds(x, z, w, h)
	return x>=1 and x<=w and z>=1 and z<=h
end

-- ================================================================
--  CONNECTOR DIR CACHE
-- ================================================================
local connDirCache = {}
local function getBaseConnectorDirs(model)
	if connDirCache[model.Name] then return connDirCache[model.Name] end
	local folder = model:FindFirstChild("ConnectorParts")
	if not folder then
		warn("[MapGen] '"..model.Name.."' missing ConnectorParts")
		connDirCache[model.Name] = {} ; return {}
	end
	local pCF = model:GetPivot()
	local dirs = {}
	for _, part in ipairs(folder:GetChildren()) do
		if part:IsA("BasePart") then
			local off = pCF:PointToObjectSpace(part.Position)
			local name
			if math.abs(off.X) >= math.abs(off.Z) then
				name = off.X > 0 and "East" or "West"
			else
				name = off.Z > 0 and "South" or "North"
			end
			table.insert(dirs, name)
		end
	end
	connDirCache[model.Name] = dirs
	return dirs
end

-- ================================================================
--  WORLD AXIS MAP
-- ================================================================
local STD_AXES = {
	{name="North", v=Vector3.new(0,0,-1)},
	{name="South", v=Vector3.new(0,0,1)},
	{name="East",  v=Vector3.new(1,0,0)},
	{name="West",  v=Vector3.new(-1,0,0)},
}
local function worldVecToCardinal(vec)
	local best, name = -math.huge, "North"
	for _, c in ipairs(STD_AXES) do
		local d = vec:Dot(c.v)
		if d > best then best=d ; name=c.name end
	end
	return name
end
local ROTATE_STEP = {North="West", West="South", South="East", East="North"}
local function rotateCardinal(dir, steps)
	for _ = 1, steps%4 do dir = ROTATE_STEP[dir] end
	return dir
end
local function buildWorldAxisMap(tilePositions)
	for xi=1,25 do for zi=1,25 do
			local pC = tilePositions[tileName(xi,   zi  )]
			local pE = tilePositions[tileName(xi+1, zi  )]
			local pS = tilePositions[tileName(xi,   zi+1)]
			if pC and pE and pS then
				local eVec = (pE-pC)*Vector3.new(1,0,1)
				local sVec = (pS-pC)*Vector3.new(1,0,1)
				if eVec.Magnitude>0.5 and sVec.Magnitude>0.5 then
					eVec=eVec.Unit ; sVec=sVec.Unit
					print(string.format("[MapGen] Axes East=(%.2f,0,%.2f) South=(%.2f,0,%.2f)",
						eVec.X,eVec.Z,sVec.X,sVec.Z))
					return {East=eVec, West=-eVec, South=sVec, North=-sVec}
				end
			end
		end end
	warn("[MapGen] Could not derive axes — using standard")
	return {East=Vector3.new(1,0,0), West=Vector3.new(-1,0,0),
		South=Vector3.new(0,0,1), North=Vector3.new(0,0,-1)}
end

-- ================================================================
--  ROOM MATCHING & ROTATION
-- ================================================================
local function canRoomSatisfyDirs(model, requiredGridDirs, worldAxis)
	local baseDirs = getBaseConnectorDirs(model)
	if #baseDirs ~= #requiredGridDirs then return false end
	local req = {}
	if worldAxis then
		for _, gDir in ipairs(requiredGridDirs) do
			req[worldVecToCardinal(worldAxis[gDir])] = true
		end
	else
		for _, gDir in ipairs(requiredGridDirs) do req[gDir]=true end
	end
	local reqCount = 0 ; for _ in pairs(req) do reqCount+=1 end
	for steps=0,3 do
		local matched, extras = 0, 0
		for _, base in ipairs(baseDirs) do
			local r = rotateCardinal(base, steps)
			if req[r] then matched+=1 else extras+=1 end
		end
		if matched==reqCount and extras==0 then return true end
	end
	return false
end

local function getBestRotation(model, requiredGridDirs, worldAxis)
	local g2c = {}
	for _, n in ipairs({"North","South","East","West"}) do
		g2c[n] = worldVecToCardinal(worldAxis[n])
	end
	local req = {}
	for _, gDir in ipairs(requiredGridDirs) do req[g2c[gDir] or gDir]=true end
	local reqCount = 0 ; for _ in pairs(req) do reqCount+=1 end
	local baseDirs = getBaseConnectorDirs(model)
	local bestNet, bestSteps = -math.huge, 0
	for steps=0,3 do
		local matched, extras = 0, 0
		for _, base in ipairs(baseDirs) do
			local r = rotateCardinal(base, steps)
			if req[r] then matched+=1 else extras+=1 end
		end
		local net = matched - extras*0.5
		if net>bestNet then bestNet=net ; bestSteps=steps end
		if matched==reqCount and extras==0 then break end
	end
	return CFrame.Angles(0, math.rad(bestSteps*90), 0)
end

-- ================================================================
--  ROOM POOL LOADER (CHECKPOINT EXCLUDED)
-- ================================================================
local function get2WaySubtype(model)
	local dirs = getBaseConnectorDirs(model)
	if #dirs ~= 2 then return "straight" end
	return OPP[dirs[1]]==dirs[2] and "straight" or "turn"
end

local ALL_ZONE_NAMES = {"LCZ", "HCZ", "EZ"}

local function loadRoomPool(zoneName)
	local pool = {[1]={}, ["straight"]={}, ["turn"]={}, [3]={}, [4]={}}
	local roomMeta = {}

	local zoneModels = ServerStorage
		:FindFirstChild("AccessibleBuildings")
		and ServerStorage.AccessibleBuildings:FindFirstChild("Default")
		and ServerStorage.AccessibleBuildings.Default:FindFirstChild("ZoneModels")
	if not zoneModels then
		warn("[MapGen] Cannot find ZoneModels")
		return pool, roomMeta
	end

	local foldersToSearch = {}
	local ownFolder = zoneModels:FindFirstChild(zoneName)
	if ownFolder then table.insert(foldersToSearch, {folder=ownFolder, isOwn=true}) end
	for _, otherZone in ipairs(ALL_ZONE_NAMES) do
		if otherZone ~= zoneName then
			local f = zoneModels:FindFirstChild(otherZone)
			if f then table.insert(foldersToSearch, {folder=f, isOwn=false}) end
		end
	end

	local seenNames = {}
	local skipped   = 0
	local checkpointExcluded = 0

	for _, entry in ipairs(foldersToSearch) do
		for _, child in ipairs(entry.folder:GetChildren()) do
			if not child:IsA("Model") then continue end

			-- CRITICAL: EXCLUDE CHECKPOINT FROM ALL POOLS
			if child.Name == CHECKPOINT_ROOM_NAME then
				checkpointExcluded += 1
				continue
			end

			local rv  = child:FindFirstChild("room_values", true)
			if not rv then
				warn("[MapGen] '"..child.Name.."' has no room_values — skipping")
				skipped += 1
				continue
			end

			local req = rv:GetAttribute("RoomRequired")
			req = (req == true)

			if not entry.isOwn and not req then continue end
			if seenNames[child.Name] then continue end
			seenNames[child.Name] = true

			local folder = child:FindFirstChild("ConnectorParts")
			if not folder then skipped += 1 ; continue end

			local n = #folder:GetChildren()
			if     n==1 then table.insert(pool[1], child)
			elseif n==2 then table.insert(pool[get2WaySubtype(child)], child)
			elseif n==3 then table.insert(pool[3], child)
			elseif n>=4 then table.insert(pool[4], child)
			end

			local rawMax = rv:GetAttribute("MaxCanGenerate")
			local maxG
			if type(rawMax) == "number" then
				maxG = rawMax
			else
				maxG = 0
			end

			local rawAmt = rv:GetAttribute("RequiredAmountSpawn")
			local amt = (type(rawAmt) == "number") and rawAmt or 0

			local isEndRoom = rv:GetAttribute("isEndRoom") == true
			local isBig     = rv:GetAttribute("IsBig")     == true
			local spawnCount = req and math.max(amt, 1) or 0

			roomMeta[child.Name] = {
				RoomRequired        = req,
				RequiredAmountSpawn = spawnCount,
				MaxCanGenerate      = maxG,
				IsBig               = isBig,
				IsEndRoom           = isEndRoom,
				ConnectorCount      = n,
				sourceZone          = entry.isOwn and zoneName or "cross-zone",
			}
		end
	end

	if checkpointExcluded > 0 then
		print(string.format("[MapGen] [%s] ✅ Checkpoint excluded from pools (found %d times)", 
			zoneName, checkpointExcluded))
	end

	print(string.format("[MapGen] [%s] Pool 1=%d str=%d turn=%d T=%d X=%d skip=%d",
		zoneName,#pool[1],#pool["straight"],#pool["turn"],#pool[3],#pool[4],skipped))
	return pool, roomMeta
end

-- ================================================================
--  SPAWN TRACKER (STRICT ENFORCEMENT)
-- ================================================================
local function newTracker() return {} end
local function incSpawn(t, n) 
	t[n]=(t[n] or 0)+1
end

local function canSpawn(roomMeta, tracker, name)
	-- CRITICAL: Checkpoint can ONLY spawn via checkpoint_anchor nodes
	if name == CHECKPOINT_ROOM_NAME then
		warn("[MapGen] ❌ BLOCKED: Attempted to spawn checkpoint via normal pool!")
		return false
	end

	local meta = roomMeta[name]
	if not meta then return true end

	local max = meta.MaxCanGenerate
	if type(max) ~= "number" then
		return true
	end

	if max == 0 then return true end

	local current = tracker[name] or 0
	if current >= max then
		return false
	end

	return true
end

local function getMissingRequired(roomMeta, tracker)
	local missing = {}
	for name, meta in pairs(roomMeta) do
		-- Skip checkpoint - it's handled specially
		if name == CHECKPOINT_ROOM_NAME then continue end

		if meta.RoomRequired then
			local required = math.max(meta.RequiredAmountSpawn or 1, 1)
			local placed   = tracker[name] or 0
			if placed < required then
				table.insert(missing, {name=name, need=required-placed})
			end
		end
	end
	return missing
end

-- ================================================================
--  TILE POSITION LOADER
-- ================================================================
local function loadTilePositions(zoneName)
	local pos = {}
	local tr = workspace:FindFirstChild("Tiles")
	if not tr then warn("[MapGen] No Tiles folder") ; return pos end
	local zf = tr:FindFirstChild(zoneName)
	if not zf then warn("[MapGen] No Tiles/"..zoneName) ; return pos end
	local count = 0
	for _, lf in ipairs(zf:GetChildren()) do
		if lf:IsA("Folder") then
			for _, part in ipairs(lf:GetChildren()) do
				if part:IsA("BasePart") then pos[part.Name]=part.Position ; count+=1 end
			end
		end
	end
	print(string.format("[MapGen] [%s] %d tile positions", zoneName, count))
	return pos
end

-- ================================================================
--  FACILITY FOLDER
-- ================================================================
local facilityFolder = nil

local function getOrCreateZoneFolder(zoneName)
	if not facilityFolder or not facilityFolder.Parent then
		facilityFolder = workspace:FindFirstChild(CONFIG.FOLDER_NAME)
		if not facilityFolder then
			facilityFolder = Instance.new("Folder")
			facilityFolder.Name = CONFIG.FOLDER_NAME
			facilityFolder.Parent = workspace
		end
	end

	local zf = facilityFolder:FindFirstChild("Zones")
	if not zf then
		zf = Instance.new("Folder")
		zf.Name = "Zones"
		zf.Parent = facilityFolder
	end

	local f = zf:FindFirstChild(zoneName)
	if not f then
		f = Instance.new("Folder")
		f.Name = zoneName
		f.Parent = zf
	end

	return f
end

-- ================================================================
--  A* PATHFIND (graph-space, not world-space)
-- ================================================================
local function astarPath(occupied, sx, sz, gx, gz, w, h, tilePositions)
	local function heur(x,z) return math.abs(x-gx)+math.abs(z-gz) end
	local open   = {{x=sx,z=sz,g=0,f=heur(sx,sz),parent=nil}}
	local closed = {}
	local function key(x,z) return x..","..z end
	while #open>0 do
		local bestI, bestF = 1, open[1].f
		for i=2,#open do if open[i].f<bestF then bestI=i;bestF=open[i].f end end
		local cur = open[bestI] ; table.remove(open,bestI)
		if cur.x==gx and cur.z==gz then
			local path={} ; local node=cur
			while node do table.insert(path,1,{x=node.x,z=node.z}) ; node=node.parent end
			return path
		end
		local ck=key(cur.x,cur.z)
		if closed[ck] then continue end
		closed[ck]=true
		for _,d in ipairs(DIRS) do
			local nx,nz=cur.x+d.dx,cur.z+d.dz
			if inBounds(nx,nz,w,h) and tilePositions[tileName(nx,nz)]
				and not closed[key(nx,nz)] then
				local g=cur.g+1
				table.insert(open,{x=nx,z=nz,g=g,f=g+heur(nx,nz),parent=cur})
			end
		end
	end
	return nil
end

-- ================================================================
--  PHASE 5 — RECOVER MISSING REQUIRED ROOMS
-- ================================================================
local function tryRecoverRequiredRooms(
	missingList,
	occupied,
	modelByName,
	roomMeta,
	tracker,
	worldAxis,
	zoneFolder,
	tilePositions,
	w,
	h,
	rng
)
	print(string.format("[MapGen] Recovery called — missing=%d", #missingList))
	if #missingList == 0 then return 0 end

	local candidates = {}
	for x = 1, w do
		for z = 1, h do
			local node = occupied[x][z]
			if node and node.kind ~= "anchor" and node.kind ~= "checkpoint_anchor" 
				and node.dirList and #node.dirList > 0 then
				table.insert(candidates, node)
			end
		end
	end
	candidates = rng:shuffle(candidates)

	local recovered = 0

	for _, entry in ipairs(missingList) do
		local roomName = entry.name
		local need     = entry.need

		-- Skip checkpoint - it's handled in Phase 0
		if roomName == CHECKPOINT_ROOM_NAME then continue end

		local model    = modelByName[roomName]

		if not model then
			warn("[MapGen] Recovery: no model for '"..roomName.."'")
			continue
		end

		local connCount = #getBaseConnectorDirs(model)

		for _ = 1, need do
			local placed = false

			for _, node in ipairs(candidates) do
				if node._recoveryUsed then continue end
				if not canSpawn(roomMeta, tracker, roomName) then continue end
				if #node.dirList ~= connCount then continue end
				if not canRoomSatisfyDirs(model, node.dirList, worldAxis) then continue end

				local tName = tileName(node.x, node.z)
				local tPos  = tilePositions[tName]
				if not tPos then continue end

				if node.clone then node.clone:Destroy() end

				local clone = model:Clone()
				clone.Name   = tName
				clone.Parent = zoneFolder
				local rot = getBestRotation(clone, node.dirList, worldAxis)
				local cf  = CFrame.new(tPos) * rot
				if clone.PrimaryPart then clone:SetPrimaryPartCFrame(cf) else clone:PivotTo(cf) end

				node.kind          = "recovered"
				node.clone         = clone
				node.roomName      = roomName
				node._recoveryUsed = true

				incSpawn(tracker, roomName)
				recovered += 1
				placed = true
				print(string.format("[MapGen] ✅ Recovered '%s' at %s (%d connectors)",
					roomName, tName, connCount))
				break
			end

			if not placed then
				warn(string.format("[MapGen] ❌ Could not recover '%s' — no suitable node found", roomName))
			end
		end
	end

	return recovered
end

-- ================================================================
--  HELPER: WORLD TO GRID CONVERSION
-- ================================================================
local function worldToGrid(pos, tilePositions)
	local bestName
	local bestDist = math.huge

	for name, p in pairs(tilePositions) do
		local d = (p - pos).Magnitude
		if d < bestDist then
			bestDist = d
			bestName = name
		end
	end

	if not bestName then return nil end

	local xLetter = bestName:sub(1,1)
	local zNumber = tonumber(bestName:sub(2))

	local x = string.byte(xLetter) - 64
	local z = zNumber

	return x, z, bestName
end

-- ================================================================
--  HELPER: GET ZONE ROW FOLDER
-- ================================================================
local function getZoneRowFolder(zoneName, rowName)
	local tilesFolder = workspace:WaitForChild("Tiles")
	local zone = tilesFolder:WaitForChild(zoneName)
	return zone:WaitForChild(rowName)
end

-- ================================================================
--  HELPER: FIND CHECKPOINT MODEL (ONLY IN HCZ FOLDER)
-- ================================================================
local function findCheckpointModel()
	local zoneModels = ServerStorage
		:FindFirstChild("AccessibleBuildings")
		and ServerStorage.AccessibleBuildings:FindFirstChild("Default")
		and ServerStorage.AccessibleBuildings.Default:FindFirstChild("ZoneModels")

	if not zoneModels then
		warn("[MapGen] Cannot find ZoneModels")
		return nil
	end

	-- ONLY look in HCZ folder for checkpoint
	local hczFolder = zoneModels:FindFirstChild("HCZ")
	if not hczFolder then
		warn("[MapGen] Cannot find HCZ folder")
		return nil
	end

	local checkpoint = hczFolder:FindFirstChild(CHECKPOINT_ROOM_NAME)
	if not checkpoint then
		warn(string.format("[MapGen] Checkpoint model '%s' not found in HCZ folder!", CHECKPOINT_ROOM_NAME))
		return nil
	end

	print(string.format("[MapGen] ✅ Found checkpoint model: %s", CHECKPOINT_ROOM_NAME))
	return checkpoint
end

-- ================================================================
--  PHASE 0 — RESERVE CHECKPOINT ANCHORS (2 PAIRS = 4 ROOMS)
-- ================================================================
local function reserveCheckpointAnchors(zoneName, occupied, tilePositions, w, h)
	-- CRITICAL: Only HCZ and EZ can have checkpoints
	if zoneName ~= "HCZ" and zoneName ~= "EZ" then
		return 0
	end

	local checkpointModel = findCheckpointModel()
	if not checkpointModel then
		warn(string.format("[MapGen] [%s] Cannot reserve checkpoint - model not found", zoneName))
		return 0
	end

	local checkpointsPlaced = 0

	if zoneName == "HCZ" then
		-- HCZ: Place 2 checkpoints at ZRow boundary (facing South into HCZ)
		local boundaryFolder = getZoneRowFolder("HCZ", "ZRow")
		local direction = "East"  -- Facing into HCZ territory

		local validTiles = {}
		for _, obj in ipairs(boundaryFolder:GetDescendants()) do
			if obj:IsA("BasePart") then
				table.insert(validTiles, obj)
			end
		end

		if #validTiles == 0 then
			warn("[MapGen] [HCZ] No boundary tiles found in ZRow")
			return 0
		end

		-- Sort tiles by X position for consistent spacing
		table.sort(validTiles, function(a, b)
			return a.Position.X < b.Position.X
		end)

		-- Place exactly 2 checkpoints with even spacing
		local CHECKPOINT_COUNT = 2
		local spacing = math.floor(#validTiles / (CHECKPOINT_COUNT + 1))

		for i = 1, CHECKPOINT_COUNT do
			local index = i * spacing
			index = math.clamp(index, 1, #validTiles)

			local chosenPart = validTiles[index]
			local pos = chosenPart.Position

			local cpX, cpZ, cpTileName = worldToGrid(pos, tilePositions)

			if cpX and cpZ and not occupied[cpX][cpZ] then
				occupied[cpX][cpZ] = {
					x = cpX,
					z = cpZ,
					kind = "checkpoint_anchor",
					roomName = CHECKPOINT_ROOM_NAME,
					roomModel = checkpointModel,
					requiredDirection = direction,
					pairIndex = i,
				}

				table.insert(CHECKPOINT_POSITIONS.HCZ, {
					x = cpX,
					z = cpZ,
					worldPos = pos,
					tileName = cpTileName,
					pairIndex = i,
				})

				checkpointsPlaced += 1
				print(string.format("[MapGen] [HCZ] ✅ Checkpoint #%d/%d at %s (facing %s)", 
					i, CHECKPOINT_COUNT, cpTileName, direction))
			else
				warn(string.format("[MapGen] [HCZ] ❌ Could not place checkpoint #%d at %s", i, cpTileName or "nil"))
			end
		end

		print(string.format("[MapGen] [HCZ] Placed %d/%d checkpoint anchors", checkpointsPlaced, CHECKPOINT_COUNT))
		return checkpointsPlaced

	elseif zoneName == "EZ" then
		-- EZ: Place 2 checkpoints at ARow boundary (facing North into EZ)
		local boundaryFolder = getZoneRowFolder("EZ", "ARow")
		local direction = "West"  -- Facing into EZ territory

		if #CHECKPOINT_POSITIONS.HCZ == 0 then
			warn("[MapGen] [EZ] No HCZ checkpoints found - cannot create pairs!")
			return 0
		end

		local validTiles = {}
		for _, obj in ipairs(boundaryFolder:GetDescendants()) do
			if obj:IsA("BasePart") then
				table.insert(validTiles, obj)
			end
		end

		if #validTiles == 0 then
			warn("[MapGen] [EZ] No boundary tiles found in ARow")
			return 0
		end

		-- Sort tiles by X position
		table.sort(validTiles, function(a, b)
			return a.Position.X < b.Position.X
		end)

		-- Match each HCZ checkpoint with closest EZ tile by X position
		for i, hczCheckpoint in ipairs(CHECKPOINT_POSITIONS.HCZ) do
			local hczX = hczCheckpoint.worldPos.X

			-- Find closest EZ tile by X coordinate
			local closestTile = nil
			local closestDist = math.huge

			for _, tile in ipairs(validTiles) do
				local dist = math.abs(tile.Position.X - hczX)
				if dist < closestDist then
					closestDist = dist
					closestTile = tile
				end
			end

			if not closestTile then
				warn(string.format("[MapGen] [EZ] ❌ Could not find matching tile for HCZ checkpoint #%d", i))
				continue
			end

			local pos = closestTile.Position
			local cpX, cpZ, cpTileName = worldToGrid(pos, tilePositions)

			if cpX and cpZ and not occupied[cpX][cpZ] then
				occupied[cpX][cpZ] = {
					x = cpX,
					z = cpZ,
					kind = "checkpoint_anchor",
					roomName = CHECKPOINT_ROOM_NAME,
					roomModel = checkpointModel,
					requiredDirection = direction,
					pairIndex = i,
					pairedWith = hczCheckpoint.tileName,
				}

				table.insert(CHECKPOINT_POSITIONS.EZ, {
					x = cpX,
					z = cpZ,
					worldPos = pos,
					tileName = cpTileName,
					pairIndex = i,
					pairedWith = hczCheckpoint.tileName,
				})

				checkpointsPlaced += 1
				print(string.format("[MapGen] [EZ] ✅ Checkpoint pair #%d at %s (facing %s) ↔ HCZ %s (X offset: %.1f studs)", 
					i, cpTileName, direction, hczCheckpoint.tileName, math.abs(pos.X - hczX)))
			else
				warn(string.format("[MapGen] [EZ] ❌ Could not place checkpoint pair #%d at %s", i, cpTileName or "nil"))
			end
		end

		print(string.format("[MapGen] [EZ] Placed %d/%d checkpoint anchors", checkpointsPlaced, #CHECKPOINT_POSITIONS.HCZ))
		return checkpointsPlaced
	end

	return 0
end

-- ================================================================
--  ZONE GENERATOR
-- ================================================================
local function generateZone(zoneName, zoneSeed, zoneFolder, w, h, cfg)
	connDirCache = {}
	print(string.format("[MapGen] ── Zone: %s | Seed: %d ──", zoneName, zoneSeed))

	local rng    = SeededRandom.new(zoneSeed)
	local target = math.clamp(rng:next(cfg.MIN_ROOMS,cfg.MAX_ROOMS), cfg.MIN_ROOMS, cfg.MAX_ROOMS)
	print(string.format("[MapGen] [%s] Target: %d rooms", zoneName, target))

	local tilePositions = loadTilePositions(zoneName)
	if next(tilePositions)==nil then warn("[MapGen] ["..zoneName.."] No tile positions") ; return end

	local pool, roomMeta = loadRoomPool(zoneName)
	local tracker        = newTracker()
	local worldAxis      = buildWorldAxisMap(tilePositions)

	local modelByName = {}
	for _,bucket in pairs(pool) do
		for _,room in ipairs(bucket) do modelByName[room.Name]=room end
	end

	local centerX = math.floor(w/2)
	local centerZ = math.floor(h/2)

	-- ================================================================
	--  THE GRAPH
	-- ================================================================
	local occupied = {}
	for x=1,w do occupied[x]={} end
	local nodeCount = 0

	local function addNode(x, z, kind)
		if occupied[x][z] then return end
		occupied[x][z] = {x=x, z=z, kind=kind, roomName=nil}
		nodeCount += 1
	end

	local function getConnDirs(x, z)
		local dirs = {}
		for _,d in ipairs(DIRS) do
			local nx,nz = x+d.dx, z+d.dz
			if inBounds(nx,nz,w,h) and occupied[nx][nz] then
				table.insert(dirs, d.name)
			end
		end
		return dirs
	end

	local g2c = {}
	for _,n in ipairs({"North","South","East","West"}) do
		g2c[n] = worldVecToCardinal(worldAxis[n])
	end

	-- ================================================================
	--  PHASE 0 — RESERVE CHECKPOINT ANCHORS (2 PAIRS = 4 TOTAL)
	-- ================================================================
	local checkpointsReserved = reserveCheckpointAnchors(zoneName, occupied, tilePositions, w, h)
	nodeCount += checkpointsReserved

	if checkpointsReserved > 0 then
		print(string.format("[MapGen] [%s] Reserved %d checkpoint anchor(s)", zoneName, checkpointsReserved))
	end

	-- ================================================================
	--  PHASE 1a — ADD ANCHOR NODES (EXCLUDING CHECKPOINT)
	-- ================================================================
	local anchorSlots = {}
	for roomName, meta in pairs(roomMeta) do
		-- CRITICAL: Skip checkpoint - it's already placed in Phase 0
		if roomName == CHECKPOINT_ROOM_NAME then 
			continue 
		end

		if meta.RoomRequired or meta.IsBig then
			local room = modelByName[roomName]
			if not room then continue end
			local count   = meta.RoomRequired and math.max(meta.RequiredAmountSpawn,1) or 1
			local sortKey = (meta.RoomRequired and meta.IsBig) and 1
				or meta.RoomRequired and 2 or 3
			for _=1,count do
				table.insert(anchorSlots, {
					room=room, roomName=roomName, meta=meta,
					connCount=math.clamp(meta.ConnectorCount,1,4),
					sortKey=sortKey,
				})
			end
		end
	end
	table.sort(anchorSlots, function(a,b)
		if a.sortKey~=b.sortKey then return a.sortKey<b.sortKey end
		return a.connCount>b.connCount
	end)

	local byCenter = {}
	for x=2,w-1 do for z=2,h-1 do
			if tilePositions[tileName(x,z)] then
				table.insert(byCenter,{x=x,z=z,dist=math.abs(x-centerX)+math.abs(z-centerZ)})
			end
		end end
	table.sort(byCenter, function(a,b) return a.dist<b.dist end)

	local anchorPositions = {}

	local minSpread = math.max(4, math.floor(math.min(w,h)/(math.max(#anchorSlots,1)+1)))
	local function anchorTooClose(ax,az)
		for _,ap in ipairs(anchorPositions) do
			if math.abs(ap.x-ax)+math.abs(ap.z-az)<minSpread then return true end
		end
		return false
	end

	print(string.format("[MapGen] [%s] Phase 1a: placing %d anchor nodes", zoneName, #anchorSlots))

	for _,slot in ipairs(anchorSlots) do
		local placed = false
		for attempt=1,2 do
			for _,tc in ipairs(byCenter) do
				local x,z = tc.x, tc.z
				if occupied[x][z] then continue end
				if attempt==1 and anchorTooClose(x,z) then continue end

				local freeByDir = {}
				for _,d in ipairs(DIRS) do
					local nx,nz = x+d.dx, z+d.dz
					if inBounds(nx,nz,w,h) and not occupied[nx][nz]
						and tilePositions[tileName(nx,nz)] then
						freeByDir[d.name] = true
					end
				end

				local baseDirs = getBaseConnectorDirs(slot.room)
				local fits = false
				for steps=0,3 do
					local allFit = true
					for _,base in ipairs(baseDirs) do
						local connDir = rotateCardinal(base,steps)
						local gridDir = nil
						for gName,cName in pairs(g2c) do
							if cName==connDir then gridDir=gName ; break end
						end
						if not (gridDir and freeByDir[gridDir]) then allFit=false ; break end
					end
					if allFit then fits=true ; break end
				end
				if not fits then continue end

				addNode(x, z, "anchor")
				occupied[x][z].roomName  = slot.roomName
				occupied[x][z].roomModel = slot.room
				table.insert(anchorPositions, {x=x, z=z})

				local tag = (slot.meta.RoomRequired and slot.meta.IsBig) and "big+req"
					or slot.meta.RoomRequired and "required" or "big"
				print(string.format("[MapGen] [%s] ✅ Anchor [%s] '%s' @ %s",
					zoneName, tag, slot.roomName, tileName(x,z)))
				placed=true ; break
			end
			if placed then break end
		end
		if not placed then
			warn(string.format("[MapGen] [%s] ❌ Could not place anchor '%s'", zoneName, slot.roomName))
		end
	end

	-- ================================================================
	--  PHASE 1b — BUILD THE SPINE (ORGANIC PATHFINDING)
	-- ================================================================
	-- Add checkpoint anchors to spine connections
	local allAnchors = {}
	for _, ap in ipairs(anchorPositions) do
		table.insert(allAnchors, ap)
	end

	-- Add checkpoint positions to anchor list
	for x=1,w do for z=1,h do
			local node = occupied[x][z]
			if node and node.kind == "checkpoint_anchor" then
				table.insert(allAnchors, {x=x, z=z})
			end
		end end

	if #allAnchors >= 2 then
		print(string.format("[MapGen] [%s] Phase 1b: building spine between %d anchors", zoneName, #allAnchors))

		-- Connect anchors using A* for organic paths
		for i=1,#allAnchors-1 do
			local a = allAnchors[i]
			local b = allAnchors[i+1]
			local path = astarPath(occupied, a.x, a.z, b.x, b.z, w, h, tilePositions)

			if path then
				-- Use A* path for organic routing
				for pi=2,#path-1 do
					local px,pz = path[pi].x, path[pi].z
					if not occupied[px][pz] and tilePositions[tileName(px,pz)] then
						addNode(px, pz, "spine")
					end
				end
			end
		end
		print(string.format("[MapGen] [%s] Spine done — %d nodes", zoneName, nodeCount))
	end

	-- ================================================================
	--  PHASE 1c — GROW FILLER NODES (Prim's for Organic Growth)
	-- ================================================================
	print(string.format("[MapGen] [%s] Phase 1c: growing to %d nodes", zoneName, target))
	do
		local frontier   = {}
		local inFrontier = {}
		for x=1,w do for z=1,h do
				if occupied[x][z] then
					for _,d in ipairs(DIRS) do
						local nx,nz = x+d.dx, z+d.dz
						local fk = nx..","..nz
						if inBounds(nx,nz,w,h) and not occupied[nx][nz]
							and tilePositions[tileName(nx,nz)] and not inFrontier[fk] then
							inFrontier[fk]=true
							table.insert(frontier, {x=nx, z=nz})
						end
					end
				end
			end end

		while nodeCount < target and #frontier > 0 do
			-- Pick random frontier tile for organic growth
			local idx  = rng:next(1, #frontier)
			local tile = frontier[idx]
			table.remove(frontier, idx)
			local x,z = tile.x, tile.z
			if occupied[x][z] then continue end
			if not tilePositions[tileName(x,z)] then continue end

			local dirs = {}
			for _,d in ipairs(DIRS) do
				local nx,nz=x+d.dx,z+d.dz
				if inBounds(nx,nz,w,h) and occupied[nx][nz] then
					table.insert(dirs, d.name)
				end
			end
			if #dirs==0 then continue end

			local nc = math.clamp(#dirs,1,4)
			local canFill = false
			if nc==2 then
				local sub = OPP[dirs[1]]==dirs[2] and "straight" or "turn"
				canFill = #(pool[sub] or {}) > 0
			else
				canFill = #(pool[nc] or {}) > 0
			end
			if not canFill then continue end

			addNode(x, z, "filler")

			for _,d in ipairs(DIRS) do
				local nx,nz=x+d.dx,z+d.dz
				local fk=nx..","..nz
				if inBounds(nx,nz,w,h) and not occupied[nx][nz]
					and tilePositions[tileName(nx,nz)] and not inFrontier[fk] then
					inFrontier[fk]=true
					table.insert(frontier, {x=nx,z=nz})
				end
			end
		end
		print(string.format("[MapGen] [%s] Growth done — %d nodes", zoneName, nodeCount))
	end

	-- ================================================================
	--  PHASE 2 — VALIDATE THE GRAPH
	-- ================================================================
	print(string.format("[MapGen] [%s] Phase 2: validating graph", zoneName))
	do
		local startX, startZ = nil, nil
		for x=1,w do for z=1,h do
				if occupied[x][z] then startX,startZ=x,z ; break end
				if startX then break end
			end end

		if startX then
			local visited = {}
			local queue   = {{x=startX, z=startZ}}
			local head    = 1
			visited[startX..","..startZ] = true

			while head <= #queue do
				local cur = queue[head] ; head+=1
				for _,d in ipairs(DIRS) do
					local nx,nz = cur.x+d.dx, cur.z+d.dz
					local nk = nx..","..nz
					if inBounds(nx,nz,w,h) and occupied[nx][nz] and not visited[nk] then
						visited[nk]=true
						table.insert(queue, {x=nx, z=nz})
					end
				end
			end

			local removed = 0
			for x=1,w do for z=1,h do
					if occupied[x][z] and not visited[x..","..z] then
						occupied[x][z] = nil
						nodeCount -= 1
						removed += 1
					end
				end end
			if removed>0 then
				warn(string.format("[MapGen] [%s] Graph validation removed %d orphan nodes", zoneName, removed))
			else
				print(string.format("[MapGen] [%s] Graph valid — %d nodes all connected ✅", zoneName, nodeCount))
			end
		end
	end

	-- ================================================================
	--  PHASE 3 — PLACE ROOMS IN THE WORLD
	-- ================================================================
	print(string.format("[MapGen] [%s] Phase 3: placing %d rooms in world", zoneName, nodeCount))
	local roomsPlaced = 0

	local nodeList = {}
	for x=1,w do for z=1,h do
			if occupied[x][z] then table.insert(nodeList, occupied[x][z]) end
		end end
	table.sort(nodeList, function(a,b)
		local order = {checkpoint_anchor=1, anchor=2, spine=3, filler=4, deadend=5}
		return (order[a.kind] or 9) < (order[b.kind] or 9)
	end)

	for _,node in ipairs(nodeList) do
		local x, z   = node.x, node.z
		local tName  = tileName(x, z)
		local tPos   = tilePositions[tName]
		if not tPos then continue end

		-- Checkpoint anchors use their required direction
		local dirList
		if node.kind == "checkpoint_anchor" then
			dirList = {node.requiredDirection}
			print(string.format("[MapGen] [%s] Placing checkpoint pair #%d at %s facing %s", 
				zoneName, node.pairIndex or 0, tName, node.requiredDirection))
		else
			dirList = getConnDirs(x, z)
			if #dirList == 0 then
				warn(string.format("[MapGen] [%s] Node %s has no connections — skipping", zoneName, tName))
				continue
			end
		end

		local room = nil
		if (node.kind == "anchor" or node.kind == "checkpoint_anchor") and node.roomModel then
			room = node.roomModel
			-- For checkpoint, always use the model
			if node.kind ~= "checkpoint_anchor" then
				if not canRoomSatisfyDirs(room, dirList, worldAxis) then
					room = nil
				end
			end
		end

		if not room then
			local nc = math.clamp(#dirList,1,4)
			local candidates = {}
			if nc==2 then
				local sub = OPP[dirList[1]]==dirList[2] and "straight" or "turn"
				for _,r in ipairs(pool[sub] or {}) do
					if canSpawn(roomMeta,tracker,r.Name) and canRoomSatisfyDirs(r,dirList,worldAxis) then
						table.insert(candidates, r)
					end
				end
			else
				for _,r in ipairs(pool[nc] or {}) do
					if canSpawn(roomMeta,tracker,r.Name) and canRoomSatisfyDirs(r,dirList,worldAxis) then
						table.insert(candidates, r)
					end
				end
			end
			if #candidates==0 then
				local bucket = nc==2
					and pool[(OPP[dirList[1]]==dirList[2] and "straight" or "turn")]
					or  pool[nc]
				for _,r in ipairs(bucket or {}) do
					if canRoomSatisfyDirs(r,dirList,worldAxis) then
						table.insert(candidates,r) ; break
					end
				end
			end
			if #candidates==0 then
				warn(string.format("[MapGen] [%s] No room for %s (%d connectors: %s)",
					zoneName, tName, #dirList, table.concat(dirList,"+")))
				continue
			end

			local filtered = {}
			for _, r in ipairs(candidates) do
				if canSpawn(roomMeta, tracker, r.Name) then
					table.insert(filtered, r)
				end
			end
			if #filtered > 0 then candidates = filtered end

			room = candidates[rng:next(1,#candidates)]
		end

		local clone = room:Clone()
		clone.Name   = tName
		clone.Parent = zoneFolder
		local rot = getBestRotation(clone, dirList, worldAxis)
		local cf  = CFrame.new(tPos) * rot
		if clone.PrimaryPart then clone:SetPrimaryPartCFrame(cf) else clone:PivotTo(cf) end

		-- Track spawn (checkpoint gets tracked here)
		incSpawn(tracker, room.Name)

		node.clone   = clone
		node.dirList = dirList
		roomsPlaced += 1

		if room.Name == CHECKPOINT_ROOM_NAME then
			print(string.format("[MapGen] [%s] ✅ CHECKPOINT PAIR #%d PLACED at %s", 
				zoneName, node.pairIndex or 0, tName))
		end
	end

	-- ================================================================
	--  PHASE 4 — SEAL OPEN CONNECTORS WITH DEAD-ENDS
	-- ================================================================
	print(string.format("[MapGen] [%s] Phase 4: sealing open connectors", zoneName))
	do
		local deadEnds = pool[1] or {}
		local sealed   = 0
		local openSlots = {}

		for x=1,w do for z=1,h do
				local node = occupied[x][z]
				if node and node.dirList then
					local meta = roomMeta[node.roomName]
					if meta and meta.IsEndRoom == true then
						for _,dir in ipairs(node.dirList) do
							local d = dirByName(dir)
							if not d then continue end
							local nx,nz = x + d.dx, z + d.dz
							if inBounds(nx,nz,w,h)
								and not occupied[nx][nz]
								and tilePositions[tileName(nx,nz)] then
								table.insert(openSlots, {x=nx, z=nz, fromDir=OPP[dir]})
							end
						end
					end
				end
			end end

		for _,slot in ipairs(openSlots) do
			local sx,sz = slot.x, slot.z
			if occupied[sx][sz] then continue end
			local dirList = {slot.fromDir}
			for _,r in ipairs(deadEnds) do
				if canRoomSatisfyDirs(r, dirList, worldAxis) then
					local tName = tileName(sx,sz)
					local tPos  = tilePositions[tName]
					if not tPos then continue end
					local clone = r:Clone()
					clone.Name   = tName
					clone.Parent = zoneFolder
					local rot = getBestRotation(clone, dirList, worldAxis)
					local cf  = CFrame.new(tPos)*rot
					if clone.PrimaryPart then clone:SetPrimaryPartCFrame(cf) else clone:PivotTo(cf) end
					incSpawn(tracker, r.Name)
					occupied[sx][sz] = {x=sx,z=sz,kind="deadend",dirList=dirList,clone=clone}
					roomsPlaced += 1 ; sealed += 1
					break
				end
			end
		end

		if sealed>0 then
			print(string.format("[MapGen] [%s] Sealed %d open connectors", zoneName, sealed))
		end
	end

	-- ================================================================
	--  PHASE 5 — RECOVER MISSING REQUIRED ROOMS
	-- ================================================================
	local missing = getMissingRequired(roomMeta, tracker)

	if #missing > 0 then
		for _,m in ipairs(missing) do
			warn(string.format("[MapGen] [%s] ⚠ Missing required '%s' x%d — attempting recovery",
				zoneName, m.name, m.need))
		end

		local recovered = tryRecoverRequiredRooms(
			missing, occupied, modelByName, roomMeta,
			tracker, worldAxis, zoneFolder, tilePositions, w, h, rng
		)

		local stillMissing = getMissingRequired(roomMeta, tracker)
		if #stillMissing > 0 then
			for _, m in ipairs(stillMissing) do
				warn(string.format("[MapGen] [%s] ❌ STILL missing required '%s' x%d after recovery",
					zoneName, m.name, m.need))
			end
		else
			print(string.format("[MapGen] [%s] ✅ All required rooms satisfied after recovering %d",
				zoneName, recovered))
		end
	else
		print(string.format("[MapGen] [%s] ✅ All required rooms satisfied", zoneName))
	end

	-- ================================================================
	--  FINAL SPAWN REPORT
	-- ================================================================
	print(string.format("[MapGen] [%s] ══ SPAWN REPORT ══", zoneName))
	for name, count in pairs(tracker) do
		local meta = roomMeta[name]
		if meta then
			local maxInfo = meta.MaxCanGenerate == 0 and "unlimited" or tostring(meta.MaxCanGenerate)
			local reqInfo = meta.RoomRequired and string.format(" [REQUIRED x%d]", meta.RequiredAmountSpawn) or ""
			print(string.format("[MapGen] [%s]   %s: %d/%s%s", zoneName, name, count, maxInfo, reqInfo))
		else
			print(string.format("[MapGen] [%s]   %s: %d", zoneName, name, count))
		end
	end

	print(string.format("[MapGen] [%s] ✅ Complete — %d rooms placed", zoneName, roomsPlaced))

	return occupied, tilePositions, worldAxis, tracker, roomMeta, modelByName
end

-- ================================================================
--  MAIN
-- ================================================================
local ZONES             = {"LCZ","HCZ","EZ"}
local ZONE_SEED_OFFSETS = {LCZ=0, HCZ=100, EZ=200}

function MapGeneratorModule.generate(numericSeed)
	-- Reset checkpoint positions for new generation
	CHECKPOINT_POSITIONS.HCZ = {}
	CHECKPOINT_POSITIONS.EZ = {}

	local cfg = {
		GRID_WIDTH  = mapvalues:GetAttribute("GRID_WIDTH"),
		GRID_LENGTH = mapvalues:GetAttribute("GRID_LENGTH"),
		MIN_ROOMS   = mapvalues:GetAttribute("MIN_ROOMS"),
		MAX_ROOMS   = mapvalues:GetAttribute("MAX_ROOMS")
	}
	for _, key in ipairs({"GRID_WIDTH","GRID_LENGTH","MIN_ROOMS","MAX_ROOMS"}) do
		if type(cfg[key]) ~= "number" then
			error(string.format("[MapGen] cfg.%s is %s — check Studio attributes",
				key, type(cfg[key])), 2)
		end
	end
	print(string.format("[MapGen] ══ Seed: %d | Grid: %dx%d | Rooms: %d-%d ══",
		numericSeed, cfg.GRID_WIDTH, cfg.GRID_LENGTH, cfg.MIN_ROOMS, cfg.MAX_ROOMS))

	local w, h = cfg.GRID_WIDTH, cfg.GRID_LENGTH
	facilityFolder = nil

	-- Generate all zones IN ORDER (HCZ must come before EZ for checkpoint alignment)
	for _, zoneName in ipairs(ZONES) do
		local zoneSeed = numericSeed + ZONE_SEED_OFFSETS[zoneName]
		local zf       = getOrCreateZoneFolder(zoneName)
		generateZone(zoneName, zoneSeed, zf, w, h, cfg)
	end

	-- Verify checkpoint connection
	if #CHECKPOINT_POSITIONS.HCZ > 0 and #CHECKPOINT_POSITIONS.EZ > 0 then
		print("[MapGen] ══ CHECKPOINT PAIR VERIFICATION ══")

		for i, cp in ipairs(CHECKPOINT_POSITIONS.HCZ) do
			print(string.format("[MapGen] HCZ checkpoint pair #%d: %s", i, cp.tileName))
		end

		for i, cp in ipairs(CHECKPOINT_POSITIONS.EZ) do
			local paired = cp.pairedWith or "?"
			print(string.format("[MapGen] EZ checkpoint pair #%d: %s ↔ HCZ %s", i, cp.tileName, paired))
		end

		local totalOffset = 0
		local count = 0

		for i = 1, math.min(#CHECKPOINT_POSITIONS.HCZ, #CHECKPOINT_POSITIONS.EZ) do
			local hcz = CHECKPOINT_POSITIONS.HCZ[i]
			local ez  = CHECKPOINT_POSITIONS.EZ[i]

			local xDiff = math.abs(hcz.worldPos.X - ez.worldPos.X)
			totalOffset += xDiff
			count += 1

			print(string.format("[MapGen] Pair #%d X-offset: %.2f studs", i, xDiff))
		end

		if count > 0 then
			local avg = totalOffset / count
			print(string.format("[MapGen] Average X alignment offset: %.2f studs", avg))

			if avg < 10 then
				print("[MapGen] ✅ All checkpoint pairs well-aligned!")
			else
				warn("[MapGen] ⚠ Some checkpoint pairs may not align properly")
			end
		end

		print(string.format("[MapGen] ✅ Total: %d checkpoint rooms placed (%d HCZ + %d EZ = %d pairs)",
			#CHECKPOINT_POSITIONS.HCZ + #CHECKPOINT_POSITIONS.EZ,
			#CHECKPOINT_POSITIONS.HCZ,
			#CHECKPOINT_POSITIONS.EZ,
			count))
	else
		warn("[MapGen] ⚠ Checkpoint generation incomplete!")
	end

	print(string.format("[MapGen] ══ Complete | Seed: %d ══", numericSeed))

	-- Call External Functions
	DoorPlaceModule.ConstructFacilityDoors()
	ElevatorPlaceModule.ConstructFacilityElevators()
	PosterPlaceModule.ConstructFacilityPosters(numericSeed)
end

return MapGeneratorModule

It would be great if you guys could possilble provide script suggestions, point out bugs! Etc!

I sent a PM with a hopeful fix, kind of chopped up.. Too much to type all that out, cuz I’m sooo lazy..
That sure is a lot of love put into that script (impressive) .. good luck!

If you guys can post ur solution, code, or code write, it would help a lot!

  • it is unclear which glitch you are referring to
  • can you please show the DoorPlaceModule? kind of interested which approach you are using for pathway connections

suggestion:

  1. add third dimension to your A* implementation
  2. add adapter / compensator tiles (those which can resize to any size and satisfy any angle)

Ight! I want to say that DoorPlaceModule places door module,s it doesnt place connections, connections are pre built into room tiles and door place module simply places my door model at such door. The glitch in referring to is that the checkpoints generate! which is amazing! the thing is! as seen in the image, hallways generate in between! trying to connect into themm also, one checkpoint seems to be just not connect to both HCZ and EZ built zones, Causing islanding. To sum it up, A checkpoint seems to just get islanded and left out, and hallways generate going into the side of such checkpoints,

describe the following:

  • what are checkpoints
  • what is HCZ and EZ

also notice,

  • the script is 1.5k lines long
  • utility functions are not isolated
  • it is working, the issue is qualitative, not a functional one
  • it is a full-fledged ‘system’ with a function call hierarchy

therefore, not many people can debug it in less than several hours
you need to point at a specific location where you suppose the problem is

Checkpoints are special rooms that connect HCZ and EZ together, HCZ and EZ are two zones in my map that wll generate, both must generate connected, that is how the player gets around. I do apologize, but I am unable to point out a problem, as I myself cannot find the problem, if I foind the problem, I likely would have debugged it :frowning:

provide a minimal working .rbxl file with tiles (possibly reduced down to placeholders)
i will be checking it out the following days