Certainly! To achieve the functionality where the script clears the previous water blocks before filling new ones, you can implement a tracking mechanism for the water-filled blocks. This ensures that each simulation step correctly removes the water from the previous state before applying the new state.
Below are the necessary modifications to your script:
-
Introduce a Table to Track Previous Water Blocks:
- Add a new table
previousWaterBlocks to keep track of all the positions where water was previously filled.
-
Clear Previous Water Blocks Before Filling New Ones:
- Before processing the new water blocks in each simulation step, iterate through the
previousWaterBlocks table and clear those blocks by setting them to Air.
-
Update the Tracking Table with Current Water Blocks:
- After filling the new water blocks, update the
previousWaterBlocks table with the current positions where water has been filled.
Modified Script with Necessary Changes Highlighted
-- MainSimulation Script
local GMFluxContainer = require(game.ServerScriptService.GMFluxContainer)
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local CollectionService = game:GetService("CollectionService")
local terrain = Workspace.Terrain
-- Simulation parameters
local texSize = 128 -- Adjust as needed (reasonable sizes: 64, 128)
local cellSize = 2 -- Size of each cell in world units
local simPosition = Vector3.new(-100, 0, -200) -- Adjust to move the fluid grid
-- Controllable simulation parameters
local simulationParameters = {
fluxStrength = 0.25, -- Controls the fluid flow strength
fluxAtten = 0.975, -- Fluid attenuation
fluxSpill = 0.0, -- Fluid spill threshold
simulationSpeed = 0.03, -- Controls the simulation step interval
fluidGenerationRate = 500, -- Controls the rate at which fluid is added per source per step
heightmapUpdateInterval = 1 -- Interval in seconds to update the heightmap
}
-- Create an instance of the simulation container
local sim = GMFluxContainer.new(texSize, simPosition, cellSize, simulationParameters)
-- Visualization parts parent
local visualizationFolder = Instance.new("Folder")
visualizationFolder.Name = "VisualizationParts"
visualizationFolder.Parent = Workspace
-- Create parts to visualize the simulation
local partsGrid = {}
local basePosition = sim.position
for x = 1, sim.texSize do
partsGrid[x] = {}
local worldX = basePosition.X + (x - 1) * sim.cellSize
for y = 1, sim.texSize do
local part = Instance.new("Part")
part.Size = Vector3.new(sim.cellSize, 0.1, sim.cellSize) -- Initial minimal size
local height = sim.cells[x][y][GMFluxContainer.FluxCell.Height]
part.Position = Vector3.new(worldX, height + 0.05, basePosition.Z + (y - 1) * sim.cellSize)
part.Anchored = true
part.Material = Enum.Material.Slate -- Terrain material
part.Color = Color3.fromRGB(139, 69, 19) -- Brown color for terrain
part.Transparency = 0
part.CastShadow = false
part.Parent = visualizationFolder -- Parent to visualization folder
-- Add attribute to track particle emitter
part:SetAttribute("HasParticleEmitter", false)
partsGrid[x][y] = part
end
end
-- List of collidable objects (Advanced collisions)
local collidableObjectsFolder = Workspace:FindFirstChild("CollidableObjects")
local collidableObjects = {}
if collidableObjectsFolder then
collidableObjects = collidableObjectsFolder:GetChildren()
end
-- List of water sources
local waterSources = {
{x = math.floor(sim.texSize / 2), y = math.floor(sim.texSize / 2)},
-- Add more sources as needed
}
-- Function to generate the terrain heightmap using raycasts
local function generateTerrainHeightmap(sim)
local heightmap = {}
local basePosition = sim.position
local cellSize = sim.cellSize
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {visualizationFolder}
raycastParams.IgnoreWater = true
local maxTerrainHeight = 1000 -- Adjust based on your terrain
local direction = Vector3.new(0, -maxTerrainHeight - 100, 0)
for x = 1, sim.texSize do
heightmap[x] = {}
local worldX = basePosition.X + (x - 0.5) * cellSize
for y = 1, sim.texSize do
local worldZ = basePosition.Z + (y - 0.5) * cellSize
local origin = Vector3.new(worldX, maxTerrainHeight, worldZ)
local raycastResult = Workspace:Raycast(origin, direction, raycastParams)
local height = 0
if raycastResult then
height = raycastResult.Position.Y
else
-- No hit, set to base level
height = 0
end
heightmap[x][y] = height
end
end
return heightmap
end
-- Generate the initial terrain heightmap
local heightmap = generateTerrainHeightmap(sim)
-- Set the terrain heightmap in the simulation
sim:cellEncodeHeightmap(heightmap, 1) -- Height factor is 1
-- **NEW CODE: Initialize a table to track previous water blocks**
local previousWaterBlocks = {}
-- Simulation loop
local lastHeightmapUpdate = 0
local simulationTimer = 0
RunService.Heartbeat:Connect(function(deltaTime)
simulationTimer = simulationTimer + deltaTime
-- Add fluid at specified water sources
for _, source in ipairs(waterSources) do
sim:addFluid(source.x, source.y, simulationParameters.fluidGenerationRate)
end
-- Perform simulation steps at the specified interval
if simulationTimer >= simulationParameters.simulationSpeed then
simulationTimer = 0
-- **NEW CODE: Clear previous water blocks**
for _, pos in ipairs(previousWaterBlocks) do
terrain:FillBlock(CFrame.new(pos), Vector3.new(cellSize, cellSize, cellSize), Enum.Material.Air)
end
-- Reset the table for the current step's water blocks
previousWaterBlocks = {}
-- Perform simulation steps
sim:stepFlux()
sim:stepDepth()
-- Handle collisions
sim:handleCollisions(collidableObjects)
-- Update visualization
for x = 1, sim.texSize do
local partsColumn = partsGrid[x]
local simCellsColumn = sim.cells[x]
local worldX = basePosition.X + (x - 1) * sim.cellSize
for y = 1, sim.texSize do
local part = partsColumn[y]
local cell = simCellsColumn[y]
local depth = cell[GMFluxContainer.FluxCell.Depth]
local height = cell[GMFluxContainer.FluxCell.Height]
local worldZ = basePosition.Z + (y - 1) * sim.cellSize
if depth > 0 then
-- Scale the part to represent the fluid depth
part.Size = Vector3.new(sim.cellSize, depth, sim.cellSize)
part.Position = Vector3.new(worldX, height + depth / 2, worldZ)
-- Set material and color for water
--part.Material = Enum.Material.Water
-- Color intensity based on depth
local colorIntensity = math.clamp(depth / 10, 0, 1)
--part.Color = Color3.new(0, 0, colorIntensity)
part.Transparency = 1 -- Less transparent with more depth
-- **NEW CODE: Fill with Air first and then Water**
terrain:FillBlock(CFrame.new(part.Position), part.Size, Enum.Material.Air)
terrain:FillBlock(CFrame.new(part.Position), part.Size, Enum.Material.Water)
-- **NEW CODE: Track current water block positions**
table.insert(previousWaterBlocks, part.Position)
else
-- Minimal size for empty cells
part.Size = Vector3.new(sim.cellSize, 0.1, sim.cellSize)
part.Position = Vector3.new(worldX, height + 0.05, worldZ)
-- Set material and color for terrain
part.Material = Enum.Material.Slate -- Terrain material
part.Color = Color3.fromRGB(139, 69, 19) -- Brown color for terrain
part.Transparency = 0
--game.Workspace.Terrain:FillBlock(CFrame.new(part.Position), part.Size, Enum.Material.Air)
end
-- NEW CODE STARTS HERE
-- Detect high flux (too much force)
-- Compute total flux magnitude for the cell
local fluxLD = cell[GMFluxContainer.FluxCell.FluxLD]
local fluxRU = cell[GMFluxContainer.FluxCell.FluxRU]
local totalFlux = math.abs(fluxLD.left) + math.abs(fluxLD.down) + math.abs(fluxRU.right) + math.abs(fluxRU.up)
-- Set a flux threshold for creating particles
local fluxThreshold = 15 -- Adjust this value as needed
-- Detect cliffs
-- Compare current cell height with neighboring cells
local isCliff = false
local heightDifferenceThreshold = 5 -- Adjust based on terrain height variation
local neighbors = {}
if x > 1 then
table.insert(neighbors, sim.cells[x - 1][y])
end
if x < sim.texSize then
table.insert(neighbors, sim.cells[x + 1][y])
end
if y > 1 then
table.insert(neighbors, sim.cells[x][y - 1])
end
if y < sim.texSize then
table.insert(neighbors, sim.cells[x][y + 1])
end
for _, neighborCell in ipairs(neighbors) do
local neighborHeight = neighborCell[GMFluxContainer.FluxCell.Height]
if math.abs(height - neighborHeight) >= heightDifferenceThreshold then
isCliff = true
break
end
end
-- If total flux exceeds threshold or is a cliff, add particle emitter
if totalFlux >= fluxThreshold or isCliff then
if not part:GetAttribute("HasParticleEmitter") then
-- Add particle emitter to the part
local particleEmitter = Instance.new("ParticleEmitter")
particleEmitter.Name = "SplashEffect"
particleEmitter.Parent = part
-- Configure particle emitter properties
particleEmitter.Texture = "rbxassetid://243660364" -- Example texture ID; replace with your own texture
particleEmitter.Lifetime = NumberRange.new(0.5, 1)
particleEmitter.Rate = 50
particleEmitter.Speed = NumberRange.new(5, 10)
particleEmitter.Rotation = NumberRange.new(0, 360)
particleEmitter.RotSpeed = NumberRange.new(-180, 180)
particleEmitter.VelocitySpread = 180
particleEmitter.Enabled = true
-- Set particle color if needed
particleEmitter.Color = ColorSequence.new(Color3.new(1, 1, 1))
-- Set the emission direction upwards
particleEmitter.EmissionDirection = Enum.NormalId.Top
part:SetAttribute("HasParticleEmitter", true)
end
else
-- Remove particle emitter if it exists
if part:GetAttribute("HasParticleEmitter") then
local particleEmitter = part:FindFirstChild("SplashEffect")
if particleEmitter then
particleEmitter:Destroy()
end
part:SetAttribute("HasParticleEmitter", false)
end
end
-- NEW CODE ENDS HERE
end
end
end
-- Periodically update the heightmap
lastHeightmapUpdate = lastHeightmapUpdate + deltaTime
if lastHeightmapUpdate >= simulationParameters.heightmapUpdateInterval then
lastHeightmapUpdate = 0
-- Update the heightmap
heightmap = generateTerrainHeightmap(sim)
sim:cellEncodeHeightmap(heightmap, 1)
end
end)
Explanation of the Changes
-
Tracking Previous Water Blocks:
-
Clearing Previous Water Blocks:
- Clearing Step: At the beginning of each simulation step (inside the
Heartbeat function), iterate through the previousWaterBlocks table and clear each block by setting it to Air. This ensures that all water from the previous step is removed before applying the new water locations.
for _, pos in ipairs(previousWaterBlocks) do
terrain:FillBlock(CFrame.new(pos), Vector3.new(cellSize, cellSize, cellSize), Enum.Material.Air)
end
-- Reset the table for the current step's water blocks
previousWaterBlocks = {}
-
Filling New Water Blocks and Tracking Them:
- Filling Water: After clearing the previous water blocks and during the visualization update, when a cell has
depth > 0, fill it with Water and track its position by inserting it into the previousWaterBlocks table.
if depth > 0 then
-- Existing code to set part size and position
-- Fill with Air first and then Water
terrain:FillBlock(CFrame.new(part.Position), part.Size, Enum.Material.Air)
terrain:FillBlock(CFrame.new(part.Position), part.Size, Enum.Material.Water)
-- Track current water block positions
table.insert(previousWaterBlocks, part.Position)
else
-- Existing code for handling non-water cells
end
Notes
-
Performance Consideration: Tracking and clearing water blocks every simulation step can be performance-intensive, especially with large texSize values. If you experience performance issues, consider optimizing the tracking mechanism, such as only tracking cells that have changed state.
-
Consistency in Positions: Ensure that the part.Position accurately represents the center of the block you intend to fill. Any discrepancies might lead to unintended blocks being cleared or filled.
-
Material Order: The script first sets the block to Air and then to Water. This order is crucial to prevent overlapping materials and ensure that the Water material is correctly applied.
By implementing these changes, the simulation will now correctly clear the previous water blocks before filling new ones, ensuring that the fluid behaves as expected without residual water from earlier steps.