71 Commits

Author SHA1 Message Date
0198771c51 WorkStation: tidying up the code, adding comments 2026-02-18 22:20:27 +03:00
5272294aeb CraftSystem: end of work? 2026-02-18 22:19:42 +03:00
2eb7d04039 WorkStationUI: update 2026-02-18 22:18:30 +03:00
c70bf96734 BaseUI: add showForm & closeForm methods 2026-02-18 22:18:10 +03:00
b64c8e9350 WorkStation: update 2026-02-17 21:44:53 +03:00
319f155849 CraftSystem: ImmersiveCraftStage`: minor changes 2026-02-17 21:43:48 +03:00
ed4094d964 CraftSystem: add ImmersiveCraftCounter` 2026-02-17 21:43:00 +03:00
6b074c7a8c CraftSystem: PrimitiveCraft`: minor changes 2026-02-17 21:42:21 +03:00
00633226cf CraftSystem: TappingNode: add get_staticdata method, enable static_save` 2026-02-17 21:40:42 +03:00
6156a4bb6f rocks`: add some locale 2026-02-17 21:38:02 +03:00
b6f354f6fe Submodules: update ide-helper 2026-02-17 21:37:00 +03:00
cfc4502cb0 Item: minor chandes 2026-02-17 21:36:32 +03:00
bafe26983c BaseUI: add recive fields methods 2026-02-17 21:35:40 +03:00
7b43def5fb HelperLib: add receive fields methods 2026-02-17 21:34:56 +03:00
f4896b89ef HelperLib: minor changes immersive craft data 2026-02-17 21:34:25 +03:00
c58467f22b Submodules: update ide-helper 2026-02-14 19:27:17 +03:00
1d5f93c35a CraftSystem: minor annotation fix 2026-02-13 21:38:04 +03:00
46427f565f Submodules: update ide-helper 2026-02-13 21:35:47 +03:00
8fb4e4db00 Submodules: update ide-helper and fix mapgen annotations 2026-02-13 21:22:48 +03:00
9c56db6ac4 CtaftSystem: Bringing the system into order, adding annotations and comments, eliminating major bugs 2026-02-13 21:09:55 +03:00
15bb906df7 HelperLib: add getObjectByGUID & immersive craft data methods 2026-02-13 21:03:01 +03:00
e9818fba24 Events & Control: remove Events.registerCallback function 2026-02-13 21:01:44 +03:00
a6fa46bb96 Creature: minor annotation fixes 2026-02-13 20:58:44 +03:00
44adcf9535 Creature: create Creature.LuaEntity class 2026-02-12 21:12:27 +03:00
97292d6205 Creature: callback fixes 2026-02-12 21:11:52 +03:00
f2af5e725a Item & Node: corrections in the order of merging tables of parameters and default parameters 2026-02-12 21:10:18 +03:00
25f38d1acd BaseUI: create base UI class 2026-02-12 21:08:43 +03:00
1d43ae1255 CraftSystem: create ImmersiveCraftNode & add first immersive craft type Tapping 2026-02-09 22:35:05 +03:00
9426ac01dd Creature: minor fixes 2026-02-09 22:19:20 +03:00
21232bd1f7 Table: fix annotation table.merge 2026-02-09 22:13:41 +03:00
0c02c0045d Rename class: Entity -> Creature 2026-02-09 19:33:23 +03:00
205cbc10c2 Node: added missing empty lines at the end of files 2026-02-09 18:17:27 +03:00
660c96ab5c Entity: add getExtended method 2026-02-09 18:16:14 +03:00
ec8499ff76 Item & Node: add merge defaults defs to getExtended and getFactory 2026-02-09 18:15:22 +03:00
430ac78ea1 Submodules: update ide-helper 2026-02-08 20:38:59 +03:00
f7140fb3cc Entity: reating a wrapper class for an entity. Close #26 2026-02-08 20:26:17 +03:00
6153b053f6 Item: minor changes 2026-02-08 20:24:53 +03:00
bc03aa4ba6 Rename custom field use snake_case and _ 2026-02-08 18:42:07 +03:00
04f90a7b2d Submodules: update ide-helper 2026-02-08 16:46:44 +03:00
66380fb873 WorkStation: create WorkStation class, register test node & crafts, add work station UI 2026-02-07 22:14:07 +03:00
169dd64bce CraftSystem: minor fixes 2026-02-07 22:13:16 +03:00
613b7ead83 Submodules: update ide-helper 2026-02-07 20:35:59 +03:00
94dc3fa819 CraftSystem: rewrite system, completion of work on immersive craft 2026-02-06 18:19:38 +03:00
6c77b5a38c Class: minor fixes 2026-02-06 17:14:02 +03:00
c41ee05b55 CraftSystem: add lastline space 2026-02-06 16:53:32 +03:00
87c6e5f3f3 CraftSystem: Immersive craft part 2 2026-02-05 22:30:25 +03:00
e435b21b43 Item: Corrections to the design, added the last empty lines 2026-02-02 14:25:20 +03:00
0baa7af759 Entity: create dummy-class 2026-02-02 14:19:14 +03:00
83304bbfc1 CraftSystem: add dummy-class ImmersiveCraftStage 2026-02-02 13:59:12 +03:00
7dbd2f3be8 CraftSystem: add immersive craft handler (no realisation) 2026-02-02 13:46:06 +03:00
b41448da7b CraftSystem: add primitive craft handler 2026-02-02 13:33:12 +03:00
865f46b734 Add Item.Rarity 2026-02-01 20:51:23 +03:00
3dd28858f5 Add some rocks 2026-02-01 19:44:59 +03:00
Van
9119582ddd Обновить .gitea/pull_request_template.yml 2026-01-29 16:04:00 +03:00
Van
a12091fc93 Обновить .gitea/pull_request_template.yml 2026-01-29 16:03:28 +03:00
Van
cfadf47951 Обновить .gitea/pull_request_template.yml 2026-01-29 16:02:47 +03:00
b0fc925750 mapGenerator: lmao fix 2026-01-24 18:35:46 +03:00
e12b0d64e5 MapGen: Added check for points belonging to the triangulation area 2026-01-24 18:30:36 +03:00
efcee33a02 MapGen: Fixed map mirroring. Added an isometric grid map 2026-01-24 17:17:47 +03:00
ce778673c7 Formspec: add method chaining to elements registrations 2026-01-23 15:10:01 +03:00
5ec4bdd933 MapGen: Layer:get<Object>ByName() methods added. Add Layer:getPeakByPos(). close #20 2026-01-23 14:38:46 +03:00
6332f23bf3 Add new types rocks, add test gradient mapgen 2026-01-22 21:45:40 +03:00
966af2328a Update rocks 2026-01-22 19:26:48 +03:00
d08ee33400 Add water flowing texture 2026-01-22 17:34:59 +03:00
ba97a8f36f MapGen: minor changes 2026-01-22 14:26:18 +03:00
ef6c0d9fe6 MapGen: add getLayerByName(). close #19 2026-01-22 14:23:28 +03:00
c3bdb29852 Formspec: adding the remaining methods. close #8 2026-01-22 14:17:28 +03:00
6904090d19 Submodules: update ide-helper 2026-01-21 19:32:53 +03:00
f3c5beb341 MapGen: Moving checks for layer object uniqueness from mapgen methods to layer methods 2026-01-21 19:10:27 +03:00
fc90ae54c0 MapGen: Added the ability to limit cave generation regionally. close #15 2026-01-21 19:05:00 +03:00
0952e96452 Formspec: some fix 2026-01-21 16:23:32 +03:00
74 changed files with 2540 additions and 414 deletions

View File

@@ -1,5 +1,5 @@
name: Сообщение об ошибке
about: Сообщить о недоработке игры, которую необходимо исправить.
name: PR-template
about: PR-template
labels:
- pr/wait review
- review/need a maintainer
@@ -23,12 +23,12 @@ body:
attributes:
label: Требования
options:
- label: Я запускал игру и убедился в том, что она работает.
required: true
- label: Я ознакомлен с соглашением по разработке и мои изменения следуют принятым стандартам.
required: true
- label: Я запускал игру и убедился в том, что она работает.
required: false
- label: Я указал в описании запроса метки (label) с префиксом `Edit:` в соответствии с теми изменениями, которые сделал.
required: true
required: false
- type: markdown
attributes:
value: |

View File

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

View File

@@ -0,0 +1,2 @@
name = smc__core__base_ui
depends = smc__system__system_loader

View File

@@ -0,0 +1,122 @@
local getInstance = Class.getInstance
---@class BaseUI
---Context for transferring data between displaying
---the form spec to the player and handling callbacks.
---@field name string
---@field getFormSpecString fun(self:BaseUI,playerName:string,...):string
---@field contex table<string, table>
local BaseUI = {
contex = {}
}
---@param name string
---@param getFormSpecString fun(self:BaseUI,playerName:string,...):string
function BaseUI:new(name, getFormSpecString)
---@type BaseUI
local instance = getInstance(self, {})
instance.name = name
instance.getFormSpecString = getFormSpecString
-- Ensure that when the form is closed, the context is cleared.
instance:registerOnFormQuit(function(player)
instance:clearContex(player)
end)
return instance
end
---Set a value for a specific key.
---Recommended for use where `core.show_formspec` is used.
---
---In the future, the key value can be obtained in the formspec callback.
---@param player string|Player Player as an object (entity) or his name
---@param key string
---@param value any
function BaseUI:setContex(player, key, value)
if type(player) ~= 'string' then
player = player:get_player_name()
end
local contex = self.contex[player]
if contex == nil then
self.contex[player] = {[key]=value}
else
contex[key] = value
end
end
---Get the value of a specific key.
---Recommended for use in a formspec callback.
---@param player string|Player Player as an object (entity) or his name
---@param key string
---@return any?
function BaseUI:getContex(player, key)
if type(player) ~= 'string' then
player = player:get_player_name()
end
local contex = self.contex[player] or {}
return contex[key]
end
---Clear saved context data for a player.
---Recommended for use when closing formspec.
---@param player string|Player Player as an object (entity) or his name
function BaseUI:clearContex(player)
if type(player) ~= 'string' then
player = player:get_player_name()
end
self.contex[player] = {}
end
---Register a callback for a specific player action in FormSpec.
---
---The callback is guaranteed to be called only for the specified field.
---@param fieldName string the name of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called.
--- * `fieldValue` - the field value that is passed in the `fields` table.
function BaseUI:registerOnFormFieldAction(fieldName, callback)
Smc.registerOnFormFieldAction(self.name, fieldName, callback)
end
---Register a callback function to close the FormSpec.
---
---The callback is guaranteed to be called only for the specified form.
---@param callback fun(player:Player) Callback to handle the close. Parameters:
--- * `player` - the player who closed the form.
function BaseUI:registerOnFormQuit(callback)
Smc.registerOnFormQuit(self.name, callback)
end
---Register a callback for a specific player action in FormSpec.
---
---The callback function is guaranteed to be called only for the specified form and
---for the field whose name matches the pattern.
---@param fieldNamePattern string the name pattern of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called (will match the pattern).
--- * `fieldValue` - the field value that is passed in the `fields` table.
function BaseUI:registerOnFormFieldActionMatch( fieldNamePattern, callback)
Smc.registerOnFormFieldActionMatch(self.name, fieldNamePattern, callback)
end
---Shows the player the FormSpec registered by the instance of this UI.
---@param playerName string
function BaseUI:showForm(playerName, ...)
core.show_formspec(playerName, self.name, self:getFormSpecString(playerName, ...))
end
---Close the player the FormSpec registered by the instance of this UI.
---@param playerName string
function BaseUI:closeForm(playerName)
core.close_formspec(playerName, self.name)
end
return BaseUI

View File

@@ -2,7 +2,6 @@
local Control = {}
-- control.on_press
Events.registerEvent('control.on_press')
---@param callbackFunc fun(player:Player, controlName:string)
function Control.subcribeOnPress(callbackFunc)
@@ -11,7 +10,6 @@ end
-- control.on_release
Events.registerEvent('control.on_release')
---@param callbackFunc fun(player:Player, controlName:string, holdTime:number)
function Control.subcribeOnRelease(callbackFunc)
@@ -20,7 +18,6 @@ end
-- control.on_hold
Events.registerEvent('control.on_hold')
---@param callbackFunc fun(player:Player, controlName:string, holdTime:number, dtime:number)
function Control.subcribeOnHold(callbackFunc)
@@ -29,7 +26,6 @@ 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)

View File

@@ -1,2 +1,2 @@
name = smc__core__craft_system
depends = smc__system__system_loader
depends = smc__system__system_loader, smc__core__creature

View File

@@ -1,117 +1,28 @@
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[]>>
---@type CraftSystem.PrimitiveCraftHandler
local PrimitiveCraftHandler = require('CraftSystem.PrimitiveCraftHandler')
---@type CraftSystem.ImmersiveCraftHandler
local ImmersiveCraftHandler= require('CraftSystem.ImmersiveCraftHandler')
---@alias CraftSystem.CraftGroup string
---@alias CraftSystem.CraftRecipe string[]
---@alias CraftSystem.CraftType 'primitive'|'immersive'
---@class CraftSystem
---@field shapelessCraftsList CraftSystem.shapelessCraftsList
---@field processualCraftsList CraftSystem.processualCraftsList
local CraftSystem = {
shapelessCraftsList = {},
processualCraftsList = {},
}
local CraftSystem = {}
---@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
---@param craftName string
---@param def CraftSystem.PrimitiveCraftDef
function CraftSystem.registerPrimitiveCraft(craftName, def)
PrimitiveCraftHandler:registerCraft(craftName, def)
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]
---@param craftName string
---@param def CraftSystem.ImmersiveCraftDef
function CraftSystem.registerImmersiveCraft(craftName, def)
ImmersiveCraftHandler:registerCraft(craftName, def)
end
return CraftSystem

View File

@@ -0,0 +1,13 @@
---Abstract class for craft.
---@class CraftSystem.BaseCraft
---@field name string
---@field group CraftSystem.CraftGroup
local BaseCraft = {}
---Definition table for the `CraftSystem.BaseCraft`.
---
---**Only for EmmyLua.**
---@class CraftSystem.BaseCraftDef
---@field group CraftSystem.CraftGroup
return BaseCraft

View File

@@ -0,0 +1,47 @@
---Abstract class for handling crafting.
---@class CraftSystem.BaseCraftHandler
---@field craftsByName table<string, CraftSystem.BaseCraft>
---@field craftsByGroup table<CraftSystem.CraftGroup, CraftSystem.BaseCraft[]>
---@field craftsList CraftSystem.BaseCraft[]
---@field learnedCrafts table<string, table<string, CraftSystem.BaseCraft>>
local BaseCraftHandler = {
craftsByName = {},
craftsByGroup = {},
craftsList = {},
learnedCrafts = {},
}
---@param craftName string
---@return CraftSystem.BaseCraft
function BaseCraftHandler:getCraftByName(craftName)
local craft = self.craftsByName[craftName]
assert(craft ~= nil, ('There is no primitive craft named `%s`.'):format(
craftName))
return craft
end
---@param craftGroup CraftSystem.CraftGroup
---@return CraftSystem.BaseCraft[]
function BaseCraftHandler:getCraftsByGroup(craftGroup)
local crafts = self.craftsByGroup[craftGroup]
assert(crafts ~= nil, ('There are no primitive crafts with `%s` group'):format(
craftGroup))
return crafts
end
---@param playerName string
---@return table<string, CraftSystem.BaseCraft>
function BaseCraftHandler:getLearnedCrafts(playerName)
local crafts = self.learnedCrafts[playerName]
assert(crafts ~= nil, ('There is no primitive crafting data for a player named `%s`.'):format(
playerName))
return crafts
end
return BaseCraftHandler

View File

@@ -0,0 +1,237 @@
local getInstance, extend = Class.getInstance, Class.extend
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.BaseCraft
local BaseCraft = require('CraftSystem.BaseCraft')
---@type CraftSystem.ImmersiveCraftCounter
local ImmersiveCraftCounter = require('CraftSystem.ImmersiveCraftCounter')
---Types of immersive stages.
---@class CraftSystem.StagesTypes : table<CraftSystem.ImmersiveCraftStage.Type, CraftSystem.ImmersiveCraftStage>
local stageTypes = {
---@type CraftSystem.ImmersiveCraftStage.TappingStage
tapping = require('CraftSystem.ImmersiveCraftStage.TappingStage'),
}
---Immersive crafting aimed at a more logical process of crafting items.
---@class CraftSystem.ImmersiveCraft : CraftSystem.BaseCraft
---@field startStageName string
---@field triggerItem string
---@field output ItemStackString
---@field stagesByName table<string, CraftSystem.ImmersiveCraftStage>
local ImmersiveCraft = extend(BaseCraft, {})
---Definition table for the `CraftSystem.ImmersiveCraft`.
---
---**Only for EmmyLua.**
---@class CraftSystem.ImmersiveCraftDef : CraftSystem.BaseCraftDef
---@field startStageName string
---@field triggerItem string
---@field output string
---@field stages CraftSystem.ImmersiveCraftStageDef[]
---@param name string
---@param def CraftSystem.ImmersiveCraftDef
---@return CraftSystem.ImmersiveCraft
function ImmersiveCraft:new(name, def)
-- We create a table of crafting stages that the player needs to complete.
---@type table<string, CraftSystem.ImmersiveCraftStage>
local stagesByName = {}
for _, stageDef in ipairs(def.stages) do
-- We get the stage class based on its type.
local StageClass = stageTypes[stageDef.type]
-- Create a stage and add the craft name to the instance.
stageDef.craftName = name
local stage = StageClass:new(stageDef)
-- We add an instance of the stage to the table by name.
stagesByName[stageDef.name] = stage
end
---@type CraftSystem.ImmersiveCraft
local instance = getInstance(self, {})
instance.name = name
instance.group = def.group
instance.startStageName = def.startStageName
instance.triggerItem = def.triggerItem
instance.output = def.output
instance.stagesByName = stagesByName
-- Subscribe to an event that will determine that the player has completed the crafting stage.
Events.subscribe('craft_system:next_immersive_stage:'..name,
---@param eventName string
---@param stage CraftSystem.ImmersiveCraftStage
---@param pos MapPosition
---@param Player Player
function(eventName, stage, pos, Player)
-- From the current stage (which has been completed) we get the name of the next one.
local nextStageName = stage.nextStage
-- If there is no next stage...
if nextStageName == nil then
-- ...we are finishing the craft.
instance:endCraft(pos, Player)
else
-- ...else we start the next stage.
local nextStage = instance.stagesByName[nextStageName]
-- We get a table of temporary data.
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- We are updating the crafting stage in it.
craftData.stageName = nextStageName
-- We save it to the workstation metadata.
Smc.setCraftDataByPos(pos, craftData)
-- We are starting the next stage of crafting.
nextStage:startHandler(pos, Player)
end
end)
return instance
end
---Initialize the start of the immersive crafting process.
---
---Returns `true` if the crafting process was running.
---@param pos MapPosition
---@param player Player
---@param amount integer
---@return boolean
function ImmersiveCraft:startCraft(pos, player, amount)
-- Adding craft to the counter.
-- If crafting has not been added...
if not ImmersiveCraftCounter:addCraft(pos, player) then
-- ...then we don't let the player start a new craft.
core.chat_send_player(player:get_player_name(),
'The limit of simultaneously active crafts has been reached:'..
'complete or cancel active crafts to start a new one')
return false
end
-- We get the material as an ItemStack.
---@type ItemStack
local stack = ItemStack(self.triggerItem)
-- We edit the amount of materials in accordance with the number of crafts being performed.
stack:set_count(stack:get_count() * amount)
-- We get the player's inventory, from where we must take the materials for crafting.
local playerInventory = player:get_inventory()
-- If the player does not have the necessary materials for crafting...
if not playerInventory:contains_item('main', stack) then
-- ...we inform him about this.
core.chat_send_player(player:get_player_name(),
'Not enough materials for crafting')
return false
end
-- If we have the materials, we take them and start initializing the craft.
playerInventory:remove_item('main', stack)
-- We get the first stage of crafting.
local stage = self.stagesByName[self.startStageName]
-- Create a temporary data table for crafting.
---@type ImmersiveCraftData
local craftData = {
craftName = self.name,
stageName = stage.name,
amount = amount,
}
-- We save it to the workstation metadata.
Smc.setCraftDataByPos(pos, craftData)
-- We are starting the first stage of crafting.
stage:startHandler(pos, player)
return true
end
---Complete the immersive crafting process.
---@param pos MapPosition
---@param Player Player
function ImmersiveCraft:endCraft(pos, Player)
-- We get current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- We drop the result of crafting.
local dropPos = vector.new(pos) + vector.new(0, 0.9,0)
for i=1, craftData.amount do
core.item_drop(ItemStack(self.output), nil, dropPos)
end
-- Clearing the temporary data table for crafting, freeing up the work station for new crafts.
Smc.setCraftDataByPos(pos)
-- Remove craft from the counter.
ImmersiveCraftCounter:removeCraft(pos, Player)
end
---Stop the crafting process and free up the workbench.
---@param pos MapPosition
---@param Player Player
function ImmersiveCraft:abortCraft(pos, Player)
-- We get current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- We get the current stage and start the abort process.
local stage = self.stagesByName[craftData.stageName]
stage:abortHandler(pos, Player)
-- Clearing the temporary data table for crafting, freeing up the work station for new crafts.
Smc.setCraftDataByPos(pos)
-- Remove craft from the counter.
ImmersiveCraftCounter:removeCraft(pos, Player)
end
---Returns a human-readable description of the crafting process.
---@return string
function ImmersiveCraft:toString()
-- We get the material as an ItemStack.
---@type ItemStack
local stack = ItemStack(self.triggerItem)
-- We obtain a table of item parameters.
---@type ItemDefinition
local itemDef = stack:get_definition()
-- Let's start writing a description of the craft.
local craftDesc = ('Material: %s x%s\n\n'):format(itemDef._title, stack:get_count())..
'Crafting process:\n'
-- Let's start with the first crafting stage.
---@type string?
local stageName = self.startStageName
local stages = self.stagesByName
-- While we have a stage name...
local count = 1
while stageName ~= nil do
-- We get a crafting stage...
local stage = stages[stageName]
-- ...and we add its description to the list of actions for crafting.
craftDesc = craftDesc..tostring(count)..'. '..stage:toString()..'\n'
-- We also get the name of the next stage.
stageName = stage.nextStage
end
-- If the cycle is interrupted, it means we have processed all the stages.
-- Return the craft description.
return craftDesc
end
return ImmersiveCraft

View File

@@ -0,0 +1,62 @@
local posToString, getSize = core.pos_to_string, table.get_size
local CRAFT_LIMIT_PER_PLAYER = 2
local CRAFT_LIMIT_PER_SERVER = 10
---Designed to keep track of active immersive
---crafts so as not to overload the server.
---
---The counter is individual for each player,
---but the total number of active crafts is also tracked.
---@class CraftSystem.ImmersiveCraftCounter
---@field craftsCountForPlayers table<string, table<string, boolean>>
---@field craftsCountForServer table<string, boolean>
local ImmersiveCraftCounter = {
craftsCountForPlayers = {},
craftsCountForServer = {}
}
---Add craft to the counter.
---
---Returns `false` if the counter is already full.
---@param pos MapPosition
---@param Player Player
---@return boolean
function ImmersiveCraftCounter:addCraft(pos, Player)
local playerName = Player:get_player_name()
if self.craftsCountForPlayers[playerName] == nil then
self.craftsCountForPlayers[playerName] = {}
end
if getSize(self.craftsCountForPlayers[playerName]) >= CRAFT_LIMIT_PER_PLAYER then
return false
end
if getSize(self.craftsCountForServer) >= CRAFT_LIMIT_PER_SERVER then
return false
end
local posString = posToString(pos)
self.craftsCountForPlayers[playerName][posString] = true
self.craftsCountForServer[posString] = true
return true
end
---Remove craft from the counter.
---@param pos MapPosition
---@param Player Player
function ImmersiveCraftCounter:removeCraft(pos, Player)
local playerCrafts = self.craftsCountForPlayers[Player:get_player_name()]
if playerCrafts == nil then
return
end
local posString = posToString(pos)
playerCrafts[posString] = nil
self.craftsCountForServer[posString] = nil
end
-- TODO: сделать сохранение данных во время перезагрузки сервера
return ImmersiveCraftCounter

View File

@@ -0,0 +1,71 @@
local extend = Class.extend
local tableInsert = table.insert
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.BaseCraftHandler
local BaseCraftHandler = require('CraftSystem.BaseCraftHandler')
---@type CraftSystem.ImmersiveCraft
local ImmersiveCraft = require('CraftSystem.ImmersiveCraft')
---A handler for immersive crafting that requires the player to complete
---crafting stages and interact with entities (crafting nodes)
---@class CraftSystem.ImmersiveCraftHandler : CraftSystem.BaseCraftHandler
---@field craftsByTriggerItem table<string, CraftSystem.ImmersiveCraft[]>
---@field getCraftByName fun(self, craftName:string):CraftSystem.ImmersiveCraft
---@field getCraftsByGroup fun(self, craftGroup):CraftSystem.ImmersiveCraft[]
---@field getLearnedCrafts fun(self, playerName):table<string, CraftSystem.ImmersiveCraft>
local ImmersiveCraftHandler = extend(BaseCraftHandler, {
craftsByTriggerItem = {},
})
---Register an immersive crafting experience that requires the player to complete
---one or more crafting stages that involve interaction with entities (crafting nodes)
---@param craftName string
---@param def CraftSystem.ImmersiveCraftDef
function ImmersiveCraftHandler:registerCraft(craftName, def)
assert(self.craftsByName[craftName] == nil, ('A craft named `%s` already exists.'):format(
craftName))
-- We obtain a crafting instance according to the given parameters.
local craft = ImmersiveCraft:new(craftName, def)
-- The craft group to which the craft belongs.
local group = def.group
-- If no craft with this group has been registered before...
if self.craftsByGroup[group] == nil then
-- ...then we create a list for this group.
self.craftsByGroup[group] = {}
end
-- The material from which crafting begins (also known as the starting item).
local triggerItem = def.triggerItem
-- If no crafting for such a starting item has been registered before...
if self.craftsByTriggerItem[triggerItem] == nil then
-- ...then we create a list for this item.
self.craftsByTriggerItem[triggerItem] = {}
end
-- Adding craft to the lists:
self.craftsByName[craftName] = craft
tableInsert(self.craftsByGroup[group], craft)
tableInsert(self.craftsByTriggerItem[triggerItem], craft)
tableInsert(self.craftsList, craft)
end
---Returns a list of crafts that use the given item as a starting material.
---
---Will return `nil` if the item is not used in any craft as a starting item.
---@param triggerItem string
---@return CraftSystem.ImmersiveCraft[]?
function ImmersiveCraftHandler:getCraftsByTriggerItem(triggerItem)
local crafts = self.craftsByTriggerItem[triggerItem]
return crafts
end
return ImmersiveCraftHandler

View File

@@ -0,0 +1,14 @@
---@type Creature
local Creature = Mod.getInfo('smc__core__creature').require('Creature')
---The entity the player interacts with during immersive crafting.
---@class CraftSystem.ImmersiveCraftNode : Creature
local ImmersiveCraftNode = Creature:getExtended({
settings = {
_name = 'craft_system:immersive_craft_node',
_add_mod_name = false,
initial_properties = {},
}
})
return ImmersiveCraftNode

View File

@@ -0,0 +1,91 @@
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.ImmersiveCraftNode
local ImmersiveCraftNode = require('CraftSystem.ImmersiveCraftNode')
---A class that extends `Creature.LuaEntity` to annotate custom fields needed for immersive crafting.
---
---**Only for EmmyLua.**
---@class CraftSystem.ImmersiveCraftNode.LuaTappingNode : Creature.LuaEntity
---The name of the item that the crafting node display.
---@field _item_name ItemStackString
---Sets the entity display of the item. If the item stack was not transferred, `self._item_name` is used.
---@field _set_item fun(self:CraftSystem.ImmersiveCraftNode.LuaTappingNode, itemName:ItemStackString?)
---@field _craft_name string
---@field _stage_name string
---@field _work_station_pos MapPosition
-- A crafting node (entity) that is used in the tapping crafting stage.
local tappingNode = ImmersiveCraftNode:new({
settings = {
_name = 'craft_system:tapping_node',
_add_mod_name = false,
initial_properties = {
visual = 'wielditem',
visual_size = {x=0.4, y=0.4, z=0.4},
--static_save = false,
},
_item_name = '',
_craft_name = '',
_stage_name = '',
_work_station_pos = {},
},
callbacks = {
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
on_activate = function(luaEntity, staticdata, dtime)
-- We obtain a table of initial parameters for the craft node entity.
---@type CraftSystem.ImmersiveCraftStage.TappingNode.InitParams?
local params = core.deserialize(staticdata)
-- We enter parameters into the entity's custom fields.
if params ~= nil then
luaEntity._item_name = params.targetItem
luaEntity._craft_name = params.craftName
luaEntity._stage_name = params.stageName
luaEntity._work_station_pos = params.WorkStationPos
end
-- we set the appearance of the item to be processed on the crafting node.
luaEntity:_set_item(luaEntity._item_name)
-- We add an immortal group to the entity so that it cannot be killed.
luaEntity.object:set_armor_groups({immortal = 1})
end,
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
on_punch = function(luaEntity, puncher, time_from_last_punch, tool_capabilities, dir, damage)
-- We simply trigger the event that the player hits the crafting node, bound to the work station with coordinates.
Events.call(('craft_system:punch_tapping_node:%s:%s'):format(
luaEntity._craft_name, luaEntity._stage_name), luaEntity._work_station_pos, puncher, luaEntity)
return false
end,
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
get_staticdata = function(luaEntity)
---@type CraftSystem.ImmersiveCraftStage.TappingNode.InitParams?
local params = {
targetItem = luaEntity._item_name,
craftName = luaEntity._craft_name,
stageName = luaEntity._stage_name,
WorkStationPos = luaEntity._work_station_pos
}
return core.serialize(params)
end,
---Sets the entity display of the item. If the item stack was not transferred, `self._item_name` is used.
---@param luaEntity CraftSystem.ImmersiveCraftNode.LuaTappingNode
---@param itemName ItemStackString?
_set_item = function(luaEntity, itemName)
-- We change the entity field so that the engine itself displays it as a given item.
luaEntity.object:set_properties({
wield_item = itemName or luaEntity._item_name,
})
end,
}
})
return tappingNode

View File

@@ -0,0 +1,43 @@
local getInstance = Class.getInstance
---@alias CraftSystem.ImmersiveCraftStage.Type 'tapping'
---One of the stages of immersive crafting.
---@class CraftSystem.ImmersiveCraftStage
---@field name string
---@field type CraftSystem.ImmersiveCraftStage.Type
---@field craftName string
---@field startHandler fun(self, pos:Position, Player:Player)
---@field processHandler fun(self, pos:Position, Player:Player)
---@field endHandler fun(self, pos:Position, Player:Player)
---@field abortHandler fun(self, pos:Position, Player:Player)
---@field toString fun(self):string
---@field nextStage string?
---@field returnItems ItemStackString[]?
local ImmersiveCraftStage = {}
---Definition table for the `CraftSystem.ImmersiveCraft`.
---
---**Only for EmmyLua.**
---@class CraftSystem.ImmersiveCraftStageDef
---@field name string
---@field type CraftSystem.ImmersiveCraftStage.Type
---@field craftName string?
---@field nextStage string?
---@field returnItems ItemStackString[]?
---@param def CraftSystem.ImmersiveCraftStageDef
---@return CraftSystem.ImmersiveCraftStage
function ImmersiveCraftStage:new(def)
---@type CraftSystem.ImmersiveCraftStage
local instance = getInstance(self, {})
instance.name = def.name
instance.type = def.type
instance.craftName = def.craftName
instance.nextStage = def.nextStage
instance.returnItems = def.returnItems
return instance
end
return ImmersiveCraftStage

View File

@@ -0,0 +1,184 @@
local extend = Class.extend
local getStageDataByPos, setStageDataByPos = Smc.getStageDataByPos, Smc.setStageDataByPos
local require = Mod.getInfo('smc__core__craft_system').require
---@type CraftSystem.ImmersiveCraftStage
local ImmersiveCraftStage = require('CraftSystem.ImmersiveCraftStage')
---A crafting step that requires the player to hit a crafting node (entity) a certain number of times.
---@class CraftSystem.ImmersiveCraftStage.TappingStage : CraftSystem.ImmersiveCraftStage
---@field targetItem string
---@field clicksNeed string
---@field startHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field processHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field endHandler fun(self:CraftSystem.ImmersiveCraftStage.TappingStage, pos:MapPosition, Player:Player)
---@field toString fun(self:CraftSystem.ImmersiveCraftStage.TappingStage):string
local TappingStage = extend(ImmersiveCraftStage, {})
---Definition table for the `CraftSystem.ImmersiveCraftStage.TappingStage`.
---
---**Only for EmmyLua.**
---@class CraftSystem.ImmersiveCraftStage.TappingStageDef : CraftSystem.ImmersiveCraftStageDef
---@field targetItem string
---@field clicksNeed string
---Data table for transferring various time parameters between calls.
---
---**Only for EmmyLua.**
---@class ImmersiveStageData.TappingStageData : ImmersiveStageData
---How many clicks were made by the player on the entity.
---@field clickCount integer
---Unique identifier of the entity (craft node).
---@field entityGUID string
---@param def CraftSystem.ImmersiveCraftStage.TappingStageDef
function TappingStage:new(def)
---@type CraftSystem.ImmersiveCraftStage.TappingStage
local instance = ImmersiveCraftStage:new(def)
instance.targetItem = def.targetItem
instance.clicksNeed = def.clicksNeed
-- Registering the crafting stage start handler.
instance.startHandler = function(tappingStage , pos, Player)
-- We determine the coordinate where we will create the crafting node (entity).
local entityPos = vector.new(pos) + vector.new(0,0.8,0)
-- We create a table of initial parameters that we will pass to the entity.
---@class CraftSystem.ImmersiveCraftStage.TappingNode.InitParams
local params = {
targetItem = tappingStage.targetItem,
craftName = tappingStage.craftName,
stageName = tappingStage.name,
WorkStationPos = pos,
}
-- Adding an entity to the world.
local obj = core.add_entity(entityPos, 'craft_system:tapping_node', core.serialize(params))
-- If the entity was not returned, something went wrong.
if obj == nil then
return
end
-- Create a temporary table of crafting stage data.
---@type ImmersiveStageData.TappingStageData
local stageData = {
clickCount = 0,
entityGUID = obj:get_guid()
}
-- Saving temporary data in work station metadata.
setStageDataByPos(pos, stageData)
end
-- Registering the crafting stage process handler.
-- Called when a player clicks on a crafting node (entity).
instance.processHandler = function(tappingStage, pos, Player)
-- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData?
local stageData = getStageDataByPos(pos)
assert(stageData ~= nil, 'Immersive stage data is empty.')
-- Increasing the click counter
local clickCount = stageData.clickCount
clickCount = clickCount + 1
-- If the number of clicks is greater than required to complete the step...
if clickCount >= tappingStage.clicksNeed then
-- ...we are completing the stage.
tappingStage:endHandler(pos, Player)
else
-- ...else we save the number of clicks in the temporary data table.
stageData.clickCount = clickCount
Smc.setStageDataByPos(pos, stageData)
end
end
-- Registering the crafting stage end handler.
instance.endHandler = function(tappingStage, pos, Player)
-- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData?
local stageData = getStageDataByPos(pos)
assert(stageData ~= nil, 'Immersive stage data is empty.')
-- We get the entity object.
local entity = Smc.getObjectByGUID(stageData.entityGUID)
assert(entity ~= nil, 'The entity for immersive crafting is nil.')
-- Removing an entity from the world.
entity:remove()
-- We trigger an event that the crafting stage has been completed.
Events.call('craft_system:next_immersive_stage:'..tappingStage.craftName, tappingStage, pos, Player)
end
-- Registering the aborting the crafting process handler.
---@param tappingStage CraftSystem.ImmersiveCraftStage.TappingStage
instance.abortHandler = function(tappingStage, pos, Player)
-- We receive current data on crafting.
---@type ImmersiveCraftData?
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
-- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData?
local stageData = craftData.stageData
assert(stageData ~= nil, 'Immersive stage data is empty.')
-- We get the entity object.
local entity = Smc.getObjectByGUID(stageData.entityGUID)
assert(entity ~= nil, 'The entity for immersive crafting is nil.')
-- Removing an entity from the world.
entity:remove()
-- We drop the item as it was before processing.
local dropPos = vector.new(pos)+vector.new(0, 0.9,0)
for i=1, craftData.amount do
core.item_drop(ItemStack(tappingStage.targetItem), nil, dropPos)
end
end
-- Returns a human-readable description of the crafting stage.
instance.toString = function(tappingStage)
local stageDesc = ('Tapping x%s'):format(tappingStage.clicksNeed)
return stageDesc
end
-- Subscribe to an event that means the player hit the entity.
Events.subscribe(('craft_system:punch_tapping_node:%s:%s'):format(instance.craftName, instance.name),
---@param craftNode LuaEntity
function(eventName, pos, Player, craftNode)
-- DRAFT START:
-- Creating particles
for i=0, 10 do
core.add_particle({
pos = vector.new(pos)+vector.new(0,0.5,0),
velocity = {x=math.random(-1,1), y=4, z=math.random(-1,1)},
acceleration = {x=0, y=-9.8, z=0},
expirationtime = 2,
collision_removal = true,
node = {name=instance.targetItem}
})
end
-- Making the entity shake (silly method :P).
craftNode.object:set_rotation(vector.new(0.01,0.1,0.01))
core.after(0.1, function() craftNode.object:set_rotation(vector.new(-0.01,-0.1,-0.01))end)
core.after(0.2, function() craftNode.object:set_rotation(vector.new(0,0,0))end)
-- DRAFT END
-- Calling the crafting stage process handler.
instance:processHandler(pos, Player)
end)
return instance
end
-- Registering an entity for immersive tapping crafting.
require('CraftSystem.ImmersiveCraftNode.tappingNode')
return TappingStage

View File

@@ -0,0 +1,39 @@
local getInstance, extend = Class.getInstance, Class.extend
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.BaseCraft
local BaseCraft = require('CraftSystem.BaseCraft')
---@class CraftSystem.PrimitiveCraft : CraftSystem.BaseCraft
---@field output string
---@field recipe CraftSystem.CraftRecipe
---@field returnItems ItemStackString[]
local PrimitiveCraft = extend(BaseCraft, {})
---Definition table for the `CraftSystem.PrimitiveCraft`.
---
---**Only for EmmyLua.**
---@class CraftSystem.PrimitiveCraftDef : CraftSystem.BaseCraftDef
---@field output string
---@field recipe CraftSystem.CraftRecipe
---@field returnItems ItemStackString[]
---@param name string
---@param def CraftSystem.PrimitiveCraftDef
---@return CraftSystem.PrimitiveCraft
function PrimitiveCraft:new(name, def)
---@type CraftSystem.PrimitiveCraft
local instance = getInstance(self, {
name = name,
group = def.group,
output = def.output,
recipe = def.recipe,
returnItems = def.returnItems or {}
})
return instance
end
return PrimitiveCraft

View File

@@ -0,0 +1,42 @@
local extend = Class.extend
local tableInsert = table.insert
local modInfo = Mod.getInfo('smc__core__craft_system')
local require = modInfo.require
---@type CraftSystem.BaseCraftHandler
local BaseCraftHandler = require('CraftSystem.BaseCraftHandler')
---@type CraftSystem.PrimitiveCraft
local PrimitiveCraft = require('CraftSystem.PrimitiveCraft')
---A primitive crafting processor that doesn't require much interaction and provides
---simple crafting based on a recipe-result scheme.
---@class CraftSystem.PrimitiveCraftHandler : CraftSystem.BaseCraftHandler
---@field getCraftByName fun(self, craftName:string):CraftSystem.PrimitiveCraft
---@field getCraftsByGroup fun(self, craftGroup):CraftSystem.PrimitiveCraft[]
---@field getLearnedCrafts fun(self, playerName):table<string, CraftSystem.PrimitiveCraft>
local PrimitiveCraftHandler = extend(BaseCraftHandler, {})
---Register a primitive craft that does not require special interaction.
---@param craftName string
---@param def CraftSystem.PrimitiveCraftDef
function PrimitiveCraftHandler:registerCraft(craftName, def)
assert(self.craftsByName[craftName] == nil, ('A craft named `%s` already exists.'):format(
craftName))
local craft = PrimitiveCraft:new(craftName, def)
local group = def.group
if self.craftsByGroup[group] == nil then
self.craftsByGroup[group] = {}
end
self.craftsByName[craftName] = craft
tableInsert(self.craftsByGroup[group], craft)
tableInsert(self.craftsList, craft)
end
return PrimitiveCraftHandler

View File

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

View File

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

View File

@@ -0,0 +1,109 @@
local getInstance, extend = Class.getInstance, Class.extend
local tableCopy, tableMerge = table.copy, table.merge
---@class Creature
---@field entityDef Creature.CreatureDefinition
---@field luantiDef EntityDefinition
---@field defaultDef Creature.CreatureDefinition
local Creature = {
defaultDef = {
settings = {
_name = '',
_add_mod_name = true,
initial_properties = {},
},
callbacks = {}
}
}
---@param entityDef Creature.CreatureDefinition
---@return EntityDefinition
local function entityDefToLuantiDef(entityDef)
entityDef = tableCopy(entityDef)
local s = entityDef.settings
local c = entityDef.callbacks or {}
---@type EntityDefinition
local luantiDef = tableMerge(s, c)
return luantiDef
end
---@param entityDef Creature.CreatureDefinition
---@return Creature
function Creature:new(entityDef)
-- Adding default parameters.
---@type Creature.CreatureDefinition
entityDef = tableMerge(entityDef, self.defaultDef, true)
-- The callback table may not be specified.
if entityDef.callbacks == nil then
---@type Creature.Callbacks
entityDef.callbacks = {}
end
local s = entityDef.settings
local c = entityDef.callbacks
-- Add the short mod name prefix to the entity name.
if s._add_mod_name then
s._name = Mod.getInfo().shortName .. ':' .. s._name
end
local onActivate = c.on_activate or function() end
-- We rewrite the entity initialization function so that custom fields
-- can be passed to it directly via `core.add_entity(pos, name, [staticdata])`.
c.on_activate = function(luaEntity, staticdata, dtime)
local initCustomFields = {}
if staticdata and staticdata ~= '' then
initCustomFields = core.deserialize(staticdata) or {}
end
-- We reset the fields that should not be overwritten.
initCustomFields.name = nil
initCustomFields.object = nil
---@type LuaEntity
self = tableMerge(self, initCustomFields)
-- If an initialization callback was specified for the entity, then we call it.
if c.on_activate ~= nil then
onActivate(luaEntity, staticdata, dtime)
end
end
---@type Creature
local instance = getInstance(self, {})
local luantiDef = entityDefToLuantiDef(entityDef)
instance.entityDef = entityDef
instance.luantiDef = luantiDef
core.register_entity(':'..s._name, luantiDef)
return instance
end
---Allows you to create a child class of an entity by specifying
---default parameters that will be added to the entity's parameters
---when an instance is received.
---@param defaultDef Creature.CreatureDefinition
---@return Creature
function Creature:getExtended(defaultDef)
-- Adding default parameters.
---@type Creature.CreatureDefinition
defaultDef = tableMerge(self.defaultDef, defaultDef)
---@type Creature
local ChildClass = extend(self, {
defaultDef = defaultDef,
})
return ChildClass
end
return Creature

View File

@@ -0,0 +1,72 @@
---@class Creature.Callbacks
local Callbacks = {}
---Called when the object is instantiated.
--- * `dtime_s` is the time passed since the object was unloaded,
---which can be used for updating the entity state.
---@type fun(self:LuaEntity, staticdata:string, dtime_s:number)?
Callbacks.on_activate = nil
---Called when the object is about to get removed or unloaded.
--- * `removal`: boolean indicating whether the object is about to get removed.
--- Calling `object:remove()` on an active object will call this with `removal=true`.
--- The mapblock the entity resides in being unloaded will call this with `removal=false`.
---
---Note that this won't be called if the object hasn't been activated in the first place.
---In particular, `core.clear_objects({mode = "full"})` won't call this,
---whereas `core.clear_objects({mode = "quick"})` might call this.
---@type fun(self:LuaEntity, removal:boolean)?
Callbacks.on_deactivate = nil
---Called on every server tick, after movement and collision processing.
--- * `dtime`: elapsed time since last call
--- * `s`: table with collision info (only available if `physical=true`)
---@type fun(self:LuaEntity, dtime:number, moveresult:table)? -- TODO: дописать более точный тип moveresult
Callbacks.on_step = nil
---Called when somebody punches the object.
---Note that you probably want to handle most punches using the automatic armor group system.
--- * `puncher`: an `ObjectRef `(can be `nil`)
--- * `time_from_last_punch`: Meant for disallowing spamming of clicks (can be `nil`).
--- * `tool_capabilities`: capability table of used item
--- * `dir`: unit vector of direction of punch. Always defined. Points from the puncher to the punched.
--- * `damage``: damage that will be done to entity.
---
---Can return `true` to prevent the default damage mechanism.
---@type (fun(self:LuaEntity, puncher:ObjectRef|Player|nil, time_from_last_punch:number|nil, tool_capabilities:table|nil, dir:vector, damage:number):boolean)? -- TODO: дописать более точный тип для tool_capabilities
Callbacks.on_punch = nil
---Called when the object dies.
--- * `killer`: an `ObjectRef` (can be `nil`)
---@type fun(self:LuaEntity, killer:ObjectRef|Player|nil)?
Callbacks.on_death = nil
---Called when `clicker` pressed the 'place/use' key while
---pointing to the object (not necessarily an actual rightclick)
--- * `clicker`: an `ObjectRef` (may or may not be a player)
---@type fun(self:LuaEntity, clicker:ObjectRef|Player)?
Callbacks.on_rightclick = nil
---Called after another object is attached to this object.
--- * `child`: an `ObjectRef` of the child
---@type fun(self:LuaEntity, child:ObjectRef)?
Callbacks.on_attach_child = nil
---Called after another object has detached from this object.
--- * `child`: an `ObjectRef` of the child
---@type fun(self:LuaEntity, child:ObjectRef)?
Callbacks.on_detach_child = nil
---Called after detaching from another object.
--- * `parent`: an ObjectRef from where it got detached
---
---**Note**: this is also called before removal from the world.
---@type fun(self:LuaEntity, parent)?
Callbacks.on_detach = nil
---Should return a string that will be passed to `on_activate` when the object
---is instantiated the next time.
---@type (fun(self:LuaEntity):string)?
Callbacks.get_staticdata = nil
return Callbacks

