4 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
5 changed files with 265 additions and 40 deletions

View File

@@ -3,17 +3,20 @@ 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 contex table<string, table>
---@field name string
---@field getFormSpecString fun(self:BaseUI,playerName:string,...):string
---@field contex table<string, table>
local BaseUI = {
contex = {}
}
---@param name string
function BaseUI:new(name)
---@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)
@@ -103,4 +106,17 @@ 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

@@ -5,6 +5,8 @@ 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>
@@ -95,10 +97,44 @@ function ImmersiveCraft:new(name, def)
end
---Initialize the start of the immersive crafting process.
---
---Returns `true` if the crafting process was running.
---@param pos MapPosition
---@param Player Player
function ImmersiveCraft:startCraft(pos, Player)
-- TODO: забирать из инвентаря игрока материалы для крафта
---@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]
@@ -108,24 +144,94 @@ function ImmersiveCraft:startCraft(pos, Player)
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)
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)
-- We drop away the result of crafting.
-- TODO: переписать определение этого метода в хелпере: itemstack не может быть строкой, а dropper опционален
core.item_drop(ItemStack(self.output), nil, vector.new(pos)+vector.new(0, 0.9,0))
-- 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

@@ -14,6 +14,7 @@ local ImmersiveCraftStage = require('CraftSystem.ImmersiveCraftStage')
---@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`.
@@ -42,7 +43,7 @@ function TappingStage:new(def)
-- 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.9,0)
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
@@ -70,7 +71,6 @@ function TappingStage:new(def)
-- Saving temporary data in work station metadata.
setStageDataByPos(pos, stageData)
print(pos, dump(Smc.getCraftDataByPos(pos)), 'ONE')
end
-- Registering the crafting stage process handler.
@@ -79,7 +79,6 @@ function TappingStage:new(def)
-- Obtaining stage time data from work station metadata.
---@type ImmersiveStageData.TappingStageData?
local stageData = getStageDataByPos(pos)
print(dump(pos), dump(Smc.getCraftDataByPos(pos)), 'TWO')
assert(stageData ~= nil, 'Immersive stage data is empty.')
-- Increasing the click counter
@@ -115,9 +114,64 @@ function TappingStage:new(def)
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),
function(eventName, pos, Player)
---@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)

View File

@@ -99,46 +99,71 @@ function WorkStation:new(name, def)
return instance
end
---@param player Player
---@param crafts CraftSystem.ImmersiveCraft[]
---@param pos Position
---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)
core.show_formspec(playerName, 'work_station:selection_craft', WorkStationUI:selectionCraftForm(playerName, false))
-- 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)
---@type ItemStackString?
-- 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')
if craftName == nil then
return
end
-- 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)
core.show_formspec(playerName, 'work_station:selection_craft', WorkStationUI:selectionCraftForm(playerName, true))
-- 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()
local pos = WorkStationUI:getContex(playerName, 'pos')
-- 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')
craft:startCraft(pos, player)
core.close_formspec(playerName, 'work_station:selection_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 ---

View File

@@ -4,23 +4,28 @@ local require = modInfo.require
---@type Formspec
local Formspec = require('Formspec')
---@class WorkStationUI
local WorkStationUI = {}
---@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')
---@param items string[]
---@return string
function WorkStationUI:selectionCraftForm(items)
local listForm = Formspec:new({
size = {x=10, y=8},
size = {x=16, y=8},
})
local listFormItems = Formspec:new()
table.sort(items)
table.sort(outputs)
local w, h = 0, 0
---@param name string
for _, name in ipairs(items) do
listFormItems:itemImageButton(w, h, 2, 2, name, name..'::item_button')
for result, craftName in pairs(outputs) do
listFormItems:itemImageButton(w, h, 2, 2, result, craftName..'::item_button')
w = w + 2
@@ -34,7 +39,26 @@ function WorkStationUI:selectionCraftForm(items)
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