6 Commits
Author SHA1 Message Date
Overlord 015bcd8545 Merge branch 'release/v1.0.1' 2026-09-18 22:39:56 +02:00
Overlord f9eccc68be Re-add helper function for file text management (fix). 2026-09-18 22:39:43 +02:00
Overlord ddb8ff718c Merge branch 'release/v1.0.0' 2026-09-18 22:12:37 +02:00
Overlord 2a7eac1a2e Merge tag 'v1.0.0' into develop
Tagging version v1.0.0 v1.0.0
2026-09-18 22:12:37 +02:00
Overlord 8d3be04061 added Repackable Items mod 2026-09-18 22:12:18 +02:00
Overlord ca19a3650c added .gitignore 2026-09-16 23:07:29 +02:00
18 changed files with 1295 additions and 0 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# Added by pz setup -- shared-tooling symlinks, machine-local
!README.md
*.md
.emmyrc.json
lib
.*/
__pycache__/
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

@@ -0,0 +1,40 @@
--[[
Shown by RepackableItems_Live (client) when this client's box/carton
definitions differ from the server's. The server's file has already been
saved by then; it only loads when the client connects, so the player has
to rejoin. Leaves the same way vanilla's disconnect screen
does (ISServerDisconnectUI: getCore():exitToMenu()).
]]
RepackableItems_RejoinPrompt = {}
local dialog = nil
local function onClick(_target, _button)
dialog = nil
getCore():exitToMenu()
end
function RepackableItems_RejoinPrompt.show()
--- @diagnostic disable-next-line: unnecessary-if
if dialog then
return
end
local width, height = 420, 150
local x = (getCore():getScreenWidth() - width) / 2
local y = (getCore():getScreenHeight() - height) / 2
dialog = ISModalDialog:new(
x, y, width, height,
getText("IGUI_RepackableItems_RejoinRequired"),
false, nil, onClick, 0
)
dialog:initialise()
dialog:addToUIManager()
dialog:setAlwaysOnTop(true)
end
return RepackableItems_RejoinPrompt
@@ -0,0 +1,108 @@
require("RepackableItems/RepackableItems_Options")
require("RepackableItems/RepackableItems_Eligibility")
RepackableItems_Config = {}
local function warn(msg)
print("[RepackableItems] " .. msg)
end
local function splitTrim(str, sep)
local parts = {}
for part in string.gmatch(str, "([^" .. sep .. "]+)") do
-- Also strips quotes: the Sandbox Options text field can leave a
-- stray `"` on the last record when pasting over the quoted default.
table.insert(parts, string.match(part, "^[%s\"]*(.-)[%s\"]*$"))
end
return parts
end
---Parses one `fullType:boxCount:cartonCount[:boxWeightOverride[:cartonWeightOverride]]` record.
---@return table|nil parsed, string|nil error
local function parseRecord(raw)
local fields = splitTrim(raw, ":")
if #fields < 3 then
return nil, "expected at least 3 fields (fullType:boxCount:cartonCount), got: '" .. raw .. "'"
end
local fullType = fields[1]
local boxCount = tonumber(fields[2])
local cartonCount = tonumber(fields[3])
local boxWeightOverride = fields[4] ~= nil and fields[4] ~= "" and tonumber(fields[4]) or nil
local cartonWeightOverride = fields[5] ~= nil and fields[5] ~= "" and tonumber(fields[5]) or nil
if fullType == "" then
return nil, "empty fullType in record: '" .. raw .. "'"
end
if not boxCount or boxCount <= 0 then
return nil, "boxCount must be a positive number, got '" .. tostring(fields[2]) .. "' in record: '" .. raw .. "'"
end
if not cartonCount or cartonCount <= 0 then
return nil, "cartonCount must be a positive number, got '" .. tostring(fields[3]) .. "' in record: '" .. raw .. "'"
end
return {
fullType = fullType,
boxCount = math.floor(boxCount),
cartonCount = math.floor(cartonCount),
boxWeightOverride = boxWeightOverride,
cartonWeightOverride = cartonWeightOverride,
}
end
---@return number weight of one full box for `record`
function RepackableItems_Config.computeBoxWeight(record)
if record.boxWeightOverride then
return record.boxWeightOverride
end
local scriptItem = ScriptManager.instance:getItem(record.fullType)
local unitWeight = scriptItem and scriptItem:getActualWeight() or 0
local factor = RepackableItems_Options.get("GlobalWeightFactor") or 1.0
return unitWeight * record.boxCount * factor
end
---@return number weight of one full carton for `record`
function RepackableItems_Config.computeCartonWeight(record)
if record.cartonWeightOverride then
return record.cartonWeightOverride
end
return RepackableItems_Config.computeBoxWeight(record) * record.cartonCount
end
---Parses SandboxVars.RepackableItems.ItemList into a validated, deduplicated
---list of records.
---@return table[] records
function RepackableItems_Config.getValidatedRecords()
local records = {}
local seen = {}
if not RepackableItems_Options.get("Enabled") then
return records
end
local raw = RepackableItems_Options.get("ItemList") or ""
if raw == "" then
return records
end
for _, rawRecord in ipairs(splitTrim(raw, ";")) do
local record, err = parseRecord(rawRecord)
if not record then
warn("skipping malformed config entry -- " .. err)
elseif seen[record.fullType] then
warn("skipping duplicate entry for " .. record.fullType .. " (first occurrence wins)")
else
local eligible, reason = RepackableItems_Eligibility.isEligibleForRepacking(record.fullType)
if not eligible then
warn("skipping " .. record.fullType .. " -- " .. reason)
else
seen[record.fullType] = true
table.insert(records, record)
end
end
end
return records
end
@@ -0,0 +1,40 @@
require("RepackableItems/RepackableItems_VanillaDenylist")
RepackableItems_Eligibility = {}
--- DisplayCategories of equipment, weapons and containers. Vanilla only packs
--- plain stackable materials; this is a heuristic, not an exhaustive list.
local UNSUITABLE_DISPLAY_CATEGORIES = {
Weapon = true,
WeaponPart = true,
Clothing = true,
Container = true,
}
---@param fullType string e.g. "Base.WaterPurificationTablets"
---@return boolean eligible
---@return string|nil reason present only when eligible == false
function RepackableItems_Eligibility.isEligibleForRepacking(fullType)
local scriptItem = ScriptManager.instance:getItem(fullType)
if not scriptItem then
return false, "unknown item type"
end
if RepackableItems_VanillaDenylist[fullType] then
return false, "already vanilla-packable"
end
local displayCategory = scriptItem:getDisplayCategory()
if displayCategory and UNSUITABLE_DISPLAY_CATEGORIES[displayCategory] then
return false, "item type not suitable for generic repacking (DisplayCategory=" .. displayCategory .. ")"
end
--- @diagnostic disable-next-line: undefined-field
if scriptItem.canBeEquipped ~= nil then
return false, "item is equippable"
end
return true
end
return RepackableItems_Eligibility
@@ -0,0 +1,115 @@
--- @diagnostic disable: need-check-nil
require("RepackableItems/RepackableItems_Config")
require("RepackableItems/RepackableItems_RecipeCode")
require("RepackableItems/RepackableItems_Types")
--[[
Keeps the generated file in step with the Sandbox config, and makes sure
clients load the same file the server booted with.
Server: remembers the file text it booted with, syncs on start and every
30s, and answers each client's "request" with that boot text plus the
current (possibly not yet applied) text.
Client: compares the file it loaded with the server's boot text. If they
differ, it saves the server's and asks the player to rejoin, since
scripts only load on connect. The request is sent on the first OnTick,
not OnGameStart: GameClient.ingame isn't set yet then, so
sendClientCommand would never reach the server.
Single player: syncs on start and every 30s; changes apply on next load.
]]
RepackableItems_Live = {}
--
local MOD_ID = "RepackableItems"
local function warn(msg)
print("[RepackableItems] " .. msg)
end
local function sync()
return RepackableItems_Types.sync(RepackableItems_Config.getValidatedRecords())
end
--
RepackableItems_Live.sync = sync
local SYNC_INTERVAL_MS = 30000
local lastSyncMs = 0
-- OnTickEvenPaused fires at the top of every IngameState update, paused or not,
-- unlike OnTick and EveryTenMinutes, which stop while the game is paused.
local function periodicSync()
local now = getTimestampMs()
if now - lastSyncMs >= SYNC_INTERVAL_MS then
lastSyncMs = now
sync()
end
end
if isServer() then
Events.OnServerStarted.Add(function()
RepackableItems_Types.captureBootText()
lastSyncMs = getTimestampMs()
sync()
end)
Events.OnTickEvenPaused.Add(periodicSync)
Events.OnClientCommand.Add(function(module, command, player, args)
if module == MOD_ID and command == "request" then
sendServerCommand(player, MOD_ID, "types", {
text = RepackableItems_Types.getBootText() or "",
current = RepackableItems_Types.getFileText(),
})
end
end)
elseif isClient() then
-- What this client's scripts were loaded from.
local loadedText = RepackableItems_Types.readFile() or ""
local promptedRejoin = false
Events.OnServerCommand.Add(function(module, command, args)
if module ~= MOD_ID or command ~= "types" then
return
end
local serverText = args.text or ""
if serverText == loadedText or promptedRejoin then
return
end
if args.current and args.current == loadedText then
-- The client shares the server's mod folder (hosted co-op) and
-- loaded a change that isn't applied yet. Overwriting it would undo
-- that change and a rejoin wouldn't help; only a restart does.
warn("The server has item list changes waiting for a restart, packing may not match the server, until then.")
return
end
promptedRejoin = true
RepackableItems_Types.writeFile(serverText)
warn("This client's box/carton definitions differ from the server's; saved the server's, rejoin required!")
--- @diagnostic disable-next-line: unnecessary-if
if RepackableItems_RejoinPrompt then
RepackableItems_RejoinPrompt.show()
end
end)
local function requestTypes()
Events.OnTick.Remove(requestTypes)
sendClientCommand(MOD_ID, "request", {})
end
Events.OnTick.Add(requestTypes)
else
Events.OnGameStart.Add(sync)
Events.OnTickEvenPaused.Add(periodicSync)
end
return RepackableItems_Live
@@ -0,0 +1,21 @@
RepackableItems_Options = {}
--- Mirrors the defaults declared in sandbox-options.txt.
local DEFAULTS = {
Enabled = true,
ItemList = "Base.WaterPurificationTablets:8:6;Base.AlcoholWipes:24:6;Base.PillsVitamins:12:6;Base.Pills:12:6;Base.PillsBeta:12:6;Base.PillsAntiDep:12:6;Base.Disinfectant:6:6;Base.PillsSleepingTablets:12:6;Base.Soap2:8:6",
GlobalWeightFactor = 1.0,
}
---@param name string a RepackableItems.* sandbox option name, without the "RepackableItems." prefix
---@return any
function RepackableItems_Options.get(name)
local sv = SandboxVars and SandboxVars.RepackableItems
local value = sv and sv[name]
if value == nil then
return DEFAULTS[name]
end
return value
end
@@ -0,0 +1,216 @@
require("RepackableItems/RepackableItems_Types")
--[[
OnCreate handlers for the generated recipes. They run on the server (or SP)
inside vanilla's ISHandcraftAction:performRecipe(), which:
1. adds each declared output to the inventory and sends it to the client,
2. calls OnCreate,
3. destroys the consumed inputs.
Changing an output here would only change the server's copy, so it is
swapped for a fully set-up replacement sent through the normal add path
(replaceCreated). Items added here are set up completely before being
sent and never synced afterwards: syncItemFields() on an item the client
doesn't have crashes the client, and it doesn't carry actualWeight for
non-food items anyway.
A box's ModData keeps which item, how many, and each unit's remaining
uses; a carton keeps a copy of each packed box's ModData (packedBoxes), so
per-unit state survives item -> box -> carton -> box -> item.
]]
RepackableItems_RecipeCode = {}
local function warn(msg)
print("[RepackableItems] " .. msg)
end
--- Item plumbing ---------------------------------------------------------------
---Adds a fully set-up item to the character's inventory and sends it to the
---client, like vanilla RecipeCodeHelper.addItemToCharacterInventory.
local function giveItem(character, item)
local inventory = character:getInventory()
if not inventory:contains(item) then
inventory:AddItem(item)
end
sendAddItemToContainer(inventory, item)
end
---Takes back a declared recipe output that the craft pipeline already added
---(and sent) before OnCreate ran.
local function takeBackCreated(item)
local container = item:getContainer()
if container then
container:Remove(item)
sendRemoveItemFromContainer(container, item)
elseif item:getWorldItem() then
-- addOrDropItem put it on the floor (character over capacity).
local worldItem = item:getWorldItem()
worldItem:getSquare():transmitRemoveItemFromSquare(worldItem)
end
end
---Swaps a declared recipe output (already added and sent) for a fully set-up
---replacement.
local function replaceCreated(character, original, replacement)
takeBackCreated(original)
giveItem(character, replacement)
end
--- ModData helpers ------------------------------------------------------------
local function copyTable(src)
local dst = {}
for k, v in pairs(src) do
if type(v) == "table" then
dst[k] = copyTable(v)
else
dst[k] = v
end
end
return dst
end
---Records which item, how many, and each unit's remaining uses.
local function recordPackedUnits(modData, consumed)
modData.packedItemType = consumed:get(0):getFullType()
modData.packedItemCount = consumed:size()
for i = 0, consumed:size() - 1 do
local unit = consumed:get(i)
local ok, uses = pcall(function() return unit:getCurrentUsesFloat() end)
if ok and uses then
modData["packedItemUses" .. i] = uses
end
end
end
---Gives back the units recorded by recordPackedUnits.
local function giveUnpackedUnits(character, modData, fullType, count)
for i = 0, count - 1 do
local newItem = instanceItem(fullType)
--- @diagnostic disable-next-line: unnecessary-if
if newItem then
local uses = modData["packedItemUses" .. i]
if uses then
pcall(function() newItem:setCurrentUsesFloat(uses) end)
end
giveItem(character, newItem)
end
end
end
---Copies of each box's ModData, for storing inside a carton.
local function packedBoxesOf(boxes)
local list = {}
for _, box in ipairs(boxes) do
table.insert(list, copyTable(box:getModData()))
end
return list
end
local function toLuaList(javaList)
local list = {}
for i = 0, javaList:size() - 1 do
table.insert(list, javaList:get(i))
end
return list
end
--- Per-item Box_*/Carton_* types ---------------------------------------------------
-- Name and weight come from the generated item script; only ModData is set.
function RepackableItems_RecipeCode.onCreateTypedBox(data, character)
local consumed = data:getAllConsumedItems()
local created = data:getAllCreatedItems()
if consumed:isEmpty() or created:isEmpty() then
return
end
local original = created:get(0)
local box = instanceItem(original:getFullType())
recordPackedUnits(box:getModData(), consumed)
replaceCreated(character, original, box)
end
function RepackableItems_RecipeCode.onUnpackTypedBox(data, character)
local consumed = data:getAllConsumedItems()
if consumed:isEmpty() then
return
end
local box = consumed:get(0)
local modData = box:getModData()
local entry = RepackableItems_Types.getEntryByBoxType(box:getFullType())
local fullType = modData.packedItemType or (entry and entry.fullType)
local count = modData.packedItemCount or (entry and entry.boxCount)
if not fullType or not count then
warn("onUnpackTypedBox: can't tell what " .. box:getFullType() .. " contains; nothing to unpack!")
return
end
giveUnpackedUnits(character, modData, fullType, count)
end
function RepackableItems_RecipeCode.onCreateTypedCarton(data, character)
local consumed = data:getAllConsumedItems()
local created = data:getAllCreatedItems()
if consumed:isEmpty() or created:isEmpty() then
return
end
local boxes = toLuaList(consumed)
local original = created:get(0)
local carton = instanceItem(original:getFullType())
local modData = carton:getModData()
local entry = RepackableItems_Types.getEntryByBoxType(boxes[1]:getFullType())
modData.packedItemType = entry and entry.fullType or boxes[1]:getModData().packedItemType
modData.packedBoxCount = #boxes
modData.packedBoxes = packedBoxesOf(boxes)
replaceCreated(character, original, carton)
end
function RepackableItems_RecipeCode.onUnpackTypedCarton(data, character)
local consumed = data:getAllConsumedItems()
if consumed:isEmpty() then
return
end
local carton = consumed:get(0)
local modData = carton:getModData()
local entry = RepackableItems_Types.getEntryByCartonType(carton:getFullType())
local fullType = modData.packedItemType or (entry and entry.fullType)
local boxCount = modData.packedBoxCount or (entry and entry.cartonCount)
if not fullType or not boxCount then
warn("onUnpackTypedCarton: can't tell what " .. carton:getFullType() .. " contains; nothing to unpack!")
return
end
local boxType = RepackableItems_Types.boxType(fullType)
local stored = modData.packedBoxes
for i = 1, boxCount do
local box = instanceItem(boxType)
if box then
local md = box:getModData()
if stored and stored[i] then
for k, v in pairs(copyTable(stored[i])) do
md[k] = v
end
else
md.packedItemType = fullType
md.packedItemCount = entry and entry.boxCount or 0
end
giveItem(character, box)
end
end
end
@@ -0,0 +1,131 @@
--[[
Builds the craftRecipe blocks that RepackableItems_Types writes into the
generated script file, next to the item types they use.
- Pack / pack-carton: configured items only. Per-type counts, IsExclusive
and an itemMapper, like vanilla PlaceInBox / Place12BoxesInCarton, so
the engine itself keeps different items apart.
- Unpack / unpack-carton: every item in the file, including ones removed
from the config, so existing boxes stay openable. No declared outputs
(like vanilla PurifyWater); OnCreate adds the contents.
]]
RepackableItems_RecipeGen = {}
-- Not required here: RepackableItems_Types requires this file, so look it up
-- at call time instead of load time.
local function T()
return RepackableItems_Types
end
local function mapperBlock(pairsList)
local lines = { " itemMapper itemType", " {" }
for _, p in ipairs(pairsList) do
table.insert(lines, " " .. p[1] .. " = " .. p[2] .. ",")
end
table.insert(lines, " }")
return table.concat(lines, "\n")
end
local function packRecipe(entries)
local inputs, mapping = {}, {}
for _, e in ipairs(entries) do
table.insert(inputs, e.boxCount .. ":" .. e.fullType)
table.insert(mapping, { T().boxType(e.fullType), e.fullType })
end
return string.format([[
craftRecipe RepackableItems_PackTyped
{
timedAction = PackingBox_Small,
time = 80,
Tags = InHandCraft;Packing,
category = Packing,
OnCreate = RepackableItems_RecipeCode.onCreateTypedBox,
inputs
{
item 1 [%s] mode:destroy mappers[itemType] flags[AllowFavorite;InheritFavorite;IsExclusive;ItemCount],
}
outputs
{
item 1 mapper:itemType,
}
%s
}
]], table.concat(inputs, ";"), mapperBlock(mapping))
end
local function packCartonRecipe(entries)
local inputs, mapping = {}, {}
for _, e in ipairs(entries) do
table.insert(inputs, e.cartonCount .. ":" .. T().boxType(e.fullType))
table.insert(mapping, { T().cartonType(e.fullType), T().boxType(e.fullType) })
end
return string.format([[
craftRecipe RepackableItems_PackCartonTyped
{
timedAction = PackingBox,
time = 80,
Tags = InHandCraft;Packing,
category = Packing,
OnCreate = RepackableItems_RecipeCode.onCreateTypedCarton,
inputs
{
item 1 [%s] mode:destroy mappers[itemType] flags[AllowFavorite;InheritFavorite;IsExclusive;ItemCount],
}
outputs
{
item 1 mapper:itemType,
}
%s
}
]], table.concat(inputs, ";"), mapperBlock(mapping))
end
local function unpackRecipe(name, timedAction, time, onCreate, inputTypes)
return string.format([[
craftRecipe %s
{
timedAction = %s,
time = %d,
Tags = InHandCraft;Packing;CanBeDoneInDark,
category = Packing,
recipeGroup = OpenBox,
OnCreate = %s,
inputs
{
item 1 [%s] mode:destroy flags[AllowFavorite;InheritFavorite],
}
outputs
{
}
}
]], name, timedAction, time, onCreate, table.concat(inputTypes, ";"))
end
---@param configured table[] entries for currently configured items
---@param all table[] every entry in the file (configured or not)
---@return string recipe blocks, to be placed inside `module RepackableItems { }`
function RepackableItems_RecipeGen.buildRecipesText(configured, all)
local parts = {}
if #configured > 0 then
table.insert(parts, packRecipe(configured))
table.insert(parts, packCartonRecipe(configured))
end
if #all > 0 then
local boxes, cartons = {}, {}
for _, e in ipairs(all) do
table.insert(boxes, T().boxType(e.fullType))
table.insert(cartons, T().cartonType(e.fullType))
end
table.insert(parts, unpackRecipe("RepackableItems_UnpackTyped", "UnPackBox_Small", 40,
"RepackableItems_RecipeCode.onUnpackTypedBox", boxes))
table.insert(parts, unpackRecipe("RepackableItems_UnpackCartonTyped", "UnPackBox", 60,
"RepackableItems_RecipeCode.onUnpackTypedCarton", cartons))
end
return table.concat(parts, "\n")
end
return RepackableItems_RecipeGen
@@ -0,0 +1,319 @@
require("RepackableItems/RepackableItems_Config")
require("RepackableItems/RepackableItems_RecipeGen")
--[[
Generates per-item box/carton types (e.g. RepackableItems.Box_Base_Soap2)
and their recipes into common/media/scripts/repackable_items_generated.txt.
The engine only discovers new item types at boot, so a config change is
written right away and applies at the next restart.
The file is append-only: booting without a type the world already knows
deletes every box/carton of it. Removed items keep their types and unpack
recipes; only their pack recipes go. Each save also records its types in
global ModData, so a wiped mod folder gets the file rewritten (with a
warning to restart before players join) instead of losing boxes.
In MP every client must load exactly what the server booted with; see
RepackableItems_Live for how that's checked. Needs DoLuaChecksum=false,
or clients without the file are kicked for a script checksum mismatch.
]]
RepackableItems_Types = {}
local MOD_ID = "RepackableItems"
local FILE_PATH = "media/scripts/repackable_items_generated.txt"
local MODDATA_KEY = "RepackableItems_Types"
local function warn(msg)
print("[RepackableItems] " .. msg)
end
--- Naming -------------------------------------------------------------------
local function sanitize(fullType)
return (string.gsub(fullType, "[^%w]", "_"))
end
function RepackableItems_Types.boxName(fullType)
return "Box_" .. sanitize(fullType)
end
function RepackableItems_Types.cartonName(fullType)
return "Carton_" .. sanitize(fullType)
end
function RepackableItems_Types.boxType(fullType)
return "RepackableItems." .. RepackableItems_Types.boxName(fullType)
end
function RepackableItems_Types.cartonType(fullType)
return "RepackableItems." .. RepackableItems_Types.cartonName(fullType)
end
---True once both of this item's types were loaded at boot on this machine.
function RepackableItems_Types.isLoaded(fullType)
local sm = getScriptManager()
return sm:getItem(RepackableItems_Types.boxType(fullType)) ~= nil
and sm:getItem(RepackableItems_Types.cartonType(fullType)) ~= nil
end
--- File I/O -----------------------------------------------------------------
function RepackableItems_Types.readFile()
local reader = getModFileReader(MOD_ID, FILE_PATH, false)
if not reader then
return nil
end
local lines = {}
local line = reader:readLine()
while line do
table.insert(lines, line)
line = reader:readLine()
end
reader:close()
return table.concat(lines, "\n") .. "\n"
end
function RepackableItems_Types.writeFile(text)
local writer = getModFileWriter(MOD_ID, FILE_PATH, true, false)
if not writer then
warn("could not open " .. FILE_PATH .. " for writing")
return false
end
-- write(), not writeln(): PrintWriter.println uses the platform line separator.
writer:write(text)
writer:close()
return true
end
--- Entries ------------------------------------------------------------------
-- entry = { fullType, boxCount, cartonCount, boxWeight, cartonWeight, label }
-- Each entry is written with a one-line metadata comment the engine ignores
-- (ScriptParser strips comments) and parseFile() reads back:
-- /* entry|Base.Soap2|8|6|1.600|9.600|Soap */
local function cleanLabel(s)
-- Commas separate script properties and braces delimit blocks; '|' and
-- '*' would break the metadata comment.
return (string.gsub(s or "", "[,{}|*/]", ""))
end
local function entryFromRecord(record)
local scriptItem = ScriptManager.instance:getItem(record.fullType)
return {
fullType = record.fullType,
boxCount = record.boxCount,
cartonCount = record.cartonCount,
boxWeight = RepackableItems_Config.computeBoxWeight(record),
cartonWeight = RepackableItems_Config.computeCartonWeight(record),
label = cleanLabel(scriptItem and scriptItem:getDisplayName() or record.fullType),
}
end
local function parseFile(text)
local list = {}
if not text then
return list
end
for fullType, boxCount, cartonCount, boxWeight, cartonWeight, label in
string.gmatch(text, "/%* entry|([^|]*)|([^|]*)|([^|]*)|([^|]*)|([^|]*)|([^|]*) %*/") do
table.insert(list, {
fullType = fullType,
boxCount = tonumber(boxCount) or 1,
cartonCount = tonumber(cartonCount) or 1,
boxWeight = tonumber(boxWeight) or 1,
cartonWeight = tonumber(cartonWeight) or 1,
label = label,
})
end
return list
end
local function itemBlock(name, displayName, weight, icon, model)
return string.format([[
item %s
{
DisplayCategory = Material,
ItemType = base:normal,
DisplayName = %s,
Weight = %.3f,
Icon = %s,
WorldStaticModel = %s,
cantBeConsolided = true,
}
]], name, displayName, weight, icon, model)
end
local function buildFileText(entries, configured)
local parts = {
"/* GENERATED at runtime by RepackableItems_Types.lua -- do not edit or delete.",
" * Append-only: removing a type deletes every existing box/carton of it. */",
"module RepackableItems",
"{",
}
for _, e in ipairs(entries) do
table.insert(parts, string.format(" /* entry|%s|%d|%d|%.3f|%.3f|%s */",
e.fullType, e.boxCount, e.cartonCount, e.boxWeight, e.cartonWeight, e.label))
table.insert(parts, itemBlock(RepackableItems_Types.boxName(e.fullType), e.label .. " Box", e.boxWeight, "Parcel2", "Parcel3"))
table.insert(parts, itemBlock(RepackableItems_Types.cartonName(e.fullType), e.label .. " Carton", e.cartonWeight, "Parcel1", "Parcel1"))
end
table.insert(parts, RepackableItems_RecipeGen.buildRecipesText(configured, entries))
table.insert(parts, "}")
return table.concat(parts, "\n") .. "\n"
end
--- Authority-side state -----------------------------------------------------
local merged = {} -- ordered entries, as last written
local configuredEntries = {} -- entries for currently configured items
local bootText = nil -- file text this process loaded at boot
local byFullType = {}
local byBoxType = {}
local byCartonType = {}
local function saveRegistry()
local md = ModData.getOrCreate(MODDATA_KEY)
md.entries = md.entries or {}
md.order = md.order or {}
return md
end
---Rebuilds the types file from file + save registry + configured records.
---Authority only (server or SP).
---@param records table[] validated config records
---@return table result { changed = bool, pending = string[], wiped = string[] }
function RepackableItems_Types.sync(records)
local md = saveRegistry()
local result = { changed = false, pending = {}, wiped = {} }
local current = RepackableItems_Types.readFile()
local list, index, names = {}, {}, {}
local function add(entry)
local name = RepackableItems_Types.boxName(entry.fullType)
if index[entry.fullType] then
list[index[entry.fullType]] = entry
elseif names[name] then
warn("skipping " .. entry.fullType .. " -- its type name collides with " .. names[name])
else
table.insert(list, entry)
index[entry.fullType] = #list
names[name] = entry.fullType
end
end
for _, e in ipairs(parseFile(current)) do
add(e)
end
for _, fullType in ipairs(md.order) do
local e = md.entries[fullType]
if e and not index[fullType] then
add({
fullType = fullType, boxCount = e.boxCount, cartonCount = e.cartonCount,
boxWeight = e.boxWeight, cartonWeight = e.cartonWeight, label = e.label,
})
end
end
for _, record in ipairs(records) do
add(entryFromRecord(record))
end
-- Keep this save's registry in step with what it uses.
for _, record in ipairs(records) do
local e = list[index[record.fullType]]
if e then
if not md.entries[record.fullType] then
table.insert(md.order, record.fullType)
end
local reg = md.entries[record.fullType] or {}
reg.boxCount, reg.cartonCount = e.boxCount, e.cartonCount
reg.boxWeight, reg.cartonWeight, reg.label = e.boxWeight, e.cartonWeight, e.label
md.entries[record.fullType] = reg
end
end
for _, fullType in ipairs(md.order) do
local reg = md.entries[fullType]
if reg then
if RepackableItems_Types.isLoaded(fullType) then
reg.everLoaded = true
elseif reg.everLoaded then
table.insert(result.wiped, fullType)
end
end
end
configuredEntries = {}
for _, record in ipairs(records) do
local e = list[index[record.fullType]]
if e then
table.insert(configuredEntries, e)
end
end
merged, byFullType, byBoxType, byCartonType = list, {}, {}, {}
for _, e in ipairs(list) do
byFullType[e.fullType] = e
byBoxType[RepackableItems_Types.boxType(e.fullType)] = e
byCartonType[RepackableItems_Types.cartonType(e.fullType)] = e
if not RepackableItems_Types.isLoaded(e.fullType) then
table.insert(result.pending, e.fullType)
end
end
local text = buildFileText(list, configuredEntries)
if text ~= current then
if RepackableItems_Types.writeFile(text) then
result.changed = true
end
end
if #result.wiped > 0 then
warn("!!! item types this save already uses were MISSING at startup (mod folder reset or updated?): "
.. table.concat(result.wiped, ", ")
.. " -- the definitions file has been rewritten. RESTART THE SERVER NOW, before players join, or"
.. " boxes/cartons of these types that get loaded this session may be lost.")
end
if result.changed and text ~= bootText then
warn("item list changed -- restart the server to apply it"
.. (#result.pending > 0 and (" (new: " .. table.concat(result.pending, ", ") .. ")") or ""))
end
if result.changed and isServer() and getServerOptions():getBoolean("DoLuaChecksum") then
warn("DoLuaChecksum=true: clients without " .. FILE_PATH
.. " will be kicked for a script checksum mismatch once the server has loaded it. Set DoLuaChecksum=false.")
end
return result
end
---Records the file text as loaded at boot. Call once, before the first
---sync() can rewrite the file. Missing file -> "".
function RepackableItems_Types.captureBootText()
if bootText == nil then
bootText = RepackableItems_Types.readFile() or ""
end
return bootText
end
---The file text this process booted with (see captureBootText).
function RepackableItems_Types.getBootText()
return bootText
end
---The file text as of the last sync (may not be applied yet).
function RepackableItems_Types.getFileText()
return buildFileText(merged, configuredEntries)
end
function RepackableItems_Types.getEntry(fullType)
return byFullType[fullType]
end
function RepackableItems_Types.getEntryByBoxType(boxType)
return byBoxType[boxType]
end
function RepackableItems_Types.getEntryByCartonType(cartonType)
return byCartonType[cartonType]
end
return RepackableItems_Types
@@ -0,0 +1,237 @@
--[[
Items vanilla can already pack: every Base.* type referenced by
media/scripts/generated/recipes/{recipes_packing.txt,recipes_ammunition.txt},
minus the box/carton/pack forms. Slightly over-inclusive on purpose; the
only cost is refusing an item vanilla already handles.
Has to be regenerated every update, current version: 42.20.4
]]
RepackableItems_VanillaDenylist = {
["Base.3030Bullets"] = true,
["Base.308Bullets"] = true,
["Base.556Bullets"] = true,
["Base.AlcoholRippedSheets"] = true,
["Base.Antibiotics"] = true,
["Base.Bandage"] = true,
["Base.Bandaid"] = true,
["Base.BarbedWire"] = true,
["Base.BarbedWireStack"] = true,
["Base.Battery"] = true,
["Base.BeerBottle"] = true,
["Base.BeerCan"] = true,
["Base.BookAiming1"] = true,
["Base.BookAiming2"] = true,
["Base.BookAiming3"] = true,
["Base.BookAiming4"] = true,
["Base.BookAiming5"] = true,
["Base.BookAimingSet"] = true,
["Base.BookBlacksmith1"] = true,
["Base.BookBlacksmith2"] = true,
["Base.BookBlacksmith3"] = true,
["Base.BookBlacksmith4"] = true,
["Base.BookBlacksmith5"] = true,
["Base.BookBlacksmithSet"] = true,
["Base.BookButchering1"] = true,
["Base.BookButchering2"] = true,
["Base.BookButchering3"] = true,
["Base.BookButchering4"] = true,
["Base.BookButchering5"] = true,
["Base.BookButcheringSet"] = true,
["Base.BookCarpentry1"] = true,
["Base.BookCarpentry2"] = true,
["Base.BookCarpentry3"] = true,
["Base.BookCarpentry4"] = true,
["Base.BookCarpentry5"] = true,
["Base.BookCarpentrySet"] = true,
["Base.BookCarving1"] = true,
["Base.BookCarving2"] = true,
["Base.BookCarving3"] = true,
["Base.BookCarving4"] = true,
["Base.BookCarving5"] = true,
["Base.BookCarvingSet"] = true,
["Base.BookCooking1"] = true,
["Base.BookCooking2"] = true,
["Base.BookCooking3"] = true,
["Base.BookCooking4"] = true,
["Base.BookCooking5"] = true,
["Base.BookCookingSet"] = true,
["Base.BookElectrician1"] = true,
["Base.BookElectrician2"] = true,
["Base.BookElectrician3"] = true,
["Base.BookElectrician4"] = true,
["Base.BookElectrician5"] = true,
["Base.BookElectricianSet"] = true,
["Base.BookFarming1"] = true,
["Base.BookFarming2"] = true,
["Base.BookFarming3"] = true,
["Base.BookFarming4"] = true,
["Base.BookFarming5"] = true,
["Base.BookFarmingSet"] = true,
["Base.BookFirstAid1"] = true,
["Base.BookFirstAid2"] = true,
["Base.BookFirstAid3"] = true,
["Base.BookFirstAid4"] = true,
["Base.BookFirstAid5"] = true,
["Base.BookFirstAidSet"] = true,
["Base.BookFishing1"] = true,
["Base.BookFishing2"] = true,
["Base.BookFishing3"] = true,
["Base.BookFishing4"] = true,
["Base.BookFishing5"] = true,
["Base.BookFishingSet"] = true,
["Base.BookFlintKnapping1"] = true,
["Base.BookFlintKnapping2"] = true,
["Base.BookFlintKnapping3"] = true,
["Base.BookFlintKnapping4"] = true,
["Base.BookFlintKnapping5"] = true,
["Base.BookFlintKnappingSet"] = true,
["Base.BookForaging1"] = true,
["Base.BookForaging2"] = true,
["Base.BookForaging3"] = true,
["Base.BookForaging4"] = true,
["Base.BookForaging5"] = true,
["Base.BookForagingSet"] = true,
["Base.BookGlassmaking1"] = true,
["Base.BookGlassmaking2"] = true,
["Base.BookGlassmaking3"] = true,
["Base.BookGlassmaking4"] = true,
["Base.BookGlassmaking5"] = true,
["Base.BookGlassmakingSet"] = true,
["Base.BookHusbandry1"] = true,
["Base.BookHusbandry2"] = true,
["Base.BookHusbandry3"] = true,
["Base.BookHusbandry4"] = true,
["Base.BookHusbandry5"] = true,
["Base.BookHusbandrySet"] = true,
["Base.BookLongBlade1"] = true,
["Base.BookLongBlade2"] = true,
["Base.BookLongBlade3"] = true,
["Base.BookLongBlade4"] = true,
["Base.BookLongBlade5"] = true,
["Base.BookLongBladeSet"] = true,
["Base.BookMaintenance1"] = true,
["Base.BookMaintenance2"] = true,
["Base.BookMaintenance3"] = true,
["Base.BookMaintenance4"] = true,
["Base.BookMaintenance5"] = true,
["Base.BookMaintenanceSet"] = true,
["Base.BookMasonry1"] = true,
["Base.BookMasonry2"] = true,
["Base.BookMasonry3"] = true,
["Base.BookMasonry4"] = true,
["Base.BookMasonry5"] = true,
["Base.BookMasonrySet"] = true,
["Base.BookMechanic1"] = true,
["Base.BookMechanic2"] = true,
["Base.BookMechanic3"] = true,
["Base.BookMechanic4"] = true,
["Base.BookMechanic5"] = true,
["Base.BookMechanicsSet"] = true,
["Base.BookMetalWelding1"] = true,
["Base.BookMetalWelding2"] = true,
["Base.BookMetalWelding3"] = true,
["Base.BookMetalWelding4"] = true,
["Base.BookMetalWelding5"] = true,
["Base.BookMetalWeldingSet"] = true,
["Base.BookPottery1"] = true,
["Base.BookPottery2"] = true,
["Base.BookPottery3"] = true,
["Base.BookPottery4"] = true,
["Base.BookPottery5"] = true,
["Base.BookPotterySet"] = true,
["Base.BookReloading1"] = true,
["Base.BookReloading2"] = true,
["Base.BookReloading3"] = true,
["Base.BookReloading4"] = true,
["Base.BookReloading5"] = true,
["Base.BookReloadingSet"] = true,
["Base.BookTailoring1"] = true,
["Base.BookTailoring2"] = true,
["Base.BookTailoring3"] = true,
["Base.BookTailoring4"] = true,
["Base.BookTailoring5"] = true,
["Base.BookTailoringSet"] = true,
["Base.BookTracking1"] = true,
["Base.BookTracking2"] = true,
["Base.BookTracking3"] = true,
["Base.BookTracking4"] = true,
["Base.BookTracking5"] = true,
["Base.BookTrackingSet"] = true,
["Base.BookTrapping1"] = true,
["Base.BookTrapping2"] = true,
["Base.BookTrapping3"] = true,
["Base.BookTrapping4"] = true,
["Base.BookTrapping5"] = true,
["Base.BookTrappingSet"] = true,
["Base.Bullets357"] = true,
["Base.Bullets38"] = true,
["Base.Bullets44"] = true,
["Base.Bullets45"] = true,
["Base.Bullets9mm"] = true,
["Base.Candle"] = true,
["Base.CannedBolognese"] = true,
["Base.CannedCarrots2"] = true,
["Base.CannedChili"] = true,
["Base.CannedCorn"] = true,
["Base.CannedCornedBeef"] = true,
["Base.CannedFruitBeverage"] = true,
["Base.CannedFruitCocktail"] = true,
["Base.CannedMilk"] = true,
["Base.CannedMushroomSoup"] = true,
["Base.CannedPeaches"] = true,
["Base.CannedPeas"] = true,
["Base.CannedPineapple"] = true,
["Base.CannedPotato2"] = true,
["Base.CannedSardines"] = true,
["Base.CannedTomato2"] = true,
["Base.CapGunCap"] = true,
["Base.CigaretteSingle"] = true,
["Base.CottonBalls"] = true,
["Base.DenimStrips"] = true,
["Base.DenimStripsBundle"] = true,
["Base.DenimStripsDirty"] = true,
["Base.DenimStripsDirtyBundle"] = true,
["Base.DentedCan"] = true,
["Base.Dogfood"] = true,
["Base.DuctTape"] = true,
["Base.EmptyJar"] = true,
["Base.FishingHook"] = true,
["Base.GunPowder"] = true,
["Base.JarLid"] = true,
["Base.LeatherStrips"] = true,
["Base.LeatherStripsBundle"] = true,
["Base.LeatherStripsDirty"] = true,
["Base.LeatherStripsDirtyBundle"] = true,
["Base.LightBulb"] = true,
["Base.Macandcheese"] = true,
["Base.Money"] = true,
["Base.MoneyBundle"] = true,
["Base.MysteryCan"] = true,
["Base.Nails"] = true,
["Base.Paperclip"] = true,
["Base.RippedSheets"] = true,
["Base.RippedSheetsBundle"] = true,
["Base.RippedSheetsDirty"] = true,
["Base.RippedSheetsDirtyBundle"] = true,
["Base.RippedSheetsSterilizedBundle"] = true,
["Base.Rope"] = true,
["Base.RopeStack"] = true,
["Base.Scotchtape"] = true,
["Base.Screws"] = true,
["Base.SheetRope"] = true,
["Base.SheetRopeBundle"] = true,
["Base.ShotgunShells"] = true,
["Base.SutureNeedle"] = true,
["Base.TinnedBeans"] = true,
["Base.TinnedSoup"] = true,
["Base.TongueDepressor"] = true,
["Base.TunaTin"] = true,
["Base.Twigs"] = true,
["Base.TwigsBundle"] = true,
["Base.WaterRationCan"] = true,
["Base.Wine"] = true,
["Base.Wine2"] = true,
["Base.Wire"] = true,
["Base.WireStack"] = true,
}
@@ -0,0 +1,3 @@
{
"IGUI_RepackableItems_RejoinRequired": "Repackable Items was updated with new box and carton types.\nPlease rejoin the server to load them."
}
@@ -0,0 +1,6 @@
{
"RepackableItems_PackTyped": "Pack Items in Box",
"RepackableItems_UnpackTyped": "Unpack Box",
"RepackableItems_PackCartonTyped": "Pack Boxes in Carton",
"RepackableItems_UnpackCartonTyped": "Unpack Carton"
}
@@ -0,0 +1,9 @@
{
"Sandbox_RepackableItems": "Repackable Items",
"Sandbox_RepackableItems_Enabled": "Enabled",
"Sandbox_RepackableItems_Enabled_tooltip": "Master switch for this mod's packing recipes (applies after a server restart). Unpacking existing boxes/cartons always stays available.",
"Sandbox_RepackableItems_ItemList": "Repackable item list",
"Sandbox_RepackableItems_ItemList_tooltip": "Semicolon-separated list of items to make packable, one record per item: 'fullType:boxCount:cartonCount[:boxWeightOverride[:cartonWeightOverride]]'. Example: Base.WaterPurificationTablets:12:6. Changes apply after a server restart; players are then asked to rejoin once to load the new boxes/cartons (multiplayer servers need DoLuaChecksum=false). Removing an item only removes its packing recipes: existing boxes can still be unpacked. Items already vanilla-packable, unknown item types, or malformed records are skipped and logged.",
"Sandbox_RepackableItems_GlobalWeightFactor": "Pack weight factor",
"Sandbox_RepackableItems_GlobalWeightFactor_tooltip": "Multiplier applied to the computed box/carton weight (unit weight x count) when an item's config doesn't supply an explicit weight override. 1.0 = exact sum of contained units' weight."
}
@@ -0,0 +1,27 @@
VERSION = 1,
option RepackableItems.Enabled
{
type = boolean,
default = true,
page = RepackableItems,
translation = RepackableItems_Enabled,
}
option RepackableItems.ItemList
{
type = string,
default = "Base.WaterPurificationTablets:8:6;Base.AlcoholWipes:24:6;Base.PillsVitamins:12:6;Base.Pills:12:6;Base.PillsBeta:12:6;Base.PillsAntiDep:12:6;Base.Disinfectant:6:6;Base.PillsSleepingTablets:12:6;Base.Soap2:8:6",
page = RepackableItems,
translation = RepackableItems_ItemList,
}
option RepackableItems.GlobalWeightFactor
{
type = double,
min = 0.1,
max = 10.0,
default = 1.0,
page = RepackableItems,
translation = RepackableItems_GlobalWeightFactor,
}
+11
View File
@@ -0,0 +1,11 @@
name=Repackable Items
author=Overlord_303
poster=poster.png
icon=icon.png
id=RepackableItems
description=Adds configurable packing recipes for admin-selected items, letting them be crafted into their own boxes and cartons like vanilla's repacking.
description= <LINE> <LINE> Configure the items in Sandbox Options (RepackableItems.ItemList). Changes apply after a server restart; players are asked to rejoin once.
description= <LINE> <LINE> Multiplayer servers must set DoLuaChecksum=false in the server settings.
modversion=1.0.1
versionMin=42.0.0
incompatible=
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

@@ -0,0 +1,5 @@
Repackable Items writes media/scripts/repackable_items_generated.txt into this
folder at runtime (per-item box/carton types and their recipes, generated from
the RepackableItems.ItemList sandbox option). It is loaded at the next server
start. Do not ship, edit or delete it by hand: removing a type deletes every
existing box/carton of that type.