Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- ============================================================
- -- MineColonies Builder Resource Recovery v2
- -- Separate companion to colony_supplier v6
- -- ============================================================
- --
- -- PURPOSE
- -- Runs on a separate CC:Tweaked computer on the same wired
- -- peripheral network as the Colony Integrator and builder_#
- -- ME Bridges.
- --
- -- It watches the Required Resources list for every dynamically
- -- assigned Builder's Hut. When a construction resource that was
- -- previously required disappears from that Hut's current list,
- -- the script waits for a grace period, then pulls any leftover
- -- copies of that exact item from the Builder's storage back into
- -- AE2 using the assigned builder_# ME Bridge.
- --
- -- SAFE BY DESIGN
- -- * Only items learned from Builder Hut Required Resources are
- -- ever eligible for recovery.
- -- * Builder personal requests (tools, food, armor, etc.) are not
- -- used as recovery candidates.
- -- * If an item becomes required again during the grace period,
- -- recovery is cancelled.
- -- * Exact item fingerprint/components are preserved when
- -- possible, important for modded/variant construction blocks.
- -- * State is persisted to disk, so learned construction-resource
- -- history survives computer reboots.
- --
- -- DYNAMIC TOPOLOGY
- -- * Finds every ME Bridge custom-named builder_1, builder_2, ...
- -- * Finds every MineColonies Builder's Hut.
- -- * Sorts Builder Huts by distance from COMPUTER_POS.
- -- * builder_1 -> closest Hut, builder_2 -> second closest, etc.
- -- * Automatically probes each bridge's six faces to discover
- -- adjacent Builder storage inventories.
- --
- -- IMPORTANT
- -- Set COMPUTER_POS below to the SAME coordinates used by
- -- colony_supplier v6 so both scripts assign bridges identically.
- --
- -- ============================================================
- -- ============================================================
- -- CONFIGURATION
- -- ============================================================
- local COMPUTER_POS = {
- x = nil,
- y = nil,
- z = nil
- }
- local BUILDER_BRIDGE_PATTERN = "^builder_(%d+)$"
- local STORAGE_PROBE_ITEMS = {
- "minecraft:cobblestone",
- "minecraft:stone",
- "minecraft:dirt"
- }
- local STORAGE_FACES = {
- "north",
- "south",
- "east",
- "west",
- "up",
- "down"
- }
- -- How often to compare current Builder Hut requirements.
- local POLL_INTERVAL = 10
- -- Re-scan bridges/huts/storage topology periodically.
- local TOPOLOGY_RESCAN_SECONDS = 60
- -- An item must remain absent from the Hut's Required Resources
- -- list for this long before leftovers are returned to AE2.
- local RECLAIM_GRACE_SECONDS = 30
- -- Pull a very large quantity so one pass can recover all matching
- -- stacks from a storage face.
- local IMPORT_COUNT = 2147483647
- -- Persistent recovery history.
- local STATE_FILE = "builder_recovery_state"
- -- ============================================================
- -- VALIDATE CONFIG
- -- ============================================================
- if type(COMPUTER_POS.x) ~= "number"
- or type(COMPUTER_POS.y) ~= "number"
- or type(COMPUTER_POS.z) ~= "number" then
- error(
- "Set COMPUTER_POS.x, COMPUTER_POS.y, and COMPUTER_POS.z "
- .. "at the top of builder_resource_recovery before running it."
- )
- end
- -- ============================================================
- -- CORE PERIPHERAL
- -- ============================================================
- local colony = peripheral.find("colony_integrator")
- if not colony then
- error("Colony Integrator not found!")
- end
- local colonyName = colony.getColonyName() or "Unknown Colony"
- -- ============================================================
- -- BASIC HELPERS
- -- ============================================================
- local function now()
- return os.epoch("utc") / 1000
- end
- local function posKey(pos)
- if not pos then return "nil" end
- return tostring(pos.x)
- .. ","
- .. tostring(pos.y)
- .. ","
- .. tostring(pos.z)
- end
- local function distanceSq(a, b)
- local dx = a.x - b.x
- local dy = a.y - b.y
- local dz = a.z - b.z
- return dx * dx + dy * dy + dz * dz
- end
- local function cleanName(name)
- if not name then
- return "Unknown Item"
- end
- name = tostring(name)
- name = name:gsub("^%[", "")
- name = name:gsub("%]$", "")
- return name
- end
- local function getDisplayName(item, fallback)
- if fallback and fallback ~= "" then
- return cleanName(fallback)
- end
- if item and item.displayName then
- return cleanName(item.displayName)
- end
- if item and item.name then
- return tostring(item.name)
- end
- return "Unknown Item"
- end
- local function itemKey(item)
- if not item then
- return nil
- end
- if item.fingerprint then
- return "fp:" .. tostring(item.fingerprint)
- end
- if item.name then
- return "item:"
- .. tostring(item.name)
- .. ":"
- .. textutils.serialize(item.components or {})
- end
- return nil
- end
- local function makeFilter(item, count)
- local filter = {}
- if item and item.fingerprint then
- filter.fingerprint = item.fingerprint
- elseif item then
- filter.name = item.name
- if item.components and next(item.components) then
- filter.components = item.components
- end
- end
- if count then
- filter.count = count
- end
- return filter
- end
- local function storedCount(result)
- if not result then return 0 end
- if type(result.count) == "number" then
- return result.count
- end
- if type(result.amount) == "number" then
- return result.amount
- end
- return 0
- end
- local function parseTransferred(result)
- if type(result) == "number" then
- return result
- end
- if type(result) == "table" then
- if type(result.count) == "number" then
- return result.count
- end
- if type(result.amount) == "number" then
- return result.amount
- end
- if type(result.transferred) == "number" then
- return result.transferred
- end
- end
- return 0
- end
- local function containsValue(list, wanted)
- for _, value in ipairs(list) do
- if value == wanted then
- return true
- end
- end
- return false
- end
- local function join(list, separator)
- return table.concat(list, separator or ",")
- end
- -- Make a completely independent, serialization-safe copy.
- --
- -- Advanced Peripherals / MineColonies can return tables which reuse
- -- nested table objects. CC:Tweaked's textutils.serialize() rejects
- -- those with:
- --
- -- Cannot serialize table with repeated entries
- --
- -- This copier deliberately duplicates shared tables and drops
- -- functions/userdata/threads. Recursive cycles are skipped.
- local function serializableCopy(value, ancestors)
- local valueType = type(value)
- if valueType == "nil"
- or valueType == "boolean"
- or valueType == "number"
- or valueType == "string" then
- return value
- end
- if valueType ~= "table" then
- return nil
- end
- ancestors = ancestors or {}
- if ancestors[value] then
- return nil
- end
- ancestors[value] = true
- local copy = {}
- for key, child in pairs(value) do
- local keyType = type(key)
- if keyType == "string"
- or keyType == "number"
- or keyType == "boolean" then
- local cleanChild =
- serializableCopy(
- child,
- ancestors
- )
- if cleanChild ~= nil then
- copy[key] = cleanChild
- end
- end
- end
- ancestors[value] = nil
- return copy
- end
- -- Keep only the item identity data needed later by importItem().
- -- This prevents peripheral-returned metadata tables from leaking
- -- non-serializable/shared references into persistent state.
- local function snapshotItem(item)
- if type(item) ~= "table" then
- return nil
- end
- local snapshot = {
- name = item.name,
- fingerprint = item.fingerprint
- }
- if not snapshot.fingerprint
- and type(item.components) == "table" then
- snapshot.components =
- serializableCopy(
- item.components
- )
- end
- return snapshot
- end
- -- ============================================================
- -- PERSISTENT STATE
- -- ============================================================
- --
- -- RECOVERY_STATE[builder_custom_name] = {
- -- hutKey = "x,y,z",
- -- knownOutputs = {"west", "down", ...},
- -- tracked = {
- -- [exactItemKey] = {
- -- item = AP item table,
- -- displayName = "Oak Stairs",
- -- lastSeenRequired = epoch,
- -- absentSince = epoch or nil
- -- }
- -- }
- -- }
- --
- -- ============================================================
- local RECOVERY_STATE = {}
- local function loadState()
- if not fs.exists(STATE_FILE) then
- return
- end
- local handle = fs.open(STATE_FILE, "r")
- if not handle then
- return
- end
- local raw = handle.readAll()
- handle.close()
- local ok, decoded = pcall(textutils.unserialize, raw)
- if ok and type(decoded) == "table" then
- RECOVERY_STATE = decoded
- else
- print("[STATE] Could not read saved state; starting fresh.")
- end
- end
- local function saveState()
- -- Serialize BEFORE opening the destination file. That way a
- -- serialization problem cannot truncate a previously-good state.
- local cleanState =
- serializableCopy(
- RECOVERY_STATE
- )
- local ok, encoded =
- pcall(
- textutils.serialize,
- cleanState,
- {compact = true}
- )
- if not ok then
- print(
- "[STATE ERROR] "
- .. tostring(encoded)
- )
- return
- end
- local tempFile =
- STATE_FILE
- .. ".tmp"
- local handle =
- fs.open(
- tempFile,
- "w"
- )
- if not handle then
- print("[STATE] Could not open temporary state file.")
- return
- end
- handle.write(encoded)
- handle.close()
- if fs.exists(STATE_FILE) then
- fs.delete(STATE_FILE)
- end
- fs.move(
- tempFile,
- STATE_FILE
- )
- end
- local function getBuilderState(customName, hutKey)
- local state = RECOVERY_STATE[customName]
- if not state or state.hutKey ~= hutKey then
- state = {
- hutKey = hutKey,
- knownOutputs = {},
- tracked = {}
- }
- RECOVERY_STATE[customName] = state
- saveState()
- end
- state.knownOutputs = state.knownOutputs or {}
- state.tracked = state.tracked or {}
- return state
- end
- loadState()
- -- ============================================================
- -- DISCOVER BUILDER ME BRIDGES
- -- ============================================================
- local function discoverBuilderBridges()
- local bridges = {}
- local seenNumbers = {}
- for _, peripheralName in ipairs(peripheral.getNames()) do
- if peripheral.getType(peripheralName) == "me_bridge" then
- local bridge = peripheral.wrap(peripheralName)
- local ok, customName = pcall(bridge.getName)
- if ok and type(customName) == "string" then
- local numberText = customName:match(BUILDER_BRIDGE_PATTERN)
- if numberText then
- local number = tonumber(numberText)
- if not seenNumbers[number] then
- seenNumbers[number] = true
- table.insert(bridges, {
- number = number,
- customName = customName,
- peripheralName = peripheralName,
- bridge = bridge
- })
- else
- print(
- "[DISCOVERY] Duplicate bridge number "
- .. tostring(number)
- .. "; ignoring "
- .. peripheralName
- )
- end
- end
- end
- end
- end
- table.sort(bridges, function(a, b)
- return a.number < b.number
- end)
- return bridges
- end
- -- ============================================================
- -- DISCOVER BUILDER HUTS
- -- ============================================================
- local function isBuilderBuilding(building)
- local typeText = string.lower(tostring(building.type or ""))
- local nameText = string.lower(tostring(building.name or ""))
- return typeText:find("building.builder", 1, true) ~= nil
- or typeText:find("builder", 1, true) ~= nil
- or nameText == "builder's hut"
- or nameText == "builders hut"
- end
- local function discoverBuilderHuts()
- local huts = {}
- local seen = {}
- local buildings = colony.getBuildings() or {}
- for _, building in ipairs(buildings) do
- if isBuilderBuilding(building)
- and type(building.location) == "table" then
- local key = posKey(building.location)
- if not seen[key] then
- seen[key] = true
- table.insert(huts, {
- pos = building.location,
- building = building,
- distance = distanceSq(
- COMPUTER_POS,
- building.location
- )
- })
- end
- end
- end
- table.sort(huts, function(a, b)
- if a.distance ~= b.distance then
- return a.distance < b.distance
- end
- if a.pos.x ~= b.pos.x then
- return a.pos.x < b.pos.x
- end
- if a.pos.z ~= b.pos.z then
- return a.pos.z < b.pos.z
- end
- return a.pos.y < b.pos.y
- end)
- return huts
- end
- -- ============================================================
- -- STORAGE FACE DISCOVERY
- -- ============================================================
- local function chooseProbeItem(bridge)
- for _, itemName in ipairs(STORAGE_PROBE_ITEMS) do
- local ok, result = pcall(
- bridge.getItem,
- {name = itemName}
- )
- if ok and storedCount(result) > 0 then
- return itemName
- end
- end
- return nil
- end
- local function scanStorageFaces(ctx)
- local bridge = ctx.bridge
- local state = ctx.state
- local probeItem = chooseProbeItem(bridge)
- local outputs = {}
- -- Preserve previously-proven faces because a full inventory may
- -- temporarily fail a future one-item probe.
- for _, oldFace in ipairs(state.knownOutputs or {}) do
- table.insert(outputs, oldFace)
- end
- if not probeItem then
- print(
- "[STORAGE]["
- .. ctx.customName
- .. "] No probe item in AE2; keeping known faces."
- )
- return outputs
- end
- for _, face in ipairs(STORAGE_FACES) do
- local ok, result = pcall(
- bridge.exportItem,
- {name = probeItem, count = 1},
- face
- )
- local moved = ok and parseTransferred(result) or 0
- if moved > 0 then
- if not containsValue(outputs, face) then
- table.insert(outputs, face)
- end
- -- Restore the exact net probe count.
- local restored = 0
- local attempts = 0
- while restored < moved and attempts < 3 do
- attempts = attempts + 1
- local importOK, importResult = pcall(
- bridge.importItem,
- {name = probeItem, count = moved - restored},
- face
- )
- if importOK then
- restored = restored + parseTransferred(importResult)
- end
- if restored < moved then
- sleep(0.1)
- end
- end
- if restored < moved then
- print(
- "[STORAGE WARNING]["
- .. ctx.customName
- .. "] Left "
- .. tostring(moved - restored)
- .. " probe item(s) on "
- .. face
- )
- end
- end
- end
- local faceOrder = {
- north = 1,
- south = 2,
- east = 3,
- west = 4,
- up = 5,
- down = 6
- }
- table.sort(outputs, function(a, b)
- return (faceOrder[a] or 99) < (faceOrder[b] or 99)
- end)
- state.knownOutputs = outputs
- saveState()
- return outputs
- end
- -- ============================================================
- -- TOPOLOGY
- -- ============================================================
- local BUILDERS = {}
- local lastTopologyScan = 0
- local function discoverTopology()
- local bridges = discoverBuilderBridges()
- local huts = discoverBuilderHuts()
- local newBuilders = {}
- print("")
- print("========================================")
- print(" RESOURCE RECOVERY TOPOLOGY")
- print("========================================")
- print("Builder bridges: " .. tostring(#bridges))
- print("Builder Huts: " .. tostring(#huts))
- for _, bridgeInfo in ipairs(bridges) do
- local hut = huts[bridgeInfo.number]
- if hut then
- local hutKey = posKey(hut.pos)
- local state = getBuilderState(
- bridgeInfo.customName,
- hutKey
- )
- local ctx = {
- number = bridgeInfo.number,
- customName = bridgeInfo.customName,
- peripheralName = bridgeInfo.peripheralName,
- bridge = bridgeInfo.bridge,
- hut = hut,
- state = state,
- outputs = {}
- }
- ctx.outputs = scanStorageFaces(ctx)
- table.insert(newBuilders, ctx)
- print(
- ctx.customName
- .. " -> Hut "
- .. hutKey
- .. " | storage: "
- .. (#ctx.outputs > 0
- and join(ctx.outputs, ",")
- or "NONE")
- )
- else
- print(
- bridgeInfo.customName
- .. " -> no matching Builder Hut"
- )
- end
- end
- BUILDERS = newBuilders
- lastTopologyScan = now()
- end
- -- ============================================================
- -- CURRENT CONSTRUCTION RESOURCE SNAPSHOT
- -- ============================================================
- local function getCurrentRequiredItems(ctx)
- local current = {}
- local resources = colony.getBuilderResources(ctx.hut.pos) or {}
- for _, resource in ipairs(resources) do
- local item = resource.item
- if type(item) == "table" then
- local key = itemKey(item)
- -- We care whether the current build lists this exact
- -- construction resource at all, not just whether it has
- -- an immediate shortage. If needs > 0, it remains protected.
- local needs = resource.needs
- if type(needs) ~= "number" then
- needs = resource.needed
- end
- needs = tonumber(needs) or 0
- if key and needs > 0 then
- current[key] = {
- item = snapshotItem(item),
- displayName = getDisplayName(
- item,
- resource.displayName
- )
- }
- end
- end
- end
- return current
- end
- -- ============================================================
- -- IMPORT LEFTOVERS BACK INTO AE2
- -- ============================================================
- local function importAcrossStorage(ctx, item)
- local totalMoved = 0
- local hardError = false
- for _, side in ipairs(ctx.outputs) do
- local ok, result = pcall(
- ctx.bridge.importItem,
- makeFilter(item, IMPORT_COUNT),
- side
- )
- if ok then
- local moved = parseTransferred(result)
- totalMoved = totalMoved + moved
- else
- hardError = true
- print(
- "[IMPORT ERROR]["
- .. ctx.customName
- .. "]["
- .. side
- .. "] "
- .. tostring(result)
- )
- end
- end
- return totalMoved, hardError
- end
- -- ============================================================
- -- UPDATE ONE BUILDER
- -- ============================================================
- local function updateBuilder(ctx)
- if #ctx.outputs == 0 then
- return
- end
- local current = getCurrentRequiredItems(ctx)
- local tracked = ctx.state.tracked
- local currentTime = now()
- local changed = false
- -- --------------------------------------------------------
- -- LEARN / REFRESH CURRENT BUILD RESOURCES
- -- --------------------------------------------------------
- for key, entry in pairs(current) do
- local trackedEntry = tracked[key]
- if not trackedEntry then
- trackedEntry = {
- item = entry.item,
- displayName = entry.displayName,
- lastSeenRequired = currentTime,
- absentSince = nil
- }
- tracked[key] = trackedEntry
- changed = true
- else
- trackedEntry.item = entry.item
- trackedEntry.displayName = entry.displayName
- trackedEntry.lastSeenRequired = currentTime
- if trackedEntry.absentSince ~= nil then
- trackedEntry.absentSince = nil
- changed = true
- print(
- "[KEEP]["
- .. ctx.customName
- .. "] "
- .. trackedEntry.displayName
- .. " is required again."
- )
- end
- end
- end
- -- --------------------------------------------------------
- -- START TIMERS / RECLAIM VANISHED RESOURCES
- -- --------------------------------------------------------
- for key, trackedEntry in pairs(tracked) do
- if not current[key] then
- if not trackedEntry.absentSince then
- trackedEntry.absentSince = currentTime
- changed = true
- print(
- "[PENDING]["
- .. ctx.customName
- .. "] "
- .. trackedEntry.displayName
- .. " no longer required; waiting "
- .. tostring(RECLAIM_GRACE_SECONDS)
- .. "s."
- )
- elseif (
- currentTime
- - trackedEntry.absentSince
- ) >= RECLAIM_GRACE_SECONDS then
- local moved, hardError = importAcrossStorage(
- ctx,
- trackedEntry.item
- )
- if moved > 0 then
- print(
- "[RECOVERED]["
- .. ctx.customName
- .. "] "
- .. trackedEntry.displayName
- .. " x"
- .. tostring(moved)
- .. " -> AE2"
- )
- -- Keep it eligible and retry next poll in case
- -- matching leftovers exist in another stack/slot.
- trackedEntry.absentSince =
- currentTime - RECLAIM_GRACE_SECONDS
- changed = true
- elseif not hardError then
- -- Every known storage face was checked and no
- -- matching item remains. Forget this old resource.
- tracked[key] = nil
- changed = true
- print(
- "[CLEAR]["
- .. ctx.customName
- .. "] "
- .. trackedEntry.displayName
- .. " cleanup complete."
- )
- end
- end
- end
- end
- if changed then
- saveState()
- end
- end
- -- ============================================================
- -- STARTUP
- -- ============================================================
- term.clear()
- term.setCursorPos(1, 1)
- print("========================================")
- print(" MINECOLONIES RESOURCE RECOVERY v2")
- print("========================================")
- print("")
- print("Colony: " .. colonyName)
- print(
- "Computer anchor: "
- .. tostring(COMPUTER_POS.x)
- .. ","
- .. tostring(COMPUTER_POS.y)
- .. ","
- .. tostring(COMPUTER_POS.z)
- )
- print("")
- print("Safe construction-resource recovery: ON")
- print("Grace period: " .. tostring(RECLAIM_GRACE_SECONDS) .. "s")
- print("Persistent state: " .. STATE_FILE)
- print("")
- print("Press Ctrl+T to stop.")
- print("")
- discoverTopology()
- -- ============================================================
- -- MAIN LOOP
- -- ============================================================
- while true do
- if (
- now()
- - lastTopologyScan
- ) >= TOPOLOGY_RESCAN_SECONDS then
- local ok, err = pcall(discoverTopology)
- if not ok then
- print("[TOPOLOGY ERROR] " .. tostring(err))
- end
- end
- for _, ctx in ipairs(BUILDERS) do
- local ok, err = pcall(
- updateBuilder,
- ctx
- )
- if not ok then
- print(
- "[BUILDER ERROR]["
- .. ctx.customName
- .. "] "
- .. tostring(err)
- )
- end
- end
- sleep(POLL_INTERVAL)
- end
Advertisement