Update from 22.06.2025: add MapGen mod outline, fix some require() issues

This commit is contained in:
2025-06-22 19:20:06 +07:00
parent 50606c7dfe
commit c0de09d597
45 changed files with 621 additions and 119 deletions

View File

@@ -1,27 +1,92 @@
{ {
"completion": { "completion": {
"enable": true, "enable": true,
"autoRequire": false, "autoRequire": false,
"callSnippet": false, "autoRequireFunction": "require",
"postfix": "@" "autoRequireNamingConvention": "keep",
}, "autoRequireSeparator": ".",
"diagnostics": { "callSnippet": false,
"globals": [ "postfix": "@"
"core", },
"table", "diagnostics": {
"Ensure", "disable": [
"string", "unnecessary-if"
"string_utf8" ],
] "enable": true,
}, "globals": [
"workspace": { "core",
"ignoreSubmodules": true "table",
}, "VoxelArea",
"runtime": { "Ensure",
"version": "Lua5.1", "string",
"requireLikeFunction": [], "string_utf8"
"frameworkVersions": [], ],
"extensions": [], "globalsRegex": [],
"requirePattern": [] "severity": {},
} "enables": [],
"diagnosticInterval": null
},
"signature": {
"detailSignatureHelper": true
},
"hint": {
"enable": true,
"paramHint": true,
"indexHint": true,
"localHint": true,
"overrideHint": true
},
"runtime": {
"version": "LuaJIT",
"requireLikeFunction": [],
"frameworkVersions": [],
"extensions": [],
"requirePattern": [],
"classDefaultCall": {
"functionName": "",
"forceNonColon": false,
"forceReturnSelf": false
}
},
"workspace": {
"ignoreDir": [],
"ignoreGlobs": [],
"library": [],
"workspaceRoots": [],
"preloadFileSize": 0,
"encoding": "utf-8",
"moduleMap": [],
"reindexDuration": 5000,
"enableReindex": false
},
"resource": {
"paths": []
},
"codeLens": {
"enable": true
},
"strict": {
"requirePath": false,
"typeCall": false,
"arrayIndex": true,
"metaOverrideFileDefine": true,
"docBaseConstMatchBaseType": true
},
"semanticTokens": {
"enable": true
},
"references": {
"enable": true,
"fuzzySearch": true,
"shortStringSearch": false
},
"hover": {
"enable": true
},
"documentColor": {
"enable": true
},
"codeAction": {
"insertSpace": false
}
} }

1
README.md Normal file
View File

@@ -0,0 +1 @@
Simple Makes Complex is a Luanti engine-based game focused on the multiplayer gameplay

View File

