4 Commits

8 changed files with 420 additions and 1 deletions

View File

@@ -71,6 +71,8 @@ function ProcessingCraftHandler:getCraftByRecipe(input)
return nil return nil
end end
-- TODO: добавить поиск по группам крафтов
local craftHash = getCraftHash(recipe) local craftHash = getCraftHash(recipe)
local craft = self.craftsByHash[craftHash] local craft = self.craftsByHash[craftHash]

View File

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

View File

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

View File

@@ -0,0 +1,343 @@
local FUEL_ENERGY_FACTOR = 10
local getInstance = Class.getInstance
local CraftSystem = Smc.requireCraftSystem()
local PlayerInventoryUI = Smc.requirePlayerInventoryUI()
local Node = Smc.requireNode()
local ProcessingStationNode = Node:getExtended({
settings = {
name = '',
drawtype = 'normal',
paramtype = 'light',
groups = { processing_node = 1, dig_immediate = 2 }
},
})
---@class ProcessingStation
---@field name string
---@field timeout number
---@field enableRegression boolean?
---@field craftType CraftSystem.ProcessingCraftType
---@field fuelGroup string
---@field inputSlots integer
---@field outputSlots integer
---@field fuelSlots integer
---@field handler CraftSystem.ProcessingCraftHandler
---@field tab PlayerInventoryUI.getTabFunc
---@field nodeName string
---@field activeNodeName string?
local ProcessingStation = {}
---Definition table for the `ProcessingStation`.
---
---**Only for EmmyLua.**
---@class ProcessingStationDef
---@field timeout number?
---@field enableRegression boolean?
---@field craftType CraftSystem.ProcessingCraftType
---@field fuelGroup string?
---@field inputSlots integer?
---@field outputSlots integer?
---@field fuelSlots integer?
---@field tab PlayerInventoryUI.getTabFunc
---@param name string
---@param def ProcessingStationDef
---@param nodeDef Node.NodeDefinition
---@param activeNodeDef Node.NodeDefinition?
function ProcessingStation:new(name, def, nodeDef, activeNodeDef)
local handler = CraftSystem:getProcessingCraftHandler(def.craftType)
---@type ProcessingStation
local instance = getInstance(self, {})
instance.name = name
instance.timeout = def.timeout or 1
instance.enableRegression = def.enableRegression
instance.craftType = def.craftType
instance.fuelGroup = def.fuelGroup or 'fuel'
instance.inputSlots = def.inputSlots or 1
instance.outputSlots = def.outputSlots or 1
instance.fuelSlots = def.outputSlots or 1
instance.handler = handler
instance.tab = def.tab
if nodeDef.callbacks == nil then
---@type Node.Callbacks
nodeDef.callbacks = {}
end
local settings = nodeDef.settings
local callbacks = nodeDef.callbacks
-- When we install a station in the world,
-- we initialize the metadata, set the inventory size, and start the timer.
callbacks.on_construct = function(pos)
local meta = core.get_meta(pos)
meta:set_float('remaining_fuel', 0.0)
meta:set_float('processing_time', 0.0)
local inventory = meta:get_inventory()
inventory:set_size('input', instance.inputSlots)
inventory:set_size('output', instance.outputSlots)
inventory:set_size('fuel', instance.fuelSlots)
core.get_node_timer(pos):start(instance.timeout)
end
-- Right-clicking on a station opens the player's inventory, adding context to the station tab.
-- Note: we do not use formspec via node metadata.
callbacks.on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
local playerName = clicker:get_player_name()
PlayerInventoryUI:setContex(playerName, 'left_tab_name', 'node_tab')
PlayerInventoryUI:setContex(playerName, 'node_tab_pos', pos)
PlayerInventoryUI:setContex(playerName, 'node_tab', instance.tab)
PlayerInventoryUI:showForm(playerName)
end
-- Whenever we change items, we start the station timer,
-- because it can be stopped (if the crafting or fuel runs out).
callbacks.on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
local timer = core.get_node_timer(pos)
if not timer:is_started() then
timer:start(instance.timeout)
end
end
callbacks.on_metadata_inventory_put = function(pos, listname, index, stack, player)
local timer = core.get_node_timer(pos)
if not timer:is_started() then
timer:start(instance.timeout)
end
end
callbacks.on_metadata_inventory_take = function(pos, listname, index, stack, player)
local timer = core.get_node_timer(pos)
if not timer:is_started() then
timer:start(instance.timeout)
end
end
-- The basic logic of the station's work.
callbacks.on_timer = function(pos, elapsed, node, timeout)
---An indicator of whether the station
---is processing resources in this iteration.
local isProcessing = true
---@type ProcessingStation.MetaData
local meta = core.get_meta(pos)
local inventory = meta:get_inventory()
---An indicator of how many units of fuel are currently remaining.
local remainingFuel = meta:get_float('remaining_fuel')
---An indicator of how long the station has been processing the materials.
local processingTime = meta:get_float('processing_time')
local craft = handler:getCraftByRecipe(inventory:get_list('input'))
-- If the materials in the input slot are not a recipe for any crafting,
-- then we will not process them.
if craft == nil then
isProcessing = false
end
-- If there is no space in the output slots for the crafting result, then we stop processing.
if isProcessing and craft ~= nil and not inventory:room_for_item('output', craft.output) then
isProcessing = false
end
-- If we are in the process of processing and we run out of fuel,
-- but there are still items in the fuel slot...
if isProcessing and remainingFuel <= 0 and not inventory:is_empty('fuel') then
-- ... then we will convert the first itemstack into station fuel
-- if it has the required fuel group.
local fuelList = inventory:get_list('fuel')
for index, fuelStack in ipairs(fuelList) do
if not fuelStack:is_empty() then
---Fuel units contained in the itemstack.
---
-- Note: since item groups can only contain integers,
-- we divide the fuel units by a constant to convert seconds to smaller units.
local fuelEnergy = core.get_item_group(fuelStack:get_name(), instance.fuelGroup or 'fuel') / FUEL_ENERGY_FACTOR
if fuelEnergy > 0 then
local itemCount = fuelStack:get_count()
-- If the energy of one item is not enough for one iteration,
-- we calculate how many items we need to take
if fuelEnergy < timeout then
itemCount = math.min(math.ceil(timeout/fuelEnergy), itemCount)
else
itemCount = 1
end
remainingFuel = remainingFuel + (fuelEnergy * itemCount)
fuelStack:set_count(itemCount)
inventory:remove_item('fuel', fuelStack)
end
end
end
end
-- If we have fuel remaining,
-- we subtract units for this iteration.
if remainingFuel >= 0 then
remainingFuel = remainingFuel - timeout
end
-- If we don't have fuel remaining,
-- we don't process the materials.
if remainingFuel < 0 then
remainingFuel = 0
isProcessing = false
end
-- If we process materials...
if isProcessing == true then
-- ...then we add the processing progress for this iteration.
processingTime = processingTime + timeout
else
-- ...else we take away progress
-- (if there was progress, but the fuel ran out,
-- the crafting progress will gradually decrease).
if instance.enableRegression then
processingTime = processingTime - timeout
end
end
-- If the station is working and the progress time is longer than required for crafting, we produce the craft
-- (we take the item stacks needed for crafting and put the result of the crafting into the output)
if isProcessing and craft ~= nil and processingTime >= craft.time then
for _, item in ipairs(craft.recipe) do
inventory:remove_item('input', item)
end
inventory:add_item('output', craft.output)
processingTime = 0
end
if processingTime < 0 then
processingTime = 0
end
meta:set_float('processing_time', processingTime)
meta:set_float('remaining_fuel', remainingFuel)
PlayerInventoryUI:updateNodeForm(pos)
-- If the processing is in progress and the station has an active node type, then we use it.
if instance.activeNodeName ~= nil then
if isProcessing then
core.swap_node(pos, {name = instance.activeNodeName})
else
core.swap_node(pos, {name = instance.nodeName})
end
end
-- If we not processing and processing time is zero
-- we stop the timer so as not to overload the server.
--
-- The timer will have to start again
-- if the player interacts with any items in the station's inventory.
if not isProcessing and processingTime == 0 then
return false
else
return true
end
end
-- Registering a nodes for Luanti.
local node = ProcessingStationNode:new(nodeDef)
instance.nodeName = node.itemDef.settings.name
if activeNodeDef ~= nil then
if activeNodeDef.callbacks == nil then
activeNodeDef.callbacks = {}
end
local activeNodeCallbacks = activeNodeDef.callbacks
activeNodeCallbacks.on_construct = callbacks.on_construct
activeNodeCallbacks.on_rightclick = callbacks.on_rightclick
activeNodeCallbacks.on_metadata_inventory_move = callbacks.on_metadata_inventory_move
activeNodeCallbacks.on_metadata_inventory_put = callbacks.on_metadata_inventory_put
activeNodeCallbacks.on_metadata_inventory_take = callbacks.on_metadata_inventory_take
activeNodeCallbacks.on_timer = callbacks.on_timer
local activeNode = ProcessingStationNode:new(activeNodeDef)
instance.activeNodeName = activeNode.itemDef.settings.name
end
return instance
end
--- DEBUG ---
local Formspec = Smc.requireFormspec()
local TileSheet = Smc.requireTileSheet()
local tileSheet = TileSheet:new('debug_processing_station_sheet.png', 16, 16)
local handler = CraftSystem:getProcessingCraftHandler('test')
handler:registerCraft('test_pro_craft', {
output = 'wood:allwhere_log',
recipe = {'wood:allwhere_stick', 'rocks:sylite'},
time = 5,
})
---@param self PlayerInventoryUI
---@param playerName string
---@param tabType PlayerInventoryUI.TabType
---@return Formspec
local tab = function(self, playerName, tabType)
local form = Formspec:new()
local pos = self:getContex(playerName, 'node_tab_pos')
local inventoryLocation = ('nodemeta:%s,%s,%s'):format(pos.x, pos.y, pos.z)
---@type ProcessingStation.MetaData
local meta = core.get_meta(pos)
form
:image(0, 0, 11, 9, 'player_inventory_tab_background.png')
:list(inventoryLocation, 'input', 1, 1, 1, 2)
:list(inventoryLocation, 'output', 3, 1, 1, 1)
:list(inventoryLocation, 'fuel', 1, 4, 1, 1)
:label(4, 3, tostring(meta:get_float('remaining_fuel')))
:label(4.5, 3, tostring(meta:get_float('processing_time')))
return form
end
ProcessingStation:new('test_processing_node', {
craftType = 'test',
tab = tab,
inputSlots = 2,
fuelGroup = 'wood'
},
{
settings = {
name = 'test_processing_node',
tiles = {
tileSheet:t(0, 0),
tileSheet:t(0, 0),
tileSheet:t(0, 1),
tileSheet:t(0, 2),
tileSheet:t(0, 2),
tileSheet:t(0, 2)
}
}
},
{
settings = {
name = 'test_processing_node_active',
tiles = {
tileSheet:t(0, 0),
tileSheet:t(0, 0),
tileSheet:t(1, 1),
tileSheet:t(0, 2),
tileSheet:t(0, 2),
tileSheet:t(0, 2)
}
}
})
return ProcessingStation

