Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- ============================================================
- -- MineColonies + AE2 Automatic Builder Supplier
- -- Dynamic Multi-Builder Edition v6
- -- ============================================================
- --
- -- WHAT CHANGED IN v6
- -- * No static Builder count.
- -- * Discovers every ME Bridge whose custom name matches:
- -- builder_1, builder_2, builder_3, ...
- -- * Discovers every MineColonies Builder's Hut.
- -- * Sorts Builder Huts by distance from COMPUTER_POS.
- -- * builder_1 is assigned to the closest Builder's Hut,
- -- builder_2 to the next closest, and so on.
- -- * Each ME Bridge automatically probes all six faces and
- -- remembers which faces can accept items.
- -- * Every assigned Builder is supplied independently.
- -- * One monitor automatically cycles through all Builders.
- --
- -- IMPORTANT
- -- Set COMPUTER_POS below before running the script.
- --
- -- STORAGE FACE DETECTION
- -- The script exports 1 probe item to each face and immediately
- -- imports 1 back. A face that successfully accepts the probe is
- -- treated as Builder storage. Previously proven faces remain
- -- remembered during later rescans, because a completely full
- -- inventory cannot accept a probe and would otherwise look
- -- disconnected.
- --
- -- ============================================================
- -- ============================================================
- -- CONFIGURATION
- -- ============================================================
- -- CHANGE THESE THREE VALUES to the world coordinates of the
- -- computer/control-room setup. These coordinates are only used
- -- to sort Builder Huts nearest-to-farthest.
- local COMPUTER_POS = {
- x = nil,
- y = nil,
- z = nil
- }
- -- ME Bridges are discovered by their Advanced Peripherals custom
- -- names. Rename them in an anvil to builder_1, builder_2, etc.
- local BUILDER_BRIDGE_PATTERN = "^builder_(%d+)$"
- -- Items used to probe for adjacent Builder storage. The script
- -- uses the first one it finds stored in AE2.
- local STORAGE_PROBE_ITEMS = {
- "minecraft:cobblestone",
- "minecraft:stone",
- "minecraft:dirt"
- }
- local STORAGE_FACES = {
- "north",
- "south",
- "east",
- "west",
- "up",
- "down"
- }
- local POLL_INTERVAL = 5
- local TOPOLOGY_RESCAN_SECONDS = 60
- local DELIVERY_HOLD_SECONDS = 15
- local CRAFT_RETRY_SECONDS = 30
- local CHAT_DELAY = 1.1
- -- Monitor paging.
- local BUILDER_SCREEN_SECONDS = 8
- local ITEM_PAGE_SECONDS = 5
- local BUILDER_ROWS = 4
- local HUT_ROWS = 7
- local ACTIVITY_ROWS = 4
- -- ============================================================
- -- 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 colony_supplier before running it."
- )
- end
- -- ============================================================
- -- CORE PERIPHERALS
- -- ============================================================
- local colony = peripheral.find("colony_integrator")
- local chat = peripheral.find("chat_box")
- local monitor = peripheral.find("monitor")
- if not colony then error("Colony Integrator not found!") end
- if not chat then error("Chat Box not found!") end
- if not monitor then error("Monitor not found!") end
- local colonyName = colony.getColonyName() or "Unknown Colony"
- local CHAT_PREFIX = "Colony: " .. colonyName
- local MON_W, MON_H = monitor.getSize()
- if MON_W < 39 or MON_H < 26 then
- error(
- "Monitor is too small. Need at least 39x26, found "
- .. tostring(MON_W) .. "x" .. tostring(MON_H)
- )
- end
- monitor.setBackgroundColor(colors.black)
- monitor.setTextColor(colors.white)
- monitor.clear()
- -- ============================================================
- -- GLOBAL RUNTIME TABLES
- -- ============================================================
- -- Rebuilt by discoverTopology().
- local BUILDERS = {}
- -- Persistent state keyed by custom bridge name, e.g. builder_1.
- -- This survives topology rescans as long as the same custom name
- -- remains assigned to the same Builder Hut.
- local STATE_BY_BRIDGE = {}
- local lastTopologyScan = 0
- local topologyMessage = "Starting discovery..."
- -- ============================================================
- -- BASIC HELPERS
- -- ============================================================
- local function now()
- return os.epoch("utc") / 1000
- end
- local function numberValue(v)
- if type(v) == "number" then return v end
- if v == true then return 1 end
- return 0
- end
- local function samePos(a, b)
- return a
- and b
- and a.x == b.x
- and a.y == b.y
- and a.z == b.z
- 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 itemDisplayName(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 "name:"
- .. tostring(item.name)
- .. ":"
- .. textutils.serialize(item.components or {})
- end
- return nil
- end
- local function makeFilter(item, count)
- local filter = {}
- -- Fingerprint works well for exact stored/exported stacks.
- 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 makeCraftFilter(item, count)
- -- Crafting lookups must use the registry ID/components rather
- -- than MineColonies' fingerprint.
- local filter = {
- name = item.name
- }
- if item.components and next(item.components) then
- filter.components = item.components
- 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 join(list, separator)
- separator = separator or ","
- local out = ""
- for i, value in ipairs(list) do
- if i > 1 then out = out .. separator end
- out = out .. tostring(value)
- end
- return out
- end
- -- ============================================================
- -- MONITOR HELPERS
- -- ============================================================
- local function fit(text, width)
- text = tostring(text or "")
- if #text <= width then
- return text
- end
- if width <= 3 then
- return text:sub(1, width)
- end
- return text:sub(1, width - 3) .. "..."
- end
- local function monitorLine(y, text, color)
- if y < 1 or y > MON_H then return end
- monitor.setCursorPos(1, y)
- monitor.setBackgroundColor(colors.black)
- monitor.setTextColor(color or colors.white)
- monitor.write(string.rep(" ", MON_W))
- monitor.setCursorPos(1, y)
- monitor.write(fit(text, MON_W))
- end
- local function separator(y)
- monitorLine(y, string.rep("-", MON_W), colors.gray)
- end
- local function itemLine(name, qty)
- local right = "x" .. tostring(qty)
- local maxName = MON_W - #right - 1
- local left = fit(name, maxName)
- return left
- .. string.rep(" ", MON_W - #left - #right)
- .. right
- end
- local function activityColor(kind)
- if kind == "PULL" then return colors.lime end
- if kind == "CRAFT" then return colors.yellow end
- if kind == "WAIT" then return colors.red end
- if kind == "INFO" then return colors.lightBlue end
- return colors.lightGray
- end
- local function addActivity(state, kind, name, qty)
- local text = kind .. " " .. tostring(name)
- if qty and qty > 0 then
- text = text .. " x" .. tostring(qty)
- end
- table.insert(state.activity, 1, {
- kind = kind,
- text = text
- })
- while #state.activity > 20 do
- table.remove(state.activity)
- end
- end
- local function pageSlice(list, rows)
- local totalPages = math.max(1, math.ceil(#list / rows))
- local page = (math.floor(now() / ITEM_PAGE_SECONDS) % totalPages) + 1
- local first = ((page - 1) * rows) + 1
- local last = math.min(#list, first + rows - 1)
- local out = {}
- for i = first, last do
- table.insert(out, list[i])
- end
- return out, page, totalPages
- end
- local function getScreenBuilder()
- local assigned = {}
- for _, ctx in ipairs(BUILDERS) do
- if ctx.hut then
- table.insert(assigned, ctx)
- end
- end
- if #assigned == 0 then
- return nil, 0, 0
- end
- local index = (math.floor(now() / BUILDER_SCREEN_SECONDS) % #assigned) + 1
- return assigned[index], index, #assigned
- end
- local function drawDashboard()
- local ctx, pageIndex, pageCount = getScreenBuilder()
- monitor.setBackgroundColor(colors.black)
- monitor.clear()
- monitorLine(1, "COLONY: " .. string.upper(colonyName), colors.purple)
- if not ctx then
- separator(2)
- monitorLine(3, "NO ASSIGNED BUILDER BRIDGES", colors.red)
- monitorLine(5, topologyMessage, colors.lightGray)
- monitorLine(26, "Status: waiting for topology", colors.lightGray)
- return
- end
- local state = ctx.state
- local builderName = ctx.builderName or "Unassigned Worker"
- monitorLine(
- 2,
- "BUILDER " .. tostring(pageIndex) .. "/" .. tostring(pageCount)
- .. " | " .. ctx.customName,
- colors.cyan
- )
- monitorLine(3, builderName, colors.white)
- local builderList = state.builderDisplay or {}
- local bPageItems, bPage, bPages = pageSlice(builderList, BUILDER_ROWS)
- monitorLine(
- 4,
- "Requests: " .. tostring(#builderList)
- .. " Page " .. tostring(bPage) .. "/" .. tostring(bPages),
- colors.lightGray
- )
- for row = 1, BUILDER_ROWS do
- local entry = bPageItems[row]
- if entry then
- monitorLine(4 + row, itemLine(entry.name, entry.qty), colors.white)
- else
- monitorLine(4 + row, "", colors.white)
- end
- end
- separator(9)
- monitorLine(10, "HUT: " .. (ctx.activeBuildingName or "Builder's Hut"), colors.cyan)
- local hutList = state.hutDisplay or {}
- local hPageItems, hPage, hPages = pageSlice(hutList, HUT_ROWS)
- monitorLine(
- 11,
- "Required: " .. tostring(#hutList)
- .. " Page " .. tostring(hPage) .. "/" .. tostring(hPages),
- colors.lightGray
- )
- for row = 1, HUT_ROWS do
- local entry = hPageItems[row]
- if entry then
- monitorLine(11 + row, itemLine(entry.name, entry.qty), colors.white)
- else
- monitorLine(11 + row, "", colors.white)
- end
- end
- separator(19)
- monitorLine(20, "ME SYSTEM ACTIVITY", colors.cyan)
- for row = 1, ACTIVITY_ROWS do
- local entry = state.activity[row]
- if entry then
- monitorLine(20 + row, entry.text, activityColor(entry.kind))
- else
- monitorLine(20 + row, "", colors.white)
- end
- end
- separator(25)
- monitorLine(26, "Status: " .. state.statusText, colors.lightGray)
- end
- -- ============================================================
- -- BUILDER STATE
- -- ============================================================
- local function newBuilderState(hutKey)
- return {
- hutKey = hutKey,
- requestState = {},
- hutDeliveryHold = {},
- alertState = {},
- craftRetry = {},
- activity = {},
- builderDisplay = {},
- hutDisplay = {},
- statusText = "Discovered",
- knownOutputs = {}
- }
- end
- local function getOrResetState(customName, hutKey)
- local state = STATE_BY_BRIDGE[customName]
- if not state or state.hutKey ~= hutKey then
- state = newBuilderState(hutKey)
- STATE_BY_BRIDGE[customName] = state
- end
- return state
- end
- -- ============================================================
- -- DISCOVERY: 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 seenNumbers[number] then
- print(
- "[DISCOVERY] Duplicate custom bridge number: "
- .. customName
- .. " - ignoring "
- .. peripheralName
- )
- else
- seenNumbers[number] = true
- table.insert(bridges, {
- number = number,
- customName = customName,
- peripheralName = peripheralName,
- bridge = bridge
- })
- end
- end
- end
- end
- end
- table.sort(bridges, function(a, b)
- return a.number < b.number
- end)
- return bridges
- end
- -- ============================================================
- -- DISCOVERY: 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
- -- ============================================================
- -- DISCOVERY: STORAGE FACES
- -- ============================================================
- 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 containsValue(list, wanted)
- for _, value in ipairs(list) do
- if value == wanted then
- return true
- end
- end
- return false
- end
- local function scanStorageFaces(ctx)
- local bridge = ctx.bridge
- local state = ctx.state
- local probeItem = chooseProbeItem(bridge)
- -- Once a face has been proven to be storage, retain it across
- -- rescans. A full inventory cannot accept the probe, so a
- -- failed later probe is not reliable evidence of removal.
- local outputs = {}
- for _, oldFace in ipairs(state.knownOutputs or {}) do
- table.insert(outputs, oldFace)
- end
- if not probeItem then
- print(
- "[STORAGE] " .. ctx.customName
- .. ": no probe item found in AE2; keeping previously known faces."
- )
- return outputs
- end
- for _, face in ipairs(STORAGE_FACES) do
- local ok, result, err = 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
- -- Put the probe back into AE2. If the inventory
- -- already contained the same item, importing any one
- -- matching item still leaves the inventory at the same
- -- net count after the probe cycle.
- 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
- local imported = parseTransferred(importResult)
- restored = restored + imported
- 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
- elseif not ok and err then
- -- Expected for non-inventory faces; no need to spam.
- end
- end
- -- Keep output order stable and human-readable.
- local order = {
- north = 1,
- south = 2,
- east = 3,
- west = 4,
- up = 5,
- down = 6
- }
- table.sort(outputs, function(a, b)
- return (order[a] or 99) < (order[b] or 99)
- end)
- state.knownOutputs = outputs
- return outputs
- end
- -- ============================================================
- -- DISCOVERY: COMPLETE TOPOLOGY
- -- ============================================================
- local function discoverTopology()
- local bridges = discoverBuilderBridges()
- local huts = discoverBuilderHuts()
- local newBuilders = {}
- print("")
- print("========================================")
- print(" TOPOLOGY DISCOVERY")
- print("========================================")
- print("Builder bridges: " .. tostring(#bridges))
- print("Builder Huts: " .. tostring(#huts))
- for _, bridgeInfo in ipairs(bridges) do
- -- builder_N maps to the Nth closest Builder Hut.
- local hut = huts[bridgeInfo.number]
- local hutKey = hut and posKey(hut.pos) or "unassigned"
- local state = getOrResetState(bridgeInfo.customName, hutKey)
- local ctx = {
- number = bridgeInfo.number,
- customName = bridgeInfo.customName,
- peripheralName = bridgeInfo.peripheralName,
- bridge = bridgeInfo.bridge,
- hut = hut,
- state = state,
- outputs = {},
- builderName = nil,
- activeBuildingName = nil
- }
- ctx.outputs = scanStorageFaces(ctx)
- table.insert(newBuilders, ctx)
- if hut then
- print(
- ctx.customName
- .. " (" .. ctx.peripheralName .. ")"
- .. " -> Hut " .. posKey(hut.pos)
- .. " | outputs: "
- .. (#ctx.outputs > 0 and join(ctx.outputs, ",") or "NONE")
- )
- else
- print(
- ctx.customName
- .. " (" .. ctx.peripheralName .. ")"
- .. " -> no " .. tostring(ctx.number)
- .. "th Builder Hut found"
- )
- end
- end
- if #huts > #bridges then
- print(
- "[DISCOVERY] "
- .. tostring(#huts - #bridges)
- .. " Builder Hut(s) currently have no matching builder_# bridge."
- )
- end
- BUILDERS = newBuilders
- topologyMessage = tostring(#bridges)
- .. " bridge(s), "
- .. tostring(#huts)
- .. " Builder Hut(s)"
- lastTopologyScan = now()
- end
- -- ============================================================
- -- COLONY LOOKUPS
- -- ============================================================
- local function findBuilderWorker(citizens, hutPos)
- for _, citizen in ipairs(citizens) do
- if citizen.work
- and citizen.work.location
- and samePos(citizen.work.location, hutPos) then
- local job = string.lower(tostring(citizen.work.job or ""))
- local workType = string.lower(tostring(citizen.work.type or ""))
- local workName = string.lower(tostring(citizen.work.name or ""))
- if job:find("builder", 1, true)
- or workType:find("builder", 1, true)
- or workName:find("builder", 1, true) then
- return citizen
- end
- end
- end
- return nil
- end
- local function isConstructionOrder(order)
- local t = tostring(order.workOrderType or "")
- return t == "BUILD"
- or t == "UPGRADE"
- or t == "REPAIR"
- end
- local function findWorkOrderForHut(orders, hutPos)
- local fallback = nil
- for _, order in ipairs(orders) do
- if isConstructionOrder(order)
- and type(order.builder) == "table"
- and samePos(order.builder, hutPos) then
- if order.isClaimed == true then
- return order
- end
- fallback = fallback or order
- end
- end
- return fallback
- end
- local function requestIsClosed(request)
- local state = string.upper(tostring(request.state or ""))
- return state:find("COMPLETE", 1, true) ~= nil
- or state:find("CANCEL", 1, true) ~= nil
- or state == "DONE"
- or state == "RESOLVED"
- end
- local function getBuilderRequests(allRequests, builderName)
- local out = {}
- if not builderName then
- return out
- end
- for _, request in ipairs(allRequests) do
- if not requestIsClosed(request)
- and tostring(request.target or ""):find(builderName, 1, true) then
- table.insert(out, request)
- end
- end
- return out
- end
- -- ============================================================
- -- BRIDGE-SPECIFIC AE2 HELPERS
- -- ============================================================
- local function getStored(ctx, item)
- local ok, result = pcall(
- ctx.bridge.getItem,
- makeFilter(item)
- )
- if not ok or not result then
- return nil, 0
- end
- return result, storedCount(result)
- end
- local function isCraftable(ctx, item)
- local ok, result = pcall(
- ctx.bridge.isCraftable,
- makeCraftFilter(item)
- )
- return ok and result == true
- end
- local function isCrafting(ctx, item)
- local ok, result = pcall(
- ctx.bridge.isCrafting,
- makeCraftFilter(item)
- )
- return ok and result == true
- end
- local function startCraft(ctx, item, quantity)
- if quantity <= 0 then return false end
- local ok, result, err = pcall(
- ctx.bridge.craftItem,
- makeCraftFilter(item, quantity)
- )
- if not ok then
- print(
- "[CRAFT ERROR][" .. ctx.customName .. "] "
- .. tostring(result)
- )
- return false
- end
- if result then
- return true
- end
- if err then
- print(
- "[CRAFT ERROR][" .. ctx.customName .. "] "
- .. tostring(err)
- )
- end
- return false
- end
- local function exportAcrossOutputs(ctx, item, quantity)
- if quantity <= 0 then return 0 end
- local totalMoved = 0
- local remaining = quantity
- for _, side in ipairs(ctx.outputs) do
- if remaining <= 0 then break end
- local ok, result, err = pcall(
- ctx.bridge.exportItem,
- makeFilter(item, remaining),
- side
- )
- if ok then
- local moved = parseTransferred(result)
- if moved > 0 then
- totalMoved = totalMoved + moved
- remaining = remaining - moved
- elseif err then
- -- Destination may simply be full. Do not spam.
- end
- else
- print(
- "[EXPORT ERROR][" .. ctx.customName .. "][" .. side .. "] "
- .. tostring(result)
- )
- end
- end
- return totalMoved
- end
- -- ============================================================
- -- CHAT ALERTS
- -- ============================================================
- local function notifyMissing(ctx, demand, quantity)
- if quantity <= 0 then return end
- local state = ctx.state
- if state.alertState[demand.key] == quantity then
- return
- end
- local who
- if ctx.builderName then
- who = "Builder " .. ctx.builderName
- else
- who = "Builder's Hut " .. ctx.customName
- end
- local message = who
- .. " has requested "
- .. demand.displayName
- .. " : x"
- .. tostring(quantity)
- local ok, result, err = pcall(
- chat.sendMessage,
- message,
- CHAT_PREFIX
- )
- if ok and result then
- state.alertState[demand.key] = quantity
- addActivity(state, "WAIT", demand.displayName, quantity)
- state.statusText = "Waiting: " .. demand.displayName
- print(
- "[ALERT][" .. ctx.customName .. "] "
- .. message
- )
- sleep(CHAT_DELAY)
- else
- print(
- "[CHAT ERROR] "
- .. tostring(err or result)
- )
- end
- end
- -- ============================================================
- -- DEMAND OBJECTS
- -- ============================================================
- local function ensureDemand(demands, item, displayName)
- local key = itemKey(item)
- if not key then return nil end
- local demand = demands[key]
- if not demand then
- demand = {
- key = key,
- item = item,
- displayName = itemDisplayName(item, displayName),
- hutNeedRaw = 0,
- hutNeedEffective = 0,
- builderNeed = 0,
- totalNeed = 0,
- requestRefs = {}
- }
- demands[key] = demand
- end
- return demand
- end
- local function chooseRequestItem(ctx, request, demands)
- if type(request.items) ~= "table"
- or #request.items == 0 then
- return nil
- end
- -- Prefer an exact variant already present in Hut demand.
- for _, item in ipairs(request.items) do
- local key = itemKey(item)
- if key and demands[key] then
- return item
- end
- end
- -- Prefer a stored variant.
- local bestItem = nil
- local bestCount = 0
- for _, item in ipairs(request.items) do
- local _, count = getStored(ctx, item)
- if count > bestCount then
- bestCount = count
- bestItem = item
- end
- end
- if bestItem then return bestItem end
- -- Prefer something AE2 can craft.
- for _, item in ipairs(request.items) do
- if isCraftable(ctx, item) then
- return item
- end
- end
- return request.items[1]
- end
- local function addDisplay(displayMap, item, fallbackName, qty)
- local key = itemKey(item)
- if not key then return end
- local entry = displayMap[key]
- if not entry then
- entry = {
- name = itemDisplayName(item, fallbackName),
- qty = 0
- }
- displayMap[key] = entry
- end
- entry.qty = entry.qty + qty
- end
- local function mapToSortedList(map)
- local list = {}
- for _, entry in pairs(map) do
- table.insert(list, entry)
- end
- table.sort(list, function(a, b)
- return string.lower(a.name) < string.lower(b.name)
- end)
- return list
- end
- local function cleanupExpiredHolds(state)
- local t = now()
- for key, hold in pairs(state.hutDeliveryHold) do
- if (t - hold.time) >= DELIVERY_HOLD_SECONDS then
- state.hutDeliveryHold[key] = nil
- end
- end
- end
- -- ============================================================
- -- COLLECT BUILDER + HUT DEMAND
- -- ============================================================
- local function collectDemands(ctx, allRequests)
- local state = ctx.state
- local demands = {}
- local builderDisplayMap = {}
- local hutDisplayMap = {}
- cleanupExpiredHolds(state)
- -- --------------------------------------------------------
- -- BUILDER HUT REQUIRED RESOURCES
- -- --------------------------------------------------------
- local hutResources = colony.getBuilderResources(ctx.hut.pos) or {}
- for _, resource in ipairs(hutResources) do
- local item = resource.item
- if type(item) == "table" then
- local rawShortage = math.max(
- 0,
- numberValue(resource.needs)
- - numberValue(resource.available)
- - numberValue(resource.delivering)
- )
- if rawShortage > 0 then
- local demand = ensureDemand(
- demands,
- item,
- resource.displayName
- )
- if demand then
- demand.hutNeedRaw = demand.hutNeedRaw + rawShortage
- addDisplay(
- hutDisplayMap,
- item,
- resource.displayName,
- rawShortage
- )
- end
- end
- end
- end
- for key, demand in pairs(demands) do
- local held = 0
- local hold = state.hutDeliveryHold[key]
- if hold then
- held = hold.amount
- end
- demand.hutNeedEffective = math.max(
- 0,
- demand.hutNeedRaw - held
- )
- end
- -- --------------------------------------------------------
- -- BUILDER PERSONAL REQUESTS
- -- --------------------------------------------------------
- local requests = getBuilderRequests(allRequests, ctx.builderName)
- local activeIds = {}
- for _, request in ipairs(requests) do
- if request.id then
- local requestId = tostring(request.id)
- activeIds[requestId] = true
- local item = chooseRequestItem(ctx, request, demands)
- if item then
- local key = itemKey(item)
- local count = tonumber(request.count) or 1
- local requestState = state.requestState[requestId]
- if not requestState
- or requestState.count ~= count
- or requestState.key ~= key then
- requestState = {
- count = count,
- sent = 0,
- key = key
- }
- state.requestState[requestId] = requestState
- end
- local outstanding = math.max(
- 0,
- count - requestState.sent
- )
- addDisplay(
- builderDisplayMap,
- item,
- nil,
- count
- )
- if outstanding > 0 then
- local demand = ensureDemand(demands, item)
- if demand then
- demand.builderNeed = demand.builderNeed + outstanding
- table.insert(demand.requestRefs, {
- id = requestId,
- outstanding = outstanding
- })
- end
- end
- end
- end
- end
- for requestId in pairs(state.requestState) do
- if not activeIds[requestId] then
- state.requestState[requestId] = nil
- end
- end
- -- --------------------------------------------------------
- -- MERGE
- -- --------------------------------------------------------
- for _, demand in pairs(demands) do
- -- One physical delivery can satisfy both MineColonies
- -- views, so do not add the two sources together.
- demand.totalNeed = math.max(
- demand.builderNeed,
- demand.hutNeedEffective
- )
- end
- state.builderDisplay = mapToSortedList(builderDisplayMap)
- state.hutDisplay = mapToSortedList(hutDisplayMap)
- return demands
- end
- -- ============================================================
- -- DELIVERY ACCOUNTING
- -- ============================================================
- local function recordDelivery(ctx, demand, quantity)
- if quantity <= 0 then return end
- local state = ctx.state
- local left = quantity
- -- Distribute credit across personal request IDs.
- for _, ref in ipairs(demand.requestRefs) do
- if left <= 0 then break end
- local requestState = state.requestState[ref.id]
- if requestState then
- local outstanding = math.max(
- 0,
- requestState.count - requestState.sent
- )
- local credit = math.min(left, outstanding)
- requestState.sent = requestState.sent + credit
- left = left - credit
- end
- end
- -- The same physical items also satisfy overlapping Hut demand.
- if demand.hutNeedEffective > 0 then
- local credit = math.min(quantity, demand.hutNeedEffective)
- local hold = state.hutDeliveryHold[demand.key]
- if not hold then
- hold = {
- amount = 0,
- time = now()
- }
- state.hutDeliveryHold[demand.key] = hold
- end
- hold.amount = hold.amount + credit
- hold.time = now()
- end
- end
- -- ============================================================
- -- PROCESS ONE MERGED DEMAND
- -- ============================================================
- local function processDemand(ctx, demand)
- local state = ctx.state
- local need = demand.totalNeed
- if need <= 0 then
- state.alertState[demand.key] = nil
- state.craftRetry[demand.key] = nil
- return
- end
- if #ctx.outputs == 0 then
- state.statusText = "No Builder storage detected"
- return
- end
- -- --------------------------------------------------------
- -- PULL STORED ITEMS
- -- --------------------------------------------------------
- local _, available = getStored(ctx, demand.item)
- if available > 0 then
- local toSend = math.min(need, available)
- state.statusText = "Pulling " .. demand.displayName
- local moved = exportAcrossOutputs(
- ctx,
- demand.item,
- toSend
- )
- if moved > 0 then
- recordDelivery(ctx, demand, moved)
- addActivity(state, "PULL", demand.displayName, moved)
- print(
- "[PULL][" .. ctx.customName .. "] "
- .. demand.displayName
- .. " x"
- .. tostring(moved)
- )
- state.alertState[demand.key] = nil
- need = need - moved
- end
- -- If AE2 had the item but none/all could not fit, do not
- -- craft more until Builder storage has room.
- if moved < toSend then
- state.statusText = "Storage full/blocked"
- return
- end
- end
- if need <= 0 then
- state.statusText = "Supplied " .. demand.displayName
- return
- end
- -- --------------------------------------------------------
- -- CRAFTING
- -- --------------------------------------------------------
- if isCrafting(ctx, demand.item) then
- state.statusText = "Crafting " .. demand.displayName
- state.alertState[demand.key] = nil
- return
- end
- if isCraftable(ctx, demand.item) then
- local retryAt = state.craftRetry[demand.key] or 0
- if now() >= retryAt then
- state.statusText = "Starting craft: " .. demand.displayName
- local started = startCraft(
- ctx,
- demand.item,
- need
- )
- state.craftRetry[demand.key] = now() + CRAFT_RETRY_SECONDS
- if started then
- addActivity(state, "CRAFT", demand.displayName, need)
- print(
- "[CRAFT][" .. ctx.customName .. "] "
- .. demand.displayName
- .. " x"
- .. tostring(need)
- )
- state.statusText = "Crafting " .. demand.displayName
- state.alertState[demand.key] = nil
- return
- end
- notifyMissing(ctx, demand, need)
- return
- end
- state.statusText = "Waiting for craft retry"
- return
- end
- -- --------------------------------------------------------
- -- NOT STORED / NOT CRAFTABLE
- -- --------------------------------------------------------
- notifyMissing(ctx, demand, need)
- end
- local function cleanupDemandState(ctx, demands)
- local state = ctx.state
- for key in pairs(state.alertState) do
- if not demands[key]
- or demands[key].totalNeed <= 0 then
- state.alertState[key] = nil
- end
- end
- for key in pairs(state.craftRetry) do
- if not demands[key]
- or demands[key].totalNeed <= 0 then
- state.craftRetry[key] = nil
- end
- end
- end
- -- ============================================================
- -- UPDATE ONE BUILDER
- -- ============================================================
- local function updateBuilder(ctx, citizens, orders, allRequests)
- local state = ctx.state
- if not ctx.hut then
- state.statusText = "No assigned Builder Hut"
- state.builderDisplay = {}
- state.hutDisplay = {}
- return
- end
- local worker = findBuilderWorker(citizens, ctx.hut.pos)
- ctx.builderName = worker and worker.name or nil
- local order = findWorkOrderForHut(orders, ctx.hut.pos)
- ctx.activeBuildingName = order and order.buildingName or "Builder's Hut"
- if #ctx.outputs == 0 then
- state.statusText = "No writable storage faces"
- elseif not worker then
- -- Still supply Hut resources even if the worker is absent;
- -- only personal requests will be empty.
- state.statusText = "No Builder worker assigned"
- else
- state.statusText = "Checking colony demand..."
- end
- local ok, demands = pcall(
- collectDemands,
- ctx,
- allRequests
- )
- if not ok then
- state.statusText = "Demand read error"
- print(
- "[ERROR][" .. ctx.customName .. "] "
- .. tostring(demands)
- )
- return
- end
- for _, demand in pairs(demands) do
- if demand.totalNeed > 0 then
- local processOK, processErr = pcall(
- processDemand,
- ctx,
- demand
- )
- if not processOK then
- print(
- "[ERROR][" .. ctx.customName .. "] "
- .. demand.displayName
- .. ": "
- .. tostring(processErr)
- )
- state.statusText = "Error: " .. demand.displayName
- end
- end
- end
- cleanupDemandState(ctx, demands)
- if next(demands) == nil then
- state.statusText = "No current requirements"
- end
- end
- -- ============================================================
- -- STARTUP DISPLAY
- -- ============================================================
- term.clear()
- term.setCursorPos(1, 1)
- print("========================================")
- print(" MineColonies AE2 Builder Supplier v6")
- print("========================================")
- print("Colony: " .. colonyName)
- print(
- "Computer anchor: "
- .. tostring(COMPUTER_POS.x) .. ","
- .. tostring(COMPUTER_POS.y) .. ","
- .. tostring(COMPUTER_POS.z)
- )
- print("Dynamic builder_# discovery: ON")
- print("Dynamic Builder Hut assignment: ON")
- print("Storage face probing: ON")
- print("AE2 autocrafting: ON")
- print("Chat alerts: ON")
- print("Monitor dashboard: ON")
- print("")
- print("Press Ctrl+T to stop.")
- print("")
- -- ============================================================
- -- INITIAL DISCOVERY
- -- ============================================================
- discoverTopology()
- -- ============================================================
- -- MAIN LOOP
- -- ============================================================
- while true do
- -- Periodically discover newly added builder_# bridges, huts,
- -- and newly writable storage faces.
- if (now() - lastTopologyScan) >= TOPOLOGY_RESCAN_SECONDS then
- local ok, err = pcall(discoverTopology)
- if not ok then
- print("[DISCOVERY ERROR] " .. tostring(err))
- lastTopologyScan = now()
- end
- end
- local citizens = colony.getCitizens() or {}
- local orders = colony.getWorkOrders() or {}
- local allRequests = colony.getRequests() or {}
- for _, ctx in ipairs(BUILDERS) do
- local ok, err = pcall(
- updateBuilder,
- ctx,
- citizens,
- orders,
- allRequests
- )
- if not ok then
- ctx.state.statusText = "Builder update error"
- print(
- "[BUILDER ERROR][" .. ctx.customName .. "] "
- .. tostring(err)
- )
- end
- end
- drawDashboard()
- sleep(POLL_INTERVAL)
- end
Advertisement