@@ -1,21 +1,18 @@
local mathAbs , mathRound, mathMin , mathMax , posToString
= math.abs , math. round , math.min , math.max , core.pos_to_string
local mathRound , mathRandom , mathClamp , tableInsert
= math.round , math.random , math.clamp , table.insert
local posToString , getUsTime = core.pos_to_string , core.get_us_time
local pairs , ipairs , assert = pairs , ipairs , assert
local v = vector.new
local id = core.get_content_id
local AIR_ID = core.CONTENT_AIR
local getInstance = Class.getInstance
local LOG_PROFILE = true
local function calculateAverage ( t )
if # t == 0 then return 0 end -- Защита от деления на ноль
local sum = 0
for i = 1 , # t do
sum = sum + t [ i ]
end
return sum / # t
end
local PROFILE_CHUNK = true
local function mglog ( text , ... )
core.log ( ( text ) : format ( ... ) )
@@ -24,34 +21,30 @@ end
local modInfo = Mod.getInfo ( ' smc__core__map_gen ' )
local require = modInfo.require
---Numeric values defining the surface height and climate for the node.
---@alias MapGen.factors {height:number, temp:number, humidity:number}
---@alias MapGen.PastCalcNoiseValue {triangle:MapGen.Triangle?, x:integer?, z:integer?, noiseValue:number?}
---Table of all past generation factor calculations for nodes.
---
---Contains generation factors by layer name and coordinate.
---@type table<string, table<string, MapGen.factors>>
local pastNoiseValues = { }
---@type table<MapGen.Layer.Category, MapGen.PastCalcNoiseValue>
local pastNoise2DCalc = {
landscape = { } ,
temp = { } ,
humidity = { }
}
---The triangle in which generation occurred for the previous node.
---@type MapGen.Triangle?
local pastTriangle
---@type MapGen.Layer
local Layer = require ( ' MapGen.Layer ' )
---@type MapGen.StaticLayer
local StaticLayer = require ( ' MapGen.StaticLayer ' )
---@type MapGen.Biome
local Biome = require ( ' MapGen.Biome ' )
---@type MapGen.Cavern
local Cavern = require ( ' MapGen.Cavern ' )
---@type MapGen.Region
local Region = require ( ' MapGen.Region ' )
local ff2luat = require ( ' MapGen.ff2luat ' )
---@class MapGen
---@field layersByName table<string, MapGen.Layer>
---@field layersList MapGen.Layer[]
@@ -60,6 +53,7 @@ local ff2luat = require('MapGen.ff2luat')
---@field isLayersNoisesInitialized boolean Is the fractal noise of the layer initialized? This is necessary for a one-time noise initialization.
---@field isCavernsNoiseInitialized boolean Is the fractal noise of the caverns initialized? This is necessary for a one-time noise initialization.
---@field isRunning boolean A static field that guarantees that only one instance of the `MapGen` class will work.
---@field nodes table<string, string>
---@field nodeIDs table<string, number>
local MapGen = {
layersByName = { } ,
@@ -86,11 +80,9 @@ function MapGen:new(def)
nodesIDs [ k ] = id ( v )
end
---@type MapGen
local instance = getInstance ( self , {
nodes = def. nodes,
nodeIDs = nodesIDs ,
} )
local instance = getInstance ( self , { } )
instance.nodes = def.nodes
instance. nodeID s = nodesIDs
return instance
end
@@ -107,18 +99,16 @@ function MapGen:getLayerByName(layerName)
end
---Determines which layer a node belongs to based on its height coordinate.
---@param yPos number
---@param y number
---@return MapGen.Layer?
function MapGen : getLayerByHeight ( yPos )
function MapGen : getLayerByHeight ( y )
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз
--- Можно подумать над тем, чтобы использовать сортированный список
---@param layer MapGen.Layer
for _ , layer in ipairs ( self.layersList ) do
if yPos >= layer.minY and yPos <= layer.maxY then
if y >= layer.minY and y <= layer.maxY then
return layer
end
@@ -126,9 +116,9 @@ function MapGen:getLayerByHeight(yPos)
end
---Determines which statics layer a node belongs to based on its height coordinate.
---@param yPos number
---@param y number
---@return MapGen.StaticLayer?
function MapGen : getStaticByHeight ( yPos )
function MapGen : getStaticByHeight ( y )
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз
@@ -137,7 +127,7 @@ function MapGen:getStaticByHeight(yPos)
---@param static MapGen.StaticLayer
for _ , static in ipairs ( self.staticsList ) do
if yPos >= static.minY and yPos <= static.maxY then
if y >= static.minY and y <= static.maxY then
return static
end
@@ -146,16 +136,15 @@ end
---Returns the `MapGen.Peak` at the coordinates. If there is no peak at these coordinates, it returns `nil`.
---@param layer string|MapGen.Layer The layer or name of the layer in which the peak is located.
---@param category MapGen.Layer.Category The category in which the peak is located.
---@param pos MapPosition Coordinate of the desired peak.
---@return MapGen.Peak?
function MapGen : getPeakByPos ( layer , category , pos )
function MapGen : getPeakByPos ( layer , pos )
if type ( layer ) == ' string ' then
local layerName = layer
layer = self : getLayerByName ( layerName )
end
return layer : getPeakByPos ( category , pos)
return layer : getPeakByPos ( pos )
end
---Checks if a point is inside a triangle using the vector product method.
@@ -165,7 +154,7 @@ end
---
---**Note**: works only with coordinates X-Z.
---@param triangle MapGen.Triangle
---@param pointPos v ector
---@param pointPos IntegerV ector
---@return boolean, MapGen.Triangle?
function MapGen : isPointInTriangle ( triangle , pointPos )
local e1 , e2 , e3 = triangle.e1 , triangle.e2 , triangle.e3
@@ -188,18 +177,22 @@ function MapGen:isPointInTriangle(triangle, pointPos)
return true , triangle
end
---Finds the triangle containing the point specified by coordinates X & Z.
---@param layer MapGen.Layer The layer of the layer the triangle is in.
---@param category MapGen.Layer.Category The category in which the triangle is in.
---@param x integer
---@param z integer
---@param triangle MapGen.Triangle?
---@param triangle MapGen.Triangle? The triangle from which to begin the search.
--- If not specified, the search will be performed
--- from the triangle at `id = 1`
---@return MapGen.Triangle?
function MapGen : findTriangle ( layer , category , x , z , triangle )
function MapGen : findTriangle ( layer , x , z , triangle )
if triangle == nil then
triangle = layer.trianglesList [ category ] [ 1 ]
triangle = layer.trianglesList [ 1 ]
end
-- Limit the number of iterations to prevent the loop from going into infinity.
local iterationCount = 1000000
local isFound = false
while not isFound do
if iterationCount < 0 then
@@ -209,7 +202,9 @@ function MapGen:findTriangle(layer, category, x, z, triangle)
end
iterationCount = iterationCount - 1
assert ( triangle )
if triangle == nil then
return nil
end
isFound , triangle = self : isPointInTriangle ( triangle , v ( x , 0 , z ) )
end
@@ -218,6 +213,7 @@ function MapGen:findTriangle(layer, category, x, z, triangle)
end
---Checks if a point is inside a region.
---
---If the point is inside the region, it will also return the distance to the nearest border.
---@param layer MapGen.Layer The name of the layer in which the region is located.
---@param regionName string The name of the region in which the location of the point is checked.
@@ -267,7 +263,7 @@ local function vertexKey(peak)
end
---Creates a canonical (sorted) key for an edge.
---@param edge MapGen.Triangulation. Edge
---@param edge MapGen.Edge
---@return string
local function edgeKey ( edge )
local k1 = vertexKey ( edge.p1 )
@@ -287,7 +283,7 @@ end
function MapGen : getTriangulateBoundaryVertices ( triangles )
-- Count how many triangles share each edge
local edgeCount = { }
---@type table<string, MapGen.Triangulation. Edge>
---@type table<string, MapGen.Edge>
local edgeData = { }
for _ , triangle in ipairs ( triangles ) do
@@ -306,12 +302,12 @@ function MapGen:getTriangulateBoundaryVertices(triangles)
end
-- Boundary edges belong to exactly ONE triangle
---@type MapGen.Triangulation. Edge[]
---@type MapGen.Edge[]
local boundaryEdges = { }
for key , count in pairs ( edgeCount ) do
if count == 1 then
table.i nsert ( boundaryEdges , edgeData [ key ] )
tableI nsert ( boundaryEdges , edgeData [ key ] )
end
end
@@ -335,8 +331,8 @@ function MapGen:getTriangulateBoundaryVertices(triangles)
adjacency [ k1 ] = adjacency [ k1 ] or { }
adjacency [ k2 ] = adjacency [ k2 ] or { }
table.i nsert ( adjacency [ k1 ] , k2 )
table.i nsert ( adjacency [ k2 ] , k1 )
tableI nsert ( adjacency [ k1 ] , k2 )
tableI nsert ( adjacency [ k2 ] , k1 )
end
-- Walk along boundary edges to create ordered vertex list
@@ -356,7 +352,7 @@ function MapGen:getTriangulateBoundaryVertices(triangles)
visited [ currentKey ] = true
local pos = vertexData [ currentKey ] . pos
table.i nsert ( boundary , {
tableI nsert ( boundary , {
x = pos.x ,
y = 0 ,
z = pos.z
@@ -398,7 +394,9 @@ function MapGen:registerLayer(name, def)
local layer = Layer : new ( name , def )
self.layersByName [ name ] = layer
table.i nsert ( self.layersList , layer )
tableI nsert ( self.layersList , layer )
pastNoiseValues [ name ] = { }
-- Sort layers by maxY descending for processing priority.
table.sort ( self.layersList , function ( a , b )
@@ -433,7 +431,7 @@ function MapGen:registerStaticLayer(name, def)
local static = StaticLayer : new ( name , def )
self.staticsByName [ name ] = static
table.i nsert ( self.staticsList , static )
tableI nsert ( self.staticsList , static )
-- Sort srtatics by maxY descending for processing priority.
table.sort ( self.staticsList , function ( a , b )
@@ -498,12 +496,11 @@ end
---Initialize the boundary region for a layer and category.
---@param layer MapGen.Layer
---@param category MapGen.Layer.Category
function MapGen : initTriangultaionBoundaryRegion ( layer , category )
local triangles = layer.trianglesList [ category ]
function MapGen : initTriangultaionBoundaryRegion ( layer )
local triangles = layer.trianglesList
local regionVertices = self : getTriangulateBoundaryVertices ( triangles )
local regionName = category .. ' _boundary '
local regionName = ' triangles _boundary'
local region = Region : new ( regionName , { vertices = regionVertices } )
@@ -511,12 +508,10 @@ function MapGen:initTriangultaionBoundaryRegion(layer, category)
end
---Initialize border regions for all layers and all categories.
function MapGen : initLayersBoundaryRegions ( )
function MapGen : initLayersBoundaryRegion ( )
---@param layer MapGen.Layer
for _ , layer in ipairs ( self.layersList ) do
self : initTriangultaionBoundaryRegion ( layer , ' landscape ' )
self : initTriangultaionBoundaryRegion ( layer , ' temp ' )
self : initTriangultaionBoundaryRegion ( layer , ' humidity ' )
self : initTriangultaionBoundaryRegion ( layer )
end
end
@@ -613,17 +608,17 @@ local function generateNode(mapGenerator, layer, factors, data, index, x, y, z)
local scattHeight = y
if scatteringGorizontal ~= 0 then
scattTemp = scattTemp + math.r andom ( scatteringGorizontal * - 1 , scatteringGorizontal )
scattHumidity = scattHumidity + math.r andom ( scatteringGorizontal * - 1 , scatteringGorizontal )
scattTemp = scattTemp + mathR andom ( scatteringGorizontal * - 1 , scatteringGorizontal )
scattHumidity = scattHumidity + mathR andom ( scatteringGorizontal * - 1 , scatteringGorizontal )
end
if scatteringVertical ~= 0 then
scattHeight = scattHeight + math.r andom ( scatteringVertical * - 1 , scatteringVertical )
scattHeight = scattHeight + mathR andom ( scatteringVertical * - 1 , scatteringVertical )
end
scattTemp = math.c lamp ( scattTemp , layer.minTemp , layer.maxTemp )
scattHumidity = math.c lamp ( scattHumidity , layer.minHumidity , layer.maxHumidity )
scattHeight = math.c lamp ( scattHeight , layer.minY , layer.maxY )
scattTemp = mathC lamp ( scattTemp , layer.minTemp , layer.maxTemp )
scattHumidity = mathC lamp ( scattHumidity , layer.minHumidity , layer.maxHumidity )
scattHeight = mathC lamp ( scattHeight , layer.minY , layer.maxY )
scattHeight , scattTemp , scattHumidity = mathRound ( scattHeight ) , mathRound ( scattTemp ) , mathRound ( scattHumidity )
height , temp , humidity = mathRound ( height ) , mathRound ( scattTemp ) , mathRound ( scattHumidity )
@@ -693,13 +688,13 @@ end
---Calculates a weight for a coordinate using the projection onto
---the triangle's height and specifying the distance to the peak
---for which the weight is calculated.
---@param height MapGen.Triangulation. Edge
---@param height MapGen.Edge
---@param x integer
---@param y integer
---@param z integer
---@return number
local function calcWeight ( height , x , y , z )
local pos1 = vector.new ( x , y , z )
local pos1 = v ( x , y , z )
local pos2 = height.p1 . pos
local pos3 = height.p2 . pos
@@ -713,7 +708,7 @@ local function calcWeight(height, x, y, z)
local posP = pos2 + v * t
return 1 - vector. distance( pos2 , posP ) / height : length ( )
return 1 - pos2 : distance( posP ) / height : length ( )
end
---Returns the weighted values of 2d noise.
@@ -766,60 +761,67 @@ end
---Calculates a smoothed 2D noise value based on a preliminary space partitioning.
---
---Returns `nil` if the point is not included in any triangle.
---@param category MapGen.Layer.Category
---@param layer MapGen.Layer
---@param x integer
---@param y integer
---@param z integer
---@return number?
function MapGen : getNoises2dValue ( categ ory , layer , x , y , z )
---@type MapGen.PastCalcNoiseValue
local pastCalc = pastNoise2DCalc [ category ]
---@return number?, number?, number?
function MapGen : getFact ors ( layer , x , y , z )
local posString = posToString ( { x = x , y = 0 , z = z } )
if ( pastCalc.x ~ = nil and pastCalc.z ~= nil ) and ( x == pastCalc.x and z == pastCalc.z ) then
return pastCalc.noiseValue
local factors = pastNoiseValues [ layer.name ] [ posString ]
if factors ~= nil then
return factors.height , factors.temp , factors.humidity
end
if not self : pointInRegion2D ( layer , category .. ' _boundary ' , { x = x , y = y , z = z } ) then
return nil
-- TODO: это сильно тормозит обычные чанки, но ускоряет те, что находятся за границей
if not self : pointInRegion2D ( layer , ' triangles_boundary ' , { x = x , y = y , z = z } ) then
return
end
if pastCalc.t riangle ~= nil then
---@type number?
local noiseValue
if pastT riangle ~= nil then
local triangles = {
pastCalc.t riangle ,
pastCalc.t riangle. neighbours [ 1 ] ,
pastCalc.t riangle. neighbours [ 2 ] ,
pastCalc.t riangle. neighbours [ 3 ] ,
pastT riangle ,
pastT riangle. neighbours [ 1 ] ,
pastT riangle. neighbours [ 2 ] ,
pastT riangle. neighbours [ 3 ] ,
}
---@param t MapGen.Triangle
for _ , t in ipairs ( triangles ) do
if self : isPointInTriangle ( t , v ( x , 0 , z ) ) then
noiseValue = calcNoise2dValue ( category , layer , t , x , y , z )
---@param triangle MapGen.Triangle
for _ , triangle in ipairs ( triangles ) do
if self : isPointInTriangle ( triangle , v ( x , 0 , z ) ) then
local height = calcNoise2dValue ( ' landscape ' , layer , triangle , x , y , z )
local temp = calcNoise2dValue ( ' temp ' , layer , triangle , x , y , z )
local humidity = calcNoise2dValue ( ' humidity ' , layer , triangle , x , y , z )
pastCalc.x = x
pastCalc.z = z
pastCalc.noiseValue = noiseValue
pastNoiseValues [ layer.name ] [ posString ] = {
height = height ,
temp = temp ,
humidity = humidity
}
return noiseValue
return height , temp , humidity
end
end
end
local triangle = self : findTriangle ( layer , category , x , z , pastCalc.t riangle )
assert ( triangle ~ = nil )
local triangle = self : findTriangle ( layer , x , z , pastT riangle )
if triangle = = nil then
return
end
local noiseValue = calcNoise2dValue ( category , layer , triangle , x , y , z )
local height = calcNoise2dValue ( ' landscape ' , layer , triangle , x , y , z )
local temp = calcNoise2dValue ( ' temp ' , layer , triangle , x , y , z )
local humidity = calcNoise2dValue ( ' humidity ' , layer , triangle , x , y , z )
pastCalc.t riangle = triangle
pastCalc.x = x
pastCalc.z = z
pastCalc.noiseValue = noiseValue
pastT riangle = triangle
pastNoiseValues [ layer.name ] [ posString ] = {
height = height ,
temp = temp ,
humidity = humidity
}
return noiseValue
return height , temp , humidity
end
---Generator handler for specific coordinates.
@@ -830,68 +832,45 @@ end
---@param x integer
---@param y integer
---@param z integer
---@return number, number, number
local function generatorHandler ( mapGenerator , layer , data , index , x , y , z )
local startGetLayerTime = core.get_us_time ( )
-- If the node belongs to a static layer, then a static node is generated.
local static = mapGenerator : getStaticByHeight ( y )
if static ~= nil then
static : generateStaticNode ( mapGenerator , data , index , x , y , z )
return core.get_us_time ( ) - startGetLayerTime , 0 , 0
return
end
-- If generation occurs outside the layers, then a void is generated.
if layer == nil then
data [ index ] = mapGenerator.nodeIDs . air
return core.get_us_time ( ) - startGetLayerTime , 0 , 0
return
end
local endGetLayerTime = core.get_us_t ime( )
local endGetLayerTime = getUsT ime( )
local startNoiseCalcTime = endGetLayerTime
-- If the value of the noise is `nil`,
-- then the point does not fall within any of the triangles.
local noiseHeightValue = mapGenerator : getNoises2dValue ( ' landscape ' , layer , x , y , z )
if noiseHeightValue == nil then
local height , temp , humidity = mapGenerator : getFactors ( layer , x , y , z )
if height == nil or temp == nil or humidity == nil then
data [ index ] = core.CONTENT_IGNORE
return endGetLayerTime - startGetLayerTime , core.get_us_time ( ) - startNoiseCalcTime , 0
end
local noiseTempValue = mapGenerator : getNoises2dValue ( ' temp ' , layer , x , y , z )
if noiseTempValue == nil then
data [ index ] = core.CONTENT_IGNORE
return endGetLayerTime - startGetLayerTime , core.get_us_time ( ) - startNoiseCalcTime , 0
end
local noiseHumidityValue = mapGenerator : getNoises2dValue ( ' humidity ' , layer , x , y , z )
if noiseHumidityValue == nil then
data [ index ] = core.CONTENT_IGNORE
return endGetLayerTime - startGetLayerTime , core.get_us_time ( ) - startNoiseCalcTime , 0
return
end
-- We recalculate the climate based on altitude.
noiseTempValue = layer : calcTemp ( noiseTempValue , y )
noiseH umidityValue = layer : calcHumidity ( noiseH umidityValue , y )
temp = layer : calcTemp ( temp , y )
h umidity = layer : calcHumidity ( h umidity, y )
---@type MapGen.factors
local factors = {
height = noiseHeightValue ,
temp = noiseTempValue ,
humidity = noiseH umidityValue ,
height = height ,
temp = temp ,
humidity = h umidity,
}
local endNoiseCalcTime = core.get_us_time ( )
local startGenNodeTime = endNoiseCalcTime
generateNode ( mapGenerator , layer , factors , data , index , x , y , z )
local endGenNodeTime = core.get_us_time ( )
return endGetLayerTime - startGetLayerTime , endNoiseCalcTime - startNoiseCalcTime , endGenNodeTime - startGenNodeTime
end
---Chunk generation handler.
@@ -901,15 +880,15 @@ end
---@param blockseed number
function MapGen : onMapGenerated ( voxelManip , minPos , maxPos , blockseed )
local minPosStr , maxPosStr = posToString ( minPos ) , posToString ( maxPos )
local getLayer Time, NoiseCalcTime , GenNodeTime = { } , { } , { }
local start Time, endTime = 0.0 , 0.0
if LOG_PROFILE then
mglog ( ' Chunk run: \n ' ..
' min_pos: %s \n ' ..
' max_pos: %s \n ' ,
minPosStr , maxPosStr )
startTime = getUsTime ( )
end
local startTime = core.get_us_time ( )
local eMin , eMax = voxelManip : get_emerged_area ( )
@@ -937,12 +916,8 @@ function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed)
for y = minPos.y , maxPos.y do
index = area : index ( x , y , z )
if data [ index ] == core.CONTENT_ AIR then
local t1 , t2 , t3 = generatorHandler ( self , layer , data , index , x , y , z )
table.insert ( getLayerTime , t1 )
table.insert ( NoiseCalcTime , t2 )
table.insert ( GenNodeTime , t3 )
if data [ index ] == AIR_ID then
generatorHandler ( self , layer , data , index , x , y , z )
end
end
end
@@ -975,19 +950,17 @@ function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed)
voxelManip : calc_lighting ( )
voxelManip : update_liquids ( )
local endTime = core.get_us_time ( )
if LOG_PROFILE then
pastTriangle = nil
if PROFILE_CHUNK then
endTime = getUsTime ( )
mglog ( ' Chunk end: \n ' ..
' min_pos: %s \n ' ..
' max_pos: %s \n ' ..
' time (sec): %.3f \n ' ..
' GenerateHandler time (us): %.3f %.3f %.3f \n ' ..
' --------------- ' ,
minPosStr , maxPosStr ,
( endTime - startTime ) / 1000000 ,
calculateAverage ( getLayerTime ) ,
calculateAverage ( NoiseCalcTime ) ,
calculateAverage ( GenNodeTime ) )
( endTime - startTime ) / 1000000 )
end
end
@@ -1011,7 +984,7 @@ function MapGen:run()
end )
self : initBiomesDiagram ( )
self : initLayersBoundaryRegions ( )
self : initLayersBoundaryRegion ( )
MapGen.isRunning = true
core.log ( ' MapGen run ' )