@@ -3,40 +3,51 @@ local tostring = tostring
Ensure = {} Ensure = {}
--- Validates a function argument's type and throws a descriptive error on mismatch. --- Validates a function argument's type and throws a descriptive error on mismatch.
--- @param arg any The argument value to type-check --- @param arg any The argument value to type-check
--- @param expectedType string Expected Lua type name (e.g., "number", "table", "string") --- @param expectedType string Expected Lua type name (e.g., "number", "table", "string")
--- @param n number Argument position in function call (1-based index) --- @param n number Argument position in function call (1-based index)
--- @param function_name string Name of the parent function for error reporting --- @param functionName string Name of the parent function for error reporting
function Ensure.argType(arg, expectedType, n, function_name) function Ensure.argType(arg, expectedType, n, functionName)
local actualType = type(arg) local actualType = type(arg)
assert(actualType == expectedType, string.format( assert(actualType == expectedType, string.format(
'bad argument #%s to \'%s\' (%s expected, got %s)', 'bad argument #%s to \'%s\' (%s expected, got %s)',
tostring(n), tostring(n),
function_name, functionName,
expectedType, expectedType,
actualType)) actualType))
end end
local ensureArgType = Ensure.argType local ensureArgType = Ensure.argType
--- @param arg string The string to check --- @param arg any The argument value to type-check
--- @param n number Argument position in function call (1-based index) --- @param allowedOptions table Lookup table where keys represent valid options (with true values)
--- @param function_name string Name of the parent function for error reporting --- @param n number Argument position in function call (1-based index)
function Ensure.stringArgNotEmpty(arg, n, function_name) --- @param functionName string Name of the parent function for error reporting
function Ensure.argIsAllowed(arg, allowedOptions , n, functionName)
assert(allowedOptions[arg] == true, string.format(
'bad argument #%s to \'%s\' (the value is not allowed)',
tostring(n),
functionName))
end
--- @param arg string The string to check
--- @param n number Argument position in function call (1-based index)
--- @param functionName string Name of the parent function for error reporting
function Ensure.stringArgNotEmpty(arg, n, functionName)
ensureArgType(arg, 'string', 1, 'Ensure.stringArgNotEmpty') ensureArgType(arg, 'string', 1, 'Ensure.stringArgNotEmpty')
assert(#arg ~= 0, string.format('bad argument #%s to \'%s\' (string cannot be empty)', n, function_name)) assert(#arg ~= 0, string.format('bad argument #%s to \'%s\' (string cannot be empty)', n, functionName))
end end
--- @param arg any The argument value to check --- @param arg any The argument value to check
--- @param n number Argument position in function call (1-based index) --- @param n number Argument position in function call (1-based index)
--- @param function_name string Name of the parent function for error reporting --- @param functionName string Name of the parent function for error reporting
function Ensure.argNotNil(arg, n, function_name) function Ensure.argNotNil(arg, n, functionName)
assert(arg ~= nil, string.format('bad argument #%s to \'%s\' (key cannot be nil)', n, function_name)) assert(arg ~= nil, string.format('bad argument #%s to \'%s\' (key cannot be nil)', n, functionName))
end end
--- @param divider number The number to check --- @param divider number The number to check
--- @param function_name string Name of the parent function for error reporting --- @param functionName string Name of the parent function for error reporting
function Ensure.zeroDivision(divider, function_name) function Ensure.zeroDivision(divider, functionName)
assert(divider ~= 0, string.format('Division by zero in \'%s\'', function_name)) assert(divider ~= 0, string.format('Division by zero in \'%s\'', functionName))
end end

9
mods/API/Math/init.lua Normal file
View File

@@ -0,0 +1,9 @@
local math = math
math.lerp = function (a, b, t)
return a + (b - a) * t
end
math.clamp = function(value, min, max)
return math.min(math.max(value, min), max)
end

1
mods/API/Math/mod.conf Normal file
View File

@@ -0,0 +1 @@
name = api__math

View File

@@ -1,12 +1,18 @@
_G.Mod = {} Mod = {}
function Mod:new(addToGlobal) function Mod.getInfo()
for key, value in pairs(addToGlobal) do local name = core.get_current_modname()
_G[key] = value local path = core.get_modpath(name)
end local require = Require.getModRequire(name, path)
local modName = core.get_current_modname()
local modPath = core.get_modpath(modName) return {name = name, path = path, require = require}
end
local modTable = ModTable:new(modName, modPath)
modTable.require = ModTable:getRequire() function Mod:new()
local mod = Mod.getInfo()
setmetatable(mod, self)
self.__index = self
return mod
end end

View File

@@ -1,2 +1 @@
name = api__mod name = api__mod_table
depends = api__mod_table, api__require,

View File

@@ -1,40 +0,0 @@
ModTable = {}
local modLoggers = {}
local loadedModules = {}
local DS = '/'
function ModTable:getRequire()
return function(fileName)
local modName = self.name
local modPath = self.path
local fullName = modName .. '..' .. fileName
local module = loadedModules[fullName]
if module ~= nil then
return module
end
local result = dofile(modPath .. DS .. 'src' .. DS .. fileName:gsub('%.', DS) .. '.lua')
if result ~= nil then
loadedModules[fullName] = result
else
loadedModules[fullName] = true
end
return loadedModules[fullName]
end
end
function ModTable:new(name, path)
local modTable = {
name = name,
path = path,
}
setmetatable(modTable, self)
self.__index = self
return modTable
end

View File

@@ -1 +0,0 @@
name = api__mod_table

View File

@@ -1,6 +0,0 @@
Path = {}
function Path:new()
return
end

View File

@@ -1 +0,0 @@
name = api__path

View File

@@ -1,11 +1,19 @@
_G.Require = {} Require = {}
local loadedModules = {} local loadedModules = {}
local DS = '/' local DS = '/'
function Require.getModRequire() --- Creates a scoped require function for a specific module
return function(fileName) --- This custom require handles module loading relative to a specific module path,
local modName = self.name --- prevents duplicate loading, and caches results appropriately.
local modPath = self.path --- @param modName string Namespace identifier for the module (prevents global collisions)
--- @param modPath string Absolute base path to the module's directory
--- @return function require Custom require function scoped to the specified module
function Require.getModRequire(modName, modPath)
--- Custom require function for module-specific loading
--- Resolves files relative to modPath/src, converts dot-notation to path separators
--- @param fileName string Module path in dot-notation (e.g. "lib.utils")
--- @return any loadedModule The loaded module's return value or cached result
local function require(fileName)
local fullName = modName .. '..' .. fileName local fullName = modName .. '..' .. fileName
local module = loadedModules[fullName] local module = loadedModules[fullName]
@@ -23,4 +31,6 @@ function Require.getModRequire()
return loadedModules[fullName] return loadedModules[fullName]
end end
return require
end end

View File

@@ -3,7 +3,7 @@ local sub, upper, ensureArgType
--- Writes a string with a capital letter. --- Writes a string with a capital letter.
--- @param str string Input string. --- @param str string Input string.
--- @return string --- @return string?
function string.capitalize(str) function string.capitalize(str)
ensureArgType(str, "string", 1, "string.capitalize") ensureArgType(str, "string", 1, "string.capitalize")

View File

@@ -1,2 +1 @@
name = api__string name = api__string
depends = api__table

View File

@@ -0,0 +1,75 @@
Api = {}
Core = {}
Environment = {}
Game = {}
Game.Items = {}
Game.Mobs = {}
Game.Structures = {}
Ui = {}
local allowedDomains = {
Api = true,
Core = true,
Environment = true,
Game = true,
Ui = true
}
--- Adds a mod to the global space under specified domain structure
---@param mod table The mod table containing functionality to expose -- TODO: !!!Make a Mod class!!!
---@param location string Dot-separated path within domain structure (e.g. "Items.Log")
---@param force boolean? Whether to overwrite the target location.
Api.addModToGlobalSpace = function(mod, location, force)
-- Ensure `mod` type and that it's not empty
Ensure.argType(mod, 'table', 1, 'Api.addModToGlobalSpace')
-- Ensure `location` type and that it's not empty
Ensure.argType(location, 'string', 2, 'Api.addModToGlobalSpace')
Ensure.stringArgNotEmpty(location, 2, 'Api.addModToGlobalSpace')
-- Ensure `location` matches this format: 'field.subfield.subsubfield.<...>'
if not location:match('^[%a_][%w_]*([%.][%a_][%w_]*)*$') then
error('bad argument #2 to \'Api.addModToGlobalSpace\' (invalid format)')
end
-- Split `location` into fields -- TODO: !!!Make a String function!!!
local fields = {}
local domain = nil
for field in string.gmatch(location, '[^.]+') do
if domain ~= nil then
table.insert(fields, field)
else
domain = field
end
end
-- Ensure the domain is allowed
Ensure.argIsAllowed(domain, allowedDomains , 2, 'Api.addModToGlobalSpace')
-- Handle case where we're modifying the domain root directly
if #fields == 0 then
error('Not allowed to directly write into the \''.. domain ..'\' domain')
end
-- Start traversing from the domain's table
local current = _G[domain]
assert(type(current) == 'table', 'The global domain is not a table')
-- Traverse each field of the location
local num_fields = #fields
for i = 1, num_fields - 1 do
local field = fields[i]
if current[field] == nil then
current[field] = {}
end
current = current[field]
assert(type(current) == 'table', 'intermediate field is not a table')
end
-- Assign mod to the final field
local last_field = fields[num_fields]
if force and current[last_field] ~= nil then
error(string.format('field \'%s\' already exists in \'%s\'', last_field, location))
end
current[last_field] = mod
end

View File

@@ -1,2 +1,3 @@
name = api__system name = api__system
depends = api__mod, api__string, description = Include this mod in your `depends` to ensure all necessary APIs are loaded for your mod
depends = api__ensure, api__math, api__mod, api__require, api__table, api__string, api__utf8,

View File

@@ -22,7 +22,7 @@ end
--- Returns all keys from the table `t` as an array. --- Returns all keys from the table `t` as an array.
--- @param t table<string, any> Table to check --- @param t table<string, any> Table to check
--- @return any[] --- @return string[] | number[]
function table.get_keys(t) function table.get_keys(t)
ensureArgType(t, 'table', 1, 'table.get_keys') ensureArgType(t, 'table', 1, 'table.get_keys')

View File

@@ -1 +0,0 @@
name = core__dynamic_recipe

View File

@@ -0,0 +1 @@
name = core__entity_modular

View File

@@ -0,0 +1,5 @@
local Item = Mod:new()
Item.Class = Item.require('Item')
Api.addModToGlobalSpace(Item, 'Core.Item')

View File

@@ -1 +1,2 @@
name = core__item name = core__item
depends = api__system

View File

@@ -0,0 +1,41 @@
local Item = {}
--- @class ItemDefinition
--- @field settings table
local ItemDefinition = {
settings = {
name = '',
title = '',
description = '',
visual = '', -- '3d' | 'flat'
},
callbacks = {
...
},
}
--- @param itemDef ItemDefinition
local function itemDefToLuantiDef(itemDef)
local s = itemDef.settings
local c = itemDef.callbacks
local luantiDef = table.copy(c)
return luantiDef
end
local function register3dItem(luantiDef)
local ld = luantiDef
core.register_node(ld.name, {
description = ld.description
})
end
local function registerFlatItem(luantiDef)
end
function Item:new(itemDef)
local item = {}
end

View File

@@ -1 +0,0 @@
name = core__modular_entity

View File

@@ -1 +0,0 @@
name = core__modular_structure

View File

@@ -1 +1,2 @@
name = core__node name = core__node
depends = core__item

View File

@@ -1 +1,2 @@
name = core__node_factory name = core__node_factory
depends = core__item_factory

View File

@@ -0,0 +1 @@
name = core__recipe_dynamic

View File

@@ -0,0 +1 @@
name = core__recipe_static

View File

@@ -1 +0,0 @@
name = core__static_recipe

View File

@@ -0,0 +1 @@
name = core__structure_modular

View File

@@ -1 +0,0 @@
name = smc__enviroment

View File

@@ -0,0 +1,5 @@
local MapGen = Mod:new()
MapGen.Class = MapGen.require('MapGen')
Api.addModToGlobalSpace(MapGen, 'Core.MapGen')

View File

@@ -1 +1,2 @@
name = core__map_gen name = core__map_gen
depends = api__system

View File

@@ -0,0 +1,22 @@
local table, setmetatable = table, setmetatable
local Layer = {}
Layer.__index = Layer
function Layer:new(name, minY, maxY)
return setmetatable({
name = name,
minY = minY,
maxY = maxY,
regions2D = {},
regions3D = {}
}, self)
end
function Layer:add2DRegion(region)
table.insert(self.regions2D, region)
end
function Layer:add3DRegion(region)
table.insert(self.regions3D, region)
end

View File

@@ -0,0 +1,223 @@
local modInfo = Mod.getInfo()
local require = modInfo.require
local MapGenUtils = require("MapGenUtils")
local Layer = require("Layer")
local Region2D = require("Region2D")
local Region3D = require("Region3D")
local core, table, math = core, table, math
local pairs, ipairs = pairs, ipairs
-- Main MapGenerator class
local MapGenerator = {}
MapGenerator.__index = MapGenerator
function MapGenerator:new()
return setmetatable({
layersByName = {},
layersList = {},
registeredRegions = {},
materials = {
impassableWater = core.get_content_id("impassable_water:water"),
impassableSeabed = core.get_content_id("impassable_water:seabed"),
air = core.get_content_id("air")
}
}, self)
end
function MapGenerator:registerLayer(name, minY, maxY)
local layer = Layer:new(name, minY, maxY)
self.layersByName[name] = layer
table.insert(self.layersList, layer)
return layer
end
function MapGenerator:register2DRegion(params)
local region = Region2D:new(params)
local layer = self.layersByName[params.layerName]
if not layer then error("Invalid layer: " .. params.layerName) end
layer:add2DRegion(region)
end
function MapGenerator:register3DRegion(params)
local region = Region3D:new(params)
local layer = self.layersByName[params.layerName]
if not layer then error("Invalid layer: " .. params.layerName) end
layer:add3DRegion(region)
end
function MapGenerator:enable()
core.register_on_generated(function(...)
self:onMapGenerated(...)
end)
end
-- Main generation logic
function MapGenerator:onMapGenerated(minp, maxp, seed)
local vm, emin, emax = core.get_mapgen_object("voxelmanip")
local area = VoxelArea:new{MinEdge=emin, MaxEdge=emax}
local data = vm:get_data()
-- Sort layers by maxY descending for processing priority
table.sort(self.layersList, function(a, b)
return a.maxY > b.maxY
end)
local terrainCache = self:process2DRegions(minp, maxp)
self:process3DRegions(minp, maxp, data, area, terrainCache)
vm:set_data(data)
vm:calc_lighting()
vm:write_to_map()
end
function MapGenerator:process2DRegions(minp, maxp)
local cache = {}
local width = maxp.x - minp.x + 1
local zSize = maxp.z - minp.z + 1
-- Precompute noise for all 2D regions
local regionNoiseCache = {}
for _, layer in ipairs(self.layersList) do
for _, region in ipairs(layer.regions2D) do
local noiseCache = {
height = {},
temp = {},
humid = {},
}
for x = minp.x, maxp.x do
noiseCache.temp[x] = {}
noiseCache.humid[x] = {}
noiseCache.height[x] = {}
for z = minp.z, maxp.z do
noiseCache.temp[x][z] = region.noiseTemp:get2d({x=x, y=z})
noiseCache.humid[x][z] = region.noiseHumid:get2d({x=x, y=z})
noiseCache.height[x][z] = region.noiseHeight:get2d({x=x, y=z})
end
end
regionNoiseCache[region] = noiseCache
end
end
for x = minp.x, maxp.x do
cache[x] = {}
for z = minp.z, maxp.z do
cache[x][z] = {}
for _, layer in ipairs(self.layersList) do
local bestHeight, bestWeight = nil, 0.0
for _, region in ipairs(layer.regions2D) do
local noiseCache = regionNoiseCache[region]
local temp = noiseCache.temp[x][z]
local humid = noiseCache.humid[x][z]
if MapGenUtils.isInRange(temp, region.tempRange) and MapGenUtils.isInRange(humid, region.humidRange) then
local tempWeight = MapGenUtils.calculateWeight(temp, region.tempRange.min, region.tempRange.max)
local heightWeight = MapGenUtils.calculateWeight(humid, region.humidRange.min, region.humidRange.max)
local weight = tempWeight * heightWeight
if weight > bestWeight then
local heightNoise = noiseCache.height[x][z]
bestHeight = math.lerp(
region.heightRange.min,
region.heightRange.max,
heightNoise
)
bestWeight = weight
end
end
end
if bestHeight then
cache[x][z][layer] = math.floor(math.clamp(bestHeight, layer.minY, layer.maxY))
end
end
end
end
return cache
end
function MapGenerator:process3DRegions(minp, maxp, data, area, terrainCache)
-- Precompute 3D noise for regions
local region3DNoise = {}
for _, layer in ipairs(self.layersList) do
for _, region in ipairs(layer.regions3D) do
region3DNoise[region] = {
temp = {},
humid = {},
cave = {}
}
for y = minp.y, maxp.y do
region3DNoise[region].temp[y] = {}
region3DNoise[region].humid[y] = {}
region3DNoise[region].cave[y] = {}
for x = minp.x, maxp.x do
region3DNoise[region].temp[y][x] = {}
region3DNoise[region].humid[y][x] = {}
region3DNoise[region].cave[y][x] = {}
for z = minp.z, maxp.z do
region3DNoise[region].temp[y][x][z] = region.noiseTemp:get3d({x=x, y=y, z=z})
region3DNoise[region].humid[y][x][z] = region.noiseHumid:get3d({x=x, y=y, z=z})
region3DNoise[region].cave[y][x][z] = region.noiseCave:get3d({x=x, y=y, z=z})
end
end
end
end
end
for x = minp.x, maxp.x do
for z = minp.z, maxp.z do
local columnCache = terrainCache[x][z]
local baseIndex = area:index(x, minp.y, z)
local yStride = area.ystride
for y = minp.y, maxp.y do
local idx = baseIndex + (y - minp.y) * yStride
local processed = false
for _, layer in ipairs(self.layersList) do
if y >= layer.minY and y <= layer.maxY then
local surfaceY = columnCache[layer]
if not surfaceY then
data[idx] = y == layer.minY and
self.materials.impassableSeabed or
self.materials.impassableWater
else
-- Set default based on position relative to surface
local default = (y <= surfaceY) and
self.materials.impassableSeabed or
self.materials.air
data[idx] = default
-- Apply 3D regions (caves/structures)
for _, region in ipairs(layer.regions3D) do
local temp = region3DNoise[region].temp[y][x][z]
local humid = region3DNoise[region].humid[y][x][z]
local cave = region3DNoise[region].cave[y][x][z]
if MapGenUtils.isInRange(temp, region.tempRange) and
MapGenUtils.isInRange(humid, region.humidRange) and cave > region.caveThreshold then
data[idx] = self.materials.air
break -- Only first matching region applies
end
end
end
processed = true
break -- Only process one layer per Y position
end
end
if not processed then
data[idx] = self.materials.air
end
end
end
end
end
return MapGenerator

View File

@@ -0,0 +1,20 @@
local math = math
-- Utility class with static methods
local MapGenUtils = {
calculateWeight = function(value, min, max)
local center = (min + max) / 2
local span = (max - min) / 2
return 1 - math.abs((value - center) / span)
end,
---@return boolean
isInRange = function(value, range)
if value >= range.min and value <= range.max then
return true
end
return false
end
}
return MapGenUtils

View File

@@ -0,0 +1,15 @@
local Region = {}
Region.__index = Region
local pairs, setmetatable = pairs, setmetatable
function Region:new(params)
local instance = setmetatable({}, self)
for k, v in pairs(params) do
instance[k] = v
end
instance:initNoises()
return instance
end
return Region

View File

@@ -0,0 +1,19 @@
local modInfo = Mod.getInfo()
local Region = modInfo.require()("Region")
local core, setmetatable = core, setmetatable
-- 2D Region implementation
local Region2D = setmetatable({}, {__index = Region})
function Region2D:new(params)
local instance = Region.new(self, params)
instance.type = "2d"
return setmetatable(instance, {__index = Region2D})
end
function Region2D:initNoises()
self.noiseHeight = core.get_value_noise(self.noiseParamsHeight)
self.noiseTemp = core.get_value_noise(self.noiseParamsTemp)
self.noiseHumid = core.get_value_noise(self.noiseParamsHumid)
end

View File

@@ -0,0 +1,19 @@
local modInfo = Mod.getInfo()
local Region = modInfo.require()("Region")
local core, setmetatable = core, setmetatable
-- 3D Region implementation
local Region3D = setmetatable({}, {__index = Region})
function Region3D:new(params)
local instance = Region.new(self, params)
instance.type = "3d"
return setmetatable(instance, {__index = Region3D})
end
function Region3D:initNoises()
self.noiseCave = core.get_value_noise(self.noiseParamsCave)
self.noiseTemp = core.get_value_noise(self.noiseParamsTemp)
self.noiseHumid = core.get_value_noise(self.noiseParamsHumid)
end

View File

@@ -0,0 +1 @@
name = smc__environment