Naddox

MineColonies Builder Resource Recovery

Sep 2nd, 2026 (edited)
88
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 26.34 KB | Gaming | 0 0
  1. -- ============================================================
  2. -- MineColonies Builder Resource Recovery v2
  3. -- Separate companion to colony_supplier v6
  4. -- ============================================================
  5. --
  6. -- PURPOSE
  7. --   Runs on a separate CC:Tweaked computer on the same wired
  8. --   peripheral network as the Colony Integrator and builder_#
  9. --   ME Bridges.
  10. --
  11. --   It watches the Required Resources list for every dynamically
  12. --   assigned Builder's Hut. When a construction resource that was
  13. --   previously required disappears from that Hut's current list,
  14. --   the script waits for a grace period, then pulls any leftover
  15. --   copies of that exact item from the Builder's storage back into
  16. --   AE2 using the assigned builder_# ME Bridge.
  17. --
  18. -- SAFE BY DESIGN
  19. --   * Only items learned from Builder Hut Required Resources are
  20. --     ever eligible for recovery.
  21. --   * Builder personal requests (tools, food, armor, etc.) are not
  22. --     used as recovery candidates.
  23. --   * If an item becomes required again during the grace period,
  24. --     recovery is cancelled.
  25. --   * Exact item fingerprint/components are preserved when
  26. --     possible, important for modded/variant construction blocks.
  27. --   * State is persisted to disk, so learned construction-resource
  28. --     history survives computer reboots.
  29. --
  30. -- DYNAMIC TOPOLOGY
  31. --   * Finds every ME Bridge custom-named builder_1, builder_2, ...
  32. --   * Finds every MineColonies Builder's Hut.
  33. --   * Sorts Builder Huts by distance from COMPUTER_POS.
  34. --   * builder_1 -> closest Hut, builder_2 -> second closest, etc.
  35. --   * Automatically probes each bridge's six faces to discover
  36. --     adjacent Builder storage inventories.
  37. --
  38. -- IMPORTANT
  39. --   Set COMPUTER_POS below to the SAME coordinates used by
  40. --   colony_supplier v6 so both scripts assign bridges identically.
  41. --
  42. -- ============================================================
  43.  
  44.  
  45. -- ============================================================
  46. -- CONFIGURATION
  47. -- ============================================================
  48.  
  49. local COMPUTER_POS = {
  50.     x = nil,
  51.     y = nil,
  52.     z = nil
  53. }
  54.  
  55. local BUILDER_BRIDGE_PATTERN = "^builder_(%d+)$"
  56.  
  57. local STORAGE_PROBE_ITEMS = {
  58.     "minecraft:cobblestone",
  59.     "minecraft:stone",
  60.     "minecraft:dirt"
  61. }
  62.  
  63. local STORAGE_FACES = {
  64.     "north",
  65.     "south",
  66.     "east",
  67.     "west",
  68.     "up",
  69.     "down"
  70. }
  71.  
  72. -- How often to compare current Builder Hut requirements.
  73. local POLL_INTERVAL = 10
  74.  
  75. -- Re-scan bridges/huts/storage topology periodically.
  76. local TOPOLOGY_RESCAN_SECONDS = 60
  77.  
  78. -- An item must remain absent from the Hut's Required Resources
  79. -- list for this long before leftovers are returned to AE2.
  80. local RECLAIM_GRACE_SECONDS = 30
  81.  
  82. -- Pull a very large quantity so one pass can recover all matching
  83. -- stacks from a storage face.
  84. local IMPORT_COUNT = 2147483647
  85.  
  86. -- Persistent recovery history.
  87. local STATE_FILE = "builder_recovery_state"
  88.  
  89.  
  90. -- ============================================================
  91. -- VALIDATE CONFIG
  92. -- ============================================================
  93.  
  94. if type(COMPUTER_POS.x) ~= "number"
  95. or type(COMPUTER_POS.y) ~= "number"
  96. or type(COMPUTER_POS.z) ~= "number" then
  97.     error(
  98.         "Set COMPUTER_POS.x, COMPUTER_POS.y, and COMPUTER_POS.z "
  99.         .. "at the top of builder_resource_recovery before running it."
  100.     )
  101. end
  102.  
  103.  
  104. -- ============================================================
  105. -- CORE PERIPHERAL
  106. -- ============================================================
  107.  
  108. local colony = peripheral.find("colony_integrator")
  109.  
  110. if not colony then
  111.     error("Colony Integrator not found!")
  112. end
  113.  
  114. local colonyName = colony.getColonyName() or "Unknown Colony"
  115.  
  116.  
  117. -- ============================================================
  118. -- BASIC HELPERS
  119. -- ============================================================
  120.  
  121. local function now()
  122.     return os.epoch("utc") / 1000
  123. end
  124.  
  125.  
  126. local function posKey(pos)
  127.     if not pos then return "nil" end
  128.  
  129.     return tostring(pos.x)
  130.         .. ","
  131.         .. tostring(pos.y)
  132.         .. ","
  133.         .. tostring(pos.z)
  134. end
  135.  
  136.  
  137. local function distanceSq(a, b)
  138.     local dx = a.x - b.x
  139.     local dy = a.y - b.y
  140.     local dz = a.z - b.z
  141.  
  142.     return dx * dx + dy * dy + dz * dz
  143. end
  144.  
  145.  
  146. local function cleanName(name)
  147.     if not name then
  148.         return "Unknown Item"
  149.     end
  150.  
  151.     name = tostring(name)
  152.     name = name:gsub("^%[", "")
  153.     name = name:gsub("%]$", "")
  154.  
  155.     return name
  156. end
  157.  
  158.  
  159. local function getDisplayName(item, fallback)
  160.     if fallback and fallback ~= "" then
  161.         return cleanName(fallback)
  162.     end
  163.  
  164.     if item and item.displayName then
  165.         return cleanName(item.displayName)
  166.     end
  167.  
  168.     if item and item.name then
  169.         return tostring(item.name)
  170.     end
  171.  
  172.     return "Unknown Item"
  173. end
  174.  
  175.  
  176. local function itemKey(item)
  177.     if not item then
  178.         return nil
  179.     end
  180.  
  181.     if item.fingerprint then
  182.         return "fp:" .. tostring(item.fingerprint)
  183.     end
  184.  
  185.     if item.name then
  186.         return "item:"
  187.             .. tostring(item.name)
  188.             .. ":"
  189.             .. textutils.serialize(item.components or {})
  190.     end
  191.  
  192.     return nil
  193. end
  194.  
  195.  
  196. local function makeFilter(item, count)
  197.     local filter = {}
  198.  
  199.     if item and item.fingerprint then
  200.         filter.fingerprint = item.fingerprint
  201.     elseif item then
  202.         filter.name = item.name
  203.  
  204.         if item.components and next(item.components) then
  205.             filter.components = item.components
  206.         end
  207.     end
  208.  
  209.     if count then
  210.         filter.count = count
  211.     end
  212.  
  213.     return filter
  214. end
  215.  
  216.  
  217. local function storedCount(result)
  218.     if not result then return 0 end
  219.  
  220.     if type(result.count) == "number" then
  221.         return result.count
  222.     end
  223.  
  224.     if type(result.amount) == "number" then
  225.         return result.amount
  226.     end
  227.  
  228.     return 0
  229. end
  230.  
  231.  
  232. local function parseTransferred(result)
  233.     if type(result) == "number" then
  234.         return result
  235.     end
  236.  
  237.     if type(result) == "table" then
  238.         if type(result.count) == "number" then
  239.             return result.count
  240.         end
  241.  
  242.         if type(result.amount) == "number" then
  243.             return result.amount
  244.         end
  245.  
  246.         if type(result.transferred) == "number" then
  247.             return result.transferred
  248.         end
  249.     end
  250.  
  251.     return 0
  252. end
  253.  
  254.  
  255. local function containsValue(list, wanted)
  256.     for _, value in ipairs(list) do
  257.         if value == wanted then
  258.             return true
  259.         end
  260.     end
  261.  
  262.     return false
  263. end
  264.  
  265.  
  266. local function join(list, separator)
  267.     return table.concat(list, separator or ",")
  268. end
  269.  
  270.  
  271. -- Make a completely independent, serialization-safe copy.
  272. --
  273. -- Advanced Peripherals / MineColonies can return tables which reuse
  274. -- nested table objects. CC:Tweaked's textutils.serialize() rejects
  275. -- those with:
  276. --
  277. --   Cannot serialize table with repeated entries
  278. --
  279. -- This copier deliberately duplicates shared tables and drops
  280. -- functions/userdata/threads. Recursive cycles are skipped.
  281. local function serializableCopy(value, ancestors)
  282.     local valueType = type(value)
  283.  
  284.     if valueType == "nil"
  285.     or valueType == "boolean"
  286.     or valueType == "number"
  287.     or valueType == "string" then
  288.         return value
  289.     end
  290.  
  291.     if valueType ~= "table" then
  292.         return nil
  293.     end
  294.  
  295.     ancestors = ancestors or {}
  296.  
  297.     if ancestors[value] then
  298.         return nil
  299.     end
  300.  
  301.     ancestors[value] = true
  302.  
  303.     local copy = {}
  304.  
  305.     for key, child in pairs(value) do
  306.         local keyType = type(key)
  307.  
  308.         if keyType == "string"
  309.         or keyType == "number"
  310.         or keyType == "boolean" then
  311.             local cleanChild =
  312.                 serializableCopy(
  313.                     child,
  314.                     ancestors
  315.                 )
  316.  
  317.             if cleanChild ~= nil then
  318.                 copy[key] = cleanChild
  319.             end
  320.         end
  321.     end
  322.  
  323.     ancestors[value] = nil
  324.  
  325.     return copy
  326. end
  327.  
  328.  
  329. -- Keep only the item identity data needed later by importItem().
  330. -- This prevents peripheral-returned metadata tables from leaking
  331. -- non-serializable/shared references into persistent state.
  332. local function snapshotItem(item)
  333.     if type(item) ~= "table" then
  334.         return nil
  335.     end
  336.  
  337.     local snapshot = {
  338.         name = item.name,
  339.         fingerprint = item.fingerprint
  340.     }
  341.  
  342.     if not snapshot.fingerprint
  343.     and type(item.components) == "table" then
  344.         snapshot.components =
  345.             serializableCopy(
  346.                 item.components
  347.             )
  348.     end
  349.  
  350.     return snapshot
  351. end
  352.  
  353.  
  354. -- ============================================================
  355. -- PERSISTENT STATE
  356. -- ============================================================
  357. --
  358. -- RECOVERY_STATE[builder_custom_name] = {
  359. --     hutKey = "x,y,z",
  360. --     knownOutputs = {"west", "down", ...},
  361. --     tracked = {
  362. --         [exactItemKey] = {
  363. --             item = AP item table,
  364. --             displayName = "Oak Stairs",
  365. --             lastSeenRequired = epoch,
  366. --             absentSince = epoch or nil
  367. --         }
  368. --     }
  369. -- }
  370. --
  371. -- ============================================================
  372.  
  373. local RECOVERY_STATE = {}
  374.  
  375.  
  376. local function loadState()
  377.     if not fs.exists(STATE_FILE) then
  378.         return
  379.     end
  380.  
  381.     local handle = fs.open(STATE_FILE, "r")
  382.  
  383.     if not handle then
  384.         return
  385.     end
  386.  
  387.     local raw = handle.readAll()
  388.     handle.close()
  389.  
  390.     local ok, decoded = pcall(textutils.unserialize, raw)
  391.  
  392.     if ok and type(decoded) == "table" then
  393.         RECOVERY_STATE = decoded
  394.     else
  395.         print("[STATE] Could not read saved state; starting fresh.")
  396.     end
  397. end
  398.  
  399.  
  400. local function saveState()
  401.     -- Serialize BEFORE opening the destination file. That way a
  402.     -- serialization problem cannot truncate a previously-good state.
  403.     local cleanState =
  404.         serializableCopy(
  405.             RECOVERY_STATE
  406.         )
  407.  
  408.     local ok, encoded =
  409.         pcall(
  410.             textutils.serialize,
  411.             cleanState,
  412.             {compact = true}
  413.         )
  414.  
  415.     if not ok then
  416.         print(
  417.             "[STATE ERROR] "
  418.             .. tostring(encoded)
  419.         )
  420.         return
  421.     end
  422.  
  423.     local tempFile =
  424.         STATE_FILE
  425.         .. ".tmp"
  426.  
  427.     local handle =
  428.         fs.open(
  429.             tempFile,
  430.             "w"
  431.         )
  432.  
  433.     if not handle then
  434.         print("[STATE] Could not open temporary state file.")
  435.         return
  436.     end
  437.  
  438.     handle.write(encoded)
  439.     handle.close()
  440.  
  441.     if fs.exists(STATE_FILE) then
  442.         fs.delete(STATE_FILE)
  443.     end
  444.  
  445.     fs.move(
  446.         tempFile,
  447.         STATE_FILE
  448.     )
  449. end
  450.  
  451.  
  452. local function getBuilderState(customName, hutKey)
  453.     local state = RECOVERY_STATE[customName]
  454.  
  455.     if not state or state.hutKey ~= hutKey then
  456.         state = {
  457.             hutKey = hutKey,
  458.             knownOutputs = {},
  459.             tracked = {}
  460.         }
  461.  
  462.         RECOVERY_STATE[customName] = state
  463.         saveState()
  464.     end
  465.  
  466.     state.knownOutputs = state.knownOutputs or {}
  467.     state.tracked = state.tracked or {}
  468.  
  469.     return state
  470. end
  471.  
  472.  
  473. loadState()
  474.  
  475.  
  476. -- ============================================================
  477. -- DISCOVER BUILDER ME BRIDGES
  478. -- ============================================================
  479.  
  480. local function discoverBuilderBridges()
  481.     local bridges = {}
  482.     local seenNumbers = {}
  483.  
  484.     for _, peripheralName in ipairs(peripheral.getNames()) do
  485.         if peripheral.getType(peripheralName) == "me_bridge" then
  486.             local bridge = peripheral.wrap(peripheralName)
  487.             local ok, customName = pcall(bridge.getName)
  488.  
  489.             if ok and type(customName) == "string" then
  490.                 local numberText = customName:match(BUILDER_BRIDGE_PATTERN)
  491.  
  492.                 if numberText then
  493.                     local number = tonumber(numberText)
  494.  
  495.                     if not seenNumbers[number] then
  496.                         seenNumbers[number] = true
  497.  
  498.                         table.insert(bridges, {
  499.                             number = number,
  500.                             customName = customName,
  501.                             peripheralName = peripheralName,
  502.                             bridge = bridge
  503.                         })
  504.                     else
  505.                         print(
  506.                             "[DISCOVERY] Duplicate bridge number "
  507.                             .. tostring(number)
  508.                             .. "; ignoring "
  509.                             .. peripheralName
  510.                         )
  511.                     end
  512.                 end
  513.             end
  514.         end
  515.     end
  516.  
  517.     table.sort(bridges, function(a, b)
  518.         return a.number < b.number
  519.     end)
  520.  
  521.     return bridges
  522. end
  523.  
  524.  
  525. -- ============================================================
  526. -- DISCOVER BUILDER HUTS
  527. -- ============================================================
  528.  
  529. local function isBuilderBuilding(building)
  530.     local typeText = string.lower(tostring(building.type or ""))
  531.     local nameText = string.lower(tostring(building.name or ""))
  532.  
  533.     return typeText:find("building.builder", 1, true) ~= nil
  534.         or typeText:find("builder", 1, true) ~= nil
  535.         or nameText == "builder's hut"
  536.         or nameText == "builders hut"
  537. end
  538.  
  539.  
  540. local function discoverBuilderHuts()
  541.     local huts = {}
  542.     local seen = {}
  543.     local buildings = colony.getBuildings() or {}
  544.  
  545.     for _, building in ipairs(buildings) do
  546.         if isBuilderBuilding(building)
  547.         and type(building.location) == "table" then
  548.             local key = posKey(building.location)
  549.  
  550.             if not seen[key] then
  551.                 seen[key] = true
  552.  
  553.                 table.insert(huts, {
  554.                     pos = building.location,
  555.                     building = building,
  556.                     distance = distanceSq(
  557.                         COMPUTER_POS,
  558.                         building.location
  559.                     )
  560.                 })
  561.             end
  562.         end
  563.     end
  564.  
  565.     table.sort(huts, function(a, b)
  566.         if a.distance ~= b.distance then
  567.             return a.distance < b.distance
  568.         end
  569.  
  570.         if a.pos.x ~= b.pos.x then
  571.             return a.pos.x < b.pos.x
  572.         end
  573.  
  574.         if a.pos.z ~= b.pos.z then
  575.             return a.pos.z < b.pos.z
  576.         end
  577.  
  578.         return a.pos.y < b.pos.y
  579.     end)
  580.  
  581.     return huts
  582. end
  583.  
  584.  
  585. -- ============================================================
  586. -- STORAGE FACE DISCOVERY
  587. -- ============================================================
  588.  
  589. local function chooseProbeItem(bridge)
  590.     for _, itemName in ipairs(STORAGE_PROBE_ITEMS) do
  591.         local ok, result = pcall(
  592.             bridge.getItem,
  593.             {name = itemName}
  594.         )
  595.  
  596.         if ok and storedCount(result) > 0 then
  597.             return itemName
  598.         end
  599.     end
  600.  
  601.     return nil
  602. end
  603.  
  604.  
  605. local function scanStorageFaces(ctx)
  606.     local bridge = ctx.bridge
  607.     local state = ctx.state
  608.     local probeItem = chooseProbeItem(bridge)
  609.     local outputs = {}
  610.  
  611.     -- Preserve previously-proven faces because a full inventory may
  612.     -- temporarily fail a future one-item probe.
  613.     for _, oldFace in ipairs(state.knownOutputs or {}) do
  614.         table.insert(outputs, oldFace)
  615.     end
  616.  
  617.     if not probeItem then
  618.         print(
  619.             "[STORAGE]["
  620.             .. ctx.customName
  621.             .. "] No probe item in AE2; keeping known faces."
  622.         )
  623.  
  624.         return outputs
  625.     end
  626.  
  627.     for _, face in ipairs(STORAGE_FACES) do
  628.         local ok, result = pcall(
  629.             bridge.exportItem,
  630.             {name = probeItem, count = 1},
  631.             face
  632.         )
  633.  
  634.         local moved = ok and parseTransferred(result) or 0
  635.  
  636.         if moved > 0 then
  637.             if not containsValue(outputs, face) then
  638.                 table.insert(outputs, face)
  639.             end
  640.  
  641.             -- Restore the exact net probe count.
  642.             local restored = 0
  643.             local attempts = 0
  644.  
  645.             while restored < moved and attempts < 3 do
  646.                 attempts = attempts + 1
  647.  
  648.                 local importOK, importResult = pcall(
  649.                     bridge.importItem,
  650.                     {name = probeItem, count = moved - restored},
  651.                     face
  652.                 )
  653.  
  654.                 if importOK then
  655.                     restored = restored + parseTransferred(importResult)
  656.                 end
  657.  
  658.                 if restored < moved then
  659.                     sleep(0.1)
  660.                 end
  661.             end
  662.  
  663.             if restored < moved then
  664.                 print(
  665.                     "[STORAGE WARNING]["
  666.                     .. ctx.customName
  667.                     .. "] Left "
  668.                     .. tostring(moved - restored)
  669.                     .. " probe item(s) on "
  670.                     .. face
  671.                 )
  672.             end
  673.         end
  674.     end
  675.  
  676.     local faceOrder = {
  677.         north = 1,
  678.         south = 2,
  679.         east = 3,
  680.         west = 4,
  681.         up = 5,
  682.         down = 6
  683.     }
  684.  
  685.     table.sort(outputs, function(a, b)
  686.         return (faceOrder[a] or 99) < (faceOrder[b] or 99)
  687.     end)
  688.  
  689.     state.knownOutputs = outputs
  690.     saveState()
  691.  
  692.     return outputs
  693. end
  694.  
  695.  
  696. -- ============================================================
  697. -- TOPOLOGY
  698. -- ============================================================
  699.  
  700. local BUILDERS = {}
  701. local lastTopologyScan = 0
  702.  
  703.  
  704. local function discoverTopology()
  705.     local bridges = discoverBuilderBridges()
  706.     local huts = discoverBuilderHuts()
  707.     local newBuilders = {}
  708.  
  709.     print("")
  710.     print("========================================")
  711.     print(" RESOURCE RECOVERY TOPOLOGY")
  712.     print("========================================")
  713.     print("Builder bridges: " .. tostring(#bridges))
  714.     print("Builder Huts:    " .. tostring(#huts))
  715.  
  716.     for _, bridgeInfo in ipairs(bridges) do
  717.         local hut = huts[bridgeInfo.number]
  718.  
  719.         if hut then
  720.             local hutKey = posKey(hut.pos)
  721.             local state = getBuilderState(
  722.                 bridgeInfo.customName,
  723.                 hutKey
  724.             )
  725.  
  726.             local ctx = {
  727.                 number = bridgeInfo.number,
  728.                 customName = bridgeInfo.customName,
  729.                 peripheralName = bridgeInfo.peripheralName,
  730.                 bridge = bridgeInfo.bridge,
  731.                 hut = hut,
  732.                 state = state,
  733.                 outputs = {}
  734.             }
  735.  
  736.             ctx.outputs = scanStorageFaces(ctx)
  737.  
  738.             table.insert(newBuilders, ctx)
  739.  
  740.             print(
  741.                 ctx.customName
  742.                 .. " -> Hut "
  743.                 .. hutKey
  744.                 .. " | storage: "
  745.                 .. (#ctx.outputs > 0
  746.                     and join(ctx.outputs, ",")
  747.                     or "NONE")
  748.             )
  749.         else
  750.             print(
  751.                 bridgeInfo.customName
  752.                 .. " -> no matching Builder Hut"
  753.             )
  754.         end
  755.     end
  756.  
  757.     BUILDERS = newBuilders
  758.     lastTopologyScan = now()
  759. end
  760.  
  761.  
  762. -- ============================================================
  763. -- CURRENT CONSTRUCTION RESOURCE SNAPSHOT
  764. -- ============================================================
  765.  
  766. local function getCurrentRequiredItems(ctx)
  767.     local current = {}
  768.     local resources = colony.getBuilderResources(ctx.hut.pos) or {}
  769.  
  770.     for _, resource in ipairs(resources) do
  771.         local item = resource.item
  772.  
  773.         if type(item) == "table" then
  774.             local key = itemKey(item)
  775.  
  776.             -- We care whether the current build lists this exact
  777.             -- construction resource at all, not just whether it has
  778.             -- an immediate shortage. If needs > 0, it remains protected.
  779.             local needs = resource.needs
  780.  
  781.             if type(needs) ~= "number" then
  782.                 needs = resource.needed
  783.             end
  784.  
  785.             needs = tonumber(needs) or 0
  786.  
  787.             if key and needs > 0 then
  788.                 current[key] = {
  789.                     item = snapshotItem(item),
  790.                     displayName = getDisplayName(
  791.                         item,
  792.                         resource.displayName
  793.                     )
  794.                 }
  795.             end
  796.         end
  797.     end
  798.  
  799.     return current
  800. end
  801.  
  802.  
  803. -- ============================================================
  804. -- IMPORT LEFTOVERS BACK INTO AE2
  805. -- ============================================================
  806.  
  807. local function importAcrossStorage(ctx, item)
  808.     local totalMoved = 0
  809.     local hardError = false
  810.  
  811.     for _, side in ipairs(ctx.outputs) do
  812.         local ok, result = pcall(
  813.             ctx.bridge.importItem,
  814.             makeFilter(item, IMPORT_COUNT),
  815.             side
  816.         )
  817.  
  818.         if ok then
  819.             local moved = parseTransferred(result)
  820.             totalMoved = totalMoved + moved
  821.         else
  822.             hardError = true
  823.  
  824.             print(
  825.                 "[IMPORT ERROR]["
  826.                 .. ctx.customName
  827.                 .. "]["
  828.                 .. side
  829.                 .. "] "
  830.                 .. tostring(result)
  831.             )
  832.         end
  833.     end
  834.  
  835.     return totalMoved, hardError
  836. end
  837.  
  838.  
  839. -- ============================================================
  840. -- UPDATE ONE BUILDER
  841. -- ============================================================
  842.  
  843. local function updateBuilder(ctx)
  844.     if #ctx.outputs == 0 then
  845.         return
  846.     end
  847.  
  848.     local current = getCurrentRequiredItems(ctx)
  849.     local tracked = ctx.state.tracked
  850.     local currentTime = now()
  851.     local changed = false
  852.  
  853.     -- --------------------------------------------------------
  854.     -- LEARN / REFRESH CURRENT BUILD RESOURCES
  855.     -- --------------------------------------------------------
  856.  
  857.     for key, entry in pairs(current) do
  858.         local trackedEntry = tracked[key]
  859.  
  860.         if not trackedEntry then
  861.             trackedEntry = {
  862.                 item = entry.item,
  863.                 displayName = entry.displayName,
  864.                 lastSeenRequired = currentTime,
  865.                 absentSince = nil
  866.             }
  867.  
  868.             tracked[key] = trackedEntry
  869.             changed = true
  870.         else
  871.             trackedEntry.item = entry.item
  872.             trackedEntry.displayName = entry.displayName
  873.             trackedEntry.lastSeenRequired = currentTime
  874.  
  875.             if trackedEntry.absentSince ~= nil then
  876.                 trackedEntry.absentSince = nil
  877.                 changed = true
  878.  
  879.                 print(
  880.                     "[KEEP]["
  881.                     .. ctx.customName
  882.                     .. "] "
  883.                     .. trackedEntry.displayName
  884.                     .. " is required again."
  885.                 )
  886.             end
  887.         end
  888.     end
  889.  
  890.     -- --------------------------------------------------------
  891.     -- START TIMERS / RECLAIM VANISHED RESOURCES
  892.     -- --------------------------------------------------------
  893.  
  894.     for key, trackedEntry in pairs(tracked) do
  895.         if not current[key] then
  896.             if not trackedEntry.absentSince then
  897.                 trackedEntry.absentSince = currentTime
  898.                 changed = true
  899.  
  900.                 print(
  901.                     "[PENDING]["
  902.                     .. ctx.customName
  903.                     .. "] "
  904.                     .. trackedEntry.displayName
  905.                     .. " no longer required; waiting "
  906.                     .. tostring(RECLAIM_GRACE_SECONDS)
  907.                     .. "s."
  908.                 )
  909.  
  910.             elseif (
  911.                 currentTime
  912.                 - trackedEntry.absentSince
  913.             ) >= RECLAIM_GRACE_SECONDS then
  914.  
  915.                 local moved, hardError = importAcrossStorage(
  916.                     ctx,
  917.                     trackedEntry.item
  918.                 )
  919.  
  920.                 if moved > 0 then
  921.                     print(
  922.                         "[RECOVERED]["
  923.                         .. ctx.customName
  924.                         .. "] "
  925.                         .. trackedEntry.displayName
  926.                         .. " x"
  927.                         .. tostring(moved)
  928.                         .. " -> AE2"
  929.                     )
  930.  
  931.                     -- Keep it eligible and retry next poll in case
  932.                     -- matching leftovers exist in another stack/slot.
  933.                     trackedEntry.absentSince =
  934.                         currentTime - RECLAIM_GRACE_SECONDS
  935.  
  936.                     changed = true
  937.  
  938.                 elseif not hardError then
  939.                     -- Every known storage face was checked and no
  940.                     -- matching item remains. Forget this old resource.
  941.                     tracked[key] = nil
  942.                     changed = true
  943.  
  944.                     print(
  945.                         "[CLEAR]["
  946.                         .. ctx.customName
  947.                         .. "] "
  948.                         .. trackedEntry.displayName
  949.                         .. " cleanup complete."
  950.                     )
  951.                 end
  952.             end
  953.         end
  954.     end
  955.  
  956.     if changed then
  957.         saveState()
  958.     end
  959. end
  960.  
  961.  
  962. -- ============================================================
  963. -- STARTUP
  964. -- ============================================================
  965.  
  966. term.clear()
  967. term.setCursorPos(1, 1)
  968.  
  969. print("========================================")
  970. print(" MINECOLONIES RESOURCE RECOVERY v2")
  971. print("========================================")
  972. print("")
  973. print("Colony: " .. colonyName)
  974. print(
  975.     "Computer anchor: "
  976.     .. tostring(COMPUTER_POS.x)
  977.     .. ","
  978.     .. tostring(COMPUTER_POS.y)
  979.     .. ","
  980.     .. tostring(COMPUTER_POS.z)
  981. )
  982. print("")
  983. print("Safe construction-resource recovery: ON")
  984. print("Grace period: " .. tostring(RECLAIM_GRACE_SECONDS) .. "s")
  985. print("Persistent state: " .. STATE_FILE)
  986. print("")
  987. print("Press Ctrl+T to stop.")
  988. print("")
  989.  
  990.  
  991. discoverTopology()
  992.  
  993.  
  994. -- ============================================================
  995. -- MAIN LOOP
  996. -- ============================================================
  997.  
  998. while true do
  999.     if (
  1000.         now()
  1001.         - lastTopologyScan
  1002.     ) >= TOPOLOGY_RESCAN_SECONDS then
  1003.  
  1004.         local ok, err = pcall(discoverTopology)
  1005.  
  1006.         if not ok then
  1007.             print("[TOPOLOGY ERROR] " .. tostring(err))
  1008.         end
  1009.     end
  1010.  
  1011.     for _, ctx in ipairs(BUILDERS) do
  1012.         local ok, err = pcall(
  1013.             updateBuilder,
  1014.             ctx
  1015.         )
  1016.  
  1017.         if not ok then
  1018.             print(
  1019.                 "[BUILDER ERROR]["
  1020.                 .. ctx.customName
  1021.                 .. "] "
  1022.                 .. tostring(err)
  1023.             )
  1024.         end
  1025.     end
  1026.  
  1027.     sleep(POLL_INTERVAL)
  1028. end
  1029.  
Advertisement
Comments
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment