April_The_Sergal

CaveGen

Jul 31st, 2025
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 97.66 KB | None | 0 0
  1. -- File: ServerScriptService/WeeklyCaveSystem.lua
  2. -- Weekly Regenerating Cave System with Neighbor Count Wall Ore Detection
  3. -- SERVER SCRIPT - COMPLETE FINAL VERSION WITH NEIGHBOR COUNT ORE SYSTEM
  4. -- PART 1: Header, Services, Core Classes, and Cave Generation
  5.  
  6. local ReplicatedStorage = game:GetService("ReplicatedStorage")
  7. local DataStoreService = game:GetService("DataStoreService")
  8. local Players = game:GetService("Players")
  9. local RunService = game:GetService("RunService")
  10. local TweenService = game:GetService("TweenService")
  11.  
  12. -- Data Storage
  13. local CaveDataStore = DataStoreService:GetDataStore("WeeklyCaveSystem")
  14. local CAVE_VERSION_KEY = "CaveWeek_"
  15.  
  16. -- Cave System Manager with Instanced Dimensions
  17. local CaveSystem = {
  18.     activeCaves = {},
  19.     playerCaveInstances = {},
  20.     currentWeek = 0,
  21.     caveConfigs = {},
  22.     playerReturnPositions = {},
  23.     caveInstances = {}, -- Store cave dimension instances
  24.     baseCavePosition = Vector3.new(0, 2000, 0), -- HIGH IN THE SKY for safety
  25.     safetyZones = {} -- Track safety zones for each cave - SAFETY SYSTEM
  26. }
  27.  
  28. -- ============================================================================
  29. -- NUCLEAR READONLY TABLE FIX
  30. -- ============================================================================
  31.  
  32. local function FORCE_MUTABLE_TABLE(original)
  33.     local fresh = {}
  34.     if type(original) == "table" then
  35.         for k, v in pairs(original) do
  36.             fresh[k] = v
  37.         end
  38.     end
  39.     return fresh
  40. end
  41.  
  42. local function FORCE_SET_TABLE_VALUE(tbl, key, value)
  43.     local success1 = pcall(function()
  44.         tbl[key] = value
  45.     end)
  46.     if success1 then return tbl end
  47.  
  48.     local success2 = pcall(function()
  49.         rawset(tbl, key, value)
  50.     end)
  51.     if success2 then return tbl end
  52.  
  53.     local fresh = {}
  54.     for k, v in pairs(tbl) do
  55.         fresh[k] = v
  56.     end
  57.     fresh[key] = value
  58.     return fresh
  59. end
  60.  
  61. local function cloneTable(t)
  62.     if type(t) ~= "table" then return t end
  63.     local copy = {}
  64.     for i, v in pairs(t) do
  65.         copy[i] = v
  66.     end
  67.     return copy
  68. end
  69.  
  70. -- ============================================================================
  71. -- MINE CELL CLASS
  72. -- ============================================================================
  73.  
  74. local MineCell = {}
  75. MineCell.__index = MineCell
  76.  
  77. function MineCell.new(x, y)
  78.     local self = {}
  79.     for k, v in pairs(MineCell) do
  80.         if type(v) == "function" then
  81.             self[k] = v
  82.         end
  83.     end
  84.  
  85.     self.x = x
  86.     self.y = y
  87.     self.Visited = false
  88.     self.isRoom = false
  89.     self.availDirs = {}
  90.     self.availDirs.N = true
  91.     self.availDirs.E = true
  92.     self.availDirs.S = true
  93.     self.availDirs.W = true
  94.     self.closeToRoom = false
  95.     self.Door = false
  96.     self.Filled = false
  97.     self.isPath = false
  98.     self.outRef = nil
  99.     self.onlyDir = nil
  100.     self.hasSupport = false
  101.     self.hasLighting = false
  102.     self.hasOre = false
  103.  
  104.     return self
  105. end
  106.  
  107. function MineCell:GetUnvisitedNeighbors(mine)
  108.     local neighbors = {}
  109.     local map = mine.Map
  110.     local sX, sY = mine.sX, mine.sY
  111.  
  112.     local directions = {
  113.         {dir = "N", dx = 0, dy = 1},
  114.         {dir = "S", dx = 0, dy = -1},
  115.         {dir = "E", dx = 1, dy = 0},
  116.         {dir = "W", dx = -1, dy = 0}
  117.     }
  118.  
  119.     for _, dirInfo in ipairs(directions) do
  120.         local nx = self.x + dirInfo.dx
  121.         local ny = self.y + dirInfo.dy
  122.  
  123.         if nx >= 1 and nx <= sX and ny >= 1 and ny <= sY then
  124.             local neighbor = map[nx][ny]
  125.             if not neighbor.Visited and not neighbor.isRoom and self.availDirs[dirInfo.dir] then
  126.                 table.insert(neighbors, {
  127.                     Dir = dirInfo.dir,
  128.                     Cell = neighbor
  129.                 })
  130.             end
  131.         end
  132.     end
  133.  
  134.     return neighbors
  135. end
  136.  
  137. function MineCell:GetNonRoomNeighbors(mine)
  138.     local neighbors = {}
  139.     local map = mine.Map
  140.     local sX, sY = mine.sX, mine.sY
  141.  
  142.     local directions = {
  143.         {dir = "N", dx = 0, dy = 1},
  144.         {dir = "S", dx = 0, dy = -1},
  145.         {dir = "E", dx = 1, dy = 0},
  146.         {dir = "W", dx = -1, dy = 0}
  147.     }
  148.  
  149.     for _, dirInfo in ipairs(directions) do
  150.         local nx = self.x + dirInfo.dx
  151.         local ny = self.y + dirInfo.dy
  152.  
  153.         if nx >= 1 and nx <= sX and ny >= 1 and ny <= sY then
  154.             local neighbor = map[nx][ny]
  155.             if self.availDirs[dirInfo.dir] then
  156.                 table.insert(neighbors, {
  157.                     Dir = dirInfo.dir,
  158.                     Cell = neighbor
  159.                 })
  160.             end
  161.         end
  162.     end
  163.  
  164.     return neighbors
  165. end
  166.  
  167. function MineCell:getCellOfDirection(map, direction)
  168.     local dx, dy = 0, 0
  169.     if direction == "N" then dy = 1
  170.     elseif direction == "S" then dy = -1
  171.     elseif direction == "E" then dx = 1
  172.     elseif direction == "W" then dx = -1
  173.     end
  174.  
  175.     local nx, ny = self.x + dx, self.y + dy
  176.     return map[nx] and map[nx][ny]
  177. end
  178.  
  179. function MineCell:DelInBetween(otherCell, direction)
  180.     self.availDirs = FORCE_SET_TABLE_VALUE(self.availDirs, direction, true)
  181.     local oppositeDir = {N = "S", S = "N", E = "W", W = "E"}
  182.     if otherCell and otherCell.availDirs then
  183.         local oppDir = oppositeDir[direction]
  184.         if oppDir then
  185.             otherCell.availDirs = FORCE_SET_TABLE_VALUE(otherCell.availDirs, oppDir, true)
  186.         end
  187.     end
  188. end
  189.  
  190. -- ============================================================================
  191. -- MINE CLASS
  192. -- ============================================================================
  193.  
  194. local Mine = {}
  195. Mine.__index = Mine
  196.  
  197. function Mine.new(sizeX, sizeY)
  198.     if sizeX < 1 or sizeY < 1 then
  199.         return nil
  200.     end
  201.  
  202.     local self = {}
  203.     for k, v in pairs(Mine) do
  204.         if type(v) == "function" then
  205.             self[k] = v
  206.         end
  207.     end
  208.  
  209.     self.Map = {}
  210.     self.sX = sizeX
  211.     self.sY = sizeY
  212.     self.unfixedCells = {}
  213.  
  214.     for x = 1, sizeX do
  215.         self.Map[x] = {}
  216.         for y = 1, sizeY do
  217.             self.Map[x][y] = MineCell.new(x, y)
  218.         end
  219.     end
  220.  
  221.     return self
  222. end
  223.  
  224. function Mine:RecursiveBacktracker()
  225.     print("โ›๏ธ Running recursive backtracker maze algorithm...")
  226.  
  227.     self.unfixedCells = {}
  228.     local uCells = self.unfixedCells
  229.     local sX, sY = self.sX, self.sY
  230.     local Map = self.Map
  231.  
  232.     for i = 1, sX do
  233.         for j = 1, sY do
  234.             local cell = Map[i][j]
  235.             if not cell.isRoom then
  236.                 table.insert(uCells, cell)
  237.             end
  238.         end
  239.     end
  240.  
  241.     while #uCells > 0 do
  242.         local curCell = uCells[#uCells]
  243.         curCell.Visited = true
  244.  
  245.         local neighbors = curCell:GetUnvisitedNeighbors(self)
  246.         if #neighbors > 0 then
  247.             local pickedNeighbor = neighbors[math.random(1, #neighbors)]
  248.             local relDir, oCell = pickedNeighbor.Dir, pickedNeighbor.Cell
  249.  
  250.             curCell:DelInBetween(oCell, relDir)
  251.             table.insert(uCells, oCell)
  252.         else
  253.             table.remove(uCells)
  254.         end
  255.     end
  256.  
  257.     print("โ›๏ธ Maze algorithm completed")
  258. end
  259.  
  260. function Mine:wipeFilled()
  261.     for x = 1, self.sX do
  262.         for y = 1, self.sY do
  263.             self.Map[x][y].Filled = false
  264.         end
  265.     end
  266. end
  267.  
  268. function Mine.Search(mine, origCell)
  269.     mine:wipeFilled()
  270.     local cPath = nil
  271.  
  272.     local function Search(startCell, startPath)
  273.         local searchQueue = {{cell = startCell, path = startPath}}
  274.         local processed = {}
  275.         local maxIterations = 10000
  276.         local iterations = 0
  277.  
  278.         while #searchQueue > 0 and iterations < maxIterations do
  279.             iterations = iterations + 1
  280.             local batchSize = 50
  281.             local currentBatch = 0
  282.  
  283.             while #searchQueue > 0 and currentBatch < batchSize do
  284.                 currentBatch = currentBatch + 1
  285.  
  286.                 local current = table.remove(searchQueue, 1)
  287.                 local tCell = current.cell
  288.                 local Path = current.path
  289.  
  290.                 local cellKey = tCell.x .. "," .. tCell.y
  291.                 if processed[cellKey] then
  292.                     continue
  293.                 end
  294.                 processed[cellKey] = true
  295.  
  296.                 if tCell.isRoom then
  297.                     if tCell.outRef ~= origCell.outRef then
  298.                         continue
  299.                     end
  300.                 end
  301.  
  302.                 local newPath = {}
  303.                 for i, v in ipairs(Path) do
  304.                     newPath[i] = v
  305.                 end
  306.                 table.insert(newPath, tCell)
  307.                 tCell.Filled = true
  308.  
  309.                 if tCell.isRoom then
  310.                     continue
  311.                 end
  312.  
  313.                 local neighbors = tCell:GetNonRoomNeighbors(mine)
  314.  
  315.                 for _, v in ipairs(neighbors) do
  316.                     local relDir, cell = v.Dir, v.Cell
  317.                     if cell.Door and origCell.outRef ~= cell.outRef then
  318.                         table.insert(newPath, cell)
  319.                         cPath = newPath
  320.                         return
  321.                     end
  322.                 end
  323.  
  324.                 if not cPath then
  325.                     for _, v in ipairs(neighbors) do
  326.                         local cell = v.Cell
  327.                         local neighborKey = cell.x .. "," .. cell.y
  328.                         if not processed[neighborKey] and (not cell.Filled or cell.isPath) then
  329.                             table.insert(searchQueue, {cell = cell, path = newPath})
  330.                         end
  331.                     end
  332.                 end
  333.             end
  334.  
  335.             if iterations % 100 == 0 then
  336.                 wait()
  337.             end
  338.         end
  339.  
  340.         if iterations >= maxIterations then
  341.             warn("โš ๏ธ Search iteration limit reached, may have incomplete pathfinding")
  342.         end
  343.     end
  344.  
  345.     local look = origCell.Door
  346.     local lookCell = origCell:getCellOfDirection(mine.Map, look)
  347.  
  348.     if lookCell then
  349.         Search(lookCell, {origCell})
  350.     end
  351.  
  352.     if cPath then
  353.         for _, v in ipairs(cPath) do
  354.             v.isPath = true
  355.         end
  356.     end
  357. end
  358.  
  359. function Mine:searchForDoor(house)
  360.     local doors = house.Doors
  361.     local oppDir = {W = "E", E = "W", S = "N", N = "S"}
  362.  
  363.     for _, v in ipairs(doors) do
  364.         if not v.Filled then
  365.             Mine.Search(self, v)
  366.         end
  367.     end
  368.  
  369.     for _, v in ipairs(doors) do
  370.         if not v.isPath then
  371.             local look = v.Door
  372.             local lookCell = v:getCellOfDirection(self.Map, look)
  373.  
  374.             if v.availDirs then
  375.                 v.availDirs = FORCE_SET_TABLE_VALUE(v.availDirs, look, true)
  376.             end
  377.  
  378.             if lookCell and lookCell.availDirs then
  379.                 lookCell.availDirs = FORCE_SET_TABLE_VALUE(lookCell.availDirs, oppDir[look], true)
  380.             end
  381.         end
  382.     end
  383. end
  384.  
  385. -- ============================================================================
  386. -- MINE ROOM CLASS WITH NEIGHBOR COUNT ORE GENERATION
  387. -- ============================================================================
  388.  
  389. local MineRoom = {}
  390. MineRoom.__index = MineRoom
  391.  
  392. function MineRoom.new(mine, x1, y1, x2, y2)
  393.     local self = {}
  394.     for k, v in pairs(MineRoom) do
  395.         if type(v) == "function" then
  396.             self[k] = v
  397.         end
  398.     end
  399.  
  400.     local sX = mine.sX
  401.     local sY = mine.sY
  402.     local roomBorderSpace = 2
  403.  
  404.     self.ref = mine
  405.     self.tl = {x = x1, y = y1}
  406.     self.br = {x = x2, y = y2}
  407.     self.Outsiders = {}
  408.     self.OrePositions = {} -- Store ore positions for this room
  409.  
  410.     local Map = mine.Map
  411.  
  412.     for x = math.max(1, x1 - roomBorderSpace), math.min(x2 + roomBorderSpace, sX) do
  413.         for y = math.max(1, y1 - roomBorderSpace), math.min(y2 + roomBorderSpace, sY) do
  414.             local cell = Map[x][y]
  415.  
  416.             if not (x < x1 or y < y1 or x > x2 or y > y2) then
  417.                 cell.Visited = true
  418.                 cell.isRoom = true
  419.                 cell.hasLighting = true
  420.  
  421.                 cell.availDirs = {}
  422.                 cell.availDirs.N = true
  423.                 cell.availDirs.E = true
  424.                 cell.availDirs.S = true
  425.                 cell.availDirs.W = true
  426.  
  427.                 if x ~= x1 then cell.availDirs.W = nil end
  428.                 if x ~= x2 then cell.availDirs.E = nil end
  429.                 if y ~= y1 then cell.availDirs.S = nil end
  430.                 if y ~= y2 then cell.availDirs.N = nil end
  431.             end
  432.  
  433.             cell.closeToRoom = true
  434.  
  435.             if x >= 1 and y >= 1 and x <= sX and y <= sY then
  436.                 if x > 1 and y > 1 and x < sX and y < sY then
  437.                     local isOutsider = (x == x1 and y >= y1 and y <= y2) or
  438.                         (y == y1 and x >= x1 and x <= x2) or
  439.                         (x == x2 and y >= y1 and y <= y2) or
  440.                         (y == y2 and x >= x1 and x <= x2)
  441.  
  442.                     if isOutsider then
  443.                         table.insert(self.Outsiders, cell)
  444.                         cell.outRef = self
  445.                     end
  446.                 end
  447.             end
  448.         end
  449.     end
  450.  
  451.     -- NEW: Generate ore positions during room creation using neighbor count
  452.     self:GenerateRoomOres(mine)
  453.  
  454.     return self
  455. end
  456.  
  457. -- NEW: Generate ores during room creation using neighbor count logic - RANDOMIZED
  458. function MineRoom:GenerateRoomOres(mine)
  459.     print("โ›๏ธ Generating ores for room at", self.tl.x, self.tl.y, "to", self.br.x, self.br.y)
  460.  
  461.     -- Get room dimensions
  462.     local roomWidth = self.br.x - self.tl.x + 1
  463.     local roomHeight = self.br.y - self.tl.y + 1
  464.  
  465.     print("๐Ÿ” Room dimensions:", roomWidth, "x", roomHeight)
  466.  
  467.     -- Use current time + room position for unique randomization each visit
  468.     local uniqueSeed = os.time() + self.tl.x * 1000 + self.tl.y * 100
  469.     math.randomseed(uniqueSeed)
  470.  
  471.     -- Loop through ALL cells in the room
  472.     for x = self.tl.x, self.br.x do
  473.         for y = self.tl.y, self.br.y do
  474.             -- 15% chance of creating ore vein (increased from 10% for more ores)
  475.             if math.random() < 0.15 then
  476.                 -- Check if this is a valid wall cell for ore placement
  477.                 if self:IsValidOreWallCell(mine, x, y) then
  478.                     -- Get the direction this wall faces
  479.                     local wallDirection = self:GetWallDirection(mine, x, y)
  480.                     local neighborCount = self:CountRoomNeighbors(mine, x, y)
  481.  
  482.                     if wallDirection then
  483.                         -- Store ore position with grid coordinates and direction info
  484.                         local oreData = {
  485.                             gridX = x,
  486.                             gridY = y,
  487.                             direction = wallDirection,
  488.                             neighborCount = neighborCount,
  489.                             roomWidth = roomWidth,
  490.                             roomHeight = roomHeight,
  491.                             randomSeed = uniqueSeed, -- Store seed for debugging
  492.                             spawnTime = os.time() -- Store when this was generated
  493.                         }
  494.                         table.insert(self.OrePositions, oreData)
  495.                         print("โ›๏ธ Planned ore at grid", x, y, "direction:", wallDirection, "neighbors:", neighborCount, "seed:", uniqueSeed)
  496.                     end
  497.                 end
  498.             end
  499.         end
  500.     end
  501.  
  502.     print("โ›๏ธ Planned", #self.OrePositions, "RANDOMIZED ore veins for this room")
  503. end
  504.  
  505. -- NEW: Check if a cell is a valid wall cell for ore placement
  506. function MineRoom:IsValidOreWallCell(mine, gridX, gridY)
  507.     -- Must be within room bounds
  508.     if gridX < self.tl.x or gridX > self.br.x or gridY < self.tl.y or gridY > self.br.y then
  509.         return false
  510.     end
  511.  
  512.     local neighborCount = self:CountRoomNeighbors(mine, gridX, gridY)
  513.  
  514.     -- Only cells with 2 or 3 room neighbors are wall cells
  515.     if neighborCount ~= 2 and neighborCount ~= 3 then
  516.         return false
  517.     end
  518.  
  519.     -- Check that adjacent non-room cells are NOT corridors/paths
  520.     local directions = {
  521.         {dx = 0, dy = 1},   -- North
  522.         {dx = 0, dy = -1},  -- South
  523.         {dx = 1, dy = 0},   -- East
  524.         {dx = -1, dy = 0}   -- West
  525.     }
  526.  
  527.     for _, dir in ipairs(directions) do
  528.         local checkX = gridX + dir.dx
  529.         local checkY = gridY + dir.dy
  530.  
  531.         -- If this direction is outside room bounds, check what's there
  532.         if checkX < self.tl.x or checkX > self.br.x or checkY < self.tl.y or checkY > self.br.y then
  533.             -- Check if the adjacent cell is a corridor/path
  534.             if checkX >= 1 and checkX <= mine.sX and checkY >= 1 and checkY <= mine.sY then
  535.                 local adjacentCell = mine.Map[checkX][checkY]
  536.  
  537.                 -- If adjacent cell is a path/corridor, this is not a valid wall for ores
  538.                 if adjacentCell.isPath then
  539.                     print("๐Ÿšซ Skipping ore at", gridX, gridY, "- adjacent to corridor at", checkX, checkY)
  540.                     return false
  541.                 end
  542.             end
  543.         end
  544.     end
  545.  
  546.     return true
  547. end
  548.  
  549. -- NEW: Count room neighbors for a grid cell
  550. function MineRoom:CountRoomNeighbors(mine, gridX, gridY)
  551.     local count = 0
  552.  
  553.     -- Check all 4 cardinal directions
  554.     local directions = {
  555.         {dx = 0, dy = 1},  -- North
  556.         {dx = 0, dy = -1}, -- South
  557.         {dx = 1, dy = 0},  -- East
  558.         {dx = -1, dy = 0}  -- West
  559.     }
  560.  
  561.     for _, dir in ipairs(directions) do
  562.         local checkX = gridX + dir.dx
  563.         local checkY = gridY + dir.dy
  564.  
  565.         -- Check if neighbor is within room bounds
  566.         if checkX >= self.tl.x and checkX <= self.br.x and
  567.             checkY >= self.tl.y and checkY <= self.br.y then
  568.             count = count + 1
  569.         end
  570.     end
  571.  
  572.     return count
  573. end
  574.  
  575. -- IMPROVED: Get wall direction based on which neighbors are missing (more accurate)
  576. function MineRoom:GetWallDirection(mine, gridX, gridY)
  577.     -- Check which directions DON'T have room neighbors
  578.     local missingDirections = {}
  579.     local solidDirections = {}  -- Directions facing solid walls (not corridors)
  580.  
  581.     local directions = {
  582.         {name = "north", dx = 0, dy = 1},
  583.         {name = "south", dx = 0, dy = -1},
  584.         {name = "east", dx = 1, dy = 0},
  585.         {name = "west", dx = -1, dy = 0}
  586.     }
  587.  
  588.     for _, dir in ipairs(directions) do
  589.         local checkX = gridX + dir.dx
  590.         local checkY = gridY + dir.dy
  591.  
  592.         -- If neighbor is outside room bounds, this direction faces outward
  593.         if checkX < self.tl.x or checkX > self.br.x or
  594.             checkY < self.tl.y or checkY > self.br.y then
  595.  
  596.             table.insert(missingDirections, dir.name)
  597.  
  598.             -- Check if this direction faces a solid wall (not a corridor)
  599.             if checkX >= 1 and checkX <= mine.sX and checkY >= 1 and checkY <= mine.sY then
  600.                 local adjacentCell = mine.Map[checkX][checkY]
  601.  
  602.                 -- If adjacent cell is NOT a path/corridor, it's a solid wall
  603.                 if not adjacentCell.isPath and not adjacentCell.isRoom then
  604.                     table.insert(solidDirections, dir.name)
  605.                 end
  606.             else
  607.                 -- Outside mine bounds = solid wall
  608.                 table.insert(solidDirections, dir.name)
  609.             end
  610.         end
  611.     end
  612.  
  613.     -- Prefer directions that face solid walls over corridors
  614.     if #solidDirections > 0 then
  615.         return solidDirections[1]
  616.     elseif #missingDirections > 0 then
  617.         return missingDirections[1]
  618.     end
  619.  
  620.     return nil
  621. end
  622.  
  623. -- ============================================================================
  624. -- MINE HOUSE CLASS
  625. -- ============================================================================
  626.  
  627. local MineHouse = {}
  628. MineHouse.__index = MineHouse
  629.  
  630. function MineHouse.new(mine)
  631.     local self = {}
  632.     for k, v in pairs(MineHouse) do
  633.         if type(v) == "function" then
  634.             self[k] = v
  635.         end
  636.     end
  637.  
  638.     self.Mine = mine
  639.     self.Rooms = {}
  640.     self.Doors = {}
  641.     return self
  642. end
  643.  
  644. function MineHouse:add(x1, y1, x2, y2)
  645.     table.insert(self.Rooms, MineRoom.new(self.Mine, x1, y1, x2, y2))
  646. end
  647.  
  648. function MineHouse:tryRoom()
  649.     local maxTries = 100
  650.     local maxRooms = 8
  651.     local minRoomSize = {x = 4, y = 4}
  652.     local maxRoomSize = {x = 10, y = 10}
  653.     local borderSpace = 5
  654.  
  655.     if #self.Rooms >= maxRooms then
  656.         return false
  657.     end
  658.  
  659.     for attempt = 1, maxTries do
  660.         local roomWidth = math.random(minRoomSize.x, maxRoomSize.x)
  661.         local roomHeight = math.random(minRoomSize.y, maxRoomSize.y)
  662.  
  663.         local x1 = math.random(borderSpace, self.Mine.sX - roomWidth - borderSpace)
  664.         local y1 = math.random(borderSpace, self.Mine.sY - roomHeight - borderSpace)
  665.         local x2 = x1 + roomWidth - 1
  666.         local y2 = y1 + roomHeight - 1
  667.  
  668.         local canPlace = true
  669.         for x = math.max(1, x1 - borderSpace), math.min(self.Mine.sX, x2 + borderSpace) do
  670.             for y = math.max(1, y1 - borderSpace), math.min(self.Mine.sY, y2 + borderSpace) do
  671.                 if self.Mine.Map[x][y].isRoom then
  672.                     canPlace = false
  673.                     break
  674.                 end
  675.             end
  676.             if not canPlace then break end
  677.         end
  678.  
  679.         if canPlace then
  680.             self:add(x1, y1, x2, y2)
  681.             print("๐Ÿ›๏ธ Created mine room", #self.Rooms, "at", x1, y1, "size", roomWidth, "x", roomHeight)
  682.             return true
  683.         end
  684.     end
  685.  
  686.     return false
  687. end
  688.  
  689. -- ============================================================================
  690. -- WEEKLY CAVE GENERATION
  691. -- ============================================================================
  692.  
  693. function CaveSystem:GetCurrentWeek()
  694.     local secondsSinceEpoch = os.time()
  695.     local daysSinceEpoch = math.floor(secondsSinceEpoch / 86400)
  696.     return math.floor(daysSinceEpoch / 7)
  697. end
  698.  
  699. function CaveSystem:ShouldRegenerateCaves()
  700.     local currentWeek = self:GetCurrentWeek()
  701.     if self.currentWeek ~= currentWeek then
  702.         print("๐Ÿ”„ New week detected:", currentWeek, "vs stored:", self.currentWeek)
  703.         return true
  704.     end
  705.     return false
  706. end
  707.  
  708. function CaveSystem:GenerateWeeklyCaves()
  709.     local currentWeek = self:GetCurrentWeek()
  710.     print("๐Ÿ”๏ธ Generating caves for week", currentWeek)
  711.  
  712.     self:ClearAllCaves()
  713.  
  714.     local caveConfigs = {}
  715.     local caveTypes = {"Crystal", "Underground", "Lava", "Ice", "Ancient"}
  716.  
  717.     for i = 1, #caveTypes do
  718.         local caveConfig = self:GenerateCaveConfig(caveTypes[i], currentWeek + i)
  719.         caveConfigs[caveTypes[i]] = caveConfig
  720.         print("โšก Generated", caveTypes[i], "cave config")
  721.     end
  722.  
  723.     self.currentWeek = currentWeek
  724.     self.caveConfigs = caveConfigs
  725.     print("โœ… Cave configurations ready for week", currentWeek)
  726.  
  727.     return caveConfigs
  728. end
  729.  
  730. function CaveSystem:GetCaveTypeProperties(caveType)
  731.     local properties = {
  732.         Crystal = {
  733.             basePosition = {x = 1000, y = 2000, z = 1000},
  734.             instanceOffset = Vector3.new(0, 0, 0),
  735.             wallMaterial = "Rock",
  736.             wallColor = {r = 0.4, g = 0.5, b = 0.6},
  737.             floorMaterial = "Cobblestone",
  738.             infrastructure = {
  739.                 lights = true,
  740.                 cables = true,
  741.                 woodenSupports = true,
  742.                 railTracks = false
  743.             },
  744.             lighting = {brightness = 1.0, color = {r = 0.6, g = 0.7, b = 0.9}, range = 18},
  745.             corridorWidth = 16,
  746.             corridorHeight = 16,
  747.             roomSize = {min = 30, max = 60}
  748.         },
  749.  
  750.         Underground = {
  751.             basePosition = {x = 1200, y = 2000, z = 800},
  752.             instanceOffset = Vector3.new(1000, 0, 0),
  753.             wallMaterial = "Rock",
  754.             wallColor = {r = 0.4, g = 0.35, b = 0.3},
  755.             floorMaterial = "Concrete",
  756.             infrastructure = {
  757.                 lights = true,
  758.                 cables = true,
  759.                 woodenSupports = true,
  760.                 railTracks = true
  761.             },
  762.             lighting = {brightness = 0.8, color = {r = 1, g = 0.8, b = 0.6}, range = 15},
  763.             corridorWidth = 18,
  764.             corridorHeight = 18,
  765.             roomSize = {min = 40, max = 80}
  766.         },
  767.  
  768.         Lava = {
  769.             basePosition = {x = 800, y = 2000, z = 1200},
  770.             instanceOffset = Vector3.new(2000, 0, 0),
  771.             wallMaterial = "Rock",
  772.             wallColor = {r = 0.6, g = 0.2, b = 0.1},
  773.             floorMaterial = "Basalt",
  774.             infrastructure = {
  775.                 lights = true,
  776.                 cables = true,
  777.                 woodenSupports = false,
  778.                 metalSupports = true,
  779.                 railTracks = false
  780.             },
  781.             lighting = {brightness = 1.2, color = {r = 1, g = 0.5, b = 0.2}, range = 20},
  782.             corridorWidth = 20,
  783.             corridorHeight = 20,
  784.             roomSize = {min = 35, max = 70}
  785.         },
  786.  
  787.         Ice = {
  788.             basePosition = {x = 600, y = 2000, z = 600},
  789.             instanceOffset = Vector3.new(0, 0, 1000),
  790.             wallMaterial = "Ice",
  791.             wallColor = {r = 0.6, g = 0.7, b = 0.8},
  792.             floorMaterial = "Glacier",
  793.             infrastructure = {
  794.                 lights = true,
  795.                 cables = true,
  796.                 woodenSupports = false,
  797.                 iceSupports = true,
  798.                 railTracks = false
  799.             },
  800.             lighting = {brightness = 0.7, color = {r = 0.7, g = 0.8, b = 1}, range = 12},
  801.             corridorWidth = 12,
  802.             corridorHeight = 16,
  803.             roomSize = {min = 25, max = 50}
  804.         },
  805.  
  806.         Ancient = {
  807.             basePosition = {x = 1400, y = 2000, z = 1400},
  808.             instanceOffset = Vector3.new(1000, 0, 1000),
  809.             wallMaterial = "Cobblestone",
  810.             wallColor = {r = 0.3, g = 0.28, b = 0.25},
  811.             floorMaterial = "Marble",
  812.             infrastructure = {
  813.                 lights = false,
  814.                 magicalLights = true,
  815.                 cables = false,
  816.                 stonePillars = true,
  817.                 railTracks = false
  818.             },
  819.             lighting = {brightness = 0.6, color = {r = 0.5, g = 0.7, b = 0.5}, range = 10},
  820.             corridorWidth = 22,
  821.             corridorHeight = 24,
  822.             roomSize = {min = 50, max = 100}
  823.         }
  824.     }
  825.  
  826.     return properties[caveType] or properties.Underground
  827. end
  828.  
  829. function CaveSystem:GenerateCaveConfig(caveType, seed)
  830.     math.randomseed(seed)
  831.  
  832.     local properties = self:GetCaveTypeProperties(caveType)
  833.  
  834.     local config = {
  835.         type = caveType,
  836.         seed = seed,
  837.         properties = properties,
  838.         centerPosition = Vector3.new(
  839.             properties.basePosition.x,
  840.             properties.basePosition.y,
  841.             properties.basePosition.z
  842.         ),
  843.         size = Vector3.new(400, 160, 400),
  844.         portalPosition = Vector3.new(
  845.             properties.basePosition.x,
  846.             properties.basePosition.y + 30,
  847.             properties.basePosition.z
  848.         ),
  849.         hiddenPassages = self:GenerateHiddenPassages(seed, properties),
  850.         generatedAt = os.time()
  851.     }
  852.  
  853.     return config
  854. end
  855.  
  856. function CaveSystem:GenerateHiddenPassages(seed, properties)
  857.     math.randomseed(seed)
  858.     local passages = {}
  859.     local numPassages = math.random(4, 8)
  860.  
  861.     for i = 1, numPassages do
  862.         local passage = {
  863.             id = "passage_" .. i,
  864.             position = Vector3.new(
  865.                 properties.basePosition.x + (math.random() - 0.5) * 300,
  866.                 properties.basePosition.y + math.random(-30, 30),
  867.                 properties.basePosition.z + (math.random() - 0.5) * 300
  868.             ),
  869.             crackSize = Vector3.new(math.random(8, 16), math.random(12, 20), 2),
  870.             leadsTo = {
  871.                 position = Vector3.new(
  872.                     properties.basePosition.x + (math.random() - 0.5) * 200,
  873.                     properties.basePosition.y - math.random(20, 60),
  874.                     properties.basePosition.z + (math.random() - 0.5) * 200
  875.                 ),
  876.                 size = Vector3.new(math.random(40, 80), math.random(25, 50), math.random(40, 80)),
  877.                 lootSpawns = math.random(3, 8),
  878.                 difficulty = math.random(1, 3)
  879.             },
  880.             requiredTool = "CaveDetector",
  881.             broken = false
  882.         }
  883.         table.insert(passages, passage)
  884.     end
  885.  
  886.     return passages
  887. end
  888.  
  889. -- ============================================================================
  890. -- CAVE SAFETY SYSTEM - PREVENT ALL DEATHS
  891. -- ============================================================================
  892.  
  893. function CaveSystem:CreateSafeSpawnZone(caveInstance)
  894.     local config = caveInstance.config
  895.     local folder = caveInstance.folder
  896.     local player = caveInstance.player
  897.  
  898.     local spawnPos = caveInstance.playerSpawnPosition or Vector3.new(config.centerPosition.X, config.centerPosition.Y - 5, config.centerPosition.Z)
  899.  
  900.     print("๐Ÿ›ก๏ธ Creating floor-level safety zone at:", spawnPos)
  901.  
  902.     local safetyPlatform = Instance.new("Part")
  903.     safetyPlatform.Name = "SafetyPlatform_" .. player.Name
  904.     safetyPlatform.Size = Vector3.new(100, 1, 100)
  905.     safetyPlatform.Position = Vector3.new(spawnPos.X, spawnPos.Y - 2, spawnPos.Z)
  906.     safetyPlatform.Material = Enum.Material.ForceField
  907.     safetyPlatform.Transparency = 1
  908.     safetyPlatform.CanCollide = true
  909.     safetyPlatform.Anchored = true
  910.     safetyPlatform.Parent = folder
  911.  
  912.     local killZoneDetector = Instance.new("Part")
  913.     killZoneDetector.Name = "KillZoneDetector_" .. player.Name
  914.     killZoneDetector.Size = Vector3.new(1000, 10, 1000)
  915.     killZoneDetector.Position = Vector3.new(spawnPos.X, spawnPos.Y - 30, spawnPos.Z)
  916.     killZoneDetector.Transparency = 1
  917.     killZoneDetector.CanCollide = false
  918.     killZoneDetector.Anchored = true
  919.     killZoneDetector.Parent = folder
  920.  
  921.     killZoneDetector.Touched:Connect(function(hit)
  922.         local character = hit.Parent
  923.         if character == player.Character and character:FindFirstChild("HumanoidRootPart") then
  924.             character.HumanoidRootPart.CFrame = CFrame.new(spawnPos)
  925.             local humanoid = character:FindFirstChild("Humanoid")
  926.             if humanoid then
  927.                 humanoid.Health = humanoid.MaxHealth
  928.             end
  929.             if _G.ShowToast then
  930.                 _G.ShowToast("๐Ÿ›ก๏ธ Returned to cave floor", "Warning")
  931.             end
  932.         end
  933.     end)
  934.  
  935.     if not self.safetyZones[player] then
  936.         self.safetyZones[player] = {}
  937.     end
  938.     self.safetyZones[player][caveInstance.config.type] = {
  939.         platform = safetyPlatform,
  940.         detector = killZoneDetector,
  941.         safeSpawn = spawnPos
  942.     }
  943.  
  944.     print("๐Ÿ›ก๏ธ Created floor-level safety zone for", player.Name, "at", spawnPos)
  945. end
  946.  
  947. function CaveSystem:ApplyCaveSafetyMode(player, caveInstance)
  948.     if not player.Character then return end
  949.  
  950.     local humanoid = player.Character:FindFirstChild("Humanoid")
  951.     if not humanoid then return end
  952.  
  953.     local safetySystem = {
  954.         player = player,
  955.         caveType = caveInstance.config.type,
  956.         originalHealth = humanoid.MaxHealth,
  957.         isActive = true
  958.     }
  959.  
  960.     local damageConnection = humanoid.HealthChanged:Connect(function(health)
  961.         if safetySystem.isActive and health < humanoid.MaxHealth then
  962.             humanoid.Health = humanoid.MaxHealth
  963.         end
  964.     end)
  965.  
  966.     local deathConnection = humanoid.Died:Connect(function()
  967.         if safetySystem.isActive then
  968.             wait(0.1)
  969.             if player.Character and caveInstance.playerSpawnPosition then
  970.                 local newCharacter = player.Character
  971.                 if newCharacter:FindFirstChild("HumanoidRootPart") then
  972.                     newCharacter.HumanoidRootPart.CFrame = CFrame.new(caveInstance.playerSpawnPosition)
  973.                 end
  974.                 local newHumanoid = newCharacter:FindFirstChild("Humanoid")
  975.                 if newHumanoid then
  976.                     newHumanoid.Health = newHumanoid.MaxHealth
  977.                 end
  978.                 if _G.ShowToast then
  979.                     _G.ShowToast("๐Ÿ›ก๏ธ Cave safety mode - death prevented!", "Success")
  980.                 end
  981.             end
  982.         end
  983.     end)
  984.  
  985.     local healthMonitor = game:GetService("RunService").Heartbeat:Connect(function()
  986.         if safetySystem.isActive and player.Character then
  987.             local currentHumanoid = player.Character:FindFirstChild("Humanoid")
  988.             if currentHumanoid and currentHumanoid.Health < currentHumanoid.MaxHealth then
  989.                 currentHumanoid.Health = currentHumanoid.MaxHealth
  990.             end
  991.         end
  992.     end)
  993.  
  994.     safetySystem.connections = {damageConnection, deathConnection, healthMonitor}
  995.     caveInstance.safetySystem = safetySystem
  996.  
  997.     print("๐Ÿ›ก๏ธ Cave safety mode activated for", player.Name, "- death disabled")
  998. end
  999.  
  1000. function CaveSystem:RemoveCaveSafetyMode(player, caveType)
  1001.     if self.safetyZones[player] and self.safetyZones[player][caveType] then
  1002.         local safetyZone = self.safetyZones[player][caveType]
  1003.         if safetyZone.platform then safetyZone.platform:Destroy() end
  1004.         if safetyZone.detector then safetyZone.detector:Destroy() end
  1005.         self.safetyZones[player][caveType] = nil
  1006.     end
  1007.  
  1008.     if self.playerCaveInstances[player] then
  1009.         for caveName, instance in pairs(self.playerCaveInstances[player]) do
  1010.             if instance.safetySystem then
  1011.                 instance.safetySystem.isActive = false
  1012.                 for _, connection in pairs(instance.safetySystem.connections) do
  1013.                     connection:Disconnect()
  1014.                 end
  1015.                 instance.safetySystem = nil
  1016.             end
  1017.         end
  1018.     end
  1019.  
  1020.     print("๐Ÿ›ก๏ธ Cave safety mode deactivated for", player.Name)
  1021. end
  1022.  
  1023. -- ============================================================================
  1024. -- CAVE INSTANCE CREATION
  1025. -- ============================================================================
  1026.  
  1027. function CaveSystem:CreateCaveInstance(caveType, player)
  1028.     local config = self.caveConfigs[caveType]
  1029.     if not config then
  1030.         warn("โŒ Cave config not found for type:", caveType)
  1031.         return nil
  1032.     end
  1033.  
  1034.     print("๐Ÿ—๏ธ Creating instanced cave dimension for", player.Name, "- Type:", caveType)
  1035.  
  1036.     local caveFolder = Instance.new("Folder")
  1037.     caveFolder.Name = player.Name .. "_" .. caveType .. "_CaveDimension"
  1038.     caveFolder.Parent = workspace
  1039.  
  1040.     local properties = self:GetCaveTypeProperties(caveType)
  1041.     local instanceOffset = properties.instanceOffset or Vector3.new(0, 0, 0)
  1042.     local instancePosition = self.baseCavePosition + instanceOffset
  1043.  
  1044.     config.centerPosition = instancePosition
  1045.     config.portalPosition = instancePosition + Vector3.new(0, 30, 0)
  1046.     config.player = player -- ADD PLAYER REFERENCE for ore creation
  1047.  
  1048.     local caveInstance = {
  1049.         folder = caveFolder,
  1050.         config = config,
  1051.         player = player,
  1052.         hiddenPassages = self:CloneHiddenPassages(config.hiddenPassages, player),
  1053.         isInstancedDimension = true,
  1054.         instancePosition = instancePosition,
  1055.         originalReturnPosition = nil,
  1056.         safetySystem = nil
  1057.     }
  1058.  
  1059.     self:GenerateInstancedCave(caveInstance)
  1060.     self:CreateReturnPortal(caveInstance)
  1061.     self:AddMiningInfrastructure(caveInstance)
  1062.     self:CreateHiddenWalls(caveInstance)
  1063.     self:AddCaveAtmosphere(caveInstance)
  1064.  
  1065.     -- CLEANUP: Now run cleanup AFTER everything is fully generated
  1066.     print("โณ Waiting for terrain/ore generation to settle...")
  1067.     wait(1) -- Give terrain carving time to complete
  1068.     self:CleanupFloatingOres(caveInstance)
  1069.  
  1070.     if not self.playerCaveInstances[player] then
  1071.         self.playerCaveInstances[player] = {}
  1072.     end
  1073.     self.playerCaveInstances[player][caveType] = caveInstance
  1074.  
  1075.     print("โœ… Safe instanced cave dimension created for", player.Name, "at", instancePosition)
  1076.     return caveInstance
  1077. end
  1078.  
  1079. function CaveSystem:GenerateInstancedCave(caveInstance)
  1080.     local config = caveInstance.config
  1081.     print("๐ŸŒŒ Generating instanced cave dimension...")
  1082.     self:CreateInstanceTerrain(config)
  1083.     local mine = self:CreateDungeonStyleMine(config)
  1084.     caveInstance.mine = mine
  1085.     caveInstance.cellSize = 8
  1086.     print("๐Ÿ”๏ธ Instanced cave dimension completed")
  1087. end
  1088.  
  1089. function CaveSystem:CreateInstanceTerrain(config)
  1090.     local centerPos = config.centerPosition
  1091.     local terrainSize = Vector3.new(800, 200, 800)
  1092.     local rockRegion = Region3.new(
  1093.         centerPos - terrainSize/2,
  1094.         centerPos + terrainSize/2
  1095.     ):ExpandToGrid(4)
  1096.     workspace.Terrain:FillRegion(rockRegion, 4, Enum.Material.Rock)
  1097.     print("๐Ÿ”๏ธ Created massive instanced terrain formation at", centerPos, "size:", terrainSize)
  1098. end
  1099.  
  1100. function CaveSystem:CreateDungeonStyleMine(config)
  1101.     local mineSize = 50
  1102.     local mine = Mine.new(mineSize, mineSize)
  1103.  
  1104.     if not mine then
  1105.         error("Failed to create mine")
  1106.     end
  1107.  
  1108.     print("๐Ÿ“Š Created", mineSize .. "x" .. mineSize, "mine grid")
  1109.  
  1110.     local house = MineHouse.new(mine)
  1111.     mine.House = house
  1112.  
  1113.     print("๐Ÿ›๏ธ Creating mine rooms...")
  1114.     for i = 1, 15 do
  1115.         house:tryRoom()
  1116.     end
  1117.     print("๐Ÿ›๏ธ Created", #house.Rooms, "mining chambers")
  1118.  
  1119.     mine:RecursiveBacktracker()
  1120.     self:CreateMineRoomOpenings(mine, house)
  1121.     mine:searchForDoor(house)
  1122.     self:CleanupNonPathCells(mine)
  1123.     self:CarvePhysicalMineFromGrid(mine, config)
  1124.  
  1125.     return mine
  1126. end
  1127.  
  1128. function CaveSystem:CreateMineRoomOpenings(mine, house)
  1129.     print("๐Ÿšช Creating room openings...")
  1130.  
  1131.     if #house.Rooms <= 1 then
  1132.         print("โš ๏ธ Need at least 2 rooms for openings")
  1133.         return
  1134.     end
  1135.  
  1136.     local maxDoors = 2
  1137.     local maxRetries = 10
  1138.  
  1139.     for _, room in ipairs(house.Rooms) do
  1140.         local outsiders = room.Outsiders
  1141.         local tries = 0
  1142.  
  1143.         for doorNum = 1, maxDoors do
  1144.             repeat
  1145.                 if #outsiders == 0 then break end
  1146.  
  1147.                 local candidate = outsiders[math.random(1, #outsiders)]
  1148.                 if not candidate.Door then
  1149.                     local dir = nil
  1150.                     if candidate.onlyDir then
  1151.                         dir = candidate.onlyDir
  1152.                     else
  1153.                         local availDirs = {}
  1154.                         for direction, available in pairs(candidate.availDirs) do
  1155.                             if available then
  1156.                                 table.insert(availDirs, direction)
  1157.                             end
  1158.                         end
  1159.                         if #availDirs > 0 then
  1160.                             dir = availDirs[math.random(1, #availDirs)]
  1161.                         end
  1162.                     end
  1163.  
  1164.                     if dir then
  1165.                         local opposite = candidate:getCellOfDirection(mine.Map, dir)
  1166.                         if opposite then
  1167.                             candidate:DelInBetween(opposite, dir)
  1168.                             candidate.Door = dir
  1169.                             table.insert(house.Doors, candidate)
  1170.                             print("๐Ÿšช Created door at", candidate.x, candidate.y, "direction", dir)
  1171.                             break
  1172.                         end
  1173.                     end
  1174.                 end
  1175.  
  1176.                 tries = tries + 1
  1177.             until tries >= maxRetries
  1178.  
  1179.             if tries >= maxRetries then
  1180.                 break
  1181.             end
  1182.         end
  1183.     end
  1184.  
  1185.     print("๐Ÿšช Created", #house.Doors, "room openings")
  1186. end
  1187.  
  1188. function CaveSystem:CleanupNonPathCells(mine)
  1189.     print("๐Ÿงน Cleaning up non-path cells...")
  1190.  
  1191.     local sX, sY = mine.sX, mine.sY
  1192.     local Map = mine.Map
  1193.     local oppDir = {W = "E", E = "W", S = "N", N = "S"}
  1194.  
  1195.     for i = 1, sX do
  1196.         for j = 1, sY do
  1197.             local cell = Map[i][j]
  1198.             if not cell.isRoom and not cell.isPath then
  1199.                 cell.availDirs = {}
  1200.                 cell.availDirs.W = false
  1201.                 cell.availDirs.E = false
  1202.                 cell.availDirs.S = false
  1203.                 cell.availDirs.N = false
  1204.  
  1205.                 local neighbors = cell:GetNonRoomNeighbors(mine)
  1206.                 for _, v in ipairs(neighbors) do
  1207.                     local dir, oCell = v.Dir, v.Cell
  1208.                     if oCell.isPath and oCell.availDirs then
  1209.                         oCell.availDirs = FORCE_SET_TABLE_VALUE(oCell.availDirs, oppDir[dir], true)
  1210.                         break
  1211.                     end
  1212.                 end
  1213.             end
  1214.         end
  1215.     end
  1216.  
  1217.     print("๐Ÿงน Cleanup completed")
  1218. end
  1219.  
  1220. -- ============================================================================
  1221. -- NEIGHBOR COUNT ORE SYSTEM - USING TESTORE FROM MATERIALS FOLDER
  1222. -- ============================================================================
  1223.  
  1224. -- UPDATED: Physical mine carving that creates ores from room neighbor count data
  1225. function CaveSystem:CarvePhysicalMineFromGrid(mine, config)
  1226.     print("โ›๏ธ Carving physical mine from grid with NEIGHBOR COUNT ores...")
  1227.  
  1228.     local cellSize = 8
  1229.     local centerPos = config.centerPosition
  1230.     local startX = centerPos.X - (mine.sX * cellSize / 2)
  1231.     local startZ = centerPos.Z - (mine.sY * cellSize / 2)
  1232.     local mineY = centerPos.Y
  1233.  
  1234.     -- First pass: Carve all spaces
  1235.     for x = 1, mine.sX do
  1236.         for y = 1, mine.sY do
  1237.             local cell = mine.Map[x][y]
  1238.  
  1239.             if cell.isRoom or cell.isPath then
  1240.                 local worldX = startX + (x - 0.5) * cellSize
  1241.                 local worldZ = startZ + (y - 0.5) * cellSize
  1242.                 local worldPos = Vector3.new(worldX, mineY, worldZ)
  1243.  
  1244.                 if cell.isRoom then
  1245.                     self:CarveRoomSpace(worldPos, cellSize * 1.2, 16)
  1246.                     cell.hasLighting = true
  1247.                     cell.hasSupport = true
  1248.                 else
  1249.                     self:CarveTunnelSpace(worldPos, cellSize * 0.9, 12)
  1250.  
  1251.                     local connectionCount = 0
  1252.                     for dir, available in pairs(cell.availDirs) do
  1253.                         if available then connectionCount = connectionCount + 1 end
  1254.                     end
  1255.  
  1256.                     if connectionCount >= 3 then
  1257.                         cell.hasLighting = true
  1258.                         cell.hasSupport = true
  1259.                     elseif connectionCount == 1 then
  1260.                         cell.hasOre = true
  1261.                     end
  1262.                 end
  1263.             end
  1264.         end
  1265.     end
  1266.  
  1267.     -- Second pass: Create ores from room neighbor count data using TestOre
  1268.     if mine.House and mine.House.Rooms then
  1269.         for _, room in ipairs(mine.House.Rooms) do
  1270.             for _, oreData in ipairs(room.OrePositions) do
  1271.                 self:CreateNeighborCountOre(oreData, startX, startZ, mineY, cellSize, config)
  1272.             end
  1273.         end
  1274.     end
  1275.  
  1276.     print("โ›๏ธ Physical mine carved with NEIGHBOR COUNT TestOres")
  1277. end
  1278.  
  1279. function CaveSystem:CarveRoomSpace(worldPos, size, height)
  1280.     local roomSize = size * 1.5
  1281.     local region = Region3.new(
  1282.         Vector3.new(worldPos.X - roomSize/2, worldPos.Y - height/2, worldPos.Z - roomSize/2),
  1283.         Vector3.new(worldPos.X + roomSize/2, worldPos.Y + height/2, worldPos.Z + roomSize/2)
  1284.     ):ExpandToGrid(4)
  1285.     workspace.Terrain:FillRegion(region, 4, Enum.Material.Air)
  1286. end
  1287.  
  1288. function CaveSystem:CarveTunnelSpace(worldPos, size, height)
  1289.     local corridorSize = size * 2.5
  1290.     local region = Region3.new(
  1291.         Vector3.new(worldPos.X - corridorSize/2, worldPos.Y - height/2, worldPos.Z - corridorSize/2),
  1292.         Vector3.new(worldPos.X + corridorSize/2, worldPos.Y + height/2, worldPos.Z + corridorSize/2)
  1293.     ):ExpandToGrid(4)
  1294.     workspace.Terrain:FillRegion(region, 4, Enum.Material.Air)
  1295. end
  1296.  
  1297. -- NEW: Get position at wall edge using half grid size
  1298. function CaveSystem:GetWallEdgePosition(gridCenter, direction, halfCellSize)
  1299.     local heightOffset = math.random(-2, 4) -- Random height variation
  1300.  
  1301.     -- CLOSER TO WALL: Use slightly more than half grid size to get closer to wall
  1302.     local wallDistance = halfCellSize + 3 -- INCREASED from halfCellSize to halfCellSize + 1.5
  1303.  
  1304.     -- Use the increased distance to position closer to the wall
  1305.     if direction == "north" then
  1306.         return Vector3.new(gridCenter.X, gridCenter.Y + heightOffset, gridCenter.Z + wallDistance)
  1307.     elseif direction == "south" then
  1308.         return Vector3.new(gridCenter.X, gridCenter.Y + heightOffset, gridCenter.Z - wallDistance)
  1309.     elseif direction == "east" then
  1310.         return Vector3.new(gridCenter.X + wallDistance, gridCenter.Y + heightOffset, gridCenter.Z)
  1311.     elseif direction == "west" then
  1312.         return Vector3.new(gridCenter.X - wallDistance, gridCenter.Y + heightOffset, gridCenter.Z)
  1313.     end
  1314.  
  1315.     return gridCenter
  1316. end
  1317.  
  1318. -- NEW: Create ore from neighbor count data using existing TestOre model
  1319. function CaveSystem:CreateNeighborCountOre(oreData, startX, startZ, mineY, cellSize, config)
  1320.     local folder = workspace:FindFirstChild(config.player and (config.player.Name .. "_" .. config.type .. "_CaveDimension") or "TempCaveFolder")
  1321.  
  1322.     if not folder then
  1323.         folder = Instance.new("Folder")
  1324.         folder.Name = "CaveOres"
  1325.         folder.Parent = workspace
  1326.     end
  1327.  
  1328.     -- Try to find the TestOre from Materials folder
  1329.     local materialsFolder = workspace:FindFirstChild("Materials")
  1330.     local testOre = materialsFolder and materialsFolder:FindFirstChild("TestOre")
  1331.  
  1332.     if not testOre then
  1333.         warn("โš ๏ธ TestOre not found in Materials folder - creating fallback ore")
  1334.         self:CreateFallbackOre(oreData, startX, startZ, mineY, cellSize, config, folder)
  1335.         return
  1336.     end
  1337.  
  1338.     -- Calculate world position of the ore grid square CENTER
  1339.     local oreWorldX = startX + (oreData.gridX - 0.5) * cellSize
  1340.     local oreWorldZ = startZ + (oreData.gridY - 0.5) * cellSize
  1341.     local oreGridCenter = Vector3.new(oreWorldX, mineY, oreWorldZ)
  1342.  
  1343.     -- Use HALF the grid width/length to position ore at wall edge
  1344.     local halfCellSize = cellSize / 2
  1345.     local orePosition = self:GetWallEdgePosition(oreGridCenter, oreData.direction, halfCellSize)
  1346.  
  1347.     -- Clone the TestOre
  1348.     local ore = testOre:Clone()
  1349.     ore.Name = "CaveOre_" .. config.type .. "_" .. oreData.gridX .. "_" .. oreData.gridY
  1350.     ore.Parent = folder
  1351.  
  1352.     -- Handle positioning based on whether TestOre is a Model or Part
  1353.     if ore:IsA("Model") then
  1354.         -- TestOre is a Model - handle Union-based models properly
  1355.         local primaryPart = ore.PrimaryPart
  1356.         if not primaryPart then
  1357.             -- Try to find the Union part as primary
  1358.             for _, child in pairs(ore:GetChildren()) do
  1359.                 if child:IsA("UnionOperation") or child:IsA("Part") then
  1360.                     ore.PrimaryPart = child
  1361.                     primaryPart = child
  1362.                     break
  1363.                 end
  1364.             end
  1365.         end
  1366.  
  1367.         if primaryPart then
  1368.             -- Rotate to face INTO the room (opposite of wall direction)
  1369.             local rotationCFrame = CFrame.new(Vector3.new(0, 0, 0))
  1370.             if oreData.direction == "north" then
  1371.                 -- Wall faces north, ore should face south (into room)
  1372.                 rotationCFrame = CFrame.Angles(0, math.rad(180), 0)
  1373.             elseif oreData.direction == "south" then
  1374.                 -- Wall faces south, ore should face north (into room)
  1375.                 rotationCFrame = CFrame.Angles(0, 0, 0)
  1376.             elseif oreData.direction == "east" then
  1377.                 -- Wall faces east, ore should face west (into room) + 180ยฐ correction
  1378.                 rotationCFrame = CFrame.Angles(0, math.rad(90 + 180), 0)
  1379.             elseif oreData.direction == "west" then
  1380.                 -- Wall faces west, ore should face east (into room) + 180ยฐ correction
  1381.                 rotationCFrame = CFrame.Angles(0, math.rad(-90 + 180), 0)
  1382.             end
  1383.  
  1384.             -- Use SetPrimaryPartCFrame for proper Model rotation
  1385.             ore:SetPrimaryPartCFrame(CFrame.new(orePosition) * rotationCFrame)
  1386.             print("โ›๏ธ Positioned TestOre Model with PrimaryPart (" .. primaryPart.ClassName .. ") at", orePosition, "facing into room")
  1387.         else
  1388.             -- Fallback: Move all BaseParts in the model individually
  1389.             local centerOffset = Vector3.new(0, 0, 0)
  1390.  
  1391.             -- Calculate center of model first
  1392.             local parts = {}
  1393.             for _, child in pairs(ore:GetChildren()) do
  1394.                 if child:IsA("BasePart") then
  1395.                     table.insert(parts, child)
  1396.                 end
  1397.             end
  1398.  
  1399.             if #parts > 0 then
  1400.                 local totalPosition = Vector3.new(0, 0, 0)
  1401.                 for _, part in pairs(parts) do
  1402.                     totalPosition = totalPosition + part.Position
  1403.                 end
  1404.                 centerOffset = totalPosition / #parts
  1405.  
  1406.                 -- Calculate rotation
  1407.                 local rotationCFrame = CFrame.new(Vector3.new(0, 0, 0))
  1408.                 if oreData.direction == "north" then
  1409.                     rotationCFrame = CFrame.Angles(0, math.rad(180), 0)
  1410.                 elseif oreData.direction == "south" then
  1411.                     rotationCFrame = CFrame.Angles(0, 0, 0)
  1412.                 elseif oreData.direction == "east" then
  1413.                     rotationCFrame = CFrame.Angles(0, math.rad(90 + 180), 0)
  1414.                 elseif oreData.direction == "west" then
  1415.                     rotationCFrame = CFrame.Angles(0, math.rad(-90 + 180), 0)
  1416.                 end
  1417.  
  1418.                 -- Apply rotation to each part relative to center
  1419.                 for _, part in pairs(parts) do
  1420.                     local relativePos = part.Position - centerOffset
  1421.                     local rotatedPos = rotationCFrame:VectorToWorldSpace(relativePos)
  1422.                     part.CFrame = CFrame.new(orePosition + rotatedPos) * rotationCFrame * (part.CFrame - part.Position)
  1423.                 end
  1424.  
  1425.                 print("โ›๏ธ Positioned TestOre Model using individual parts at", orePosition, "facing into room")
  1426.             else
  1427.                 -- Final fallback - just move to position
  1428.                 ore:MoveTo(orePosition)
  1429.                 print("โ›๏ธ Positioned TestOre Model using MoveTo at", orePosition, "(no rotation)")
  1430.             end
  1431.         end
  1432.     else
  1433.         -- TestOre is a Part - use Position and CFrame directly
  1434.         ore.Position = orePosition
  1435.  
  1436.         -- Rotate ore to face INTO the room (opposite of wall direction)
  1437.         if oreData.direction == "north" then
  1438.             -- Wall faces north, ore should face south (into room)
  1439.             ore.CFrame = CFrame.new(orePosition) * CFrame.Angles(0, math.rad(180), 0)
  1440.         elseif oreData.direction == "south" then
  1441.             -- Wall faces south, ore should face north (into room)
  1442.             ore.CFrame = CFrame.new(orePosition) * CFrame.Angles(0, 0, 0)
  1443.         elseif oreData.direction == "east" then
  1444.             -- Wall faces east, ore should face west (into room) + 180ยฐ correction
  1445.             ore.CFrame = CFrame.new(orePosition) * CFrame.Angles(0, math.rad(90 + 180), 0)
  1446.         elseif oreData.direction == "west" then
  1447.             -- Wall faces west, ore should face east (into room) + 180ยฐ correction
  1448.             ore.CFrame = CFrame.new(orePosition) * CFrame.Angles(0, math.rad(-90 + 180), 0)
  1449.         end
  1450.  
  1451.         print("โ›๏ธ Positioned TestOre Part at", orePosition, "facing into room")
  1452.     end
  1453.  
  1454.     -- Add cave-specific identifier to distinguish from surface ores
  1455.     local stringValue = Instance.new("StringValue")
  1456.     stringValue.Name = "CaveType"
  1457.     stringValue.Value = config.type
  1458.     stringValue.Parent = ore
  1459.  
  1460.     local intValue = Instance.new("IntValue")
  1461.     intValue.Name = "NeighborCount"
  1462.     intValue.Value = oreData.neighborCount
  1463.     intValue.Parent = ore
  1464.  
  1465.     -- Add position data for debugging
  1466.     local positionValue = Instance.new("Vector3Value")
  1467.     positionValue.Name = "GridPosition"
  1468.     positionValue.Value = Vector3.new(oreData.gridX, oreData.gridY, 0)
  1469.     positionValue.Parent = ore
  1470.  
  1471.     -- Add debug click detector for manual analysis
  1472.     local debugDetector = Instance.new("ClickDetector")
  1473.     debugDetector.Name = "DebugClickDetector"
  1474.     debugDetector.MaxActivationDistance = 15
  1475.     debugDetector.Parent = ore
  1476.  
  1477.     -- Store grid parameters for debug analysis
  1478.     local gridDataValue = Instance.new("StringValue")
  1479.     gridDataValue.Name = "GridDebugData"
  1480.     gridDataValue.Value = string.format("CellSize:%d,StartX:%.1f,StartZ:%.1f,MineSize:50x50",
  1481.         cellSize, startX, startZ)
  1482.     gridDataValue.Parent = ore
  1483.  
  1484.     debugDetector.MouseClick:Connect(function(player)
  1485.         print("=== SUSPECT FLOATING ORE DATA ===")
  1486.         print("Ore Name:", ore.Name)
  1487.         print("Ore Position:", self:GetOrePosition(ore))
  1488.  
  1489.         local gridPos = ore:FindFirstChild("GridPosition")
  1490.         if gridPos then
  1491.             print("Grid Position:", gridPos.Value.X .. "," .. gridPos.Value.Y)
  1492.         end
  1493.  
  1494.         local gridDebug = ore:FindFirstChild("GridDebugData")
  1495.         if gridDebug then
  1496.             print("Grid Parameters:", gridDebug.Value)
  1497.         end
  1498.  
  1499.         -- Calculate expected position
  1500.         local expectedGridCenterX = startX + (oreData.gridX - 0.5) * cellSize
  1501.         local expectedGridCenterZ = startZ + (oreData.gridY - 0.5) * cellSize
  1502.         print("Expected Grid Center:", expectedGridCenterX .. "," .. expectedGridCenterZ)
  1503.  
  1504.         -- Calculate distance from expected center
  1505.         local orePos = self:GetOrePosition(ore)
  1506.         if orePos then
  1507.             local distance = math.sqrt(
  1508.                 (orePos.X - expectedGridCenterX)^2 +
  1509.                     (orePos.Z - expectedGridCenterZ)^2
  1510.             )
  1511.             print("Distance from Grid Center:", math.floor(distance * 10) / 10, "studs")
  1512.             print("Cell Size:", cellSize, "studs")
  1513.             print("Half Cell Size:", cellSize/2, "studs")
  1514.             print("Max Allowed Distance:", (cellSize/2) + 5, "studs")
  1515.  
  1516.             if distance > (cellSize/2) + 5 then
  1517.                 print("STATUS: โŒ FLOATING (too far from grid center)")
  1518.             else
  1519.                 print("STATUS: โœ… VALID (within grid bounds)")
  1520.             end
  1521.         end
  1522.  
  1523.         print("Wall Direction:", oreData.direction)
  1524.         print("Neighbor Count:", oreData.neighborCount)
  1525.         print("=== END SUSPECT ORE DATA ===")
  1526.     end)
  1527.  
  1528.     print("โ›๏ธ Cloned TestOre (" .. ore.ClassName .. ") at", orePosition, "direction", oreData.direction, "neighbors:", oreData.neighborCount)
  1529.     print("๐Ÿ” DEBUG: Grid(" .. oreData.gridX .. "," .. oreData.gridY .. ") CellSize:" .. cellSize .. " Expected Center: " .. (startX + (oreData.gridX - 0.5) * cellSize) .. "," .. (startZ + (oreData.gridY - 0.5) * cellSize))
  1530. end
  1531.  
  1532. -- Fallback ore creation if TestOre is not found
  1533. function CaveSystem:CreateFallbackOre(oreData, startX, startZ, mineY, cellSize, config, folder)
  1534.     local oreWorldX = startX + (oreData.gridX - 0.5) * cellSize
  1535.     local oreWorldZ = startZ + (oreData.gridY - 0.5) * cellSize
  1536.     local oreGridCenter = Vector3.new(oreWorldX, mineY, oreWorldZ)
  1537.  
  1538.     local halfCellSize = cellSize / 2
  1539.     local orePosition = self:GetWallEdgePosition(oreGridCenter, oreData.direction, halfCellSize)
  1540.  
  1541.     -- Create basic fallback ore
  1542.     local ore = Instance.new("Part")
  1543.     ore.Name = "FallbackOre_" .. config.type
  1544.     ore.Size = Vector3.new(2, 2, 1)
  1545.     ore.Position = orePosition
  1546.     ore.Material = Enum.Material.Neon
  1547.     ore.Color = self:GetSimpleOreColor(config.type)
  1548.     ore.Anchored = true
  1549.     ore.CanCollide = false
  1550.     ore.Parent = folder
  1551.  
  1552.     -- Add basic mining interaction
  1553.     local clickDetector = Instance.new("ClickDetector")
  1554.     clickDetector.MaxActivationDistance = 8
  1555.     clickDetector.Parent = ore
  1556.  
  1557.     clickDetector.MouseClick:Connect(function(player)
  1558.         if ore.Size.X > 1 then
  1559.             ore.Size = ore.Size * 0.8
  1560.             if _G.ShowToast then
  1561.                 _G.ShowToast("โ›๏ธ Mined fallback ore!", "Success")
  1562.             end
  1563.         else
  1564.             ore:Destroy()
  1565.         end
  1566.     end)
  1567.  
  1568.     print("โ›๏ธ Created fallback ore at", orePosition)
  1569. end
  1570.  
  1571. -- NEW: Simple ore colors for fallback
  1572. function CaveSystem:GetSimpleOreColor(caveType)
  1573.     local colors = {
  1574.         Crystal = Color3.new(0.4, 0.8, 1),      -- Bright blue
  1575.         Underground = Color3.new(0.8, 0.6, 0.2), -- Gold
  1576.         Lava = Color3.new(1, 0.3, 0.1),         -- Red
  1577.         Ice = Color3.new(0.7, 0.9, 1),          -- Light blue
  1578.         Ancient = Color3.new(0.8, 0.7, 0.3)     -- Ancient gold
  1579.     }
  1580.  
  1581.     return colors[caveType] or Color3.new(0.8, 0.6, 0.2)
  1582. end
  1583.  
  1584. -- NEW: Cleanup floating ores that aren't touching terrain
  1585. function CaveSystem:CleanupFloatingOres(caveInstance)
  1586.     local folder = caveInstance.folder
  1587.     if not folder then return end
  1588.  
  1589.     print("๐Ÿงน Cleaning up floating ores...")
  1590.  
  1591.     local totalOres = 0
  1592.     local floatingOres = 0
  1593.     local removedOres = 0
  1594.  
  1595.     -- Find all ore objects in the cave
  1596.     for _, child in pairs(folder:GetChildren()) do
  1597.         if child.Name:find("CaveOre_") or child.Name:find("FallbackOre_") then
  1598.             totalOres = totalOres + 1
  1599.  
  1600.             local isFloating = self:IsOreFloating(child)
  1601.             if isFloating then
  1602.                 floatingOres = floatingOres + 1
  1603.                 print("๐Ÿ—‘๏ธ Removing floating ore:", child.Name, "at position", self:GetOrePosition(child))
  1604.                 child:Destroy()
  1605.                 removedOres = removedOres + 1
  1606.             end
  1607.         end
  1608.     end
  1609.  
  1610.     print("๐Ÿงน Ore cleanup complete:")
  1611.     print("  - Total ores found:", totalOres)
  1612.     print("  - Floating ores detected:", floatingOres)
  1613.     print("  - Floating ores removed:", removedOres)
  1614.     print("  - Remaining ores:", totalOres - removedOres)
  1615. end
  1616.  
  1617. -- NEW: Check if an ore is floating using grid-based distance logic
  1618. function CaveSystem:IsOreFloating(ore)
  1619.     local orePosition = self:GetOrePosition(ore)
  1620.     if not orePosition then return true end -- If we can't get position, assume floating
  1621.  
  1622.     -- Get ore data from the ore itself
  1623.     local gridPositionValue = ore:FindFirstChild("GridPosition")
  1624.     local caveTypeValue = ore:FindFirstChild("CaveType")
  1625.  
  1626.     if not gridPositionValue or not caveTypeValue then
  1627.         print("๐Ÿ” Ore missing grid data - keeping it:", ore.Name)
  1628.         return false -- If no grid data, don't remove it
  1629.     end
  1630.  
  1631.     local gridPos = gridPositionValue.Value
  1632.     local caveType = caveTypeValue.Value
  1633.  
  1634.     -- Find the cave instance to get grid parameters
  1635.     local caveInstance = nil
  1636.     for player, caves in pairs(self.playerCaveInstances) do
  1637.         if caves[caveType] then
  1638.             caveInstance = caves[caveType]
  1639.             break
  1640.         end
  1641.     end
  1642.  
  1643.     if not caveInstance then
  1644.         print("๐Ÿ” No cave instance found - keeping ore:", ore.Name)
  1645.         return false
  1646.     end
  1647.  
  1648.     -- Calculate expected grid center position
  1649.     local cellSize = caveInstance.cellSize or 8
  1650.     local config = caveInstance.config
  1651.     local centerPos = config.centerPosition
  1652.     local startX = centerPos.X - (50 * cellSize / 2) -- Mine is 50x50
  1653.     local startZ = centerPos.Z - (50 * cellSize / 2)
  1654.  
  1655.     local expectedGridCenterX = startX + (gridPos.X - 0.5) * cellSize
  1656.     local expectedGridCenterZ = startZ + (gridPos.Y - 0.5) * cellSize
  1657.     local expectedGridCenter = Vector3.new(expectedGridCenterX, centerPos.Y, expectedGridCenterZ)
  1658.  
  1659.     -- Calculate maximum allowed distance from grid center
  1660.     local halfCellSize = cellSize / 2
  1661.     local maxAllowedDistance = halfCellSize + 5 -- Allow some extra margin for wall placement
  1662.  
  1663.     -- Calculate actual distance from expected grid center
  1664.     local actualDistance = math.sqrt(
  1665.         (orePosition.X - expectedGridCenter.X)^2 +
  1666.             (orePosition.Z - expectedGridCenter.Z)^2
  1667.     )
  1668.  
  1669.     -- If ore is too far from its grid center, it's floating/misplaced
  1670.     local isFloating = actualDistance > maxAllowedDistance
  1671.  
  1672.     if isFloating then
  1673.         print("๐Ÿ—‘๏ธ Ore too far from grid center:", ore.Name)
  1674.         print("  - Expected center:", expectedGridCenter.X .. "," .. expectedGridCenter.Z)
  1675.         print("  - Actual position:", orePosition.X .. "," .. orePosition.Z)
  1676.         print("  - Distance:", math.floor(actualDistance * 10) / 10, "studs (max allowed:", maxAllowedDistance .. ")")
  1677.     else
  1678.         print("โœ… Ore within grid bounds:", ore.Name, "distance:", math.floor(actualDistance * 10) / 10)
  1679.     end
  1680.  
  1681.     return isFloating
  1682. end
  1683.  
  1684. -- NEW: Get position of ore (handles both Models and Parts)
  1685. function CaveSystem:GetOrePosition(ore)
  1686.     if ore:IsA("Model") then
  1687.         if ore.PrimaryPart then
  1688.             return ore.PrimaryPart.Position
  1689.         else
  1690.             -- Find first BasePart and use its position
  1691.             for _, child in pairs(ore:GetChildren()) do
  1692.                 if child:IsA("BasePart") then
  1693.                     return child.Position
  1694.                 end
  1695.             end
  1696.         end
  1697.     elseif ore:IsA("BasePart") then
  1698.         return ore.Position
  1699.     end
  1700.  
  1701.     return nil -- Couldn't determine position
  1702. end
  1703.  
  1704. -- NEW: Clear existing ores from cave
  1705. function CaveSystem:ClearExistingOres(caveInstance)
  1706.     local folder = caveInstance.folder
  1707.     if not folder then return end
  1708.  
  1709.     local removedCount = 0
  1710.     for _, child in pairs(folder:GetChildren()) do
  1711.         if child.Name:find("CaveOre_") or child.Name:find("FallbackOre_") then
  1712.             child:Destroy()
  1713.             removedCount = removedCount + 1
  1714.         end
  1715.     end
  1716.  
  1717.     print("๐Ÿ—‘๏ธ Cleared", removedCount, "existing ores for fresh generation")
  1718. end
  1719.  
  1720. -- NEW: Regenerate random ores in existing cave
  1721. function CaveSystem:RegenerateRandomOres(caveInstance)
  1722.     local mine = caveInstance.mine
  1723.     local config = caveInstance.config
  1724.  
  1725.     if not mine or not mine.House or not mine.House.Rooms then
  1726.         warn("โŒ No mine data found for ore regeneration")
  1727.         return
  1728.     end
  1729.  
  1730.     print("๐ŸŽฒ Regenerating random ores...")
  1731.  
  1732.     -- Clear existing ore positions from all rooms
  1733.     for _, room in ipairs(mine.House.Rooms) do
  1734.         room.OrePositions = {}
  1735.     end
  1736.  
  1737.     -- Regenerate ore positions with new randomization
  1738.     for _, room in ipairs(mine.House.Rooms) do
  1739.         room:GenerateRoomOres(mine)
  1740.     end
  1741.  
  1742.     -- Create physical ores from new positions
  1743.     local cellSize = caveInstance.cellSize or 8
  1744.     local centerPos = config.centerPosition
  1745.     local startX = centerPos.X - (mine.sX * cellSize / 2)
  1746.     local startZ = centerPos.Z - (mine.sY * cellSize / 2)
  1747.     local mineY = centerPos.Y
  1748.  
  1749.     local totalNewOres = 0
  1750.     for _, room in ipairs(mine.House.Rooms) do
  1751.         for _, oreData in ipairs(room.OrePositions) do
  1752.             self:CreateNeighborCountOre(oreData, startX, startZ, mineY, cellSize, config)
  1753.             totalNewOres = totalNewOres + 1
  1754.         end
  1755.     end
  1756.  
  1757.     print("๐ŸŽฒ Generated", totalNewOres, "new randomized TestOres")
  1758. end
  1759.  
  1760. -- ============================================================================
  1761. -- MINING INFRASTRUCTURE (WITHOUT FLOATING ORES)
  1762. -- ============================================================================
  1763.  
  1764. function CaveSystem:AddMiningInfrastructure(caveInstance)
  1765.     local config = caveInstance.config
  1766.     local properties = config.properties
  1767.     local folder = caveInstance.folder
  1768.  
  1769.     print("โšก Adding mining infrastructure...")
  1770.  
  1771.     local mine = caveInstance.mine
  1772.     local cellSize = caveInstance.cellSize
  1773.  
  1774.     if not mine then
  1775.         warn("โŒ No mine data found")
  1776.         return
  1777.     end
  1778.  
  1779.     self:AddGridBasedMineInfrastructure(mine, cellSize, config, properties, folder)
  1780.  
  1781.     print("โšก Mining infrastructure completed")
  1782. end
  1783.  
  1784. function CaveSystem:AddGridBasedMineInfrastructure(mine, cellSize, config, properties, folder)
  1785.     local centerPos = config.centerPosition
  1786.     local startX = centerPos.X - (mine.sX * cellSize / 2)
  1787.     local startZ = centerPos.Z - (mine.sY * cellSize / 2)
  1788.     local mineY = centerPos.Y
  1789.  
  1790.     for x = 1, mine.sX do
  1791.         for y = 1, mine.sY do
  1792.             local cell = mine.Map[x][y]
  1793.  
  1794.             if cell.isRoom or cell.isPath then
  1795.                 local worldX = startX + (x - 0.5) * cellSize
  1796.                 local worldZ = startZ + (y - 0.5) * cellSize
  1797.                 local worldPos = Vector3.new(worldX, mineY, worldZ)
  1798.  
  1799.                 -- LIGHTING: Light most rooms and intersections
  1800.                 if cell.hasLighting and (cell.isRoom or math.random() < 0.6) then
  1801.                     local lightPos = Vector3.new(worldX, mineY + 6, worldZ)
  1802.                     self:CreateBalancedMiningLight(lightPos, properties, folder)
  1803.                 end
  1804.  
  1805.                 -- ROOM SUPPORTS: Sparse support beams
  1806.                 if cell.isRoom and cell.hasSupport and properties.infrastructure.woodenSupports then
  1807.                     if math.random() < 0.05 then
  1808.                         local supportHeight = 16
  1809.                         self:CreateRoomSupport(worldPos, supportHeight, folder)
  1810.                     end
  1811.                 end
  1812.  
  1813.                 -- CORRIDOR SUPPORTS: Mineshaft-style supports
  1814.                 if cell.isPath and properties.infrastructure.woodenSupports then
  1815.                     if (x + y) % 7 == 0 then
  1816.                         self:CreateCorridorMineshaftSupport(worldPos, cellSize, folder, cell, mine)
  1817.                     end
  1818.                 end
  1819.  
  1820.                 -- CABLES: Power cables along paths
  1821.                 if properties.infrastructure.cables then
  1822.                     self:AddCablesForCell(cell, worldPos, cellSize, folder, mine)
  1823.                 end
  1824.  
  1825.                 -- NO ORE CREATION HERE - ores are now created during room generation using neighbor count
  1826.             end
  1827.         end
  1828.     end
  1829. end
  1830.  
  1831. function CaveSystem:CreateBalancedMiningLight(position, properties, folder)
  1832.     local fixture = Instance.new("Part")
  1833.     fixture.Name = "MiningLight"
  1834.     fixture.Size = Vector3.new(1, 3, 1)
  1835.     fixture.Position = position
  1836.     fixture.Material = Enum.Material.Metal
  1837.     fixture.BrickColor = BrickColor.new("Dark stone grey")
  1838.     fixture.Anchored = true
  1839.     fixture.Parent = folder
  1840.  
  1841.     local light = Instance.new("PointLight")
  1842.     light.Brightness = properties.lighting.brightness * 0.8
  1843.     light.Color = Color3.new(
  1844.         properties.lighting.color.r * 0.9,
  1845.         properties.lighting.color.g * 0.9,
  1846.         properties.lighting.color.b * 0.9
  1847.     )
  1848.     light.Range = properties.lighting.range * 0.9
  1849.     light.Parent = fixture
  1850.  
  1851.     spawn(function()
  1852.         while fixture.Parent do
  1853.             wait(math.random(3, 8))
  1854.             local originalBrightness = light.Brightness
  1855.             light.Brightness = originalBrightness * (0.8 + math.random() * 0.2)
  1856.             wait(0.1)
  1857.             light.Brightness = originalBrightness
  1858.         end
  1859.     end)
  1860.  
  1861.     local cage = Instance.new("Part")
  1862.     cage.Name = "LightCage"
  1863.     cage.Size = Vector3.new(2, 2, 2)
  1864.     cage.Position = position - Vector3.new(0, 0.5, 0)
  1865.     cage.Material = Enum.Material.Metal
  1866.     cage.BrickColor = BrickColor.new("Really black")
  1867.     cage.Transparency = 0.7
  1868.     cage.Anchored = true
  1869.     cage.Parent = folder
  1870. end
  1871.  
  1872. function CaveSystem:CreateRoomSupport(position, height, folder)
  1873.     local beam = Instance.new("Part")
  1874.     beam.Name = "RoomSupport"
  1875.     beam.Size = Vector3.new(1.2, height, 1.2)
  1876.     beam.Position = position
  1877.     beam.Material = Enum.Material.Wood
  1878.     beam.BrickColor = BrickColor.new("Dark brown")
  1879.     beam.Anchored = true
  1880.     beam.Parent = folder
  1881. end
  1882.  
  1883. function CaveSystem:CreateCorridorMineshaftSupport(position, cellSize, folder, cell, mine)
  1884.     local supportDirection = self:GetCorridorDirection(cell, mine)
  1885.  
  1886.     if supportDirection == "horizontal" then
  1887.         self:CreateMineshaftFrame(position, cellSize, "horizontal", folder)
  1888.     elseif supportDirection == "vertical" then
  1889.         self:CreateMineshaftFrame(position, cellSize, "vertical", folder)
  1890.     else
  1891.         self:CreateMineshaftFrame(position, cellSize, "cross", folder)
  1892.     end
  1893. end
  1894.  
  1895. function CaveSystem:GetCorridorDirection(cell, mine)
  1896.     local openDirs = {}
  1897.     for dir, available in pairs(cell.availDirs) do
  1898.         if available then
  1899.             table.insert(openDirs, dir)
  1900.         end
  1901.     end
  1902.  
  1903.     if #openDirs == 2 then
  1904.         if (table.find(openDirs, "N") and table.find(openDirs, "S")) then
  1905.             return "horizontal"
  1906.         elseif (table.find(openDirs, "E") and table.find(openDirs, "W")) then
  1907.             return "vertical"
  1908.         end
  1909.     end
  1910.  
  1911.     return "intersection"
  1912. end
  1913.  
  1914. function CaveSystem:CreateMineshaftFrame(position, cellSize, orientation, folder)
  1915.     local frameHeight = 12
  1916.     local postWidth = 0.8
  1917.     local beamWidth = 0.6
  1918.  
  1919.     local function setSafeMaterial(part, materialName)
  1920.         local success = pcall(function()
  1921.             if materialName == "VerticalPlanks" then
  1922.                 part.Material = "VerticalPlanks"
  1923.             elseif materialName == "HorizontalPlanks" then
  1924.                 part.Material = "HorizontalPlanks"
  1925.             else
  1926.                 part.Material = Enum.Material.Wood
  1927.             end
  1928.         end)
  1929.         if not success then
  1930.             part.Material = Enum.Material.Wood
  1931.         end
  1932.     end
  1933.  
  1934.     if orientation == "horizontal" then
  1935.         local leftPost = Instance.new("Part")
  1936.         leftPost.Name = "CorridorPost"
  1937.         leftPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
  1938.         leftPost.Position = position + Vector3.new(-cellSize/2 + postWidth/2, frameHeight/2, 0)
  1939.         setSafeMaterial(leftPost, "VerticalPlanks")
  1940.         leftPost.BrickColor = BrickColor.new("Dark brown")
  1941.         leftPost.Anchored = true
  1942.         leftPost.Parent = folder
  1943.  
  1944.         local rightPost = Instance.new("Part")
  1945.         rightPost.Name = "CorridorPost"
  1946.         rightPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
  1947.         rightPost.Position = position + Vector3.new(cellSize/2 - postWidth/2, frameHeight/2, 0)
  1948.         setSafeMaterial(rightPost, "VerticalPlanks")
  1949.         rightPost.BrickColor = BrickColor.new("Dark brown")
  1950.         rightPost.Anchored = true
  1951.         rightPost.Parent = folder
  1952.  
  1953.         local topBeam = Instance.new("Part")
  1954.         topBeam.Name = "CorridorBeam"
  1955.         topBeam.Size = Vector3.new(cellSize - postWidth, beamWidth, beamWidth)
  1956.         topBeam.Position = position + Vector3.new(0, frameHeight - beamWidth/2, 0)
  1957.         setSafeMaterial(topBeam, "HorizontalPlanks")
  1958.         topBeam.BrickColor = BrickColor.new("Dark brown")
  1959.         topBeam.Anchored = true
  1960.         topBeam.Parent = folder
  1961.  
  1962.     elseif orientation == "vertical" then
  1963.         local frontPost = Instance.new("Part")
  1964.         frontPost.Name = "CorridorPost"
  1965.         frontPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
  1966.         frontPost.Position = position + Vector3.new(0, frameHeight/2, -cellSize/2 + postWidth/2)
  1967.         setSafeMaterial(frontPost, "VerticalPlanks")
  1968.         frontPost.BrickColor = BrickColor.new("Dark brown")
  1969.         frontPost.Anchored = true
  1970.         frontPost.Parent = folder
  1971.  
  1972.         local backPost = Instance.new("Part")
  1973.         backPost.Name = "CorridorPost"
  1974.         backPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
  1975.         backPost.Position = position + Vector3.new(0, frameHeight/2, cellSize/2 - postWidth/2)
  1976.         setSafeMaterial(backPost, "VerticalPlanks")
  1977.         backPost.BrickColor = BrickColor.new("Dark brown")
  1978.         backPost.Anchored = true
  1979.         backPost.Parent = folder
  1980.  
  1981.         local topBeam = Instance.new("Part")
  1982.         topBeam.Name = "CorridorBeam"
  1983.         topBeam.Size = Vector3.new(beamWidth, beamWidth, cellSize - postWidth)
  1984.         topBeam.Position = position + Vector3.new(0, frameHeight - beamWidth/2, 0)
  1985.         setSafeMaterial(topBeam, "HorizontalPlanks")
  1986.         topBeam.BrickColor = BrickColor.new("Dark brown")
  1987.         topBeam.Anchored = true
  1988.         topBeam.Parent = folder
  1989.  
  1990.     else
  1991.         local centerPost = Instance.new("Part")
  1992.         centerPost.Name = "IntersectionPost"
  1993.         centerPost.Size = Vector3.new(postWidth, frameHeight, postWidth)
  1994.         centerPost.Position = position + Vector3.new(0, frameHeight/2, 0)
  1995.         setSafeMaterial(centerPost, "VerticalPlanks")
  1996.         centerPost.BrickColor = BrickColor.new("Dark brown")
  1997.         centerPost.Anchored = true
  1998.         centerPost.Parent = folder
  1999.  
  2000.         local crossBeam1 = Instance.new("Part")
  2001.         crossBeam1.Name = "CrossBeam"
  2002.         crossBeam1.Size = Vector3.new(cellSize * 0.8, beamWidth, beamWidth)
  2003.         crossBeam1.Position = position + Vector3.new(0, frameHeight - 2, 0)
  2004.         setSafeMaterial(crossBeam1, "HorizontalPlanks")
  2005.         crossBeam1.BrickColor = BrickColor.new("Dark brown")
  2006.         crossBeam1.Anchored = true
  2007.         crossBeam1.Parent = folder
  2008.  
  2009.         local crossBeam2 = Instance.new("Part")
  2010.         crossBeam2.Name = "CrossBeam"
  2011.         crossBeam2.Size = Vector3.new(beamWidth, beamWidth, cellSize * 0.8)
  2012.         crossBeam2.Position = position + Vector3.new(0, frameHeight - 2, 0)
  2013.         setSafeMaterial(crossBeam2, "HorizontalPlanks")
  2014.         crossBeam2.BrickColor = BrickColor.new("Dark brown")
  2015.         crossBeam2.Anchored = true
  2016.         crossBeam2.Parent = folder
  2017.     end
  2018. end
  2019.  
  2020. function CaveSystem:AddCablesForCell(cell, worldPos, cellSize, folder, mine)
  2021.     local directions = {
  2022.         {dir = "E", dx = cellSize, dz = 0},
  2023.         {dir = "N", dx = 0, dz = cellSize}
  2024.     }
  2025.  
  2026.     for _, dirInfo in ipairs(directions) do
  2027.         if cell.availDirs[dirInfo.dir] then
  2028.             local startPos = Vector3.new(worldPos.X, worldPos.Y + 4, worldPos.Z)
  2029.             local endPos = Vector3.new(worldPos.X + dirInfo.dx, worldPos.Y + 4, worldPos.Z + dirInfo.dz)
  2030.             self:CreateCableRun(startPos, endPos, folder)
  2031.         end
  2032.     end
  2033. end
  2034.  
  2035. function CaveSystem:CreateCableRun(startPos, endPos, folder)
  2036.     local cable = Instance.new("Part")
  2037.     cable.Name = "PowerCable"
  2038.     cable.Size = Vector3.new(0.2, 0.2, (endPos - startPos).Magnitude)
  2039.     cable.Position = startPos:Lerp(endPos, 0.5)
  2040.     cable.CFrame = CFrame.lookAt(cable.Position, endPos)
  2041.     cable.Material = Enum.Material.Plastic
  2042.     cable.BrickColor = BrickColor.new("Really black")
  2043.     cable.Anchored = true
  2044.     cable.Parent = folder
  2045. end
  2046.  
  2047. -- ============================================================================
  2048. -- PORTAL AND TELEPORTATION SYSTEM
  2049. -- ============================================================================
  2050.  
  2051. function CaveSystem:CreateReturnPortal(caveInstance)
  2052.     local config = caveInstance.config
  2053.     local folder = caveInstance.folder
  2054.     local mine = caveInstance.mine
  2055.  
  2056.     local spawnRoom = nil
  2057.     local bestRoomSize = 0
  2058.  
  2059.     if mine and mine.House and mine.House.Rooms then
  2060.         for _, room in ipairs(mine.House.Rooms) do
  2061.             local roomWidth = room.br.x - room.tl.x
  2062.             local roomHeight = room.br.y - room.tl.y
  2063.             local roomSize = roomWidth * roomHeight
  2064.  
  2065.             if roomSize > bestRoomSize then
  2066.                 bestRoomSize = roomSize
  2067.                 spawnRoom = room
  2068.             end
  2069.         end
  2070.     end
  2071.  
  2072.     local portalPosition = config.portalPosition
  2073.  
  2074.     if spawnRoom then
  2075.         local centerPos = config.centerPosition
  2076.         local cellSize = caveInstance.cellSize or 8
  2077.         local startX = centerPos.X - (mine.sX * cellSize / 2)
  2078.         local startZ = centerPos.Z - (mine.sY * cellSize / 2)
  2079.  
  2080.         local roomCenterX = (spawnRoom.tl.x + spawnRoom.br.x) / 2
  2081.         local roomCenterY = (spawnRoom.tl.y + spawnRoom.br.y) / 2
  2082.  
  2083.         local worldX = startX + (roomCenterX - 0.5) * cellSize
  2084.         local worldZ = startZ + (roomCenterY - 0.5) * cellSize
  2085.  
  2086.         local wallOffset = cellSize * 2
  2087.         local floorLevel = centerPos.Y - 8
  2088.         portalPosition = Vector3.new(worldX, floorLevel, worldZ - wallOffset)
  2089.  
  2090.         local playerFloorLevel = centerPos.Y - 8 + 3
  2091.         caveInstance.playerSpawnPosition = Vector3.new(worldX, playerFloorLevel, worldZ + wallOffset/3)
  2092.  
  2093.         print("๐ŸŒ€ Portal placed on floor at:", floorLevel)
  2094.         print("๐ŸŒ€ Player spawn on floor at:", playerFloorLevel)
  2095.     else
  2096.         print("๐ŸŒ€ No suitable room found, using default floor positions")
  2097.         local floorLevel = config.centerPosition.Y - 8
  2098.         portalPosition = Vector3.new(config.centerPosition.X, floorLevel, config.centerPosition.Z)
  2099.         caveInstance.playerSpawnPosition = Vector3.new(config.centerPosition.X, floorLevel + 3, config.centerPosition.Z + 10)
  2100.     end
  2101.  
  2102.     self:CreatePortalWoodenFrame(portalPosition, folder)
  2103.  
  2104.     local portal = Instance.new("Part")
  2105.     portal.Name = "ReturnPortal"
  2106.     portal.Size = Vector3.new(4, 12, 1)
  2107.     portal.Position = Vector3.new(portalPosition.X, portalPosition.Y + 6, portalPosition.Z)
  2108.     portal.Material = Enum.Material.Neon
  2109.     portal.Color = Color3.new(0, 0, 0)
  2110.     portal.Anchored = true
  2111.     portal.CanCollide = false
  2112.     portal.Transparency = 0
  2113.     portal.Parent = folder
  2114.  
  2115.     local portalLight = Instance.new("PointLight")
  2116.     portalLight.Brightness = 0.8
  2117.     portalLight.Color = Color3.new(0.2, 0.1, 0.3)
  2118.     portalLight.Range = 12
  2119.     portalLight.Parent = portal
  2120.  
  2121.     self:CreateDarkPortalEffects(portal, folder)
  2122.     self:SetupPortalDetection(portal, caveInstance.player)
  2123.  
  2124.     print("๐ŸŒ€ Created floor-level portal for", caveInstance.player.Name)
  2125. end
  2126.  
  2127. function CaveSystem:CreatePortalWoodenFrame(portalPosition, folder)
  2128.     local postHeight = 12
  2129.     local postWidth = 1
  2130.     local frameWidth = 5
  2131.  
  2132.     local function setSafeMaterial(part, materialName)
  2133.         local success = pcall(function()
  2134.             if materialName == "VerticalPlanks" then
  2135.                 part.Material = "VerticalPlanks"
  2136.             elseif materialName == "HorizontalPlanks" then
  2137.                 part.Material = "HorizontalPlanks"
  2138.             else
  2139.                 part.Material = Enum.Material.Wood
  2140.             end
  2141.         end)
  2142.         if not success then
  2143.             part.Material = Enum.Material.Wood
  2144.         end
  2145.     end
  2146.  
  2147.     local leftPost = Instance.new("Part")
  2148.     leftPost.Name = "PortalPost"
  2149.     leftPost.Size = Vector3.new(postWidth, postHeight, postWidth)
  2150.     leftPost.Position = Vector3.new(
  2151.         portalPosition.X - frameWidth/2,
  2152.         portalPosition.Y + postHeight/2,
  2153.         portalPosition.Z
  2154.     )
  2155.     setSafeMaterial(leftPost, "VerticalPlanks")
  2156.     leftPost.BrickColor = BrickColor.new("Dark brown")
  2157.     leftPost.Anchored = true
  2158.     leftPost.Parent = folder
  2159.  
  2160.     local rightPost = Instance.new("Part")
  2161.     rightPost.Name = "PortalPost"
  2162.     rightPost.Size = Vector3.new(postWidth, postHeight, postWidth)
  2163.     rightPost.Position = Vector3.new(
  2164.         portalPosition.X + frameWidth/2,
  2165.         portalPosition.Y + postHeight/2,
  2166.         portalPosition.Z
  2167.     )
  2168.     setSafeMaterial(rightPost, "VerticalPlanks")
  2169.     rightPost.BrickColor = BrickColor.new("Dark brown")
  2170.     rightPost.Anchored = true
  2171.     rightPost.Parent = folder
  2172.  
  2173.     local topBeam = Instance.new("Part")
  2174.     topBeam.Name = "PortalBeam"
  2175.     topBeam.Size = Vector3.new(frameWidth + postWidth, postWidth, postWidth)
  2176.     topBeam.Position = Vector3.new(
  2177.         portalPosition.X,
  2178.         portalPosition.Y + postHeight + postWidth/2,
  2179.         portalPosition.Z
  2180.     )
  2181.     setSafeMaterial(topBeam, "HorizontalPlanks")
  2182.     topBeam.BrickColor = BrickColor.new("Dark brown")
  2183.     topBeam.Anchored = true
  2184.     topBeam.Parent = folder
  2185.  
  2186.     local baseBeam = Instance.new("Part")
  2187.     baseBeam.Name = "PortalBase"
  2188.     baseBeam.Size = Vector3.new(frameWidth + postWidth, postWidth, postWidth)
  2189.     baseBeam.Position = Vector3.new(
  2190.         portalPosition.X,
  2191.         portalPosition.Y - postWidth/2,
  2192.         portalPosition.Z
  2193.     )
  2194.     setSafeMaterial(baseBeam, "HorizontalPlanks")
  2195.     baseBeam.BrickColor = BrickColor.new("Dark brown")
  2196.     baseBeam.Anchored = true
  2197.     baseBeam.Parent = folder
  2198. end
  2199.  
  2200. function CaveSystem:CreateDarkPortalEffects(portal, folder)
  2201.     local sparkles = Instance.new("Sparkles")
  2202.     sparkles.SparkleColor = Color3.new(0.2, 0.1, 0.3)
  2203.     sparkles.Parent = portal
  2204.  
  2205.     spawn(function()
  2206.         while portal.Parent do
  2207.             local light = portal:FindFirstChild("PointLight")
  2208.             if light then
  2209.                 local baseBrightness = 1
  2210.                 light.Brightness = baseBrightness + math.sin(tick() * 1.5) * 0.3
  2211.             end
  2212.             wait(0.1)
  2213.         end
  2214.     end)
  2215.  
  2216.     for i = 1, 3 do
  2217.         local particle = Instance.new("Part")
  2218.         particle.Name = "DarkPortalParticle"
  2219.         particle.Size = Vector3.new(0.3, 0.3, 0.3)
  2220.         particle.Material = Enum.Material.Neon
  2221.         particle.Color = Color3.new(0.1, 0.05, 0.2)
  2222.         particle.CanCollide = false
  2223.         particle.Anchored = true
  2224.         particle.Transparency = 0.5
  2225.         particle.Parent = folder
  2226.  
  2227.         spawn(function()
  2228.             local angle = (i / 3) * math.pi * 2
  2229.             while particle.Parent do
  2230.                 local time = tick() * 1.5 + angle
  2231.                 local radius = 2 + math.sin(time * 0.3) * 1
  2232.                 local height = math.sin(time * 1.2) * 2
  2233.  
  2234.                 particle.Position = portal.Position + Vector3.new(
  2235.                     math.cos(time) * radius,
  2236.                     height,
  2237.                     math.sin(time) * radius
  2238.                 )
  2239.                 wait(0.08)
  2240.             end
  2241.         end)
  2242.     end
  2243. end
  2244.  
  2245. function CaveSystem:SetupPortalDetection(portal, player)
  2246.     local detector = Instance.new("Part")
  2247.     detector.Name = "PortalDetector"
  2248.     detector.Size = Vector3.new(10, 12, 10)
  2249.     detector.Position = portal.Position
  2250.     detector.Transparency = 1
  2251.     detector.CanCollide = false
  2252.     detector.Anchored = true
  2253.     detector.Parent = portal.Parent
  2254.  
  2255.     detector.Touched:Connect(function(hit)
  2256.         local character = hit.Parent
  2257.         if character == player.Character and character:FindFirstChild("Humanoid") then
  2258.             wait(0.5)
  2259.             local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
  2260.             if humanoidRootPart then
  2261.                 local distance = (humanoidRootPart.Position - portal.Position).Magnitude
  2262.                 if distance < 8 then
  2263.                     if _G.ShowToast then
  2264.                         _G.ShowToast("๐ŸŒ… Returning to surface...", "Info")
  2265.                     end
  2266.                     self:TeleportPlayerBack(player)
  2267.                 end
  2268.             end
  2269.         end
  2270.     end)
  2271. end
  2272.  
  2273. function CaveSystem:GetSafeSpawnPosition(caveInstance)
  2274.     local config = caveInstance.config
  2275.     local mine = caveInstance.mine
  2276.  
  2277.     local spawnRoom = nil
  2278.     local bestRoomSize = 0
  2279.  
  2280.     if mine and mine.House and mine.House.Rooms then
  2281.         for _, room in ipairs(mine.House.Rooms) do
  2282.             local roomWidth = room.br.x - room.tl.x
  2283.             local roomHeight = room.br.y - room.tl.y
  2284.             local roomSize = roomWidth * roomHeight
  2285.  
  2286.             if roomSize > bestRoomSize then
  2287.                 bestRoomSize = roomSize
  2288.                 spawnRoom = room
  2289.             end
  2290.         end
  2291.     end
  2292.  
  2293.     if spawnRoom then
  2294.         local centerPos = config.centerPosition
  2295.         local cellSize = caveInstance.cellSize or 8
  2296.         local startX = centerPos.X - (mine.sX * cellSize / 2)
  2297.         local startZ = centerPos.Z - (mine.sY * cellSize / 2)
  2298.  
  2299.         local roomCenterX = (spawnRoom.tl.x + spawnRoom.br.x) / 2
  2300.         local roomCenterY = (spawnRoom.tl.y + spawnRoom.br.y) / 2
  2301.  
  2302.         local worldX = startX + (roomCenterX - 0.5) * cellSize
  2303.         local worldZ = startZ + (roomCenterY - 0.5) * cellSize
  2304.  
  2305.         local floorLevel = centerPos.Y - 8 + 3
  2306.  
  2307.         print("๐ŸŽฏ Calculated ground spawn: Room center at", worldX, floorLevel, worldZ)
  2308.  
  2309.         return Vector3.new(worldX, floorLevel, worldZ)
  2310.     else
  2311.         local floorLevel = config.centerPosition.Y - 8 + 3
  2312.         print("๐ŸŽฏ No room found, using fallback ground spawn at", floorLevel)
  2313.         return Vector3.new(config.centerPosition.X, floorLevel, config.centerPosition.Z + 10)
  2314.     end
  2315. end
  2316.  
  2317. function CaveSystem:TeleportPlayerToCave(player, caveType, returnPosition)
  2318.     self.playerReturnPositions[player] = returnPosition
  2319.  
  2320.     local caveInstance = nil
  2321.     if self.playerCaveInstances[player] and self.playerCaveInstances[player][caveType] then
  2322.         caveInstance = self.playerCaveInstances[player][caveType]
  2323.         print("๐Ÿš€ Using existing", caveType, "cave for", player.Name)
  2324.  
  2325.         -- REGENERATE ORES: Clear existing ores and generate new random ones
  2326.         self:ClearExistingOres(caveInstance)
  2327.         self:RegenerateRandomOres(caveInstance)
  2328.  
  2329.         -- CLEANUP: Wait for ore generation to settle, then cleanup
  2330.         print("โณ Waiting for ore generation to settle before cleanup...")
  2331.         wait(0.5) -- Give ore creation time to complete
  2332.         self:CleanupFloatingOres(caveInstance)
  2333.     else
  2334.         warn("โš ๏ธ Cave not pre-generated, creating on-demand for", player.Name)
  2335.         caveInstance = self:GetOrCreateCaveInstance(player, caveType)
  2336.     end
  2337.  
  2338.     if not caveInstance then
  2339.         warn("โŒ Failed to access cave instance")
  2340.         return false
  2341.     end
  2342.  
  2343.     if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
  2344.         self:CreateSafeSpawnZone(caveInstance)
  2345.         self:ApplyCaveSafetyMode(player, caveInstance)
  2346.  
  2347.         local humanoid = player.Character:FindFirstChild("Humanoid")
  2348.         if humanoid then
  2349.             humanoid.Health = humanoid.MaxHealth
  2350.         end
  2351.  
  2352.         wait(0.3)
  2353.  
  2354.         local spawnPosition = self:GetSafeSpawnPosition(caveInstance)
  2355.         player.Character.HumanoidRootPart.CFrame = CFrame.new(spawnPosition)
  2356.  
  2357.         if humanoid then
  2358.             humanoid.Health = humanoid.MaxHealth
  2359.         end
  2360.  
  2361.         print("โšก Teleported", player.Name, "to floor level in", caveType, "cave at", spawnPosition)
  2362.  
  2363.         if _G.ShowToast then
  2364.             _G.ShowToast("โœ… Entered " .. caveType .. " Cave - Fresh randomized TestOres!", "Success")
  2365.         end
  2366.  
  2367.         return true
  2368.     end
  2369.  
  2370.     return false
  2371. end
  2372.  
  2373. function CaveSystem:TeleportPlayerBack(player)
  2374.     local returnPosition = self.playerReturnPositions[player]
  2375.  
  2376.     if returnPosition and player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
  2377.         self:RemoveCaveSafetyMode(player, "all")
  2378.  
  2379.         player.Character.HumanoidRootPart.CFrame = CFrame.new(returnPosition)
  2380.         print("๐Ÿ  Teleported", player.Name, "back to surface")
  2381.         self.playerReturnPositions[player] = nil
  2382.  
  2383.         self:RemoveCaveAtmosphere(player)
  2384.         self:DespawnPlayerCaves(player)
  2385.  
  2386.         if _G.ShowToast then
  2387.             _G.ShowToast("๐ŸŒ… Returned to surface - Safety mode deactivated", "Success")
  2388.         end
  2389.     end
  2390. end
  2391.  
  2392. -- ============================================================================
  2393. -- ATMOSPHERE AND UTILITY FUNCTIONS
  2394. -- ============================================================================
  2395.  
  2396. function CaveSystem:CreateHiddenWalls(caveInstance)
  2397.     local config = caveInstance.config
  2398.     local folder = caveInstance.folder
  2399.  
  2400.     for _, passage in ipairs(caveInstance.hiddenPassages) do
  2401.         local wall = Instance.new("Part")
  2402.         wall.Name = "HiddenWall_" .. passage.id
  2403.         wall.Size = passage.crackSize
  2404.         wall.Position = passage.position
  2405.         wall.Material = Enum.Material[config.properties.wallMaterial] or Enum.Material.Rock
  2406.         wall.Color = Color3.new(config.properties.wallColor.r, config.properties.wallColor.g, config.properties.wallColor.b)
  2407.         wall.Anchored = true
  2408.         wall.Parent = folder
  2409.  
  2410.         local crack = Instance.new("Part")
  2411.         crack.Name = "HiddenCrack_" .. passage.id
  2412.         crack.Size = passage.crackSize + Vector3.new(0.1, 0.1, 0.1)
  2413.         crack.Position = passage.position
  2414.         crack.Material = Enum.Material.Neon
  2415.         crack.Color = Color3.new(1, 0.5, 0)
  2416.         crack.Anchored = true
  2417.         crack.CanCollide = false
  2418.         crack.Transparency = 1
  2419.         crack.Parent = folder
  2420.  
  2421.         self:SetupCrackDetection(wall, crack, passage, caveInstance.player)
  2422.     end
  2423.  
  2424.     print("๐Ÿ” Created", #caveInstance.hiddenPassages, "hidden passages")
  2425. end
  2426.  
  2427. function CaveSystem:SetupCrackDetection(wall, crack, passage, player)
  2428.     local connection = RunService.Heartbeat:Connect(function()
  2429.         if player.Character then
  2430.             local tool = player.Character:FindFirstChild("CaveDetector")
  2431.             crack.Transparency = tool and 0 or 1
  2432.         end
  2433.     end)
  2434.  
  2435.     local clickDetector = Instance.new("ClickDetector")
  2436.     clickDetector.MaxActivationDistance = 10
  2437.     clickDetector.Parent = wall
  2438.  
  2439.     clickDetector.MouseClick:Connect(function(clickingPlayer)
  2440.         if clickingPlayer == player and crack.Transparency == 0 then
  2441.             self:BreakHiddenWall(wall, crack, passage, player)
  2442.             connection:Disconnect()
  2443.         end
  2444.     end)
  2445. end
  2446.  
  2447. function CaveSystem:BreakHiddenWall(wall, crack, passage, player)
  2448.     print("๐Ÿ’ฅ Breaking hidden wall for", player.Name)
  2449.  
  2450.     local explosion = Instance.new("Explosion")
  2451.     explosion.Position = wall.Position
  2452.     explosion.BlastRadius = 15
  2453.     explosion.BlastPressure = 0
  2454.     explosion.Parent = workspace
  2455.  
  2456.     wall:Destroy()
  2457.     crack:Destroy()
  2458.  
  2459.     self:CreateSecretChamber(passage, player)
  2460.     passage.broken = true
  2461. end
  2462.  
  2463. function CaveSystem:CreateSecretChamber(passage, player)
  2464.     local chamber = passage.leadsTo
  2465.     local tunnelStart = passage.position
  2466.     local tunnelEnd = chamber.position
  2467.     local direction = (tunnelEnd - tunnelStart).Unit
  2468.     local distance = (tunnelEnd - tunnelStart).Magnitude
  2469.  
  2470.     for i = 0, distance, 8 do
  2471.         local pos = tunnelStart + direction * i
  2472.         pos = Vector3.new(
  2473.             math.floor(pos.X / 4) * 4,
  2474.             math.floor(pos.Y / 4) * 4,
  2475.             math.floor(pos.Z / 4) * 4
  2476.         )
  2477.  
  2478.         local region = Region3.new(
  2479.             pos - Vector3.new(4, 4, 4),
  2480.             pos + Vector3.new(4, 4, 4)
  2481.         ):ExpandToGrid(4)
  2482.         workspace.Terrain:FillRegion(region, 4, Enum.Material.Air)
  2483.     end
  2484.  
  2485.     local alignedChamberPos = Vector3.new(
  2486.         math.floor(chamber.position.X / 4) * 4,
  2487.         math.floor(chamber.position.Y / 4) * 4,
  2488.         math.floor(chamber.position.Z / 4) * 4
  2489.     )
  2490.  
  2491.     local chamberRegion = Region3.new(
  2492.         alignedChamberPos - chamber.size/2,
  2493.         alignedChamberPos + chamber.size/2
  2494.     ):ExpandToGrid(4)
  2495.     workspace.Terrain:FillRegion(chamberRegion, 4, Enum.Material.Air)
  2496.  
  2497.     self:SpawnLoot(chamber, player)
  2498.     print("๐Ÿ›๏ธ Created secret chamber for", player.Name)
  2499. end
  2500.  
  2501. function CaveSystem:SpawnLoot(chamber, player)
  2502.     for i = 1, chamber.lootSpawns do
  2503.         local lootPos = chamber.position + Vector3.new(
  2504.             (math.random() - 0.5) * chamber.size.X * 0.8,
  2505.             -chamber.size.Y/2 + 2,
  2506.             (math.random() - 0.5) * chamber.size.Z * 0.8
  2507.         )
  2508.  
  2509.         local loot = Instance.new("Part")
  2510.         loot.Name = "LootChest"
  2511.         loot.Size = Vector3.new(3, 2, 2)
  2512.         loot.Position = lootPos
  2513.         loot.Material = Enum.Material.Wood
  2514.         loot.BrickColor = BrickColor.new("Dark brown")
  2515.         loot.Anchored = true
  2516.         loot.Parent = workspace
  2517.  
  2518.         local light = Instance.new("PointLight")
  2519.         light.Brightness = 3
  2520.         light.Color = Color3.new(1, 0.8, 0.2)
  2521.         light.Range = 15
  2522.         light.Parent = loot
  2523.  
  2524.         local sparkle = Instance.new("Sparkles")
  2525.         sparkle.SparkleColor = Color3.new(1, 1, 0)
  2526.         sparkle.Parent = loot
  2527.     end
  2528. end
  2529.  
  2530. function CaveSystem:AddCaveAtmosphere(caveInstance)
  2531.     local config = caveInstance.config
  2532.     local player = caveInstance.player
  2533.  
  2534.     caveInstance.atmosphereConfig = {
  2535.         tintColor = Color3.new(
  2536.             config.properties.lighting.color.r * 0.7,
  2537.             config.properties.lighting.color.g * 0.7,
  2538.             config.properties.lighting.color.b * 0.7
  2539.         ),
  2540.         brightness = -0.3,
  2541.         contrast = 0.2,
  2542.         saturation = -0.1,
  2543.         fogConfig = {
  2544.             density = 0.3,
  2545.             offset = 0.2,
  2546.             color = Color3.new(
  2547.                 config.properties.lighting.color.r * 0.8,
  2548.                 config.properties.lighting.color.g * 0.8,
  2549.                 config.properties.lighting.color.b * 0.8
  2550.             ),
  2551.             decay = Color3.new(0.6, 0.6, 0.7),
  2552.             glare = 0.4,
  2553.             haze = 0.4
  2554.         }
  2555.     }
  2556.  
  2557.     print("๐ŸŒ‘ Cave atmosphere config prepared for", player.Name)
  2558. end
  2559.  
  2560. function CaveSystem:RemoveCaveAtmosphere(player)
  2561.     for _, effect in pairs(game.Lighting:GetChildren()) do
  2562.         if effect.Name:find("CaveAmbient_" .. player.Name) or effect.Name:find("CaveFog_" .. player.Name) then
  2563.             effect:Destroy()
  2564.         end
  2565.     end
  2566.     print("๐ŸŒ… Removed cave atmosphere for", player.Name)
  2567. end
  2568.  
  2569. function CaveSystem:GetOrCreateCaveInstance(player, caveType)
  2570.     if self.playerCaveInstances[player] and self.playerCaveInstances[player][caveType] then
  2571.         return self.playerCaveInstances[player][caveType]
  2572.     end
  2573.     return self:CreateCaveInstance(caveType, player)
  2574. end
  2575.  
  2576. function CaveSystem:CloneHiddenPassages(passages, player)
  2577.     local cloned = {}
  2578.     for _, passage in ipairs(passages) do
  2579.         table.insert(cloned, {
  2580.             id = passage.id,
  2581.             position = passage.position,
  2582.             crackSize = passage.crackSize,
  2583.             leadsTo = passage.leadsTo,
  2584.             requiredTool = passage.requiredTool,
  2585.             broken = false
  2586.         })
  2587.     end
  2588.     return cloned
  2589. end
  2590.  
  2591. function CaveSystem:DespawnPlayerCaves(player)
  2592.     if self.playerCaveInstances[player] then
  2593.         print("๐Ÿ—‘๏ธ Despawning caves for", player.Name)
  2594.  
  2595.         for caveType, instance in pairs(self.playerCaveInstances[player]) do
  2596.             if instance.folder then
  2597.                 print("๐Ÿ—‘๏ธ Destroying", caveType, "cave for", player.Name)
  2598.                 self:RestoreCaveTerrain(instance)
  2599.                 instance.folder:Destroy()
  2600.             end
  2601.         end
  2602.  
  2603.         self.playerCaveInstances[player] = nil
  2604.         print("โœ… All caves and terrain despawned for", player.Name)
  2605.     end
  2606. end
  2607.  
  2608. function CaveSystem:RestoreCaveTerrain(caveInstance)
  2609.     local config = caveInstance.config
  2610.  
  2611.     if config and config.centerPosition and config.size then
  2612.         print("๐Ÿชจ Restoring terrain for cave...")
  2613.         local centerPos = config.centerPosition
  2614.         local expandedSize = config.size * 1.3
  2615.  
  2616.         local rockRegion = Region3.new(
  2617.             centerPos - expandedSize/2,
  2618.             centerPos + expandedSize/2
  2619.         ):ExpandToGrid(4)
  2620.         workspace.Terrain:FillRegion(rockRegion, 4, Enum.Material.Rock)
  2621.         print("โœ… Cave terrain restored to solid rock")
  2622.     else
  2623.         warn("โš ๏ธ Could not restore terrain - missing cave config data")
  2624.     end
  2625. end
  2626.  
  2627. function CaveSystem:CleanupPlayerCaves(player)
  2628.     self:DespawnPlayerCaves(player)
  2629.     self.playerReturnPositions[player] = nil
  2630.  
  2631.     for _, effect in pairs(game.Lighting:GetChildren()) do
  2632.         if effect.Name:find("CaveAmbient_" .. player.Name) or effect.Name:find("CaveFog_" .. player.Name) then
  2633.             effect:Destroy()
  2634.         end
  2635.     end
  2636.  
  2637.     print("๐Ÿงน Cleaned up all cave data for", player.Name)
  2638. end
  2639.  
  2640. function CaveSystem:ClearAllCaves()
  2641.     for player, caves in pairs(self.playerCaveInstances) do
  2642.         for _, instance in pairs(caves) do
  2643.             if instance.folder then
  2644.                 instance.folder:Destroy()
  2645.             end
  2646.         end
  2647.     end
  2648.     self.playerCaveInstances = {}
  2649.  
  2650.     for _, effect in pairs(game.Lighting:GetChildren()) do
  2651.         if effect.Name:find("CaveAmbient_") or effect.Name:find("CaveFog_") then
  2652.             effect:Destroy()
  2653.         end
  2654.     end
  2655.  
  2656.     print("๐Ÿงน Cleared all cave instances")
  2657. end
  2658.  
  2659. function CaveSystem:Initialize()
  2660.     print("๐Ÿš€ Initializing Dark Cave System...")
  2661.  
  2662.     local success, err = pcall(function()
  2663.         if self:ShouldRegenerateCaves() then
  2664.             self:GenerateWeeklyCaves()
  2665.         end
  2666.     end)
  2667.  
  2668.     if not success then
  2669.         warn("โŒ Error during cave generation:", err)
  2670.         print("๐Ÿ”„ Retrying cave system initialization...")
  2671.         wait(2)
  2672.         self.currentWeek = self:GetCurrentWeek()
  2673.         self.caveConfigs = {}
  2674.     end
  2675.  
  2676.     Players.PlayerAdded:Connect(function(player)
  2677.         print("๐Ÿ‘‹ Player joined:", player.Name)
  2678.     end)
  2679.  
  2680.     Players.PlayerRemoving:Connect(function(player)
  2681.         self:CleanupPlayerCaves(player)
  2682.     end)
  2683.  
  2684.     print("โœ… Dark Cave System initialized - caves generate on-demand")
  2685. end
  2686.  
  2687. -- ============================================================================
  2688. -- REMOTE EVENTS AND GLOBAL FUNCTIONS
  2689. -- ============================================================================
  2690.  
  2691. local enterCaveEvent = Instance.new("RemoteEvent")
  2692. enterCaveEvent.Name = "EnterCaveEvent"
  2693. enterCaveEvent.Parent = ReplicatedStorage
  2694.  
  2695. enterCaveEvent.OnServerEvent:Connect(function(player, caveType, returnPosition)
  2696.     local success, err = pcall(function()
  2697.         CaveSystem:TeleportPlayerToCave(player, caveType, returnPosition)
  2698.     end)
  2699.     if not success then
  2700.         warn("โŒ Error teleporting player to cave:", err)
  2701.     end
  2702. end)
  2703.  
  2704. _G.CaveSystem = CaveSystem
  2705.  
  2706. _G.GenerateCaveForPlayer = function(player, caveType)
  2707.     if CaveSystem and player and caveType then
  2708.         return CaveSystem:CreateCaveInstance(caveType, player)
  2709.     end
  2710. end
  2711.  
  2712. _G.GetPlayerCaveStatus = function(player)
  2713.     if CaveSystem.playerCaveInstances[player] then
  2714.         local status = {}
  2715.         for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  2716.             status[caveType] = {
  2717.                 active = instance and true or false,
  2718.                 instancePosition = instance.instancePosition,
  2719.                 isInstancedDimension = instance.isInstancedDimension,
  2720.                 safetyActive = instance.safetySystem and instance.safetySystem.isActive or false
  2721.             }
  2722.         end
  2723.         return status
  2724.     end
  2725.     return "No active cave dimensions"
  2726. end
  2727.  
  2728. _G.GetInstanceDimensionInfo = function()
  2729.     return {
  2730.         baseCavePosition = CaveSystem.baseCavePosition,
  2731.         instanceOffsets = {
  2732.             Crystal = Vector3.new(0, 0, 0),
  2733.             Underground = Vector3.new(1000, 0, 0),
  2734.             Lava = Vector3.new(2000, 0, 0),
  2735.             Ice = Vector3.new(0, 0, 1000),
  2736.             Ancient = Vector3.new(1000, 0, 1000)
  2737.         },
  2738.         actualPositions = {
  2739.             Crystal = CaveSystem.baseCavePosition + Vector3.new(0, 0, 0),
  2740.             Underground = CaveSystem.baseCavePosition + Vector3.new(1000, 0, 0),
  2741.             Lava = CaveSystem.baseCavePosition + Vector3.new(2000, 0, 0),
  2742.             Ice = CaveSystem.baseCavePosition + Vector3.new(0, 0, 1000),
  2743.             Ancient = CaveSystem.baseCavePosition + Vector3.new(1000, 0, 1000)
  2744.         },
  2745.         note = "All caves now generate at HIGH ALTITUDE (Y=2000+) for safety"
  2746.     }
  2747. end
  2748.  
  2749. _G.ClearAllInstanceDimensions = function()
  2750.     for _, player in pairs(game.Players:GetPlayers()) do
  2751.         if CaveSystem.playerCaveInstances[player] then
  2752.             CaveSystem:DespawnPlayerCaves(player)
  2753.         end
  2754.     end
  2755.  
  2756.     local clearRegion = Region3.new(
  2757.         Vector3.new(-1000, 1800, -1000),
  2758.         Vector3.new(3000, 2200, 2000)
  2759.     ):ExpandToGrid(4)
  2760.     workspace.Terrain:FillRegion(clearRegion, 4, Enum.Material.Air)
  2761.     print("๐ŸŒŒ Cleared all instance dimensions")
  2762. end
  2763.  
  2764. _G.EnableCaveSafetyForPlayer = function(player)
  2765.     if CaveSystem.playerCaveInstances[player] then
  2766.         for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  2767.             CaveSystem:ApplyCaveSafetyMode(player, instance)
  2768.         end
  2769.         print("๐Ÿ›ก๏ธ Enabled cave safety for", player.Name)
  2770.     end
  2771. end
  2772.  
  2773. _G.DisableCaveSafetyForPlayer = function(player)
  2774.     CaveSystem:RemoveCaveSafetyMode(player, "all")
  2775.     print("๐Ÿ›ก๏ธ Disabled cave safety for", player.Name)
  2776. end
  2777.  
  2778. _G.TeleportPlayerToSafety = function(player)
  2779.     if player.Character and CaveSystem.playerCaveInstances[player] then
  2780.         for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  2781.             local safePos = CaveSystem:GetSafeSpawnPosition(instance)
  2782.             player.Character.HumanoidRootPart.CFrame = CFrame.new(safePos)
  2783.  
  2784.             local humanoid = player.Character:FindFirstChild("Humanoid")
  2785.             if humanoid then
  2786.                 humanoid.Health = humanoid.MaxHealth
  2787.             end
  2788.  
  2789.             print("๐Ÿ›ก๏ธ Teleported", player.Name, "to safety in", caveType, "cave")
  2790.             break
  2791.         end
  2792.     end
  2793. end
  2794.  
  2795. _G.DebugCaveSpawnInfo = function(player)
  2796.     if CaveSystem.playerCaveInstances[player] then
  2797.         for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  2798.             print("๐Ÿ” DEBUG:", caveType, "cave for", player.Name)
  2799.             print("๐Ÿ” Cave center position:", instance.config.centerPosition)
  2800.             print("๐Ÿ” Player spawn position:", instance.playerSpawnPosition)
  2801.             print("๐Ÿ” Portal position:", instance.config.portalPosition)
  2802.  
  2803.             if instance.mine and instance.mine.House then
  2804.                 print("๐Ÿ” Number of rooms:", #instance.mine.House.Rooms)
  2805.                 for i, room in ipairs(instance.mine.House.Rooms) do
  2806.                     local roomWidth = room.br.x - room.tl.x + 1
  2807.                     local roomHeight = room.br.y - room.tl.y + 1
  2808.                     print("๐Ÿ” Room", i .. ":", "Size", roomWidth .. "x" .. roomHeight, "at grid", room.tl.x .. "," .. room.tl.y)
  2809.                 end
  2810.             end
  2811.             break
  2812.         end
  2813.     else
  2814.         print("๐Ÿ” No active caves for", player.Name)
  2815.     end
  2816. end
  2817.  
  2818. _G.DebugNeighborCountOres = function(player)
  2819.     if CaveSystem.playerCaveInstances[player] then
  2820.         for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  2821.             local mine = instance.mine
  2822.             if mine and mine.House then
  2823.                 print("๐Ÿ” NEIGHBOR COUNT ORE DEBUG for", caveType, "cave:")
  2824.                 print("๐Ÿ” Logic: 2-3 neighbors = wall cell, 4 neighbors = interior cell")
  2825.                 print("๐Ÿ” Corridor Detection: Skip walls adjacent to corridors")
  2826.                 print("๐Ÿ” TestOre Integration: Uses Materials/TestOre when available")
  2827.  
  2828.                 for i, room in ipairs(mine.House.Rooms) do
  2829.                     local roomWidth = room.br.x - room.tl.x + 1
  2830.                     local roomHeight = room.br.y - room.tl.y + 1
  2831.                     print("๐Ÿ” Room", i, "dimensions:", roomWidth .. "x" .. roomHeight)
  2832.                     print("๐Ÿ” Room bounds: (", room.tl.x, room.tl.y, ") to (", room.br.x, room.br.y, ")")
  2833.  
  2834.                     local wallCells = 0
  2835.                     local interiorCells = 0
  2836.                     local corridorAdjacent = 0
  2837.                     local validWalls = 0
  2838.  
  2839.                     for x = room.tl.x, room.br.x do
  2840.                         for y = room.tl.y, room.br.y do
  2841.                             local neighborCount = room:CountRoomNeighbors(mine, x, y)
  2842.                             if neighborCount == 2 or neighborCount == 3 then
  2843.                                 wallCells = wallCells + 1
  2844.  
  2845.                                 if room:IsValidOreWallCell(mine, x, y) then
  2846.                                     validWalls = validWalls + 1
  2847.                                 else
  2848.                                     corridorAdjacent = corridorAdjacent + 1
  2849.                                 end
  2850.                             elseif neighborCount == 4 then
  2851.                                 interiorCells = interiorCells + 1
  2852.                             end
  2853.                         end
  2854.                     end
  2855.  
  2856.                     print("๐Ÿ” Wall cells (2-3 neighbors):", wallCells)
  2857.                     print("๐Ÿ” Valid wall cells (not adjacent to corridors):", validWalls)
  2858.                     print("๐Ÿ” Walls adjacent to corridors (skipped):", corridorAdjacent)
  2859.                     print("๐Ÿ” Interior cells (4 neighbors):", interiorCells)
  2860.                     print("๐Ÿ” Planned TestOres:", #room.OrePositions)
  2861.  
  2862.                     for j, oreData in ipairs(room.OrePositions) do
  2863.                         print("  TestOre", j, "at grid (", oreData.gridX, oreData.gridY, ") facing", oreData.direction, "with", oreData.neighborCount, "neighbors")
  2864.                     end
  2865.  
  2866.                     if i >= 3 then break end
  2867.                 end
  2868.             end
  2869.             break
  2870.         end
  2871.     end
  2872. end
  2873.  
  2874. _G.CheckTestOreAvailability = function()
  2875.     local materialsFolder = workspace:FindFirstChild("Materials")
  2876.     local testOre = materialsFolder and materialsFolder:FindFirstChild("TestOre")
  2877.  
  2878.     if testOre then
  2879.         print("โœ… TestOre found in Materials folder")
  2880.         print("๐Ÿ” TestOre properties:")
  2881.         print("  - Name:", testOre.Name)
  2882.         print("  - Type:", testOre.ClassName)
  2883.  
  2884.         if testOre:IsA("Model") then
  2885.             print("  - Is Model: true")
  2886.             print("  - PrimaryPart:", testOre.PrimaryPart and testOre.PrimaryPart.Name or "None")
  2887.             if testOre.PrimaryPart then
  2888.                 print("  - PrimaryPart Size:", testOre.PrimaryPart.Size)
  2889.                 print("  - PrimaryPart Material:", testOre.PrimaryPart.Material)
  2890.                 print("  - PrimaryPart Color:", testOre.PrimaryPart.Color)
  2891.             end
  2892.         else
  2893.             print("  - Is Part: true")
  2894.             print("  - Size:", testOre.Size)
  2895.             print("  - Material:", testOre.Material)
  2896.             print("  - Color:", testOre.Color)
  2897.         end
  2898.  
  2899.         print("  - Children count:", #testOre:GetChildren())
  2900.  
  2901.         for _, child in ipairs(testOre:GetChildren()) do
  2902.             print("    - Child:", child.Name, "(" .. child.ClassName .. ")")
  2903.         end
  2904.  
  2905.         return true
  2906.     else
  2907.         warn("โŒ TestOre not found in Materials folder")
  2908.         if not materialsFolder then
  2909.             warn("โŒ Materials folder not found in workspace")
  2910.         else
  2911.             print("๐Ÿ“ Materials folder contents:")
  2912.             for _, child in ipairs(materialsFolder:GetChildren()) do
  2913.                 print("  - " .. child.Name .. " (" .. child.ClassName .. ")")
  2914.             end
  2915.         end
  2916.         return false
  2917.     end
  2918. end
  2919.  
  2920. _G.CountCaveTestOres = function(player)
  2921.     if not CaveSystem.playerCaveInstances[player] then
  2922.         print("๐Ÿ” No active caves for", player.Name)
  2923.         return
  2924.     end
  2925.  
  2926.     for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  2927.         local folder = instance.folder
  2928.         if folder then
  2929.             local testOreCount = 0
  2930.             local fallbackOreCount = 0
  2931.  
  2932.             for _, child in ipairs(folder:GetChildren()) do
  2933.                 if child.Name:find("CaveOre_") then
  2934.                     testOreCount = testOreCount + 1
  2935.                 elseif child.Name:find("FallbackOre_") then
  2936.                     fallbackOreCount = fallbackOreCount + 1
  2937.                 end
  2938.             end
  2939.  
  2940.             print("๐Ÿ”", caveType, "cave for", player.Name .. ":")
  2941.             print("  - TestOre clones:", testOreCount)
  2942.             print("  - Fallback ores:", fallbackOreCount)
  2943.             print("  - Total ores:", testOreCount + fallbackOreCount)
  2944.         end
  2945.         break
  2946.     end
  2947. end
  2948.  
  2949. _G.FindCaveOresByType = function(player, caveType)
  2950.     if not CaveSystem.playerCaveInstances[player] or not CaveSystem.playerCaveInstances[player][caveType] then
  2951.         print("๐Ÿ” No", caveType, "cave found for", player.Name)
  2952.         return {}
  2953.     end
  2954.  
  2955.     local instance = CaveSystem.playerCaveInstances[player][caveType]
  2956.     local folder = instance.folder
  2957.     local ores = {}
  2958.  
  2959.     if folder then
  2960.         for _, child in ipairs(folder:GetChildren()) do
  2961.             if child.Name:find("CaveOre_" .. caveType) or child.Name:find("FallbackOre_" .. caveType) then
  2962.                 local oreInfo = {
  2963.                     name = child.Name,
  2964.                     position = CaveSystem:GetOrePosition(child),
  2965.                     isTestOre = child.Name:find("CaveOre_") ~= nil
  2966.                 }
  2967.  
  2968.                 local caveTypeValue = child:FindFirstChild("CaveType")
  2969.                 local neighborCountValue = child:FindFirstChild("NeighborCount")
  2970.                 local gridPositionValue = child:FindFirstChild("GridPosition")
  2971.  
  2972.                 if caveTypeValue then oreInfo.caveType = caveTypeValue.Value end
  2973.                 if neighborCountValue then oreInfo.neighborCount = neighborCountValue.Value end
  2974.                 if gridPositionValue then oreInfo.gridPosition = gridPositionValue.Value end
  2975.  
  2976.                 table.insert(ores, oreInfo)
  2977.             end
  2978.         end
  2979.     end
  2980.  
  2981.     print("๐Ÿ” Found", #ores, "ores in", caveType, "cave for", player.Name)
  2982.     for i, ore in ipairs(ores) do
  2983.         local oreType = ore.isTestOre and "TestOre Clone" or "Fallback Ore"
  2984.         print("  " .. i .. ".", oreType, "at", ore.position, "neighbors:", ore.neighborCount or "unknown")
  2985.     end
  2986.  
  2987.     return ores
  2988. end
  2989.  
  2990. _G.CleanupFloatingOres = function(player)
  2991.     if not CaveSystem.playerCaveInstances[player] then
  2992.         print("๐Ÿ” No active caves for", player.Name)
  2993.         return
  2994.     end
  2995.  
  2996.     for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  2997.         print("๐Ÿงน Manually cleaning floating ores in", caveType, "cave for", player.Name)
  2998.         CaveSystem:CleanupFloatingOres(instance)
  2999.         break
  3000.     end
  3001. end
  3002.  
  3003. _G.DisableOreCleanup = function(player)
  3004.     if CaveSystem.playerCaveInstances[player] then
  3005.         for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  3006.             instance.oresCleanedUp = true
  3007.             print("๐Ÿ›ก๏ธ Disabled ore cleanup for", caveType, "cave - ores will persist")
  3008.         end
  3009.     end
  3010. end
  3011.  
  3012. _G.EnableOreCleanup = function(player)
  3013.     if CaveSystem.playerCaveInstances[player] then
  3014.         for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  3015.             instance.oresCleanedUp = false
  3016.             print("๐Ÿงน Enabled ore cleanup for", caveType, "cave - floating ores will be removed")
  3017.         end
  3018.     end
  3019. end
  3020.  
  3021. _G.ForceOreCleanup = function(player)
  3022.     if CaveSystem.playerCaveInstances[player] then
  3023.         for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  3024.             print("๐Ÿงน Force cleaning floating ores in", caveType, "cave for", player.Name)
  3025.             CaveSystem:CleanupFloatingOres(instance)
  3026.         end
  3027.     end
  3028. end
  3029.  
  3030. _G.TestRandomOreGeneration = function(player)
  3031.     if not CaveSystem.playerCaveInstances[player] then
  3032.         print("๐Ÿ” No active caves for", player.Name)
  3033.         return
  3034.     end
  3035.  
  3036.     for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  3037.         print("๐ŸŽฒ Testing random ore generation for", caveType, "cave...")
  3038.  
  3039.         -- Show current ore positions
  3040.         print("๐Ÿ” Current ore positions:")
  3041.         CaveSystem:ClearExistingOres(instance)
  3042.  
  3043.         -- Generate new random positions
  3044.         print("๐ŸŽฒ Generating new random positions...")
  3045.         CaveSystem:RegenerateRandomOres(instance)
  3046.  
  3047.         -- Clean up any floating ones
  3048.         CaveSystem:CleanupFloatingOres(instance)
  3049.  
  3050.         print("โœ… Random ore generation test complete!")
  3051.         break
  3052.     end
  3053. end
  3054.  
  3055. _G.GetOreGenerationStats = function(player)
  3056.     if not CaveSystem.playerCaveInstances[player] then
  3057.         print("๐Ÿ” No active caves for", player.Name)
  3058.         return
  3059.     end
  3060.  
  3061.     for caveType, instance in pairs(CaveSystem.playerCaveInstances[player]) do
  3062.         local mine = instance.mine
  3063.         if mine and mine.House then
  3064.             print("๐Ÿ“Š Ore generation statistics for", caveType, "cave:")
  3065.  
  3066.             local totalPlanned = 0
  3067.             local totalActual = 0
  3068.  
  3069.             -- Count planned ores
  3070.             for _, room in ipairs(mine.House.Rooms) do
  3071.                 totalPlanned = totalPlanned + #room.OrePositions
  3072.  
  3073.                 print("  Room", room.tl.x .. "," .. room.tl.y, "planned ores:", #room.OrePositions)
  3074.                 for _, oreData in ipairs(room.OrePositions) do
  3075.                     if oreData.spawnTime then
  3076.                         print("    - Generated at:", os.date("%H:%M:%S", oreData.spawnTime))
  3077.                     end
  3078.                 end
  3079.             end
  3080.  
  3081.             -- Count actual ores in world
  3082.             local folder = instance.folder
  3083.             if folder then
  3084.                 for _, child in pairs(folder:GetChildren()) do
  3085.                     if child.Name:find("CaveOre_") or child.Name:find("FallbackOre_") then
  3086.                         totalActual = totalActual + 1
  3087.                     end
  3088.                 end
  3089.             end
  3090.  
  3091.             print("๐Ÿ“Š Total planned ores:", totalPlanned)
  3092.             print("๐Ÿ“Š Total actual ores:", totalActual)
  3093.             print("๐Ÿ“Š Success rate:", math.floor(totalActual / math.max(totalPlanned, 1) * 100) .. "%")
  3094.         end
  3095.         break
  3096.     end
  3097. end
  3098.  
  3099. -- Initialize the system
  3100. spawn(function()
  3101.     CaveSystem:Initialize()
  3102. end)
  3103.  
  3104. print("๐ŸŒŒ DARK CAVE SYSTEM: Instanced dimension system active!")
  3105. print("๐Ÿ“ Each cave type gets its own isolated dimension")
  3106. print("๐ŸŽฏ Unlimited space - no terrain conflicts possible")
  3107. print("๐ŸŒ Main world remains completely untouched")
  3108. print("๐Ÿš€ Use _G.GetInstanceDimensionInfo() to check dimension layout")
  3109. print("๐Ÿงน Use _G.ClearAllInstanceDimensions() to clear all instances")
  3110. print("")
  3111. print("๐Ÿ›ก๏ธ CAVE SAFETY SYSTEM: Death prevention active for all cave dimensions!")
  3112. print("๐Ÿ›ก๏ธ Features: Damage immunity, death prevention, safety zones, fall protection")
  3113. print("๐Ÿ›ก๏ธ Use _G.EnableCaveSafetyForPlayer(player) to manually enable safety")
  3114. print("๐Ÿ›ก๏ธ Use _G.TeleportPlayerToSafety(player) for emergency rescue")
  3115. print("")
  3116. print("โ›๏ธ NEIGHBOR COUNT ORE SYSTEM: Wall detection using room neighbor logic!")
  3117. print("โ›๏ธ Logic: Count room neighbors โ†’ 2-3 neighbors = wall cell โ†’ Place TestOre at edge")
  3118. print("โ›๏ธ Position: Grid center + direction * (cellSize / 2) = wall edge")
  3119. print("โ›๏ธ TestOre Integration: Uses workspace.Materials.TestOre when available")
  3120. print("โ›๏ธ Fallback: Creates basic ores if TestOre not found")
  3121. print("")
  3122. print("๐Ÿ” DEBUGGING FUNCTIONS:")
  3123. print("๐Ÿ” Use _G.DebugCaveSpawnInfo(player) to debug cave structure")
  3124. print("๐Ÿ” Use _G.DebugNeighborCountOres(player) to see neighbor count analysis")
  3125. print("๐Ÿ” Use _G.CheckTestOreAvailability() to verify TestOre exists")
  3126. print("๐Ÿ” Use _G.CountCaveTestOres(player) to count ores in player's caves")
  3127. print("๐Ÿ” Use _G.FindCaveOresByType(player, caveType) to find specific cave ores")
  3128.  
  3129. return CaveSystem
Tags: Roblox luau
Advertisement
Add Comment
Please, Sign In to add comment