View File

@@ -0,0 +1,6 @@
---@alias ProcessingStation.MetaData.FloatKey 'remaining_fuel'|'processing_time'
---**Only for EmmyLua.**
---@class ProcessingStation.MetaData : NodeMetaRef
---@field get_float fun(self, key:ProcessingStation.MetaData.FloatKey):number
---@field set_float fun(self, key:ProcessingStation.MetaData.FloatKey, value:number)

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

View File

@@ -23,6 +23,7 @@ function Mod.getInfo(modname)
local name = modname or core.get_current_modname() local name = modname or core.get_current_modname()
local shortName = getShortModName(name) local shortName = getShortModName(name)
local path = core.get_modpath(name) local path = core.get_modpath(name)
assert(path ~= nil, ('A mod `%s` does not exist.'):format(name))
local require = Require.getModRequire(name, path) local require = Require.getModRequire(name, path)
return {name = name, shortName = shortName, path = path, require = require} return {name = name, shortName = shortName, path = path, require = require}

View File

@@ -1,6 +1,7 @@
local MAX_NODE_TAB_DISTANCE = 20 local MAX_NODE_TAB_DISTANCE = 20
local stringMatch = string.match local stringMatch = string.match
local tableInsert, tableRemoveValue = table.insert, table.remove_value
local BaseUI, Formspec = Smc.requireBaseUI(), Smc.requireFormspec() local BaseUI, Formspec = Smc.requireBaseUI(), Smc.requireFormspec()
local CraftSystem = Smc.requireCraftSystem() local CraftSystem = Smc.requireCraftSystem()
@@ -256,13 +257,60 @@ end
---@field setContex fun(self:PlayerInventoryUI,player:string|Player,key:PlayerInventoryUI.ContexKey,value:any) ---@field setContex fun(self:PlayerInventoryUI,player:string|Player,key:PlayerInventoryUI.ContexKey,value:any)
local PlayerInventoryUI = BaseUI:new('', getFormSpecString, false) local PlayerInventoryUI = BaseUI:new('', getFormSpecString, false)
-- We are overriding the `BaseUI.showForm`. ---@type table<string, string[]>
PlayerInventoryUI.ActiveNodeForms = {}
---@param nodePos MapPosition
function PlayerInventoryUI:addActiveNodeForm(nodePos, playerName)
local stringPos = core.pos_to_string(nodePos)
local playerNames = self.ActiveNodeForms[stringPos]
if playerNames == nil then
self.ActiveNodeForms[stringPos] = { playerNames }
else
tableInsert(playerNames, playerName)
end
end
---@param nodePos MapPosition
function PlayerInventoryUI:updateNodeForm(nodePos)
local stringPos = core.pos_to_string(nodePos)
local playerNames = self.ActiveNodeForms[stringPos]
if playerNames == nil then
return
end
for _, playerName in ipairs(playerNames) do
local player = core.get_player_by_name(playerName)
if player ~= nil then
player:set_inventory_formspec(PlayerInventoryUI:getFormSpecString(playerName))
end
end
end
---@param nodePos MapPosition
function PlayerInventoryUI:removeActiveNodeForm(nodePos, playerName)
local stringPos = core.pos_to_string(nodePos)
local playerNames = self.ActiveNodeForms[stringPos]
if playerNames == nil then
return
end
tableRemoveValue(playerNames, playerName)
end
-- We are overriding the `BaseUI.showForm` & `BaseUI.closeForm`.
local showForm = PlayerInventoryUI.showForm local showForm = PlayerInventoryUI.showForm
local closeForm = PlayerInventoryUI.closeForm
function PlayerInventoryUI:showForm(playerName) function PlayerInventoryUI:showForm(playerName)
local player = core.get_player_by_name(playerName) local player = core.get_player_by_name(playerName)
assert(player ~= nil) assert(player ~= nil)
local nodePos = self:getContex(playerName, 'node_tab_pos')
if nodePos ~= nil then
self:addActiveNodeForm(nodePos, playerName)
end
-- We overwrite the player's inventory definition so that the updated inventory -- We overwrite the player's inventory definition so that the updated inventory
-- is shown to the player when they press the "open inventory" key. -- is shown to the player when they press the "open inventory" key.
player:set_inventory_formspec(PlayerInventoryUI:getFormSpecString(playerName)) player:set_inventory_formspec(PlayerInventoryUI:getFormSpecString(playerName))
@@ -271,10 +319,23 @@ function PlayerInventoryUI:showForm(playerName)
return showForm(self, playerName) return showForm(self, playerName)
end end
function PlayerInventoryUI:closeForm(playerName)
local nodePos = self:getContex(playerName, 'node_tab_pos')
if nodePos ~= nil then
self:removeActiveNodeForm(nodePos, playerName)
end
closeForm(PlayerInventoryUI, playerName)
end
---Clears all data on the node's inventory tab. ---Clears all data on the node's inventory tab.
---@param player Player ---@param player Player
local function closeNodeTab(player) local function closeNodeTab(player)
local playerName = player:get_player_name() local playerName = player:get_player_name()
local nodePos = PlayerInventoryUI:getContex(playerName, 'node_tab_pos')
if nodePos ~= nil then
PlayerInventoryUI:addActiveNodeForm(nodePos, playerName)
end
PlayerInventoryUI:setContex(playerName, 'node_tab_pos', nil) PlayerInventoryUI:setContex(playerName, 'node_tab_pos', nil)
PlayerInventoryUI:setContex(playerName, 'node_tab', nil) PlayerInventoryUI:setContex(playerName, 'node_tab', nil)