Hello! I’m currently working on a simple mining game, and am currently trying to generate caves. The functions below handle all the logic that goes into it, mainly the caveGen() function, which uses a flood fill algorithm. Unfortunately it’s pretty unoptimized and I have absolutely no clue how to improve it, I’m fairly new to this kind of algorithm. It takes a while for the server to process, way too long compared to what I’ve seen other games pull off.
Let me know if I need to supply any more information. The isCave() function just returns a set math.noise() function. I’m looking to optimize how it loops through all the positions.
local generatingCave = false
local function caveGen(Pos)
generatingCave = true
local queue = {}
local isChecked = {}
local lastLen = 0
table.insert(queue, Pos)
while #queue ~= 0 do
local Point = queue[1]
table.remove(queue, 1)
if table.find(isChecked, Point) == nil then
table.insert(isChecked, Point)
if isCave(Point) then
for _,v in Helper.adjacent(Point) do
if not table.find(isChecked, v) then
table.insert(queue, v)
end
end
end
end
task.wait()
end
generatingCave = false
return isChecked
end
local function fabricateOre(Ore, Pos : Vector3)
if isCave(Pos) then
print("Is a cave!")
local CaveArray = caveGen(Pos)
for _,v in CaveArray do
if isCave(v) then
table.insert(PositionArray, v)
for _,w in Helper.adjacent(v) do
if not table.find(PositionArray, w) and w.Y <= 0 and not isCave(w) then
fabricateOre(randomPick(w.Y), w)
end
end
else
print("What are you doing here.")
end
end
for _,w in Helper.adjacent(Pos) do
if not table.find(PositionArray, w) and w.Y <= 0 and not isCave(w) then
fabricateOre(randomPick(w.Y), w)
end
end
print("FINSIHED!")
end
local ActualOre = OreStorage:FindFirstChild(Ore)
table.insert(PositionArray, Pos)
local NewOre = ActualOre:Clone()
NewOre.Position = Helper.convertFrom(Pos)
NewOre.Parent = Ores
end
Edit: I’d like to append some more information. It seems after testing it can actually be really quick, or at least as quick as realistic. But I still think it’s likely tanking server performance every time one generates. Here’s an example of what the caves look like when finished.

