70 Commits

Author SHA1 Message Date
8fb3235937 Added TODO: for gzip decompressing 2026-01-11 11:42:08 +03:00
83e22f192b Rewrote ff2luat func for using string:sub (not file:read) 2026-01-11 11:42:08 +03:00
52630eb85a Add test map image parsing 2026-01-10 12:04:25 +03:00
Van
7658d74387 Merge pull request #2 from ssdaniel24/mapgen-img-fix
Fixed uintb2num func for normal conversion...
2026-01-09 21:08:49 +03:00
4c143b2055 Fixed uintb2num func for normal conversion... 2026-01-09 21:02:52 +03:00
Van
54184fc32a Merge pull request #1 from ssdaniel24/mapgen-img-fix
Fixed unsigned int bytes to number conversion
2026-01-09 19:19:16 +03:00
108c0c8817 Fixed unsigned int bytes to number conversion 2026-01-09 19:14:52 +03:00
a97d806f6b Mapgen: add peaks register from image 2026-01-09 18:44:26 +03:00
395f45aeb9 Add stone generate on suraface 2026-01-08 12:41:47 +03:00
d9aa50fc91 Add draft /list command 2026-01-07 14:26:21 +03:00
876b24e1fe Formspec: add item image button 2026-01-07 14:26:01 +03:00
37ad60d348 Formspec: add scrollbar and minor fixes 2026-01-07 13:45:13 +03:00
bc50096293 Formspec: add scrollContainer 2026-01-07 12:53:27 +03:00
1c5038ff14 ItemFactory: change params for registerNodesByShortDef: remove titile & description params 2026-01-06 14:12:15 +03:00
562ff7d24c Submodules: update ide-helper 2026-01-06 13:23:33 +03:00
a08934c6e4 Item: add param addModName 2026-01-05 15:44:53 +03:00
6236a12ca9 Item: add titleColor & descriptionColor params 2026-01-05 15:18:12 +03:00
f7ec69bd54 minor fix 2026-01-05 15:15:42 +03:00
bf107cb167 Rename GlobalStep.lua -> globalStep.lua 2026-01-05 15:06:05 +03:00
cb49582a19 Api globalStep minor changes 2026-01-05 14:57:09 +03:00
cf4ca6f8dc Add test locale 2026-01-02 23:03:54 +03:00
2032082ba8 Added auto-completion of items title and description for localization 2026-01-02 22:31:32 +03:00
9557642805 MapGen: fix light 2026-01-02 21:36:53 +03:00
6db2e9f77a Autocomplete mod name prefix for items 2026-01-02 21:32:54 +03:00
275f54c7b7 Create empty adminCommands mod 2025-12-30 19:11:48 +03:00
47dc024b6c Create draft biome 2025-12-30 19:11:32 +03:00
efeb5c75cd Add draft plants 2025-12-30 19:10:46 +03:00
c0575e2c82 Tilesheet: minor fix 2025-12-30 19:10:04 +03:00
4e823bfee6 Math: add annotation to function 2025-12-30 18:13:11 +03:00
44ba5c7cfa Rename some mods 2025-12-30 17:53:26 +03:00
475b199ddb Create Plant class 2025-12-29 19:51:28 +03:00
96b51caaaf Fix game start 2025-12-29 19:12:48 +03:00
514e676e9a minor fix 2025-12-29 19:03:51 +03:00
7773e25a81 Callbacks -> Events. Fihish Control 2025-12-29 18:51:22 +03:00
96289375b1 CallbacksControl: add base logic 2025-12-29 15:29:44 +03:00
40c1d34124 ApiLoader: add GlobalStep.lua 2025-12-29 14:51:15 +03:00
2655127a22 ApiLoader: delete comment code 2025-12-29 14:00:55 +03:00
b1c3e50445 Add Callbacks API 2025-12-29 12:53:30 +03:00
9c919343cf Transfer Formspec mod from UI to CORE 2025-12-28 20:28:57 +03:00
13391b085e Delete Enum & VisualEnum classes 2025-12-28 20:27:16 +03:00
27004ebf45 Minor changes 2025-12-28 20:10:08 +03:00
7b951b64ac Formspec: create our api. Part 2 2025-12-28 15:02:29 +03:00
c57a7ceadd Formspec: create our api. Part 1 2025-12-26 20:28:04 +03:00
95084d5daf Formspec: create mod and basic class 2025-12-25 22:23:14 +03:00
3e9996e6a0 bump changes 25.12 2025-12-25 14:31:11 +03:00
3646ec78cd Update README.md and add last_title.png 2025-12-19 21:56:33 +03:00
cf141f9797 Update README.md 2025-12-19 21:54:24 +03:00
475b5fab0c Update heared_scale.png 2025-12-19 21:53:28 +03:00
6f742e7291 Update README.md & add heared_scale.png 2025-12-19 21:52:45 +03:00
b5994d7383 Update README.md 2025-12-19 21:51:28 +03:00
c5a71d5bdc Update icons & title 2025-12-19 21:49:21 +03:00
1ac87b464a CraftSystem: create base system 2025-12-16 21:49:54 +03:00
5b22c900d5 Create CraftSystem mod 2025-12-14 14:38:27 +03:00
0b749564af MapGen: move waterLevel MapGenDef -> LayerDef 2025-12-11 19:19:53 +03:00
a699367bf4 bruh commit 2025-12-11 19:08:49 +03:00
720b7edcdb Create Player class and Player.HUD, Player.GUI 2025-12-08 21:28:30 +03:00
bbd5c781e4 Create Sound class 2025-12-08 21:25:46 +03:00
0870ce37e9 Rename mod Log -> Wood, add base logs 2025-12-08 20:37:55 +03:00
a5c8846130 MapGen: fix biome scattering 2025-12-03 21:23:35 +03:00
745fdb8dd3 MapGen: add StaticLayer 2025-12-02 22:06:41 +03:00
a0a1db6179 MapGen & MapGenerator: update mod.confs 2025-12-01 19:16:24 +03:00
1d576dcaf5 Update README.md 2025-12-01 19:11:34 +03:00
414d5008d3 Update menu & README.md 2025-12-01 19:04:18 +03:00
7908f5fc9f Update game.conf 2025-12-01 18:45:50 +03:00
af87c2912c MapGen: updagrade biomes scattering 2025-12-01 18:36:09 +03:00
e44420d0ab Remove GlobalSpace, domains and extends methods in Mod 2025-12-01 17:08:56 +03:00
ace217832b Write Class lib 2025-12-01 17:07:44 +03:00
f9eccced09 Mapgen: write SuperUltraSigmaMapgen part 9 (FINAL) 2025-11-28 20:23:51 +03:00
d07b7c811f Mapgen: write SuperUltraSigmaMapgen part 8.3 2025-11-27 22:31:33 +03:00
f556e4349e Update README.md 2025-11-27 20:30:55 +03:00
98 changed files with 2414 additions and 645 deletions

View File

