chore: refractor
This commit is contained in:
84
ReplicatedStorage/Shared/ChunkManager/BlockManager.lua
Normal file
84
ReplicatedStorage/Shared/ChunkManager/BlockManager.lua
Normal file
@@ -0,0 +1,84 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
|
||||
local BlockManager = {}
|
||||
|
||||
BlockManager.BlockIdMappings = {} :: {BasePart}
|
||||
|
||||
for _,v in pairs(game:GetService("ReplicatedStorage"):WaitForChild("Blocks"):GetChildren()) do
|
||||
BlockManager.BlockIdMappings[v:GetAttribute("n")] = v
|
||||
end
|
||||
|
||||
BlockManager.UpdateIdMappings = {} :: {BasePart}
|
||||
|
||||
for _,v in pairs(game:GetService("ReplicatedStorage"):WaitForChild("BlockUpdateOperations"):GetChildren()) do
|
||||
local success, reason = pcall(function()
|
||||
BlockManager.UpdateIdMappings[v:GetAttribute("n")] = require(v)
|
||||
end)
|
||||
if not success then
|
||||
warn("[BLOCKMANAGER] Invalid update operation",v:GetAttribute("n"),":",reason)
|
||||
end
|
||||
end
|
||||
|
||||
local warnedBlockIds = {}
|
||||
|
||||
function BlockManager:GetBlock(blockId: number, attr: {[typeof("")]: any}?)
|
||||
if not BlockManager.BlockIdMappings[blockId] then
|
||||
if not warnedBlockIds[blockId] then
|
||||
warnedBlockIds[blockId] = true
|
||||
warn("[BLOCKMANAGER] Invalid block id",blockId)
|
||||
end
|
||||
return script.invalid:Clone()
|
||||
end
|
||||
|
||||
local b = BlockManager.BlockIdMappings[blockId]:Clone()
|
||||
b.Size = Vector3.new(3.95,3.95,3.95)
|
||||
|
||||
for _,v in pairs(attr or {}) do
|
||||
b:SetAttribute(_,v)
|
||||
end
|
||||
|
||||
if BlockManager.UpdateIdMappings[blockId] then
|
||||
local success, reason = pcall(function()
|
||||
BlockManager.UpdateIdMappings[blockId](b)
|
||||
end)
|
||||
if not success then
|
||||
warn("[BLOCKMANAGER] Failed update operation",blockId,":",reason)
|
||||
end
|
||||
end
|
||||
|
||||
return b
|
||||
end
|
||||
|
||||
-- ChatGPT Generated Func!!!!
|
||||
function BlockManager:GetBlockRotated(blockId: number, face: Enum.NormalId, attr: {[typeof("")]: any}?)
|
||||
-- Returns block with id blockId, rotated so the given face (NormalId) points north (+X).
|
||||
local block = BlockManager:GetBlock(blockId, attr)
|
||||
local rot = CFrame.new()
|
||||
|
||||
if face == Enum.NormalId.Front then
|
||||
rot = CFrame.Angles(0, 0, 0) -- no rot
|
||||
elseif face == Enum.NormalId.Back then
|
||||
rot = CFrame.Angles(0, math.rad(180), 0)
|
||||
elseif face == Enum.NormalId.Left then
|
||||
rot = CFrame.Angles(0, math.rad(90), 0)
|
||||
elseif face == Enum.NormalId.Right then
|
||||
rot = CFrame.Angles(0, math.rad(-90), 0)
|
||||
elseif face == Enum.NormalId.Top then
|
||||
rot = CFrame.Angles(math.rad(-90), 0, 0) -- top +x
|
||||
elseif face == Enum.NormalId.Bottom then
|
||||
rot = CFrame.Angles(math.rad(90), 0, 0) -- bottom +x
|
||||
end
|
||||
|
||||
|
||||
-- ocbwoy3's fix
|
||||
block:PivotTo(rot)
|
||||
block.CFrame = CFrame.new(rot.Position)
|
||||
|
||||
return block
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
return BlockManager
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"ignoreUnknownInstances": true
|
||||
}
|
||||
217
ReplicatedStorage/Shared/ChunkManager/Chunk.lua
Normal file
217
ReplicatedStorage/Shared/ChunkManager/Chunk.lua
Normal file
@@ -0,0 +1,217 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
|
||||
local Chunk = {}
|
||||
Chunk.__index = Chunk
|
||||
|
||||
Chunk.UpdateBlockBindable = Instance.new("BindableEvent") :: BindableEvent
|
||||
|
||||
Chunk.AllChunks = {} :: {[typeof("")]: typeof(Chunk.new(0,0,0))}
|
||||
|
||||
local RunService = game:GetService("RunService")
|
||||
|
||||
local function normalizeCoord(n)
|
||||
if typeof(n) ~= "number" then
|
||||
return n
|
||||
end
|
||||
if n >= 0 then
|
||||
return math.floor(n + 0.5)
|
||||
end
|
||||
return math.ceil(n - 0.5)
|
||||
end
|
||||
|
||||
local function keyFromCoords(x, y, z)
|
||||
x = normalizeCoord(x)
|
||||
y = normalizeCoord(y)
|
||||
z = normalizeCoord(z)
|
||||
return `{tostring(x)},{tostring(y)},{tostring(z)}`
|
||||
end
|
||||
|
||||
local function Swait(l)
|
||||
for i = 1,l do
|
||||
RunService.Stepped:Wait()
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
export type BlockData = {
|
||||
id: number,
|
||||
state: {
|
||||
[typeof("")]: string | boolean | number
|
||||
}
|
||||
}
|
||||
|
||||
function Chunk.new(x,y,z)
|
||||
local self = setmetatable({}, Chunk)
|
||||
self.pos = Vector3.new(x,y,z)
|
||||
|
||||
-- Tick ONLY in a 5 chunk distance of LP's char
|
||||
self.inhabitedTime = tick()
|
||||
self.instance = Instance.new("Folder")
|
||||
self.unloadChunkHook = function() end
|
||||
self.UpdateBlockBindableL = Instance.new("BindableEvent") :: BindableEvent
|
||||
|
||||
self.loaded = false
|
||||
self.loading = false
|
||||
self.delayedRemoval = {}
|
||||
|
||||
self.data = {} :: {[typeof("")]: BlockData} -- "X,Y,Z": BlockData ("-1,-1,1": BlockData)
|
||||
return self
|
||||
end
|
||||
|
||||
function Chunk.from(x,y,z,data)
|
||||
local self = setmetatable({}, Chunk)
|
||||
self.pos = Vector3.new(x,y,z)
|
||||
|
||||
-- Tick ONLY in a 5 chunk distance of LP's char
|
||||
self.inhabitedTime = tick()
|
||||
self.instance = Instance.new("Folder")
|
||||
self.unloadChunkHook = function() end
|
||||
self.UpdateBlockBindableL = Instance.new("BindableEvent") :: BindableEvent
|
||||
|
||||
self.data = data :: {[typeof("")]: BlockData} -- "X,Y,Z": BlockData ("-1,-1,1": BlockData)
|
||||
self.delayedRemoval = {}
|
||||
return self
|
||||
end
|
||||
|
||||
function Chunk:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, offsetX, offsetY, offsetZ)
|
||||
-- Calculate the local position of the neighboring block
|
||||
local neighborRX, neighborRY, neighborRZ = rx + offsetX, ry + offsetY, rz + offsetZ
|
||||
local neighborGX, neighborGY, neighborGZ = gx, gy, gz
|
||||
|
||||
-- Adjust for chunk boundaries
|
||||
if neighborRX < 1 then
|
||||
neighborRX = 8
|
||||
neighborGX = gx - 1
|
||||
elseif neighborRX > 8 then
|
||||
neighborRX = 1
|
||||
neighborGX = gx + 1
|
||||
end
|
||||
|
||||
if neighborRY < 1 then
|
||||
neighborRY = 8
|
||||
neighborGY = gy - 1
|
||||
elseif neighborRY > 8 then
|
||||
neighborRY = 1
|
||||
neighborGY = gy + 1
|
||||
end
|
||||
|
||||
if neighborRZ < 1 then
|
||||
neighborRZ = 8
|
||||
neighborGZ = gz - 1
|
||||
elseif neighborRZ > 8 then
|
||||
neighborRZ = 1
|
||||
neighborGZ = gz + 1
|
||||
end
|
||||
|
||||
if neighborGY < 0 then
|
||||
return true
|
||||
end
|
||||
|
||||
-- Get the neighboring chunk
|
||||
local neighborChunk = Chunk.AllChunks[`{neighborGX},{neighborGY},{neighborGZ}`]
|
||||
if not neighborChunk then
|
||||
return false -- Treat unloaded chunks as empty so edges render
|
||||
end
|
||||
|
||||
-- Check if the block exists in the neighboring chunk
|
||||
return neighborChunk:GetBlockAt(neighborRX, neighborRY, neighborRZ) ~= nil
|
||||
end
|
||||
|
||||
function Chunk:IsBlockRenderable(rx, ry, rz)
|
||||
local gx, gy, gz = self.pos.X, self.pos.Y, self.pos.Z
|
||||
-- Check all six neighboring blocks
|
||||
local d = not (
|
||||
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 1, 0, 0) and
|
||||
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, -1, 0, 0) and
|
||||
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 0, 1, 0) and
|
||||
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 0, -1, 0) and
|
||||
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 0, 0, 1) and
|
||||
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 0, 0, -1)
|
||||
)
|
||||
return d
|
||||
end
|
||||
|
||||
|
||||
function Chunk:Tick()
|
||||
self.inhabitedTime = tick()
|
||||
end
|
||||
|
||||
function Chunk:PropogateChanges(x: number,y: number,z: number,d:BlockData)
|
||||
self.UpdateBlockBindableL:Fire(x,y,z,d)
|
||||
end
|
||||
|
||||
function Chunk:GetBlockAt(x,y,z)
|
||||
if not self.data[keyFromCoords(x, y, z)] then
|
||||
return nil
|
||||
end
|
||||
return self.data[keyFromCoords(x, y, z)]
|
||||
end
|
||||
|
||||
function Chunk:CreateBlock(x: number,y: number,z: number,d:BlockData)
|
||||
self.data[keyFromCoords(x, y, z)] = d
|
||||
self:PropogateChanges(x,y,z,d)
|
||||
return self:GetBlockAt(x,y,z)
|
||||
end
|
||||
|
||||
function Chunk:RemoveBlock(x, y, z)
|
||||
local blockKey = keyFromCoords(x, y, z)
|
||||
self.data[blockKey] = nil
|
||||
self:PropogateChanges(x,y,z,0)
|
||||
end
|
||||
|
||||
function Chunk:RemoveBlockSmooth(x, y, z)
|
||||
local blockKey = keyFromCoords(x, y, z)
|
||||
self.data[blockKey] = nil
|
||||
self.delayedRemoval[blockKey] = true
|
||||
self:PropogateChanges(x,y,z,0)
|
||||
end
|
||||
|
||||
-- unsure why this exists
|
||||
function Chunk:Load()
|
||||
end
|
||||
|
||||
function Chunk:Unload()
|
||||
|
||||
self.loaded = false
|
||||
|
||||
-- SLOWCLEAR
|
||||
|
||||
task.defer(function()
|
||||
local g = 0
|
||||
for _,v in pairs(self.instance:GetChildren()) do
|
||||
pcall(function()
|
||||
v:Destroy()
|
||||
end)
|
||||
g += 1
|
||||
if g == 30 then
|
||||
g = 0
|
||||
Swait(2)
|
||||
end
|
||||
end
|
||||
|
||||
self.instance.Parent = nil
|
||||
self.instance:Destroy()
|
||||
self.unloadChunkHook()
|
||||
end)
|
||||
end
|
||||
|
||||
function Chunk:UnloadImmediate()
|
||||
self.loaded = false
|
||||
pcall(function()
|
||||
self.unloadChunkHook()
|
||||
end)
|
||||
pcall(function()
|
||||
if self.instance then
|
||||
self.instance.Parent = nil
|
||||
self.instance:Destroy()
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
-- DO NOT INTERACT WITH CHUNK AFTER CALLING THIS
|
||||
function Chunk:Destroy()
|
||||
self.data = {}
|
||||
end
|
||||
|
||||
return Chunk :: typeof(Chunk)
|
||||
246
ReplicatedStorage/Shared/ChunkManager/ChunkBuilder.lua
Normal file
246
ReplicatedStorage/Shared/ChunkManager/ChunkBuilder.lua
Normal file
@@ -0,0 +1,246 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
|
||||
local ChunkBuilder = {}
|
||||
|
||||
local Chunk = require("./Chunk")
|
||||
local BlockManager = require("./BlockManager")
|
||||
local util = require("../Util")
|
||||
|
||||
local objects = script.Parent.Parent.Parent.Objects
|
||||
|
||||
local RunService = game:GetService("RunService")
|
||||
|
||||
local ChunkBorderFolder = game:GetService("Workspace"):FindFirstChildOfClass("Terrain")
|
||||
local DEBUG_GHOST = true
|
||||
|
||||
local NEIGHBOR_OFFSETS = {
|
||||
{-1, 0, 0}, {1, 0, 0},
|
||||
{0, -1, 0}, {0, 1, 0},
|
||||
{0, 0, -1}, {0, 0, 1}
|
||||
}
|
||||
|
||||
-- TODO: Move to Chunk
|
||||
type BlockData = {
|
||||
id: number,
|
||||
state: {
|
||||
[typeof("")]: string | boolean | number
|
||||
}
|
||||
}
|
||||
|
||||
local function placeBorder(a,b,c)
|
||||
local pos = util.ChunkPosToCFrame(Vector3.new(a,b,c),Vector3.new(1,1,1)).Position - Vector3.new(2,2,2)
|
||||
local d = objects.ChunkLoading:Clone()
|
||||
d:PivotTo(CFrame.new(pos))
|
||||
d.Parent = ChunkBorderFolder
|
||||
return d
|
||||
end
|
||||
|
||||
local function Swait(l)
|
||||
for i = 1,l do
|
||||
RunService.Stepped:Wait()
|
||||
end
|
||||
end
|
||||
|
||||
local function propogateNeighboringBlockChanges(cx, cy, cz, x, y, z)
|
||||
local c = Chunk.AllChunks[`{cx},{cy},{cz}`]
|
||||
if not c then return end
|
||||
|
||||
local d = c.data[`{x},{y},{z}`]
|
||||
if not d then return end
|
||||
|
||||
if c:IsBlockRenderable(x, y, z) then
|
||||
if c.instance:FindFirstChild(`{x},{y},{z}`) then return end
|
||||
local block = BlockManager:GetBlockRotated(d.id, util.RotationStringToNormalId(d.state["r"] or "f"), d.state)
|
||||
block.Name = `{x},{y},{z}`
|
||||
block:PivotTo(util.ChunkPosToCFrame(c.pos, Vector3.new(x, y, z)))
|
||||
block.Parent = c.instance
|
||||
else
|
||||
local existing = c.instance:FindFirstChild(`{x},{y},{z}`)
|
||||
if existing then
|
||||
existing:Destroy()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkBuilder:BuildChunk(c: typeof(Chunk.new(0,0,0)),parent: Instance?)
|
||||
|
||||
if c.loaded then
|
||||
return c.instance
|
||||
end
|
||||
|
||||
local blocks = c.data
|
||||
local newcache = {} :: {[typeof("")]: BlockData}
|
||||
|
||||
local finished = false
|
||||
|
||||
local ch = Instance.new("Folder")
|
||||
ch.Parent = parent
|
||||
ch.Name = `{c.pos.X},{c.pos.Y},{c.pos.Z}`
|
||||
|
||||
local conn = c.UpdateBlockBindableL.Event:Connect(function(x: number, y: number, z: number, d: BlockData)
|
||||
if finished == false then
|
||||
newcache[`{x},{y},{z}`] = d
|
||||
return
|
||||
end
|
||||
for _, o in pairs(NEIGHBOR_OFFSETS) do
|
||||
local b = {x = x + o[1], y = y + o[2], z = z + o[3]}
|
||||
local chPos = {x = c.pos.X, y = c.pos.Y, z = c.pos.Z}
|
||||
|
||||
if b.x < 1 then chPos.x = c.pos.X - 1 b.x = 8 end
|
||||
if b.x > 8 then chPos.x = c.pos.X + 1 b.x = 1 end
|
||||
if b.y < 1 then chPos.y = c.pos.Y - 1 b.y = 8 end
|
||||
if b.y > 8 then chPos.y = c.pos.Y + 1 b.y = 1 end
|
||||
if b.z < 1 then chPos.z = c.pos.Z - 1 b.z = 8 end
|
||||
if b.z > 8 then chPos.z = c.pos.Z + 1 b.z = 1 end
|
||||
|
||||
propogateNeighboringBlockChanges(chPos.x, chPos.y, chPos.z, b.x, b.y, b.z)
|
||||
end
|
||||
|
||||
local blockName = `{x},{y},{z}`
|
||||
local existing = ch:FindFirstChild(blockName)
|
||||
if d == 0 then
|
||||
if c.delayedRemoval and c.delayedRemoval[blockName] then
|
||||
c.delayedRemoval[blockName] = nil
|
||||
if existing then
|
||||
task.defer(function()
|
||||
RunService.RenderStepped:Wait()
|
||||
if existing.Parent then
|
||||
existing:Destroy()
|
||||
end
|
||||
end)
|
||||
elseif DEBUG_GHOST then
|
||||
print("[CHUNKBUILDER][GHOST] Delayed remove missing instance", c.pos, blockName)
|
||||
end
|
||||
return
|
||||
end
|
||||
if existing then
|
||||
existing:Destroy()
|
||||
elseif DEBUG_GHOST then
|
||||
print("[CHUNKBUILDER][GHOST] Remove missing instance", c.pos, blockName)
|
||||
end
|
||||
return
|
||||
end
|
||||
if not c:IsBlockRenderable(x, y, z) then
|
||||
if existing then
|
||||
existing:Destroy()
|
||||
end
|
||||
return
|
||||
end
|
||||
if existing then
|
||||
existing:Destroy()
|
||||
end
|
||||
if not d then return end
|
||||
if d.id == 0 then return end
|
||||
local N = util.RotationStringToNormalId(d.state["r"] or "f")
|
||||
local block = BlockManager:GetBlockRotated(d.id, N, d.state)
|
||||
block.Name = blockName
|
||||
block:PivotTo(util.ChunkPosToCFrame(c.pos, Vector3.new(x, y, z)))
|
||||
block.Parent = ch
|
||||
end)
|
||||
|
||||
c.unloadChunkHook = function()
|
||||
conn:Disconnect()
|
||||
blocks = nil
|
||||
c = nil
|
||||
end
|
||||
|
||||
task.defer(function()
|
||||
|
||||
local p = 0
|
||||
|
||||
local hb = false
|
||||
for _,b in pairs(blocks) do
|
||||
hb = true
|
||||
break
|
||||
end
|
||||
|
||||
local border = Instance.new("Part")
|
||||
if hb == true then
|
||||
border:Destroy()
|
||||
border = placeBorder(c.pos.X, c.pos.Y, c.pos.Z)
|
||||
end
|
||||
|
||||
for a,b in pairs(blocks) do
|
||||
local coords = util.BlockPosStringToCoords(a)
|
||||
if not c or not c.IsBlockRenderable or not c:IsBlockRenderable(coords.X, coords.Y, coords.Z) then
|
||||
if ch:FindFirstChild(a) then
|
||||
ch:FindFirstChild(a):Destroy()
|
||||
end
|
||||
continue
|
||||
end
|
||||
local N = util.RotationStringToNormalId(b.state["r"] or "f")
|
||||
local block = BlockManager:GetBlockRotated(b.id, N, b.state)
|
||||
local existing = ch:FindFirstChild(a)
|
||||
if existing then
|
||||
existing:Destroy()
|
||||
end
|
||||
block.Name = a
|
||||
block:PivotTo(util.ChunkPosToCFrame(c.pos, coords))
|
||||
block.Parent = ch
|
||||
p += 1
|
||||
if p == 15 then
|
||||
p = 0
|
||||
Swait(1)
|
||||
end
|
||||
end
|
||||
|
||||
finished = true
|
||||
|
||||
border:Destroy()
|
||||
|
||||
task.defer(function()
|
||||
for key, data in pairs(newcache) do
|
||||
local coords = util.BlockPosStringToCoords(key)
|
||||
for _, o in pairs(NEIGHBOR_OFFSETS) do
|
||||
local nb = {x = coords.X + o[1], y = coords.Y + o[2], z = coords.Z + o[3]}
|
||||
local chCoords = {x = c.pos.X, y = c.pos.Y, z = c.pos.Z}
|
||||
if nb.x == 0 then chCoords.x = c.pos.X - 1 nb.x = 8 end
|
||||
if nb.x == 9 then chCoords.x = c.pos.X + 1 nb.x = 1 end
|
||||
|
||||
if nb.y == 0 then chCoords.y = c.pos.Y - 1 nb.y = 8 end
|
||||
if nb.y == 9 then chCoords.y = c.pos.Y + 1 nb.y = 1 end
|
||||
|
||||
if nb.z == 0 then chCoords.z = c.pos.Z - 1 nb.z = 8 end
|
||||
if nb.z == 9 then chCoords.z = c.pos.Z + 1 nb.z = 1 end
|
||||
|
||||
propogateNeighboringBlockChanges(chCoords.x, chCoords.y, chCoords.z, nb.x, nb.y, nb.z)
|
||||
end
|
||||
|
||||
local existing = ch:FindFirstChild(key)
|
||||
if data == 0 or (data and data.id == 0) then
|
||||
if existing then
|
||||
existing:Destroy()
|
||||
end
|
||||
continue
|
||||
end
|
||||
if not c or not c.IsBlockRenderable or not c:IsBlockRenderable(coords.X, coords.Y, coords.Z) then
|
||||
if existing then
|
||||
existing:Destroy()
|
||||
end
|
||||
continue
|
||||
end
|
||||
if existing then
|
||||
existing:Destroy()
|
||||
end
|
||||
if not data then
|
||||
continue
|
||||
end
|
||||
local N = util.RotationStringToNormalId(data.state["r"] or "f")
|
||||
local block = BlockManager:GetBlockRotated(data.id, N, data.state)
|
||||
block.Name = key
|
||||
block:PivotTo(util.ChunkPosToCFrame(c.pos, coords))
|
||||
block.Parent = ch
|
||||
end
|
||||
newcache = nil
|
||||
blocks = nil
|
||||
end)
|
||||
end)
|
||||
|
||||
c.loaded = true
|
||||
|
||||
return ch
|
||||
|
||||
end
|
||||
|
||||
return ChunkBuilder
|
||||
413
ReplicatedStorage/Shared/ChunkManager/init.lua
Normal file
413
ReplicatedStorage/Shared/ChunkManager/init.lua
Normal file
@@ -0,0 +1,413 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
|
||||
local ChunkManager = {}
|
||||
|
||||
local RunService = game:GetService("RunService")
|
||||
|
||||
local Chunk = require("./ChunkManager/Chunk")
|
||||
local BlockManager = require("./ChunkManager/BlockManager")
|
||||
local ChunkBuilder = require("./ChunkManager/ChunkBuilder")
|
||||
local Util = require("./Util")
|
||||
local Globals = require(script.Parent:WaitForChild("Globals"))
|
||||
|
||||
local remote = game:GetService("ReplicatedStorage"):WaitForChild("RecieveChunkPacket")
|
||||
local tickremote = game:GetService("ReplicatedStorage"):WaitForChild("Tick")
|
||||
|
||||
local ChunkFolder = Instance.new("Folder")
|
||||
ChunkFolder.Name = "$blockscraft_client"
|
||||
|
||||
ChunkManager.ChunkFolder = ChunkFolder
|
||||
|
||||
local CHUNK_RADIUS = Globals.RenderDistance or 5
|
||||
local LOAD_BATCH = Globals.LoadBatch or 8
|
||||
local RESYNC_INTERVAL = Globals.ResyncInterval or 5
|
||||
local RESYNC_RADIUS = Globals.ResyncRadius or 2
|
||||
local DEBUG_RESYNC = true
|
||||
local FORCELOAD_CHUNKS = {
|
||||
{0, 1, 0}
|
||||
}
|
||||
|
||||
local unloadingChunks = {}
|
||||
local pendingChunkRequests = {}
|
||||
|
||||
local lastChunkKey: string? = nil
|
||||
local lastHeavyTick = 0
|
||||
local HEAVY_TICK_INTERVAL = 1.5
|
||||
local lastUnloadSweep = 0
|
||||
local UNLOAD_SWEEP_INTERVAL = 1.5
|
||||
|
||||
local function worldToChunkCoord(v: number): number
|
||||
return math.floor((v + 16) / 32)
|
||||
end
|
||||
|
||||
local CHUNK_OFFSETS = {}
|
||||
do
|
||||
for y = -CHUNK_RADIUS, CHUNK_RADIUS do
|
||||
for x = -CHUNK_RADIUS, CHUNK_RADIUS do
|
||||
for z = -CHUNK_RADIUS, CHUNK_RADIUS do
|
||||
table.insert(CHUNK_OFFSETS, {x, y, z, (x * x) + (y * y) + (z * z)})
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(CHUNK_OFFSETS, function(a, b)
|
||||
return a[4] < b[4]
|
||||
end)
|
||||
end
|
||||
|
||||
function ChunkManager:UnloadAllNow()
|
||||
for key, chunk in pairs(Chunk.AllChunks) do
|
||||
unloadingChunks[key] = true
|
||||
pcall(function()
|
||||
if chunk.loaded then
|
||||
chunk:UnloadImmediate()
|
||||
end
|
||||
end)
|
||||
pcall(function()
|
||||
chunk:Destroy()
|
||||
end)
|
||||
Chunk.AllChunks[key] = nil
|
||||
unloadingChunks[key] = nil
|
||||
end
|
||||
end
|
||||
|
||||
local function Swait(l)
|
||||
for _ = 1, l do
|
||||
RunService.Stepped:Wait()
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkManager:GetChunk(x, y, z)
|
||||
local key = `{x},{y},{z}`
|
||||
if Chunk.AllChunks[key] then
|
||||
return Chunk.AllChunks[key]
|
||||
end
|
||||
|
||||
if pendingChunkRequests[key] then
|
||||
while pendingChunkRequests[key] do
|
||||
task.wait()
|
||||
end
|
||||
return Chunk.AllChunks[key]
|
||||
end
|
||||
|
||||
pendingChunkRequests[key] = true
|
||||
local ok, data = pcall(function()
|
||||
return remote:InvokeServer(x, y, z)
|
||||
end)
|
||||
if not ok then
|
||||
data = {}
|
||||
end
|
||||
local ch = Chunk.from(x, y, z, data)
|
||||
Chunk.AllChunks[key] = ch
|
||||
pendingChunkRequests[key] = nil
|
||||
return ch
|
||||
end
|
||||
|
||||
local function ensureNeighboringChunksLoaded(x, y, z)
|
||||
local offsets = {
|
||||
{1, 0, 0}, {-1, 0, 0},
|
||||
{0, 1, 0}, {0, -1, 0},
|
||||
{0, 0, 1}, {0, 0, -1}
|
||||
}
|
||||
|
||||
for _, offset in ipairs(offsets) do
|
||||
local nx, ny, nz = x + offset[1], y + offset[2], z + offset[3]
|
||||
ChunkManager:GetChunk(nx, ny, nz):Tick()
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkManager:LoadChunk(x, y, z)
|
||||
local key = `{x},{y},{z}`
|
||||
if unloadingChunks[key] or not Chunk.AllChunks[key] or Chunk.AllChunks[key].loaded then
|
||||
return
|
||||
end
|
||||
|
||||
unloadingChunks[key] = true
|
||||
task.defer(function()
|
||||
ensureNeighboringChunksLoaded(x, y, z)
|
||||
|
||||
local chunk = Chunk.AllChunks[key]
|
||||
if not chunk then
|
||||
chunk = ChunkManager:GetChunk(x, y, z)
|
||||
Chunk.AllChunks[key] = chunk
|
||||
end
|
||||
|
||||
local instance = ChunkBuilder:BuildChunk(chunk, ChunkFolder)
|
||||
chunk.instance = instance
|
||||
chunk.loaded = true
|
||||
unloadingChunks[key] = nil
|
||||
end)
|
||||
end
|
||||
|
||||
function ChunkManager:RefreshChunk(x, y, z)
|
||||
local key = `{x},{y},{z}`
|
||||
local chunk = Chunk.AllChunks[key]
|
||||
if not chunk then
|
||||
pendingChunkRequests[key] = nil
|
||||
ChunkManager:GetChunk(x, y, z)
|
||||
ChunkManager:LoadChunk(x, y, z)
|
||||
return
|
||||
end
|
||||
|
||||
local ok, newData = pcall(function()
|
||||
return remote:InvokeServer(x, y, z)
|
||||
end)
|
||||
if not ok or typeof(newData) ~= "table" then
|
||||
if DEBUG_RESYNC then
|
||||
warn("[CHUNKMANAGER][RESYNC] Failed to fetch chunk data", key, ok, typeof(newData))
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
local function sameState(a, b)
|
||||
if a == b then
|
||||
return true
|
||||
end
|
||||
if not a or not b then
|
||||
return false
|
||||
end
|
||||
local count = 0
|
||||
for k, v in pairs(a) do
|
||||
count += 1
|
||||
if b[k] ~= v then
|
||||
return false
|
||||
end
|
||||
end
|
||||
for _ in pairs(b) do
|
||||
count -= 1
|
||||
end
|
||||
return count == 0
|
||||
end
|
||||
|
||||
local function sameBlockData(a, b)
|
||||
if a == b then
|
||||
return true
|
||||
end
|
||||
if not a or not b then
|
||||
return false
|
||||
end
|
||||
if a.id ~= b.id then
|
||||
return false
|
||||
end
|
||||
return sameState(a.state, b.state)
|
||||
end
|
||||
|
||||
local changed = 0
|
||||
local removed = 0
|
||||
for keyStr, newBlock in pairs(newData) do
|
||||
local oldBlock = chunk.data[keyStr]
|
||||
if not sameBlockData(oldBlock, newBlock) then
|
||||
chunk.data[keyStr] = newBlock
|
||||
local coords = Util.BlockPosStringToCoords(keyStr)
|
||||
chunk:PropogateChanges(coords.X, coords.Y, coords.Z, newBlock)
|
||||
changed += 1
|
||||
end
|
||||
end
|
||||
|
||||
for keyStr in pairs(chunk.data) do
|
||||
if not newData[keyStr] then
|
||||
chunk.data[keyStr] = nil
|
||||
local coords = Util.BlockPosStringToCoords(keyStr)
|
||||
chunk:PropogateChanges(coords.X, coords.Y, coords.Z, 0)
|
||||
removed += 1
|
||||
end
|
||||
end
|
||||
if chunk.loaded and chunk.instance then
|
||||
local pruned = 0
|
||||
for _, child in ipairs(chunk.instance:GetChildren()) do
|
||||
if not newData[child.Name] then
|
||||
pruned += 1
|
||||
child:Destroy()
|
||||
end
|
||||
end
|
||||
if DEBUG_RESYNC and pruned > 0 then
|
||||
print("[CHUNKMANAGER][RESYNC] Pruned ghost instances", key, "count", pruned)
|
||||
end
|
||||
end
|
||||
if DEBUG_RESYNC and (changed > 0 or removed > 0) then
|
||||
print("[CHUNKMANAGER][RESYNC] Applied diff", key, "changed", changed, "removed", removed)
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkManager:ForceTick()
|
||||
for _, coords in ipairs(FORCELOAD_CHUNKS) do
|
||||
local key = `{coords[1]},{coords[2]},{coords[3]}`
|
||||
local chunk = Chunk.AllChunks[key]
|
||||
if not chunk then
|
||||
ChunkManager:LoadChunk(coords[1], coords[2], coords[3])
|
||||
else
|
||||
chunk:Tick()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkManager:TickI()
|
||||
for key, chunk in pairs(Chunk.AllChunks) do
|
||||
if tick() - chunk.inhabitedTime <= 5 then
|
||||
tickremote:FireServer(key)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkManager:Tick()
|
||||
ChunkManager:ForceTick()
|
||||
local player = game:GetService("Players").LocalPlayer
|
||||
if not player.Character then
|
||||
return
|
||||
end
|
||||
|
||||
local pos = player.Character:GetPivot().Position
|
||||
local chunkPos = {
|
||||
x = worldToChunkCoord(pos.X),
|
||||
y = worldToChunkCoord(pos.Y),
|
||||
z = worldToChunkCoord(pos.Z)
|
||||
}
|
||||
local ck = `{chunkPos.x},{chunkPos.y},{chunkPos.z}`
|
||||
local now = tick()
|
||||
local shouldHeavyTick = (ck ~= lastChunkKey) or (now - lastHeavyTick >= HEAVY_TICK_INTERVAL)
|
||||
lastChunkKey = ck
|
||||
if shouldHeavyTick then
|
||||
lastHeavyTick = now
|
||||
end
|
||||
|
||||
if shouldHeavyTick then
|
||||
task.defer(function()
|
||||
local processed = 0
|
||||
for _, offset in ipairs(CHUNK_OFFSETS) do
|
||||
local cx, cy, cz = chunkPos.x + offset[1], chunkPos.y + offset[2], chunkPos.z + offset[3]
|
||||
local chunk = ChunkManager:GetChunk(cx, cy, cz)
|
||||
chunk.inhabitedTime = now
|
||||
if not chunk.loaded then
|
||||
ChunkManager:LoadChunk(cx, cy, cz)
|
||||
processed += 1
|
||||
if processed % LOAD_BATCH == 0 then
|
||||
Swait(1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end)
|
||||
else
|
||||
local current = Chunk.AllChunks[ck]
|
||||
if current then
|
||||
current.inhabitedTime = now
|
||||
end
|
||||
end
|
||||
|
||||
--[[
|
||||
task.defer(function()
|
||||
for y = 0, 2 do
|
||||
task.defer(function()
|
||||
for x = -CHUNK_RADIUS, CHUNK_RADIUS do
|
||||
for z = -CHUNK_RADIUS, CHUNK_RADIUS do
|
||||
local cx, cy, cz = chunkPos.x + x, y, chunkPos.z + z
|
||||
local key = `{cx},{cy},{cz}`
|
||||
local chunk = ChunkManager:GetChunk(cx, cy, cz)
|
||||
chunk.inhabitedTime = tick()
|
||||
if not chunk.loaded then
|
||||
ChunkManager:LoadChunk(cx, cy, cz)
|
||||
Swait(2)
|
||||
end
|
||||
end
|
||||
end
|
||||
end)
|
||||
Swait(10)
|
||||
end
|
||||
end)
|
||||
--]]
|
||||
|
||||
if now - lastUnloadSweep >= UNLOAD_SWEEP_INTERVAL then
|
||||
lastUnloadSweep = now
|
||||
for key, loadedChunk in pairs(Chunk.AllChunks) do
|
||||
if now - loadedChunk.inhabitedTime > 15 and not unloadingChunks[key] then
|
||||
unloadingChunks[key] = true
|
||||
task.defer(function()
|
||||
loadedChunk:Unload()
|
||||
loadedChunk:Destroy()
|
||||
Chunk.AllChunks[key] = nil
|
||||
unloadingChunks[key] = nil
|
||||
end)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkManager:ResyncAroundPlayer(radius: number)
|
||||
local player = game:GetService("Players").LocalPlayer
|
||||
if not player.Character then
|
||||
return
|
||||
end
|
||||
local pos = player.Character:GetPivot().Position
|
||||
local chunkPos = {
|
||||
x = worldToChunkCoord(pos.X),
|
||||
y = worldToChunkCoord(pos.Y),
|
||||
z = worldToChunkCoord(pos.Z)
|
||||
}
|
||||
for y = -radius, radius do
|
||||
for x = -radius, radius do
|
||||
for z = -radius, radius do
|
||||
local cx, cy, cz = chunkPos.x + x, chunkPos.y + y, chunkPos.z + z
|
||||
ChunkManager:RefreshChunk(cx, cy, cz)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkManager:ResyncAroundChunk(cx: number, cy: number, cz: number, radius: number)
|
||||
for y = -radius, radius do
|
||||
for x = -radius, radius do
|
||||
for z = -radius, radius do
|
||||
ChunkManager:RefreshChunk(cx + x, cy + y, cz + z)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ChunkManager:Init()
|
||||
if not RunService:IsClient() then
|
||||
error("ChunkManager:Init can only be called on the client")
|
||||
end
|
||||
|
||||
ChunkFolder.Parent = game:GetService("Workspace")
|
||||
ChunkManager:ForceTick()
|
||||
|
||||
tickremote.OnClientEvent:Connect(function(m)
|
||||
if m == "U_ALL" then
|
||||
ChunkManager:UnloadAllNow()
|
||||
end
|
||||
end)
|
||||
|
||||
task.defer(function()
|
||||
while true do
|
||||
wait(2)
|
||||
ChunkManager:TickI()
|
||||
end
|
||||
end)
|
||||
|
||||
task.defer(function()
|
||||
while true do
|
||||
task.defer(function()
|
||||
local success, err = pcall(function()
|
||||
ChunkManager:Tick()
|
||||
end)
|
||||
if not success then
|
||||
warn("[CHUNKMANAGER]", err)
|
||||
end
|
||||
end)
|
||||
Swait(20)
|
||||
end
|
||||
end)
|
||||
|
||||
task.defer(function()
|
||||
while true do
|
||||
wait(RESYNC_INTERVAL)
|
||||
local ok, err = pcall(function()
|
||||
ChunkManager:ResyncAroundPlayer(RESYNC_RADIUS)
|
||||
end)
|
||||
if not ok then
|
||||
warn("[CHUNKMANAGER][RESYNC]", err)
|
||||
end
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
return ChunkManager
|
||||
11
ReplicatedStorage/Shared/Globals.lua
Normal file
11
ReplicatedStorage/Shared/Globals.lua
Normal file
@@ -0,0 +1,11 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
|
||||
local Globals = {}
|
||||
|
||||
Globals.RenderDistance = 6
|
||||
Globals.LoadBatch = 8
|
||||
Globals.ResyncInterval = 5
|
||||
Globals.ResyncRadius = 2
|
||||
|
||||
return Globals
|
||||
58
ReplicatedStorage/Shared/ModLoader.lua
Normal file
58
ReplicatedStorage/Shared/ModLoader.lua
Normal file
@@ -0,0 +1,58 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
|
||||
local ML = {}
|
||||
|
||||
type modContext = {
|
||||
name: string,
|
||||
description: string,
|
||||
ns: string,
|
||||
author: {string},
|
||||
init: typeof(function()end)
|
||||
}
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local Shared = ReplicatedStorage:WaitForChild("Shared")
|
||||
local ModsFolder = ReplicatedStorage:WaitForChild("Mods")
|
||||
|
||||
function ML.loadModsS()
|
||||
print("[SSModLoader] Loading Mods")
|
||||
|
||||
for _, m in pairs(ModsFolder:GetChildren()) do
|
||||
local success, reason = pcall(function()
|
||||
-- ignore type err
|
||||
local mod: modContext = require(m)
|
||||
mod.init()
|
||||
print(`[SSModLoader] Loaded {mod.name} ({mod.ns}) by {table.concat(mod.author,", ")}`)
|
||||
end)
|
||||
if not success then
|
||||
warn(`[CSModLoader] Error loading {m.Name}: {reason}`)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ML.loadModsC(onProgress: ((number, number, Instance, boolean) -> ())?)
|
||||
print("[CSModLoader] Loading Mods")
|
||||
|
||||
local mods = ModsFolder:GetChildren()
|
||||
local total = #mods
|
||||
|
||||
for i, m in ipairs(mods) do
|
||||
local success, reason = pcall(function()
|
||||
-- ignore type err
|
||||
local mod: modContext = require(m)
|
||||
mod.init()
|
||||
print(`[CSModLoader] Loaded {mod.name} ({mod.ns}) by {table.concat(mod.author,", ")}`)
|
||||
end)
|
||||
if not success then
|
||||
warn(`[CSModLoader] Error loading {m.Name}: {reason}`)
|
||||
end
|
||||
if onProgress then
|
||||
pcall(function()
|
||||
onProgress(i, total, m, success)
|
||||
end)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return ML
|
||||
683
ReplicatedStorage/Shared/PlacementManager.lua
Normal file
683
ReplicatedStorage/Shared/PlacementManager.lua
Normal file
@@ -0,0 +1,683 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
|
||||
local PlacementManager = {}
|
||||
|
||||
local ChunkManager = require("./ChunkManager")
|
||||
local Util = require("./Util")
|
||||
|
||||
local DEBUG_PLACEMENT = true
|
||||
local function debugPlacementLog(...: any)
|
||||
if DEBUG_PLACEMENT then
|
||||
Util.StudioLog(...)
|
||||
end
|
||||
end
|
||||
|
||||
local function debugPlacementWarn(...: any)
|
||||
if DEBUG_PLACEMENT then
|
||||
Util.StudioWarn(...)
|
||||
end
|
||||
end
|
||||
|
||||
PlacementManager.ChunkFolder = ChunkManager.ChunkFolder
|
||||
|
||||
local raycastParams = RaycastParams.new()
|
||||
raycastParams.FilterDescendantsInstances = {PlacementManager.ChunkFolder}
|
||||
raycastParams.FilterType = Enum.RaycastFilterType.Include
|
||||
raycastParams.IgnoreWater = true
|
||||
|
||||
local Mouse: Mouse = nil
|
||||
local lastNormalId: Enum.NormalId? = nil
|
||||
local lastRaycastFailure: string? = nil
|
||||
local lastSelectedChunkKey: string? = nil
|
||||
local lastSelectedBlockKey: string? = nil
|
||||
local duplicateResyncCooldown: {[string]: number} = {}
|
||||
local BREAK_ROLLBACK_TIMEOUT = 0.6
|
||||
local pendingBreaks = {}
|
||||
local clearSelection
|
||||
|
||||
if _G.__BLOCKSCRAFT_PLACEMENT_MANAGER then
|
||||
return _G.__BLOCKSCRAFT_PLACEMENT_MANAGER
|
||||
end
|
||||
_G.__BLOCKSCRAFT_PLACEMENT_MANAGER = PlacementManager
|
||||
|
||||
PlacementManager.SelectionBox = script.SelectionBox:Clone()
|
||||
PlacementManager.SelectionBox.Name = "$SelectionBox"..(game:GetService("RunService"):IsServer() and "_SERVER" or "")
|
||||
PlacementManager.SelectionBox.Parent = game:GetService("Workspace"):FindFirstChildOfClass("Terrain")
|
||||
PlacementManager.SelectionBox.Adornee = nil
|
||||
PlacementManager.SelectionBox:GetPropertyChangedSignal("Adornee"):Connect(function()
|
||||
local adornee = PlacementManager.SelectionBox.Adornee
|
||||
if not adornee then
|
||||
return
|
||||
end
|
||||
adornee.AncestryChanged:Connect(function(_, parent)
|
||||
if not parent then
|
||||
clearSelection("adornee destroyed")
|
||||
end
|
||||
end)
|
||||
end)
|
||||
|
||||
-- Trash method TODO: Fix this
|
||||
local function findChunkFolderFromDescendant(inst: Instance): Instance?
|
||||
local current = inst
|
||||
while current and current.Parent do
|
||||
if current.Parent == PlacementManager.ChunkFolder then
|
||||
return current
|
||||
end
|
||||
-- Fallback: match by name in case the ChunkFolder reference differs (e.g. recreated/parented later)
|
||||
if current.Parent:IsA("Folder") and current.Parent.Name == (PlacementManager.ChunkFolder and PlacementManager.ChunkFolder.Name) then
|
||||
return current
|
||||
end
|
||||
current = current.Parent
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function findBlockRoot(inst: Instance, chunkFolder: Instance): Instance?
|
||||
local current = inst
|
||||
while current and current ~= chunkFolder do
|
||||
if current:IsA("BasePart") then
|
||||
return current
|
||||
end
|
||||
current = current.Parent
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function resolveBlockInstance(chunkFolder: Instance, chunkName: string, blockName: string): Instance?
|
||||
local chunkInst = chunkFolder:FindFirstChild(chunkName)
|
||||
if not chunkInst then
|
||||
return nil
|
||||
end
|
||||
return chunkInst:FindFirstChild(blockName)
|
||||
end
|
||||
|
||||
clearSelection = function(reason: string?)
|
||||
PlacementManager.SelectionBox.Adornee = nil
|
||||
PlacementManager.SelectionBox.Parent = nil
|
||||
lastNormalId = nil
|
||||
lastSelectedChunkKey = nil
|
||||
lastSelectedBlockKey = nil
|
||||
if reason then
|
||||
lastRaycastFailure = reason
|
||||
end
|
||||
end
|
||||
|
||||
local function setSelection(target: Instance, parent: Instance)
|
||||
PlacementManager.SelectionBox.Parent = parent
|
||||
PlacementManager.SelectionBox.Adornee = target
|
||||
end
|
||||
|
||||
local function findChunkAndBlock(inst: Instance): (string?, string?)
|
||||
local root = PlacementManager.ChunkFolder
|
||||
if not root then
|
||||
return nil, nil
|
||||
end
|
||||
local current = inst
|
||||
while current and current.Parent do
|
||||
-- case: current parent is the chunk folder root; then current is the chunk itself (no block name yet)
|
||||
if current.Parent == root then
|
||||
return current.Name, inst.Name
|
||||
end
|
||||
-- case: grandparent is chunk folder root; parent is chunk, current is block/model
|
||||
if current.Parent.Parent == root then
|
||||
return current.Parent.Name, current.Name
|
||||
end
|
||||
current = current.Parent
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
local function vectorToNormalId(normal: Vector3): Enum.NormalId
|
||||
local ax, ay, az = math.abs(normal.X), math.abs(normal.Y), math.abs(normal.Z)
|
||||
if ax >= ay and ax >= az then
|
||||
return normal.X >= 0 and Enum.NormalId.Right or Enum.NormalId.Left
|
||||
elseif ay >= ax and ay >= az then
|
||||
return normal.Y >= 0 and Enum.NormalId.Top or Enum.NormalId.Bottom
|
||||
else
|
||||
return normal.Z >= 0 and Enum.NormalId.Back or Enum.NormalId.Front
|
||||
end
|
||||
end
|
||||
|
||||
local function makeChunkKey(cx: number, cy: number, cz: number): string
|
||||
return `{cx},{cy},{cz}`
|
||||
end
|
||||
|
||||
local function makeBlockKey(x: number, y: number, z: number): string
|
||||
return `{x},{y},{z}`
|
||||
end
|
||||
|
||||
local function getPendingBreak(chunkKey: string, blockKey: string)
|
||||
local chunkMap = pendingBreaks[chunkKey]
|
||||
if not chunkMap then
|
||||
return nil
|
||||
end
|
||||
return chunkMap[blockKey]
|
||||
end
|
||||
|
||||
local function clearPendingBreak(chunkKey: string, blockKey: string)
|
||||
local chunkMap = pendingBreaks[chunkKey]
|
||||
if not chunkMap then
|
||||
return
|
||||
end
|
||||
chunkMap[blockKey] = nil
|
||||
if not next(chunkMap) then
|
||||
pendingBreaks[chunkKey] = nil
|
||||
end
|
||||
end
|
||||
|
||||
local function clearPendingBreaksForChunk(chunkKey: string)
|
||||
pendingBreaks[chunkKey] = nil
|
||||
end
|
||||
|
||||
local function scheduleBreakRollback(cx: number, cy: number, cz: number, x: number, y: number, z: number)
|
||||
task.delay(BREAK_ROLLBACK_TIMEOUT, function()
|
||||
local chunkKey = makeChunkKey(cx, cy, cz)
|
||||
local blockKey = makeBlockKey(x, y, z)
|
||||
local pending = getPendingBreak(chunkKey, blockKey)
|
||||
if not pending then
|
||||
return
|
||||
end
|
||||
clearPendingBreak(chunkKey, blockKey)
|
||||
local chunk = ChunkManager:GetChunk(cx, cy, cz)
|
||||
if pending.data and chunk then
|
||||
chunk:CreateBlock(x, y, z, pending.data)
|
||||
end
|
||||
ChunkManager:RefreshChunk(cx, cy, cz)
|
||||
end)
|
||||
end
|
||||
|
||||
local function normalIdToOffset(normal: Enum.NormalId): Vector3
|
||||
if normal == Enum.NormalId.Top then
|
||||
return Vector3.new(0, 1, 0)
|
||||
elseif normal == Enum.NormalId.Bottom then
|
||||
return Vector3.new(0, -1, 0)
|
||||
elseif normal == Enum.NormalId.Left then
|
||||
return Vector3.new(-1, 0, 0)
|
||||
elseif normal == Enum.NormalId.Right then
|
||||
return Vector3.new(1, 0, 0)
|
||||
elseif normal == Enum.NormalId.Back then
|
||||
return Vector3.new(0, 0, 1)
|
||||
elseif normal == Enum.NormalId.Front then
|
||||
return Vector3.new(0, 0, -1)
|
||||
end
|
||||
return Vector3.new(0, 0, 0)
|
||||
end
|
||||
|
||||
local function offsetChunkBlock(chunk: Vector3, block: Vector3, offset: Vector3)
|
||||
local cx, cy, cz = chunk.X, chunk.Y, chunk.Z
|
||||
local bx, by, bz = block.X + offset.X, block.Y + offset.Y, block.Z + offset.Z
|
||||
|
||||
if bx < 1 then
|
||||
bx = 8
|
||||
cx -= 1
|
||||
elseif bx > 8 then
|
||||
bx = 1
|
||||
cx += 1
|
||||
end
|
||||
|
||||
if by < 1 then
|
||||
by = 8
|
||||
cy -= 1
|
||||
elseif by > 8 then
|
||||
by = 1
|
||||
cy += 1
|
||||
end
|
||||
|
||||
if bz < 1 then
|
||||
bz = 8
|
||||
cz -= 1
|
||||
elseif bz > 8 then
|
||||
bz = 1
|
||||
cz += 1
|
||||
end
|
||||
|
||||
return Vector3.new(cx, cy, cz), Vector3.new(bx, by, bz)
|
||||
end
|
||||
|
||||
local function getPlayerPosition(): Vector3?
|
||||
local player = game:GetService("Players").LocalPlayer
|
||||
local character = player and player.Character
|
||||
if not character then
|
||||
return nil
|
||||
end
|
||||
local root = character:FindFirstChild("HumanoidRootPart")
|
||||
return root and root.Position or nil
|
||||
end
|
||||
|
||||
local MAX_REACH = 512
|
||||
|
||||
local function isWithinReach(cx: number, cy: number, cz: number, x: number, y: number, z: number): boolean
|
||||
-- Client-side reach loosened; rely on server authority
|
||||
return true
|
||||
end
|
||||
|
||||
local function ensureChunkFolder(): Instance?
|
||||
if PlacementManager.ChunkFolder and PlacementManager.ChunkFolder.Parent then
|
||||
return PlacementManager.ChunkFolder
|
||||
end
|
||||
local found = workspace:FindFirstChild("$blockscraft_client")
|
||||
if found then
|
||||
PlacementManager.ChunkFolder = found
|
||||
return found
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Gets the block and normalid of the block (and surface) the player is looking at
|
||||
function PlacementManager:Raycast()
|
||||
if not Mouse then
|
||||
Mouse = game:GetService("Players").LocalPlayer:GetMouse()
|
||||
end
|
||||
local chunkFolder = ensureChunkFolder()
|
||||
if not chunkFolder then
|
||||
clearSelection("chunk folder missing")
|
||||
script.RaycastResult.Value = nil
|
||||
return
|
||||
end
|
||||
|
||||
raycastParams.FilterDescendantsInstances = {chunkFolder}
|
||||
local cam = workspace.CurrentCamera
|
||||
if not cam then
|
||||
lastRaycastFailure = "no camera"
|
||||
return
|
||||
end
|
||||
local ray = Mouse.UnitRay
|
||||
local result = workspace:Raycast(ray.Origin, ray.Direction * MAX_REACH, raycastParams)
|
||||
if not result then
|
||||
clearSelection("raycast miss")
|
||||
script.RaycastResult.Value = nil
|
||||
debugPlacementLog("[PLACE][CLIENT][RAYCAST]", "miss")
|
||||
return
|
||||
end
|
||||
|
||||
local objLookingAt = result.Instance
|
||||
if not objLookingAt then
|
||||
clearSelection("raycast nil instance")
|
||||
script.RaycastResult.Value = nil
|
||||
debugPlacementWarn("[PLACE][CLIENT][RAYCAST]", "nil instance in result")
|
||||
return
|
||||
end
|
||||
|
||||
local hitChunkFolder = findChunkFolderFromDescendant(objLookingAt)
|
||||
if not hitChunkFolder then
|
||||
debugPlacementWarn(
|
||||
"[PLACE][CLIENT][REJECT]",
|
||||
"target not in chunk folder",
|
||||
objLookingAt:GetFullName(),
|
||||
"parent",
|
||||
objLookingAt.Parent and objLookingAt.Parent:GetFullName() or "nil"
|
||||
)
|
||||
clearSelection("target not in chunk folder")
|
||||
script.RaycastResult.Value = nil
|
||||
return
|
||||
end
|
||||
if hitChunkFolder:GetAttribute("ns") == true then
|
||||
debugPlacementWarn(
|
||||
"[PLACE][CLIENT][REJECT]",
|
||||
"chunk flagged ns",
|
||||
hitChunkFolder:GetFullName()
|
||||
)
|
||||
clearSelection("target chunk marked ns")
|
||||
script.RaycastResult.Value = nil
|
||||
return
|
||||
end
|
||||
PlacementManager.ChunkFolder = chunkFolder
|
||||
|
||||
local blockRoot = findBlockRoot(objLookingAt, chunkFolder) or objLookingAt
|
||||
local chunkName, blockName = findChunkAndBlock(blockRoot)
|
||||
if not chunkName or not blockName then
|
||||
clearSelection("failed to resolve chunk/block")
|
||||
script.RaycastResult.Value = nil
|
||||
return
|
||||
end
|
||||
local okChunk, chunkCoords = pcall(function()
|
||||
return Util.BlockPosStringToCoords(chunkName)
|
||||
end)
|
||||
local okBlock, blockCoords = pcall(function()
|
||||
return Util.BlockPosStringToCoords(blockName)
|
||||
end)
|
||||
if not okChunk or not okBlock then
|
||||
clearSelection("failed to parse chunk/block names")
|
||||
script.RaycastResult.Value = nil
|
||||
return
|
||||
end
|
||||
local chunkKey = makeChunkKey(chunkCoords.X, chunkCoords.Y, chunkCoords.Z)
|
||||
local blockKey = makeBlockKey(blockCoords.X, blockCoords.Y, blockCoords.Z)
|
||||
|
||||
-- block is being optimistically broken, do not highlight it
|
||||
if getPendingBreak(chunkKey, blockKey) then
|
||||
clearSelection("block pending break")
|
||||
script.RaycastResult.Value = nil
|
||||
return
|
||||
end
|
||||
|
||||
-- hide selection if block no longer exists (air/removed)
|
||||
local chunk = ChunkManager:GetChunk(chunkCoords.X, chunkCoords.Y, chunkCoords.Z)
|
||||
local blockData = chunk and chunk:GetBlockAt(blockCoords.X, blockCoords.Y, blockCoords.Z)
|
||||
if not blockData or blockData == 0 or blockData.id == 0 then
|
||||
clearSelection("block missing/air")
|
||||
script.RaycastResult.Value = nil
|
||||
return
|
||||
end
|
||||
local blockInstance = resolveBlockInstance(chunkFolder, chunkName, blockName) or blockRoot
|
||||
if not blockInstance then
|
||||
clearSelection("missing block instance")
|
||||
script.RaycastResult.Value = nil
|
||||
return
|
||||
end
|
||||
|
||||
lastRaycastFailure = nil
|
||||
if lastSelectedChunkKey ~= chunkKey or lastSelectedBlockKey ~= blockKey then
|
||||
setSelection(blockInstance, PlacementManager.ChunkFolder)
|
||||
lastSelectedChunkKey = chunkKey
|
||||
lastSelectedBlockKey = blockKey
|
||||
end
|
||||
script.RaycastResult.Value = objLookingAt
|
||||
lastNormalId = vectorToNormalId(result.Normal)
|
||||
debugPlacementLog(
|
||||
"[PLACE][CLIENT][RAYCAST][HIT]",
|
||||
blockInstance:GetFullName(),
|
||||
"chunkFolder",
|
||||
hitChunkFolder:GetFullName(),
|
||||
"blockName",
|
||||
blockInstance.Name,
|
||||
"normal",
|
||||
lastNormalId.Name
|
||||
)
|
||||
return objLookingAt, lastNormalId
|
||||
end
|
||||
|
||||
function PlacementManager:RaycastGetResult()
|
||||
return script.RaycastResult.Value
|
||||
end
|
||||
|
||||
local remotes = game:GetService("ReplicatedStorage"):WaitForChild("Remotes")
|
||||
local placeRemote = remotes:WaitForChild("PlaceBlock")
|
||||
local breakRemote = remotes:WaitForChild("BreakBlock")
|
||||
local tickRemote = game:GetService("ReplicatedStorage").Tick
|
||||
|
||||
-- FIRES REMOTE
|
||||
function PlacementManager:PlaceBlock(cx, cy, cz, x, y, z, blockId: string)
|
||||
debugPlacementLog("[PLACE][CLIENT][PLACE_CALL]", "chunk", cx, cy, cz, "block", x, y, z, "blockId", blockId)
|
||||
if typeof(cx) ~= "number" or typeof(cy) ~= "number" or typeof(cz) ~= "number" then
|
||||
debugPlacementWarn("[PLACE][CLIENT][REJECT]", "chunk type", cx, cy, cz, x, y, z, blockId)
|
||||
return
|
||||
end
|
||||
if typeof(x) ~= "number" or typeof(y) ~= "number" or typeof(z) ~= "number" then
|
||||
debugPlacementWarn("[PLACE][CLIENT][REJECT]", "block type", cx, cy, cz, x, y, z, blockId)
|
||||
return
|
||||
end
|
||||
if x < 1 or x > 8 or y < 1 or y > 8 or z < 1 or z > 8 then
|
||||
debugPlacementWarn("[PLACE][CLIENT][REJECT]", "block bounds", cx, cy, cz, x, y, z, blockId)
|
||||
return
|
||||
end
|
||||
if not isWithinReach(cx, cy, cz, x, y, z) then
|
||||
debugPlacementWarn("[PLACE][CLIENT][REJECT]", "reach", cx, cy, cz, x, y, z, blockId)
|
||||
return
|
||||
end
|
||||
|
||||
-- ensure chunk is present/rendered client-side
|
||||
local chunk = ChunkManager:GetChunk(cx, cy, cz)
|
||||
if chunk and not chunk.loaded then
|
||||
ChunkManager:LoadChunk(cx, cy, cz)
|
||||
end
|
||||
if not chunk then
|
||||
debugPlacementWarn("[PLACE][CLIENT][REJECT]", "missing chunk", cx, cy, cz, x, y, z, blockId)
|
||||
return
|
||||
end
|
||||
|
||||
-- allow sending even if the client thinks the id matches; server truth wins
|
||||
if chunk then
|
||||
local existing = chunk:GetBlockAt(x, y, z)
|
||||
local existingId = existing and existing.id
|
||||
if existingId and tostring(existingId) == tostring(blockId) then
|
||||
debugPlacementLog(
|
||||
"[PLACE][CLIENT][DUPLICATE]",
|
||||
"still sending",
|
||||
"chunk",
|
||||
cx,
|
||||
cy,
|
||||
cz,
|
||||
"block",
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
"existingId",
|
||||
existingId,
|
||||
"blockId",
|
||||
blockId
|
||||
)
|
||||
local ck = makeChunkKey(cx, cy, cz)
|
||||
local last = duplicateResyncCooldown[ck]
|
||||
if not last or (tick() - last) > 0.5 then
|
||||
duplicateResyncCooldown[ck] = tick()
|
||||
task.defer(function()
|
||||
ChunkManager:RefreshChunk(cx, cy, cz)
|
||||
end)
|
||||
end
|
||||
else
|
||||
debugPlacementLog(
|
||||
"[PLACE][CLIENT][EXISTING]",
|
||||
"chunk",
|
||||
cx,
|
||||
cy,
|
||||
cz,
|
||||
"block",
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
"existingId",
|
||||
existingId
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
-- optimistic local apply; server will correct on tick
|
||||
if chunk then
|
||||
chunk:CreateBlock(x, y, z, {
|
||||
id = tonumber(blockId) or blockId,
|
||||
state = {},
|
||||
})
|
||||
end
|
||||
|
||||
debugPlacementLog("[PLACE][CLIENT][SEND]", cx, cy, cz, x, y, z, blockId)
|
||||
placeRemote:FireServer(cx, cy, cz, x, y, z, blockId)
|
||||
end
|
||||
|
||||
-- FIRES REMOTE
|
||||
function PlacementManager:BreakBlock(cx, cy, cz, x, y, z)
|
||||
if typeof(cx) ~= "number" or typeof(cy) ~= "number" or typeof(cz) ~= "number" then
|
||||
return
|
||||
end
|
||||
if typeof(x) ~= "number" or typeof(y) ~= "number" or typeof(z) ~= "number" then
|
||||
debugPlacementWarn("[BREAK][CLIENT][REJECT]", "block type", cx, cy, cz, x, y, z)
|
||||
return
|
||||
end
|
||||
if x < 1 or x > 8 or y < 1 or y > 8 or z < 1 or z > 8 then
|
||||
debugPlacementWarn("[BREAK][CLIENT][REJECT]", "block bounds", cx, cy, cz, x, y, z)
|
||||
return
|
||||
end
|
||||
if not isWithinReach(cx, cy, cz, x, y, z) then
|
||||
debugPlacementWarn("[BREAK][CLIENT][REJECT]", "reach", cx, cy, cz, x, y, z)
|
||||
return
|
||||
end
|
||||
|
||||
local chunk = ChunkManager:GetChunk(cx, cy, cz)
|
||||
local blockData = chunk and chunk:GetBlockAt(x, y, z) or nil
|
||||
local chunkKey = makeChunkKey(cx, cy, cz)
|
||||
local blockKey = makeBlockKey(x, y, z)
|
||||
if getPendingBreak(chunkKey, blockKey) then
|
||||
debugPlacementLog("[BREAK][CLIENT][SKIP]", "pending rollback", cx, cy, cz, x, y, z)
|
||||
return
|
||||
end
|
||||
pendingBreaks[chunkKey] = pendingBreaks[chunkKey] or {}
|
||||
pendingBreaks[chunkKey][blockKey] = {
|
||||
data = blockData,
|
||||
time = tick(),
|
||||
}
|
||||
if blockData then
|
||||
chunk:RemoveBlock(x, y, z)
|
||||
end
|
||||
scheduleBreakRollback(cx, cy, cz, x, y, z)
|
||||
debugPlacementLog("[BREAK][CLIENT][SEND]", cx, cy, cz, x, y, z)
|
||||
breakRemote:FireServer(cx, cy, cz, x, y, z)
|
||||
end
|
||||
|
||||
-- CLIENTSIDED: only apply server-validated changes
|
||||
local function applyPlaceBlockLocal(cx, cy, cz, x, y, z, blockData)
|
||||
local chunk = ChunkManager:GetChunk(cx, cy, cz)
|
||||
if chunk and not chunk.loaded then
|
||||
ChunkManager:LoadChunk(cx, cy, cz)
|
||||
end
|
||||
chunk:CreateBlock(x, y, z, blockData)
|
||||
end
|
||||
|
||||
-- CLIENTSIDED: only apply server-validated changes
|
||||
local function applyBreakBlockLocal(cx, cy, cz, x, y, z)
|
||||
local chunk = ChunkManager:GetChunk(cx, cy, cz)
|
||||
if chunk and not chunk.loaded then
|
||||
ChunkManager:LoadChunk(cx, cy, cz)
|
||||
end
|
||||
if not chunk then
|
||||
return
|
||||
end
|
||||
local chunkKey = makeChunkKey(cx, cy, cz)
|
||||
local blockKey = makeBlockKey(x, y, z)
|
||||
if getPendingBreak(chunkKey, blockKey) then
|
||||
clearPendingBreak(chunkKey, blockKey)
|
||||
return
|
||||
end
|
||||
chunk:RemoveBlock(x, y, z)
|
||||
end
|
||||
|
||||
function PlacementManager:GetBlockAtMouse(): nil | {chunk:Vector3, block: Vector3}
|
||||
pcall(function()
|
||||
PlacementManager:Raycast()
|
||||
end)
|
||||
local selectedPart = PlacementManager:RaycastGetResult()
|
||||
--print(selectedPart and selectedPart:GetFullName() or nil)
|
||||
if selectedPart == nil then
|
||||
clearSelection()
|
||||
script.RaycastResult.Value = nil
|
||||
debugPlacementLog("[PLACE][CLIENT][TARGET]", "no selectedPart after raycast", lastRaycastFailure)
|
||||
return nil
|
||||
end
|
||||
local chunkName, blockName = findChunkAndBlock(selectedPart)
|
||||
if not chunkName or not blockName then
|
||||
debugPlacementWarn(
|
||||
"[PLACE][CLIENT][TARGET]",
|
||||
"failed to find chunk/block from selection",
|
||||
selectedPart:GetFullName()
|
||||
)
|
||||
return nil
|
||||
end
|
||||
|
||||
local okChunk, chunkCoords = pcall(function()
|
||||
return Util.BlockPosStringToCoords(chunkName :: string)
|
||||
end)
|
||||
local okBlock, blockCoords = pcall(function()
|
||||
return Util.BlockPosStringToCoords(blockName :: string)
|
||||
end)
|
||||
if not okChunk or not okBlock then
|
||||
debugPlacementWarn(
|
||||
"[PLACE][CLIENT][TARGET]",
|
||||
"failed to parse names",
|
||||
"chunkName",
|
||||
chunkName,
|
||||
"blockName",
|
||||
blockName
|
||||
)
|
||||
return nil
|
||||
end
|
||||
debugPlacementLog(
|
||||
"[PLACE][CLIENT][TARGET]",
|
||||
"chunk",
|
||||
chunkName,
|
||||
"block",
|
||||
blockName,
|
||||
"normal",
|
||||
(lastNormalId and lastNormalId.Name) or "nil"
|
||||
)
|
||||
|
||||
return {
|
||||
chunk = chunkCoords,
|
||||
block = blockCoords
|
||||
}
|
||||
|
||||
end
|
||||
|
||||
function PlacementManager:GetTargetAtMouse(): nil | {chunk:Vector3, block: Vector3, normal: Enum.NormalId}
|
||||
local hit = PlacementManager:GetBlockAtMouse()
|
||||
if not hit then
|
||||
return nil
|
||||
end
|
||||
local normal = lastNormalId or Enum.NormalId.Top
|
||||
|
||||
return {
|
||||
chunk = hit.chunk,
|
||||
block = hit.block,
|
||||
normal = normal
|
||||
}
|
||||
end
|
||||
|
||||
function PlacementManager:GetPlacementAtMouse(): nil | {chunk:Vector3, block: Vector3}
|
||||
local hit = PlacementManager:GetTargetAtMouse()
|
||||
if not hit then
|
||||
return nil
|
||||
end
|
||||
local offset = normalIdToOffset(hit.normal)
|
||||
local placeChunk, placeBlock = offsetChunkBlock(hit.chunk, hit.block, offset)
|
||||
debugPlacementLog(
|
||||
"[PLACE][CLIENT][PLACE_TARGET]",
|
||||
"target chunk",
|
||||
hit.chunk,
|
||||
"target block",
|
||||
hit.block,
|
||||
"normal",
|
||||
hit.normal.Name,
|
||||
"place chunk",
|
||||
placeChunk,
|
||||
"place block",
|
||||
placeBlock
|
||||
)
|
||||
return {
|
||||
chunk = placeChunk,
|
||||
block = placeBlock
|
||||
}
|
||||
end
|
||||
|
||||
function PlacementManager:DebugGetPlacementOrWarn()
|
||||
local placement = PlacementManager:GetPlacementAtMouse()
|
||||
if not placement then
|
||||
debugPlacementWarn("[PLACE][CLIENT][REJECT]", "no placement target under mouse", lastRaycastFailure)
|
||||
end
|
||||
return placement
|
||||
end
|
||||
|
||||
function PlacementManager:Init()
|
||||
game:GetService("RunService").RenderStepped:Connect(function()
|
||||
local a,b = pcall(function()
|
||||
PlacementManager:Raycast()
|
||||
end)
|
||||
if not a then
|
||||
clearSelection("raycast error")
|
||||
script.RaycastResult.Value = nil
|
||||
end
|
||||
end)
|
||||
tickRemote.OnClientEvent:Connect(function(m, cx, cy, cz, x, y, z, d)
|
||||
--warn("PROPOGATED TICK", m, cx, cy, cz, x, y, z, d)
|
||||
if m == "B_C" then
|
||||
applyPlaceBlockLocal(cx, cy, cz, x, y ,z, d)
|
||||
end
|
||||
if m == "B_D" then
|
||||
applyBreakBlockLocal(cx, cy, cz, x, y ,z)
|
||||
end
|
||||
if m == "C_R" then
|
||||
clearPendingBreaksForChunk(makeChunkKey(cx, cy, cz))
|
||||
ChunkManager:RefreshChunk(cx, cy, cz)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
return PlacementManager
|
||||
3
ReplicatedStorage/Shared/PlacementManager.meta.json
Normal file
3
ReplicatedStorage/Shared/PlacementManager.meta.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"ignoreUnknownInstances": true
|
||||
}
|
||||
35
ReplicatedStorage/Shared/PlacementState.lua
Normal file
35
ReplicatedStorage/Shared/PlacementState.lua
Normal file
@@ -0,0 +1,35 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
|
||||
local PlacementState = {}
|
||||
|
||||
local selectedId: string = ""
|
||||
local selectedName: string = ""
|
||||
|
||||
local changed = Instance.new("BindableEvent")
|
||||
PlacementState.Changed = changed.Event
|
||||
|
||||
local valueObject = ReplicatedStorage:FindFirstChild("HotbarSelectedBlock")
|
||||
if not valueObject then
|
||||
valueObject = Instance.new("StringValue")
|
||||
valueObject.Name = "HotbarSelectedBlock"
|
||||
valueObject.Parent = ReplicatedStorage
|
||||
end
|
||||
PlacementState.ValueObject = valueObject
|
||||
|
||||
function PlacementState:SetSelected(id: string?, name: string?)
|
||||
selectedId = id or ""
|
||||
selectedName = name or selectedId
|
||||
valueObject.Value = selectedName or ""
|
||||
local Util = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Util"))
|
||||
Util.StudioLog("[PLACE][CLIENT][SELECT]", "id", selectedId, "name", selectedName)
|
||||
changed:Fire(selectedId, selectedName)
|
||||
end
|
||||
|
||||
function PlacementState:GetSelected()
|
||||
return selectedId, selectedName
|
||||
end
|
||||
|
||||
return PlacementState
|
||||
76
ReplicatedStorage/Shared/Util.lua
Normal file
76
ReplicatedStorage/Shared/Util.lua
Normal file
@@ -0,0 +1,76 @@
|
||||
local RunService = game:GetService("RunService")
|
||||
local IS_STUDIO = RunService:IsStudio()
|
||||
|
||||
local module = {}
|
||||
|
||||
-- Prints only when running in Studio (avoids noisy live logs)
|
||||
function module.StudioLog(...: any)
|
||||
if not IS_STUDIO then
|
||||
return
|
||||
end
|
||||
print(...)
|
||||
end
|
||||
|
||||
function module.StudioWarn(...: any)
|
||||
if not IS_STUDIO then
|
||||
return
|
||||
end
|
||||
warn(...)
|
||||
end
|
||||
|
||||
function module.isNaN(n: number): boolean
|
||||
-- NaN is never equal to itself
|
||||
return n ~= n
|
||||
end
|
||||
|
||||
function module.isInf(n: number): boolean
|
||||
-- Number could be -inf or +inf
|
||||
return math.abs(n) == math.huge
|
||||
end
|
||||
|
||||
function module.BlockPosStringToCoords(s: string): Vector3
|
||||
-- a,b,c
|
||||
local split = string.split(s,",")
|
||||
return Vector3.new(tonumber(split[1]), tonumber(split[2]), tonumber(split[3]))
|
||||
end
|
||||
|
||||
function module.RotationStringToNormalId(s: string): Enum.NormalId
|
||||
if not s then return Enum.NormalId.Front end
|
||||
if s == "f" then
|
||||
return Enum.NormalId.Front
|
||||
end
|
||||
if s == "b" then
|
||||
return Enum.NormalId.Back
|
||||
end
|
||||
if s == "l" then
|
||||
return Enum.NormalId.Left
|
||||
end
|
||||
if s == "r" then
|
||||
return Enum.NormalId.Right
|
||||
end
|
||||
if s == "t" then
|
||||
return Enum.NormalId.Top
|
||||
end
|
||||
if s == "b" then
|
||||
return Enum.NormalId.Bottom
|
||||
end
|
||||
warn("Could not convert",s,"to Enum.NormalId")
|
||||
return Enum.NormalId.Front
|
||||
end
|
||||
|
||||
-- chunk size 8x8x8 relative block indexs 1-8
|
||||
function module.GlobalBlockPosToRelative(x: number,y:number,z:number)
|
||||
return x%8,y%8,z%8
|
||||
end
|
||||
|
||||
function module.ChunkPosToCFrame(chunk: Vector3, block: Vector3): CFrame
|
||||
return CFrame.new(
|
||||
CFrame.new(
|
||||
(32*chunk.X)+(block.X*4)-18,
|
||||
(32*chunk.Y)+(block.Y*4)-18,
|
||||
(32*chunk.Z)+(block.Z*4)-18
|
||||
).Position
|
||||
)
|
||||
end
|
||||
|
||||
return module
|
||||
3
ReplicatedStorage/Shared/init.meta.json
Normal file
3
ReplicatedStorage/Shared/init.meta.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"ignoreUnknownInstances": true
|
||||
}
|
||||
Reference in New Issue
Block a user