diff --git a/mods/CORE/BaseUI/init.lua b/mods/CORE/BaseUI/init.lua new file mode 100644 index 0000000..9b276ca --- /dev/null +++ b/mods/CORE/BaseUI/init.lua @@ -0,0 +1,4 @@ +local modInfo = Mod.getInfo('smc__core__base_ui') +local require = modInfo.require + +return require('BaseUI') diff --git a/mods/CORE/BaseUI/mod.conf b/mods/CORE/BaseUI/mod.conf new file mode 100644 index 0000000..3b698e4 --- /dev/null +++ b/mods/CORE/BaseUI/mod.conf @@ -0,0 +1,2 @@ +name = smc__core__base_ui +depends = smc__system__system_loader diff --git a/mods/CORE/BaseUI/src/BaseUI.lua b/mods/CORE/BaseUI/src/BaseUI.lua new file mode 100644 index 0000000..3695a4a --- /dev/null +++ b/mods/CORE/BaseUI/src/BaseUI.lua @@ -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 +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 diff --git a/mods/CORE/Control/src/Control.lua b/mods/CORE/Control/src/Control.lua index a16ff34..f65b82d 100644 --- a/mods/CORE/Control/src/Control.lua +++ b/mods/CORE/Control/src/Control.lua @@ -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) diff --git a/mods/CORE/CraftSystem/src/CraftSystem.lua b/mods/CORE/CraftSystem/src/CraftSystem.lua index a8691ea..01ae6f9 100644 --- a/mods/CORE/CraftSystem/src/CraftSystem.lua +++ b/mods/CORE/CraftSystem/src/CraftSystem.lua @@ -5,8 +5,6 @@ local require = modInfo.require local PrimitiveCraftHandler = require('CraftSystem.PrimitiveCraftHandler') ---@type CraftSystem.ImmersiveCraftHandler local ImmersiveCraftHandler= require('CraftSystem.ImmersiveCraftHandler') ----@type CraftSystem.ImmersiveCraftNode -local ImmersiveCraftNode= require('CraftSystem.ImmersiveCraftNode') ---@alias CraftSystem.CraftGroup string ---@alias CraftSystem.CraftRecipe string[] @@ -18,13 +16,13 @@ local CraftSystem = {} ---@param craftName string ---@param def CraftSystem.PrimitiveCraftDef function CraftSystem.registerPrimitiveCraft(craftName, def) - PrimitiveCraftHandler:addCraft(craftName, def) + PrimitiveCraftHandler:registerCraft(craftName, def) end ---@param craftName string ---@param def CraftSystem.ImmersiveCraftDef function CraftSystem.registerImmersiveCraft(craftName, def) - ImmersiveCraftHandler:addCraft(craftName, def) + ImmersiveCraftHandler:registerCraft(craftName, def) end return CraftSystem diff --git a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraft.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraft.lua index 0d4952c..c283828 100644 --- a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraft.lua +++ b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraft.lua @@ -5,13 +5,21 @@ local require = modInfo.require ---@type CraftSystem.BaseCraft local BaseCraft = require('CraftSystem.BaseCraft') ----@type CraftSystem.ImmersiveCraftStage -local ImmersiveCraftStage = require('CraftSystem.ImmersiveCraftStage') +---@type CraftSystem.ImmersiveCraftCounter +local ImmersiveCraftCounter = require('CraftSystem.ImmersiveCraftCounter') +---Types of immersive stages. +---@class CraftSystem.StagesTypes : table +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 string +---@field output ItemStackString ---@field stagesByName table local ImmersiveCraft = extend(BaseCraft, {}) @@ -28,24 +36,202 @@ local ImmersiveCraft = extend(BaseCraft, {}) ---@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 local stagesByName = {} for _, stageDef in ipairs(def.stages) do - local stage = ImmersiveCraftStage:new(stageDef) + -- 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 - local instance = getInstance(self, { - name = name, - group = def.group, - startStageName = def.startStageName, - triggerItem = def.triggerItem, - output = def.output, - stagesByName = stagesByName, - }) + ---@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 diff --git a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftCounter.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftCounter.lua new file mode 100644 index 0000000..84be27f --- /dev/null +++ b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftCounter.lua @@ -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> +---@field craftsCountForServer table +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 diff --git a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftHandler.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftHandler.lua index 4a3e916..dafa271 100644 --- a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftHandler.lua +++ b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftHandler.lua @@ -10,6 +10,8 @@ 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 ---@field getCraftByName fun(self, craftName:string):CraftSystem.ImmersiveCraft @@ -19,32 +21,45 @@ 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:addCraft(craftName, def) +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) diff --git a/mods/CORE/CraftSystem/src/CraftSystem/immersiveCraftNode.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode.lua similarity index 59% rename from mods/CORE/CraftSystem/src/CraftSystem/immersiveCraftNode.lua rename to mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode.lua index c84b95a..3b556df 100644 --- a/mods/CORE/CraftSystem/src/CraftSystem/immersiveCraftNode.lua +++ b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode.lua @@ -1,14 +1,13 @@ ---@type Creature -local Creature = Mod.getInfo('smc__core__entity').require('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 = { - - } + initial_properties = {}, } }) diff --git a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode/TapperNode.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode/TapperNode.lua deleted file mode 100644 index 2cbc9f3..0000000 --- a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode/TapperNode.lua +++ /dev/null @@ -1,12 +0,0 @@ -local extend = Class.extend - -local modInfo = Mod.getInfo('smc__core__craft_system') -local require = modInfo.require - ----@type CraftSystem.ImmersiveCraftNode -local ImmersiveCraftNode = require('CraftSystem.ImmersiveCraftNode') - ----@class CraftSystem.ImmersiveCraftNode.TapperNode : CraftSystem.ImmersiveCraftNode -local TapperNode = extend(ImmersiveCraftNode, {}) - -return TapperNode diff --git a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode/tappingNode.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode/tappingNode.lua new file mode 100644 index 0000000..5f08c50 --- /dev/null +++ b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftNode/tappingNode.lua @@ -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 diff --git a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage.lua index fd5bcc7..f2a4cb5 100644 --- a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage.lua +++ b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage.lua @@ -1,36 +1,41 @@ local getInstance = Class.getInstance ----@alias CraftSystem.ImmersiveCraftStage.HandlerFunc fun(self, Player) +---@alias CraftSystem.ImmersiveCraftStage.Type 'tapping' +---One of the stages of immersive crafting. ---@class CraftSystem.ImmersiveCraftStage ---@field name string ----@field startHandler CraftSystem.ImmersiveCraftStage.HandlerFunc ----@field processHandler CraftSystem.ImmersiveCraftStage.HandlerFunc ----@field endHandler CraftSystem.ImmersiveCraftStage.HandlerFunc ----@field returnItems table? TODO: доделать тут тип -local ImmersiveCraftStage = { - data = {} -} +---@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 startHandler CraftSystem.ImmersiveCraftStage.HandlerFunc ----@field processHandler CraftSystem.ImmersiveCraftStage.HandlerFunc ----@field endHandler CraftSystem.ImmersiveCraftStage.HandlerFunc ----@field returnItems table? TODO: доделать тут тип +---@field name string +---@field type CraftSystem.ImmersiveCraftStage.Type +---@field craftName string? +---@field nextStage string? +---@field returnItems ItemStackString[]? ----@param def CraftSystem.ImmersiveCraftStageDef ----@return CraftSystem.ImmersiveCraftStage +---@param def CraftSystem.ImmersiveCraftStageDef +---@return CraftSystem.ImmersiveCraftStage function ImmersiveCraftStage:new(def) - local instance = getInstance(self, { - name = def.name, - startHandler = def.startHandler, - processHandler = def.processHandler, - endHandler = def.endHandler - }) + ---@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 diff --git a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage/Tapping.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage/Tapping.lua deleted file mode 100644 index b47a93b..0000000 --- a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage/Tapping.lua +++ /dev/null @@ -1,38 +0,0 @@ -local getInstance, extend = Class.getInstance, Class.extend - ----@type CraftSystem.ImmersiveCraftStage -local ImmersiveCraftStage = Mod.getInfo('smc__core__craft_system').require('ImmersiveCraftStage') - ----@class CraftSystem.ImmersiveCraftStage.Tapping : CraftSystem.ImmersiveCraftStage ----@field targetItem string ----@field startHandler fun(self:CraftSystem.ImmersiveCraftStage.Tapping, pos:Position, Player:Player) ----@field processHandler fun(self:CraftSystem.ImmersiveCraftStage.Tapping, pos:Position, Player:Player) ----@field endHabdler fun(self:CraftSystem.ImmersiveCraftStage.Tapping, pos:Position, Player:Player) ----@field entity Entity -local Tapping = extend(ImmersiveCraftStage, {}) - ----@class CraftSystem.ImmersiveCraftStage.TappingDef ----@field targetItem string - ----@param def CraftSystem.ImmersiveCraftStage.TappingDef -function Tapping:new(def) - local instance = getInstance(self, {}) - - instance.targetItem = def.targetItem - - instance.startHandler = function(self, pos, Player) - - end - - instance.processHandler = function(self, pos, Player) - - end - - instance.endHabdler = function(self, pos, Player) - - end - - return instance -end - -return Tapping diff --git a/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage/TappingStage.lua b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage/TappingStage.lua new file mode 100644 index 0000000..c9be85d --- /dev/null +++ b/mods/CORE/CraftSystem/src/CraftSystem/ImmersiveCraftStage/TappingStage.lua @@ -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 diff --git a/mods/CORE/CraftSystem/src/CraftSystem/PrimitiveCraft.lua b/mods/CORE/CraftSystem/src/CraftSystem/PrimitiveCraft.lua index d954c77..48c64cd 100644 --- a/mods/CORE/CraftSystem/src/CraftSystem/PrimitiveCraft.lua +++ b/mods/CORE/CraftSystem/src/CraftSystem/PrimitiveCraft.lua @@ -7,23 +7,24 @@ local require = modInfo.require local BaseCraft = require('CraftSystem.BaseCraft') ---@class CraftSystem.PrimitiveCraft : CraftSystem.BaseCraft ----@field output string ----@field recipe CraftSystem.CraftRecipe ----@field returnItems table? TODO: доделать тут тип +---@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 table? TODO: доделать тут тип +---@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, diff --git a/mods/CORE/CraftSystem/src/CraftSystem/PrimitiveCraftHandler.lua b/mods/CORE/CraftSystem/src/CraftSystem/PrimitiveCraftHandler.lua index c898348..6694a36 100644 --- a/mods/CORE/CraftSystem/src/CraftSystem/PrimitiveCraftHandler.lua +++ b/mods/CORE/CraftSystem/src/CraftSystem/PrimitiveCraftHandler.lua @@ -11,15 +11,18 @@ 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 local PrimitiveCraftHandler = extend(BaseCraftHandler, {}) +---Register a primitive craft that does not require special interaction. ---@param craftName string ---@param def CraftSystem.PrimitiveCraftDef -function PrimitiveCraftHandler:addCraft(craftName, def) +function PrimitiveCraftHandler:registerCraft(craftName, def) assert(self.craftsByName[craftName] == nil, ('A craft named `%s` already exists.'):format( craftName)) diff --git a/mods/CORE/Creature/src/Creature.lua b/mods/CORE/Creature/src/Creature.lua index 7619a77..1b2cd5a 100644 --- a/mods/CORE/Creature/src/Creature.lua +++ b/mods/CORE/Creature/src/Creature.lua @@ -55,7 +55,7 @@ function Creature:new(entityDef) -- 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(self, staticdata, dtime) + c.on_activate = function(luaEntity, staticdata, dtime) local initCustomFields = {} if staticdata and staticdata ~= '' then @@ -71,7 +71,7 @@ function Creature:new(entityDef) -- If an initialization callback was specified for the entity, then we call it. if c.on_activate ~= nil then - onActivate(self, staticdata, dtime) + onActivate(luaEntity, staticdata, dtime) end end @@ -83,7 +83,7 @@ function Creature:new(entityDef) instance.entityDef = entityDef instance.luantiDef = luantiDef - core.register_entity(s._name, luantiDef) + core.register_entity(':'..s._name, luantiDef) return instance end diff --git a/mods/CORE/Creature/src/Creature/LuaEntity.lua b/mods/CORE/Creature/src/Creature/LuaEntity.lua new file mode 100644 index 0000000..2c46bf5 --- /dev/null +++ b/mods/CORE/Creature/src/Creature/LuaEntity.lua @@ -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 diff --git a/mods/CORE/Item/src/Item.lua b/mods/CORE/Item/src/Item.lua index 30d7559..150a688 100644 --- a/mods/CORE/Item/src/Item.lua +++ b/mods/CORE/Item/src/Item.lua @@ -103,17 +103,19 @@ local function itemDefToLuantiDef(itemDef) end if s._title_color ~= nil and s._description_color ~= nil then - description = colorize(s._title_color ,S(title))..'\n'.. - colorize(s._description_color, S(description)) + title = colorize(s._title_color ,S(title)) + description = colorize(s._description_color, S(description)) else error('Item description color parameters cannot be empty.') end assert(s._rarity ~= nil, 'The rarity of an item cannot be empty.') - description = addRarityToDesc(s._rarity, description) + local luantiDescription = addRarityToDesc(s._rarity, title..'\n'..description) - s.description = description..core.get_background_escape_sequence('#110F13') + s._title = title + s._description = description + s.description = luantiDescription..core.get_background_escape_sequence('#110F13') local luantiDef = defMerge(s, c) @@ -193,7 +195,7 @@ end ---@param defaultDef Item.ItemDefinition ---@return Item function Item:getExtended(defaultDef) - defaultDef = defMerge(self.defaultDef, defaultDef) + defaultDef = defMerge(defaultDef, self.defaultDef) ---@type Item local ChildClass = extend(self, { diff --git a/mods/CORE/MapGen/src/MapGen.lua b/mods/CORE/MapGen/src/MapGen.lua index e30ab3e..c90af67 100644 --- a/mods/CORE/MapGen/src/MapGen.lua +++ b/mods/CORE/MapGen/src/MapGen.lua @@ -133,7 +133,7 @@ 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 @@ -177,7 +177,7 @@ 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 @@ -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] @@ -315,7 +315,7 @@ function MapGen:getTriangulateBoundaryVertices(triangles) end -- Walk along boundary edges to create ordered vertex list - ---@type Position[] + ---@type MapPosition[] local boundary = {} ---@type table local visited = {} @@ -425,9 +425,9 @@ end function MapGen:registerPeak(layerName, category, def) local layer = self:getLayerByName(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) @@ -473,7 +473,7 @@ 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 `/textures/maps` folder and have the following format `.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 Groups that will be added to all peaks. function MapGen:register2DPeaksFromFile(layerName, map, scale,zeroPos, category, groups) @@ -495,16 +495,17 @@ function MapGen:register2DPeaksFromFile(layerName, map, scale,zeroPos, category, 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 = x + (scale/2) + x = mathRound(x + (scale/2)) end ---@type MapGen.PeakDef local def = { - pos = vector.new(x, 0, z), + pos = {x=x, y=0, z=z}, color = color, groups = groups, } @@ -518,7 +519,7 @@ 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 Groups to be added. function MapGen:addGroupsToPeakByPos(layerName, category, pos, groups) local layer = self:getLayerByName(layerName) @@ -546,7 +547,7 @@ 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` ----@param regionVertices Position[]? The region to which the cave generation will be limited. +---@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) @@ -1023,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 diff --git a/mods/CORE/MapGen/src/MapGen/Peak.lua b/mods/CORE/MapGen/src/MapGen/Peak.lua index a40b52c..d798a48 100644 --- a/mods/CORE/MapGen/src/MapGen/Peak.lua +++ b/mods/CORE/MapGen/src/MapGen/Peak.lua @@ -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 ---@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 diff --git a/mods/CORE/MapGen/src/MapGen/Region.lua b/mods/CORE/MapGen/src/MapGen/Region.lua index 925798b..fd9063b 100644 --- a/mods/CORE/MapGen/src/MapGen/Region.lua +++ b/mods/CORE/MapGen/src/MapGen/Region.lua @@ -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 diff --git a/mods/CORE/MapGen/src/MapGen/Tetrahedron.lua b/mods/CORE/MapGen/src/MapGen/Tetrahedron.lua index c8457aa..9757837 100644 --- a/mods/CORE/MapGen/src/MapGen/Tetrahedron.lua +++ b/mods/CORE/MapGen/src/MapGen/Tetrahedron.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: param-type-not-match local mathAbs = math.abs local getInstance = Class.getInstance diff --git a/mods/CORE/MapGen/src/MapGen/Triangulation.lua b/mods/CORE/MapGen/src/MapGen/Triangulation.lua index 2c2cefc..f459944 100644 --- a/mods/CORE/MapGen/src/MapGen/Triangulation.lua +++ b/mods/CORE/MapGen/src/MapGen/Triangulation.lua @@ -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 diff --git a/mods/CORE/MapGen/src/MapGen/Triangulation/FakePeak.lua b/mods/CORE/MapGen/src/MapGen/Triangulation/FakePeak.lua index c12a183..bbbc7ca 100644 --- a/mods/CORE/MapGen/src/MapGen/Triangulation/FakePeak.lua +++ b/mods/CORE/MapGen/src/MapGen/Triangulation/FakePeak.lua @@ -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'}) diff --git a/mods/CORE/Node/src/Node.lua b/mods/CORE/Node/src/Node.lua index 41cfec9..8ff8a20 100644 --- a/mods/CORE/Node/src/Node.lua +++ b/mods/CORE/Node/src/Node.lua @@ -35,7 +35,7 @@ end ---@param defaultDef Node.NodeDefinition ---@return Node function Node:getExtended(defaultDef) - defaultDef = defMerge(self.defaultDef, defaultDef) + defaultDef = defMerge(defaultDef, self.defaultDef) ---@type Node local ChildClass = Class.extend(self, { diff --git a/mods/CORE/WorkStation/src/WorkStation.lua b/mods/CORE/WorkStation/src/WorkStation.lua index 408c61d..e6d4ac2 100644 --- a/mods/CORE/WorkStation/src/WorkStation.lua +++ b/mods/CORE/WorkStation/src/WorkStation.lua @@ -9,15 +9,18 @@ local WorkStationUI = Mod.getInfo('smc__ui__work_station').require('WorkStationU ---@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} + 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 @@ -36,53 +39,135 @@ local WorkStation = {} 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) - --meta:set_string('work_station_name', name) - --meta:set_string('craft_group', def.group) + -- 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) - Logger.warningLog('Punch') - local crafts = ImmersiveCraftHandler:getCraftsByTriggerItem(itemstack:get_name()) - - if crafts == nil then + -- 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 - self:showSelectionCraftForm(clicker, crafts) + -- 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 - local instance = getInstance(self, { - name = name, - group = def.group, - nodeDef = nodeDef - }) - print('NODEDEF: ',dump(nodeDef.callbacks)) + 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 ----@param player Player ----@param crafts CraftSystem.ImmersiveCraft[] -function WorkStation:showSelectionCraftForm(player, crafts) +---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 i, craft in ipairs(crafts) do - outputs[i] = craft.output + for _, craft in ipairs(crafts) do + outputs[craft.output] = craft.name end - core.show_formspec(player:get_player_name(), 'work_station:selection_craft', WorkStationUI:selectionCraftForm(outputs)) + -- 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 = { @@ -93,20 +178,52 @@ WorkStation:new('test_station', { } }) -ImmersiveCraftHandler:addCraft('bricks', { +ImmersiveCraftHandler:registerCraft('bricks', { triggerItem = 'rocks:sylite', output = 'rocks:sylite_bricks', - startStageName = 'ab', + startStageName = 'tapping', group = 'test', - stages = {}, + stages = { + ---@type CraftSystem.ImmersiveCraftStage.TappingStageDef + { + name = 'tapping', + targetItem = 'rocks:sylite', + type = 'tapping', + clicksNeed = 3, + } + }, }) -ImmersiveCraftHandler:addCraft('block', { +ImmersiveCraftHandler:registerCraft('block', { triggerItem = 'rocks:sylite', output = 'rocks:sylite_block', - startStageName = 'ab', + startStageName = 'tapping', group = 'test', - stages = {}, + 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 diff --git a/mods/GAME/ITEMS/rocks/init.lua b/mods/GAME/ITEMS/rocks/init.lua index 87be972..13c6e90 100644 --- a/mods/GAME/ITEMS/rocks/init.lua +++ b/mods/GAME/ITEMS/rocks/init.lua @@ -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, diff --git a/mods/GAME/ITEMS/rocks/locale/rocks.ru.tr b/mods/GAME/ITEMS/rocks/locale/rocks.ru.tr new file mode 100644 index 0000000..0c7cb12 --- /dev/null +++ b/mods/GAME/ITEMS/rocks/locale/rocks.ru.tr @@ -0,0 +1,6 @@ +# textdomain: rocks + +sylite_block-title=Силитовый блок +sylite_block-desc=Массивный блок из цельного куска силита. +sylite_bricks-title=Силитовые кирпичи +sylite_bricks-desc=Кладка из силитовых кирпичей. \ No newline at end of file diff --git a/mods/SYSTEM/Events/init.lua b/mods/SYSTEM/Events/init.lua index 42bea3f..779999b 100644 --- a/mods/SYSTEM/Events/init.lua +++ b/mods/SYSTEM/Events/init.lua @@ -5,20 +5,16 @@ Events = {} ---@type table local registeredEvents = {} ----@param eventName string -function Events.registerEvent(eventName) - assert(registeredEvents[eventName] == nil, ('Event %s is already registered.'):format(eventName)) - - registeredEvents[eventName] = {} -end - ---@param eventName string ---@param callback Events.callback function Events.subscribe(eventName, callback) local callbacks = registeredEvents[eventName] - assert(callbacks ~= nil, ('Event %s does not exist'):format(eventName)) - table.insert(callbacks, callback) + if callbacks == nil then + registeredEvents[eventName] = {callback} + else + table.insert(callbacks, callback) + end end ---@param eventName string @@ -30,4 +26,4 @@ function Events.call(eventName, ...) for _, func in ipairs(callbacks) do func(eventName, ...) end -end \ No newline at end of file +end diff --git a/mods/SYSTEM/HelperLib/src/Lib.lua b/mods/SYSTEM/HelperLib/src/Lib.lua index 526150e..e8050ee 100644 --- a/mods/SYSTEM/HelperLib/src/Lib.lua +++ b/mods/SYSTEM/HelperLib/src/Lib.lua @@ -5,3 +5,6 @@ local require = modInfo.require require('Lib.globalStep') require('Lib.color') +require('Lib.immersiveCraftData') +require('Lib.getObjectByGUID') +require('Lib.receiveFields') \ No newline at end of file diff --git a/mods/SYSTEM/HelperLib/src/Lib/getObjectByGUID.lua b/mods/SYSTEM/HelperLib/src/Lib/getObjectByGUID.lua new file mode 100644 index 0000000..be359f2 --- /dev/null +++ b/mods/SYSTEM/HelperLib/src/Lib/getObjectByGUID.lua @@ -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 diff --git a/mods/SYSTEM/HelperLib/src/Lib/immersiveCraftData.lua b/mods/SYSTEM/HelperLib/src/Lib/immersiveCraftData.lua new file mode 100644 index 0000000..9c98299 --- /dev/null +++ b/mods/SYSTEM/HelperLib/src/Lib/immersiveCraftData.lua @@ -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 diff --git a/mods/SYSTEM/HelperLib/src/Lib/receiveFields.lua b/mods/SYSTEM/HelperLib/src/Lib/receiveFields.lua new file mode 100644 index 0000000..d6ce543 --- /dev/null +++ b/mods/SYSTEM/HelperLib/src/Lib/receiveFields.lua @@ -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 diff --git a/mods/UI/WorkStationUI/src/WorkStationUI.lua b/mods/UI/WorkStationUI/src/WorkStationUI.lua index 6b359d7..9927dc4 100644 --- a/mods/UI/WorkStationUI/src/WorkStationUI.lua +++ b/mods/UI/WorkStationUI/src/WorkStationUI.lua @@ -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 -return WorkStationUI \ No newline at end of file +---@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 diff --git a/util/ide-helper b/util/ide-helper index e5a12d3..a8dfcb7 160000 --- a/util/ide-helper +++ b/util/ide-helper @@ -1 +1 @@ -Subproject commit e5a12d31babc80d125c6a37185edb52a58023b51 +Subproject commit a8dfcb767b725352383882e5e6f7fabe0d5ec606