@@ -25,6 +25,7 @@
"globals": [ "globals": [
"core", "core",
"table", "table",
"Events",
"VoxelArea", "VoxelArea",
"VoxelManip", "VoxelManip",
"vector", "vector",

View File

@@ -1,3 +1,12 @@
Simple Makes Complex is a Luanti engine-based game focused on the multiplayer gameplay ![image](/menu/header_scale.png)
![image](/menu/icon.png) # Simple Makes Complex
Simple Makes Complex is a Luanti engine-based game focused on the multiplayer gameplay.
# Licensing
- The project's core code is licensed under [MIT](/LICENSE).
- Submodules may contain their own license.
- Media assets are used and distributed under [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/).
# Assets used
- Font used in the `/menu/last_header.png`: https://fontstruct.com/fontstructions/show/2722233/gbjve (danil_2461, [CC0](http://creativecommons.org/publicdomain/zero/1.0/))

View File

@@ -1 +1,4 @@
title = SMC title = SMC
allowed_mapgens = singlenode
default_mapgen = singlenode

BIN
menu/background.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

BIN
menu/header.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

BIN
menu/header_scale.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 770 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
menu/last_header.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

View File

@@ -1,91 +1,4 @@
Api = {} local modInfo = Mod.getInfo('smc__api__api_loader')
local require = modInfo.require
---@alias Domain table<string,Mod|SubDomain> Global table for accessing public classes provided by mods. require('Api')
---@alias SubDomain table<string,Mod>
---@type Domain
Core = {}
---@type Domain
Environment = {}
---@type Domain
Game = {}
---@type SubDomain
Game.Items = {}
---@type SubDomain
Game.Mobs = {}
---@type SubDomain
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 Mod The mod table containing functionality to expose
---@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.<...>'
-- TODO: баг: ликвидные имена не определяются шаблоном
--[[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,3 +1,3 @@
name = smc__api__api_loader name = smc__api__api_loader
description = Include this mod in your `depends` to ensure all necessary APIs are loaded for your mod description = Include this mod in your `depends` to ensure all necessary APIs are loaded for your mod
depends = smc__api__ensure, smc__api__math, smc__api__mod, smc__api__require, smc__api__table, smc__api__string, smc__api__utf8, depends = smc__api__ensure, smc__api__math, smc__api__mod, smc__api__require, smc__api__table, smc__api__string, smc__api__utf8, smc__api__class

View File

@@ -0,0 +1,7 @@
Api = {}
local modInfo = Mod.getInfo('smc__api__api_loader')
local require = modInfo.require
require('Api.ff2lua')
require('Api.globalStep')

View File

@@ -0,0 +1,99 @@
-- A method for converting an image with colored dots (pixels) into a Lua table grouped by color.
-- Author: @ssdaniel24 (github)
---Table with color as key and value is table with coordinates of dots. Note: coords begin from 1,1 (not 0,0).
---Example of table:
---```lua
---{
--- 'size': { h=256, w=256 },
--- '#fff': { {x=1,y=1}, {x=2,y=2}, ... },
--- '#ff0': { {x=3,y=3}, {x=4,y=4}, ... },
--- ...
---}
---```
---@alias ColoredDotsTable table<string,table>
---@param uintb string unsigned int bytes
---@return number
local function uintb2num(uintb)
local num = 0
local len = string.len(uintb)
for i = 1,len do
num = num*256 + string.byte(uintb, i)
end
return num
end
---Converts (scaling) 16-bit unsigned integer to 8-bit unsigned integer.
---Why? Because hex codes of colors are 8-bit: #ffffff -> ff = 256 (8 bit). Not 65536 (16 bit).
---@param num number 16-bit number
---@return number 8-bit number
local function uint16ToUint8(num)
return math.floor(num / 256)
end
---Converts given farbfeld image to ColoredDotsTable.
---Farbfeld format:
---```
---╔════════╤═════════════════════════════════════════════════════════╗
---║ Bytes │ Description ║
---╠════════╪═════════════════════════════════════════════════════════╣
---║ 8 │ 'farbfeld' magic value ║
---╟────────┼─────────────────────────────────────────────────────────╢
---║ 4 │ 32-Bit BE unsigned integer (width) ║
---╟────────┼─────────────────────────────────────────────────────────╢
---║ 4 │ 32-Bit BE unsigned integer (height) ║
---╟────────┼─────────────────────────────────────────────────────────╢
---║ [2222] │ 4x16-Bit BE unsigned integers [RGBA] / pixel, row-major ║
---╚════════╧═════════════════════════════════════════════════════════╝
---```
---[tools/farbfeld | suckless.org software that sucks less](https://tools.suckless.org/farbfeld/)
---@param filepath string image in farbfeld format
---@param backgroundColor string? ColorString, will be ignored while processing image. Default: `#000000FF`
---@return ColoredDotsTable
function Api.ff2luat(filepath, backgroundColor)
local file = io.open(filepath, 'rb')
if not file then error('Can\'t open farbfeld image: ' .. dump(filepath)) end
local ff = file:read('*a') -- binary!
file:close()
-- TODO: make it decompressing gzip format -> https://en.wikipedia.org/wiki/Gzip
-- I should skip 10 bytes in a beginning, read how many extra fields after it, skip them too, and skip last 8 bytes
-- (read wiki for information).
-- if filepath:sub(-3) == '.gz' then ff = core.decompress(ff, 'deflate') end
if not ff:sub(1,8) == 'farbfeld' then error('Not farbfeld image: ' .. dump(filepath)) end
if not backgroundColor then backgroundColor = '#000000FF' end
--HACK: normalizing colorstring for future string comparison ('#000' -> '#000000FF')
backgroundColor = core.colorspec_to_colorstring(core.colorspec_to_table(backgroundColor))
---@type ColoredDotsTable
local dots = { size = { w = uintb2num(ff:sub(9,12)), h = uintb2num(ff:sub(13,16)) } }
local cursor
for i = 1,dots.size.h do
for j = 1,dots.size.w do
cursor = 16 + ((i-1)*dots.size.w + j-1)*8 + 1
local colorT = {
r = uint16ToUint8(uintb2num(ff:sub(cursor, cursor+1))),
g = uint16ToUint8(uintb2num(ff:sub(cursor+2,cursor+3))),
b = uint16ToUint8(uintb2num(ff:sub(cursor+4,cursor+5))),
a = uint16ToUint8(uintb2num(ff:sub(cursor+6,cursor+7)))
}
---@type string @ColorString
local color = core.colorspec_to_colorstring(colorT)
if color ~= backgroundColor then
if not dots[color] then
dots[color] = {}
end
table.insert(dots[color], { x=j, y=i })
end
end
end
return dots
end

View File

@@ -0,0 +1,75 @@
---@type {timeDelay:number, callbackFunc:fun(deltaTime:number), timer:number, lastCall:number}[]
local callsWithDelay = {}
---@param timeDelay number
---@param callbackFunc fun(deltaTime:number)
function Api.registerGlobalStepWithDelay(timeDelay, callbackFunc)
table.insert(callsWithDelay, {
timeDelay = timeDelay,
callbackFunc = callbackFunc,
timer = 0.0,
lastCall = 0.0
})
end
core.register_globalstep(function(deltaTime)
---@type number
local timer
local lastCall
for _, callback in ipairs(callsWithDelay) do
timer = callback.timer
lastCall = callback.lastCall
timer = timer + deltaTime
lastCall = lastCall + deltaTime
if timer >= callback.timeDelay then
callback.callbackFunc(lastCall)
callback.timer = timer - callback.timeDelay
callback.lastCall = 0.0
else
callback.timer = timer
callback.lastCall = lastCall
end
end
end)
---@type {timeDelay:number, callbackFunc:fun(deltaTime:number, player), timer:number, lastCall:number}[]
local callsForEachPlayer = {}
---@param timeDelay number
---@param callbackFunc fun(deltaTime:number, player:Player)
function Api.registerGlobalStepForEachPlayer(timeDelay, callbackFunc)
table.insert(callsWithDelay, {
timeDelay = timeDelay,
callbackFunc = callbackFunc,
timer = 0.0,
lastCall = 0.0,
})
end
core.register_globalstep(function(deltaTime)
---@type number
local timer
local lastCall
for _, player in ipairs(core.get_connected_players()) do
for _, callback in ipairs(callsForEachPlayer) do
timer = callback.timer
lastCall = callback.lastCall
timer = timer + deltaTime
lastCall = lastCall + deltaTime
if timer >= callback.timeDelay then
callback.callbackFunc(lastCall, player)
callback.timer = timer - callback.timeDelay
callback.lastCall = 0.0
else
callback.timer = timer
callback.lastCall = lastCall
end
end
end
end)

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

@@ -0,0 +1,9 @@
---@class Class
Class = {}
---Returns a child class with inherited parameters from the parent class.
---@param parent table
---@param child table
function Class.extend(parent ,child)
return setmetatable(child or {}, { __index = parent })
end

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

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

33
mods/API/Events/init.lua Normal file
View File

@@ -0,0 +1,33 @@
Events = {}
---@alias Events.callback fun(eventName, ...)
---@type table<string, Events.callback[]>
local registeredEvents = {}
---@param eventName string
function Events.registerEvent(eventName)
assert(registeredEvents[eventName] == nil, ('Event %s is already registered.'):format(eventName))
registeredEvents[eventName] = {}
end
---@param eventName string
---@param callback Events.callback
function Events.subscribe(eventName, callback)
local callbacks = registeredEvents[eventName]
assert(callbacks ~= nil, ('Event %s does not exist'):format(eventName))
table.insert(callbacks, callback)
end
---@param eventName string
---@param ... any
function Events.call(eventName, ...)
local callbacks = registeredEvents[eventName]
assert(callbacks ~= nil, ('Event %s does not exist'):format(eventName))
for _, func in ipairs(callbacks) do
func(eventName, ...)
end
end

2
mods/API/Events/mod.conf Normal file
View File

@@ -0,0 +1,2 @@
name = smc__api__events
depends = smc__api__table

View File

@@ -1,9 +1,19 @@
local math = math local math = math
math.lerp = function (a, b, t) ---Limiting the value by minimum and maximum value.
return a + (b - a) * t ---@param value number The value to be limited.
end ---@param min number Minimum limit.
---@param max number Maximum limit.
math.clamp = function(value, min, max) math.clamp = function(value, min, max)
return math.min(math.max(value, min), max) return math.min(math.max(value, min), max)
end end
---Linear interpolation.
---@param a number Minimum value.
---@param b number Maximum value.
---@param t number Number in range [0, 1].
math.lerp = function (a, b, t)
t = math.clamp(t, 0, 1)
return a + (b - a) * t
end

View File

@@ -28,6 +28,7 @@ function Mod.getInfo(modname)
return {name = name, shortName = shortName, path = path, require = require} return {name = name, shortName = shortName, path = path, require = require}
end end
--[[
function Mod:new() function Mod:new()
---@type Mod ---@type Mod
local instance = setmetatable(Mod.getInfo(), { __index = self }) local instance = setmetatable(Mod.getInfo(), { __index = self })
@@ -61,6 +62,6 @@ function Mod:getModClassExtended(ChildClass)
local childClass = Mod:getClassExtended(self.Class, ChildClass or {}) local childClass = Mod:getClassExtended(self.Class, ChildClass or {})
return childClass return childClass
end end --]]
return Mod return Mod

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__control')
local require = modInfo.require
return require('Control')

View File

@@ -0,0 +1,2 @@
name = smc__core__control
depends = smc__api__api_loader

View File

@@ -0,0 +1,140 @@
---@class Events.Control
local Control = {}
-- control.on_press
Events.registerEvent('control.on_press')
---@param callbackFunc fun(player:Player, controlName:string)
function Control.subcribeOnPress(callbackFunc)
Events.subscribe('control.on_press', callbackFunc)
end
-- control.on_release
Events.registerEvent('control.on_release')
---@param callbackFunc fun(player:Player, controlName:string, holdTime:number)
function Control.subcribeOnRelease(callbackFunc)
Events.subscribe('control.on_release', callbackFunc)
end
-- control.on_hold
Events.registerEvent('control.on_hold')
---@param callbackFunc fun(player:Player, controlName:string, holdTime:number, dtime:number)
function Control.subcribeOnHold(callbackFunc)
Events.subscribe('control.on_hold', callbackFunc)
end
-- control.on_wield_change
Events.registerEvent('control.on_wield_change')
---@param callbackFunc fun(player:Player, player_wield_index:number, player_last_wield_index:number)
function Control.subcribeOnWieldChange(callbackFunc)
Events.subscribe('control.on_wield_change', callbackFunc)
end
-- --- Call events ---
local ControlPressKeys = {
'up', 'down', 'left', 'right', 'jump', 'aux1', 'sneak', 'dig', 'place', 'zoom'
}
local ControlMovementKeys = {
'movement_x', 'movement_y'
}
local playersLastControl = {}
local playersControlTimer = {}
core.register_on_joinplayer(function(player, last_login)
local playerName = player:get_player_name()
if playerName == nil then
return
end
local nowControl = player:get_player_control()
if nowControl == nil then
return
end
local controlTimer = {}
for _, key in ipairs(ControlPressKeys) do
controlTimer[key] = 0.0
end
playersLastControl[playerName] = nowControl
playersControlTimer[playerName] = controlTimer
end)
core.register_on_leaveplayer(function(player, timed_out)
local playerName = player:get_player_name()
if playerName == nil then
return
end
playersLastControl[playerName] = nil
playersControlTimer[playerName] = nil
end)
Api.registerGlobalStepForEachPlayer(0, function(deltaTime, player)
if player == nil then
return
end
local playerName = player:get_player_name()
if playerName == nil then
return
end
local lastControl = playersLastControl[playerName]
if lastControl == nil then
return
end
local controlTimer = playersControlTimer[playerName]
if controlTimer == nil then
return
end
local nowControl = player:get_player_control()
if nowControl == nil then
return
end
for _, key in ipairs(ControlPressKeys) do
local lastPressed = lastControl[key]
local nowPressed = nowControl[key]
-- on_press
if not lastPressed and nowPressed then
Events.call('control.on_press', key)
controlTimer[key] = 0
-- on_release
elseif lastPressed and not nowPressed then
Events.call('control.on_release', key, controlTimer[key])
controlTimer[key] = 0
-- on_hold
elseif lastPressed and nowPressed then
Events.call('control.on_hold', key, controlTimer[key], deltaTime)
controlTimer[key] = controlTimer[key] + deltaTime
end
end
--TODO: add player movement callbacks
--TODO: add mouse movement callbacks on dir
playersLastControl[playerName] = nowControl
playersControlTimer[playerName] = controlTimer
end)
return Control

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
return require('CraftSystem')

View File

@@ -0,0 +1,2 @@
name = smc__core__craft_system
depends = smc__api__api_loader

View File

@@ -0,0 +1,117 @@
local HASH_SPLITTER = '&'
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@alias CraftSystem.shapelessCraftsList table<CraftSystem.Craft.Group, table<string, CraftSystem.ShapelessCraft[]>>
---@alias CraftSystem.processualCraftsList table<CraftSystem.Craft.Group, table<string, CraftSystem.ProcessualCraft[]>>
---@class CraftSystem
---@field shapelessCraftsList CraftSystem.shapelessCraftsList
---@field processualCraftsList CraftSystem.processualCraftsList
local CraftSystem = {
shapelessCraftsList = {},
processualCraftsList = {},
}
---@alias CraftSystem.Craft.Type
---|'shapeless'
---|'processual'
---@alias CraftSystem.Craft.Group string
---@alias CraftSystem.Craft.Recipe string[]
---@alias shapelessCraftFunc fun(self:CraftSystem.ShapelessCraft, input:ItemStack[], workbenchMeta:NodeMetaRef?):boolean
---@alias processualCraftFunc fun(self:CraftSystem.ProcessualCraft, input:ItemStack[], workbenchMeta:NodeMetaRef?, processTime:number):boolean
---@class CraftSystem.BaseCraft
---@field type CraftSystem.Craft.Type
---@field group CraftSystem.Craft.Group
---@field output string
---@field recipe CraftSystem.Craft.Recipe
---@field return table? TODO: доделать тут тип
---@field craftFunc (fun(self, ...):boolean)?
---@class CraftSystem.ShapelessCraft : CraftSystem.BaseCraft
---@field craftFunc shapelessCraftFunc?
---@class CraftSystem.ProcessualCraft : CraftSystem.BaseCraft
---@field processTime number
---@field craftFunc processualCraftFunc?
---@param type CraftSystem.Craft.Type
---@return CraftSystem.shapelessCraftsList|CraftSystem.processualCraftsList
local function getCraftList(type)
local craftList
if type == 'shapeless' then
craftList = CraftSystem.shapelessCraftsList
elseif type == 'processual' then
craftList = CraftSystem.processualCraftsList
else
error(string.format('Craft type `%s` does not exist.', type))
end
return craftList
end
---@param type CraftSystem.Craft.Type
---@param group CraftSystem.Craft.Group
---@return table<string, table>
local function getCraftGroup(type, group)
local craftList = getCraftList(type)
---@type table<string, table>?
local craftGroup = craftList[group]
assert(craftGroup ~= nil, string.format('Craft group `%s` does not exist.', type))
return craftGroup
end
---@param type CraftSystem.Craft.Type
---@param group CraftSystem.Craft.Group
function CraftSystem.registerCraftGroup(type, group)
local craftList = getCraftList(type)
assert(craftList[group] == nil, string.format('Craft group `%s` is already registered.', type))
craftList[group] = {}
end
---@param recipe CraftSystem.Craft.Recipe
---@return string
function CraftSystem.getCraftHash(recipe)
table.sort(recipe)
local hash = ''
for i = 0, #recipe-1 do
hash = hash..recipe[i]..HASH_SPLITTER
end
return hash..recipe[#recipe]
end
---@param craftDef CraftSystem.ShapelessCraft|CraftSystem.ProcessualCraft
function CraftSystem.registerCraft(craftDef)
local craftGroup = getCraftGroup(craftDef.type, craftDef.group)
local hash = CraftSystem.getCraftHash(craftDef.recipe)
table.insert(craftGroup[hash], craftDef)
end
---@param type CraftSystem.Craft.Type
---@param group CraftSystem.Craft.Group
---@return CraftSystem.ShapelessCraft[] |
--- CraftSystem.processualCraftsList[] |
--- nil
function CraftSystem.getCraftResults(type, group, recipe)
local craftGroup = getCraftGroup(type, group)
local hash = CraftSystem.getCraftHash(recipe)
return craftGroup[hash]
end
return CraftSystem

View File

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

View File

@@ -1,30 +0,0 @@
---Abstract class implementing enumeration. It is a table<ENUM_KEY, ENUM_KEY>. Read-only table!
---@abstract
---@class Enum
local Enum = {}
---@param enum table[]
---@return Enum
function Enum:new(enum)
local metaEnum = {}
-- Create table<ENUM_KEY, ENUM_KEY>
for _, v in ipairs(enum) do
metaEnum[v] = v
end
---@type Enum
local instance = setmetatable({}, {
__index = metaEnum,
__newindex = function()
error('The Enum table is read only!')
end,
__metatable = false
})
return instance
end
---@alias Enum.EnumKey string Key from enumeration
return Enum

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__formspec')
local require = modInfo.require
return require('Formspec')

View File

@@ -0,0 +1,2 @@
name = smc__core__formspec
depends = smc__api__api_loader

View File

@@ -0,0 +1,502 @@
---@class Formspec
---@field params string
---@field elements string
local Formspec = {
elements = ''
}
---@class FormspecDef
---Set the formspec version to a certain number. If not specified, version `10` is assumed.
---@field version? number
---Define the size of the menu in inventory slots. `fixed_size` is optional, default `true`
---@field size {x:number, y:number, fixed_size:boolean?}
---Defines the position on the game window of the formspec's anchor point.
---@field position? {x:number, y:number}
---Defines the location of the anchor point within the formspec.
---@field anchor? {x:number, y:number}
---Defines how much space is padded around the formspec if the formspec tries to increase
---past the size of the screen and coordinates have to be shrunk.
---@field padding? {x:number, y:number}
---Disables player:set_formspec_prepend() from applying to this formspec.
---@field noPrepend? boolean
---When set to true, all following formspec elements will use the new coordinate system.
---@field realCoordinates? boolean
---When set to false, the formspec will not close when the user tries to close
---it with the Escape key or similar. Default true.
---@field allowClose? boolean
---@param def FormspecDef?
---@return Formspec
function Formspec:new(def)
if def == nil then
local instance = setmetatable({}, {__index = self})
return instance
end
local version = ('formspec_version[%s]'):format( def.version or 10) -- formspec version 10 (5.13.0)
local size = ('size[%s,%s,%s]'):format(def.size.x, def.size.y, def.size.fixed_size or true)
local position
if def.position ~= nil then
position = ('position[%s,%s]'):format(def.position.x or 0.5, def.position.y or 0.5)
else
position = ''
end
local anchor
if def.anchor ~= nil then
anchor = ('anchor[%s,%s]'):format(def.anchor.x, def.anchor.y)
else
anchor = ''
end
local padding
if def.padding ~= nil then
padding = ('padding[%s,%s]'):format(def.padding.x, def.padding.y)
else
padding = ''
end
local noPrepend
if def.noPrepend == true then
noPrepend = 'no_prepend[]'
else
noPrepend = ''
end
local realCoordinates
if def.realCoordinates ~= nil then
noPrepend = ('real_coordinates[%s]'):format(def.realCoordinates)
else
realCoordinates = ''
end
local allowClose = ('allow_close[%s]'):format(def.allowClose or true)
---@type Formspec
local instance = setmetatable({
params = version..size..position..anchor..padding..noPrepend..realCoordinates..allowClose,
}, {__index = self})
return instance
end
---TODO: описание
---@return string
function Formspec:getParams()
return self.params
end
---TODO: описание
---@return string
function Formspec:getElements()
return self.elements
end
---TODO: описание
---@return string
function Formspec:toString()
return self:getParams()..self:getElements()
end
---TODO: описание
---@param element string
function Formspec:addElement(element)
self.elements = self.elements..element
end
---Start of a container block, moves all physical elements in the container by (X, Y).
---Containers can be nested, in which case the offsets are added (child containers are relative to parent containers).
---@param container Formspec
---@param x number
---@param y number
function Formspec:container(container, x, y)
local element = ('container[%s,%s]'):format(x, y)..container:getElements()..'container_end[]'
self:addElement(element)
end
---Start of a scroll_container block. All contained elements will
---take the scroll_container coordinate as position origin,
---be additionally moved by the current value of the scrollbar with
---the name `scrollbar name` times `scroll factor` along the orientation `orientation` and
---be clipped to the rectangle defined by `X`, `Y`, `W` and `H`.
---@param container Formspec
---@param x number
---@param y number
---@param w number
---@param h number
---@param scrollbarName string
---@param orientation 'vertical'|'horizontal'
---@param scrollFactor number? Defaults to 0.1.
---@param contentPadding string? TODO: разобраться, что тут
function Formspec:scrollContainer(container, x, y, w, h, scrollbarName, orientation, scrollFactor, contentPadding)
local element = ('scroll_container[%s,%s;%s,%s;%s;%s;%s;%s]'):format(
x, y, w, h, scrollbarName, orientation, scrollFactor or '', contentPadding or '')..
container:getElements()..'scroll_container_end[]'
self:addElement(element)
end
---@alias Formspec.ListDef {inventoryLocation:string, listName:string, x:number, y:number, w:number, h:number,startingItemIndex:number}
---@param inventoryLocation string
---@param listName string
---@param x number
---@param y number
---@param w number Are in inventory slots, not in coordinates.
---@param h number Are in inventory slots, not in coordinates.
---@param startingItemIndex number?
function Formspec:list(inventoryLocation, listName, x, y, w, h,startingItemIndex)
if startingItemIndex == nil then
startingItemIndex = 0
end
local element = ('list[%s;%s;%s,%s;%s,%s;%s]'):format(
inventoryLocation, listName, x, y, w, h,startingItemIndex)
self:addElement(element)
end
---TODO: немного отличается от листринга луанти, так что надо дописать подробности
---@param lists [string, string][]? List of looping lists in the format `[inventory location, list name]`
function Formspec:listring(lists)
if lists == nil then
self:addElement('listring[]')
end
local element = ''
for list in lists do
element = element..('listring[%s;%s]'):format(list[1], list[2])
end
self:addElement(element)
end
---The following descriptions are allowed:
--- * `listcolors[<slot_bg_normal>;<slot_bg_hover>]`
--- * `listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>]`
--- * `listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>;<tooltip_bgcolor>;<tooltip_fontcolor>]`
---@param slotBackgroundNormal ColorString
---@param slotBackgroundHover ColorString
---@param slotBorder ColorString?
---@param tooltipBgcolor ColorString?
---@param tooltipFontcolor ColorString?
function Formspec:listColors(slotBackgroundNormal, slotBackgroundHover, slotBorder, tooltipBgcolor, tooltipFontcolor)
local element
if tooltipBgcolor ~= nil and tooltipFontcolor ~= nil then
element = ('listcolors[%s;%s;%s;%s;%s]'):format(
slotBackgroundNormal, slotBackgroundHover, slotBorder, tooltipBgcolor, tooltipFontcolor)
elseif slotBorder ~= nil then
element = ('listcolors[%s;%s;%s]'):format(
slotBackgroundNormal, slotBackgroundHover, slotBorder)
else
element = ('listcolors[%s;%s]'):format(
slotBackgroundNormal, slotBackgroundHover)
end
self:addElement(element)
end
---Adds tooltip for an element.
---@param elementName string
---@param tooltipText string
---@param bgcolor ColorString?
---@param fontcolor ColorString?
function Formspec:tooltipForElement(elementName, tooltipText, bgcolor, fontcolor)
local element = ('tooltip[%s;%s;%s;%s]'):format(
elementName, tooltipText, bgcolor or '', fontcolor or '')
self:addElement(element)
end
---Adds tooltip for an area. Other tooltips will take priority when present.
---@param x number
---@param y number
---@param w number
---@param h number
---@param tooltipText string
---@param bgcolor ColorString?
---@param fontcolor ColorString?
function Formspec:tooltipForArea(x, y, w, h, tooltipText, bgcolor, fontcolor)
local element = ('tooltip[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, tooltipText, bgcolor or '', fontcolor or '')
self:addElement(element)
end
---Show an image.
---@param x number
---@param y number
---@param w number
---@param h number
---@param textureName string
---@param middle boolean? Makes the image render in 9-sliced mode and defines the middle rect.
function Formspec:image(x, y, w, h, textureName, middle)
local element = ('image[%s,%s;%s,%s;%s;%s]'):format(
x, y, w, h, textureName, middle or '')
self:addElement(element)
end
---Show an animated image. The image is drawn like a "vertical_frames" tile animation
---(See Tile animation definition), but uses a frame count/duration for simplicity.
---@param x number
---@param y number
---@param w number
---@param h number
---@param textureName string
---@param frameCount number
---@param frameDuration number
---@param frameStart number
---@param middle boolean? Makes the image render in 9-sliced mode and defines the middle rect.
function Formspec:animatedImage(x, y, w, h, textureName, frameCount, frameDuration, frameStart, middle)
if middle == nil then
middle = false
end
local element = ('animated_image[%s,%s;%s,%s;%s;%s;%s;%s;%s;%s]'):format(
x, y, w, h, textureName, frameCount, frameDuration, frameStart, middle)
self:addElement(element)
end
---Show a mesh model.
---@param x number
---@param y number
---@param w number
---@param h number
---@param name string Element name that can be used for styling
---@param mesh string The mesh model to use.
---@param textures string The mesh textures to use according to the mesh materials. Texture names must be separated by commas.
---@param rotation number? Initial rotation of the camera, format x,y. The axes are euler angles in degrees.
---@param continuous boolean? Whether the rotation is continuous. Default `false`.
---@param mouseControl boolean? Whether the model can be controlled with the mouse. Default `true`.
---@param frameLoopRange string? Range of the animation frames. Defaults to the full range of all available frames. Syntax: `<begin>,<end>`.
---@param animationSpeed number? Sets the animation speed. Default 0 FPS.
function Formspec:model(x, y, w, h, name, mesh, textures, rotation, continuous, mouseControl, frameLoopRange, animationSpeed)
local element = ('model[%s,%s;%s,%s;%s;%s;%s;%s;%s;%s;%s;%s]'):format(
x, y, w, h, name, mesh, textures, rotation or '', continuous or '', mouseControl or '', frameLoopRange or '', animationSpeed or '')
self:addElement(element)
end
---Show an inventory image of registered item/node.
---@param x number
---@param y number
---@param w number
---@param h number
---@param itemName string
function Formspec:itemImage(x, y, w, h, itemName)
local element = ('item_image[%s,%s;%s,%s;%s]'):format(
x, y, w, h, itemName)
self:addElement(element)
end
---Sets background color of formspec.
---
---`fullscreen`:
--- * `false`: Only the non-fullscreen background color is drawn. (default)
--- * `true`: Only the fullscreen background color is drawn.
--- * `both`: The non-fullscreen and the fullscreen background color are drawn.
--- * `neither`: No background color is drawn.
---@param bgcolor ColorString Define the color of the non-fullscreen and the fullscreen background.
---@param fullscreen 'false'|'true'|'both'|'neither'
---@param fbgcolor ColorString? Define the color of the non-fullscreen and the fullscreen background.
function Formspec:bgcolor(bgcolor, fullscreen, fbgcolor)
local element = ('bgcolor[%s;%s;%s]'):format(
bgcolor, fullscreen or '', fbgcolor or '')
self:addElement(element)
end
---Example for formspec 8x4 in 16x resolution: image shall be sized 8 times 16px times 4 times 16px.
---@param x number
---@param y number
---@param w number
---@param h number
---@param textureName string
---@param autoClip boolean? If is `true`, the background is clipped
---to the formspec size (x and y are used as offset values, w and h are ignored)
function Formspec:background(x, y, w, h, textureName, autoClip)
local element
if autoClip ~= nil then
element = ('background[%s,%s;%s,%s;%s;%s]'):format(
x, y, w, h, textureName, autoClip)
else
element = ('background[%s,%s;%s,%s;%s]'):format(
x, y, w, h, textureName)
end
self:addElement(element)
end
---TODO
function Formspec:background9()
end
---TODO
function Formspec:pwdfield()
end
---TODO
function Formspec:field()
end
---TODO
function Formspec:fieldCloseOnEnter()
end
---TODO
function Formspec:textArea()
end
---TODO
function Formspec:label()
end
---TODO
function Formspec:hypertext()
end
---TODO
function Formspec:vertlabel()
end
---TODO
function Formspec:button()
end
---TODO
function Formspec:buttonUrl()
end
---TODO
function Formspec:imageButton()
end
---@param x number
---@param y number
---@param w number
---@param h number
---@param itemName string
---@param name string
---@param label string?
function Formspec:itemImageButton(x, y, w, h, itemName, name, label)
local element = ('item_image_button[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, itemName, name, label or '')
self:addElement(element)
end
---TODO
function Formspec:buttonExit()
end
---TODO
function Formspec:buttonUrlExit()
end
---TODO
function Formspec:imageButtonExit()
end
---TODO
function Formspec:textlist()
end
---TODO
function Formspec:tabheader()
end
---TODO
function Formspec:box()
end
---TODO
function Formspec:dropdown()
end
---TODO
function Formspec:checkbox()
end
---Show a scrollbar using options defined by the previous `scrollbaroptions[]`
---@param x number
---@param y number
---@param w number
---@param h number
---@param orientation 'vertical'|'horizontal'
---@param name string
---@param value number?
function Formspec:scrollbar(x, y, w, h, orientation, name, value)
local element = ('scrollbar[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, orientation, name, value or '')
self:addElement(element)
end
---TODO
function Formspec:scrollbarOptions()
end
---TODO
function Formspec:table()
end
---TODO
function Formspec:tableOptions()
end
---TODO
function Formspec:tablecolumns()
end
---TODO
function Formspec:style()
end
---TODO
function Formspec:style_type()
end
---TODO
function Formspec:set_focus()
end
return Formspec

View File

@@ -1,5 +1,4 @@
local Item = Mod:new() local modInfo = Mod.getInfo('smc__core__item')
local require = modInfo.require
Item.Class = Item.require('Item') return require('Item')
Api.addModToGlobalSpace(Item, 'Core.Item')

View File

@@ -1,2 +1,2 @@
name = smc__core__item name = smc__core__item
depends = smc__api__api_loader, smc__core__enum, smc__core__item_factory depends = smc__api__api_loader, smc__core__item_factory

View File

@@ -1,7 +1,7 @@
local modInfo = Mod.getInfo() local modInfo = Mod.getInfo('smc__core__item')
local require = modInfo.require local require = modInfo.require
local VisualEnum = require('Item.VisualEnum') local ItemFactory = Mod.getInfo('smc__core__item_factory').require('ItemFactory')
---@class Item ---@class Item
---@field itemDef Item.ItemDefinition ---@field itemDef Item.ItemDefinition
@@ -11,9 +11,12 @@ local VisualEnum = require('Item.VisualEnum')
local Item = { local Item = {
defaultDef = { defaultDef = {
settings = { settings = {
name = "", name = '',
title = "", title = '',
description = "", description = '',
titleColor = '#FFFFFF',
descriptionColor = '#C0C0C0',
addModName = true,
}, },
callbacks = {} callbacks = {}
} }
@@ -28,10 +31,35 @@ end
---@param itemDef Item.ItemDefinition ---@param itemDef Item.ItemDefinition
---@return NodeDefinition|ItemDefinition ---@return NodeDefinition|ItemDefinition
local function itemDefToLuantiDef(itemDef) local function itemDefToLuantiDef(itemDef)
local modName = Mod.getInfo().shortName
local S = core.get_translator(modName)
itemDef = table.copy(itemDef) itemDef = table.copy(itemDef)
local s = itemDef.settings local s = itemDef.settings
local c = itemDef.callbacks local c = itemDef.callbacks
local description = s.title .. "\n" .. s.description
if s.addModName then
s.name = modName .. ':' .. s.name
end
local title = s.title
local description = s.description
if title == nil or title == '' then
title = string.match(s.name, '%S:(%S+)')..'-title'
end
if description == nil or description == '' then
description = string.match(s.name, '%S:(%S+)')..'-desc'
end
if s.titleColor ~= nil and s.descriptionColor ~= nil then
description = core.colorize(s.titleColor ,S(title))..'\n'..
core.colorize(s.descriptionColor, S(description))
else
error('Item description color parameters cannot be empty.')
end
s.title, s.description = nil, description s.title, s.description = nil, description
local luantiDef = defMerge(s, c) local luantiDef = defMerge(s, c)
@@ -61,7 +89,7 @@ local defMerge = function(...)
return table.merge(...) return table.merge(...)
end end
---@param itemDef Item.ItemDefinition ---@param itemDef Item.ItemDefinition|Node.NodeDefinition
---@return Item ---@return Item
function Item:new(itemDef) function Item:new(itemDef)
---Adding default parameters ---Adding default parameters
@@ -74,15 +102,15 @@ function Item:new(itemDef)
local visual = itemDef.settings.visual local visual = itemDef.settings.visual
if visual == nil then if visual == nil then
visual = VisualEnum.ITEM_2D visual = 'item_2d'
end end
itemDef.settings.visual = nil itemDef.settings.visual = nil
if visual == VisualEnum.ITEM_3D then if visual == 'item_3d' then
register3dItem(luantiDef) register3dItem(luantiDef)
else else
visual = VisualEnum.ITEM_2D visual = 'item_2d'
registerFlatItem(luantiDef) registerFlatItem(luantiDef)
end end
@@ -103,7 +131,7 @@ end
---@return Item ---@return Item
function Item:getExtended(defaultDef) function Item:getExtended(defaultDef)
---@type Item ---@type Item
local ChildClass = Mod:getClassExtended(self, { local ChildClass = Class.extend(self, {
defaultDef = defaultDef, defaultDef = defaultDef,
}) })
@@ -119,7 +147,7 @@ function Item:getFactory(defaultDef)
end end
---@type ItemFactory ---@type ItemFactory
local instance = Core.ItemFactory():new(self, defaultDef) local instance = ItemFactory:new(self, defaultDef)
return instance return instance
end end

View File

@@ -1,8 +1,6 @@
---@class Item.Callbacks ---@class Item.Callbacks
local Callbacks = {} local Callbacks = {}
-- TODO: Разобраться с дубликатами аннотаций полей. Приоритетно брать аннотации из util/ide-helper
---Called when the 'place' key was pressed with the item in hand ---Called when the 'place' key was pressed with the item in hand
---and pointing at a node. ---and pointing at a node.
---Shall place item and return the leftover itemstack ---Shall place item and return the leftover itemstack

View File

@@ -3,7 +3,11 @@ local Settings = {}
---Technical name of the item. Must be unique and have the format `mod_name:item_name` ---Technical name of the item. Must be unique and have the format `mod_name:item_name`
---@type string ---@type string
Settings.name = "" Settings.name = ''
---Whether to add the mod name to the settings.name. Default: `true`
---@type boolean?
Settings.addModName = nil
---Item description. 1st line of item description. ---Item description. 1st line of item description.
---@type string? ---@type string?
@@ -13,10 +17,25 @@ Settings.title = nil
---@type string? ---@type string?
Settings.description = nil Settings.description = nil
---Item title color in description.
---
---Default: `#FFFFFF`
---@type ColorString?
Settings.titleColor = nil
---Item description color in description.
---
---Default: `#C0C0C0`
---@type ColorString?
Settings.descriptionColor = nil
---@alias Item.Visual
---'item_2d'|
---'item_3d'
---Visual node type. ---Visual node type.
---Values ​​are specified via an enumeration `Item.VisualEnum`. ---@type Item.Visual?
---@type Enum.EnumKey? Settings.visual = nil
Settings.visual = ""

View File

@@ -1,9 +0,0 @@
---@class Item.VisualEnum : Enum
---@field ITEM_2D Enum.EnumKey
---@field ITEM_3D Enum.EnumKey
local VisualEnum = Core.Enum:getModClassInstance({
'ITEM_2D',
'ITEM_3D',
})
return VisualEnum

View File

@@ -1,5 +1,4 @@
local ItemFactory = Mod:new() local modInfo = Mod.getInfo('smc__core__item_factory')
local require = modInfo.require
ItemFactory.Class = ItemFactory.require('ItemFactory') return require('ItemFactory')
Api.addModToGlobalSpace(ItemFactory, 'Core.ItemFactory')

View File

@@ -23,22 +23,11 @@ local defMerge = function(...)
end end
---@param itemDefs Item.ItemDefinition[]|Node.NodeDefinition[] List of nodes with parameters unique to them. ---@param itemDefs Item.ItemDefinition[]|Node.NodeDefinition[] List of nodes with parameters unique to them.
---@param addModName boolean? Whether to add the mod name to the settings.name. Default: `true` function ItemFactory:registerItems(itemDefs)
function ItemFactory:registerItems(itemDefs, addModName)
if addModName == nil then
addModName = true
end
local modName = Mod.getInfo().shortName
---@param nodeDef Item.ItemDefinition | Node.NodeDefinition ---@param nodeDef Item.ItemDefinition | Node.NodeDefinition
for _, itemDef in ipairs(itemDefs) do for _, itemDef in ipairs(itemDefs) do
itemDef = defMerge(itemDef, self.defaultDef, true) itemDef = defMerge(itemDef, self.defaultDef, true)
if addModName then
itemDef.settings.name = modName .. ':' .. itemDef.settings.name
end
self.itemClass:new(itemDef) self.itemClass:new(itemDef)
end end
@@ -50,34 +39,20 @@ local defMerge = function(...)
return table.merge(...) return table.merge(...)
end end
---@param shortNodeDefs table Table of the form `{ {name, title, description, tiles}, {name, title, description, tiles}, ...}` ---@param shortNodeDefs [string, (string[]|TileDefinition[])?][] Format list {{name, tiles}, {name, tiles}, ...}
---@param addModName boolean? Whether to add the mod name to the settings.name. Default: `true` function ItemFactory:registerNodesByShortDef(shortNodeDefs)
function ItemFactory:registerNodesByShortDef(shortNodeDefs, addModName)
if addModName == nil then
addModName = true
end
local modName = Mod.getInfo().shortName
for _, shortNodeDef in ipairs(shortNodeDefs) do for _, shortNodeDef in ipairs(shortNodeDefs) do
---@type Node.NodeDefinition ---@type Node.NodeDefinition
local nodeDef = { local nodeDef = {
settings = { settings = {
name = shortNodeDef[1], name = shortNodeDef[1],
title = shortNodeDef[2], tiles = shortNodeDef[2]
description = shortNodeDef[3],
tiles = shortNodeDef[4]
} }
} }
nodeDef = defMerge(nodeDef, self.defaultDef, true) nodeDef = defMerge(nodeDef, self.defaultDef, true)
if addModName then
nodeDef.settings.name = modName .. ':' .. nodeDef.settings.name
end
self.itemClass:new(nodeDef) self.itemClass:new(nodeDef)
end end
end end

View File

@@ -1,5 +1,4 @@
local MapGen = Mod:new() local modInfo = Mod.getInfo('smc__core__map_gen')
local require = modInfo.require
MapGen.Class = MapGen.require('MapGen') return require('MapGen')
Api.addModToGlobalSpace(MapGen, 'Core.MapGen')

View File

@@ -1,2 +1,2 @@
name = smc__core__map_gen name = smc__core__map_gen
depends = smc__api__api_loader, smc__game__items__rocks, smc__game__items__liquids depends = smc__api__api_loader

View File

@@ -1,5 +1,5 @@
local mathAbs, mathRound, mathMin, mathMax local mathAbs, mathRound, mathMin, mathMax, id
= math.abs, math.round, math.min, math.max = math.abs, math.round, math.min, math.max, core.get_content_id
local pastNoise2DCalc = { local pastNoise2DCalc = {
---@type MapGen.Triangle? ---@type MapGen.Triangle?
@@ -24,6 +24,9 @@ local require = modInfo.require
---@type MapGen.Layer ---@type MapGen.Layer
local Layer = require('MapGen.Layer') local Layer = require('MapGen.Layer')
---@type MapGen.StaticLayer
local StaticLayer = require('MapGen.StaticLayer')
---@type MapGen.Peak ---@type MapGen.Peak
local Peak = require('MapGen.Peak') local Peak = require('MapGen.Peak')
@@ -39,27 +42,41 @@ local Cavern = require('MapGen.Cavern')
---@class MapGen ---@class MapGen
---@field layersByName table<string, MapGen.Layer> ---@field layersByName table<string, MapGen.Layer>
---@field layersList MapGen.Layer[] ---@field layersList MapGen.Layer[]
---@field staticsByName table<string, MapGen.StaticLayer>
---@field staticsList MapGen.StaticLayer[]
---@field peaksMultinoiseInitialized boolean Is the fractal noise of the peaks initialized? This is necessary for a one-time noise initialization. ---@field peaksMultinoiseInitialized boolean Is the fractal noise of the peaks initialized? This is necessary for a one-time noise initialization.
---@field cavernsNoiseInitialized boolean TODO: описание ---@field cavernsNoiseInitialized 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 isRunning boolean A static field that guarantees that only one instance of the `MapGen` class will work.
---@field nodeIDs table<string, number> ---@field nodeIDs table<string, number>
---@field waterLevel number
local MapGen = { local MapGen = {
layersByName = {}, layersByName = {},
layersList = {}, layersList = {},
staticsByName = {},
staticsList = {},
peaksMultinoiseInitialized = false, peaksMultinoiseInitialized = false,
cavernsNoiseInitialized = false, cavernsNoiseInitialized = false,
isRunning = false, isRunning = false,
} }
---@param nodeIDs table<string, number> ---Definition table for the `MapGen`.
---@param waterLevel number ---
---**Only for EmmyLua.**
---@class MapGenDef
---@field nodes table<string, string>
---@param def MapGenDef
---@return MapGen ---@return MapGen
function MapGen:new(nodeIDs, waterLevel) function MapGen:new(def)
local nodesIDs = {}
-- Converting node names to IDs
for k, v in pairs(def.nodes) do
nodesIDs[k] = id(v)
end
---@type MapGen ---@type MapGen
local instance = setmetatable({ local instance = setmetatable({
nodeIDs = nodeIDs, nodes = def.nodes,
waterLevel = waterLevel or 0, nodeIDs = nodesIDs,
}, {__index = self}) }, {__index = self})
return instance return instance
@@ -84,6 +101,25 @@ function MapGen:getLayerByHeight(yPos)
end end
end end
---Determines which statics layer a node belongs to based on its height coordinate.
---@param yPos number
---@return MapGen.StaticLayer?
function MapGen:getStaticByHeight(yPos)
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз
--- Можно подумать над тем, чтобы использовать сортированный список
---@param static MapGen.StaticLayer
for _, static in ipairs(self.staticsList) do
if yPos >= static.minY and yPos <= static.maxY then
return static
end
end
end
-- --- REGISTRATION METHODS --- -- --- REGISTRATION METHODS ---
@@ -92,27 +128,50 @@ end
--- ---
---Note: layers must not overlap. ---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 name string The name that will be assigned to the layer. The name must be unique for each layer.
---@param minY number Minimum layer generation height. ---@param def MapGen.LayerDef Layer description table, see details `MapGen.LayerDef`
---@param maxY number Maximum layer generation height. function MapGen:registerLayer(name, def)
function MapGen:RegisterLayer(name, minY, maxY)
-- Layers with the same name cannot exist. -- Layers with the same name cannot exist.
assert(self.layersByName[name] == nil, ('A layer named `%s` is already registered.'):format(name)) assert(self.layersByName[name] == nil, ('A layer named `%s` is already registered.'):format(name))
-- Layers cannot overlap. -- Layers cannot overlap.
assert(self:getLayerByHeight(minY) == nil and self:getLayerByHeight(maxY) == nil, 'Registered layers must not overlap!') assert(self:getLayerByHeight(def.minY) == nil and self:getLayerByHeight(def.maxY) == nil, 'Registered layers must not overlap!')
---@type MapGen.Layer ---@type MapGen.Layer
local layer = Layer:new(name, minY, maxY) local layer = Layer:new(name, def)
self.layersByName[name] = layer self.layersByName[name] = layer
table.insert(self.layersList, layer) table.insert(self.layersList, layer)
-- Sort layers by maxY descending for processing priority -- Sort layers by maxY descending for processing priority.
table.sort(self.layersList, function(a, b) table.sort(self.layersList, function(a, b)
return a.maxY > b.maxY return a.maxY > b.maxY
end) end)
end 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
table.insert(self.staticsList, static)
-- Sort srtatics by maxY descending for processing priority.
table.sort(self.staticsList, function(a, b)
return a.maxY > b.maxY
end)
end
---Mark a world point as `MapGen.Peak` and assign it a specific noise that will affect the generation. ---Mark a world point as `MapGen.Peak` and assign it a specific noise that will affect the generation.
--- ---
---Note: The peaks shouldn't overlap. This won't cause any errors, but it might ruin the generation. ---Note: The peaks shouldn't overlap. This won't cause any errors, but it might ruin the generation.
@@ -173,6 +232,31 @@ function MapGen:register2DPeaks(layerName, multinoise, peakPoses, groups)
end end
end end
---TODO: описание
---@alias PeakColors table<ColorString, {noise:MapGen.Peak.MultinoiseParams, groups:table<string, number>?}>
---TODO: описание
---@param layerName string The name of the layer in which the new peaks will be included.
---@param map string TODO
---@param zeroPos Position2d
---@param peakColors PeakColors TODO
function MapGen:register2DPeaksFromFile(layerName, map, zeroPos,peakColors)
local modPath = core.get_modpath(core.get_current_modname())
local peaks = Api.ff2luat(modPath .. '/textures/maps/' .. map)
local mapSize = peaks.size
peaks.size = nil
print(dump(peaks))
for color, peaksPos in pairs(peaks) do
local peakParams = peakColors[color]
assert(peakParams ~= nil, ('There are no generation settings declared for the color `%s`'):format(color))
for _, peakPos in ipairs(peaksPos) do
self:register2DPeak(layerName, vector.new(peakPos.x - zeroPos.x, 0, peakPos.y - zeroPos.y), peakParams.noise, peakParams.groups)
end
end
end
---Mark a point on the biomes diagram and constrain the world area by height to mark it as `MapGen.Biome`. ---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 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 biomeName string The name to be assigned to the biome. The name must be unique for each biome.
@@ -287,30 +371,79 @@ end
---@param z number ---@param z number
local function generateNode(mapGenerator, layer, height, temp, humidity, data, index, x, y, z) local function generateNode(mapGenerator, layer, height, temp, humidity, data, index, x, y, z)
local ids = mapGenerator.nodeIDs local ids = mapGenerator.nodeIDs
local waterLevel = mapGenerator.waterLevel local waterLevel = layer.waterLevel
local m = math.random(-5, 5) -- 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
temp = mathMin(100, mathMax(0, temp + m)) if scatteringGorizontal ~= 0 then
humidity = mathMin(100, mathMax(0, humidity + m)) ---@diagnostic disable-next-line: param-type-not-match
--_height = mathMin(layer.maxY, mathMax(layer.minY, y + m)) scattTemp = scattTemp + math.random(scatteringGorizontal * -1, scatteringGorizontal)
---@diagnostic disable-next-line: param-type-not-match
scattHumidity = scattHumidity + math.random(scatteringGorizontal * -1, scatteringGorizontal)
end
if scatteringVertical ~= 0 then
---@diagnostic disable-next-line: param-type-not-match
scattHeight = scattHeight + math.random(scatteringVertical * -1, scatteringVertical)
end
scattTemp = math.clamp(scattTemp, layer.minTemp, layer.maxTemp)
scattHumidity = math.clamp(scattHumidity, layer.minHumidity, layer.maxHumidity)
scattHeight = math.clamp(scattHeight, layer.minY, layer.maxY)
scattHeight, scattTemp, scattHumidity = mathRound(scattHeight), mathRound(scattTemp), mathRound(scattHumidity)
height, temp, humidity = mathRound(height), mathRound(scattTemp), mathRound(scattHumidity)
---@type MapGen.Biome ---@type MapGen.Biome
local biome = layer.biomesDiagram[y][mathRound(temp)][mathRound(humidity)] local biome = layer.biomesDiagram[scattHeight][scattTemp][scattHumidity]
-- If the block is above surface height and above water level...
if y > height and y > waterLevel then if y > height and y > waterLevel then
data[index] = ids.air -- ... then airspace is generated.
biome:generateAir(mapGenerator, data, index, x, y, z)
-- If the block is above the surface height BUT below the water level...
elseif y > height and y <= waterLevel then elseif y > height and y <= waterLevel then
data[index] = ids.water -- ... then underwater space is generated.
biome:generateWater(mapGenerator, data, index, x, y, z)
-- If the block is below the surface height...
elseif y <= height then elseif y <= height then
-- ... and a cavern is generated in the block...
if isCavern(layer, x, y, z) then if isCavern(layer, x, y, z) then
data[index] = ids.air -- ... then airspace is generated.
elseif y == height and y >= waterLevel then biome:generateCavernAir(mapGenerator, data, index, x, y, z)
biome.generateSoil(mapGenerator, biome, data, index, x, y, z)
elseif y == height and y < waterLevel then -- ... or if the surface height is above the water level...
biome.generateBottom(mapGenerator, biome, data, index, x, y, z) 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, data, index, x, y, z)
-- ... 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, data, index, x, y, z)
else else
biome.generateRock(mapGenerator, biome, data, index, x, y, z) -- ... else e a stone is generated.
biome:generateRock(mapGenerator, data, index, x, y, z)
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, data, index, x, y, z)
else
-- ... else a stone is generated.
biome:generateRock(mapGenerator, data, index, x, y, z)
end
end end
else else
data[index] = ids.air data[index] = ids.air
@@ -412,7 +545,7 @@ local function calcNoises2dValues(triangle, x, y, z)
noiseHumidityValue = noiseHumidityValue + peak3:getMultinoise().humidityNoise:get_2d({x = x, y = z}) * weight noiseHumidityValue = noiseHumidityValue + peak3:getMultinoise().humidityNoise:get_2d({x = x, y = z}) * weight
totalWeight = totalWeight + weight totalWeight = totalWeight + weight
return mathRound(noiseHeightValue / totalWeight), mathRound(noiseTempValue / totalWeight), mathRound(noiseHumidityValue / totalWeight) return noiseHeightValue / totalWeight, noiseTempValue / totalWeight, noiseHumidityValue / totalWeight
end end
---Calculates a smoothed 2D noise value based on a preliminary space partitioning. ---Calculates a smoothed 2D noise value based on a preliminary space partitioning.
@@ -431,6 +564,8 @@ function MapGen:getNoises2dValues(layer, x, y, z)
if pastNoise2DCalc.triangle ~= nil and pointInTriangle(x, z, pastNoise2DCalc.triangle) then if pastNoise2DCalc.triangle ~= nil and pointInTriangle(x, z, pastNoise2DCalc.triangle) then
local noiseHeightValue, noiseTempValue, noiseHumidityValue = calcNoises2dValues(pastNoise2DCalc.triangle, x, y, z) local noiseHeightValue, noiseTempValue, noiseHumidityValue = calcNoises2dValues(pastNoise2DCalc.triangle, x, y, z)
noiseTempValue, noiseHumidityValue = layer:calcTemp(noiseTempValue, y), layer:calcHumidity(noiseHumidityValue, y)
pastNoise2DCalc.x = x pastNoise2DCalc.x = x
pastNoise2DCalc.z = z pastNoise2DCalc.z = z
pastNoise2DCalc.noiseValues = { pastNoise2DCalc.noiseValues = {
@@ -447,6 +582,8 @@ function MapGen:getNoises2dValues(layer, x, y, z)
if pointInTriangle(x, z,triangle) then if pointInTriangle(x, z,triangle) then
local noiseHeightValue, noiseTempValue, noiseHumidityValue = calcNoises2dValues(triangle, x, y, z) local noiseHeightValue, noiseTempValue, noiseHumidityValue = calcNoises2dValues(triangle, x, y, z)
noiseTempValue, noiseHumidityValue = layer:calcTemp(noiseTempValue, y), layer:calcHumidity(noiseHumidityValue, y)
pastNoise2DCalc.triangle = triangle pastNoise2DCalc.triangle = triangle
pastNoise2DCalc.x = x pastNoise2DCalc.x = x
pastNoise2DCalc.z = z pastNoise2DCalc.z = z
@@ -563,6 +700,14 @@ end
---@param y number ---@param y number
---@param z number ---@param z number
local function generatorHandler(mapGenerator, data, index, x, y, z) local function generatorHandler(mapGenerator, data, 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, index, x, y, z)
return
end
-- If generation occurs outside the layers, then a void is generated. -- If generation occurs outside the layers, then a void is generated.
local layer = mapGenerator:getLayerByHeight(y) local layer = mapGenerator:getLayerByHeight(y)
if layer == nil then if layer == nil then
@@ -574,7 +719,7 @@ local function generatorHandler(mapGenerator, data, index, x, y, z)
-- Calculating landscape height -- Calculating landscape height
local noiseHeightValue, noiseTempValue, noiseHumidityValue = mapGenerator:getNoises2dValues(layer, x, y, z) local noiseHeightValue, noiseTempValue, noiseHumidityValue = mapGenerator:getNoises2dValues(layer, x, y, z)
-- If the height of the landscape is zero, -- If the height of the landscape is `nil`,
-- then the point does not fall within any of the triangles. -- then the point does not fall within any of the triangles.
if noiseHeightValue == nil then if noiseHeightValue == nil then
noiseHeightValue = 0.0 noiseHeightValue = 0.0
@@ -609,8 +754,6 @@ function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed)
-- local param2_data = voxelManip:get_param2_data() -- local param2_data = voxelManip:get_param2_data()
local area = VoxelArea:new({MinEdge = eMin, MaxEdge = eMax}) local area = VoxelArea:new({MinEdge = eMin, MaxEdge = eMax})
data[area:index(0,50,0)] = core.get_content_id('rocks:malachite')
local index local index
-- Initial generation: landscape -- Initial generation: landscape
for z = minPos.z, maxPos.z do for z = minPos.z, maxPos.z do
@@ -627,14 +770,15 @@ function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed)
-- We make changes back to LVM and recalculate light & liquids -- We make changes back to LVM and recalculate light & liquids
voxelManip:set_data(data) voxelManip:set_data(data)
core.generate_ores(voxelManip, minPos, maxPos)
core.generate_decorations(voxelManip, minPos, maxPos)
--voxelManip:set_param2_data() --voxelManip:set_param2_data()
voxelManip:set_lighting({ day = 14, night = 0}) voxelManip:set_lighting({ day = 14, night = 0})
voxelManip:calc_lighting() voxelManip:calc_lighting()
voxelManip:update_liquids() voxelManip:update_liquids()
core.generate_ores(voxelManip, minPos, maxPos)
core.generate_decorations(voxelManip, minPos, maxPos)
--voxelManip:write_to_map() -- Async edit --voxelManip:write_to_map() -- Async edit
end end

View File

@@ -1,3 +1,5 @@
local id = core.get_content_id
---@class MapGen.Biome ---@class MapGen.Biome
---@field name string ---@field name string
---@field tempPoint number ---@field tempPoint number
@@ -5,12 +7,19 @@
---@field minY number ---@field minY number
---@field maxY number ---@field maxY number
---@field groundNodes MapGen.Biome.GroundNodes ---@field groundNodes MapGen.Biome.GroundNodes
---@field groundNodesIDs MapGen.Biome.GroundNodesIDs
---@field soilHeight number ---@field soilHeight number
---@field generateRock fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number) ---@field generateAir generateFunc
---@field generateSoil fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number) ---@field generateCavernAir generateFunc
---@field generateBottom fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number) ---@field generateWater generateFunc
---@field generateRock generateFunc
---@field generateTurf generateFunc
---@field generateSoil generateFunc
---@field generateBottom generateFunc
local Biome = {} local Biome = {}
---@alias generateFunc fun(self, mapGenerator:MapGen, data:number[], index:number, x:number, y:number, z:number)
---Definition table for the `MapGen.Biome`. ---Definition table for the `MapGen.Biome`.
--- ---
---**Only for EmmyLua.** ---**Only for EmmyLua.**
@@ -21,44 +30,92 @@ local Biome = {}
---@field maxY number ---@field maxY number
---@field groundNodes MapGen.Biome.GroundNodes ---@field groundNodes MapGen.Biome.GroundNodes
---@field soilHeight number ---@field soilHeight number
---@field generateRock fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)? ---@field generateAir generateFunc?
---@field generateSoil fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)? ---@field generateCavernAir generateFunc?
---@field generateBottom fun(mapGenerator:MapGen, biome:MapGen.Biome, data:number[], index:number, x:number, y:number, z:number)? ---@field generateWater generateFunc?
---@field generateRock generateFunc?
---@field generateTurf generateFunc?
---@field generateSoil generateFunc?
---@field generateBottom generateFunc?
-- Default generate functions -- Default generate functions
---@param self MapGen.Biome
---@param mapGenerator MapGen ---@param mapGenerator MapGen
---@param biome MapGen.Biome
---@param data number[] ---@param data number[]
---@param index number ---@param index number
---@param x number ---@param x number
---@param y number ---@param y number
---@param z number ---@param z number
local defaultGenerateRock = function(mapGenerator, biome, data, index, x, y, z) local defaultGenerateAir = function(self, mapGenerator, data, index, x, y, z)
--TODO: минимальную логику генерации прописать data[index] = mapGenerator.nodeIDs.air
end end
---@param self MapGen.Biome
---@param mapGenerator MapGen ---@param mapGenerator MapGen
---@param biome MapGen.Biome
---@param data number[] ---@param data number[]
---@param index number ---@param index number
---@param x number ---@param x number
---@param y number ---@param y number
---@param z number ---@param z number
local defaultGenerateSoil = function(mapGenerator, biome, data, index, x, y, z) local defaultGenerateCavernAir = function(self, mapGenerator, data, index, x, y, z)
--TODO: минимальную логику генерации прописать self:generateAir(mapGenerator, data, index, x, y, z)
end end
---@param self MapGen.Biome
---@param mapGenerator MapGen ---@param mapGenerator MapGen
---@param biome MapGen.Biome
---@param data number[] ---@param data number[]
---@param index number ---@param index number
---@param x number ---@param x number
---@param y number ---@param y number
---@param z number ---@param z number
local defaultGenerateBottom = function(mapGenerator, biome, data, index, x, y, z) local defaultGenerateWater = function(self, mapGenerator, data, index, x, y, z)
--TODO: минимальную логику генерации прописать data[index] = mapGenerator.nodeIDs.water
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateRock = function(self, mapGenerator, data, index, x, y, z)
data[index] = self.groundNodesIDs.rock
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateTurf = function(self, mapGenerator, data, index, x, y, z)
data[index] = self.groundNodesIDs.turf
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateSoil = function(self, mapGenerator,data, index, x, y, z)
data[index] = self.groundNodesIDs.soil
end
---@param self MapGen.Biome
---@param mapGenerator MapGen
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateBottom = function(self, mapGenerator, data, index, x, y, z)
data[index] = self.groundNodesIDs.bottom
end end
@@ -66,21 +123,47 @@ end
---@param def MapGen.BiomeDef ---@param def MapGen.BiomeDef
---@return MapGen.Biome ---@return MapGen.Biome
function Biome:new(name, def) function Biome:new(name, def)
if def.generateAir == nil then
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateAir()` function. The default function is used.', name)
def.generateAir = defaultGenerateAir
end
if def.generateCavernAir == nil then
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateCavernAir()` function. The default function is used.', name)
def.generateCavernAir = defaultGenerateCavernAir
end
if def.generateWater == nil then
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateWater()` function. The default function is used.', name)
def.generateWater = defaultGenerateWater
end
if def.generateRock == nil then if def.generateRock == nil then
Logger.warningLog('MapGen.Biome: The `%s` biome does not have a specified `generateRock()` function. The default function is used.', name) Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateRock()` function. The default function is used.', name)
def.generateRock = defaultGenerateRock def.generateRock = defaultGenerateRock
end end
if def.generateTurf == nil then
Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateTurf()` function. The default function is used.', name)
def.generateTurf = defaultGenerateTurf
end
if def.generateSoil == nil then if def.generateSoil == nil then
Logger.warningLog('MapGen.Biome: The `%s` biome does not have a specified `generateSoil()` function. The default function is used.', name) Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateSoil()` function. The default function is used.', name)
def.generateSoil = defaultGenerateSoil def.generateSoil = defaultGenerateSoil
end end
if def.generateBottom == nil then if def.generateBottom == nil then
Logger.warningLog('MapGen.Biome: The `%s` biome does not have a specified `generateBottom()` function. The default function is used.', name) Logger.infoLog('MapGen.Biome: The `%s` biome does not have a specified `generateBottom()` function. The default function is used.', name)
def.generateBottom = defaultGenerateBottom def.generateBottom = defaultGenerateBottom
end end
local groundNodesIDs = {}
-- Converting node names to IDs
for k, v in pairs(def.groundNodes) do
groundNodesIDs[k] = id(v)
end
---@type MapGen.Biome ---@type MapGen.Biome
local instance = setmetatable({ local instance = setmetatable({
name = name, name = name,
@@ -89,10 +172,15 @@ function Biome:new(name, def)
minY = def.minY, minY = def.minY,
maxY = def.maxY, maxY = def.maxY,
groundNodes = def.groundNodes, groundNodes = def.groundNodes,
groundNodesIDs = groundNodesIDs,
soilHeight = def.soilHeight, soilHeight = def.soilHeight,
generateRock = def.generateRock or defaultGenerateRock, generateAir = def.generateAir,
generateSoil = def.generateSoil or defaultGenerateSoil, generateCavernAir = def.generateCavernAir,
generateBottom = def.generateBottom or defaultGenerateBottom, generateWater = def.generateWater,
generateRock = def.generateRock,
generateSoil = def.generateSoil,
generateTurf = def.generateTurf,
generateBottom = def.generateBottom,
}, {__index = self}) }, {__index = self})
return instance return instance

View File

@@ -4,6 +4,8 @@
---@class MapGen.Biome.GroundNodes ---@class MapGen.Biome.GroundNodes
---@field turf string The soil covering the surface of the biome ---@field turf string The soil covering the surface of the biome
---@field soil string The soil beneath the turf. The height of this layer depends on `Biome.soilHeight` ---@field soil string The soil beneath the turf. The height of this layer depends on `Biome.soilHeight`
---@field rock string The rock found beneath the soil of a biome.
---@field bottom string Covering the bottom of reservoirs.
local GroundNodes = {} local GroundNodes = {}
return GroundNodes return GroundNodes

View File

@@ -0,0 +1,11 @@
--- Only for EmmyLua
---**Only for EmmyLua.**
---@class MapGen.Biome.GroundNodesIDs
---@field turf number The soil covering the surface of the biome
---@field soil number The soil beneath the turf. The height of this layer depends on `Biome.soilHeight`
---@field rock number The rock found beneath the soil of a biome.
---@field bottom number Covering the bottom of reservoirs.
local GroundNodes = {}
return GroundNodes

View File

@@ -2,10 +2,19 @@
---@field name string ---@field name string
---@field minY number ---@field minY number
---@field maxY number ---@field maxY number
---@field minTemp number
---@field maxTemp number
---@field minHumidity number
---@field maxHumidity number
---@field waterLevel number
---@field calcTemp fun(self:MapGen.Layer, value:number, height:number):number
---@field calcHumidity fun(self:MapGen.Layer, value:number, height:number):number
---@field peaksList MapGen.Peak[] ---@field peaksList MapGen.Peak[]
---@field biomesByName table<string, MapGen.Biome> ---@field biomesByName table<string, MapGen.Biome>
---@field biomesList MapGen.Biome[] ---@field biomesList MapGen.Biome[]
---@field biomesDiagram table ---@field biomesDiagram table
---@field biomesGorizontalScattering number
---@field biomesVerticalScattering number
---@field cavernsByName table<string, MapGen.Cavern> ---@field cavernsByName table<string, MapGen.Cavern>
---@field cavernsList MapGen.Cavern[] ---@field cavernsList MapGen.Cavern[]
---@field trianglesList MapGen.Triangle[] ---@field trianglesList MapGen.Triangle[]
@@ -21,16 +30,58 @@ local Layer = {
tetrahedronsList = {}, tetrahedronsList = {},
} }
---Definition table for the `MapGen.Layer`.
---
---**Only for EmmyLua.**
---@class MapGen.LayerDef
---@field minY number
---@field maxY number
---@field minTemp number
---@field maxTemp number
---@field minHumidity number
---@field maxHumidity number
---@field waterLevel? number
---@field calcTemp (fun(self:MapGen.Layer, value:number, height:number):number)?
---@field calcHumidity (fun(self:MapGen.Layer, value:number, height:number):number)?
---@field biomesGorizontalScattering number?
---@field biomesVerticalScattering number?
---@param self MapGen.Layer
---@param value number
---@param height number
---@return number
local function defaultCalcFunc(self, value, height)
return value
end
---@param name string ---@param name string
---@param minY number ---@param def MapGen.LayerDef
---@param maxY number
---@return MapGen.Layer ---@return MapGen.Layer
function Layer:new(name, minY, maxY) function Layer:new(name, def)
if def.calcTemp == nil then
Logger.infoLog('MapGen.Layer: The `%s` layer does not have a specified `calcTemp()` function. The default function is used.', name)
def.calcTemp = defaultCalcFunc
end
if def.calcHumidity == nil then
Logger.infoLog('MapGen.Layer: The `%s` layer does not have a specified `calcHumidity()` function. The default function is used.', name)
def.calcHumidity = defaultCalcFunc
end
---@type MapGen.Layer ---@type MapGen.Layer
local instance = setmetatable({ local instance = setmetatable({
name = name, name = name,
minY = minY, minY = def.minY,
maxY = maxY, maxY = def.maxY,
minTemp = def.minTemp,
maxTemp = def.maxTemp,
minHumidity = def.minHumidity,
maxHumidity = def.maxHumidity,
waterLevel = def.waterLevel or 0,
calcTemp = def.calcTemp,
calcHumidity = def.calcHumidity,
biomesGorizontalScattering = def.biomesGorizontalScattering or 0,
biomesVerticalScattering = def.biomesVerticalScattering or 0,
}, {__index = self}) }, {__index = self})
return instance return instance
@@ -98,10 +149,10 @@ function Layer:initBiomesDiagram()
end end
pastBiomesNames = newBiomesNames pastBiomesNames = newBiomesNames
for temp = 0, 100 do for temp = self.minTemp, self.maxTemp do
diagram[height][temp] = {} diagram[height][temp] = {}
for humidity = 0, 100 do for humidity = self.minHumidity, self.maxHumidity do
local minDistance = math.huge local minDistance = math.huge
local closestBiome = nil local closestBiome = nil

View File

@@ -0,0 +1,58 @@
local id = core.get_content_id
---@class MapGen.StaticLayer
---@field name string
---@field minY number
---@field maxY number
---@field staticNode string
---@field staticNodeID number
---@field generateStaticNode generateFunc
local StaticLayer = {}
---Definition table for the `MapGen.StaticLayer`.
---
---**Only for EmmyLua.**
---@class MapGen.StaticLayerDef
---@field minY number
---@field maxY number
---@field staticNode string
---@field generateStaticNode generateFunc
---@param self MapGen.StaticLayer
---@param mapGenerator MapGen
---@param data number[]
---@param index number
---@param x number
---@param y number
---@param z number
local defaultGenerateStaticNode = function(self, mapGenerator, data, index, x, y, z)
data[index] = self.staticNodeID
end
---@param name string
---@param def MapGen.StaticLayerDef
---@return MapGen.StaticLayer
function StaticLayer:new(name, def)
assert(def.maxY > def.minY, 'maxY there should be more minY')
if def.generateStaticNode == nil then
Logger.infoLog('MapGen.StaticLayer: The `%s` static layer does not have a specified `generateStaticNode()` function. The default function is used.', name)
def.generateStaticNode = defaultGenerateStaticNode
end
local staticNodeID = id(def.staticNode)
---@type MapGen.StaticLayer
local instance = setmetatable({
name = name,
minY = def.minY,
maxY = def.maxY,
staticNode = def.staticNode,
staticNodeID = staticNodeID,
generateStaticNode = def.generateStaticNode
}, {__index = self})
return instance
end
return StaticLayer

View File

@@ -10,7 +10,7 @@ local Peak = require('MapGen.Peak')
---@class MapGen.Triangulation.FakePeak : MapGen.Peak ---@class MapGen.Triangulation.FakePeak : MapGen.Peak
---@field id number ---@field id number
---@field getPeakPos fun():vector ---@field getPeakPos fun():vector
local FakePeak = Mod:getClassExtended(Peak, {}) local FakePeak = Class.extend(Peak, {})
---Returns a fake `MapGen.Peak` that has no noise parameters. ---Returns a fake `MapGen.Peak` that has no noise parameters.
---Note that the initialized peak should not be used in generation. ---Note that the initialized peak should not be used in generation.

View File

@@ -1,5 +1,4 @@
local Node = Mod:new() local modInfo = Mod.getInfo('smc__core__node')
local require = modInfo.require
Node.Class = Node.require('Node') return require('Node')
Api.addModToGlobalSpace(Node, 'Core.Node')

View File

@@ -1,18 +1,31 @@
---@type Item.VisualEnum local itemRequire = Mod.getInfo('smc__core__item').require
local VisualEnum = Core.Item.require('Item.VisualEnum')
---@type Item
local Item = itemRequire('Item')
---@type ItemFactory
local ItemFactory = Mod.getInfo('smc__core__item_factory').require('ItemFactory')
---@class Node : Item ---@class Node : Item
---@field defaultDef Node.NodeDefinition ---@field defaultDef Node.NodeDefinition
local Node = Core.Item:getModClassExtended({}) local Node = Class.extend(Item, {})
---The alias `table.merge` for EmmyLua
---@type fun(...):(Node.NodeDefinition)
local defMerge = function(...)
return table.merge(...)
end
---@param nodeDef Node.NodeDefinition ---@param nodeDef Node.NodeDefinition
---@return Node ---@return Node
function Node:new(nodeDef) function Node:new(nodeDef)
nodeDef.settings.visual = VisualEnum.ITEM_3D ---Adding default parameters
nodeDef = defMerge(nodeDef, self.defaultDef, true)
nodeDef.settings.visual = 'item_3d'
---@type Node ---@type Node
local instance = Core.Item:getModClassInstance(nodeDef) local instance = Item:new(nodeDef)
return instance return instance
end end
@@ -23,7 +36,7 @@ end
---@return Node ---@return Node
function Node:getExtended(defaultDef) function Node:getExtended(defaultDef)
---@type Node ---@type Node
local ChildClass = Mod:getClassExtended(self, { local ChildClass = Class.extend(self, {
defaultDef = defaultDef, defaultDef = defaultDef,
}) })
@@ -39,7 +52,7 @@ function Node:getFactory(defaultDef)
end end
---@type ItemFactory ---@type ItemFactory
local instance = Core.ItemFactory:getModClassInstance(self, defaultDef) local instance = ItemFactory:new(self, defaultDef)
return instance return instance
end end

View File

@@ -1,8 +1,8 @@
---@type Item.Callbacks ---@type Item.Callbacks
local ItemCallbacks = Core.Item.require('Item.Callbacks') local ItemCallbacks = Mod.getInfo('smc__core__item').require('Item.Callbacks')
---@class Node.Callbacks : Item.Callbacks ---@class Node.Callbacks : Item.Callbacks
local Callbacks = Mod:getClassExtended(ItemCallbacks, {}) local Callbacks = Class.extend(ItemCallbacks, {})
---Node constructor; called after adding node. ---Node constructor; called after adding node.
---Can set up metadata and stuff like that. ---Can set up metadata and stuff like that.

View File

@@ -1,8 +1,8 @@
---@type Item.Settings ---@type Item.Settings
local ItemSettings = Core.Item.require('Item.Settings') local ItemSettings = Mod.getInfo('smc__core__item').require('Item.Settings')
---@class Node.Settings : Item.Settings ---@class Node.Settings : Item.Settings
local Settings = Mod:getClassExtended(ItemSettings, {}) local Settings = Class.extend(ItemSettings, {})
---See "Node drawtypes" ---See "Node drawtypes"
---@type string? ---@type string?

4
mods/CORE/Plant/init.lua Normal file
View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__plant')
local require = modInfo.require
return require('Plant')

2
mods/CORE/Plant/mod.conf Normal file
View File

@@ -0,0 +1,2 @@
name = smc__core__plant
depends = smc__core__node

View File

@@ -0,0 +1,27 @@
local nodeRequire = Mod.getInfo('smc__core__node').require
---@type Node
local Node = nodeRequire('Node')
-- -@type ItemFactory
---local ItemFactory = Mod.getInfo('smc__core__item_factory').require('ItemFactory')
---@class Plant : Node
local Plant = Node:getExtended({
settings = {
name = 'smc__core__plant:abstract_plant',
drawtype = "plantlike",
sunlight_propagates = true,
paramtype = "light",
paramtype2 = "meshoptions",
walkable = false,
buildable_to = true,
groups = {dig_immediate = 3},
selection_box = {
type = "fixed",
fixed = {-0.25, -0.5, -0.25, 0.25, 0.5, 0.25},
},
}
})
return Plant

View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__player')
local require = modInfo.require
return require('Player')

View File

@@ -1,2 +1,2 @@
name = smc__core__enum name = smc__core__player
depends = smc__api__api_loader depends = smc__api__api_loader

View File

@@ -0,0 +1,4 @@
---@class Player
local Player = {}
return Player

View File

@@ -0,0 +1,4 @@
---@class Player.GUI
local GUI = {}
return GUI

View File

@@ -0,0 +1,4 @@
---@class Player.HUD
local HUD = {}
return HUD

4
mods/CORE/Sound/init.lua Normal file
View File

@@ -0,0 +1,4 @@
local modInfo = Mod.getInfo('smc__core__sound')
local require = modInfo.require
return require('Sound')

2
mods/CORE/Sound/mod.conf Normal file
View File

@@ -0,0 +1,2 @@
name = smc__core__sound
depends = smc__api__api_loader

View File

@@ -0,0 +1,4 @@
---@class Sound
local Sound = {}
return Sound

View File

@@ -1,5 +1,4 @@
local TileSheet = Mod:new() local modInfo = Mod.getInfo('smc__core__tilesheet')
local require = modInfo.require
TileSheet.Class = TileSheet.require('TileSheet') return require('TileSheet')
Api.addModToGlobalSpace(TileSheet, 'Core.TileSheet')

View File

@@ -84,7 +84,7 @@ end
---@param y number ---@param y number
---@return string ---@return string
function TileSheet:getTextureName(x, y) function TileSheet:getTextureName(x, y)
local textureName = self.image .. '^[sheet:'.. self.width .. 'x' .. self.height .. ':' .. x .. ',' .. y local textureName = '('..self.image .. '^[sheet:'.. self.width .. 'x' .. self.height .. ':' .. x .. ',' .. y..')'
return textureName return textureName
end end

View File

@@ -0,0 +1,71 @@
local modInfo = Mod.getInfo('smc__core__formspec')
local require = modInfo.require
---@type Formspec
local Formspec = require('Formspec')
local listForm = Formspec:new({
size = {x=21, y=12},
})
listForm:list('current_player', 'main', 10.5, 6.5, 8, 4)
local listFormItems = Formspec:new()
local items = core.registered_nodes
local w, h = 0, 0
---@param name string
---@param def NodeDefinition
for name, def in pairs(items) do
listFormItems:itemImageButton(w, h, 1, 1, name, name..'::item_button')
w = w + 1
if w > 9 then
w = 0
h = h + 1
end
end
--listFormItems:list('current_player', 'main', 0, 0, 1, 32)
listForm:scrollContainer(listFormItems, 0.5, 0.5, 9, 11, 'admin_commands:list_items', 'vertical')
listForm:scrollbar(10, 0.5, 0.25, 10, 'vertical', 'admin_commands:list_items')
core.log(listForm:toString())
core.register_chatcommand('list', {
privs = {server = true},
func = function(name, param)
local player = core.get_player_by_name(name)
core.show_formspec(name, 'admin_commands:list_form', listForm:toString())
return true, ''
end
})
core.register_on_player_receive_fields(function(player, formname, fields)
if formname ~= 'admin_commands:list_form' then
return
end
for key, value in pairs(fields) do
if string.ends_with(key, '::item_button') then
---@type ItemStackString
local stack = string.match(key, '(%S+)::item_button')
core.log(tostring(stack))
---@type InvRef
local inv = player:get_inventory()
if inv:room_for_item("main", stack) then
inv:add_item("main", stack)
end
end
end
end)

View File

@@ -0,0 +1,2 @@
name = smc__core__admin_commands
depends = smc__api__api_loader, smc__core__formspec, smc__core__item

View File

@@ -1,243 +0,0 @@
-- MAPGEN ENVIROMENT ONLY
-- https://api.luanti.org/core-namespace-reference/#mapgen-environment
-- This environment is isolated from the main environment,
-- so global tables need to be preloaded manually.
-- --- Global APIs load --
-- Ensure
dofile(core.get_modpath('smc__api__ensure')..'/init.lua')
-- Logger
dofile(core.get_modpath('smc__api__logger')..'/init.lua')
-- Math
dofile(core.get_modpath('smc__api__math')..'/init.lua')
-- Require
dofile(core.get_modpath('smc__api__require')..'/init.lua')
-- Mod
dofile(core.get_modpath('smc__api__mod')..'/init.lua')
-- TODO: исправить загрузку строковых библиотек (хотя они пока что не юзаются в мапгене)
-- Они не работают из-за get_current_modname внутри utf8
-- UTF-8
-- dofile(core.get_modpath('smc__api__utf8')..'/init.lua')
-- String
-- dofile(core.get_modpath('smc__api__string')..'/init.lua')
-- Table
dofile(core.get_modpath('smc__api__table')..'/init.lua')
-- --- MapGen definiton ---
local id = core.get_content_id
local mathRound = math.round
local mapGenRequire = Mod.getInfo('smc__core__map_gen').require
---@type MapGen
local MapGen = mapGenRequire('MapGen')
---@type MapGen
local mapGenerator = MapGen:new({
-- Special nodes
air = id("air"),
-- Rocks
sylite = id("rocks:sylite"),
tauitite = id("rocks:tauitite"),
iyellite = id("rocks:iyellite"),
falmyte = id("rocks:falmyte"),
hapcoryte = id("rocks:hapcoryte"),
burcite = id("rocks:burcite"),
felhor = id("rocks:felhor"),
malachite = id("rocks:malachite"),
-- Liquids
water = id("liquids:water_source"),
}, 10
)
mapGenerator:RegisterLayer("world", -1000, 500)
local land1 = {
offset = -20,
scale = 5,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 3,
persistence = 0.4,
lacunarity = 2,
}
local land2 = {
offset = 20,
scale = 5,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 3,
persistence = 0.4,
lacunarity = 2,
}
local climat1 = {
offset = 80,
scale = 10,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 8,
persistence = 0.6,
lacunarity = 2,
}
local climat2 = {
offset = 30,
scale = 10,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 8,
persistence = 0.6,
lacunarity = 2,
}
local climat0 = {
offset = 50,
scale = 0,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 8,
persistence = 0.4,
lacunarity = 2,
}
local v = vector.new
mapGenerator:register2DPeaks("world",
{
landscapeNoise = land1,
tempNoise = climat2,
humidityNoise = climat2,
},{
v(500, 0, 500),
v(-500, 0, -500),
v(-500, 0, 500),
v(500, 0, -500),
})
mapGenerator:register2DPeaks("world",
{
landscapeNoise = land2,
tempNoise = climat1,
humidityNoise = climat1,
},{
v(-300, 0, 300),
v(200, 0, -400),
})
mapGenerator:register2DPeaks("world",
{
landscapeNoise = land2,
tempNoise = climat2,
humidityNoise = climat2,
},{
v(200, 0, 100),
v(-300, 0, -200),
})
mapGenerator:registerCavern('world', 'cavern1', {
minY = -100,
maxY = -10,
smoothDistance = 20,
threshold = 0.3,
noiseParams ={
offset = 0,
scale = 1,
spread = {x = 25, y = 25, z = 25},
seed = 5934,
octaves = 3,
persistence = 0.5,
lacunarity = 2.0
},
})
-- --- Biomes ---
---@type ValueNoise
local rocksNoise
---@type NoiseParams
local rocksNoiseParams ={
offset = 4,
scale = 2,
spread = {x = 30, y = 30, z = 30},
seed = 47,
octaves = 3,
persistence = 0.5,
lacunarity = 4,
}
local function generateRock(mapGenerator, biome, data, index, x, y, z)
local ids = mapGenerator.nodeIDs --TODO перенести камни в Biome
if rocksNoise == nil then
rocksNoise = core.get_value_noise(rocksNoiseParams)
end
local noiseRocksValue = mathRound(rocksNoise:get_3d({x = x, y = y, z = z}))
if noiseRocksValue == 1 then
data[index] = ids.malachite
elseif noiseRocksValue == 2 then
data[index] = ids.hapcoryte
elseif noiseRocksValue == 3 then
data[index] = ids.iyellite
elseif noiseRocksValue == 4 then
data[index] = ids.sylite
elseif noiseRocksValue == 5 then
data[index] = ids.tauitite
elseif noiseRocksValue == 6 then
data[index] = ids.falmyte
elseif noiseRocksValue == 7 then
data[index] = ids.burcite
elseif noiseRocksValue == 8 then
data[index] = ids.felhor
end
end
local function generateSoil(mapGenerator, biome, data, index, x, y, z)
data[index] = core.get_content_id(biome.groundNodes.turf) -- TODO: убрать тут get_content_id(), переместить его куда-то "выше"
end
mapGenerator:registerBiome('world', "biome1", {
tempPoint = 0,
humidityPoint = 0,
minY = -10000,
maxY = 1000,
groundNodes = {
soil = "soils:clay_soil_baren",
turf = "soils:clay_soil_baren",
},
soilHeight = 1,
generateRock = generateRock,
generateSoil = generateSoil,
})
mapGenerator:registerBiome('world', "biome2", {
tempPoint = 100,
humidityPoint = 100,
minY = -1000,
maxY = 1000,
groundNodes = {
soil = "soils:rocky_soil_baren",
turf = "soils:rocky_soil_baren",
},
soilHeight = 1,
generateRock = generateRock,
generateSoil = generateSoil,
})
mapGenerator:run()

View File

@@ -1,23 +0,0 @@
-- World generation runs in the mapgen environment (separate thread)
-- The Mapgen environment is isolated from the main enviroment.
core.register_mapgen_script(core.get_modpath(core.get_current_modname())..'/MapGenerator.lua')
core.register_ore({
ore_type = "scatter",
ore = "soils:rocky_soil_baren",
wherein = "rocks:sylite",
clust_scarcity = 8*8*8,
clust_num_ores = 8,
clust_size = 3,
y_min = -31000,
y_max = 64,
})
core.register_decoration({
deco_type = "simple",
place_on = "soils:clay_soil_baren",
sidelen = 8,
fill_ratio = 0.1,
decoration = "plants:plants",
})

View File

@@ -0,0 +1,52 @@
-- World generation occurs in a separate thread (MapGen Environment).
-- But for the main thread, the mapgenerator object is also initialized.
local mapGeneneratorRequire = Mod.getInfo('smc__core__map_generator').require
-- Main env init
local mapGenerator = mapGeneneratorRequire('mapGenerator')
-- Async env init
core.register_mapgen_script(core.get_modpath('smc__core__map_generator')..'/src/asyncInit.lua')
-- --- Register vanilla ores & decorations ---
-- For now, the generation does not have its own support
-- for the generation of ores and decorations, so vanilla ones are used.
core.register_ore({
ore_type = "scatter",
ore = "soils:rocky_soil_baren",
wherein = "rocks:sylite",
clust_scarcity = 8*8*8,
clust_num_ores = 8,
clust_size = 3,
y_min = -31000,
y_max = 64,
})
core.register_decoration({
deco_type = "simple",
place_on = "soils:turf_swamp",
sidelen = 8,
fill_ratio = 0.4,
decoration = "plants:plants",
})
core.register_decoration({
deco_type = "simple",
place_on = "soils:turf_swamp",
sidelen = 8,
fill_ratio = 0.05,
decoration = "plants:plant0",
})
core.register_decoration({
deco_type = "simple",
place_on = "soils:turf_swamp",
sidelen = 8,
fill_ratio = 0.01,
decoration = "plants:plant2",
})
return mapGenerator

View File

@@ -0,0 +1,46 @@
-- MAPGEN ENVIROMENT ONLY
-- https://api.luanti.org/core-namespace-reference/#mapgen-environment
-- This environment is isolated from the main environment,
-- so global tables need to be preloaded manually.
-- --- Global APIs load --
-- Class
dofile(core.get_modpath('smc__api__class')..'/init.lua')
-- Ensure
dofile(core.get_modpath('smc__api__ensure')..'/init.lua')
-- Logger
dofile(core.get_modpath('smc__api__logger')..'/init.lua')
-- Math
dofile(core.get_modpath('smc__api__math')..'/init.lua')
-- Require
dofile(core.get_modpath('smc__api__require')..'/init.lua')
-- Mod
dofile(core.get_modpath('smc__api__mod')..'/init.lua')
-- TODO: исправить загрузку строковых библиотек (хотя они пока что не юзаются в мапгене)
-- Они не работают из-за get_current_modname внутри utf8
-- UTF-8
-- dofile(core.get_modpath('smc__api__utf8')..'/init.lua')
-- String
-- dofile(core.get_modpath('smc__api__string')..'/init.lua')
-- Table
dofile(core.get_modpath('smc__api__table')..'/init.lua')
-- TODO: пока что закоментировано, поскольку вызывает ошибку из-за global_step
-- Api loader
-- dofile(core.get_modpath('smc__api__api_loader')..'/init.lua')
Api = {}
dofile(core.get_modpath('smc__api__api_loader')..'/src/Api/ff2lua.lua')
---@type MapGen
local mapGenerator = dofile(core.get_modpath('smc__core__map_generator')..'/src/mapGenerator.lua')
mapGenerator:run()

View File

@@ -0,0 +1,280 @@
-- --- MapGen definiton ---
local id = core.get_content_id
local mathRound = math.round
local mapGenRequire = Mod.getInfo('smc__core__map_gen').require
---@type MapGen
local MapGen = mapGenRequire('MapGen')
---@type MapGen
local mapGenerator = MapGen:new({
nodes = {
-- Special nodes
air = 'air',
-- Rocks
sylite = 'rocks:sylite',
tauitite = 'rocks:tauitite',
iyellite = 'rocks:iyellite',
falmyte = 'rocks:falmyte',
hapcoryte = 'rocks:hapcoryte',
burcite = 'rocks:burcite',
felhor = 'rocks:felhor',
malachite = 'rocks:malachite',
-- Liquids
water = 'liquids:water_source',
},
})
local function calcTemp(layer, value, height)
return value
end
local function calcHumidity(layer, value, height)
return value
end
mapGenerator:registerLayer('midgard', {
minY = -256,
maxY = 256,
minTemp = -100,
maxTemp = 100,
minHumidity = 0,
maxHumidity = 100,
calcTemp = calcTemp,
calcHumidity = calcHumidity,
biomesVerticalScattering = 5,
biomesGorizontalScattering = 5
})
local land1 = {
offset = -20,
scale = 5,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 3,
persistence = 0.4,
lacunarity = 2,
}
local land2 = {
offset = 10,
scale = 5,
spread = {x = 30, y = 30, z = 30},
seed = 47,
octaves = 3,
persistence = 0.4,
lacunarity = 2,
}
local climat1 = {
offset = 80,
scale = 10,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 8,
persistence = 0.6,
lacunarity = 2,
}
local climat2 = {
offset = 30,
scale = 10,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 8,
persistence = 0.6,
lacunarity = 2,
}
local climat0 = {
offset = 50,
scale = 0,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 8,
persistence = 0.4,
lacunarity = 2,
}
local v = vector.new
--[[
mapGenerator:register2DPeaks('midgard',
{
landscapeNoise = land1,
tempNoise = climat2,
humidityNoise = climat2,
},{
v(500, 0, 500),
v(-500, 0, -500),
v(-500, 0, 500),
v(500, 0, -500),
})
mapGenerator:register2DPeaks('midgard',
{
landscapeNoise = land2,
tempNoise = climat1,
humidityNoise = climat1,
},{
v(-300, 0, 300),
v(200, 0, -400),
})
mapGenerator:register2DPeaks('midgard',
{
landscapeNoise = land2,
tempNoise = climat2,
humidityNoise = climat2,
},{
v(200, 0, 100),
v(-300, 0, -200),
})--]]
--[[
mapGenerator:register2DPeaksFromFile('midgard', 'map.ff', {x=250, y=250}, {
['#396FFFFF'] = {noise = {
landscapeNoise = land1,
tempNoise = climat2,
humidityNoise = climat2,
}
},
['#3FFF26FF'] = {noise = {
landscapeNoise = land2,
tempNoise = climat2,
humidityNoise = climat2,
}
}
})--]]
local N = 32
for x = -10, 10 do
for z = - 10, 10 do
local land
if math.random(0,1) == 0 then
land = land1
else
land = land2
end
print(x)
mapGenerator:register2DPeak('midgard', vector.new(x*N, 0, z*N), {
landscapeNoise = land,
tempNoise = climat2,
humidityNoise = climat2,
})
end
end
--[[
mapGenerator:registerCavern('midgard', 'cavern1', {
minY = -48,
maxY = 0,
smoothDistance = 20,
threshold = 0.3,
noiseParams ={
offset = 0,
scale = 1,
spread = {x = 25, y = 25, z = 25},
seed = 5934,
octaves = 3,
persistence = 0.5,
lacunarity = 2.0
},
})--]]
-- --- Biomes ---
---@type ValueNoise
local rocksNoise
---@type NoiseParams
local rocksNoiseParams ={
offset = 4,
scale = 2,
spread = {x = 30, y = 30, z = 30},
seed = 47,
octaves = 3,
persistence = 0.5,
lacunarity = 4,
}
local function generateRock(biome, mapGenerator, data, index, x, y, z)
local ids = mapGenerator.nodeIDs
if rocksNoise == nil then
rocksNoise = core.get_value_noise(rocksNoiseParams)
end
local noiseRocksValue = mathRound(rocksNoise:get_3d({x = x, y = y, z = z}))
if noiseRocksValue == 1 then
data[index] = ids.malachite
elseif noiseRocksValue == 2 then
data[index] = ids.hapcoryte
elseif noiseRocksValue == 3 then
data[index] = ids.iyellite
elseif noiseRocksValue == 4 then
data[index] = ids.sylite
elseif noiseRocksValue == 5 then
data[index] = ids.tauitite
elseif noiseRocksValue == 6 then
data[index] = ids.falmyte
elseif noiseRocksValue == 7 then
data[index] = ids.burcite
elseif noiseRocksValue == 8 then
data[index] = ids.felhor
end
end
---@param biome MapGen.Biome
local function generateSoil(biome, mapGenerator, data, index, x, y, z)
local ids = mapGenerator.nodeIDs
if rocksNoise == nil then
rocksNoise = core.get_value_noise(rocksNoiseParams)
end
local noiseRocksValue = mathRound(rocksNoise:get_3d({x = x, y = y, z = z}))
if noiseRocksValue > 4 then
data[index] = ids.sylite
else
data[index] = biome.groundNodesIDs.soil
end
end
---@param biome MapGen.Biome
local function generateTurf(biome, mapGenerator, data, index, x, y, z)
local ids = mapGenerator.nodeIDs
if rocksNoise == nil then
rocksNoise = core.get_value_noise(rocksNoiseParams)
end
local noiseRocksValue = mathRound(rocksNoise:get_3d({x = x, y = y, z = z}))
if noiseRocksValue > 4 then
data[index] = ids.sylite
else
data[index] = biome.groundNodesIDs.turf
end
end
mapGenerator:registerBiome('midgard', 'swamp', {
tempPoint = 0,
humidityPoint = 80,
minY = 100,
maxY = 0,
groundNodes = {
soil = 'soils:rocky_soil_baren',
turf = 'soils:turf_swamp',
rock = 'rocks:sylite',
bottom = 'soils:rocky_soil_baren',
},
soilHeight = 3,
generateRock = generateRock,
generateTurf = generateTurf,
generateSoil = generateSoil,
})
return mapGenerator

View File

@@ -1 +1,2 @@
name = smc__environment name = smc__environment
depends = smc__core__map_gen, smc__game__items__rocks, smc__game__items__liquids

View File

@@ -1,3 +1,3 @@
name = smc__game__items__items_loader name = smc__game__items__items_loader
description = Include this mod in your `depends` to ensure all items are registered description = Include this mod in your `depends` to ensure all items are registered
depends = smc__game__items__rocks, smc__game__items__log, smc__game__items__soils, smc__game__items__liquids depends = smc__game__items__rocks, smc__game__items__wood, smc__game__items__soils, smc__game__items__liquids

View File

@@ -1 +0,0 @@
print(":)")

View File

@@ -1,2 +0,0 @@
name = smc__game__items__log
depends = smc__core__node

View File

@@ -1,23 +0,0 @@
core.register_node(":plants:plants", {
description = 'Plant',
drawtype = "plantlike",
tiles = { "test_plant.png" },
sunlight_propagates = true,
paramtype = "light",
paramtype2 = "meshoptions",
place_param2 = 3,
waving = 1,
walkable = false,
buildable_to = true,
groups = {dig_immediate = 2},
selection_box = {
type = "fixed",
fixed = { -0.15, -0.5, -0.15, 0.15, 0.2, 0.15 },
},
on_construct = function(pos)
local node = core.get_node(pos)
node.param2 = 3
end,
})

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -1,7 +1,11 @@
---@type Node
local Node = Mod.getInfo('smc__core__node').require('Node')
---@type Node.NodeDefinition ---@type Node.NodeDefinition
local defaultLiquidDef = { local defaultLiquidDef = {
settings = { settings = {
name = '', name = '',
addModName = false,
tiles = {}, tiles = {},
waving = 3, waving = 3,
use_texture_alpha = "blend", use_texture_alpha = "blend",
@@ -19,7 +23,7 @@ local defaultLiquidDef = {
} }
---@type Node ---@type Node
local defaultLiquid = Core.Node.Class:getExtended(defaultLiquidDef) local defaultLiquid = Node:getExtended(defaultLiquidDef)
local liquidFactory = defaultLiquid:getFactory() local liquidFactory = defaultLiquid:getFactory()
@@ -91,4 +95,4 @@ liquidFactory:registerItems({
paramtype2 = "flowingliquid", paramtype2 = "flowingliquid",
} }
} }
}, false) })

View File

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -0,0 +1,29 @@
local modInfo = Mod.getInfo('smc__core__plant')
---@type TileSheet
local TileSheet = Mod.getInfo('smc__core__tilesheet').require('TileSheet')
---@type Plant
local Plant = modInfo.require('Plant')
Plant:new({
settings = {
name = 'plants',
tiles = { "test_plant.png" },
place_param2 = 3,
},
})
local ts = TileSheet:new('plants_test_sheet.png', 16, 16)
for i=0, 3 do
Plant:new({
settings = {
name = 'plant'..tostring(i),
title = 'Plant',
tiles = { ts:t(i,0) },
place_param2 = 3,
},
})
end

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -1,3 +1,9 @@
---@type TileSheet
local TileSheet = Mod.getInfo('smc__core__tilesheet').require('TileSheet')
---@type Node
local Node = Mod.getInfo('smc__core__node').require('Node')
---@type Node.NodeDefinition ---@type Node.NodeDefinition
local defaultRockDef = { local defaultRockDef = {
settings = { settings = {
@@ -11,22 +17,22 @@ local defaultRockDef = {
} }
---@type Node ---@type Node
local defaultRock = Core.Node.Class:getExtended(defaultRockDef) local defaultRock = Node:getExtended(defaultRockDef)
local rockFactory = defaultRock:getFactory() local rockFactory = defaultRock:getFactory()
---@type TileSheet ---@type TileSheet
local ts = Core.TileSheet:getModClassInstance("rocks_sheet.png", 16, 16) local ts = TileSheet:new("rocks_sheet.png", 16, 16)
rockFactory:registerNodesByShortDef({ rockFactory:registerNodesByShortDef({
{"sylite", "Sylite", nil, {ts:t(0, 0)}}, {"sylite", {ts:t(0, 0)}},
{"tauitite", "Tauitite", nil, {ts:t(0, 2)}}, {"tauitite", {ts:t(0, 2)}},
{"iyellite", "Iyellite", nil, {ts:t(0, 4)}}, {"iyellite", {ts:t(0, 4)}},
{"falmyte", "Falmyte", nil, {ts:t(0, 6)}}, {"falmyte", {ts:t(0, 6)}},
{"hapcoryte", "Hapcoryte", nil, {ts:t(0, 8)}}, {"hapcoryte", {ts:t(0, 8)}},
{"burcite", "Burcite", nil, {ts:t(0, 10)}}, {"burcite", {ts:t(0, 10)}},
{"felhor", "Felhor", nil, {ts:t(0, 12)}}, {"felhor", {ts:t(0, 12)}},
{"malachite", "malachite", nil, {ts:t(0, 14)}} {"malachite", {ts:t(0, 14)}}
}) })
--[[ --[[

View File

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 106 KiB

View File

@@ -1,3 +1,9 @@
---@type TileSheet
local TileSheet = Mod.getInfo('smc__core__tilesheet').require('TileSheet')
---@type Node
local Node = Mod.getInfo('smc__core__node').require('Node')
---@type Node.NodeDefinition ---@type Node.NodeDefinition
local defaultSoilDef = { local defaultSoilDef = {
settings = { settings = {
@@ -12,12 +18,12 @@ local defaultSoilDef = {
} }
---@type Node ---@type Node
local defaultSoil = Core.Node.Class:getExtended(defaultSoilDef) local defaultSoil = Node:getExtended(defaultSoilDef)
local soilFactory = defaultSoil:getFactory() local soilFactory = defaultSoil:getFactory()
---@type TileSheet ---@type TileSheet
local ts = Core.TileSheet:getModClassInstance("soils_sheet.png", 16, 16) local ts = TileSheet:new("soils_sheet.png", 16, 16)
local clayTiles = { local clayTiles = {
ts:t(0,0) ts:t(0,0)
@@ -230,4 +236,18 @@ soilFactory:registerItems({
}, },
}, },
}, true) })
---@type TileSheet
local tsT = TileSheet:new("soils_turfs_sheet.png", 16, 16)
Node:new({
settings = {
name = 'turf_swamp',
tiles = {tsT:t(0,0), ts:t(6, 0), ts:t(6,0)..'^'..tsT:t(0,1)},
groups = {
dig_immediate = 2,
soil_fertiliry = 100, -- Soil fertility for agriculture
}
}
})

View File

@@ -0,0 +1,4 @@
# textdomain: soils
turf_swamp-title=Болотистая Почва
turf_swamp-desc=Высокоплодородистая почва с высоким содержанием удобрений.

View File

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@@ -0,0 +1,207 @@
---@type Node
local Node = Mod.getInfo('smc__core__node').require('Node')
---@type TileSheet
local TileSheet = Mod.getInfo('smc__core__tilesheet').require('TileSheet')
---@type Node.NodeDefinition
local defaultRockDef = {
settings = {
name = "",
description = "A log",
tiles = {},
groups = {
dig_immediate = 2,
},
paramtype2 = "facedir",
},
}
---@type Node.NodeDefinition
local defaultPlanksDef = {
settings = {
name = "",
description = "A planks",
tiles = {},
groups = {
dig_immediate = 2,
},
paramtype2 = "facedir",
},
}
local defaultLog = Node:getExtended(defaultRockDef)
local defaultPlanks = Node:getExtended(defaultPlanksDef)
local logFactory = defaultLog:getFactory()
local planksFactory = defaultPlanks:getFactory()
---@type TileSheet
local logTileSheet = TileSheet:new("wood_sheet.png", 16, 16)
local function getLogTiles(x, y)
return {
logTileSheet:t(x, y),
logTileSheet:t(x, y),
logTileSheet:t(x, y+1),
}
end
local t = getLogTiles
logFactory:registerItems({
---@type Node.NodeDefinition
{
settings = {
name = "marentine_log",
title = "Marentine Log",
--description = "",
tiles = t(0, 1),
},
},
---@type Node.NodeDefinition
{
settings = {
name = "allwhere_log",
title = "Allwhere Log",
--description = "",
tiles = t(2, 1),
},
},
---@type Node.NodeDefinition
{
settings = {
name = "fis_log",
title = "Fis Log",
--description = "",
tiles = t(4, 1),
},
},
---@type Node.NodeDefinition
{
settings = {
name = "tammoy_log",
title = "Tammoy Log",
--description = "",
tiles = t(6, 1),
},
},
---@type Node.NodeDefinition
{
settings = {
name = "dallalia_log",
title = "Dallalia Log",
--description = "",
tiles = t(8, 1),
},
},
---@type Node.NodeDefinition
{
settings = {
name = "zuph_log",
title = "Zuph Log",
--description = "",
tiles = t(10, 1),
},
},
})
planksFactory:registerItems({
---@type Node.NodeDefinition
{
settings = {
name = "marentine_planks",
title = "Marentine Planks",
--description = "",
tiles = { logTileSheet:t(0, 4) },
},
},
---@type Node.NodeDefinition
{
settings = {
name = "allwhere_planks",
title = "Allwhere Planks",
--description = "",
tiles = { logTileSheet:t(2, 4) },
},
},
---@type Node.NodeDefinition
{
settings = {
name = "fis_planks",
title = "Fis Planks",
--description = "",
tiles = { logTileSheet:t(4, 4) },
},
},
---@type Node.NodeDefinition
{
settings = {
name = "tammoy_planks",
title = "Tammoy Planks",
--description = "",
tiles = { logTileSheet:t(6, 4) },
},
},
---@type Node.NodeDefinition
{
settings = {
name = "dallalia_planks",
title = "Dallalia Planks",
--description = "",
tiles = { logTileSheet:t(8, 4) },
},
},
---@type Node.NodeDefinition
{
settings = {
name = "zuph_planks",
title = "Zuph Planks",
--description = "",
tiles = { logTileSheet:t(10, 4) },
},
},
})
-- сундучки
---@type TileSheet
local caseTileSheet = TileSheet:new("cases_sheet.png", 16, 16)
local function getCaseTiles(x, y)
return {
caseTileSheet:t(x, y),
caseTileSheet:t(x, y),
caseTileSheet:t(x, y+1),
}
end
local t = getCaseTiles
planksFactory:registerItems({
---@type Node.NodeDefinition
{
settings = {
name = "case_closed",
title = "Case",
--description = "",
tiles = t(0,0)
},
},
---@type Node.NodeDefinition
{
settings = {
name = "case_open",
title = "Case",
--description = "",
tiles = t(1,0);
drawtype = 'nodebox';
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.5 - 1/16*2, 0.5},
}
}
},
},
})

View File

@@ -0,0 +1,2 @@
name = smc__game__items__wood
depends = smc__core__node

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB