local assert = assert local pairs, ipairs = pairs, ipairs local mathRound, mathRandom, mathClamp = math.round, math.random, math.clamp local tableInsert, tableSort = table.insert, table.sort local v = vector.new local id = core.get_content_id local AIR_ID = core.CONTENT_AIR local corePosToString, coreGetUsTime = core.pos_to_string, core.get_us_time local getInstance = Class.getInstance local LOG_PROFILE = true local PROFILE_CHUNK = true local function mglog(text, ...) core.log((text):format(...)) end local require = Mod.getInfo('smc__core__map_gen').require ---Numeric values ​​defining the surface height and climate for the node. ---@alias MapGen.Factors {height:number, temp:number, humidity:number, weight:number} ---Table of all past generation factor calculations for nodes. --- ---Contains generation factors by layer name and coordinate. ---@type table> local pastNoiseValues = {} ---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') ---@type MapGen.Tree local Tree = require('MapGen.Tree') ---@type MapGen.Ore local Ore = require('MapGen.Ore') ---@class MapGen ---@field layersByName table ---@field layersList MapGen.Layer[] --- ---@field staticsByName table ---@field staticsList MapGen.StaticLayer[] --- ---@field treesByName table --- ---@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 isOresNoiseInitialized boolean Is the fractal noise of the ores 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 ---@field nodeIDs table local MapGen = { layersByName = {}, layersList = {}, staticsByName = {}, staticsList = {}, treesByName = {}, isLayersNoisesInitialized = false, isCavernsNoiseInitialized = false, isOresNoiseInitialized = false, isRunning = false, } ---Definition table for the `MapGen`. --- ---**Only for EmmyLua.** ---@class MapGenDef ---@field nodes table ---@param def MapGenDef ---@return MapGen function MapGen:new(def) local nodesIDs = {} -- Converting node names to IDs for k, v in pairs(def.nodes) do nodesIDs[k] = id(v) end local instance = getInstance(self, {}) instance.nodes = def.nodes instance.nodeIDs = nodesIDs return instance end -- --- API METHODS --- ---Returns a layer by name. If such a layer does not exist, an error will be raised. ---@param layerName string The name of the layer to be retrieved. ---@return MapGen.Layer function MapGen:getLayerByName(layerName) local layer = self.layersByName[layerName] assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName)) return layer end ---Determines which layer a node belongs to based on its height coordinate. ---@param y integer ---@return MapGen.Layer? function MapGen:getLayerByHeight(y) --- TODO: возможно здесь получится сделать более оптимизированный алгоритм --- Можно подумать над тем, чтобы использовать сортированный список ---@param layer MapGen.Layer for _, layer in ipairs(self.layersList) do if y >= layer.minY and y <= layer.maxY then return layer end end end ---Determines which statics layer a node belongs to based on its height coordinate. ---@param y integer ---@return MapGen.StaticLayer? function MapGen:getStaticByHeight(y) --- TODO: возможно здесь получится сделать более оптимизированный алгоритм --- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated --- и может быть даже не один раз --- Можно подумать над тем, чтобы использовать сортированный список ---@param static MapGen.StaticLayer for _, static in ipairs(self.staticsList) do if y >= static.minY and y <= static.maxY then return static end end 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 pos MapVector Coordinate of the desired peak. ---@return MapGen.Peak? function MapGen:getPeakByPos(layer, pos) if type(layer) == 'string' then local layerName = layer layer = self:getLayerByName(layerName) end return layer:getPeakByPos(pos) 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. ---@param point MapVector Point position. ---@return boolean, number? function MapGen:pointInRegion2D(layer, regionName, point) local region = layer.regionsByName[regionName] assert(region ~= nil, ('There is no region named `%s` registered.'):format(regionName)) return region:pointInRegion(point) end ---Returns `true` if there is a cavern at the specified coordinates. ---@param layer MapGen.Layer ---@param x integer ---@param y integer ---@param z integer ---@return boolean function MapGen:isCavern(layer, x, y, z) for _, cavern in ipairs(layer.cavernsList) do if cavern.isRegional then local inRegion, distance = self:pointInRegion2D(layer, cavern.name, v(x, y, z) --[[@as MapVector]]) if inRegion and distance ~= nil then if cavern:isCavern(x, y, z, distance) then return true end end else if cavern:isLayeredCavern(x, y, z) then return true end end end return false end ---@param name string ---@return MapGen.Tree function MapGen:getTree(name) assert(self.treesByName[name] ~= nil, ('There is no tree named `%s` registered.'):format(name)) return self.treesByName[name] end -- --- API METHODS: REGISTRATION --- ---Mark the world area between two heights as a `MapGen.Layer`. --- ---Note: layers must not overlap. ---@param name string The name that will be assigned to the layer. The name must be unique for each layer. ---@param def MapGen.LayerDef Layer description table, see details `MapGen.LayerDef`. function MapGen:registerLayer(name, def) -- Layers with the same name cannot exist. assert(self.layersByName[name] == nil, ('A layer named `%s` is already registered.'):format(name)) -- Layers cannot overlap. assert(self:getLayerByHeight(def.minY) == nil and self:getLayerByHeight(def.maxY) == nil, 'Registered layers must not overlap!') ---@type MapGen.Layer local layer = Layer:new(name, def) self.layersByName[name] = layer tableInsert(self.layersList, layer) pastNoiseValues[name] = {} -- Sort layers by maxY descending for processing priority. tableSort(self.layersList, function(a, b) return a.maxY > b.maxY end) end ---Register the color and the noise parameters that correspond to it. ---@param layerName string The name of the layer for which the color will be registered. ---@param category MapGen.Layer.Category Category indicating what will be generated by noise. ---@param color ColorString Noise color. Must be unique. ---@param noiseParams NoiseParams Fractal noise parameters. function MapGen:registerLayerNoiseColor(layerName, category, color, noiseParams) local layer = self:getLayerByName(layerName) layer:addNoiseParamsColor(category, color, noiseParams) end ---Mark the world area between two heights as a `MapGen.StaticLayer`. --- ---Note: layers must not overlap. ---@param name string The name that will be assigned to the static layer. The name must be unique for each layer. ---@param def MapGen.StaticLayerDef Static layer description table, see details `MapGen.StaticLayerDef`. function MapGen:registerStaticLayer(name, def) -- Static layer with the same name cannot exist. assert(self.staticsByName[name] == nil, ('A static layer named `%s` is already registered.'):format(name)) -- Static layers cannot overlap. assert(self:getStaticByHeight(def.minY) == nil and self:getLayerByHeight(def.maxY) == nil, 'Registered static layers must not overlap!') ---@type MapGen.StaticLayer local static = StaticLayer:new(name, def) self.staticsByName[name] = static tableInsert(self.staticsList, static) -- Sort srtatics by maxY descending for processing priority. tableSort(self.staticsList, function(a, b) return a.maxY > b.maxY end) end ---Mark a point on the biomes diagram and constrain the world area by height to mark it as `MapGen.Biome`. ---@param layerName string The name of the layer in which the new biome will be included. ---@param biomeName string The name to be assigned to the biome. The name must be unique for each biome. ---@param def MapGen.BiomeDef Biome description table, see details `MapGen.BiomeDef` function MapGen:registerBiome(layerName, biomeName, def) local layer = self:getLayerByName(layerName) local biome = Biome:new(biomeName, def) layer:addBiome(biomeName, biome) end ---Mark the world area between two heights as a `MapGen.Cavern` and assign the noise that the cave will be generated from. ---@param layerName string The name of the layer in which the new cavern will be included. ---@param cavernName string The name to be assigned to the cavern. The name must be unique for each cavern. ---@param def MapGen.CavernDef Cavern description table, see details `MapGen.CavernDef` ---@param regionVertices MapVector[]? The region to which the cave generation will be limited. function MapGen:registerCavern(layerName, cavernName, def, regionVertices) local layer = self:getLayerByName(layerName) if regionVertices ~= nil then self:registerRegion(layerName, cavernName, { vertices = regionVertices }) def.isRegional = true end local cavern = Cavern:new(cavernName, def) layer:addCavern(cavernName, cavern) end ---Mark the world region between the vertices as `MapGen.Region` and give it a name. ---@param layerName string The name of the layer in which the new region will be included. ---@param regionName string The name to be assigned to the region. The name must be unique for each region. ---@param def MapGen.RegionDef Region description table, see details `MapGen.RegionDef` function MapGen:registerRegion(layerName, regionName, def) if regionName == 'landscape_boundary' or regionName == 'temp_boundary' or regionName == 'humidity_boundary' then error(('The name `%s` is reserved for special regions and cannot be used.'):format(regionName)) end local layer = self:getLayerByName(layerName) local region = Region:new(regionName, def) layer:addRegion(regionName, region) end ---@param name string ---@param def MapGen.TreeDef function MapGen:registerTree(name, def) assert(self.treesByName[name] == nil, ('A tree named `%s` is already registered.'):format(name)) local tree = Tree:new(name, def) self.treesByName[name] = tree end ---@param layerName string ---@param name string ---@param def MapGen.OreDef function MapGen:registerOre(layerName, name, def) local layer = self:getLayerByName(layerName) local ore = Ore:new(name, def) layer:addOre(name, ore) end -- --- HELPER METHODS --- ---Checks if a point is inside a triangle using the vector product method. --- ---If the point is inside the triangle, it will return the triangle itself; ---if it is outside, its neighbor in the direction of the point will be returned. --- ---**Note**: works only with coordinates X-Z. ---@param triangle MapGen.Triangle ---@param pointPos IntegerVector ---@return boolean, MapGen.Triangle? function MapGen:isPointInTriangle(triangle, pointPos) local e1, e2, e3 = triangle.e1, triangle.e2, triangle.e3 local y1 = e1.vec:cross(pointPos - e1.p1.pos).y if y1 > 0 then return false, triangle.neighbours[3] end local y2 = e2.vec:cross(pointPos - e2.p1.pos).y if y2 > 0 then return false, triangle.neighbours[1] end local y3 = e3.vec:cross(pointPos - e3.p1.pos).y if y3 > 0 then return false, triangle.neighbours[2] end 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 x integer ---@param z integer ---@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, x, z, triangle) if triangle == nil then 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 error('The number of triangle search iterations'.. 'has significantly exceeded the number of triangles'.. 'in the list. Most likely, the loop has become infinite') end iterationCount = iterationCount - 1 if triangle == nil then return nil end isFound, triangle = self:isPointInTriangle(triangle, v(x, 0, z) --[[@as MapVector]]) end return triangle end ---Creates a unique key for a vertex (using X and Z coordinates). ---@param peak MapGen.Peak ---@return string local function vertexKey(peak) local pos = peak.pos return ('%.6f,%.6f'):format(pos.x, pos.z) end ---Creates a canonical (sorted) key for an edge. ---@param edge MapGen.Edge ---@return string local function edgeKey(edge) local k1 = vertexKey(edge.p1) local k2 = vertexKey(edge.p2) if k1 < k2 then return k1 .. "|" .. k2 else return k2 .. "|" .. k1 end end ---Calculates the outer boundary of a triangulated region. ---Works on the XZ horizontal plane. ---@param triangles MapGen.Triangle[] ---@return table function MapGen:getTriangulateBoundaryVertices(triangles) -- Count how many triangles share each edge local edgeCount = {} ---@type table local edgeData = {} for _, triangle in ipairs(triangles) do local edges = { triangle.e1, triangle.e2, triangle.e3 } for _, edge in ipairs(edges) do local key = edgeKey(edge) edgeCount[key] = (edgeCount[key] or 0) + 1 edgeData[key] = edge end end -- Boundary edges belong to exactly ONE triangle ---@type MapGen.Edge[] local boundaryEdges = {} for key, count in pairs(edgeCount) do if count == 1 then tableInsert(boundaryEdges, edgeData[key]) end end if #boundaryEdges == 0 then return {} end -- Build adjacency list for boundary vertices ---@type table local adjacency = {} ---@type table local vertexData = {} for _, edge in ipairs(boundaryEdges) do local k1 = vertexKey(edge.p1) local k2 = vertexKey(edge.p2) vertexData[k1] = edge.p1 vertexData[k2] = edge.p2 adjacency[k1] = adjacency[k1] or {} adjacency[k2] = adjacency[k2] or {} tableInsert(adjacency[k1], k2) tableInsert(adjacency[k2], k1) end -- Walk along boundary edges to create ordered vertex list ---@type MapVector[] local boundary = {} ---@type table local visited = {} if boundaryEdges[1] == nil then error() end ---@type string? local currentKey = vertexKey(boundaryEdges[1].p1) while currentKey and not visited[currentKey] do visited[currentKey] = true local pos = vertexData[currentKey].pos tableInsert(boundary, { x = pos.x, y = 0, z = pos.z }) -- Move to next unvisited neighbor local nextKey = nil for _, neighborKey in ipairs(adjacency[currentKey] or {}) do if not visited[neighborKey] then nextKey = neighborKey break end end currentKey = nextKey end return boundary end -- --- INITIALIZATION METHODS --- ---Initialize the boundary region for a layer and category. ---@param layer MapGen.Layer function MapGen:initTriangultaionBoundaryRegion(layer) local triangles = layer.trianglesList local regionVertices = self:getTriangulateBoundaryVertices(triangles) local regionName = 'triangles_boundary' local region = Region:new(regionName, {vertices = regionVertices}) layer:addRegion(regionName, region) end ---Initialize border regions for all layers and all categories. function MapGen:initLayersBoundaryRegion() ---@param layer MapGen.Layer for _, layer in ipairs(self.layersList) do self:initTriangultaionBoundaryRegion(layer) end end ---Initialize all layer noises. This should be called after the map object is loaded. function MapGen:initLayersNoises() ---@param layer MapGen.Layer for _, layer in ipairs(self.layersList) do layer:initNoises() end end ---Initialization of the biome diagram using the Voronoi method. function MapGen:initBiomesDiagram() ---@param layer MapGen.Layer for _, layer in ipairs(self.layersList) do layer:initBiomesDiagram() end end ---Initialize caverns's noises. This should be called after the map object is loaded. function MapGen:initCavernsNoise() ---@param layer MapGen.Layer for _, layer in ipairs(self.layersList) do for _, cavern in ipairs(layer.cavernsList) do cavern:initNoise() end end self.isCavernsNoiseInitialized = true end ---Initialize ores's noises. This should be called after the map object is loaded. function MapGen:initOresNoise() ---@param layer MapGen.Layer for _, layer in ipairs(self.layersList) do for _, ore in pairs(layer.oresByName) do ore:initNoise() end end self.isOresNoiseInitialized = true end -- --- GENERATION METHODS --- ---@alias MapGen.nodeType 'AIR'|'WATER'|'CAVERN_AIR'|'TURF'|'SOIL'|'ROCK'|'BOTTOM' ---@alias MapGen.dataPostProcessingData {biome:MapGen.Biome, mapGenerator:MapGen, factors:MapGen.Factors, index:integer, x:integer, y:integer, z:integer, nodeType:MapGen.nodeType} ---@alias MapGen.vmPostProcessingData {biome:MapGen.Biome, mapGenerator:MapGen, factors:MapGen.Factors, x:integer, y:integer, z:integer, nodeType:MapGen.nodeType} ---@type table local dataPostProcessing = {} ---@type table local vmPostProcessing = {} ---@param biome MapGen.Biome ---@param mapGenerator MapGen ---@param factors MapGen.Factors ---@param index integer ---@param x integer ---@param y integer ---@param z integer ---@param nodeType MapGen.nodeType local function addPostProccessing(biome, mapGenerator, factors, index, x, y, z, nodeType) if biome.dataPostProcessing ~= nil then dataPostProcessing[index] = { biome = biome, mapGenerator = mapGenerator, factors = factors, index = index, x = x, y = y, z = z, nodeType = nodeType } end if biome.vmPostProcessing ~= nil then vmPostProcessing[index] = { biome = biome, mapGenerator = mapGenerator, factors = factors, x = x, y = y, z = z, nodeType = nodeType } end end ---The core logic of world generation. Determines which node type (water, rock, soil, air) ---and which biome will be generated at the specified coordinates. ---@param mapGenerator MapGen ---@param layer MapGen.Layer ---@param factors MapGen.Factors ---@param data integer[] ---@param data2 integer[] ---@param index integer ---@param x integer ---@param y integer ---@param z integer local function generateNode(mapGenerator, layer, factors, data, data2, index, x, y, z) local ids = mapGenerator.nodeIDs local waterLevel = layer.waterLevel local height, temp, humidity = factors.height, factors.temp, factors.humidity -- Creating a rougher biome boundary. local scatteringGorizontal = layer.biomesGorizontalScattering or 0 local scatteringVertical = layer.biomesVerticalScattering or 0 local scattTemp = temp local scattHumidity = humidity local scattHeight = y if scatteringGorizontal ~= 0 then scattTemp = scattTemp + mathRandom(scatteringGorizontal * -1, scatteringGorizontal) scattHumidity = scattHumidity + mathRandom(scatteringGorizontal * -1, scatteringGorizontal) end if scatteringVertical ~= 0 then scattHeight = scattHeight + mathRandom(scatteringVertical * -1, scatteringVertical) end scattTemp = mathClamp(scattTemp, layer.minTemp, layer.maxTemp) scattHumidity = mathClamp(scattHumidity, layer.minHumidity, layer.maxHumidity) scattHeight = mathClamp(scattHeight, layer.minY, layer.maxY) scattHeight, scattTemp, scattHumidity = mathRound(scattHeight), mathRound(scattTemp), mathRound(scattHumidity) height, temp, humidity = mathRound(height), mathRound(scattTemp), mathRound(scattHumidity) local diagramPoint = layer.biomesDiagram[height][scattTemp][scattHumidity] -- TODO: разобраться со смещением по вертикали ---@type MapGen.Biome local biome = diagramPoint.biome factors.weight = diagramPoint.weight -- If the block is above surface height and above water level... if y > height and y > waterLevel then -- ... then airspace is generated. biome:generateAir(mapGenerator, factors, data, data2, index, x, y, z) addPostProccessing(biome, mapGenerator, factors, index, x, y, z, 'AIR') -- If the block is above the surface height BUT below the water level... elseif y > height and y <= waterLevel then -- ... then underwater space is generated. biome:generateWater(mapGenerator, factors, data, data2, index, x, y, z) addPostProccessing(biome, mapGenerator, factors, index, x, y, z, 'WATER') -- If the block is below the surface height... elseif y <= height then -- ... and a cavern is generated in the block... if mapGenerator:isCavern(layer, x, y, z) then -- ... then airspace is generated. biome:generateCavernAir(mapGenerator, factors, data, data2, index, x, y, z) addPostProccessing(biome, mapGenerator, factors, index, x, y, z, 'CAVERN_AIR') -- ... or if the surface height is above the water level... elseif height > waterLevel then --- ... and the height of the block is equal to the height of the surface... if y == height then -- ... then turf is generated. biome:generateTurf(mapGenerator, factors, data, data2, index, x, y, z) addPostProccessing(biome, mapGenerator, factors, index, x, y, z, 'TURF') -- ... or if the height of the block falls within the thickness of the soil layer... elseif y > height - biome.soilHeight then -- ... then soil is generated. biome:generateSoil(mapGenerator, factors, data, data2, index, x, y, z) addPostProccessing(biome, mapGenerator, factors, index, x, y, z, 'SOIL') else -- ... else a stone is generated. biome:generateRock(mapGenerator, factors, data, data2, index, x, y, z) addPostProccessing(biome, mapGenerator, factors, index, x, y, z, 'ROCK') end -- ... or if the surface height is below the water level... elseif height <= waterLevel then -- ... and if the height of the block falls within the thickness of the soil layer... if y > height - biome.soilHeight then -- ... then the river/ocean bottom is generated. biome:generateBottom(mapGenerator, factors, data, data2, index, x, y, z) addPostProccessing(biome, mapGenerator, factors, index, x, y, z, 'BOTTOM') else -- ... else a stone is generated. biome:generateRock(mapGenerator, factors, data, data2, index, x, y, z) addPostProccessing(biome, mapGenerator, factors, index, x, y, z, 'ROCK') end end else data[index] = ids.air Logger.warningLog('If you see this error, it means that the map generator does'.. 'not handle all cases of generation on coordinates: %s, %s, %s.', x, y, z) end -- Ore generation -- Biome ores are generated first. -- If no ores are generated, the ores registered in the layer are generated. -- This means that biome ores have priority over layer ores. if not biome:generateOre(factors, data, data2, index, x, y, z) then layer:generateOre(factors, data, data2, index, x, y, z) end 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.Edge ---@param x integer ---@param y integer ---@param z integer ---@return number local function calcWeight(height, x, y, z) local pos1 = v(x, y, z) local pos2 = height.p1.pos local pos3 = height.p2.pos local v = pos3 - pos2 ---@type vector local w = pos1 - pos2 -- Formula: (w * v) / (v * v) -- When * the dot product. local t = w:dot(v) / v:dot(v) local posP = pos2 + v * t return 1 - pos2:distance(posP) / height:length() end ---Returns the weighted values of 2d noise. ---@param category MapGen.Layer.Category ---@param layer MapGen.Layer ---@param triangle MapGen.Triangle ---@param x integer ---@param y integer ---@param z integer ---@return number local function calcNoise2dValue(category, layer, triangle, x, y, z) local triangleColor = triangle.color -- If the triangle is monochromatic (all peaks have the same color and, -- accordingly, the same noise), then there is no point in smoothing out the noise. if triangleColor ~= nil then return layer:getNoiseByColor(category, triangleColor):get_2d({x = x, y = z}) end local peak1 = triangle.p1 local peak2 = triangle.p2 local peak3 = triangle.p3 local noise1 = layer:getNoiseByColor(category, peak1.color) local noise2 = layer:getNoiseByColor(category, peak2.color) local noise3 = layer:getNoiseByColor(category, peak3.color) local noiseValue = 0.0 local totalWeight = 0.0 -- We calculate the noise value using the smoothing formula: -- ( peak1 * weight1 + peak2 * weight2 + peak3 * weight3) / totalWeight, when -- totalWeight = weight1 + weight2 + weight3 local weight = calcWeight(triangle.h1, x, y, z) noiseValue = noiseValue + noise1:get_2d({x = x, y = z}) * weight totalWeight = totalWeight + weight weight = calcWeight(triangle.h2, x, y, z) noiseValue = noiseValue + noise2:get_2d({x = x, y = z}) * weight totalWeight = totalWeight + weight weight = calcWeight(triangle.h3, x, y, z) noiseValue = noiseValue + noise3:get_2d({x = x, y = z}) * weight totalWeight = totalWeight + weight return (noiseValue / totalWeight) 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 layer MapGen.Layer ---@param x integer ---@param y integer ---@param z integer ---@return number?, number?, number? function MapGen:getFactors(layer, x, y, z) local posString = corePosToString({x=x,y=0,z=z}) local factors = pastNoiseValues[layer.name][posString] if factors ~= nil then return factors.height, factors.temp, factors.humidity end -- TODO: это сильно тормозит обычные чанки, но ускоряет те, что находятся за границей if not self:pointInRegion2D(layer, 'triangles_boundary', v(x, y, z) --[[@as MapVector]]) then return end if pastTriangle ~= nil then local triangles = { pastTriangle, pastTriangle.neighbours[1], pastTriangle.neighbours[2], pastTriangle.neighbours[3], } ---@param triangle MapGen.Triangle for _, triangle in ipairs(triangles) do if self:isPointInTriangle(triangle, v(x, 0, z) --[[@as MapVector]]) 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) pastNoiseValues[layer.name][posString] = { height = height, temp = temp, humidity = humidity } return height, temp, humidity end end end local triangle = self:findTriangle(layer, x, z, pastTriangle) if triangle == nil then return end 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) pastTriangle = triangle pastNoiseValues[layer.name][posString] = { height = height, temp = temp, humidity = humidity } return height, temp, humidity end ---Generator handler for specific coordinates. ---@param mapGenerator MapGen ---@param layer MapGen.Layer? ---@param data integer[] ---@param data2 integer[] ---@param index integer ---@param x integer ---@param y integer ---@param z integer local function generatorHandler(mapGenerator, layer, data, data2, index, x, y, z) -- 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, data2, index, x, y, z) return end -- If generation occurs outside the layers, then a void is generated. if layer == nil then data[index] = mapGenerator.nodeIDs.air return end local endGetLayerTime = coreGetUsTime() local startNoiseCalcTime = endGetLayerTime -- If the value of the noise is `nil`, -- then the point does not fall within any of the triangles. 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 end -- We recalculate the climate based on altitude. temp = layer:calcTemp(temp, y) humidity = layer:calcHumidity(humidity, y) ---@type MapGen.Factors local factors = { height = height, temp = temp, humidity = humidity, } generateNode(mapGenerator, layer, factors, data, data2, index, x, y, z) end ---Chunk generation handler. ---@param voxelManip VoxelManip ---@param minPos MapVector ---@param maxPos MapVector ---@param blockseed number function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed) local minPosStr, maxPosStr = corePosToString(minPos), corePosToString(maxPos) local startTime, endTime = 0.0, 0.0 if LOG_PROFILE then mglog('Chunk run:\n'.. 'min_pos: %s\n'.. 'max_pos: %s\n', minPosStr, maxPosStr) startTime = coreGetUsTime() end local eMin, eMax = voxelManip:get_emerged_area() if not self.isLayersNoisesInitialized then self:initLayersNoises() end if not self.isCavernsNoiseInitialized then self:initCavernsNoise() end if not self.isOresNoiseInitialized then self:initOresNoise() end local data, data2 = voxelManip:get_data(), voxelManip:get_param2_data() -- local param2_data = voxelManip:get_param2_data() local area = VoxelArea:new({MinEdge = eMin, MaxEdge = eMax}) -- We obtain a layer for the entire chunk at once for optimization purposes. -- Therefore, if the layer boundaries do not coincide with the chunk boundaries, -- the chunk will be entirely contained within the layer containing its center. local layer = self:getLayerByHeight((minPos.y+maxPos.y)/2) local index -- Initial generation: landscape for z = minPos.z, maxPos.z do for x = minPos.x, maxPos.x do for y = minPos.y, maxPos.y do index = area:index(x, y, z) if data[index] == AIR_ID then generatorHandler(self, layer, data, data2, index, x, y, z) end end end end -- Data post-proccesing generation for _, ppdata in pairs(dataPostProcessing) do if ppdata.biome.dataPostProcessing ~= nil then ppdata.biome:dataPostProcessing(ppdata.mapGenerator, ppdata.factors, data, data2, ppdata.index, ppdata.x, ppdata.y, ppdata.z, ppdata.nodeType, area) end end voxelManip:set_data(data) voxelManip:set_param2_data(data2) -- VoxelManip Post-proccesing generation for _, ppdata in pairs(vmPostProcessing) do if ppdata.biome.vmPostProcessing ~= nil then ppdata.biome:vmPostProcessing(ppdata.mapGenerator, ppdata.factors, voxelManip, ppdata.x, ppdata.y, ppdata.z, ppdata.nodeType, area) end end -- Clear post processing tables dataPostProcessing, vmPostProcessing = {}, {} core.generate_ores(voxelManip, minPos, maxPos) core.generate_decorations(voxelManip, minPos, maxPos) voxelManip:set_lighting({ day = 14, night = 0}) voxelManip:calc_lighting() voxelManip:update_liquids() if PROFILE_CHUNK then endTime = coreGetUsTime() mglog('Chunk end:\n'.. 'min_pos: %s\n'.. 'max_pos: %s\n'.. 'time (sec): %.3f\n'.. '---------------', minPosStr, maxPosStr, (endTime - startTime)/1000000) end end -- --- OTHER --- ---Run world generation through this mapgen object --- ---Note: only one instance of a `MapGen` class can be running. --- ---**FOR MAPGEN ENVIRONMENT ONLY** function MapGen:run() if MapGen.isRunning then error('Only one instance of a `MapGen` class can be running.') end ---@param ... VoxelManip core.register_on_generated(function(...) self:onMapGenerated(...) end) self:initBiomesDiagram() self:initLayersBoundaryRegion() MapGen.isRunning = true core.log('MapGen run') end return MapGen