How do I make this faster?

Hello! so I been working on my voxel destruction physics but I find a problem that I couldn’t fix on my own and it the physics performance I try a lot of method but I still get 50ms on the get connected parts

--!native
--!optimize 2

local Physic = {}
local Blink = require(game.ReplicatedStorage.Blink.Server)
local Config = require(script.Parent.Config)
local MsConvert = require(script.Parent.MSConvert)
local WeldCache = require(script.WeldCache)
local Queuer = require(script.Parent.Queue)
local Cache = WeldCache.new(10000, 100)

local tempDeque = table.create(2000)
local tempResult = table.create(1000)
local connectionGroups = table.create(100)
local fallParts = table.create(500)
local deleteIds = table.create(500)
local u_anchored = table.create(500)
local weldQueue = table.create(1000)

local weldedLookup = {}
local fallId = 0
local tagCache = {}
local visited = {}
local pending = {
    deletes = {}
}

local function GetTagStatus(part)
    local cached = tagCache[part]
    if cached then return cached end

    local hasTag = part:HasTag(Config.tag)
    local hasGround = part:HasTag("Anchored")
    local noPhysics = part:HasTag("NoPhyiscs")

    local status = {
        hasMainTag = hasTag or hasGround,
        isGround = hasGround,
        noPhysics = noPhysics
    }
    tagCache[part] = status
    return status
end

local function CanConnect(a, b, aStatus, bStatus)
    if aStatus.noPhysics or bStatus.noPhysics then return false end
    if not aStatus.hasMainTag or not bStatus.hasMainTag then return false end

    local aIsFall = a:GetAttribute("_FALL")
    local bIsFall = b:GetAttribute("_FALL")
    if aIsFall ~= bIsFall then return false end

    --local aParent = a.Parent
    --local bParent = b.Parent
    --if aParent.Name == "ObjectCache" or bParent.Name == "ObjectCache" then return false end

    return true
end

local function GetConnectedParts(startPart, preweld)
    --local searchTime = os.clock()
    
    table.clear(tempDeque)
    table.clear(tempResult)

    tempDeque[1] = { part = startPart}
    local stackSize = 1
    local resultCount = 0
    local touchGround = false
    local weldCount = #weldQueue

    while stackSize > 0 do
        local item = tempDeque[stackSize]
        stackSize -= 1
        local current = item.part :: BasePart

        if not visited[current] then
            visited[current] = true
            resultCount += 1
            tempResult[resultCount] = current

            local currentStatus = GetTagStatus(current)

            if currentStatus.isGround then
                touchGround = true
            end

            local neighbors = workspace:GetPartBoundsInBox(current.CFrame, current.Size + vector.create(0.01,0.01,0.01))

            for i = 1, #neighbors do
                local neighbor = neighbors[i]
                if neighbor ~= current and not visited[neighbor] then
                    local neighborStatus = GetTagStatus(neighbor)

                    if CanConnect(current, neighbor, currentStatus, neighborStatus) then
                        if neighbor:IsA("Part") and neighbor.Shape ~= Enum.PartType.Block then
                            neighbor.Shape = Enum.PartType.Block
                        end

                        if neighborStatus.isGround then
                            touchGround = true
                        end

                        local a, b = current, neighbor
                        if currentStatus.isGround and not neighborStatus.isGround then
                            a, b = neighbor, current
                        end

                        if preweld then
                            stackSize += 1
                            tempDeque[stackSize] = {part = neighbor}
                        else
                            if not neighborStatus.isGround then
                                stackSize += 1
                                tempDeque[stackSize] = {part = neighbor}
                            end
                        end

                        local aWelds = weldedLookup[a]
                        if not aWelds then
                            aWelds = {}
                            weldedLookup[a] = aWelds
                        end

                        if not aWelds[b] then
                            weldCount += 1
                            weldQueue[weldCount] = { a, b }
                            aWelds[b] = true

                            local bWelds = weldedLookup[b]
                            if not bWelds then
                                bWelds = {}
                                weldedLookup[b] = bWelds
                            end
                            bWelds[a] = true
                        end
                    end
                end
            end
        end
    end
    
    --print("[DEBUG] Search Time:",MsConvert.Convert(searchTime))

    local result = table.move(tempResult, 1, resultCount, 1, {})
    return result, touchGround
end

