Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- File: ServerScriptService/WeeklyCaveSystem.lua
- -- Weekly Regenerating Cave System with Neighbor Count Wall Ore Detection
- -- SERVER SCRIPT - COMPLETE FINAL VERSION WITH NEIGHBOR COUNT ORE SYSTEM
- -- PART 1: Header, Services, Core Classes, and Cave Generation
- local ReplicatedStorage = game:GetService("ReplicatedStorage")
- local DataStoreService = game:GetService("DataStoreService")
- local Players = game:GetService("Players")
- local RunService = game:GetService("RunService")
- local TweenService = game:GetService("TweenService")
- -- Data Storage
- local CaveDataStore = DataStoreService:GetDataStore("WeeklyCaveSystem")
- local CAVE_VERSION_KEY = "CaveWeek_"
- -- Cave System Manager with Instanced Dimensions
- local CaveSystem = {
- activeCaves = {},
- playerCaveInstances = {},
- currentWeek = 0,
- caveConfigs = {},
- playerReturnPositions = {},
- caveInstances = {}, -- Store cave dimension instances
- baseCavePosition = Vector3.new(0, 2000, 0), -- HIGH IN THE SKY for safety
- safetyZones = {} -- Track safety zones for each cave - SAFETY SYSTEM
- }
- -- ============================================================================
- -- NUCLEAR READONLY TABLE FIX
- -- ============================================================================
- local function FORCE_MUTABLE_TABLE(original)
- local fresh = {}
- if type(original) == "table" then
- for k, v in pairs(original) do
- fresh[k] = v
- end
- end
- return fresh
- end
- local function FORCE_SET_TABLE_VALUE(tbl, key, value)
- local success1 = pcall(function()
- tbl[key] = value
- end)
- if success1 then return tbl end
- local success2 = pcall(function()
- rawset(tbl, key, value)
- end)
- if success2 then return tbl end
- local fresh = {}
- for k, v in pairs(tbl) do
- fresh[k] = v
- end
- fresh[key] = value
- return fresh
- end
- local function cloneTable(t)
- if type(t) ~= "table" then return t end
- local copy = {}
- for i, v in pairs(t) do
- copy[i] = v
- end
- return copy
- end
- -- ============================================================================
- -- MINE CELL CLASS
- -- ============================================================================
- local MineCell = {}
- MineCell.__index = MineCell
- function MineCell.new(x, y)
- local self = {}
- for k, v in pairs(MineCell) do
- if type(v) == "function" then
- self[k] = v
- end
- end
- self.x = x
- self.y = y
- self.Visited = false
- self.isRoom = false
- self.availDirs = {}
- self.availDirs.N = true
- self.availDirs.E = true
- self.availDirs.S = true
- self.availDirs.W = true
- self.closeToRoom = false
- self.Door = false
- self.Filled = false
- self.isPath = false
- self.outRef = nil
- self.onlyDir = nil
- self.hasSupport = false
- self.hasLighting = false
- self.hasOre = false
- return self
- end
- function MineCell:GetUnvisitedNeighbors(mine)
- local neighbors = {}
- local map = mine.Map
- local sX, sY = mine.sX, mine.sY
- local directions = {
- {dir = "N", dx = 0, dy = 1},
- {dir = "S", dx = 0, dy = -1},
- {dir = "E", dx = 1, dy = 0},
- {dir = "W", dx = -1, dy = 0}
- }
- for _, dirInfo in ipairs(directions) do
- local nx = self.x + dirInfo.dx
- local ny = self.y + dirInfo.dy
- if nx >= 1 and nx <= sX and ny >= 1 and ny <= sY then
- local neighbor = map[nx][ny]
- if not neighbor.Visited and not neighbor.isRoom and self.availDirs[dirInfo.dir] then
- table.insert(neighbors, {
- Dir = dirInfo.dir,
- Cell = neighbor
- })
- end
- end
- end
- return neighbors
- end
- function MineCell:GetNonRoomNeighbors(mine)
- local neighbors = {}
- local map = mine.Map
- local sX, sY = mine.sX, mine.sY
- local directions = {
- {dir = "N", dx = 0, dy = 1},
- {dir = "S", dx = 0, dy = -1},
- {dir = "E", dx = 1, dy = 0},
- {dir = "W", dx = -1, dy = 0}
- }
- for _, dirInfo in ipairs(directions) do
- local nx = self.x + dirInfo.dx
- local ny = self.y + dirInfo.dy
- if nx >= 1 and nx <= sX and ny >= 1 and ny <= sY then
- local neighbor = map[nx][ny]
- if self.availDirs[dirInfo.dir] then
- table.insert(neighbors, {
- Dir = dirInfo.dir,
- Cell = neighbor
- })
- end
- end
- end
- return neighbors
- end
- function MineCell:getCellOfDirection(map, direction)
- local dx, dy = 0, 0
- if direction == "N" then dy = 1
- elseif direction == "S" then dy = -1
- elseif direction == "E" then dx = 1
- elseif direction == "W" then dx = -1
- end
- local nx, ny = self.x + dx, self.y + dy
- return map[nx] and map[nx][ny]
- end
- function MineCell:DelInBetween(otherCell, direction)
- self.availDirs = FORCE_SET_TABLE_VALUE(self.availDirs, direction, true)
- local oppositeDir = {N = "S", S = "N", E = "W", W = "E"}
- if otherCell and otherCell.availDirs then
- local oppDir = oppositeDir[direction]
- if oppDir then
- otherCell.availDirs = FORCE_SET_TABLE_VALUE(otherCell.availDirs, oppDir, true)
- end
- end
- end
- -- ============================================================================
- -- MINE CLASS
- -- ============================================================================
- local Mine = {}
- Mine.__index = Mine
- function Mine.new(sizeX, sizeY)
- if sizeX < 1 or sizeY < 1 then
- return nil
- end
- local self = {}
- for k, v in pairs(Mine) do
- if type(v) == "function" then
- self[k] = v
- end
- end
- self.Map = {}
- self.sX = sizeX
- self.sY = sizeY
- self.unfixedCells = {}
- for x = 1, sizeX do
- self.Map[x] = {}
- for y = 1, sizeY do
- self.Map[x][y] = MineCell.new(x, y)
- end
- end
- return self
- end
- function Mine:RecursiveBacktracker()
- print("โ๏ธ Running recursive backtracker maze algorithm...")
- self.unfixedCells = {}
- local uCells = self.unfixedCells
- local sX, sY = self.sX, self.sY
- local Map = self.Map
- for i = 1, sX do
- for j = 1, sY do
- local cell = Map[i][j]
- if not cell.isRoom then
- table.insert(uCells, cell)
- end
- end
- end
- while #uCells > 0 do
- local curCell = uCells[#uCells]
- curCell.Visited = true
- local neighbors = curCell:GetUnvisitedNeighbors(self)
- if #neighbors > 0 then
- local pickedNeighbor = neighbors[math.random(1, #neighbors)]
- local relDir, oCell = pickedNeighbor.Dir, pickedNeighbor.Cell
- curCell:DelInBetween(oCell, relDir)
- table.insert(uCells, oCell)
- else
- table.remove(uCells)
- end
- end
- print("โ๏ธ Maze algorithm completed")
- end
- function Mine:wipeFilled()
- for x = 1, self.sX do
- for y = 1, self.sY do
- self.Map[x][y].Filled = false
- end
- end
- end
- function Mine.Search(mine, origCell)
- mine:wipeFilled()
- local cPath = nil
- local function Search(startCell, startPath)
- local searchQueue = {{cell = startCell, path = startPath}}
- local processed = {}
- local maxIterations = 10000
- local iterations = 0
- while #searchQueue > 0 and iterations < maxIterations do
- iterations = iterations + 1
- local batchSize = 50
- local currentBatch = 0
- while #searchQueue > 0 and currentBatch < batchSize do
- currentBatch = currentBatch + 1
- local current = table.remove(searchQueue, 1)
- local tCell = current.cell
- local Path = current.path
- local cellKey = tCell.x .. "," .. tCell.y
- if processed[cellKey] then
- continue
- end
- processed[cellKey] = true
- if tCell.isRoom then
- if tCell.outRef ~= origCell.outRef then
- continue
- end
- end
- local newPath = {}
- for i, v in ipairs(Path) do
- newPath[i] = v
- end
- table.insert(newPath, tCell)
- tCell.Filled = true
- if tCell.isRoom then
- continue
- end
- local neighbors = tCell:GetNonRoomNeighbors(mine)
- for _, v in ipairs(neighbors) do
- local relDir, cell = v.Dir, v.Cell
- if cell.Door and origCell.outRef ~= cell.outRef then
- table.insert(newPath, cell)
- cPath = newPath
- return
- end
- end
- if not cPath then
- for _, v in ipairs(neighbors) do
- local cell = v.Cell
- local neighborKey = cell.x .. "," .. cell.y
- if not processed[neighborKey] and (not cell.Filled or cell.isPath) then
- table.insert(searchQueue, {cell = cell, path = newPath})
- end
- end
- end
- end
- if iterations % 100 == 0 then
- wait()
- end
- end
- if iterations >= maxIterations then
- warn("โ ๏ธ Search iteration limit reached, may have incomplete pathfinding")
- end
- end
- local look = origCell.Door
- local lookCell = origCell:getCellOfDirection(mine.Map, look)
- if lookCell then
- Search(lookCell, {origCell})
- end
- if cPath then
- for _, v in ipairs(cPath) do
- v.isPath = true
- end
- end
- end
- function Mine:searchForDoor(house)
- local doors = house.Doors
- local oppDir = {W = "E", E = "W", S = "N", N = "S"}
- for _, v in ipairs(doors) do
- if not v.Filled then
- Mine.Search(self, v)
- end
- end
- for _, v in ipairs(doors) do
- if not v.isPath then
- local look = v.Door
- local lookCell = v:getCellOfDirection(self.Map, look)
- if v.availDirs then
- v.availDirs = FORCE_SET_TABLE_VALUE(v.availDirs, look, true)
- end
- if lookCell and lookCell.availDirs then
- lookCell.availDirs = FORCE_SET_TABLE_VALUE(lookCell.availDirs, oppDir[look], true)
- end
- end
- end
- end
- -- ============================================================================
- -- MINE ROOM CLASS WITH NEIGHBOR COUNT ORE GENERATION
- -- ============================================================================
- local MineRoom = {}
- MineRoom.__index = MineRoom
- function MineRoom.new(mine, x1, y1, x2, y2)
- local self = {}
- for k, v in pairs(MineRoom) do
- if type(v) == "function" then
- self[k] = v
- end
- end
- local sX = mine.sX
- local sY = mine.sY
- local roomBorderSpace = 2
- self.ref = mine
- self.tl = {x = x1, y = y1}
- self.br = {x = x2, y = y2}
- self.Outsiders = {}
- self.OrePositions = {} -- Store ore positions for this room
- local Map = mine.Map
- for x = math.max(1, x1 - roomBorderSpace), math.min(x2 + roomBorderSpace, sX) do
- for y = math.max(1, y1 - roomBorderSpace), math.min(y2 + roomBorderSpace, sY) do
- local cell = Map[x][y]
- if not (x < x1 or y < y1 or x > x2 or y > y2) then
- cell.Visited = true
- cell.isRoom = true
- cell.hasLighting = true
- cell.availDirs = {}
- cell.availDirs.N = true
- cell.availDirs.E = true
- cell.availDirs.S = true
- cell.availDirs.W = true
- if x ~= x1 then cell.availDirs.W = nil end
- if x ~= x2 then cell.availDirs.E = nil end
- if y ~= y1 then cell.availDirs.S = nil end
- if y ~= y2 then cell.availDirs.N = nil end
- end
- cell.closeToRoom = true
- if x >= 1 and y >= 1 and x <= sX and y <= sY then
- if x > 1 and y > 1 and x < sX and y < sY then
- local isOutsider = (x == x1 and y >= y1 and y <= y2) or
- (y == y1 and x >= x1 and x <= x2) or
- (x == x2 and y >= y1 and y <= y2) or
- (y == y2 and x >= x1 and x <= x2)
- if isOutsider then
- table.insert(self.Outsiders, cell)
- cell.outRef = self
- end
- end
- end
- end
- end
- -- NEW: Generate ore positions during room creation using neighbor count
- self:GenerateRoomOres(mine)
- return self
- end
- -- NEW: Generate ores during room creation using neighbor count logic - RANDOMIZED
- function MineRoom:GenerateRoomOres(mine)
- print("โ๏ธ Generating ores for room at", self.tl.x, self.tl.y, "to", self.br.x, self.br.y)
- -- Get room dimensions
- local roomWidth = self.br.x - self.tl.x + 1
- local roomHeight = self.br.y - self.tl.y + 1
- print("๐ Room dimensions:", roomWidth, "x", roomHeight)
- -- Use current time + room position for unique randomization each visit
- local uniqueSeed = os.time() + self.tl.x * 1000 + self.tl.y * 100
- math.randomseed(uniqueSeed)
- -- Loop through ALL cells in the room
- for x = self.tl.x, self.br.x do
- for y = self.tl.y, self.br.y do
- -- 15% chance of creating ore vein (increased from 10% for more ores)
- if math.random() < 0.15 then
- -- Check if this is a valid wall cell for ore placement
- if self:IsValidOreWallCell(mine, x, y) then
- -- Get the direction this wall faces
- local wallDirection = self:GetWallDirection(mine, x, y)
- local neighborCount = self:CountRoomNeighbors(mine, x, y)
- if wallDirection then
- -- Store ore position with grid coordinates and direction info
- local oreData = {
- gridX = x,
- gridY = y,
- direction = wallDirection,
- neighborCount = neighborCount,
- roomWidth = roomWidth,
- roomHeight = roomHeight,
- randomSeed = uniqueSeed, -- Store seed for debugging
- spawnTime = os.time() -- Store when this was generated
- }
- table.insert(self.OrePositions, oreData)
- print("โ๏ธ Planned ore at grid", x, y, "direction:", wallDirection, "neighbors:", neighborCount, "seed:", uniqueSeed)
- end
- end
- end
- end
- end
- print("โ๏ธ Planned", #self.OrePositions, "RANDOMIZED ore veins for this room")
- end
- -- NEW: Check if a cell is a valid wall cell for ore placement
- function MineRoom:IsValidOreWallCell(mine, gridX, gridY)
- -- Must be within room bounds
- if gridX < self.tl.x or gridX > self.br.x or gridY < self.tl.y or gridY > self.br.y then
- return false
- end
- local neighborCount = self:CountRoomNeighbors(mine, gridX, gridY)
- -- Only cells with 2 or 3 room neighbors are wall cells
- if neighborCount ~= 2 and neighborCount ~= 3 then
- return false
- end
- -- Check that adjacent non-room cells are NOT corridors/paths
- local directions = {
- {dx = 0, dy = 1}, -- North
- {dx = 0, dy = -1}, -- South
- {dx = 1, dy = 0}, -- East
- {dx = -1, dy = 0} -- West
- }
- for _, dir in ipairs(directions) do
- local checkX = gridX + dir.dx
- local checkY = gridY + dir.dy
- -- If this direction is outside room bounds, check what's there
- if checkX < self.tl.x or checkX > self.br.x or checkY < self.tl.y or checkY > self.br.y then
- -- Check if the adjacent cell is a corridor/path
- if checkX >= 1 and checkX <= mine.sX and checkY >= 1 and checkY <= mine.sY then
- local adjacentCell = mine.Map[checkX][checkY]
- -- If adjacent cell is a path/corridor, this is not a valid wall for ores
- if adjacentCell.isPath then
- print("๐ซ Skipping ore at", gridX, gridY, "- adjacent to corridor at", checkX, checkY)
- return false
- end
- end
- end
- end
- return true
- end
- -- NEW: Count room neighbors for a grid cell
- function MineRoom:CountRoomNeighbors(mine, gridX, gridY)
- local count = 0
- -- Check all 4 cardinal directions
- local directions = {
- {dx = 0, dy = 1}, -- North
- {dx = 0, dy = -1}, -- South
- {dx = 1, dy = 0}, -- East
- {dx = -1, dy = 0} -- West
- }
- for _, dir in ipairs(directions) do
- local checkX = gridX + dir.dx
- local checkY = gridY + dir.dy
- -- Check if neighbor is within room bounds
- if checkX >= self.tl.x and checkX <= self.br.x and
- checkY >= self.tl.y and checkY <= self.br.y then
- count = count + 1
- end
- end
- return count
- end
- -- IMPROVED: Get wall direction based on which neighbors are missing (more accurate)
- function MineRoom:GetWallDirection(mine, gridX, gridY)
- -- Check which directions DON'T have room neighbors
- local missingDirections = {}
- local solidDirections = {} -- Directions facing solid walls (not corridors)
- local directions = {
- {name = "north", dx = 0, dy = 1},
- {name = "south", dx = 0, dy = -1},
- {name = "east", dx = 1, dy = 0},
- {name = "west", dx = -1, dy = 0}
- }
- for _, dir in ipairs(directions) do
- local checkX = gridX + dir.dx
- local checkY = gridY + dir.dy
- -- If neighbor is outside room bounds, this direction faces outward
- if checkX < self.tl.x or checkX > self.br.x or
- checkY < self.tl.y or checkY > self.br.y then
- table.insert(missingDirections, dir.name)
- -- Check if this direction faces a solid wall (not a corridor)
- if checkX >= 1 and checkX <= mine.sX and checkY >= 1 and checkY <= mine.sY then
- local adjacentCell = mine.Map[checkX][checkY]
- -- If adjacent cell is NOT a path/corridor, it's a solid wall
- if not adjacentCell.isPath and not adjacentCell.isRoom then
- table.insert(solidDirections, dir.name)
- end
- else
- -- Outside mine bounds = solid wall
- table.insert(solidDirections, dir.name)
- end
- end
- end
- -- Prefer directions that face solid walls over corridors
- if #solidDirections > 0 then
- return solidDirections[1]
- elseif #missingDirections > 0 then
- return missingDirections[1]
- end
- return nil
- end
- -- ============================================================================
- -- MINE HOUSE CLASS
- -- ============================================================================
- local MineHouse = {}
- MineHouse.__index = MineHouse
- function MineHouse.new(mine)
- local self = {}
- for k, v in pairs(MineHouse) do
- if type(v) == "function" then
- self[k] = v
- end
- end
- self.Mine = mine
- self.Rooms = {}
- self.Doors = {}
- return self
- end
- function MineHouse:add(x1, y1, x2, y2)
- table.insert(self.Rooms, MineRoom.new(self.Mine, x1, y1, x2, y2))
- end
- function MineHouse:tryRoom()
- local maxTries = 100
- local maxRooms = 8
- local minRoomSize = {x = 4, y = 4}
- local maxRoomSize = {x = 10, y = 10}
- local borderSpace = 5
- if #self.Rooms >= maxRooms then
- return false
- end
- for attempt = 1, maxTries do
- local roomWidth = math.random(minRoomSize.x, maxRoomSize.x)
- local roomHeight = math.random(minRoomSize.y, maxRoomSize.y)
- local x1 = math.random(borderSpace, self.Mine.sX - roomWidth - borderSpace)
- local y1 = math.random(borderSpace, self.Mine.sY - roomHeight - borderSpace)
- local x2 = x1 + roomWidth - 1
- local y2 = y1 + roomHeight - 1
- local canPlace = true
- for x = math.max(1, x1 - borderSpace), math.min(self.Mine.sX, x2 + borderSpace) do
- for y = math.max(1, y1 - borderSpace), math.min(self.Mine.sY, y2 + borderSpace) do
- if self.Mine.Map[x][y].isRoom then
- canPlace = false
- break
- end
- end
- if not canPlace then break end
- end
- if canPlace then
- self:add(x1, y1, x2, y2)
- print("๐๏ธ Created mine room", #self.Rooms, "at", x1, y1, "size", roomWidth, "x", roomHeight)
- return true
- end
- end
- return false
- end
- -- ============================================================================
- -- WEEKLY CAVE GENERATION
- -- ============================================================================
- function CaveSystem:GetCurrentWeek()
- local secondsSinceEpoch = os.time()
- local daysSinceEpoch = math.floor(secondsSinceEpoch / 86400)
- return math.floor(daysSinceEpoch / 7)
- end
- function CaveSystem:ShouldRegenerateCaves()
- local currentWeek = self:GetCurrentWeek()
- if self.currentWeek ~= currentWeek then
- print("๐ New week detected:", currentWeek, "vs stored:", self.currentWeek)
- return true
- end
- return false
- end
- function CaveSystem:GenerateWeeklyCaves()
- local currentWeek = self:GetCurrentWeek()
- print("๐๏ธ Generating caves for week", currentWeek)
- self:ClearAllCaves()
- local caveConfigs = {}
- local caveTypes = {"Crystal", "Underground", "Lava", "Ice", "Ancient"}
- for i = 1, #caveTypes do
- local caveConfig = self:GenerateCaveConfig(caveTypes[i], currentWeek + i)
- caveConfigs[caveTypes[i]] = caveConfig
- print("โก Generated", caveTypes[i], "cave config")
- end
- self.currentWeek = currentWeek
- self.caveConfigs = caveConfigs
- print("โ Cave configurations ready for week", currentWeek)
- return caveConfigs
- end
- function CaveSystem:GetCaveTypeProperties(caveType)
- local properties = {
- Crystal = {
- basePosition = {x = 1000, y = 2000, z = 1000},
- instanceOffset = Vector3.new(0, 0, 0),
- wallMaterial = "Rock",
- wallColor = {r = 0.4, g = 0.5, b = 0.6},
- floorMaterial = "Cobblestone",
- infrastructure = {
- lights = true,
- cables = true,
- woodenSupports = true,
- railTracks = false
- },
- lighting = {brightness = 1.0, color = {r = 0.6, g = 0.7, b = 0.9}, range = 18},
- corridorWidth = 16,
- corridorHeight = 16,
- roomSize = {min = 30, max = 60}
- },
- Underground = {
- basePosition = {x = 1200, y = 2000, z = 800},
- instanceOffset = Vector3.new(1000, 0, 0),
- wallMaterial = "Rock",
- wallColor = {r = 0.4, g = 0.35, b = 0.3},
- floorMaterial = "Concrete",
- infrastructure = {
- lights = true,
- cables = true,
- woodenSupports = true,
- railTracks = true
- },
- lighting = {brightness = 0.8, color = {r = 1, g = 0.8, b = 0.6}, range = 15},
- corridorWidth = 18,
- corridorHeight = 18,
- roomSize = {min = 40, max = 80}
- },
- Lava = {
- basePosition = {x = 800, y = 2000, z = 1200},
- instanceOffset = Vector3.new(2000, 0, 0),
- wallMaterial = "Rock",
- wallColor = {r = 0.6, g = 0.2, b = 0.1},
- floorMaterial = "Basalt",
- infrastructure = {
- lights = true,
- cables = true,
- woodenSupports = false,
- metalSupports = true,
- railTracks = false
- },
- lighting = {brightness = 1.2, color = {r = 1, g = 0.5, b = 0.2}, range = 20},
- corridorWidth = 20,
- corridorHeight = 20,
- roomSize = {min = 35, max = 70}
- },
- Ice = {
- basePosition = {x = 600, y = 2000, z = 600},
- instanceOffset = Vector3.new(0, 0, 1000),
- wallMaterial = "Ice",
- wallColor = {r = 0.6, g = 0.7, b = 0.8},
- floorMaterial = "Glacier",
- infrastructure = {
- lights = true,
- cables = true,
- woodenSupports = false,
- iceSupports = true,
- railTracks = false
- },
- lighting = {brightness = 0.7, color = {r = 0.7, g = 0.8, b = 1}, range = 12},
- corridorWidth = 12,
- corridorHeight = 16,
- roomSize = {min = 25, max = 50}
- },
- Ancient = {
- basePosition = {x = 1400, y = 2000, z = 1400},
- instanceOffset = Vector3.new(1000, 0, 1000),
- wallMaterial = "Cobblestone",
- wallColor = {r = 0.3, g = 0.28, b = 0.25},
- floorMaterial = "Marble",
- infrastructure = {
- lights = false,
- magicalLights = true,
- cables = false,
- stonePillars = true,
- railTracks = false
- },
- lighting = {brightness = 0.6, color = {r = 0.5, g = 0.7, b = 0.5}, range = 10},
- corridorWidth = 22,
- corridorHeight = 24,
- roomSize = {min = 50, max = 100}
- }
- }
- return properties[caveType] or properties.Underground
- end
- function CaveSystem:GenerateCaveConfig(caveType, seed)
- math.randomseed(seed)
- local properties = self:GetCaveTypeProperties(caveType)
- local config = {
- type = caveType,
- seed = seed,
- properties = properties,
- centerPosition = Vector3.new(
- properties.basePosition.x,
- properties.basePosition.y,
- properties.basePosition.z
- ),
- size = Vector3.new(400, 160, 400),
- portalPosition = Vector3.new(
- properties.basePosition.x,
- properties.basePosition.y + 30,
- properties.basePosition.z
- ),
- hiddenPassages = self:GenerateHiddenPassages(seed, properties),
- generatedAt = os.time()
- }
- return config
- end
- function CaveSystem:GenerateHiddenPassages(seed, properties)
- math.randomseed(seed)
- local passages = {}
- local numPassages = math.random(4, 8)
- for i = 1, numPassages do
- local passage = {
- id = "passage_" .. i,
- position = Vector3.new(
- properties.basePosition.x + (math.random() - 0.5) * 300,
- properties.basePosition.y + math.random(-30, 30),
- properties.basePosition.z + (math.random() - 0.5) * 300
- ),
- crackSize = Vector3.new(math.random(8, 16), math.random(12, 20), 2),
- leadsTo = {
- position = Vector3.new(
- properties.basePosition.x + (math.random() - 0.5) * 200,
- properties.basePosition.y - math.random(20, 60),
- properties.basePosition.z + (math.random() - 0.5) * 200
- ),
- size = Vector3.new(math.random(40, 80), math.random(25, 50), math.random(40, 80)),
- lootSpawns = math.random(3, 8),
- difficulty = math.random(1, 3)
- },
- requiredTool = "CaveDetector",
- broken = false
- }
- table.insert(passages, passage)
- end
- return passages
- end
- -- ============================================================================
- -- CAVE SAFETY SYSTEM - PREVENT ALL DEATHS
- -- ============================================================================
- function CaveSystem:CreateSafeSpawnZone(caveInstance)
- local config = caveInstance.config
- local folder = caveInstance.folder
- local player = caveInstance.player
- local spawnPos = caveInstance.playerSpawnPosition or Vector3.new(config.centerPosition.X, config.centerPosition.Y - 5, config.centerPosition.Z)
- print("๐ก๏ธ Creating floor-level safety zone at:", spawnPos)
- local safetyPlatform = Instance.new("Part")
- safetyPlatform.Name = "SafetyPlatform_" .. player.Name
- safetyPlatform.Size = Vector3.new(100, 1, 100)
- safetyPlatform.Position = Vector3.new(spawnPos.X, spawnPos.Y - 2, spawnPos.Z)
- safetyPlatform.Material = Enum.Material.ForceField
- safetyPlatform.Transparency = 1
- safetyPlatform.CanCollide = true
- safetyPlatform.Anchored = true
- safetyPlatform.Parent = folder
- local killZoneDetector = Instance.new("Part")
- killZoneDetector.Name = "KillZoneDetector_" .. player.Name
- killZoneDetector.Size = Vector3.new(1000, 10, 1000)
- killZoneDetector.Position = Vector3.new(spawnPos.X, spawnPos.Y - 30, spawnPos.Z)
- killZoneDetector.Transparency = 1
- killZoneDetector.CanCollide = false
- killZoneDetector.Anchored = true
- killZoneDetector.Parent = folder
- killZoneDetector.Touched:Connect(function(hit)
- local character = hit.Parent
- if character == player.Character and character:FindFirstChild("HumanoidRootPart") then
- character.HumanoidRootPart.CFrame = CFrame.new(spawnPos)
- local humanoid = character:FindFirstChild("Humanoid")
- if humanoid then
- humanoid.Health = humanoid.MaxHealth
- end
- if _G.ShowToast then
- _G.ShowToast("๐ก๏ธ Returned to cave floor", "Warning")
- end
- end
- end)
- if not self.safetyZones[player] then
- self.safetyZones[player] = {}
- end
- self.safetyZones[player][caveInstance.config.type] = {
- platform = safetyPlatform,
- detector = killZoneDetector,
- safeSpawn = spawnPos
- }
- print("๐ก๏ธ Created floor-level safety zone for", player.Name, "at", spawnPos)
- end
- function CaveSystem:ApplyCaveSafetyMode(player, caveInstance)
- if not player.Character then return end
- local humanoid = player.Character:FindFirstChild("Humanoid")
- if not humanoid then return end
- local safetySystem = {
- player = player,
- caveType = caveInstance.config.type,
- originalHealth = humanoid.MaxHealth,
- isActive = true
- }
- local damageConnection = humanoid.HealthChanged:Connect(function(health)
- if safetySystem.isActive and health < humanoid.MaxHealth then
- humanoid.Health = humanoid.MaxHealth
- end
- end)
- local deathConnection = humanoid.Died:Connect(function()
- if safetySystem.isActive then
- wait(0.1)
- if player.Character and caveInstance.playerSpawnPosition then
- local newCharacter = player.Character
- if newCharacter:FindFirstChild("HumanoidRootPart") then
- newCharacter.HumanoidRootPart.CFrame = CFrame.new(caveInstance.playerSpawnPosition)
- end
- local newHumanoid = newCharacter:FindFirstChild("Humanoid")
- if newHumanoid then
- newHumanoid.Health = newHumanoid.MaxHealth
- end
- if _G.ShowToast then
- _G.ShowToast("๐ก๏ธ Cave safety mode - death prevented!", "Success")
- end
- end
- end
- end)
- local healthMonitor = game:GetService("RunService").Heartbeat:Connect(function()
- if safetySystem.isActive and player.Character then
- local currentHumanoid = player.Character:FindFirstChild("Humanoid")
- if currentHumanoid and currentHumanoid.Health < currentHumanoid.MaxHealth then
- currentHumanoid.Health = currentHumanoid.MaxHealth
- end
- end
- end)
- safetySystem.connections = {damageConnection, deathConnection, healthMonitor}
- caveInstance.safetySystem = safetySystem
- print("๐ก๏ธ Cave safety mode activated for", player.Name, "- death disabled")
- end
- function CaveSystem:RemoveCaveSafetyMode(player, caveType)
- if self.safetyZones[player] and self.safetyZones[player][caveType] then
- local safetyZone = self.safetyZones[player][caveType]
- if safetyZone.platform then safetyZone.platform:Destroy() end
- if safetyZone.detector then safetyZone.detector:Destroy() end
- self.safetyZones[player][caveType] = nil
- end
- if self.playerCaveInstances[player] then
- for caveName, instance in pairs(self.playerCaveInstances[player]) do
- if instance.safetySystem then
- instance.safetySystem.isActive = false
- for _, connection in pairs(instance.safetySystem.connections) do
- connection:Disconnect()
- end
- instance.safetySystem = nil
- end
- end
- end
- print("๐ก๏ธ Cave safety mode deactivated for", player.Name)
- end
- -- ============================================================================
- -- CAVE INSTANCE CREATION
- -- ============================================================================
- function CaveSystem:CreateCaveInstance(caveType, player)
- local config = self.caveConfigs[caveType]
- if not config then
- warn("โ Cave config not found for type:", caveType)
- return nil
- end
- print("๐๏ธ Creating instanced cave dimension for", player.Name, "- Type:", caveType)
- local caveFolder = Instance.new("Folder")
- caveFolder.Name = player.Name .. "_" .. caveType .. "_CaveDimension"
- caveFolder.Parent = workspace
- local properties = self:GetCaveTypeProperties(caveType)
- local instanceOffset = properties.instanceOffset or Vector3.new(0, 0, 0)
- local instancePosition = self.baseCavePosition + instanceOffset
- config.centerPosition = instancePosition
- config.portalPosition = instancePosition + Vector3.new(0, 30, 0)
- config.player = player -- ADD PLAYER REFERENCE for ore creation
- local caveInstance = {
- folder = caveFolder,
- config = config,
- player = player,
- hiddenPassages = self:CloneHiddenPassages(config.hiddenPassages, player),
- isInstancedDimension = true,
- instancePosition = instancePosition,
- originalReturnPosition = nil,
- safetySystem = nil
- }
- self:GenerateInstancedCave(caveInstance)
- self:CreateReturnPortal(caveInstance)
- self:AddMiningInfrastructure(caveInstance)
- self:CreateHiddenWalls(caveInstance)
- self:AddCaveAtmosphere(caveInstance)
- -- CLEANUP: Now run cleanup AFTER everything is fully generated
- print("โณ Waiting for terrain/ore generation to settle...")
- wait(1) -- Give terrain carving time to complete
- self:CleanupFloatingOres(caveInstance)
- if not self.playerCaveInstances[player] then
- self.playerCaveInstances[player] = {}
- end
- self.playerCaveInstances[player][caveType] = caveInstance
- print("โ Safe instanced cave dimension created for", player.Name, "at", instancePosition)
- return caveInstance
- end
- function CaveSystem:GenerateInstancedCave(caveInstance)
- local config = caveInstance.config
- print("๐ Generating instanced cave dimension...")
- self:CreateInstanceTerrain(config)
- local mine = self:CreateDungeonStyleMine(config)
- caveInstance.mine = mine
- caveInstance.cellSize = 8
- print("๐๏ธ Instanced cave dimension completed")
- end
- function CaveSystem:CreateInstanceTerrain(config)
- local centerPos = config.centerPosition
- local terrainSize = Vector3.new(800, 200, 800)
- local rockRegion = Region3.new(
- centerPos - terrainSize/2,
- centerPos + terrainSize/2
- ):ExpandToGrid(4)
- workspace.Terrain:FillRegion(rockRegion, 4, Enum.Material.Rock)
- print("๐๏ธ Created massive instanced terrain formation at", centerPos, "size:", terrainSize)
- end
- function CaveSystem:CreateDungeonStyleMine(config)
- local mineSize = 50
- local mine = Mine.new(mineSize, mineSize)
- if not mine then
- error("Failed to create mine")
- end
- print("๐ Created", mineSize .. "x" .. mineSize, "mine grid")
- local house = MineHouse.new(mine)
- mine.House = house
- print("๐๏ธ Creating mine rooms...")
- for i = 1, 15 do
- house:tryRoom()
- end
- print("๐๏ธ Created", #house.Rooms, "mining chambers")
- mine:RecursiveBacktracker()
- self:CreateMineRoomOpenings(mine, house)
- mine:searchForDoor(house)
- self:CleanupNonPathCells(mine)
- self:CarvePhysicalMineFromGrid(mine, config)
- return mine
- end
- function CaveSystem:CreateMineRoomOpenings(mine, house)
- print("๐ช Creating room openings...")
- if #house.Rooms <= 1 then
- print("โ ๏ธ Need at least 2 rooms for openings")
- return
- end
- local maxDoors = 2
- local maxRetries = 10
- for _, room in ipairs(house.Rooms) do
- local outsiders = room.Outsiders
- local tries = 0
- for doorNum = 1, maxDoors do
- repeat
- if #outsiders == 0 then break end
- local candidate = outsiders[math.random(1, #outsiders)]
- if not candidate.Door then
- local dir = nil
- if candidate.onlyDir then
- dir = candidate.onlyDir
- else
- local availDirs = {}
- for direction, available in pairs(candidate.availDirs) do
- if available then
- table.insert(availDirs, direction)
- end
- end
- if #availDirs > 0 then
- dir = availDirs[math.random(1, #availDirs)]
- end
- end
- if dir then
- local opposite = candidate:getCellOfDirection(mine.Map, dir)
- if opposite then
- candidate:DelInBetween(opposite, dir)
- candidate.Door = dir
- table.insert(house.Doors, candidate)
- print("๐ช Created door at", candidate.x, candidate.y, "direction", dir)
- break
- end
- end
- end
- tries = tries + 1
- until tries >= maxRetries
- if tries >= maxRetries then
- break
- end
- end
- end
- print("๐ช Created", #house.Doors, "room openings")
- end
- function CaveSystem:CleanupNonPathCells(mine)
- print("๐งน Cleaning up non-path cells...")
- local sX, sY = mine.sX, mine.sY
- local Map = mine.Map
- local oppDir = {W = "E", E = "W", S = "N", N = "S"}
- for i = 1, sX do
- for j = 1, sY do
- local cell = Map[i][j]
- if not cell.isRoom and not cell.isPath then
- cell.availDirs = {}
- cell.availDirs.W = false
- cell.availDirs.E = false
- cell.availDirs.S = false
- cell.availDirs.N = false
- local neighbors = cell:GetNonRoomNeighbors(mine)
- for _, v in ipairs(neighbors) do
- local dir, oCell = v.Dir, v.Cell
- if oCell.isPath and oCell.availDirs then
- oCell.availDirs = FORCE_SET_TABLE_VALUE(oCell.availDirs, oppDir[dir], true)
- break
- end
- end
- end
- end
- end
- print("๐งน Cleanup completed")
- end
- -- ============================================================================
- -- NEIGHBOR COUNT ORE SYSTEM - USING TESTORE FROM MATERIALS FOLDER
- -- ============================================================================
- -- UPDATED: Physical mine carving that creates ores from room neighbor count data
- function CaveSystem:CarvePhysicalMineFromGrid(mine, config)
- print("โ๏ธ Carving physical mine from grid with NEIGHBOR COUNT ores...")
- local cellSize = 8
- local centerPos = config.centerPosition
- local startX = centerPos.X - (mine.sX * cellSize / 2)
- local startZ = centerPos.Z - (mine.sY * cellSize / 2)
- local mineY = centerPos.Y
- -- First pass: Carve all spaces
- for x = 1, mine.sX do
- for y = 1, mine.sY do
- local cell = mine.Map[x][y]
- if cell.isRoom or cell.isPath then
- local worldX = startX + (x - 0.5) * cellSize
- local worldZ = startZ + (y - 0.5) * cellSize
- local worldPos = Vector3.new(worldX, mineY, worldZ)
- if cell.isRoom then
- self:CarveRoomSpace(worldPos, cellSize * 1.2, 16)
- cell.hasLighting = true
- cell.hasSupport = true
- else
- self:CarveTunnelSpace(worldPos, cellSize * 0.9, 12)
- local connectionCount = 0
- for dir, available in pairs(cell.availDirs) do
- if available then connectionCount = connectionCount + 1 end
- end
- if connectionCount >= 3 then
- cell.hasLighting = true
- cell.hasSupport = true
- elseif connectionCount == 1 then
- cell.hasOre = true
- end
- end
- end
- end
- end
- -- Second pass: Create ores from room neighbor count data using TestOre
- if mine.House and mine.House.Rooms then
- for _, room in ipairs(mine.House.Rooms) do
- for _, oreData in ipairs(room.OrePositions) do
- self:CreateNeighborCountOre(oreData, startX, startZ, mineY, cellSize, config)
- end
- end
- end
- print("โ๏ธ Physical mine carved with NEIGHBOR COUNT TestOres")
- end
- function CaveSystem:CarveRoomSpace(worldPos, size, height)
- local roomSize = size * 1.5
- local region = Region3.new(
- Vector3.new(worldPos.X - roomSize/2, worldPos.Y - height/2, worldPos.Z - roomSize/2),
- Vector3.new(worldPos.X + roomSize/2, worldPos.Y + height/2, worldPos.Z + roomSize/2)
- ):ExpandToGrid(4)
- workspace.Terrain:FillRegion(region, 4, Enum.Material.Air)
- end
- function CaveSystem:CarveTunnelSpace(worldPos, size, height)
- local corridorSize = size * 2.5
- local region = Region3.new(
- Vector3.new(worldPos.X - corridorSize/2, worldPos.Y - height/2, worldPos.Z - corridorSize/2),
- Vector3.new(worldPos.X + corridorSize/2, worldPos.Y + height/2, worldPos.Z + corridorSize/2)
- ):ExpandToGrid(4)
- workspace.Terrain:FillRegion(region, 4, Enum.Material.Air)
- end
- -- NEW: Get position at wall edge using half grid size
- function CaveSystem:GetWallEdgePosition(gridCenter, direction, halfCellSize)
- local heightOffset = math.random(-2, 4) -- Random height variation
- -- CLOSER TO WALL: Use slightly more than half grid size to get closer to wall
- local wallDistance = halfCellSize + 3 -- INCREASED from halfCellSize to halfCellSize + 1.5
- -- Use the increased distance to position closer to the wall
- if direction == "north" then
- return Vector3.new(gridCenter.X, gridCenter.Y + heightOffset, gridCenter.Z + wallDistance)
- elseif direction == "south" then
- return Vector3.new(gridCenter.X, gridCenter.Y + heightOffset, gridCenter.Z - wallDistance)
- elseif direction == "east" then
- return Vector3.new(gridCenter.X + wallDistance, gridCenter.Y + heightOffset, gridCenter.Z)
- elseif direction == "west" then
- return Vector3.new(gridCenter.X - wallDistance, gridCenter.Y + heightOffset, gridCenter.Z)
- end
- return gridCenter
- end
- -- NEW: Create ore from neighbor count data using existing TestOre model
- function CaveSystem:CreateNeighborCountOre(oreData, startX, startZ, mineY, cellSize, config)
- local folder = workspace:FindFirstChild(config.player and (config.player.Name .. "_" .. config.type .. "_CaveDimension") or "TempCaveFolder")
- if not folder then
- folder = Instance.new("Folder")
- folder.Name = "CaveOres"
- folder.Parent = workspace
- end
- -- Try to find the TestOre from Materials folder
- local materialsFolder = workspace:FindFirstChild("Materials")
- local testOre = materialsFolder and materialsFolder:FindFirstChild("TestOre")
- if not testOre then
- warn("โ ๏ธ TestOre not found in Materials folder - creating fallback ore")
- self:CreateFallbackOre(oreData, startX, startZ, mineY, cellSize, config, folder)
- return
- end
- -- Calculate world position of the ore grid square CENTER
- local oreWorldX = startX + (oreData.gridX - 0.5) * cellSize
- local oreWorldZ = startZ + (oreData.gridY - 0.5) * cellSize
- local oreGridCenter = Vector3.new(oreWorldX, mineY, oreWorldZ)
- -- Use HALF the grid width/length to position ore at wall edge
- local halfCellSize = cellSize / 2
- local orePosition = self:GetWallEdgePosition(oreGridCenter, oreData.direction, halfCellSize)
- -- Clone the TestOre
- local ore = testOre:Clone()
- ore.Name = "CaveOre_" .. config.type .. "_" .. oreData.gridX .. "_" .. oreData.gridY
- ore.Parent = folder
- -- Handle positioning based on whether TestOre is a Model or Part
- if ore:IsA("Model") then
- -- TestOre is a Model - handle Union-based models properly
- local primaryPart = ore.PrimaryPart
- if not primaryPart then
- -- Try to find the Union part as primary
- for _, child in pairs(ore:GetChildren()) do
- if child:IsA("UnionOperation") or child:IsA("Part") then
- ore.PrimaryPart = child
- primaryPart = child
- break
- end
- end
- end
- if primaryPart then
- -- Rotate to face INTO the room (opposite of wall direction)
- local rotationCFrame = CFrame.new(Vector3.new(0, 0, 0))
- if oreData.direction == "north" then
- -- Wall faces north, ore should face south (into room)
- rotationCFrame = CFrame.Angles(0, math.rad(180), 0)
- elseif oreData.direction == "south" then
- -- Wall faces south, ore should face north (into room)
- rotationCFrame = CFrame.Angles(0, 0, 0)
- elseif oreData.direction == "east" then
- -- Wall faces east, ore should face west (into room) + 180ยฐ correction
- rotationCFrame = CFrame.Angles(0, math.rad(90 + 180), 0)
- elseif oreData.direction == "west" then
- -- Wall faces west, ore should face east (into room) + 180ยฐ correction
- rotationCFrame = CFrame.Angles(0, math.rad(-90 + 180), 0)
- end
- -- Use SetPrimaryPartCFrame for proper Model rotation
- ore:SetPrimaryPartCFrame(CFrame.new(orePosition) * rotationCFrame)
- print("โ๏ธ Positioned TestOre Model with PrimaryPart (" .. primaryPart.ClassName .. ") at", orePosition, "facing into room")
- else
- -- Fallback: Move all BaseParts in the model individually
- local centerOffset = Vector3.new(0, 0, 0)
- -- Calculate center of model first
- local parts = {}
- for _, child in pairs(ore:GetChildren()) do
- if child:IsA("BasePart") then
- table.insert(parts, child)
- end
- end
- if #parts > 0 then
- local totalPosition = Vector3.new(0, 0, 0)
- for _, part in pairs(parts) do
- totalPosition = totalPosition + part.Position
- end
- centerOffset = totalPosition / #parts
- -- Calculate rotation
- local rotationCFrame = CFrame.new(Vector3.new(0, 0, 0))
- if oreData.direction == "north" then
- rotationCFrame = CFrame.Angles(0, math.rad(180), 0)
- elseif oreData.direction == "south" then
- rotationCFrame = CFrame.Angles(0, 0, 0)
- elseif oreData.direction == "east" then
- rotationCFrame = CFrame.Angles(0, math.rad(90 + 180), 0)
- elseif oreData.direction == "west" then
- rotationCFrame = CFrame.Angles(0, math.rad(-90 + 180), 0)
- end
- -- Apply rotation to each part relative to center
- for _, part in pairs(parts) do
- local relativePos = part.Position - centerOffset
- local rotatedPos = rotationCFrame:VectorToWorldSpace(relativePos)
- part.CFrame = CFrame.new(orePosition + rotatedPos) * rotationCFrame * (part.CFrame - part.Position)
- end
- print("โ๏ธ Positioned TestOre Model using individual parts at", orePosition, "facing into room")
- else
- -- Final fallback - just move to position
- ore:MoveTo(orePosition)
- print("โ๏ธ Positioned TestOre Model using MoveTo at", orePosition, "(no rotation)")
- end
- end
- else
- -- TestOre is a Part - use Position and CFrame directly
- ore.Position = orePosition
- -- Rotate ore to face INTO the room (opposite of wall direction)
- if oreData.direction == "north" then
- -- Wall faces north, ore should face south (into room)
- ore.CFrame = CFrame.new(orePosition) * CFrame.Angles(0, math.rad(180), 0)
- elseif oreData.direction == "south" then
- -- Wall faces south, ore should face north (into room)
- ore.CFrame = CFrame.new(orePosition) * CFrame.Angles(0, 0, 0)
- elseif oreData.direction == "east" then
- -- Wall faces east, ore should face west (into room) + 180ยฐ correction
- ore.CFrame = CFrame.new(orePosition) * CFrame.Angles(0, math.rad(90 + 180), 0)
- elseif oreData.direction == "west" then
- -- Wall faces west, ore should face east (into room) + 180ยฐ correction
- ore.CFrame = CFrame.new(orePosition) * CFrame.Angles(0, math.rad(-90 + 180), 0)
- end
- print("โ๏ธ Positioned TestOre Part at", orePosition, "facing into room")
- end
- -- Add cave-specific identifier to distinguish from surface ores
- local stringValue = Instance.new("StringValue")
- stringValue.Name = "CaveType"
- stringValue.Value = config.type
- stringValue.Parent = ore
- local intValue = Instance.new("IntValue")
- intValue.Name = "NeighborCount"
- intValue.Value = oreData.neighborCount
- intValue.Parent = ore
- -- Add position data for debugging
- local positionValue = Instance.new("Vector3Value")
- positionValue.Name = "GridPosition"
- positionValue.Value = Vector3.new(oreData.gridX, oreData.gridY, 0)
- positionValue.Parent = ore
- -- Add debug click detector for manual analysis
- local debugDetector = Instance.new("ClickDetector")
- debugDetector.Name = "DebugClickDetector"
- debugDetector.MaxActivationDistance = 15
- debugDetector.Parent = ore
- -- Store grid parameters for debug analysis
- local gridDataValue = Instance.new("StringValue")
- gridDataValue.Name = "GridDebugData"
- gridDataValue.Value = string.format("CellSize:%d,StartX:%.1f,StartZ:%.1f,MineSize:50x50",
- cellSize, startX, startZ)
- gridDataValue.Parent = ore
- debugDetector.MouseClick:Connect(function(player)
- print("=== SUSPECT FLOATING ORE DATA ===")
- print("Ore Name:", ore.Name)
- print("Ore Position:", self:GetOrePosition(ore))
- local gridPos = ore:FindFirstChild("GridPosition")
- if gridPos then
- print("Grid Position:", gridPos.Value.X .. "," .. gridPos.Value.Y)
- end
- local gridDebug = ore:FindFirstChild("GridDebugData")
- if gridDebug then
- print("Grid Parameters:", gridDebug.Value)
- end
- -- Calculate expected position
- local expectedGridCenterX = startX + (oreData.gridX - 0.5) * cellSize
- local expectedGridCenterZ = startZ + (oreData.gridY - 0.5) * cellSize
- print("Expected Grid Center:", expectedGridCenterX .. "," .. expectedGridCenterZ)
- -- Calculate distance from expected center
- local orePos = self:GetOrePosition(ore)
- if orePos then
- local distance = math.sqrt(
- (orePos.X - expectedGridCenterX)^2 +
- (orePos.Z - expectedGridCenterZ)^2
- )
- print("Distance from Grid Center:", math.floor(distance * 10) / 10, "studs")
- print("Cell Size:", cellSize, "studs")
- print("Half Cell Size:", cellSize/2, "studs")
- print("Max Allowed Distance:", (cellSize/2) + 5, "studs")
- if distance > (cellSize/2) + 5 then
- print("STATUS: โ FLOATING (too far from grid center)")
- else
- print("STATUS: โ VALID (within grid bounds)")
- end
- end
- print("Wall Direction:", oreData.direction)
- print("Neighbor Count:", oreData.neighborCount)
- print("=== END SUSPECT ORE DATA ===")
- end)
- print("โ๏ธ Cloned TestOre (" .. ore.ClassName .. ") at", orePosition, "direction", oreData.direction, "neighbors:", oreData.neighborCount)
- print("๐ DEBUG: Grid(" .. oreData.gridX .. "," .. oreData.gridY .. ") CellSize:" .. cellSize .. " Expected Center: " .. (startX + (oreData.gridX - 0.5) * cellSize) .. "," .. (startZ + (oreData.gridY - 0.5) * cellSize))
- end
- -- Fallback ore creation if TestOre is not found
- function CaveSystem:CreateFallbackOre(oreData, startX, startZ, mineY, cellSize, config, folder)
- local oreWorldX = startX + (oreData.gridX - 0.5) * cellSize
- local oreWorldZ = startZ + (oreData.gridY - 0.5) * cellSize
- local oreGridCenter = Vector3.new(oreWorldX, mineY, oreWorldZ)
- local halfCellSize = cellSize / 2
- local orePosition = self:GetWallEdgePosition(oreGridCenter, oreData.direction, halfCellSize)
- -- Create basic fallback ore
- local ore = Instance.new("Part")
- ore.Name = "FallbackOre_" .. config.type
- ore.Size = Vector3.new(2, 2, 1)
- ore.Position = orePosition
- ore.Material = Enum.Material.Neon
- ore.Color = self:GetSimpleOreColor(config.type)
- ore.Anchored = true
- ore.CanCollide = false
- ore.Parent = folder
- -- Add basic mining interaction
- local clickDetector = Instance.new("ClickDetector")
- clickDetector.MaxActivationDistance = 8
- clickDetector.Parent = ore
- clickDetector.MouseClick:Connect(function(player)
- if ore.Size.X > 1 then
- ore.Size = ore.Size * 0.8
- if _G.ShowToast then
- _G.ShowToast("โ๏ธ Mined fallback ore!", "Success")
- end
- else
- ore:Destroy()
- end
- end)
- print("โ๏ธ Created fallback ore at", orePosition)
- end
- -- NEW: Simple ore colors for fallback
- function CaveSystem:GetSimpleOreColor(caveType)
- local colors = {
- Crystal = Color3.new(0.4, 0.8, 1), -- Bright blue
- Underground = Color3.new(0.8, 0.6, 0.2), -- Gold
- Lava = Color3.new(1, 0.3, 0.1), -- Red
- Ice = Color3.new(0.7, 0.9, 1), -- Light blue
- Ancient = Color3.new(0.8, 0.7, 0.3) -- Ancient gold
- }
- return colors[caveType] or Color3.new(0.8, 0.6, 0.2)
- end
- -- NEW: Cleanup floating ores that aren't touching terrain
- function CaveSystem:CleanupFloatingOres(caveInstance)
- local folder = caveInstance.folder
- if not folder then return end
- print("๐งน Cleaning up floating ores...")
- local totalOres = 0
- local floatingOres = 0
- local removedOres = 0
- -- Find all ore objects in the cave
- for _, child in pairs(folder:GetChildren()) do
- if child.Name:find("CaveOre_") or child.Name:find("FallbackOre_") then
- totalOres = totalOres + 1
- local isFloating = self:IsOreFloating(child)
- if isFloating then
- floatingOres = floatingOres + 1
- print("๐๏ธ Removing floating ore:", child.Name, "at position", self:GetOrePosition(child))
- child:Destroy()
- removedOres = removedOres + 1
- end
- end
- end
- print("๐งน Ore cleanup complete:")
- print(" - Total ores found:", totalOres)
- print(" - Floating ores detected:", floatingOres)
- print(" - Floating ores removed:", removedOres)
- print(" - Remaining ores:", totalOres - removedOres)
- end
- -- NEW: Check if an ore is floating using grid-based distance logic
- function CaveSystem:IsOreFloating(ore)
- local orePosition = self:GetOrePosition(ore)
- if not orePosition then return true end -- If we can't get position, assume floating
- -- Get ore data from the ore itself
- local gridPositionValue = ore:FindFirstChild("GridPosition")
- local caveTypeValue = ore:FindFirstChild("CaveType")
- if not gridPositionValue or not caveTypeValue then
- print("๐ Ore missing grid data - keeping it:", ore.Name)
- return false -- If no grid data, don't remove it
- end
- local gridPos = gridPositionValue.Value
- local caveType = caveTypeValue.Value
- -- Find the cave instance to get grid parameters
- local caveInstance = nil
- for player, caves in pairs(self.playerCaveInstances) do
- if caves[caveType] then
- caveInstance = caves[caveType]
- break
- end
- end
- if not caveInstance then
- print("๐ No cave instance found - keeping ore:", ore.Name)
- return false
- end
- -- Calculate expected grid center position
- local cellSize = caveInstance.cellSize or 8
- local config = caveInstance.config
- local centerPos = config.centerPosition
- local startX = centerPos.X - (50 * cellSize / 2) -- Mine is 50x50
- local startZ = centerPos.Z - (50 * cellSize / 2)
- local expectedGridCenterX = startX + (gridPos.X - 0.5) * cellSize
- local expectedGridCenterZ = startZ + (gridPos.Y - 0.5) * cellSize
- local expectedGridCenter = Vector3.new(expectedGridCenterX, centerPos.Y, expectedGridCenterZ)
- -- Calculate maximum allowed distance from grid center
- local halfCellSize = cellSize / 2
- local maxAllowedDistance = halfCellSize + 5 -- Allow some extra margin for wall placement
- -- Calculate actual distance from expected grid center
- local actualDistance = math.sqrt(
- (orePosition.X - expectedGridCenter.X)^2 +
- (orePosition.Z - expectedGridCenter.Z)^2
- )
- -- If ore is too far from its grid center, it's floating/misplaced
- local isFloating = actualDistance > maxAllowedDistance
- if isFloating then
- print("๐๏ธ Ore too far from grid center:", ore.Name)
- print(" - Expected center:", expectedGridCenter.X .. "," .. expectedGridCenter.Z)
- print(" - Actual position:", orePosition.X .. "," .. orePosition.Z)
- print(" - Distance:", math.floor(actualDistance * 10) / 10, "studs (max allowed:", maxAllowedDistance .. ")")
- else
- print("โ Ore within grid bounds:", ore.Name, "distance:", math.floor(actualDistance * 10) / 10)
- end
- return isFloating
- end
- -- NEW: Get position of ore (handles both Models and Parts)
- function CaveSystem:GetOrePosition(ore)
- if ore:IsA("Model") then
- if ore.PrimaryPart then
- return ore.PrimaryPart.Position
- else
- -- Find first BasePart and use its position
- for _, child in pairs(ore:GetChildren()) do
- if child:IsA("BasePart") then
- return child.Position
- end
- end
- end
- elseif ore:IsA("BasePart") then
- return ore.Position
- end
- return nil -- Couldn't determine position
- end
- -- NEW: Clear existing ores from cave
- function CaveSystem:ClearExistingOres(caveInstance)
- local folder = caveInstance.folder
- if not folder then return end
- local removedCount = 0
- for _, child in pairs(folder:GetChildren()) do
- if child.Name:find("CaveOre_") or child.Name:find("FallbackOre_") then
- child:Destroy()
- removedCount = removedCount + 1
- end
- end
- print("๐๏ธ Cleared", removedCount, "existing ores for fresh generation")
- end
- -- NEW: Regenerate random ores in existing cave
- function CaveSystem:RegenerateRandomOres(caveInstance)
- local mine = caveInstance.mine
- local config = caveInstance.config
- if not mine or not mine.House or not mine.House.Rooms then
- warn("โ No mine data found for ore regeneration")
- return
- end
- print("๐ฒ Regenerating random ores...")
- -- Clear existing ore positions from all rooms
- for _, room in ipairs(mine.House.Rooms) do
- room.OrePositions = {}
- end
- -- Regenerate ore positions with new randomization
- for _, room in ipairs(mine.House.Rooms) do
- room:GenerateRoomOres(mine)
- end
- -- Create physical ores from new positions
- local cellSize = caveInstance.cellSize or 8
- local centerPos = config.centerPosition
- local startX = centerPos.X - (mine.sX * cellSize / 2)
- local startZ = centerPos.Z - (mine.sY * cellSize / 2)
- local mineY = centerPos.Y
- local totalNewOres = 0
- for _, room in ipairs(mine.House.Rooms) do
- for _, oreData in ipairs(room.OrePositions) do
- self:CreateNeighborCountOre(oreData, startX, startZ, mineY, cellSize, config)
- totalNewOres = totalNewOres + 1
- end
- end
- print("๐ฒ Generated", totalNewOres, "new randomized TestOres")
- end
- -- ============================================================================
- -- MINING INFRASTRUCTURE (WITHOUT FLOATING ORES)
- -- ============================================================================
- function CaveSystem:AddMiningInfrastructure(caveInstance)
- local config = caveInstance.config
- local properties = config.properties
- local folder = caveInstance.folder
- print("โก Adding mining infrastructure...")
- local mine = caveInstance.mine
- local cellSize = caveInstance.cellSize
- if not mine then
- warn("โ No mine data found")
- return
- end
- self:AddGridBasedMineInfrastructure(mine, cellSize, config, properties, folder)
- print("โก Mining infrastructure completed")
- end
- function CaveSystem:AddGridBasedMineInfrastructure(mine, cellSize, config, properties, folder)
- local centerPos = config.centerPosition
- local startX = centerPos.X - (mine.sX * cellSize / 2)
- local startZ = centerPos.Z - (mine.sY * cellSize / 2)
- local mineY = centerPos.Y
- for x = 1, mine.sX do
- for y = 1, mine.sY do
- local cell = mine.Map[x][y]
- if cell.isRoom or cell.isPath then
- local worldX = startX + (x - 0.5) * cellSize
- local worldZ = startZ + (y - 0.5) * cellSize
- local worldPos = Vector3.new(worldX, mineY, worldZ)
- -- LIGHTING: Light most rooms and intersections
- if cell.hasLighting and (cell.isRoom or math.random() < 0.6) then
- local lightPos = Vector3.new(worldX, mineY + 6, worldZ)
- self:CreateBalancedMiningLight(lightPos, properties, folder)
- end
- -- ROOM SUPPORTS: Sparse support beams
- if cell.isRoom and cell.hasSupport and properties.infrastructure.woodenSupports then
- if math.random() < 0.05 then
- local supportHeight = 16
- self:CreateRoomSupport(worldPos, supportHeight, folder)
- end
- end
- -- CORRIDOR SUPPORTS: Mineshaft-style supports
- if cell.isPath and properties.infrastructure.woodenSupports then
- if (x + y) % 7 == 0 then
- self:CreateCorridorMineshaftSupport(worldPos, cellSize, folder, cell, mine)
- end
- end
- -- CABLES: Power cables along paths
- if properties.infrastructure.cables then
- self:AddCablesForCell(cell, worldPos, cellSize, folder, mine)
- end
- -- NO ORE CREATION HERE - ores are now created during room generation using neighbor count
- end
- end
- end
- end
- function CaveSystem:CreateBalancedMiningLight(position, properties, folder)
- local fixture = Instance.new("Part")
- fixture.Name = "MiningLight"
- fixture.Size = Vector3.new(1, 3, 1)
- fixture.Position = position
- fixture.Material = Enum.Material.Metal
- fixture.BrickColor = BrickColor.new("Dark stone grey")
- fixture.Anchored = true
- fixture.Parent = folder
- local light = Instance.new("PointLight")
- light.Brightness = properties.lighting.brightness * 0.8
- light.Color = Color3.new(
- properties.lighting.color.r * 0.9,
- properties.lighting.color.g * 0.9,
- properties.lighting.color.b * 0.9
- )
- light.Range = properties.lighting.range * 0.9
- light.Parent = fixture
- spawn(function()
- while fixture.Parent do
- wait(math.random(3, 8))
- local originalBrightness = light.Brightness
- light.Brightness = originalBrightness * (0.8 + math.random() * 0.2)
- wait(0.1)
- light.Brightness = originalBrightness
- end
- end)
- local cage = Instance.new("Part")
- cage.Name = "LightCage"
- cage.Size = Vector3.new(2, 2, 2)
- cage.Position = position - Vector3.new(0, 0.5, 0)
- cage.Material = Enum.Material.Metal
- cage.BrickColor = BrickColor.new("Really black")
- cage.Transparency = 0.7
- cage.Anchored = true
- cage.Parent = folder
- end
- function CaveSystem:CreateRoomSupport(position, height, folder)
- local beam = Instance.new("Part")
- beam.Name = "RoomSupport"
- beam.Size = Vector3.new(1.2, height, 1.2)
- beam.Position = position
- beam.Material = Enum.Material.Wood
- beam.BrickColor = BrickColor.new("Dark brown")
- beam.Anchored = true
- beam.Parent = folder
- end
- function CaveSystem:CreateCorridorMineshaftSupport(position, cellSize, folder, cell, mine)
- local supportDirection = self:GetCorridorDirection(cell, mine)
- if supportDirection == "horizontal" then
- self:CreateMineshaftFrame(position, cellSize, "horizontal", folder)
- elseif supportDirection == "vertical" then
- self:CreateMineshaftFrame(position, cellSize, "vertical", folder)
- else
- self:CreateMineshaftFrame(position, cellSize, "cross", folder)
- end
- end
- function CaveSystem:GetCorridorDirection(cell, mine)
- local openDirs = {}
- for dir, available in pairs(cell.availDirs) do
- if available then
- table.insert(openDirs, dir)
- end
- end
- if #openDirs == 2 then
- if (table.find(openDirs, "N") and table.find(openDirs, "S")) then
- return "horizontal"
- elseif (table.find(openDirs, "E") and table.find(openDirs, "W")) then
- return "vertical"
- end
- end
- return "intersection"
- end
- function CaveSystem:CreateMineshaftFrame(position, cellSize, orientation, folder)
- local frameHeight = 12
- local postWidth = 0.8
- local beamWidth = 0.6
- local function setSafeMaterial(part, materialName)
- local success = pcall(function()
- if materialName == "VerticalPlanks" then
- part.Material = "VerticalPlanks"
- elseif materialName == "HorizontalPlanks" then
- part.Material = "HorizontalPlanks"
- else
- part.Material = Enum.Material.Wood
- end
- end)
- if not success then
- part.Material = Enum.Material.Wood
- end
- end
- if orientation == "horizontal" then
- local leftPost = Instance.new("Part")
- leftPost.Name = "CorridorPost"
- leftPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
- leftPost.Position = position + Vector3.new(-cellSize/2 + postWidth/2, frameHeight/2, 0)
- setSafeMaterial(leftPost, "VerticalPlanks")
- leftPost.BrickColor = BrickColor.new("Dark brown")
- leftPost.Anchored = true
- leftPost.Parent = folder
- local rightPost = Instance.new("Part")
- rightPost.Name = "CorridorPost"
- rightPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
- rightPost.Position = position + Vector3.new(cellSize/2 - postWidth/2, frameHeight/2, 0)
- setSafeMaterial(rightPost, "VerticalPlanks")
- rightPost.BrickColor = BrickColor.new("Dark brown")
- rightPost.Anchored = true
- rightPost.Parent = folder
- local topBeam = Instance.new("Part")
- topBeam.Name = "CorridorBeam"
- topBeam.Size = Vector3.new(cellSize - postWidth, beamWidth, beamWidth)
- topBeam.Position = position + Vector3.new(0, frameHeight - beamWidth/2, 0)
- setSafeMaterial(topBeam, "HorizontalPlanks")
- topBeam.BrickColor = BrickColor.new("Dark brown")
- topBeam.Anchored = true
- topBeam.Parent = folder
- elseif orientation == "vertical" then
- local frontPost = Instance.new("Part")
- frontPost.Name = "CorridorPost"
- frontPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
- frontPost.Position = position + Vector3.new(0, frameHeight/2, -cellSize/2 + postWidth/2)
- setSafeMaterial(frontPost, "VerticalPlanks")
- frontPost.BrickColor = BrickColor.new("Dark brown")
- frontPost.Anchored = true
- frontPost.Parent = folder
- local backPost = Instance.new("Part")
- backPost.Name = "CorridorPost"
- backPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
- backPost.Position = position + Vector3.new(0, frameHeight/2, cellSize/2 - postWidth/2)
- setSafeMaterial(backPost, "VerticalPlanks")
- backPost.BrickColor = BrickColor.new("Dark brown")
- backPost.Anchored = true
- backPost.Parent = folder
- local topBeam = Instance.new("Part")
- topBeam.Name = "CorridorBeam"
- topBeam.Size = Vector3.new(beamWidth, beamWidth, cellSize - postWidth)
- topBeam.Position = position + Vector3.new(0, frameHeight - beamWidth/2, 0)
- setSafeMaterial(topBeam, "HorizontalPlanks")
- topBeam.BrickColor = BrickColor.new("Dark brown")
- topBeam.Anchored = true
- topBeam.Parent = folder
- else
- local centerPost = Instance.new("Part")
- centerPost.Name = "IntersectionPost"
- centerPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
- centerPost.Position = position + Vector3.new(0, frameHeight/2, 0)
- setSafeMaterial(centerPost, "VerticalPlanks")
- centerPost.BrickColor = BrickColor.new("Dark brown")
- centerPost.Anchored = true
- centerPost.Parent = folder
- local crossBeam1 = Instance.new("Part")
- crossBeam1.Name = "CrossBeam"
- crossBeam1.Size = Vector3.new(cellSize * 0.8, beamWidth, beamWidth)
- crossBeam1.Position = position + Vector3.new(0, frameHeight - 2, 0)
- setSafeMaterial(crossBeam1, "HorizontalPlanks")
- crossBeam1.BrickColor = BrickColor.new("Dark brown")
- crossBeam1.Anchored = true
- crossBeam1.Parent = folder
- local crossBeam2 = Instance.new("Part")
- crossBeam2.Name = "CrossBeam"
- crossBeam2.Size = Vector3.new(beamWidth, beamWidth, cellSize * 0.8)
- crossBeam2.Position = position + Vector3.new(0, frameHeight - 2, 0)
- setSafeMaterial(crossBeam2, "HorizontalPlanks")
- crossBeam2.BrickColor = BrickColor.new("Dark brown")
- crossBeam2.Anchored = true
- crossBeam2.Parent = folder
- end
- end
- function CaveSystem:AddCablesForCell(cell, worldPos, cellSize, folder, mine)
- local directions = {
- {dir = "E", dx = cellSize, dz = 0},
- {dir = "N", dx = 0, dz = cellSize}
- }
- for _, dirInfo in ipairs(directions) do
- if cell.availDirs[dirInfo.dir] then
- local startPos = Vector3.new(worldPos.X, worldPos.Y + 4, worldPos.Z)
- local endPos = Vector3.new(worldPos.X + dirInfo.dx, worldPos.Y + 4, worldPos.Z + dirInfo.dz)
- self:CreateCableRun(startPos, endPos, folder)
- end
- end
- end
- function CaveSystem:CreateCableRun(startPos, endPos, folder)
- local cable = Instance.new("Part")
- cable.Name = "PowerCable"
- cable.Size = Vector3.new(0.2, 0.2, (endPos - startPos).Magnitude)
- cable.Position = startPos:Lerp(endPos, 0.5)
- cable.CFrame = CFrame.lookAt(cable.Position, endPos)
- cable.Material = Enum.Material.Plastic
- cable.BrickColor = BrickColor.new("Really black")
- cable.Anchored = true
- cable.Parent = folder
- end
- -- ============================================================================
- -- PORTAL AND TELEPORTATION SYSTEM
- -- ============================================================================
- function CaveSystem:CreateReturnPortal(caveInstance)
- local config = caveInstance.config
- local folder = caveInstance.folder
- local mine = caveInstance.mine
- local spawnRoom = nil
- local bestRoomSize = 0
- if mine and mine.House and mine.House.Rooms then
- for _, room in ipairs(mine.House.Rooms) do
- local roomWidth = room.br.x - room.tl.x
- local roomHeight = room.br.y - room.tl.y
- local roomSize = roomWidth * roomHeight
- if roomSize > bestRoomSize then
- bestRoomSize = roomSize
- spawnRoom = room
- end
- end
- end
- local portalPosition = config.portalPosition
- if spawnRoom then
- local centerPos = config.centerPosition
- local cellSize = caveInstance.cellSize or 8
- local startX = centerPos.X - (mine.sX * cellSize / 2)
- local startZ = centerPos.Z - (mine.sY * cellSize / 2)
- local roomCenterX = (spawnRoom.tl.x + spawnRoom.br.x) / 2
- local roomCenterY = (spawnRoom.tl.y + spawnRoom.br.y) / 2
- local worldX = startX + (roomCenterX - 0.5) * cellSize
- local worldZ = startZ + (roomCenterY - 0.5) * cellSize
- local wallOffset = cellSize * 2
- local floorLevel = centerPos.Y - 8
- portalPosition = Vector3.new(worldX, floorLevel, worldZ - wallOffset)
- local playerFloorLevel = centerPos.Y - 8 + 3
- caveInstance.playerSpawnPosition = Vector3.new(worldX, playerFloorLevel, worldZ + wallOffset/3)
- print("๐ Portal placed on floor at:", floorLevel)
- print("๐ Player spawn on floor at:", playerFloorLevel)
- else
- print("๐ No suitable room found, using default floor positions")
- local floorLevel = config.centerPosition.Y - 8
- portalPosition = Vector3.new(config.centerPosition.X, floorLevel, config.centerPosition.Z)
- caveInstance.playerSpawnPosition = Vector3.new(config.centerPosition.X, floorLevel + 3, config.centerPosition.Z + 10)
- end
- self:CreatePortalWoodenFrame(portalPosition, folder)
- local portal = Instance.new("Part")
- portal.Name = "ReturnPortal"
- portal.Size = Vector3.new(4, 12, 1)
- portal.Position = Vector3.new(portalPosition.X, portalPosition.Y + 6, portalPosition.Z)
- portal.Material = Enum.Material.Neon
- portal.Color = Color3.new(0, 0, 0)
- portal.Anchored = true
- portal.CanCollide = false
- portal.Transparency = 0
- portal.Parent = folder
- local portalLight = Instance.new("PointLight")
- portalLight.Brightness = 0.8
- portalLight.Color = Color3.new(0.2, 0.1, 0.3)
- portalLight.Range = 12
- portalLight.Parent = portal
- self:CreateDarkPortalEffects(portal, folder)
- self:SetupPortalDetection(portal, caveInstance.player)
- print("๐ Created floor-level portal for", caveInstance.player.Name)
- end
- function CaveSystem:CreatePortalWoodenFrame(portalPosition, folder)
- local postHeight = 12
- local postWidth = 1
- local frameWidth = 5
- local function setSafeMaterial(part, materialName)
- local success = pcall(function()
- if materialName == "VerticalPlanks" then
- part.Material = "VerticalPlanks"
- elseif materialName == "HorizontalPlanks" then
- part.Material = "HorizontalPlanks"
- else
- part.Material = Enum.Material.Wood
- end
- end)
- if not success then
- part.Material = Enum.Material.Wood
- end
- end
- local leftPost = Instance.new("Part")
- leftPost.Name = "PortalPost"
- leftPost.Size = Vector3.new(postWidth, postHeight, postWidth)
- leftPost.Position = Vector3.new(
- portalPosition.X - frameWidth/2,
- portalPosition.Y + postHeight/2,
- portalPosition.Z
- )
- setSafeMaterial(leftPost, "VerticalPlanks")
- leftPost.BrickColor = BrickColor.new("Dark brown")
- leftPost.Anchored = true
- leftPost.Parent = folder
- local rightPost = Instance.new("Part")
- rightPost.Name = "PortalPost"
- rightPost.Size = Vector3.new(postWidth, postHeight, postWidth)
- rightPost.Position = Vector3.new(
- portalPosition.X + frameWidth/2,
- portalPosition.Y + postHeight/2,
- portalPosition.Z
- )
- setSafeMaterial(rightPost, "VerticalPlanks")
- rightPost.BrickColor = BrickColor.new("Dark brown")
- rightPost.Anchored = true
- rightPost.Parent = folder
- local topBeam = Instance.new("Part")
- topBeam.Name = "PortalBeam"
- topBeam.Size = Vector3.new(frameWidth + postWidth, postWidth, postWidth)
- topBeam.Position = Vector3.new(
- portalPosition.X,
- portalPosition.Y + postHeight + postWidth/2,
- portalPosition.Z
- )
- setSafeMaterial(topBeam, "HorizontalPlanks")
- topBeam.BrickColor = BrickColor.new("Dark brown")
- topBeam.Anchored = true
- topBeam.Parent = folder
- local baseBeam = Instance.new("Part")
- baseBeam.Name = "PortalBase"
- baseBeam.Size = Vector3.new(frameWidth + postWidth, postWidth, postWidth)
- baseBeam.Position = Vector3.new(
- portalPosition.X,
- portalPosition.Y - postWidth/2,
- portalPosition.Z
- )
- setSafeMaterial(baseBeam, "HorizontalPlanks")
- baseBeam.BrickColor = BrickColor.new("Dark brown")
- baseBeam.Anchored = true
- baseBeam.Parent = folder
- end
- function CaveSystem:CreateDarkPortalEffects(portal, folder)
- local sparkles = Instance.new("Sparkles")
- sparkles.SparkleColor = Color3.new(0.2, 0.1, 0.3)
- sparkles.Parent = portal
- spawn(function()
- while portal.Parent do
- local light = portal:FindFirstChild("PointLight")
- if light then
- local baseBrightness = 1
- light.Brightness = baseBrightness + math.sin(tick() * 1.5) * 0.3
- end
- wait(0.1)
- end
- end)
- for i = 1, 3 do
- local particle = Instance.new("Part")
- particle.Name = "DarkPortalParticle"
- particle.Size = Vector3.new(0.3, 0.3, 0.3)
- particle.Material = Enum.Material.Neon
- particle.Color = Color3.new(0.1, 0.05, 0.2)
- particle.CanCollide = false
- particle.Anchored = true
- particle.Transparency = 0.5
- particle.Parent = folder
- spawn(function()
- local angle = (i / 3) * math.pi * 2
- while particle.Parent do
- local time = tick() * 1.5 + angle
- local radius = 2 + math.sin(time * 0.3) * 1
- local height = math.sin(time * 1.2) * 2
- particle.Position = portal.Position + Vector3.new(
- math.cos(time) * radius,
- height,
- math.sin(time) * radius
- )
- wait(0.08)
- end
- end)
- end
- end
- function CaveSystem:SetupPortalDetection(portal, player)
- local detector = Instance.new("Part")
- detector.Name = "PortalDetector"
- detector.Size = Vector3.new(10, 12, 10)
- detector.Position = portal.Position
- detector.Transparency = 1
- detector.CanCollide = false
- detector.Anchored = true
- detector.Parent = portal.Parent
- detector.Touched:Connect(function(hit)
- local character = hit.Parent
- if character == player.Character and character:FindFirstChild("Humanoid") then
- wait(0.5)
- local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
- if humanoidRootPart then
- local distance = (humanoidRootPart.Position - portal.Position).Magnitude
- if distance < 8 then
- if _G.ShowToast then
- _G.ShowToast("๐ Returning to surface...", "Info")
- end
- self:TeleportPlayerBack(player)
- end
- end
- end
- end)
- end
- function CaveSystem:GetSafeSpawnPosition(caveInstance)
- local config = caveInstance.config
- local mine = caveInstance.mine
- local spawnRoom = nil
- local bestRoomSize = 0
- if mine and mine.House and mine.House.Rooms then
- for _, room in ipairs(mine.House.Rooms) do
- local roomWidth = room.br.x - room.tl.x
- local roomHeight = room.br.y - room.tl.y
- local roomSize = roomWidth * roomHeight
- if roomSize > bestRoomSize then
- bestRoomSize = roomSize
- spawnRoom = room
- end
- end
- end
- if spawnRoom then
- local centerPos = config.centerPosition
- local cellSize = caveInstance.cellSize or 8
- local startX = centerPos.X - (mine.sX * cellSize / 2)
- local startZ = centerPos.Z - (mine.sY * cellSize / 2)
- local roomCenterX = (spawnRoom.tl.x + spawnRoom.br.x) / 2
- local roomCenterY = (spawnRoom.tl.y + spawnRoom.br.y) / 2
- local worldX = startX + (roomCenterX - 0.5) * cellSize
- local worldZ = startZ + (roomCenterY - 0.5) * cellSize
- local floorLevel = centerPos.Y - 8 + 3
- print("๐ฏ Calculated ground spawn: Room center at", worldX, floorLevel, worldZ)
- return Vector3.new(worldX, floorLevel, worldZ)
- else
- local floorLevel = config.centerPosition.Y - 8 + 3
- print("๐ฏ No room found, using fallback ground spawn at", floorLevel)
- return Vector3.new(config.centerPosition.X, floorLevel, config.centerPosition.Z + 10)
- end
- end
- function CaveSystem:TeleportPlayerToCave(player, caveType, returnPosition)
- self.playerReturnPositions[player] = returnPosition
- local caveInstance = nil
- if self.playerCaveInstances[player] and self.playerCaveInstances[player][caveType] then
- caveInstance = self.playerCaveInstances[player][caveType]
- print("๐ Using existing", caveType, "cave for", player.Name)
- -- REGENERATE ORES: Clear existing ores and generate new random ones
- self:ClearExistingOres(caveInstance)
- self:RegenerateRandomOres(caveInstance)
- -- CLEANUP: Wait for ore generation to settle, then cleanup
- print("โณ Waiting for ore generation to settle before cleanup...")
- wait(0.5) -- Give ore creation time to complete
- self:CleanupFloatingOres(caveInstance)
- else
- warn("โ ๏ธ Cave not pre-generated, creating on-demand for", player.Name)
- caveInstance = self:GetOrCreateCaveInstance(player, caveType)
- end
- if not caveInstance then
- warn("โ Failed to access cave instance")
- return false
- end
- if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
- self:CreateSafeSpawnZone(caveInstance)
- self:ApplyCaveSafetyMode(player, caveInstance)
- local humanoid = player.Character:FindFirstChild("Humanoid")
- if humanoid then
- humanoid.Health = humanoid.MaxHealth
- end
- wait(0.3)
- local spawnPosition = self:GetSafeSpawnPosition(caveInstance)
- player.Character.HumanoidRootPart.CFrame = CFrame.new(spawnPosition)
- if humanoid then
- humanoid.Health = humanoid.MaxHealth
- end
- print("โก Teleported", player.Name, "to floor level in", caveType, "cave at", spawnPosition)
- if _G.ShowToast then
- _G.ShowToast("โ Entered " .. caveType .. " Cave - Fresh randomized TestOres!", "Success")
- end
- return true
- end
- return false
- end
- function CaveSystem:TeleportPlayerBack(player)
- local returnPosition = self.playerReturnPositions[player]
- if returnPosition and player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
- self:RemoveCaveSafetyMode(player, "all")
- player.Character.HumanoidRootPart.CFrame = CFrame.new(returnPosition)
- print("๐ Teleported", player.Name, "back to surface")
- self.playerReturnPositions[player] = nil
- self:RemoveCaveAtmosphere(player)
- self:DespawnPlayerCaves(player)
- if _G.ShowToast then
- _G.ShowToast("๐ Returned to surface - Safety mode deactivated", "Success")
- end
- end
- end
- -- ============================================================================
- -- ATMOSPHERE AND UTILITY FUNCTIONS
- -- ============================================================================
- function CaveSystem:CreateHiddenWalls(caveInstance)
- local config = caveInstance.config
- local folder = caveInstance.folder
- for _, passage in ipairs(caveInstance.hiddenPassages) do
- local wall = Instance.new("Part")
- wall.Name = "HiddenWall_" .. passage.id
- wall.Size = passage.crackSize
- wall.Position = passage.position
- wall.Material = Enum.Material[config.properties.wallMaterial] or Enum.Material.Rock
- wall.Color = Color3.new(config.properties.wallColor.r, config.properties.wallColor.g, config.properties.wallColor.b)
- wall.Anchored = true
- wall.Parent = folder
- local crack = Instance.new("Part")
- crack.Name = "HiddenCrack_" .. passage.id
- crack.Size = passage.crackSize + Vector3.new(0.1, 0.1, 0.1)
- crack.Position = passage.position
- crack.Material = Enum.Material.Neon
- crack.Color = Color3.new(1, 0.5, 0)
- crack.Anchored = true
- crack.CanCollide = false
- crack.Transparency = 1
- crack.Parent = folder
- self:SetupCrackDetection(wall, crack, passage, caveInstance.player)
- end
- print("๐ Created", #caveInstance.hiddenPassages, "hidden passages")
- end
- function CaveSystem:SetupCrackDetection(wall, crack, passage, player)
- local connection = RunService.Heartbeat:Connect(function()
- if player.Character then
- local tool = player.Character:FindFirstChild("CaveDetector")
- crack.Transparency = tool and 0 or 1
- end
- end)
- local clickDetector = Instance.new("ClickDetector")
- clickDetector.MaxActivationDistance = 10
- clickDetector.Parent = wall
- clickDetector.MouseClick:Connect(function(clickingPlayer)
- if clickingPlayer == player and crack.Transparency == 0 then
- self:BreakHiddenWall(wall, crack, passage, player)
- connection:Disconnect()
- end
- end)
- end
- function CaveSystem:BreakHiddenWall(wall, crack, passage, player)
- print("๐ฅ Breaking hidden wall for", player.Name)
- local explosion = Instance.new("Explosion")
- explosion.Position = wall.Position
- explosion.BlastRadius = 15
- explosion.BlastPressure = 0
- explosion.Parent = workspace
- wall:Destroy()
- crack:Destroy()
- self:CreateSecretChamber(passage, player)
- passage.broken = true
- end
- function CaveSystem:CreateSecretChamber(passage, player)
- local chamber = passage.leadsTo
- local tunnelStart = passage.position
- local tunnelEnd = chamber.position
- local direction = (tunnelEnd - tunnelStart).Unit
- local distance = (tunnelEnd - tunnelStart).Magnitude
- for i = 0, distance, 8 do
- local pos = tunnelStart + direction * i
- pos = Vector3.new(
- math.floor(pos.X / 4) * 4,
- math.floor(pos.Y / 4) * 4,
- math.floor(pos.Z / 4) * 4
- )
- local region = Region3.new(
- pos - Vector3.new(4, 4, 4),
- pos + Vector3.new(4, 4, 4)
- ):ExpandToGrid(4)
- workspace.Terrain:FillRegion(region, 4, Enum.Material.Air)
- end
- local alignedChamberPos = Vector3.new(
- math.floor(chamber.position.X / 4) * 4,
- math.floor(chamber.position.Y / 4) * 4,
- math.floor(chamber.position.Z / 4) * 4
- )
- local chamberRegion = Region3.new(
- alignedChamberPos - chamber.size/2,
- alignedChamberPos + chamber.size/2
- ):ExpandToGrid(4)
- workspace.Terrain:FillRegion(chamberRegion, 4, Enum.Material.Air)
- self:SpawnLoot(chamber, player)
- print("๐๏ธ Created secret chamber for", player.Name)
- end
- function CaveSystem:SpawnLoot(chamber, player)
- for i = 1, chamber.lootSpawns do
- local lootPos = chamber.position + Vector3.new(
- (math.random() - 0.5) * chamber.size.X * 0.8,
- -chamber.size.Y/2 + 2,
- (math.random() - 0.5) * chamber.size.Z * 0.8
- )
- local loot = Instance.new("Part")
- loot.Name = "LootChest"
- loot.Size = Vector3.new(3, 2, 2)
- loot.Position = lootPos
- loot.Material = Enum.Material.Wood
- loot.BrickColor = BrickColor.new("Dark brown")
- loot.Anchored = true
- loot.Parent = workspace
- local light = Instance.new("PointLight")
- light.Brightness = 3
- light.Color = Color3.new(1, 0.8, 0.2)
- light.Range = 15
- light.Parent = loot
- local sparkle = Instance.new("Sparkles")
- sparkle.SparkleColor = Color3.new(1, 1, 0)
- sparkle.Parent = loot
- end
- end
- function CaveSystem:AddCaveAtmosphere(caveInstance)
- local config = caveInstance.config
- local player = caveInstance.player
- caveInstance.atmosphereConfig = {
- tintColor = Color3.new(
- config.properties.lighting.color.r * 0.7,
- config.properties.lighting.color.g * 0.7,
- config.properties.lighting.color.b * 0.7
- ),
- brightness = -0.3,
- contrast = 0.2,
- saturation = -0.1,
- fogConfig = {
- density = 0.3,
- offset = 0.2,
- color = Color3.new(
- config.properties.lighting.color.r * 0.8,
- config.properties.lighting.color.g * 0.8,
- config.properties.lighting.color.b * 0.8
- ),
- decay = Color3.new(0.6, 0.6, 0.7),
- glare = 0.4,
- haze = 0.4
- }
- }
- print("๐ Cave atmosphere config prepared for", player.Name)
- end
- function CaveSystem:RemoveCaveAtmosphere(player)
- for _, effect in pairs(game.Lighting:GetChildren()) do
- if effect.Name:find("CaveAmbient_" .. player.Name) or effect.Name:find("CaveFog_" .. player.Name) then
- effect:Destroy()
- end
- end
- print("๐ Removed cave atmosphere for", player.Name)
- end
- function CaveSystem:GetOrCreateCaveInstance(player, caveType)
- if self.playerCaveInstances[player] and self.playerCaveInstances[player][caveType] then
- return self.playerCaveInstances[player][caveType]
- end
- return self:CreateCaveInstance(caveType, player)
- end
- function CaveSystem:CloneHiddenPassages(passages, player)
- local cloned = {}
- for _, passage in ipairs(passages) do
- table.insert(cloned, {
- id = passage.id,
- position = passage.position,
- crackSize = passage.crackSize,
- leadsTo = passage.leadsTo,
- requiredTool = passage.requiredTool,
- broken = false
- })
- end
- return cloned
- end
- function CaveSystem:DespawnPlayerCaves(player)
- if self.playerCaveInstances[player] then
- print("๐๏ธ Despawning caves for", player.Name)
- for caveType, instance in pairs(self.playerCaveInstances[player]) do
- if instance.folder then
- print("๐๏ธ Destroying", caveType, "cave for", player.Name)
- self:RestoreCaveTerrain(instance)
- instance.folder:Destroy()
- end
- end
- self.playerCaveInstances[player] = nil
- print("โ All caves and terrain despawned for", player.Name)
- end
- end
- function CaveSystem:RestoreCaveTerrain(caveInstance)
- local config = caveInstance.config
- if config and config.centerPosition and config.size then
- print("๐ชจ Restoring terrain for cave...")
- local centerPos = config.centerPosition
- local expandedSize = config.size * 1.3
- local rockRegion = Region3.new(
- centerPos - expandedSize/2,
- centerPos + expandedSize/2
- ):ExpandToGrid(4)
- workspace.Terrain:FillRegion(rockRegion, 4, Enum.Material.Rock)
- print("โ Cave terrain restored to solid rock")
- else
- warn("โ ๏ธ Could not restore terrain - missing cave config data")
- end
- end
- function CaveSystem:CleanupPlayerCaves(player)
- self:DespawnPlayerCaves(player)
- self.playerReturnPositions[player] = nil
- for _, effect in pairs(game.Lighting:GetChildren()) do
- if effect.Name:find("CaveAmbient_" .. player.Name) or effect.Name:find("CaveFog_" .. player.Name) then
- effect:Destroy()
- end
- end
- print("๐งน Cleaned up all cave data for", player.Name)
- end
- function CaveSystem:ClearAllCaves()
- for player, caves in pairs(self.playerCaveInstances) do
- for _, instance in pairs(caves) do
- if instance.folder then
- instance.folder:Destroy()
- end
- end
- end
- self.playerCaveInstances = {}
- for _, effect in pairs(game.Lighting:GetChildren()) do
- if effect.Name:find("CaveAmbient_") or effect.Name:find("CaveFog_") then
- effect:Destroy()
- end
- end
- print("๐งน Cleared all cave instances")
- end
- function CaveSystem:Initialize()
- print("๐ Initializing Dark Cave System...")
- local success, err = pcall(function()
- if self:ShouldRegenerateCaves() then
- self:GenerateWeeklyCaves()
- end
- end)
- if not success then
- warn("โ Error during cave generation:", err)
- print("๐ Retrying cave system initialization...")
- wait(2)
- self.currentWeek = self:GetCurrentWeek()
- self.caveConfigs = {}
- end
- Players.PlayerAdded:Connect(function(player)
- print("๐ Player joined:", player.Name)
- end)
- Players.PlayerRemoving:Connect(function(player)
- self:CleanupPlayerCaves(player)
- end)
- print("โ Dark Cave System initialized - caves generate on-demand")
- end
- -- ============================================================================
- -- REMOTE EVENTS AND GLOBAL FUNCTIONS
- -- ============================================================================
- local enterCaveEvent = Instance.new("RemoteEvent")
- enterCaveEvent.Name = "EnterCaveEvent"
- enterCaveEvent.Parent = ReplicatedStorage
- enterCaveEvent.OnServerEvent:Connect(function(player, caveType, returnPosition)
- local success, err = pcall(function()
- CaveSystem:TeleportPlayerToCave(player, caveType, returnPosition)
- end)
- if not success then
- warn("โ Error teleporting player to cave:", err)
- end
- end)
- _G.CaveSystem = CaveSystem
- _G.GenerateCaveForPlayer = function(player, caveType)
- if CaveSystem and player and caveType then
- return CaveSystem:CreateCaveInstance(caveType, player)
- end
- end
- _G.GetPlayerCaveStatus = function(player)
- if CaveSystem.playerCaveInstances[player] then
- local status = {}
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- status[caveType] = {
- active = instance and true or false,
- instancePosition = instance.instancePosition,
- isInstancedDimension = instance.isInstancedDimension,
- safetyActive = instance.safetySystem and instance.safetySystem.isActive or false
- }
- end
- return status
- end
- return "No active cave dimensions"
- end
- _G.GetInstanceDimensionInfo = function()
- return {
- baseCavePosition = CaveSystem.baseCavePosition,
- instanceOffsets = {
- Crystal = Vector3.new(0, 0, 0),
- Underground = Vector3.new(1000, 0, 0),
- Lava = Vector3.new(2000, 0, 0),
- Ice = Vector3.new(0, 0, 1000),
- Ancient = Vector3.new(1000, 0, 1000)
- },
- actualPositions = {
- Crystal = CaveSystem.baseCavePosition + Vector3.new(0, 0, 0),
- Underground = CaveSystem.baseCavePosition + Vector3.new(1000, 0, 0),
- Lava = CaveSystem.baseCavePosition + Vector3.new(2000, 0, 0),
- Ice = CaveSystem.baseCavePosition + Vector3.new(0, 0, 1000),
- Ancient = CaveSystem.baseCavePosition + Vector3.new(1000, 0, 1000)
- },
- note = "All caves now generate at HIGH ALTITUDE (Y=2000+) for safety"
- }
- end
- _G.ClearAllInstanceDimensions = function()
- for _, player in pairs(game.Players:GetPlayers()) do
- if CaveSystem.playerCaveInstances[player] then
- CaveSystem:DespawnPlayerCaves(player)
- end
- end
- local clearRegion = Region3.new(
- Vector3.new(-1000, 1800, -1000),
- Vector3.new(3000, 2200, 2000)
- ):ExpandToGrid(4)
- workspace.Terrain:FillRegion(clearRegion, 4, Enum.Material.Air)
- print("๐ Cleared all instance dimensions")
- end
- _G.EnableCaveSafetyForPlayer = function(player)
- if CaveSystem.playerCaveInstances[player] then
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- CaveSystem:ApplyCaveSafetyMode(player, instance)
- end
- print("๐ก๏ธ Enabled cave safety for", player.Name)
- end
- end
- _G.DisableCaveSafetyForPlayer = function(player)
- CaveSystem:RemoveCaveSafetyMode(player, "all")
- print("๐ก๏ธ Disabled cave safety for", player.Name)
- end
- _G.TeleportPlayerToSafety = function(player)
- if player.Character and CaveSystem.playerCaveInstances[player] then
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- local safePos = CaveSystem:GetSafeSpawnPosition(instance)
- player.Character.HumanoidRootPart.CFrame = CFrame.new(safePos)
- local humanoid = player.Character:FindFirstChild("Humanoid")
- if humanoid then
- humanoid.Health = humanoid.MaxHealth
- end
- print("๐ก๏ธ Teleported", player.Name, "to safety in", caveType, "cave")
- break
- end
- end
- end
- _G.DebugCaveSpawnInfo = function(player)
- if CaveSystem.playerCaveInstances[player] then
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- print("๐ DEBUG:", caveType, "cave for", player.Name)
- print("๐ Cave center position:", instance.config.centerPosition)
- print("๐ Player spawn position:", instance.playerSpawnPosition)
- print("๐ Portal position:", instance.config.portalPosition)
- if instance.mine and instance.mine.House then
- print("๐ Number of rooms:", #instance.mine.House.Rooms)
- for i, room in ipairs(instance.mine.House.Rooms) do
- local roomWidth = room.br.x - room.tl.x + 1
- local roomHeight = room.br.y - room.tl.y + 1
- print("๐ Room", i .. ":", "Size", roomWidth .. "x" .. roomHeight, "at grid", room.tl.x .. "," .. room.tl.y)
- end
- end
- break
- end
- else
- print("๐ No active caves for", player.Name)
- end
- end
- _G.DebugNeighborCountOres = function(player)
- if CaveSystem.playerCaveInstances[player] then
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- local mine = instance.mine
- if mine and mine.House then
- print("๐ NEIGHBOR COUNT ORE DEBUG for", caveType, "cave:")
- print("๐ Logic: 2-3 neighbors = wall cell, 4 neighbors = interior cell")
- print("๐ Corridor Detection: Skip walls adjacent to corridors")
- print("๐ TestOre Integration: Uses Materials/TestOre when available")
- for i, room in ipairs(mine.House.Rooms) do
- local roomWidth = room.br.x - room.tl.x + 1
- local roomHeight = room.br.y - room.tl.y + 1
- print("๐ Room", i, "dimensions:", roomWidth .. "x" .. roomHeight)
- print("๐ Room bounds: (", room.tl.x, room.tl.y, ") to (", room.br.x, room.br.y, ")")
- local wallCells = 0
- local interiorCells = 0
- local corridorAdjacent = 0
- local validWalls = 0
- for x = room.tl.x, room.br.x do
- for y = room.tl.y, room.br.y do
- local neighborCount = room:CountRoomNeighbors(mine, x, y)
- if neighborCount == 2 or neighborCount == 3 then
- wallCells = wallCells + 1
- if room:IsValidOreWallCell(mine, x, y) then
- validWalls = validWalls + 1
- else
- corridorAdjacent = corridorAdjacent + 1
- end
- elseif neighborCount == 4 then
- interiorCells = interiorCells + 1
- end
- end
- end
- print("๐ Wall cells (2-3 neighbors):", wallCells)
- print("๐ Valid wall cells (not adjacent to corridors):", validWalls)
- print("๐ Walls adjacent to corridors (skipped):", corridorAdjacent)
- print("๐ Interior cells (4 neighbors):", interiorCells)
- print("๐ Planned TestOres:", #room.OrePositions)
- for j, oreData in ipairs(room.OrePositions) do
- print(" TestOre", j, "at grid (", oreData.gridX, oreData.gridY, ") facing", oreData.direction, "with", oreData.neighborCount, "neighbors")
- end
- if i >= 3 then break end
- end
- end
- break
- end
- end
- end
- _G.CheckTestOreAvailability = function()
- local materialsFolder = workspace:FindFirstChild("Materials")
- local testOre = materialsFolder and materialsFolder:FindFirstChild("TestOre")
- if testOre then
- print("โ TestOre found in Materials folder")
- print("๐ TestOre properties:")
- print(" - Name:", testOre.Name)
- print(" - Type:", testOre.ClassName)
- if testOre:IsA("Model") then
- print(" - Is Model: true")
- print(" - PrimaryPart:", testOre.PrimaryPart and testOre.PrimaryPart.Name or "None")
- if testOre.PrimaryPart then
- print(" - PrimaryPart Size:", testOre.PrimaryPart.Size)
- print(" - PrimaryPart Material:", testOre.PrimaryPart.Material)
- print(" - PrimaryPart Color:", testOre.PrimaryPart.Color)
- end
- else
- print(" - Is Part: true")
- print(" - Size:", testOre.Size)
- print(" - Material:", testOre.Material)
- print(" - Color:", testOre.Color)
- end
- print(" - Children count:", #testOre:GetChildren())
- for _, child in ipairs(testOre:GetChildren()) do
- print(" - Child:", child.Name, "(" .. child.ClassName .. ")")
- end
- return true
- else
- warn("โ TestOre not found in Materials folder")
- if not materialsFolder then
- warn("โ Materials folder not found in workspace")
- else
- print("๐ Materials folder contents:")
- for _, child in ipairs(materialsFolder:GetChildren()) do
- print(" - " .. child.Name .. " (" .. child.ClassName .. ")")
- end
- end
- return false
- end
- end
- _G.CountCaveTestOres = function(player)
- if not CaveSystem.playerCaveInstances[player] then
- print("๐ No active caves for", player.Name)
- return
- end
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- local folder = instance.folder
- if folder then
- local testOreCount = 0
- local fallbackOreCount = 0
- for _, child in ipairs(folder:GetChildren()) do
- if child.Name:find("CaveOre_") then
- testOreCount = testOreCount + 1
- elseif child.Name:find("FallbackOre_") then
- fallbackOreCount = fallbackOreCount + 1
- end
- end
- print("๐", caveType, "cave for", player.Name .. ":")
- print(" - TestOre clones:", testOreCount)
- print(" - Fallback ores:", fallbackOreCount)
- print(" - Total ores:", testOreCount + fallbackOreCount)
- end
- break
- end
- end
- _G.FindCaveOresByType = function(player, caveType)
- if not CaveSystem.playerCaveInstances[player] or not CaveSystem.playerCaveInstances[player][caveType] then
- print("๐ No", caveType, "cave found for", player.Name)
- return {}
- end
- local instance = CaveSystem.playerCaveInstances[player][caveType]
- local folder = instance.folder
- local ores = {}
- if folder then
- for _, child in ipairs(folder:GetChildren()) do
- if child.Name:find("CaveOre_" .. caveType) or child.Name:find("FallbackOre_" .. caveType) then
- local oreInfo = {
- name = child.Name,
- position = CaveSystem:GetOrePosition(child),
- isTestOre = child.Name:find("CaveOre_") ~= nil
- }
- local caveTypeValue = child:FindFirstChild("CaveType")
- local neighborCountValue = child:FindFirstChild("NeighborCount")
- local gridPositionValue = child:FindFirstChild("GridPosition")
- if caveTypeValue then oreInfo.caveType = caveTypeValue.Value end
- if neighborCountValue then oreInfo.neighborCount = neighborCountValue.Value end
- if gridPositionValue then oreInfo.gridPosition = gridPositionValue.Value end
- table.insert(ores, oreInfo)
- end
- end
- end
- print("๐ Found", #ores, "ores in", caveType, "cave for", player.Name)
- for i, ore in ipairs(ores) do
- local oreType = ore.isTestOre and "TestOre Clone" or "Fallback Ore"
- print(" " .. i .. ".", oreType, "at", ore.position, "neighbors:", ore.neighborCount or "unknown")
- end
- return ores
- end
- _G.CleanupFloatingOres = function(player)
- if not CaveSystem.playerCaveInstances[player] then
- print("๐ No active caves for", player.Name)
- return
- end
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- print("๐งน Manually cleaning floating ores in", caveType, "cave for", player.Name)
- CaveSystem:CleanupFloatingOres(instance)
- break
- end
- end
- _G.DisableOreCleanup = function(player)
- if CaveSystem.playerCaveInstances[player] then
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- instance.oresCleanedUp = true
- print("๐ก๏ธ Disabled ore cleanup for", caveType, "cave - ores will persist")
- end
- end
- end
- _G.EnableOreCleanup = function(player)
- if CaveSystem.playerCaveInstances[player] then
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- instance.oresCleanedUp = false
- print("๐งน Enabled ore cleanup for", caveType, "cave - floating ores will be removed")
- end
- end
- end
- _G.ForceOreCleanup = function(player)
- if CaveSystem.playerCaveInstances[player] then
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- print("๐งน Force cleaning floating ores in", caveType, "cave for", player.Name)
- CaveSystem:CleanupFloatingOres(instance)
- end
- end
- end
- _G.TestRandomOreGeneration = function(player)
- if not CaveSystem.playerCaveInstances[player] then
- print("๐ No active caves for", player.Name)
- return
- end
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- print("๐ฒ Testing random ore generation for", caveType, "cave...")
- -- Show current ore positions
- print("๐ Current ore positions:")
- CaveSystem:ClearExistingOres(instance)
- -- Generate new random positions
- print("๐ฒ Generating new random positions...")
- CaveSystem:RegenerateRandomOres(instance)
- -- Clean up any floating ones
- CaveSystem:CleanupFloatingOres(instance)
- print("โ Random ore generation test complete!")
- break
- end
- end
- _G.GetOreGenerationStats = function(player)
- if not CaveSystem.playerCaveInstances[player] then
- print("๐ No active caves for", player.Name)
- return
- end
- for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
- local mine = instance.mine
- if mine and mine.House then
- print("๐ Ore generation statistics for", caveType, "cave:")
- local totalPlanned = 0
- local totalActual = 0
- -- Count planned ores
- for _, room in ipairs(mine.House.Rooms) do
- totalPlanned = totalPlanned + #room.OrePositions
- print(" Room", room.tl.x .. "," .. room.tl.y, "planned ores:", #room.OrePositions)
- for _, oreData in ipairs(room.OrePositions) do
- if oreData.spawnTime then
- print(" - Generated at:", os.date("%H:%M:%S", oreData.spawnTime))
- end
- end
- end
- -- Count actual ores in world
- local folder = instance.folder
- if folder then
- for _, child in pairs(folder:GetChildren()) do
- if child.Name:find("CaveOre_") or child.Name:find("FallbackOre_") then
- totalActual = totalActual + 1
- end
- end
- end
- print("๐ Total planned ores:", totalPlanned)
- print("๐ Total actual ores:", totalActual)
- print("๐ Success rate:", math.floor(totalActual / math.max(totalPlanned, 1) * 100) .. "%")
- end
- break
- end
- end
- -- Initialize the system
- spawn(function()
- CaveSystem:Initialize()
- end)
- print("๐ DARK CAVE SYSTEM: Instanced dimension system active!")
- print("๐ Each cave type gets its own isolated dimension")
- print("๐ฏ Unlimited space - no terrain conflicts possible")
- print("๐ Main world remains completely untouched")
- print("๐ Use _G.GetInstanceDimensionInfo() to check dimension layout")
- print("๐งน Use _G.ClearAllInstanceDimensions() to clear all instances")
- print("")
- print("๐ก๏ธ CAVE SAFETY SYSTEM: Death prevention active for all cave dimensions!")
- print("๐ก๏ธ Features: Damage immunity, death prevention, safety zones, fall protection")
- print("๐ก๏ธ Use _G.EnableCaveSafetyForPlayer(player) to manually enable safety")
- print("๐ก๏ธ Use _G.TeleportPlayerToSafety(player) for emergency rescue")
- print("")
- print("โ๏ธ NEIGHBOR COUNT ORE SYSTEM: Wall detection using room neighbor logic!")
- print("โ๏ธ Logic: Count room neighbors โ 2-3 neighbors = wall cell โ Place TestOre at edge")
- print("โ๏ธ Position: Grid center + direction * (cellSize / 2) = wall edge")
- print("โ๏ธ TestOre Integration: Uses workspace.Materials.TestOre when available")
- print("โ๏ธ Fallback: Creates basic ores if TestOre not found")
- print("")
- print("๐ DEBUGGING FUNCTIONS:")
- print("๐ Use _G.DebugCaveSpawnInfo(player) to debug cave structure")
- print("๐ Use _G.DebugNeighborCountOres(player) to see neighbor count analysis")
- print("๐ Use _G.CheckTestOreAvailability() to verify TestOre exists")
- print("๐ Use _G.CountCaveTestOres(player) to count ores in player's caves")
- print("๐ Use _G.FindCaveOresByType(player, caveType) to find specific cave ores")
- return CaveSystem
Advertisement
Add Comment
Please, Sign In to add comment