View File

@@ -0,0 +1,6 @@
---@class Creature.CreatureDefinition
---@field settings Creature.Settings
---@field callbacks Creature.Callbacks?
local CreatureDefinition = {}
return CreatureDefinition

View File

@@ -0,0 +1,9 @@
---A class that extends `LuaEntity` to annotate custom fields.
---
---**Only for EmmyLua.**
---@class Creature.LuaEntity : LuaEntity
---@field _name string
---@field _add_mod_name boolean
local LuaEntity = {}
return LuaEntity

View File

@@ -0,0 +1,14 @@
---@class Creature.Settings
local Settings = {}
---Registration name for the entity. Must be unique.
---@type string
Settings._name = nil
---Whether to add the mod name to the settings._name. Default: `true`
Settings._add_mod_name = nil
---@type ObjectProperties
Settings.initial_properties = nil
return Settings

View File

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

View File

@@ -1,3 +1,6 @@
local tableConcat, tableKeyValueList, tableInsert
= table.concat, table.key_value_list, table.insert
local getInstance = Class.getInstance
---@class Formspec
@@ -107,25 +110,26 @@ function Formspec:new(def)
return instance
end
---TODO: описание
---Returns a string specifying the form parameters:
---`version`, `size`, `position`, `anchor`, `padding`, `no_prepend`, `real_coordinates`, `allowClose`.
---@return string
function Formspec:getParams()
return self.params
end
---TODO: описание
---Returns a string containing all elements registered in the form.
---@return string
function Formspec:getElements()
return self.elements
end
---TODO: описание
---Returns a formspec string that is a form definition for Luanti.
---@return string
function Formspec:toString()
return self:getParams()..self:getElements()
end
---TODO: описание
---Adds an element to the list of form elements.
---@param element string
function Formspec:addElement(element)
self.elements = self.elements..element
@@ -138,13 +142,15 @@ end
---@param container Formspec
---@param x number
---@param y number
---@return Formspec
function Formspec:container(container, x, y)
local element = ('container[%s,%s]'):format(x, y)..container:getElements()..'container_end[]'
self:addElement(element)
return self
end
---Start of a scroll_container block. All contained elements will
---Create 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
@@ -159,13 +165,16 @@ end
---@param scrollbarName string
---@param orientation 'vertical'|'horizontal'
---@param scrollFactor number? Defaults to 0.1.
---@param contentPadding string? TODO: разобраться, что тут
---@param contentPadding number? In formspec coordinate units. If specified, the scrollbar properties `max` and `thumbsize` are calculated
--- automatically based on the content size plus `content padding` at the end of the container. `min` is set to `0`.
---@return Formspec
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)
return self
end
---@alias Formspec.ListDef {inventoryLocation:string, listName:string, x:number, y:number, w:number, h:number,startingItemIndex:number}
@@ -185,29 +194,35 @@ end
---@param w number Are in inventory slots, not in coordinates.
---@param h number Are in inventory slots, not in coordinates.
---@param startingItemIndex number? The index of the first (upper-left) item to draw. Indices start at `0`. Default is `0`.
---@return Formspec
function Formspec:list(inventoryLocation, listName, x, y, w, h, startingItemIndex)
local element = ('list[%s;%s;%s,%s;%s,%s;%s]'):format(
inventoryLocation, listName, x, y, w, h,startingItemIndex or '')
self:addElement(element)
return self
end
---TODO: немного отличается от листринга луанти, так что надо дописать подробности
---Creates and appends a list of `listring[<inventory location>;<list name>]` items based on the passed inventory list.
---
---**Elements:** `listring[<inventory location>;<list name>]` or `listring[]`
---@param lists [string, string][]? List of looping lists in the format `[inventory location, list name]`
---@param lists [string, string][]? List of looping lists in the format `[inventory location, list name]`. If `nil`, it will be added `listring[]`.
---@return Formspec
function Formspec:listring(lists)
if lists == nil then
self:addElement('listring[]')
return self
end
local element = ''
for list in lists do
for _, list in pairs(lists) do
element = element..('listring[%s;%s]'):format(list[1], list[2])
end
self:addElement(element)
return self
end
---The following descriptions are allowed:
@@ -219,6 +234,7 @@ end
---@param slotBorder ColorString?
---@param tooltipBgcolor ColorString?
---@param tooltipFontcolor ColorString?
---@return Formspec
function Formspec:listColors(slotBackgroundNormal, slotBackgroundHover, slotBorder, tooltipBgcolor, tooltipFontcolor)
local element
@@ -234,6 +250,7 @@ function Formspec:listColors(slotBackgroundNormal, slotBackgroundHover, slotBord
end
self:addElement(element)
return self
end
---Adds tooltip for an element.
@@ -243,11 +260,13 @@ end
---@param tooltipText string
---@param bgcolor ColorString?
---@param fontcolor ColorString?
---@return Formspec
function Formspec:tooltipForElement(elementName, tooltipText, bgcolor, fontcolor)
local element = ('tooltip[%s;%s;%s;%s]'):format(
elementName, tooltipText, bgcolor or '', fontcolor or '')
self:addElement(element)
return self
end
---Adds tooltip for an area. Other tooltips will take priority when present.
@@ -260,11 +279,13 @@ end
---@param tooltipText string
---@param bgcolor ColorString?
---@param fontcolor ColorString?
---@return Formspec
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)
return self
end
---Show an image.
@@ -276,11 +297,13 @@ end
---@param h number
---@param textureName string
---@param middle boolean? Makes the image render in 9-sliced mode and defines the middle rect.
---@return Formspec
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)
return self
end
---Show an animated image. The image is drawn like a "vertical_frames" tile animation
@@ -296,6 +319,7 @@ end
---@param frameDuration number
---@param frameStart number
---@param middle boolean? Makes the image render in 9-sliced mode and defines the middle rect.
---@return Formspec
function Formspec:animatedImage(x, y, w, h, textureName, frameCount, frameDuration, frameStart, middle)
if middle == nil then
middle = false
@@ -305,6 +329,7 @@ function Formspec:animatedImage(x, y, w, h, textureName, frameCount, frameDurati
x, y, w, h, textureName, frameCount, frameDuration, frameStart, middle)
self:addElement(element)
return self
end
---Show a mesh model.
@@ -322,11 +347,13 @@ end
---@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.
---@return Formspec
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)
return self
end
---Show an inventory image of registered item/node.
@@ -337,11 +364,13 @@ end
---@param w number
---@param h number
---@param itemName string
---@return Formspec
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)
return self
end
---Sets background color of formspec.
@@ -356,11 +385,13 @@ end
---@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.
---@return Formspec
function Formspec:bgcolor(bgcolor, fullscreen, fbgcolor)
local element = ('bgcolor[%s;%s;%s]'):format(
bgcolor, fullscreen or '', fbgcolor or '')
self:addElement(element)
return self
end
---Example for formspec 8x4 in 16x resolution: image shall be sized 8 times 16px times 4 times 16px.
@@ -374,6 +405,7 @@ end
---@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)
---@return Formspec
function Formspec:background(x, y, w, h, textureName, autoClip)
local element
@@ -386,6 +418,7 @@ function Formspec:background(x, y, w, h, textureName, autoClip)
end
self:addElement(element)
return self
end
---9-sliced background. See https://en.wikipedia.org/wiki/9-slice_scaling
@@ -406,11 +439,13 @@ end
--- Negative x2 and y2 values will be added to the width and height of
--- the texture, allowing it to be used as the distance from the far end.
--- * All numbers in middle are integers.
---@return Formspec
function Formspec:background9(x, y, w, h, textureName, autoClip, middle)
local element = ('background9[%s,%s;%s,%s;%s;%s]'):format(
x, y, w, h, textureName, autoClip, middle)
self:addElement(element)
return self
end
---Textual password style field; will be sent to server when a button is clicked
@@ -427,11 +462,13 @@ end
---@param h number
---@param name string Is the name of the field as returned in `fields to on_receive_fields`.
---@param label string? If not blank, will be text printed on the top left above the field.
---@return Formspec
function Formspec:pwdfield(x, y, w, h, name, label)
local element = ('pwdfield[%s,%s;%s,%s;%s;%s]'):format(
x, y, w, h, name, label or '')
self:addElement(element)
return self
end
---Textual field; will be sent to server when a button is clicked.
@@ -451,11 +488,13 @@ end
---@param default string? is the default value of the field default may contain variable references
--- such as `${text}` which will fill the value from the metadata value text.
--- Note: no extra text or more than a single variable is supported ATM.
---@return Formspec
function Formspec:field(x, y, w, h, name, label, default)
local element = ('field[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, name, label or '', default or '')
self:addElement(element)
return self
end
---Textual field; will be sent to server when a button is clicked.
@@ -472,11 +511,13 @@ end
---@param default string? is the default value of the field default may contain variable references
--- such as `${text}` which will fill the value from the metadata value text.
--- Note: no extra text or more than a single variable is supported ATM.
---@return Formspec
function Formspec:fieldWithoutPos(name, label, default)
local element = ('field[%s,%s;%s,%s;%s;%s;%s]'):format(
name, label or '', default or '')
self:addElement(element)
return self
end
@@ -488,11 +529,13 @@ end
---@param enterAfterEdit boolean? If is true, pressing the "Done" button in the Android
--- text input dialog will simulate an Enter keypress. Defaults to `false`
--- when not specified (i.e. no tag for a field).
---@return Formspec
function Formspec:fieldEnterAfterEdit(name, enterAfterEdit)
local element = ('field_enter_after_edit[%s;%s]'):format(
name, enterAfterEdit or false)
self:addElement(element)
return self
end
---
@@ -500,11 +543,13 @@ end
---@param name string Is the name of the field.
---@param closeOnEnter boolean? If` is false, pressing Enter in the field will submit the form but not close it.
--- Defaults to true when not specified (i.e. no tag for a field).
---@return Formspec
function Formspec:fieldCloseOnEnter(name, closeOnEnter)
local element = ('field_enter_after_edit[%s;%s]'):format(
name, closeOnEnter or false)
self:addElement(element)
return self
end
---Same as text fields, but with multi-line input.
@@ -524,11 +569,13 @@ end
---@param default string? is the default value of the field default may contain variable references
--- such as `${text}` which will fill the value from the metadata value text.
--- Note: no extra text or more than a single variable is supported ATM.
---@return Formspec
function Formspec:textArea(x, y, w, h, name, label, default)
local element = ('textarea[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, name or '', label or '', default or '')
self:addElement(element)
return self
end
---The label formspec element displays the text set in `label` at the specified position.
@@ -542,11 +589,13 @@ end
---@param x number
---@param y number
---@param label string
---@return Formspec
function Formspec:label(x, y, label)
local element = ('label[%s,%s;%s]'):format(
x, y, label)
self:addElement(element)
return self
end
---The "area label" formspec element displays the text set in label at the specified position and size.
@@ -560,11 +609,13 @@ end
---@param w number
---@param h number
---@param label string
---@return Formspec
function Formspec:areaLabel(x, y, w, h, label)
local element = ('label[%s,%s;%s,%s;%s]'):format(
x, y, w, h, label)
self:addElement(element)
return self
end
---Displays a static formatted text with hyperlinks.
@@ -577,11 +628,13 @@ end
---@param h number
---@param name string Is the name of the field as returned in fields to `on_receive_fields` in case of action in text.
---@param text string Is the formatted text using `Markup Language` described below.
---@return Formspec
function Formspec:hypertext(x, y, w, h, name, text)
local element = ('hypertext[%s,%s;%s,%s;%s;%s]'):format(
x, y, w, h, name, text)
self:addElement(element)
return self
end
---Textual label drawn vertically.
@@ -590,11 +643,13 @@ end
---@param x number
---@param y number
---@param label string
---@return Formspec
function Formspec:vertlabel(x, y, label)
local element = ('vertlabel[%s,%s;%s]'):format(
x, y, label)
self:addElement(element)
return self
end
---Clickable button. When clicked, fields will be sent. With the old coordinate system,
@@ -608,11 +663,13 @@ end
---@param h number
---@param name string
---@param label string? Is the text on the button
---@return Formspec
function Formspec:button(x, y, w, h, name, label)
local element = ('button[%s,%s;%s,%s;%s;%s]'):format(
x, y, w, h, name, label or '')
self:addElement(element)
return self
end
---Clickable button. When clicked, fields will be sent and the user will be given
@@ -628,11 +685,13 @@ end
---@param name string
---@param label string? Is the text on the button
---@param url string Must be a valid web URL, starting with `http://` or `https://`.
---@return Formspec
function Formspec:buttonUrl(x, y, w, h, name, label, url)
local element = ('button_url[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, name, label or '', url)
self:addElement(element)
return self
end
---Clickable image button. When clicked, fields will be sent.
@@ -652,6 +711,7 @@ end
---@param pressedTextureName string Is the filename of an image on pressed state.
---@param noclip boolean? Means the image button doesn't need to be within specified formsize. Default: `true`
---@param drawborder boolean? Draw button border or not. Default `false`
---@return Formspec
function Formspec:imageButton(x, y, w, h, textureName, name, label, pressedTextureName, noclip, drawborder)
local element
@@ -664,9 +724,10 @@ function Formspec:imageButton(x, y, w, h, textureName, name, label, pressedTextu
end
self:addElement(element)
return self
end
---TODO: описание
---Clickable item image button. When clicked, fields will be sent.
---
---**Element:** `item_image_button[<X>,<Y>;<W>,<H>;<item name>;<name>;<label>]`
---@param x number
@@ -676,11 +737,13 @@ end
---@param itemName string
---@param name string
---@param label string?
---@return Formspec
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)
return self
end
---When clicked, fields will be sent and the form will quit.
@@ -693,11 +756,13 @@ end
---@param h number
---@param name string
---@param label string? Is the text on the button
---@return Formspec
function Formspec:buttonExit(x, y, w, h, name, label)
local element = ('button_exit[%s,%s;%s,%s;%s;%s]'):format(
x, y, w, h, name, label or '')
self:addElement(element)
return self
end
---When clicked, fields will be sent and the form will quit.
@@ -711,11 +776,13 @@ end
---@param name string
---@param label string? Is the text on the button
---@param url string Must be a valid web URL, starting with `http://` or `https://`.
---@return Formspec
function Formspec:buttonUrlExit(x, y, w, h, name, label, url)
local element = ('button_url_exit[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, name, label or '', url)
self:addElement(element)
return self
end
---When clicked, fields will be sent and the form will quit.
@@ -729,11 +796,13 @@ end
---@param textureName string Is the filename of an image.
---@param name string
---@param label string?
---@return Formspec
function Formspec:imageButtonExit(x, y, w, h, textureName, name, label)
local element = ('image_button_exit[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, textureName, name, label or '')
self:addElement(element)
return self
end
---Scrollable item list showing arbitrary text elements.
@@ -749,18 +818,20 @@ end
--- If you want a listelement to start with "#" write "##"
---@param selectedIdx number? Index to be selected within textlist.
---@param transparent boolean? Draw transparent background.
---@return Formspec
function Formspec:textlist(x, y, w, h, name, listElements, selectedIdx, transparent)
local element
if selectedIdx == nil and transparent == nil then
element = ('textlist[%s,%s;%s,%s;%s;%s]'):format(
x, y, w, h, name, table.concat(listElements, ','))
x, y, w, h, name, tableConcat(listElements, ','))
else
element = ('textlist[%s,%s;%s,%s;%s;%s;%s;%s]'):format(
x, y, w, h, name, table.concat(listElements, ','), selectedIdx or '', transparent or '')
x, y, w, h, name, tableConcat(listElements, ','), selectedIdx or '', transparent or '')
end
self:addElement(element)
return self
end
---Show a tabheader at specific position (ignores formsize).
@@ -778,21 +849,23 @@ end
---@param currentTab number?
---@param transparent boolean?
---@param drawBorder boolean?
---@return Formspec
function Formspec:tabheader(x, y, w, h, name, listCaptions, currentTab, transparent, drawBorder)
local element
if w == nil and h == nil then
element = ('tabheader[%s,%s;%s;%s;%s;%s;%s]'):format(
x, y, name, table.concat(listCaptions, ','), currentTab or '', transparent or '', drawBorder or '')
x, y, name, tableConcat(listCaptions, ','), currentTab or '', transparent or '', drawBorder or '')
elseif w == nil then
element = ('tabheader[%s,%s;%s;%s;%s;%s;%s;%s]'):format(
x, y, name, h, table.concat(listCaptions, ','), currentTab or '', transparent or '', drawBorder or '')
x, y, name, h, tableConcat(listCaptions, ','), currentTab or '', transparent or '', drawBorder or '')
else
element = ('tabheader[%s,%s;%s,%s;%s;%s,%s;%s;%s;%s]'):format(
x, y, name, w, h, table.concat(listCaptions, ','), currentTab or '', transparent or '', drawBorder or '')
x, y, name, w, h, tableConcat(listCaptions, ','), currentTab or '', transparent or '', drawBorder or '')
end
self:addElement(element)
return self
end
---Simple colored box.
@@ -806,11 +879,13 @@ end
--- the box will be semitransparent. If the color is not specified, the box will
--- use the options specified by its style. If the color is specified, all styling
--- options will be ignored.
---@return Formspec
function Formspec:box(x, y, w, h, color)
local element = ('box[%s,%s;%s,%s;%s]'):format(
x, y, w, h, color)
self:addElement(element)
return self
end
---Show a dropdown field
@@ -831,18 +906,20 @@ end
---@param indexEvent boolean? (optional, allowed parameter since formspec version 4): Specifies the event field value for selected items.
--- * `true`: Selected item index
--- * `false` (default): Selected item value
---@return Formspec
function Formspec:dropdown(x, y, w, h, name, listItems, selectedIdx, indexEvent)
local element
if h == nil then
element = ('dropdown[%s,%s;%s;%s;%s;%s;%s]'):format(
x, y, w, name, table.concat(listItems, ','), selectedIdx or '', indexEvent or '')
x, y, w, name, tableConcat(listItems, ','), selectedIdx or '', indexEvent or '')
else
element = ('dropdown[%s,%s;%s,%s;%s;%s;%s;%s]'):format(
x, y, w, h, name, table.concat(listItems, ','), selectedIdx or '', indexEvent or '')
x, y, w, h, name, tableConcat(listItems, ','), selectedIdx or '', indexEvent or '')
end
self:addElement(element)
return self
end
---Show a checkbox.
@@ -856,11 +933,13 @@ end
---@param name string Fieldname data is transferred to Lua
---@param label string? To be shown left of checkbox
---@param selected boolean?
---@return Formspec
function Formspec:checkbox(x, y, name, label, selected)
local element = ('checkbox[%s,%s;%s;%s;%s]'):format(
x, y, name, label or '', selected or '')
self:addElement(element)
return self
end
---Show a scrollbar using options defined by the previous `scrollbaroptions[]`
@@ -873,11 +952,13 @@ end
---@param orientation 'vertical'|'horizontal'
---@param name string
---@param value number?
---@return Formspec
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)
return self
end
---@alias Formspec.scrollbarOptionsDef {min:integer?, max:integer?, smallstep:integer?, largestep:integer?, thumbsize:integer?, arrows:'show'|'hide'|'default'|nil}
@@ -902,11 +983,13 @@ end
---
---**Element**: `scrollbaroptions[opt1;opt2;...]`
---@param options Formspec.scrollbarOptionsDef
---@return Formspec
function Formspec:scrollbarOptions(options)
local element = ('scrollbaroptions[%s]'):format(
table.key_value_list(options, ';'))
tableKeyValueList(options, ';'))
self:addElement(element)
return self
end
---Show scrollable table using options defined by the previous `tableoptions[]`.
@@ -922,11 +1005,13 @@ end
---@param name string Fieldname sent to server on row select or double-click
---@param listCells string[] Cells contents given in row-major order.
---@param selectedIdx number? Index of row to be selected within table (first row = `1`)
---@return Formspec
function Formspec:table(x, y, w, h, name, listCells, selectedIdx)
local element = ('table[%s,%s;%s,%s;%s;%s;%s]'):format(
x, y, w, h, name, table.concat(listCells, ','), selectedIdx or '')
x, y, w, h, name, tableConcat(listCells, ','), selectedIdx or '')
self:addElement(element)
return self
end
---@alias Formspec.tableOptionsDef {color:ColorString?, background:ColorString?, border:boolean?, highlight:ColorString?, highlight_text:ColorString?, opendepth:integer?}
@@ -948,11 +1033,13 @@ end
---
---**Element:** `tableoptions[<opt 1>;<opt 2>;...]`
---@param options Formspec.tableOptionsDef
---@return Formspec
function Formspec:tableOptions(options)
local element = ('tableoptions[%s]'):format(
table.key_value_list(options, ';'))
tableKeyValueList(options, ';'))
self:addElement(element)
return self
end
---@alias Formspec.tableColumnsTypes 'text'|'image'|'color'|'indent'|'tree'
@@ -986,29 +1073,77 @@ end
---
---**Element**: `tablecolumns[<type 1>,<opt 1a>,<opt 1b>,...;<type 2>,<opt 2a>,<opt 2b>;...]`
---@param columns Formspec.tableColumn[]
---@return Formspec
function Formspec:tablecolumns(columns)
local columnsStrings = {}
for _, column in pairs(columns) do
table.insert(columnsStrings,
column.type..','..table.key_value_list(column.options,',')
tableInsert(columnsStrings,
column.type..','..tableKeyValueList(column.options,',')
)
end
local element = ('tablecolumns[%s]'):format(
table.key_value_list(columnsStrings, ';'))
tableKeyValueList(columnsStrings, ';'))
self:addElement(element)
return self
end
---TODO
function Formspec:style()
---Set the style for the element(s) matching `selector` by name.
---
---`state` is a list of states separated by the `+` character.
--- * If a state is provided, the style will only take effect when the element is in that state.
--- * All provided states must be active for the style to apply.
---
---**Note**: this must be before the element is defined.
---
---See [Styling Formspecs](https://api.luanti.org/formspec/#styling-formspecs).
---
---**Element**: `style[<selector 1>,<selector 2>,...;<prop1>;<prop2>;...]`
---@param selectors string|string[] Can be one of:
--- * `<name>` - An element name. Includes `*`, which represents every element.
--- * `<name>:<state>` - An element name, a colon, and one or more states.
---@param properties string[] TODO: добавить тут алиас, который бы содержал доступные настройки
---@return Formspec
function Formspec:style(selectors, properties)
if type(selectors) == 'string' then
selectors = { selectors }
end
local element = ('style[%s;%s]'):format(
tableConcat(selectors, ','), tableConcat(properties, ','))
self:addElement(element)
return self
end
---TODO
function Formspec:styleType()
---Set the style for the element(s) matching `selector` by type.
---
---`state` is a list of states separated by the `+` character.
--- * If a state is provided, the style will only take effect when the element is in that state.
--- * All provided states must be active for the style to apply.
---
---**Note**: this must be before the element is defined.
---
---See [Styling Formspecs](https://api.luanti.org/formspec/#styling-formspecs).
---
---**Element**: `style[<selector 1>,<selector 2>,...;<prop1>;<prop2>;...]`
---@param selectors string|string[] Can be one of:
--- * `<name>` - An element name. Includes `*`, which represents every element.
--- * `<name>:<state>` - An element name, a colon, and one or more states.
---@param properties string[] TODO: добавить тут алиас, который бы содержал доступные настройки
---@return Formspec
function Formspec:styleType(selectors, properties)
if type(selectors) == 'string' then
selectors = { selectors }
end
local element = ('style[%s;%s]'):format(
tableConcat(selectors, ','), tableConcat(properties, ','))
self:addElement(element)
return self
end
---Sets the focus to the element with the same name parameter.
@@ -1033,11 +1168,13 @@ end
---@param force string? (optional, default `false`): By default, focus is not applied for re-sent
--- formspecs with the same name so that player-set focus is kept. true sets
--- the focus to the specified element for every sent formspec.
---@return Formspec
function Formspec:setFocus(name, force)
local element = ('set_focus[%s;%s]'):format(
name, force or '')
self:addElement(element)
return self
end
return Formspec

View File

@@ -0,0 +1,9 @@
# textdomain: item
Rarity=Редкость
common=простой
uncommon=необычный
distinguished=выдающийся
eminent=исключительный
prime=Превосходный
unique=Уникальный

View File

@@ -1,33 +1,84 @@
local getInstance = Class.getInstance
local getInstance, extend = Class.getInstance, Class.extend
local tableCopy, tableMerge, colorize = table.copy, table.merge, core.colorize
local modInfo = Mod.getInfo('smc__core__item')
local require = modInfo.require
local ItemFactory = Mod.getInfo('smc__core__item_factory').require('ItemFactory')
---Determines whether common rarity will be shown in item descriptions or not.
local SHOW_COMMON_RARITY = true
---Colors corresponding to the rarity color in the item description.
---@type table<Item.Rarity, ColorString>
local RARITY_COLORS = {
['common'] = '#C0C0C0',
['uncommon'] = '#7cd2e2',
['distinguished'] = '#7ce2da',
['eminent'] = '#44d1a9',
['prime'] = '#9CF0B1',
['unique'] = '#f4c95a'
}
---Whether to show the numeric index in the rarity description.
local SHOW_RARITY_INDEX = true
---@type table<Item.Rarity, integer>
local RARITY_INDEX = {
['common'] = 1,
['uncommon'] = 2,
['distinguished'] = 3,
['eminent'] = 4,
['prime'] = 5,
['unique'] = 0
}
---@class Item
---@field itemDef Item.ItemDefinition
---@field luantiDef table
---@field luantiDef ItemDefinition
---@field getVisual fun(): string
---@field defaultDef Item.ItemDefinition
local Item = {
defaultDef = {
settings = {
name = '',
title = '',
description = '',
titleColor = '#FFFFFF',
descriptionColor = '#C0C0C0',
addModName = true,
_title = '',
_description = '',
_title_color = '#FFFFFF',
_description_color = '#C0C0C0',
_rarity = 'common',
_add_mod_name = true,
},
callbacks = {}
}
}
---Adds an item's rarity tag to the description.
---@param rarity Item.Rarity
---@param desc string
---@return string
local function addRarityToDesc(rarity, desc)
if not SHOW_COMMON_RARITY and rarity == 'common' then
return desc
end
local S = core.get_translator('item')
local color = RARITY_COLORS[rarity]
local rarityString = S('Rarity')..': '..S(rarity)
if SHOW_RARITY_INDEX then
rarityString = rarityString..' ['..RARITY_INDEX[rarity]..']'
end
return desc..'\n'..colorize(color, rarityString)
end
---The alias `table.merge` for EmmyLua
---@type fun(...):(NodeDefinition|ItemDefinition)
local defMerge = function(...)
return table.merge(...)
return tableMerge(...)
end
---@param itemDef Item.ItemDefinition
@@ -36,16 +87,12 @@ local function itemDefToLuantiDef(itemDef)
local modName = Mod.getInfo().shortName
local S = core.get_translator(modName)
itemDef = table.copy(itemDef)
itemDef = tableCopy(itemDef)
local s = itemDef.settings
local c = itemDef.callbacks
if s.addModName then
s.name = modName .. ':' .. s.name
end
local title = s.title
local description = s.description
local title = s._title
local description = s._description
if title == nil or title == '' then
title = string.match(s.name, '%S:(%S+)')..'-title'
@@ -55,59 +102,75 @@ local function itemDefToLuantiDef(itemDef)
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))
if s._title_color ~= nil and s._description_color ~= nil then
title = colorize(s._title_color ,S(title))
description = colorize(s._description_color, S(description))
else
error('Item description color parameters cannot be empty.')
end
s.title, s.description = nil, description
assert(s._rarity ~= nil, 'The rarity of an item cannot be empty.')
local luantiDescription = addRarityToDesc(s._rarity, title..'\n'..description)
s._title = title
s._description = description
s.description = luantiDescription..core.get_background_escape_sequence('#110F13')
local luantiDef = defMerge(s, c)
return luantiDef
end
---@param luantiDef NodeDefinition|ItemDefinition
---@param luantiDef NodeDefinition
local function register3dItem(luantiDef)
local ld = luantiDef
local name = ld.name
ld.name = nil
local name = luantiDef.name
luantiDef.name = nil
core.register_node(':'..name, luantiDef)
end
---@param luantiDef ItemDefinition
local function registerFlatItem(luantiDef)
local ld = luantiDef
local name = ld.name
ld.name = nil
local name = luantiDef.name
luantiDef.name = nil
core.register_craftitem(':'..name, luantiDef)
end
---The alias `table.merge` for EmmyLua
---@type fun(...):(Item.ItemDefinition)
local defMerge = function(...)
return table.merge(...)
return tableMerge(...)
end
---@param itemDef Item.ItemDefinition|Node.NodeDefinition
---@return Item
function Item:new(itemDef)
---Adding default parameters
assert(itemDef.settings.description == nil,
'The item description was specified using `description`, not `_description`. '..
'Please note that the `description` field should not be used when registering an item. '..
'Use `_title` and `_description` instead.')
-- Adding default parameters
itemDef = defMerge(itemDef, self.defaultDef, true)
local s = itemDef.settings
if s._add_mod_name then
s.name = Mod.getInfo().shortName .. ':' .. s.name
end
---@type Item
local instance = getInstance(self, {})
local luantiDef = itemDefToLuantiDef(itemDef)
local visual = itemDef.settings.visual
local visual = itemDef.settings._visual
if visual == nil then
visual = 'item_2d'
end
itemDef.settings.visual = nil
itemDef.settings._visual = nil
if visual == 'item_3d' then
register3dItem(luantiDef)
@@ -132,8 +195,10 @@ end
---@param defaultDef Item.ItemDefinition
---@return Item
function Item:getExtended(defaultDef)
defaultDef = defMerge(defaultDef, self.defaultDef)
---@type Item
local ChildClass = Class.extend(self, {
local ChildClass = extend(self, {
defaultDef = defaultDef,
})
@@ -146,6 +211,8 @@ end
function Item:getFactory(defaultDef)
if defaultDef == nil then
defaultDef = self.defaultDef
else
defaultDef = defMerge(self.defaultDef, defaultDef)
end
---@type ItemFactory

View File

@@ -0,0 +1,8 @@
---Rarity of items:
--- * `common`
--- * `uncommon`
--- * `distinguished`
--- * `eminent`
--- * `prime`
--- * `unique`
---@alias Item.Rarity 'common'|'uncommon'|'distinguished'|'eminent'|'prime'|'unique'

View File

@@ -5,38 +5,40 @@ local Settings = {}
---@type string
Settings.name = ''
---@type string?
Settings.description = nil
---Whether to add the mod name to the settings.name. Default: `true`
---@type boolean?
Settings.addModName = nil
Settings._add_mod_name = nil
---Item description. 1st line of item description.
---@type string?
Settings.title = nil
Settings._title = nil
---Item description. The rest of item description.
---@type string?
Settings.description = nil
Settings._description = nil
---Item title color in description.
---
---Default: `#FFFFFF`
---@type ColorString?
Settings.titleColor = nil
Settings._title_color = nil
---Item description color in description.
---
---Default: `#C0C0C0`
---@type ColorString?
Settings.descriptionColor = nil
---@alias Item.Visual
---'item_2d'|
---'item_3d'
Settings._description_color = nil
---Visual node type.
---@type Item.Visual?
Settings.visual = nil
Settings._visual = nil
---Formal (lore) rarity of an item. Default `common`.
---@type Item.Rarity?
Settings._rarity = nil
---Table of groups-characteristics of Item.

View File

@@ -0,0 +1 @@
---@alias Item.Visual 'item_2d'|'item_3d'

View File

@@ -81,6 +81,17 @@ function MapGen:new(def)
return instance
end
---Returns a layer by name. If such a layer does not exist, an error will be raised.
---@param layerName string The name of the layer to be retrieved.
---@return MapGen.Layer
function MapGen:getLayerByName(layerName)
local layer = self.layersByName[layerName]
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
return layer
end
---Determines which layer a node belongs to based on its height coordinate.
---@param yPos number
---@return MapGen.Layer?
@@ -122,24 +133,15 @@ end
---Returns the `MapGen.Peak` at the coordinates. If there is no peak at these coordinates, it returns `nil`.
---@param layer string|MapGen.Layer The layer or name of the layer in which the peak is located.
---@param category MapGen.Layer.Category The category in which the peak is located.
---@param pos Position Coordinate of the desired peak.
---@param pos MapPosition Coordinate of the desired peak.
---@return MapGen.Peak?
function MapGen:getPeakByPos(layer, category, pos)
if type(layer) == 'string' then
local layerName = layer
layer = self.layersByName[layerName]
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
layer = self:getLayerByName(layerName)
end
pos = vector.new(pos)
---@param peak MapGen.Peak
for _, peak in ipairs(layer.peaksList[category]) do
if peak:getPeakPos() == pos then
return peak
end
end
return layer:getPeakByPos(category, pos)
end
---Returns `true` if the point is within the triangle's region.
@@ -175,14 +177,12 @@ end
---**Important:** works only in the XZ plane.
---@param layer string|MapGen.Layer The layer or name of the layer the triangle is in.
---@param category MapGen.Layer.Category The category in which the triangle is in.
---@param pos Position Coordinate of the desired peak.
---@param pos MapPosition Coordinate of the desired peak.
---@return MapGen.Triangle?
function MapGen:getTriangleByPos2D(layer, category, pos)
if type(layer) == 'string' then
local layerName = layer
layer = self.layersByName[layerName]
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
layer = self:getLayerByName(layerName)
end
for _, triangle in ipairs(layer.trianglesList[category]) do
@@ -196,7 +196,7 @@ end
---If the point is inside the region, it will also return the distance to the nearest border.
---@param layer MapGen.Layer The name of the layer in which the region is located.
---@param regionName string The name of the region in which the location of the point is checked.
---@param point Position Point position.
---@param point MapPosition Point position.
---@return boolean, number?
function MapGen:pointInRegion2D(layer, regionName, point)
local region = layer.regionsByName[regionName]
@@ -206,6 +206,153 @@ function MapGen:pointInRegion2D(layer, regionName, point)
return region:pointInRegion(point)
end
---Returns `true` if there is a cavern at the specified coordinates.
---@param layer MapGen.Layer
---@param x integer
---@param y integer
---@param z integer
---@return boolean
function MapGen:isCavern(layer, x, y, z)
for _, cavern in ipairs(layer.cavernsList) do
if cavern.isRegional then
local inRegion, distance = self:pointInRegion2D(layer, cavern.name, {x=x,y=y,z=z})
if inRegion and distance ~= nil then
if cavern:isCavern(x, y, z, distance) then
return true
end
end
else
if cavern:isLayeredCavern(x, y, z) then
return true
end
end
end
return false
end
---Creates a unique key for a vertex (using X and Z coordinates).
---@param peak MapGen.Peak
---@return string
local function vertexKey(peak)
local pos = peak:getPeakPos()
return string.format("%.6f,%.6f", pos.x, pos.z)
end
---Creates a canonical (sorted) key for an edge.
---@param edge MapGen.Triangulation.Edge
---@return string
local function edgeKey(edge)
local k1 = vertexKey(edge.p1)
local k2 = vertexKey(edge.p2)
if k1 < k2 then
return k1 .. "|" .. k2
else
return k2 .. "|" .. k1
end
end
---Calculates the outer boundary of a triangulated region.
---Works on the XZ horizontal plane.
---@param triangles MapGen.Triangle[]
---@return table
function MapGen:getTriangulateBoundaryVertices(triangles)
-- Count how many triangles share each edge
local edgeCount = {}
---@type table<string, MapGen.Triangulation.Edge>
local edgeData = {}
for _, triangle in ipairs(triangles) do
local edges = {
triangle.e1,
triangle.e2,
triangle.e3
}
for _, edge in ipairs(edges) do
local key = edgeKey(edge)
edgeCount[key] = (edgeCount[key] or 0) + 1
edgeData[key] = edge
end
end
-- Boundary edges belong to exactly ONE triangle
---@type MapGen.Triangulation.Edge[]
local boundaryEdges = {}
for key, count in pairs(edgeCount) do
if count == 1 then
table.insert(boundaryEdges, edgeData[key])
end
end
if #boundaryEdges == 0 then
return {}
end
-- Build adjacency list for boundary vertices
---@type table<string, MapGen.Peak>
local adjacency = {}
---@type table<string, MapGen.Peak>
local vertexData = {}
for _, edge in ipairs(boundaryEdges) do
local k1 = vertexKey(edge.p1)
local k2 = vertexKey(edge.p2)
vertexData[k1] = edge.p1
vertexData[k2] = edge.p2
adjacency[k1] = adjacency[k1] or {}
adjacency[k2] = adjacency[k2] or {}
table.insert(adjacency[k1], k2)
table.insert(adjacency[k2], k1)
end
-- Walk along boundary edges to create ordered vertex list
---@type MapPosition[]
local boundary = {}
---@type table<string, boolean>
local visited = {}
if boundaryEdges[1] == nil then
error()
end
---@type string?
local currentKey = vertexKey(boundaryEdges[1].p1)
while currentKey and not visited[currentKey] do
visited[currentKey] = true
local pos = vertexData[currentKey]:getPeakPos()
table.insert(boundary, {
x = pos.x,
y = 0,
z = pos.z
})
-- Move to next unvisited neighbor
local nextKey = nil
for _, neighborKey in ipairs(adjacency[currentKey] or {}) do
if not visited[neighborKey] then
nextKey = neighborKey
break
end
end
currentKey = nextKey
end
return boundary
end
-- --- REGISTRATION METHODS ---
@@ -240,10 +387,7 @@ end
---@param color ColorString Noise color. Must be unique.
---@param noiseParams NoiseParams Fractal noise parameters.
function MapGen:registerLayerNoiseColor(layerName, category, color, noiseParams)
---@type MapGen.Layer
local layer = self.layersByName[layerName]
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
local layer = self:getLayerByName(layerName)
layer:addNoiseParamsColor(category, color, noiseParams)
end
@@ -279,14 +423,11 @@ end
---@param category MapGen.Layer.Category Category indicating what will be generated by peak.
---@param def MapGen.PeakDef Peak description table, see details `MapGen.PeakDef`.
function MapGen:registerPeak(layerName, category, def)
---@type MapGen.Layer
local layer = self.layersByName[layerName]
local layer = self:getLayerByName(layerName)
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
assert(self:getPeakByPos(layer, category, def.pos) == nil,
('In the `%s` layer in the `%s` category there is already a peak with coordinates: %s, %s, %s.'):format(
layerName, category, def.pos.x, def.pos.y, def.pos.z))
--assert(self:getPeakByPos(layer, category, def.pos) == nil,
--('In the `%s` layer in the `%s` category there is already a peak with coordinates: %s, %s, %s.'):format(
-- layerName, category, def.pos.x, def.pos.y, def.pos.z))
---@type MapGen.Peak
local peak = Peak:new(def)
@@ -332,21 +473,39 @@ end
---@param layerName string The name of the layer in which the new peaks will be included.
---@param map string The name of the image from which the peaks will be extracted. It should be located in the `<mod_name>/textures/maps` folder and have the following format `<image_name>.ff`
---@param scale number Multiplier of how many blocks (nodes) will be between image pixels. It is not recommended to set the value below 50 for performance reasons.
---@param zeroPos Position2d The position in pixels where the zero world coordinate will be in the image.
---@param zeroPos IntegerPosition2d The position in pixels where the zero world coordinate will be in the image.
---@param category MapGen.Layer.Category Category indicating what will be generated by peaks.
---@param groups? table<string, number> Groups that will be added to all peaks.
function MapGen:register2DPeaksFromFile(layerName, map, scale,zeroPos, category, groups)
if scale < 2 then
error('The map scale should not be less than 2.')
end
local modPath = core.get_modpath(core.get_current_modname())
local peaks = ff2luat(modPath .. '/textures/maps/' .. map)
---@type {h:integer, w:integer}
local mapSize = peaks.size
peaks.size = nil
zeroPos.x = zeroPos.x + mathRound(mapSize.w/2)
zeroPos.y = zeroPos.y + mathRound(mapSize.h/2)
local x, z
for color, peaksPos in pairs(peaks) do
for _, peakPos in ipairs(peaksPos) do
---@type integer, integer
x, z = (peakPos.x - zeroPos.x - 1) * scale, (peakPos.y - zeroPos.y - 1) * -scale
-- Converting a rectangular grid into an isometric-like one.
if peakPos.y % 2 == 1 then
x = mathRound(x + (scale/2))
end
---@type MapGen.PeakDef
local def = {
pos = vector.new((peakPos.x - zeroPos.x - 1) * scale, 0, (peakPos.y - zeroPos.y - 1) * scale),
pos = {x=x, y=0, z=z},
color = color,
groups = groups,
}
@@ -360,13 +519,10 @@ end
---If the peak does not exist, an error will be raised.
---@param layerName string The name of the layer in which the new peak will be included.
---@param category MapGen.Layer.Category Category indicating what will be generated by peak.
---@param pos Position The position of the peak to which the group should be added.
---@param pos MapPosition The position of the peak to which the group should be added.
---@param groups table<string, number> Groups to be added.
function MapGen:addGroupsToPeakByPos(layerName, category, pos, groups)
---@type MapGen.Layer
local layer = self.layersByName[layerName]
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
local layer = self:getLayerByName(layerName)
local peak = self:getPeakByPos(layer, category, pos)
assert( peak ~= nil, ('In the `%s` layer in the `%s` category there is no peak with coordinates: %s, %s, %s.'):format(
@@ -380,10 +536,7 @@ end
---@param biomeName string The name to be assigned to the biome. The name must be unique for each biome.
---@param def MapGen.BiomeDef Biome description table, see details `MapGen.BiomeDef`
function MapGen:registerBiome(layerName, biomeName, def)
local layer = self.layersByName[layerName]
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
---TODO: перенести проверку на уникальность в конструктор
assert(layer.biomesByName[biomeName] == nil, ('A biome named `%s` already exists in the `%s` layer.'):format(biomeName, layerName))
local layer = self:getLayerByName(layerName)
local biome = Biome:new(biomeName, def)
@@ -394,25 +547,35 @@ end
---@param layerName string The name of the layer in which the new cavern will be included.
---@param cavernName string The name to be assigned to the cavern. The name must be unique for each cavern.
---@param def MapGen.CavernDef Cavern description table, see details `MapGen.CavernDef`
function MapGen:registerCavern(layerName, cavernName, def)
local layer = self.layersByName[layerName]
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
---TODO: перенести проверку на уникальность в конструктор
assert(layer.cavernsByName[cavernName] == nil, ('A cavern named `%s` already exists in the `%s` layer.'):format(cavernName, layerName))
---@param regionVertices MapPosition[]? The region to which the cave generation will be limited.
function MapGen:registerCavern(layerName, cavernName, def, regionVertices)
local layer = self:getLayerByName(layerName)
if regionVertices ~= nil then
self:registerRegion(layerName, cavernName, {
vertices = regionVertices
})
def.isRegional = true
end
local cavern = Cavern:new(cavernName, def)
layer:addCavern(cavernName, cavern)
end
---Designate the world region between the vertices as `MapGen.Region` and give it a name.
---Mark the world region between the vertices as `MapGen.Region` and give it a name.
---@param layerName string The name of the layer in which the new region will be included.
---@param regionName string The name to be assigned to the region. The name must be unique for each region.
---@param def MapGen.RegionDef Region description table, see details `MapGen.RegionDef`
function MapGen:registerRegion(layerName, regionName, def)
local layer = self.layersByName[layerName]
assert(layer ~= nil, ('There is no layer named `%s` registered.'):format(layerName))
assert(layer.regionsByName[regionName] == nil, ('A region named `%s` already exists in the `%s` layer.'):format(regionName, layerName))
if regionName == 'landscape_boundary' or
regionName == 'temp_boundary' or
regionName == 'humidity_boundary' then
error(('The name `%s` is reserved for special regions and cannot be used.'):format(regionName))
end
local layer = self:getLayerByName(layerName)
local region = Region:new(regionName, def)
@@ -420,15 +583,32 @@ function MapGen:registerRegion(layerName, regionName, def)
end
-- --- INITIALIZATION METHODS ---
---Initialize the boundary region for a triangulated area.
---@param layer MapGen.Layer
---@param category MapGen.Layer.Category
---@param triangles MapGen.Triangle[]
function MapGen:initTriangultaionBoundaryRegion(layer, category, triangles)
local regionVertices = self:getTriangulateBoundaryVertices(triangles)
local regionName = category..'_boundary'
local region = Region:new(regionName, {vertices = regionVertices})
layer:addRegion(regionName, region)
end
---Divide all layers into triangles whose vertices are the `Mapgen.Peak` belonging to these layers.
function MapGen:initLayersTriangultaion()
---@param layer MapGen.Layer
for _, layer in ipairs(self.layersList) do
for category, peaks in pairs(layer.peaksList) do
local triangles = Triangulation.triangulate(peaks)
layer.trianglesList[category] = Triangulation.triangulate(peaks)
layer.trianglesList[category] = triangles
self:initTriangultaionBoundaryRegion(layer, category, triangles)
-- layer.tetrahedronsList = Triangulation.tetrahedralize(layer.peaksList) -- 3D not supported
end
end
@@ -469,22 +649,6 @@ end
-- --- GENERATION METHODS ---
---Returns `true` if there is a cavern at the specified coordinates.
---@param layer MapGen.Layer
---@param x integer
---@param y integer
---@param z integer
---@return boolean
local function isCavern(layer, x, y, z)
for _, cavern in ipairs(layer.cavernsList) do
if cavern:isCavern(x, y, z) then
return true
end
end
return false
end
---The core logic of world generation. Determines which node type (water, rock, soil, air)
---and which biome will be generated at the specified coordinates.
---@param mapGenerator MapGen
@@ -541,7 +705,7 @@ local function generateNode(mapGenerator, layer, height, temp, humidity, data, i
-- If the block is below the surface height...
elseif y <= height then
-- ... and a cavern is generated in the block...
if isCavern(layer, x, y, z) then
if mapGenerator:isCavern(layer, x, y, z) then
-- ... then airspace is generated.
biome:generateCavernAir(mapGenerator, data, index, x, y, z)
@@ -694,6 +858,10 @@ function MapGen:getNoises2dValue(category, layer, x, y, z)
end
end
if not self:pointInRegion2D(layer, category..'_boundary', {x=x, y=y, z=z}) then
return nil
end
---@param triangle MapGen.Triangle
for _, triangle in ipairs(layer.trianglesList[category]) do
if pointInTriangle2D(x, z, triangle) then
@@ -829,9 +997,23 @@ local function generatorHandler(mapGenerator, data, index, x, y, z)
-- If the value of the noise is `nil`,
-- then the point does not fall within any of the triangles.
local noiseHeightValue = mapGenerator:getNoises2dValue('landscape', layer, x, y, z) or 0.0
local noiseTempValue = mapGenerator:getNoises2dValue('temp', layer, x, y, z) or 0.0
local noiseHumidityValue = mapGenerator:getNoises2dValue('humidity', layer, x, y, z) or 0.0
local noiseHeightValue = mapGenerator:getNoises2dValue('landscape', layer, x, y, z)
if noiseHeightValue == nil then
data[index] = core.CONTENT_IGNORE
return
end
local noiseTempValue = mapGenerator:getNoises2dValue('temp', layer, x, y, z)
if noiseTempValue == nil then
data[index] = core.CONTENT_IGNORE
return
end
local noiseHumidityValue = mapGenerator:getNoises2dValue('humidity', layer, x, y, z)
if noiseHumidityValue == nil then
data[index] = core.CONTENT_IGNORE
return
end
-- We recalculate the climate based on altitude.
noiseTempValue = layer:calcTemp(noiseTempValue, y)
@@ -842,8 +1024,8 @@ end
---Chunk generation handler.
---@param voxelManip VoxelManip
---@param minPos Position
---@param maxPos Position
---@param minPos MapPosition
---@param maxPos MapPosition
---@param blockseed number
function MapGen:onMapGenerated(voxelManip, minPos, maxPos, blockseed)
-- We obtain a generation area for further manipulations

View File

@@ -1,10 +1,11 @@
local mathMin, mathMax, mathAbs
= math.min, math.max, math.abs
local mathMin, mathMax, mathAbs, mathClamp
= math.min, math.max, math.abs, math.clamp
local getInstance = Class.getInstance
---@class MapGen.Cavern
---@field name string
---@field isRegional boolean
---@field minY number
---@field maxY number
---@field smoothDistance number
@@ -18,6 +19,7 @@ local Cavern = {}
---
---**Only for EmmyLua.**
---@class MapGen.CavernDef
---@field isRegional boolean?
---@field minY number
---@field maxY number
---@field noiseParams NoiseParams
@@ -58,6 +60,7 @@ function Cavern:new(name, def)
maxY = def.maxY,
smoothDistance = def.smoothDistance,
threshold = def.threshold,
isRegional = def.isRegional or false,
})
function instance:getNoise()
@@ -79,16 +82,31 @@ function Cavern:new(name, def)
return instance
end
---@param y number
---@param minY number
---@param maxY number
---@param smoothDistance number
---@param distance number
---@return number
local function calcCavernWeight(y, smoothDistance, minY, maxY)
local maxDist = maxY - y
local minDist = y - minY
function Cavern:calcCavernWeight(distance)
return mathClamp(distance / self.smoothDistance, 0, 1)
end
return mathMax(0, mathMin(maxDist / smoothDistance, minDist / smoothDistance, 1))
---Returns `true` if there is a cavern at the specified coordinates.
---@param x integer
---@param y integer
---@param z integer
---@param distance number
---@return boolean
function Cavern:isCavern(x, y, z, distance)
local minY, maxY = self.minY, self.maxY
if y >= maxY or y <= minY then
return false
end
distance = mathMin(maxY - y, y - minY, distance)
local noise = self:getNoise()
local weight = self:calcCavernWeight(distance)
return noise:get_3d({x = x, y = y, z = z}) * weight > self.threshold
end
---Returns `true` if there is a cavern at the specified coordinates.
@@ -96,15 +114,17 @@ end
---@param y integer
---@param z integer
---@return boolean
function Cavern:isCavern(x, y, z)
function Cavern:isLayeredCavern(x, y, z)
local minY, maxY = self.minY, self.maxY
if y > maxY or y < minY then
return false
end
local distance = mathMin(maxY - y, y - minY)
local noise = self:getNoise()
local weight = calcCavernWeight(y, self.smoothDistance, minY, maxY)
local weight = self:calcCavernWeight(distance)
return noise:get_3d({x = x, y = y, z = z}) * weight > self.threshold
end

View File

@@ -129,6 +129,21 @@ function Layer:addPeak(category, peak)
end
end
---Returns the `MapGen.Peak` at the coordinates. If there is no peak at these coordinates, it returns `nil`.
---@param category MapGen.Layer.Category The category in which the peak is located.
---@param pos Position Coordinate of the desired peak.
---@return MapGen.Peak?
function Layer:getPeakByPos(category, pos)
pos = vector.new(pos)
---@param peak MapGen.Peak
for _, peak in ipairs(self.peaksList[category]) do
if peak:getPeakPos() == pos then
return peak
end
end
end
---Adds a NoiseParams color to the `Layer.noisesParamsByColor`
---@param category MapGen.Layer.Category
---@param color ColorString
@@ -179,26 +194,69 @@ end
---@param biomeName string
---@param biome MapGen.Biome
function Layer:addBiome(biomeName, biome)
-- TODO: перенести сюда проверку на уникальность
assert(self.biomesByName[biomeName] == nil,
('A biome named `%s` already exists in the `%s` layer.'):format(
biomeName, self.name))
self.biomesByName[biomeName] = biome
table.insert(self.biomesList, biome)
end
---Returns a biome by name, if there is no such biome, it will raise an error.
---@param biomeName string
---@return MapGen.Biome
function Layer:getBiomeByName(biomeName)
local biome = self.biomesByName[biomeName]
assert(biome ~= nil, ('Biome named `%s` does not exist in the `%s` layer.'):format(
biomeName, self.name))
return biome
end
---Adds a cavern to the `Layer.cavernsByName` & `Layer.cavernsList`
---@param cavernName string
---@param cavern MapGen.Cavern
function Layer:addCavern(cavernName, cavern)
-- TODO: перенести сюда проверку на уникальность
assert(self.cavernsByName[cavernName] == nil,
('A cavern named `%s` already exists in the `%s` layer.'):format(
cavernName, self.name))
self.cavernsByName[cavernName] = cavern
table.insert(self.cavernsList, cavern)
end
---Returns a cavern by name, if there is no such cavern, it will raise an error.
---@param cavernName string
---@return MapGen.Cavern
function Layer:getCavernByName(cavernName)
local cavern = self.cavernsByName[cavernName]
assert(cavern ~= nil, ('Cavern named `%s` does not exist in the `%s` layer.'):format(
cavernName, self.name))
return cavern
end
function Layer:addRegion(regionName, region)
-- TODO: перенести сюда проверку на уникальность
assert(self.regionsByName[regionName] == nil,
('A region named `%s` already exists in the `%s` layer.'):format(
regionName, self.name))
self.regionsByName[regionName] = region
--table.insert(self.regionsList, region)
end
---Returns a region by name, if there is no such region, it will raise an error.
---@param regionName string
---@return MapGen.Region
function Layer:getRegionByName(regionName)
local region = self.regionsByName[regionName]
assert(region ~= nil, ('Region named `%s` does not exist in the `%s` layer.'):format(
regionName, self.name))
return region
end
---@param height number
---@param biomesList MapGen.Biome[]
---@return string[], MapGen.Biome[]

View File

@@ -16,14 +16,14 @@ local Peak = {
---
---**Only for EmmyLua.**
---@class MapGen.PeakDef
---@field pos vector
---@field pos MapPosition|vector
---@field color ColorString
---@field groups? table<string, number>
---@param def MapGen.PeakDef
---@return MapGen.Peak
function Peak:new(def)
local _pos = def.pos
local _pos = vector.new(def.pos)
local _color = def.color
local _groups

View File

@@ -4,11 +4,11 @@ local getInstance = Class.getInstance
---@class MapGen.Region
---@field name string
---@field vertices Position[]
---@field vertices MapPosition[]
local Region = {}
---@class MapGen.RegionDef
---@field vertices Position[]
---@field vertices MapPosition[]
---@param def MapGen.RegionDef
---@return MapGen.Region
@@ -50,7 +50,7 @@ local function calcDistanceSq(px, pz, x1, z1, x2, z2)
end
---Checks if a point is inside a `MapGen.Region` (2D check using x and z coordinates).
---@param point Position
---@param point MapPosition
---@return boolean, number?
function Region:pointInRegion(point)
local vertices = self.vertices

View File

@@ -1,3 +1,4 @@
---@diagnostic disable: param-type-not-match
local mathAbs = math.abs
local getInstance = Class.getInstance

View File

@@ -1,3 +1,4 @@
---@diagnostic disable: param-type-not-match
-- Tringulation lib
-- Original code: https://github.com/iskolbin/Triangulation/blob/master/Triangulation.lua
-- Date of copying: 07.11.2025

View File

@@ -14,7 +14,7 @@ local FakePeak = Class.extend(Peak, {})
---Returns a fake `MapGen.Peak` that has no noise parameters.
---Note that the initialized peak should not be used in generation.
---@param peakPos vector
---@param peakPos MapPosition|vector
---@return MapGen.Peak
function FakePeak:new(peakPos)
local instance = Peak:new({pos = peakPos, color = '#000000'})

View File

@@ -22,7 +22,7 @@ function Node:new(nodeDef)
---Adding default parameters
nodeDef = defMerge(nodeDef, self.defaultDef, true)
nodeDef.settings.visual = 'item_3d'
nodeDef.settings._visual = 'item_3d'
---@type Node
local instance = Item:new(nodeDef)
@@ -35,6 +35,8 @@ end
---@param defaultDef Node.NodeDefinition
---@return Node
function Node:getExtended(defaultDef)
defaultDef = defMerge(defaultDef, self.defaultDef)
---@type Node
local ChildClass = Class.extend(self, {
defaultDef = defaultDef,
@@ -49,6 +51,8 @@ end
function Node:getFactory(defaultDef)
if defaultDef == nil then
defaultDef = self.defaultDef
else
defaultDef = defMerge(self.defaultDef, defaultDef)
end
---@type ItemFactory

View File

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

View File

@@ -0,0 +1,2 @@
name = smc__core__work_station
depends = smc__core__craft_system, smc__core__node, smc__ui__work_station

View File

@@ -0,0 +1,229 @@
local getInstance = Class.getInstance
---@type CraftSystem.ImmersiveCraftHandler
local ImmersiveCraftHandler = Mod.getInfo('smc__core__craft_system').require('CraftSystem.ImmersiveCraftHandler')
---@type WorkStationUI
local WorkStationUI = Mod.getInfo('smc__ui__work_station').require('WorkStationUI')
---@type Node
local Node = Mod.getInfo('smc__core__node').require('Node')
-- Default settings that a work station node should have.
local WorkStationNode = Node:getExtended({
settings = {
name = 'work_station',
drawtype = 'normal',
paramtype = 'light',
groups = {work_station = 1, dig_immediate = 2,}
}
})
---A work station (node) that enables player interaction
---with the immersive crafting mechanics.
---@class WorkStation
---@field name string
---@field group CraftSystem.CraftGroup
---@field nodeDef Node.NodeDefinition
local WorkStation = {}
---Definition table for the `CraftSystem.WorkStation`.
---
---**Only for EmmyLua.**
---@class WorkStationDef
---@field group CraftSystem.CraftGroup
---@field nodeDef Node.NodeDefinition
---@param name string
---@param def WorkStationDef
function WorkStation:new(name, def)
local nodeDef = def.nodeDef
if nodeDef.callbacks == nil then
---@type Node.Callbacks
nodeDef.callbacks = {}
end
local settings = nodeDef.settings
local callbacks = nodeDef.callbacks
-- Callback when the work station block is installed in the world
-- Ensures initialization of necessary parameters
callbacks.on_construct = function(pos)
-- Getting node metadata
local meta = core.get_meta(pos)
-- Initializing the table of temporary parameters for crafting.
Smc.setCraftDataByMeta(meta)
end
-- Callback for interaction with a work station (start of crafting)
callbacks.on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
-- If the workstation is occupied by another craft...
if not Smc.workStationIsFree(pos) then
-- ...we inform the player about this...
core.chat_send_player(clicker:get_player_name(), 'The workbench is occupied by another craft.')
-- ...and do nothing.
return
end
-- We get a list of crafts that can be produced using the item that the player was holding in his hand.
local crafts = ImmersiveCraftHandler:getCraftsByTriggerItem(itemstack:get_name())
-- If the list is empty...
if crafts == nil then
-- ..this means there are no crafts for this item,
-- so we don't do anything.
return
else
-- ...else we show the player the formspec for choosing a craft.
self:showSelectionCraftForm(clicker, crafts, pos)
end
end
callbacks.on_dig = function(pos, node, digger)
if Smc.workStationIsFree(pos) then
return core.node_dig(pos, node, digger)
else
return false
end
end
---@type WorkStation
local instance = getInstance(self, {})
instance.name = name
instance.group = def.group
instance.nodeDef = nodeDef
-- Registering a node for Luanti.
WorkStationNode:new(nodeDef)
return instance
end
---Show the player the initial workstation interface for choosing a craft.
---@param player Player
---@param crafts CraftSystem.ImmersiveCraft[]
---@param pos Position
function WorkStation:showSelectionCraftForm(player, crafts, pos)
-- Create a table in the format craft result - craft name.
local outputs = {}
for _, craft in ipairs(crafts) do
outputs[craft.output] = craft.name
end
-- We get the name of the player who wants to start crafting.
local playerName = player:get_player_name()
-- We set the context for transferring data about the workstation coordinates and the list of crafts.
WorkStationUI:setContex(playerName, 'pos', pos)
WorkStationUI:setContex(playerName, 'outputs', outputs)
-- Showing the desktop interface to the player.
WorkStationUI:showForm(playerName,false)
end
-- Registering a callback for player choice of craft (this does not start crafting).
WorkStationUI:registerOnFormFieldActionMatch('%S+::item_button',function(player, fieldName, fieldValue)
-- We get the name of the craft from the name of the button the player pressed.
local craftName = string.match(fieldName, '(%S+)::item_button')
assert(craftName ~= nil, 'Craft name cannot be empty')
-- We get a craft object.
local craft = ImmersiveCraftHandler:getCraftByName(craftName)
-- We get the name of the player who wants to start crafting.
local playerName = player:get_player_name()
-- We enter into the context the craft that the player has chosen.
WorkStationUI:setContex(playerName, 'craft', craft)
-- We show the player a new interface with a crafting description tab.
WorkStationUI:showForm(playerName, true)
end)
-- We register a callback when the player starts crafting.
WorkStationUI:registerOnFormFieldAction('work_station:start_craft', function(player, fieldName, fieldValue)
-- We get the name of the player who wants to start crafting.
local playerName = player:get_player_name()
-- We get the workstation position and craft from the context.
local pos = WorkStationUI:getContex(playerName, 'pos')
---@type CraftSystem.ImmersiveCraft
local craft = WorkStationUI:getContex(playerName, 'craft')
-- We process the amount of crafting.
local isCraftStart = false
if fieldValue == 'x1' then
-- Single craft
isCraftStart = craft:startCraft(pos, player, 1)
elseif fieldValue == 'x10' then
-- Ten crafts at a time.
isCraftStart = craft:startCraft(pos, player, 10)
end
-- If the craft was started...
if isCraftStart then
-- ...we are closing the formspec.
WorkStationUI:closeForm(playerName)
end
end)
-- --- DEBUG ---
WorkStation:new('test_station', {
group = 'test',
nodeDef = {
settings = {
name = 'test_station',
tiles = {'test_station.png'}
}
}
})
ImmersiveCraftHandler:registerCraft('bricks', {
triggerItem = 'rocks:sylite',
output = 'rocks:sylite_bricks',
startStageName = 'tapping',
group = 'test',
stages = {
---@type CraftSystem.ImmersiveCraftStage.TappingStageDef
{
name = 'tapping',
targetItem = 'rocks:sylite',
type = 'tapping',
clicksNeed = 3,
}
},
})
ImmersiveCraftHandler:registerCraft('block', {
triggerItem = 'rocks:sylite',
output = 'rocks:sylite_block',
startStageName = 'tapping',
group = 'test',
stages = {
---@type CraftSystem.ImmersiveCraftStage.TappingStageDef
{
name = 'tapping',
targetItem = 'rocks:sylite',
type = 'tapping',
clicksNeed = 5,
}
},
})
ImmersiveCraftHandler:registerCraft('marentine_planks', {
triggerItem = 'wood:marentine_log',
output = 'wood:marentine_planks',
startStageName = 'tapping',
group = 'test',
stages = {
---@type CraftSystem.ImmersiveCraftStage.TappingStageDef
{
name = 'tapping',
targetItem = 'wood:marentine_log',
type = 'tapping',
clicksNeed = 5,
}
},
})
return WorkStation

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -12,13 +12,12 @@ listForm:list('current_player', 'main', 10.5, 6.5, 8, 4)
local listFormItems = Formspec:new()
local items = core.registered_nodes
local items = table.get_keys(core.registered_nodes)
table.sort(items)
local w, h = 0, 0
---@param name string
---@param def NodeDefinition
for name, def in pairs(items) do
for _, name in ipairs(items) do
listFormItems:itemImageButton(w, h, 1, 1, name, name..'::item_button')
w = w + 1
@@ -31,10 +30,9 @@ 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())
listForm:
scrollContainer(listFormItems, 0.5, 0.5, 9, 11, 'admin_commands:list_items', 'vertical'):
scrollbar(10, 0.5, 0.25, 10, 'vertical', 'admin_commands:list_items')
core.register_chatcommand('list', {
privs = {server = true},

View File

@@ -16,6 +16,8 @@ local MapGen = mapGenRequire('MapGen')
-- Rocks
sylite = 'rocks:sylite',
syliteGray = 'rocks:sylite_gray',
syliteBlack = 'rocks:sylite_black',
tauitite = 'rocks:tauitite',
iyellite = 'rocks:iyellite',
falmyte = 'rocks:falmyte',
@@ -72,7 +74,7 @@ local land2 = {
local land3 = {
offset = 40,
scale = 20,
scale = 5,
spread = {x = 45, y = 20, z = 45},
seed = 472,
octaves = 3,
@@ -169,18 +171,18 @@ for _, c in ipairs({'landscape', 'temp', 'humidity'}) do
})--]]
end
mapGenerator:register2DPeaksFromFile('midgard', 'map.ff', 32,{x=0, y=0}, 'landscape')
mapGenerator:register2DPeaksFromFile('midgard', 'map.ff', 100,{x=0, y=0}, 'landscape')
mapGenerator:register2DPeaksFromFile('midgard', 'map.ff', 150,{x=0, y=0}, 'temp')
mapGenerator:register2DPeaksFromFile('midgard', 'map.ff', 200,{x=0, y=0}, 'humidity')
--[[
-- [[
mapGenerator:registerCavern('midgard', 'cavern1', {
minY = -48,
maxY = 50,
maxY = 100,
smoothDistance = 20,
threshold = 0.2,
threshold = 0.1,
noiseParams ={
offset = 0,
offset = 0.2,
scale = 1,
spread = {x = 10, y = 250, z = 30},
seed = 5934,
@@ -188,6 +190,12 @@ mapGenerator:registerCavern('midgard', 'cavern1', {
persistence = 0.4,
lacunarity = 2.0
},
},
{
{x=100, y=0, z=100},
{x=100, y=0, z=200},
{x=200, y=0, z=200},
{x=200, y=0, z=100},
})--]]
-- --- Biomes ---
@@ -213,8 +221,8 @@ local function generateRock(biome, mapGenerator, data, index, x, y, z)
rocksNoise = core.get_value_noise(rocksNoiseParams)
end
local noiseRocksValue = mathRound(rocksNoise:get_3d({x = x, y = y, z = z}))
if noiseRocksValue == 1 then
local noiseRocksValue = (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
@@ -230,6 +238,13 @@ local function generateRock(biome, mapGenerator, data, index, x, y, z)
data[index] = ids.burcite
elseif noiseRocksValue == 8 then
data[index] = ids.felhor
end--]]
if noiseRocksValue > 5 then
data[index] = ids.syliteBlack
elseif noiseRocksValue > 4.5 then
data[index] = ids.syliteGray
else
data[index] = ids.sylite
end
end
@@ -240,9 +255,13 @@ local function generateSoil(biome, mapGenerator, data, index, x, y, z)
rocksNoise = core.get_value_noise(rocksNoiseParams)
end
local noiseRocksValue = mathRound(rocksNoise:get_3d({x = x, y = y, z = z}))
local noiseRocksValue = (rocksNoise:get_3d({x = x, y = y, z = z}))
if noiseRocksValue > 4 then
if noiseRocksValue > 5 then
data[index] = ids.syliteBlack
elseif noiseRocksValue > 4.5 then
data[index] = ids.syliteGray
elseif noiseRocksValue > 4 then
data[index] = ids.sylite
else
data[index] = biome.groundNodesIDs.soil
@@ -256,9 +275,13 @@ local function generateTurf(biome, mapGenerator, data, index, x, y, z)
rocksNoise = core.get_value_noise(rocksNoiseParams)
end
local noiseRocksValue = mathRound(rocksNoise:get_3d({x = x, y = y, z = z}))
local noiseRocksValue = (rocksNoise:get_3d({x = x, y = y, z = z}))
if noiseRocksValue > 4 then
if noiseRocksValue > 5 then
data[index] = ids.syliteBlack
elseif noiseRocksValue > 4.5 then
data[index] = ids.syliteGray
elseif noiseRocksValue > 4 then
data[index] = ids.sylite
else
data[index] = biome.groundNodesIDs.turf

View File

@@ -5,7 +5,7 @@ local Node = Mod.getInfo('smc__core__node').require('Node')
local defaultLiquidDef = {
settings = {
name = '',
addModName = false,
_add_mod_name = false,
tiles = {},
waving = 3,
use_texture_alpha = "blend",
@@ -66,10 +66,10 @@ liquidFactory:registerItems({
settings = {
name = "liquids:water_flowing",
drawtype = "flowingliquid",
tiles = {"default_water.png"},
tiles = {"liquids_water.png"},
special_tiles = {
{
name = "default_water_flowing_animated.png",
name = "liquids_water_flowing.png",
backface_culling = false,
animation = {
type = "vertical_frames",
@@ -79,7 +79,7 @@ liquidFactory:registerItems({
},
},
{
name = "default_water_flowing_animated.png",
name = "liquids_water_flowing.png",
backface_culling = true,
animation = {
type = "vertical_frames",

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -21,7 +21,7 @@ for i=0, 3 do
Plant:new({
settings = {
name = 'plant'..tostring(i),
title = 'Plant',
_title = 'Plant',
tiles = { ts:t(i,0) },
place_param2 = 3,
},

View File

@@ -7,8 +7,7 @@ local Node = Mod.getInfo('smc__core__node').require('Node')
---@type Node.NodeDefinition
local defaultRockDef = {
settings = {
name = "",
description = "A rocks",
name = '',
tiles = {},
groups = {
dig_immediate = 2,
@@ -24,16 +23,49 @@ local rockFactory = defaultRock:getFactory()
---@type TileSheet
local ts = TileSheet:new("rocks_sheet.png", 16, 16)
rockFactory:registerNodesByShortDef({
{"sylite", {ts:t(0, 0)}},
{"tauitite", {ts:t(0, 2)}},
{"iyellite", {ts:t(0, 4)}},
{"falmyte", {ts:t(0, 6)}},
{"hapcoryte", {ts:t(0, 8)}},
{"burcite", {ts:t(0, 10)}},
{"felhor", {ts:t(0, 12)}},
{"malachite", {ts:t(0, 14)}}
})
local function registerRocksTypes(postfix, x)
rockFactory:registerNodesByShortDef({
{"sylite"..postfix, {ts:t(x, 0)}},
{"sylite_gray"..postfix, {ts:t(x, 1)}},
{"sylite_black"..postfix, {ts:t(x, 2)}},
{"tauitite_light"..postfix, {ts:t(x, 3)}},
{"tauitite_pink"..postfix, {ts:t(x, 4)}},
{"tauitite"..postfix, {ts:t(x, 5)}},
{"falmyte_light"..postfix, {ts:t(x, 6)}},
{"falmyte_yellow"..postfix, {ts:t(x, 7)}},
{"falmyte_red"..postfix, {ts:t(x, 8)}},
{"falmyte_dark"..postfix, {ts:t(x, 9)}},
{"iyellite"..postfix, {ts:t(x, 14)}},
{"falmyte"..postfix, {ts:t(x, 14)}},
{"hapcoryte"..postfix, {ts:t(x, 14)}},
{"burcite"..postfix, {ts:t(x, 14)}},
{"felhor"..postfix, {ts:t(x, 14)}},
{"malachite"..postfix, {ts:t(x, 14)}}
})
end
local function registerPilarStaff(rock, y)
local columnTop = ts:t(9, y)
rockFactory:registerNodesByShortDef({
{rock..'_fluted_column', {columnTop, columnTop, ts:t(6, y)}},
{rock..'_ionic_chapiter', {
ts:t(3, y),
columnTop,
ts:t(7, y),
ts:t(7, y),
ts:t(8, y),
ts:t(8, y)}},
})
end
registerPilarStaff('sylite_black', 2)
registerRocksTypes('', 0)
registerRocksTypes('_chipped', 1)
registerRocksTypes('_block', 3)
registerRocksTypes('_bricks', 4)
registerRocksTypes('_bricks_2', 5)
--[[
rockFactory:registerItems({

View File

@@ -0,0 +1,6 @@
# textdomain: rocks
sylite_block-title=Силитовый блок
sylite_block-desc=Массивный блок из цельного куска силита.
sylite_bricks-title=Силитовые кирпичи
sylite_bricks-desc=Кладка из силитовых кирпичей.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 151 KiB

View File

@@ -8,7 +8,7 @@ local Node = Mod.getInfo('smc__core__node').require('Node')
local defaultSoilDef = {
settings = {
name = "",
description = "A soil",
_description = "A soil",
tiles = {},
groups = {
dig_immediate = 2,
@@ -47,7 +47,7 @@ soilFactory:registerItems({
{
settings = {
name = "clay_soil_baren",
title = "Barren Clay Soil",
_title = "Barren Clay Soil",
--description = "",
tiles = clayTiles,
},
@@ -56,7 +56,7 @@ soilFactory:registerItems({
{
settings = {
name = "clay_soil_poor",
title = "Poor Clay Soil",
_title = "Poor Clay Soil",
--description = "",
tiles = clayTiles,
},
@@ -65,7 +65,7 @@ soilFactory:registerItems({
{
settings = {
name = "clay_soil_moderate",
title = "Moderate Clay Soil",
_title = "Moderate Clay Soil",
--description = "",
tiles = clayTiles,
},
@@ -74,7 +74,7 @@ soilFactory:registerItems({
{
settings = {
name = "clay_soil_fertile",
title = "Fertile Clay Soil",
_title = "Fertile Clay Soil",
--description = "",
tiles = clayTiles,
},
@@ -83,7 +83,7 @@ soilFactory:registerItems({
{
settings = {
name = "clay_soil_rich",
title = "Rich Clay Soil",
_title = "Rich Clay Soil",
--description = "",
tiles = clayTiles,
},
@@ -96,7 +96,7 @@ soilFactory:registerItems({
{
settings = {
name = "sandy_soil_baren",
title = "Barren Sandy Soil",
_title = "Barren Sandy Soil",
--description = "",
tiles = sandyTiles,
},
@@ -105,7 +105,7 @@ soilFactory:registerItems({
{
settings = {
name = "sandy_soil_poor",
title = "Poor Sandy Soil",
_title = "Poor Sandy Soil",
--description = "",
tiles = sandyTiles,
},
@@ -114,7 +114,7 @@ soilFactory:registerItems({
{
settings = {
name = "sandy_soil_moderate",
title = "Moderate Sandy Soil",
_title = "Moderate Sandy Soil",
--description = "",
tiles = sandyTiles,
},
@@ -123,7 +123,7 @@ soilFactory:registerItems({
{
settings = {
name = "sandy_soil_fertile",
title = "Fertile Sandy Soil",
_title = "Fertile Sandy Soil",
--description = "",
tiles = sandyTiles,
},
@@ -132,7 +132,7 @@ soilFactory:registerItems({
{
settings = {
name = "sandy_soil_rich",
title = "Rich Sandy Soil",
_title = "Rich Sandy Soil",
--description = "",
tiles = sandyTiles,
},
@@ -145,7 +145,7 @@ soilFactory:registerItems({
{
settings = {
name = "mixed_soil_baren",
title = "Barren Mixed Soil",
_title = "Barren Mixed Soil",
--description = "",
tiles = mixedTiles,
},
@@ -154,7 +154,7 @@ soilFactory:registerItems({
{
settings = {
name = "mixed_soil_poor",
title = "Poor Mixed Soil",
_title = "Poor Mixed Soil",
--description = "",
tiles = mixedTiles,
},
@@ -163,7 +163,7 @@ soilFactory:registerItems({
{
settings = {
name = "mixed_soil_moderate",
title = "Moderate Mixed Soil",
_title = "Moderate Mixed Soil",
--description = "",
tiles = mixedTiles,
},
@@ -172,7 +172,7 @@ soilFactory:registerItems({
{
settings = {
name = "mixed_soil_fertile",
title = "Fertile Mixed Soil",
_title = "Fertile Mixed Soil",
--description = "",
tiles = mixedTiles,
},
@@ -181,7 +181,7 @@ soilFactory:registerItems({
{
settings = {
name = "mixed_soil_rich",
title = "Rich Mixed Soil",
_title = "Rich Mixed Soil",
--description = "",
tiles = mixedTiles,
},
@@ -194,43 +194,47 @@ soilFactory:registerItems({
{
settings = {
name = "rocky_soil_baren",
title = "Barren Rocky Soil",
_title = "Barren Rocky Soil",
--description = "",
tiles = rockyTiles,
rarity = 'uncommon'
},
},
---@type Node.NodeDefinition
{
settings = {
name = "rocky_soil_poor",
title = "Poor Rocky Soil",
_title = "Poor Rocky Soil",
--description = "",
tiles = rockyTiles,
rarity = 'distinguished'
},
},
---@type Node.NodeDefinition
{
settings = {
name = "rocky_soil_moderate",
title = "Moderate Rocky Soil",
_title = "Moderate Rocky Soil",
--description = "",
tiles = rockyTiles,
rarity = 'eminent'
},
},
---@type Node.NodeDefinition
{
settings = {
name = "rocky_soil_fertile",
title = "Fertile Rocky Soil",
_title = "Fertile Rocky Soil",
--description = "",
tiles = rockyTiles,
rarity = 'prime'
},
},
---@type Node.NodeDefinition
{
settings = {
name = "rocky_soil_rich",
title = "Rich Rocky Soil",
_title = "Rich Rocky Soil",
--description = "",
tiles = rockyTiles,
},
@@ -248,6 +252,7 @@ Node:new({
groups = {
dig_immediate = 2,
soil_fertiliry = 100, -- Soil fertility for agriculture
}
},
_rarity = 'unique'
}
})

View File

@@ -8,7 +8,7 @@ local TileSheet = Mod.getInfo('smc__core__tilesheet').require('TileSheet')
local defaultRockDef = {
settings = {
name = "",
description = "A log",
_description = "A log",
tiles = {},
groups = {
dig_immediate = 2,
@@ -21,7 +21,7 @@ local defaultRockDef = {
local defaultPlanksDef = {
settings = {
name = "",
description = "A planks",
_description = "A planks",
tiles = {},
groups = {
dig_immediate = 2,
@@ -54,7 +54,7 @@ logFactory:registerItems({
{
settings = {
name = "marentine_log",
title = "Marentine Log",
_title = "Marentine Log",
--description = "",
tiles = t(0, 1),
},
@@ -63,7 +63,7 @@ logFactory:registerItems({
{
settings = {
name = "allwhere_log",
title = "Allwhere Log",
_title = "Allwhere Log",
--description = "",
tiles = t(2, 1),
},
@@ -72,7 +72,7 @@ logFactory:registerItems({
{
settings = {
name = "fis_log",
title = "Fis Log",
_title = "Fis Log",
--description = "",
tiles = t(4, 1),
},
@@ -81,7 +81,7 @@ logFactory:registerItems({
{
settings = {
name = "tammoy_log",
title = "Tammoy Log",
_title = "Tammoy Log",
--description = "",
tiles = t(6, 1),
},
@@ -90,7 +90,7 @@ logFactory:registerItems({
{
settings = {
name = "dallalia_log",
title = "Dallalia Log",
_title = "Dallalia Log",
--description = "",
tiles = t(8, 1),
},
@@ -99,7 +99,7 @@ logFactory:registerItems({
{
settings = {
name = "zuph_log",
title = "Zuph Log",
_title = "Zuph Log",
--description = "",
tiles = t(10, 1),
},
@@ -111,7 +111,7 @@ planksFactory:registerItems({
{
settings = {
name = "marentine_planks",
title = "Marentine Planks",
_title = "Marentine Planks",
--description = "",
tiles = { logTileSheet:t(0, 4) },
},
@@ -120,7 +120,7 @@ planksFactory:registerItems({
{
settings = {
name = "allwhere_planks",
title = "Allwhere Planks",
_title = "Allwhere Planks",
--description = "",
tiles = { logTileSheet:t(2, 4) },
},
@@ -129,7 +129,7 @@ planksFactory:registerItems({
{
settings = {
name = "fis_planks",
title = "Fis Planks",
_title = "Fis Planks",
--description = "",
tiles = { logTileSheet:t(4, 4) },
},
@@ -138,7 +138,7 @@ planksFactory:registerItems({
{
settings = {
name = "tammoy_planks",
title = "Tammoy Planks",
_title = "Tammoy Planks",
--description = "",
tiles = { logTileSheet:t(6, 4) },
},
@@ -147,7 +147,7 @@ planksFactory:registerItems({
{
settings = {
name = "dallalia_planks",
title = "Dallalia Planks",
_title = "Dallalia Planks",
--description = "",
tiles = { logTileSheet:t(8, 4) },
},
@@ -156,7 +156,7 @@ planksFactory:registerItems({
{
settings = {
name = "zuph_planks",
title = "Zuph Planks",
_title = "Zuph Planks",
--description = "",
tiles = { logTileSheet:t(10, 4) },
},
@@ -183,7 +183,7 @@ planksFactory:registerItems({
{
settings = {
name = "case_closed",
title = "Case",
_title = "Case",
--description = "",
tiles = t(0,0)
},
@@ -192,7 +192,7 @@ planksFactory:registerItems({
{
settings = {
name = "case_open",
title = "Case",
_title = "Case",
--description = "",
tiles = t(1,0);
drawtype = 'nodebox';

View File

@@ -1,13 +1,13 @@
local setMetaTable, TableCopy = setmetatable, table.copy_with_metatables
local setMetaTable, tableCopy = setmetatable, table.copy_with_metatables
---@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 = TableCopy(parent) })
---@param child table?
function Class.extend(parent, child)
return setMetaTable(child or {}, { __index = tableCopy(parent) })
end
---Intended for class constructors.
@@ -23,7 +23,7 @@ function Class.getInstance(self, params, metatable)
metatable = {}
end
metatable.__index = TableCopy(self)
metatable.__index = tableCopy(self)
local instance = setMetaTable(params, metatable)

View File

@@ -5,20 +5,16 @@ Events = {}
---@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))
if callbacks == nil then
registeredEvents[eventName] = {callback}
else
table.insert(callbacks, callback)
end
end
---@param eventName string

View File

@@ -5,3 +5,6 @@ local require = modInfo.require
require('Lib.globalStep')
require('Lib.color')
require('Lib.immersiveCraftData')
require('Lib.getObjectByGUID')
require('Lib.receiveFields')

View File

@@ -0,0 +1,16 @@
---Returns an active object by unique identifier (GUID).
---* For players, this is a player name.
---* For Lua entities, this is a uniquely generated string, guaranteed not to collide with player names.
---
---**Note**: If an object with such an identifier does not exist or is inactive, the value `nil` will be returned.
---@param guid string only use printable ASCII characters. Example: `@bGh3p2AbRE29Mb4biqX6OA`.
---@return ObjectRef|Player|Entity|nil
function Smc.getObjectByGUID(guid)
local obj = core.objects_by_guid[guid]
if obj == nil then
return
else
return obj
end
end

View File

@@ -0,0 +1,93 @@
local EMPTY_FLAG = 'EMPTY_FLAG'
---@class ImmersiveStageData
---@class ImmersiveCraftData
---@field craftName string
---@field stageName string
---@field amount integer
---@field stageData ImmersiveStageData?
---Returns craft data for immersive crafting, which is stored in the desktop metadata.
---@param meta NodeMetaRef
---@return ImmersiveCraftData?
function Smc.getCraftDataByMeta(meta)
local dataString = meta:get_string('craft_data')
if dataString == EMPTY_FLAG then
return
end
return core.deserialize(dataString)
end
---Sets craft data for immersive crafting that is stored in the work station metadata.
---
---If `data` is `nil`, the data is cleared.
---@param meta NodeMetaRef
---@param craftData ImmersiveCraftData?
function Smc.setCraftDataByMeta(meta, craftData)
if craftData == nil then
meta:set_string('craft_data', EMPTY_FLAG)
end
meta:set_string('craft_data', core.serialize(craftData))
end
---Returns craft data for immersive crafting, which is stored in the work station metadata.
---@param pos MapPosition
---@return ImmersiveCraftData?
function Smc.getCraftDataByPos(pos)
local meta = core.get_meta(pos)
return Smc.getCraftDataByMeta(meta)
end
---Sets craft data for immersive crafting that is stored in the work station metadata.
---
---If `data` is `nil`, the data is cleared.
---@param pos MapPosition
---@param craftData ImmersiveCraftData?
function Smc.setCraftDataByPos(pos, craftData)
local meta = core.get_meta(pos)
Smc.setCraftDataByMeta(meta, craftData)
end
---Returns stage data for immersive crafting, which is stored in the work station metadata.
---
---**Note**: If the workbench does not have crafting data, an error will be thrown.
---@param pos MapPosition
---@return ImmersiveStageData?
function Smc.getStageDataByPos(pos)
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
return craftData.stageData
end
---Sets stage data for immersive crafting that is stored in the work station metadata.
---@param pos MapPosition
---@param stageData ImmersiveStageData
function Smc.setStageDataByPos(pos, stageData)
local craftData = Smc.getCraftDataByPos(pos)
assert(craftData ~= nil, 'Immersive crafting data is empty.')
craftData.stageData = stageData
Smc.setCraftDataByPos(pos, craftData)
end
---Checks if the workstation is busy or free for new crafting.
---
---The verification is based on `ImmersiveCraftData`.
---@param pos MapPosition
---@return boolean
function Smc.workStationIsFree(pos)
local data = Smc.getCraftDataByPos(pos)
if data == nil then
return true
else
return false
end
end

View File

@@ -0,0 +1,67 @@
---Register a callback for a specific player action in FormSpec.
---
---The callback is guaranteed to be called only for the specified form and the specified field.
---@param formName string the name of the formspec for which the callback will be called.
---@param fieldName string the name of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called.
--- * `fieldValue` - the field value that is passed in the `fields` table.
function Smc.registerOnFormFieldAction(formName, fieldName, callback)
core.register_on_player_receive_fields(function(player, formname, fields)
-- If the form name does not match the given...
if formName ~= formname then
-- ...we do nothing.
return
end
local fieldValue = fields[fieldName]
-- If the field value is not nil (the player called this field)...
if fieldValue ~= nil then
-- ...calling a callback.
callback(player, fieldName, fieldValue)
end
end)
end
---Register a callback function to close the FormSpec.
---
---The callback is guaranteed to be called only for the specified form.
---@param formName string the name of the form that is being closed.
---@param callback fun(player:Player) Callback to handle the close. Parameters:
--- * `player` - the player who closed the form.
function Smc.registerOnFormQuit(formName, callback)
Smc.registerOnFormFieldAction(formName, 'quit', callback)
end
---Register a callback for a specific player action in FormSpec.
---
---The callback function is guaranteed to be called only for the specified form and
---for the field whose name matches the pattern.
---@param formName string the name of the formspec for which the callback will be called.
---@param fieldNamePattern string the name pattern of the field for which the callback will be called.
---@param callback fun(player:Player, fieldName:string, fieldValue:any) Callback to handle the action. Parameters:
--- * `player` - the player who performed the action.
--- * `fieldName` - the name of the field on which the callback is called (will match the pattern).
--- * `fieldValue` - the field value that is passed in the `fields` table.
function Smc.registerOnFormFieldActionMatch(formName, fieldNamePattern, callback)
core.register_on_player_receive_fields(function(player, formname, fields)
-- If the form name does not match the given...
if formName ~= formname then
-- ...we do nothing.
return
end
-- We go through each field in the list of fields.
for fieldName, fieldValue in pairs(fields) do
-- We check the field name pattern compliance.
local capturedName = string.match(fieldName, fieldNamePattern)
-- If the captured name is not nil...
if capturedName ~= nil then
-- ...calling a callback.
callback(player, fieldName, fieldValue)
end
end
end)
end

View File

@@ -156,10 +156,10 @@ local function mergeInPlace(target, source, recursively)
end
--- Merges entries from `t2` into a deep copy of `t1`, skipping existing keys.
--- @param t1 table<string, any> | any[] Target table to merge into
--- @param t2 table<string, any> | any[] Source table to merge from
--- @param t1 table Target table to merge into
--- @param t2 table Source table to merge from
--- @param recursively? boolean Enable recursive merging (default: false)
--- @return table<string, any> | any[]
--- @return table
function table.merge(t1, t2, recursively)
ensureArgType(t1, 'table', 1, 'table.merge')
ensureArgType(t2, 'table', 2, 'table.merge')

View File

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

View File

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

View File

@@ -0,0 +1,64 @@
local modInfo = Mod.getInfo('smc__core__formspec')
local require = modInfo.require
---@type Formspec
local Formspec = require('Formspec')
---@type BaseUI
local BaseUI = Mod.getInfo('smc__core__base_ui').require('BaseUI')
---@param self BaseUI
---@param playerName string
---@param isSelect boolean
---@return string
local function getFormSpecString(self, playerName, isSelect)
local outputs = self:getContex(playerName, 'outputs')
---@type CraftSystem.ImmersiveCraft
local craft = self:getContex(playerName, 'craft')
local listForm = Formspec:new({
size = {x=16, y=8},
})
local listFormItems = Formspec:new()
table.sort(outputs)
local w, h = 0, 0
for result, craftName in pairs(outputs) do
listFormItems:itemImageButton(w, h, 2, 2, result, craftName..'::item_button')
w = w + 2
if w > 9 then
w = 0
h = h + 2
end
end
listForm:
scrollContainer(listFormItems, 0.5, 0.5, 8, 6, 'work_station:list_items', 'vertical'):
scrollbar(8, 0.5, 0.25, 7, 'vertical', 'work_station:list_items')
if isSelect then
local stage = craft.stagesByName[craft.startStageName]
local outputDef = core.registered_nodes[craft.output]
listForm:
itemImage(9, 0.5, 2, 2, craft.output):
areaLabel(9, 6, 2, 1, 'Start crafting:'):
button(9, 6.5, 3, 1, 'work_station:start_craft', 'x1'):
button(12, 6.5,3, 1, 'work_station:start_craft', 'x10'):
areaLabel(11.5, 0.5, 4, 4,
outputDef._title..'\n'..
outputDef._description):
areaLabel(9, 2.5, 6, 4, 'Craft description:'..'\n'..craft:toString())
end
return listForm:toString()
end
---@class WorkStationUI : BaseUI
---@field getFormSpecString fun(self:BaseUI,playerName:string,isSelect:boolean):string
---@field showForm fun(self:BaseUI,playerName:string,isSelect:boolean):string
local WorkStationUI = BaseUI:new('work_station:selection_craft', getFormSpecString)
return WorkStationUI