function Physic.Process(parts, ignore, voxels, preWeld)
    task.spawn(function()
        local startTime = os.clock()
        preWeld = preWeld or false

        table.clear(connectionGroups)
        table.clear(fallParts)
        table.clear(deleteIds) 
        table.clear(u_anchored)
        table.clear(weldQueue)

        local ignoreSet
        if ignore then
            ignoreSet = {}
            for i = 1, #ignore do 
                ignoreSet[ignore[i]] = true 
            end
        end

        if voxels and #voxels > 0 then
            local partsSet = {}
            local partsCount = #parts
            for i = 1, partsCount do
                partsSet[parts[i]] = true
            end

            for i = 1, #voxels do
                local voxel = voxels[i]
                local neighbors = workspace:GetPartBoundsInBox(voxel.CFrame, voxel.Size + vector.create(0.01, 0.01, 0.01))
                for j = 1, #neighbors do
                    local neighbor = neighbors[j]
                    if neighbor ~= voxel and 
                        not neighbor:HasTag("Voxel") and 
                        neighbor:HasTag(Config.tag) and
                        not partsSet[neighbor] then

                        partsCount += 1
                        parts[partsCount] = neighbor
                        partsSet[neighbor] = true
                    end
                end
            end
        end

        for i = 1, #parts do
            local part = parts[i]
            if not visited[part] then
                local connection, touchGround = GetConnectedParts(part, preWeld)

                if #connection > 0 then
                    local groupCount = #connectionGroups
                    connectionGroups[groupCount + 1] = { connection = connection, touchGround = touchGround }
                end
            end
        end

        --local weldStartTime = os.clock()

        for i = 1, #weldQueue do
            local data = weldQueue[i]
            local weld = Cache:getWeld()
            weld.Part0 = data[1]
            weld.Part1 = data[2]
            weld.Parent = data[1]
        end

        --print("[DEBUG] Weld:",MsConvert.Convert(weldStartTime))

        local fallPartsCount = 0
        local deleteIdsCount = 0

        for i = 1, #connectionGroups do
            local group = connectionGroups[i]
            local connection, touchGround = group.connection, group.touchGround
            if not touchGround then fallId += 1 end

            for j = 1, #connection do
                local part = connection[j]

                if not part:HasTag("Anchored") then
                    local uAnchoredCount = #u_anchored
                    u_anchored[uAnchoredCount + 1] = part

                    if not touchGround then
                        local id = part:GetAttribute("_IDVoxel")
                        if id then 
                            deleteIdsCount += 1
                            deleteIds[deleteIdsCount] = id
                        end

                        if not part:GetAttribute("_FALL") then 
                            fallPartsCount += 1
                            fallParts[fallPartsCount] = { part = part, fallId = fallId }
                        end
                    end
                end
            end
        end

        for i = 1, fallPartsCount do
            local data = fallParts[i]
            data.part:SetAttribute("_FALL", data.fallId)
        end

        if deleteIdsCount > 0 then
            for i = 1, deleteIdsCount do
                local pendingCount = #pending.deletes
                pending.deletes[pendingCount + 1] = deleteIds[i]
            end
            Blink.DeleteEvent.FireAll(pending.deletes)
            table.clear(pending.deletes)
        end

        for i = 1, #u_anchored do
            u_anchored[i].Anchored = false 
        end

        task.delay(1, function()
            Blink.DeleteEveryParts.FireAll(true)
        end)
        --local totalTime = MsConvert.Convert(startTime)
        --print("[DEBUG] Physics processing took:", totalTime, "ms for", #parts, "parts")

        table.clear(visited)
    end)
end

return Physic

here the example of the lag

a stutter come most from the weld but they combine I still get 80-100+ which still pretty good but I still want to find a way to optimize this!

I can’t find any solution for about 2-3 months it will get into 100-200ms when search the big map

1 Like

I haven’t examined the script yet, but this looks like a big amount of “something” is being done within one frame causing fps stutter, if this is true, consider “voxxeling” parts within few frames.

I actually use greedy mesh and octree to optimize it and I test it without physics and it run smoothly

Flatten your tempDeque, you don’t need a wrapper for a part, consider using arrays or even if that holds just one part, you can do tempDeque[1] = startPart

I don’t actually know if it faster or not I suppose it faster but I still need to figure a way to weld without lag I do bit of benchmarks for really alot of parts it took 299 ms to weld and and less part took 58-0ms I try

workspace:JoinToOutsiders({data[1],data[2]},Enum.JointCreationMode.All)

but it took 1000ms I also built my own weld pooling idk how vdp 2 weld without any lag

weld cache code

--!native
--!optimize 2

local WeldCache = {}
WeldCache.__index = WeldCache

function WeldCache.new(cacheSize, expandSize)
	local self = setmetatable({}, WeldCache)
	self.cacheSize = cacheSize or 100
	self.expandSize = expandSize or 50
	self.available = {}
	self.inUse = {}
	self.totalWelds = 0

	for i = 1, self.cacheSize do
		local weld = Instance.new("WeldConstraint")
		table.insert(self.available, weld)
		self.totalWelds = self.totalWelds + 1
	end

	return self
end

function WeldCache:getWeld()
	if #self.available == 0 then
		for i = 1, self.expandSize do
			local weld = Instance.new("WeldConstraint")
			table.insert(self.available, weld)
			self.totalWelds = self.totalWelds + 1
		end
	end

	local weld = table.remove(self.available)
	self.inUse[weld] = true

	return weld
end

function WeldCache:returnWeld(weld)
	if self.inUse[weld] then
		self.inUse[weld] = nil
		weld.Part0 = nil
		weld.Part1 = nil
		weld.Parent = nil
		table.insert(self.available, weld)
	end
end

function WeldCache:getStats()
	return {
		available = #self.available,
		inUse = self:getInUseCount(),
		total = self.totalWelds
	}
end

function WeldCache:getInUseCount()
	local count = 0
	for _ in pairs(self.inUse) do
		count = count + 1
	end
	return count
end

function WeldCache:destroy()
	for _, weld in ipairs(self.available) do
		weld:Destroy()
	end

	for weld in pairs(self.inUse) do
		weld:Destroy()
	end

	self.available = {}
	self.inUse = {}
	self.totalWelds = 0
end

return WeldCache

With your welding, you need to ignore welding already welded parts, for example:

Welding A → B (success)
Welding B → A (also success? shouldn’t happen)

Use flat dictionary and keys can be like A.UniqueID.."_"..B.UniqueID then just compare if A B or B A has been weldied before attempting to weld

Turns out UniqueId is only accessable in CoreScripts, so you can generate a custom ID to each part

local NextID = 0
local WeldLookup = {}

local function assignId(part: BasePart)
    local Id = part:GetAttribute("_ID")
    if not Id then
        NextID += 1
        Id = NextID
        part:SetAttribute("_ID", Id)
    end
    
    return Id
end

local function getKey(a: BasePart, b: BasePart): string
    local aKey, bKey = assignId(a), assignId(b)
    
    --// Comparing numeric allows us to get same result no matter the order of parts provided in args. A OR B vs B OR A returns the same key
    if aKey < bKey then
        return aKey.."_"..bKey
    else
        return bKey.."_"..aKey
    end
end

local function addWeld(a: BasePart, b: BasePart)
    local Key = getKey(a, b)
    if WeldLookup[Key] then
        return
    end
    
    WeldLookup[Key] = true
    local Weld: Weld = WeldCache:getWeld()
    Weld.Part0 = a
    Weld.Part1 = b
    Weld.Parent = a
end


also, why do you have inUse and available?, all you need is to cache free Welds to use, storing it in a table to mark it as active is not needed

my current code is already do that but I suppose this way is better bc I use weldlookup[a][b] but I still has the stutter problem maybe queue is the way but idk

you don’t do that tho, you still weld part A and part B in both ways

like here ig

                        local aWelds = weldedLookup[a]
                        if not aWelds then
                            aWelds = {}
                            weldedLookup[a] = aWelds
                        end

                        if not aWelds[b] then
                            weldCount += 1
                            weldQueue[weldCount] = { a, b }
                            aWelds[b] = true

                            local bWelds = weldedLookup[b]
                            if not bWelds then
                                bWelds = {}
                                weldedLookup[b] = bWelds
                            end
                            bWelds[a] = true
                        end

if it part a didn’t weld with part b it gonna put a,b into a queue and then tag the part b

also theres absolutely no reason to add another step and add queue for welds? just weld them , this is extremely unoptimized.

you have aWelds lookup and bWelds lookup, weldcount for no reason and a queue that holds the array of a b parts??

also u leave alot of references

aWelds = {}
weldedLookup[a] = aWelds
weldedLookup[a] = nil --// aWelds is still alive and is not gc'd

I already change it into key one and using table instead of attribute but I still need to figure out the how to optimize the search

and this is the current one (using deque for optimized idk)


local function GetConnectedParts(startPart, preweld)
    local searchTime = os.clock()

    table.clear(tempDeque)
    table.clear(tempResult)

    tempDeque[1] = startPart
    local dequeFront = 1
    local dequeBack = 1

    local resultCount = 0
    local touchGround = false

    while dequeFront <= dequeBack do
        local current = tempDeque[dequeFront]
        dequeFront += 1

        if not visited[current] then
            visited[current] = true
            resultCount += 1
            tempResult[resultCount] = current

            local currentStatus = GetTagStatus(current)

            if currentStatus.isGround then
                touchGround = true
            end

            local neighbors = workspace:GetPartBoundsInBox(current.CFrame, current.Size + vector.create(0.01,0.01,0.01))

            for i = 1, #neighbors do
                local neighbor = neighbors[i]
                if neighbor ~= current and not visited[neighbor] then
                    local neighborStatus = GetTagStatus(neighbor)

                    if CanConnect(current, neighbor, currentStatus, neighborStatus) then
                        if neighbor:IsA("Part") and neighbor.Shape ~= Enum.PartType.Block then
                            neighbor.Shape = Enum.PartType.Block
                        end

                        if neighborStatus.isGround then
                            touchGround = true
                        end

                        local a, b = current, neighbor
                        if currentStatus.isGround and not neighborStatus.isGround then
                            a, b = neighbor, current
                        end

                        if preweld then
                            dequeBack += 1
                            tempDeque[dequeBack] = neighbor
                        else
                            if not neighborStatus.isGround then
                                dequeBack += 1
                                tempDeque[dequeBack] = neighbor
                            end
                        end

                        local key = getKey(current, neighbor)

                        if not weldedLookup[key] then
                            weldQueue[#weldQueue + 1] = { a, b }
                            weldedLookup[key] = true
                        end
                    end
                end
            end
        end
    end

    print("[DEBUG] Search Time:", MsConvert.Convert(searchTime))

    local result = table.move(tempResult, 1, resultCount, 1, {})
    return result, touchGround
end

i can only suggest rewriting the whole system and not overcomplicating things

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.