diff --git a/genericAutocraft.lua b/genericAutocraft.lua index 3931eaa..21f4d9d 100644 --- a/genericAutocraft.lua +++ b/genericAutocraft.lua @@ -5,12 +5,71 @@ local function agc(name) end local computer = agc("computer") -local fs = require("filesystem") -local kernel = require("kernel") -local crafter = agc("digitalCrafter") -local interface = agc("adapter") -local k = 1000 +local function getComponentOfTypeAndId(componentType, componentId) + for cType, ud in components:list() do + if ud.uniqueId == componentId then + assert(cType == componentType, ("component with id %d was expected to be of type '%s' but was '%s'."):format(componentId, componentType, cType)) + return ud + end + end + assert(false, ("couldnt find component of type '%s' with id %d."):format(componentType, componentId)) +end + +---@class craftSetup +---@field crafter componentUd +---@field interface componentUd +---@field onCooldownUntil number + +---@type craftSetup[] +local craftSetups = {} +local anyInterface = nil +local anyCrafter = nil +local function registerCraftSetup(crafterId, adapterId) + local adapterUd = getComponentOfTypeAndId("adapter", adapterId) + assert(adapterUd.getCount ~= nil, ("adapter with id %d was found but didnt have a getCount method. Is it maybe not pointing at interface?"):format(adapterId)) + + ---@type craftSetup + local setup = { + crafter = getComponentOfTypeAndId("digitalCrafter",crafterId), + interface = adapterUd, + onCooldownUntil = -1 + } + anyInterface = anyInterface or adapterUd + anyCrafter = anyCrafter or setup.crafter + table.insert(craftSetups, setup) +end + +registerCraftSetup(38, 41) +registerCraftSetup(72, 75) +registerCraftSetup(73, 76) +registerCraftSetup(74, 77) + +assert(#craftSetups > 0, "no craft setups were registered :C") +assert(anyInterface) +assert(anyCrafter) + +local function timeNow() return computer:getEpoch() end + +local function getAvailableCraftSetup() + ---@type craftSetup + local nextCraftSetup = nil + local now = timeNow() + for _, value in ipairs(craftSetups) do + local readyAt = value.onCooldownUntil + if nextCraftSetup == nil or readyAt < nextCraftSetup.onCooldownUntil then + if value.onCooldownUntil < now then return value end -- we found a setup thats ready, so return it immediately + nextCraftSetup = value -- set new best craft setup + end + end + + -- we didnt find one thats ready yet, so wait for the one in nextCraftSetup + sleep(nextCraftSetup.onCooldownUntil - now) + return nextCraftSetup +end + + +local k = 1000 local currentCraftCondition = nil local recipesToAutocraft = {} @@ -35,24 +94,24 @@ end local function pred_itemGreaterThan(itemName, amount) return function() - return interface:getCount(itemName) > amount + return anyInterface:getCount(itemName) > amount end end local function pred_itemLessThan(itemName, amount) return function() - return interface:getCount(itemName) < amount + return anyInterface:getCount(itemName) < amount end end local function addSingleRecipeOfItem(name) -- ensures that there is exactly one recipe to use - local recipesForItem = crafter:searchRecipesWithResult(name) + local recipesForItem = anyCrafter:searchRecipesWithResult(name) assert(#recipesForItem == 1, "somehow there was not exactly one recipe for "..tostring(name)) local recipe = recipesForItem[1] addRecipeDirect(recipe) end local function addSingleRecipeForItemOfIngredients(target, ingredients) -- ensures that there is exactly one recipe to use - local recipesForItem = crafter:searchRecipesWithResult(target) + local recipesForItem = anyCrafter:searchRecipesWithResult(target) local filteredRecipes = {} for index, recipe in ipairs(recipesForItem) do local recipeIngredients = recipe.ingredients @@ -81,7 +140,7 @@ local function addSingleRecipeForItemOfIngredients(target, ingredients) -- ensur -- make sure there are no listed ingredients that are not mentioned in 'ingredients' for j = 1, #ingredients do if not referencedFilterIngredientIdxs[j] then - currentRecipeIsMatch = false + currentRecipeIsMatch = false end end end @@ -94,13 +153,13 @@ local function addSingleRecipeForItemOfIngredients(target, ingredients) -- ensur assert(#filteredRecipes == 1, ("somehow there was not exactly one recipe for %s from ingredients %s"):format(target, table.concat(ingredients, " "))) local recipe = filteredRecipes[1] for i = 1, #recipe.ingredients do - print("ingredient: ",recipe.ingredients[i][1]) + print("ingredient: ", recipe.ingredients[i][1]) end addRecipeDirect(recipe) end local function addSingleRecipeWithExactlyNIngredients(name, ingredientCount, justTakeTheFirstRecipeIfTheresMultiple) -- ensures that there is exactly one recipe to use - local recipesForItem = crafter:searchRecipesWithResult(name) + local recipesForItem = anyCrafter:searchRecipesWithResult(name) local filtered = {} for _, recipe in ipairs(recipesForItem) do local recipeIngredientCount = 0 @@ -129,7 +188,7 @@ local function addSingleRecipeForAllCsv(csv, prefixOrNil) end local function addSingleRecipeThatUsesItem(itemToConsume) - local recipesForItem = crafter:searchRecipesWithIngredient(itemToConsume) + local recipesForItem = anyCrafter:searchRecipesWithIngredient(itemToConsume) assert(#recipesForItem == 1, "somehow there was not exactly one recipe that uses "..tostring(itemToConsume)) local recipe = recipesForItem[1] addRecipeDirect(recipe) @@ -151,6 +210,14 @@ withCraftCondition(pred_itemLessThan("minecraft:oak_planks",256), function() addSingleRecipeWithExactlyNIngredients("minecraft:oak_planks", 1) end) +withCraftCondition(pred_itemLessThan("hostilenetworks:prediction_matrix", 2*k), function() + addSingleRecipeOfItem("hostilenetworks:prediction_matrix") +end) + +withCraftCondition(pred_itemLessThan("minecraft:glass_pane", 512), function() + addSingleRecipeOfItem("minecraft:glass_pane") +end) + for resourceName in ("copper,iron,lapis,redstone,diamond,emerald,amethyst,netherite"):gmatch("[^,]+") do local resourceItem = resourceName if resourceName == "copper" or resourceName == "iron" or resourceName == "gold" or resourceName == "netherite" then @@ -191,19 +258,24 @@ addSingleRecipeForAllCsv([[zinc_block]], "create:raw_") addSingleRecipeForAllCsv([[aluminum_block,platinum_block,iridium_block]], "alltheores:raw_") addSingleRecipeForAllCsv([[tin_block,lead_block,silver_block,nickel_block]], "thermal:raw_") -withCraftCondition(pred_itemGreaterThan("minecraft:netherite_scrap",512), function() - addSingleRecipeForItemOfIngredients("minecraft:netherite_ingot", {"minecraft:netherite_scrap", "minecraft:gold"}) -end) +--withCraftCondition(pred_itemGreaterThan("minecraft:netherite_scrap",512), function() + --addSingleRecipeForItemOfIngredients("minecraft:netherite_ingot", {"minecraft:netherite_scrap", "minecraft:gold"}) +--end) print(("%s Recipes loaded."):format(#recipesToAutocraft)) -local function safeCraft(...) +---comment +---@param craftSetup craftSetup +---@param ... any +local function safeCraft(craftSetup, ...) + local crafter = craftSetup.crafter while true do local cooldown = crafter.cooldownRemaining if cooldown <= 0 then break end sleep(cooldown) end - return crafter:craft(...) + crafter:craft(...) + craftSetup.onCooldownUntil = timeNow() + crafter.cooldownRemaining end -- try to craft the given recipe as often as possible; greedy not optimal. Might need to be called multiple times in order to consume all valid items in case there are multiple options @@ -214,6 +286,7 @@ local function tryCraftRecipeAsOftenAsPossible(recipe) local resultItemName = recipe.result local actualIngredients = {} + -- pick concrete items that we have in stock for this recipe for i = 1, 9 do local currentSlotOptions = recipe.ingredients[i] @@ -223,7 +296,7 @@ local function tryCraftRecipeAsOftenAsPossible(recipe) local anyInStock = false for _, slotOption in ipairs(currentSlotOptions) do if stockOfIngredientForItemSelection[slotOption] == nil then - local x = interface:getCount(slotOption) + local x = anyInterface:getCount(slotOption) stockOfIngredientForItemSelection[slotOption] = x stockOfIngredientForCraftCountSelection[slotOption] = x end @@ -257,17 +330,18 @@ local function tryCraftRecipeAsOftenAsPossible(recipe) if recipeCraftCount == 0 then error(("We somehow dont have enough to craft %s. Is our math wrong?"):format(resultItemName)) else + local ourCraftSetup = getAvailableCraftSetup() print(("Time to craft %dx %s."):format(recipeCraftCount, resultItemName)) - crafter:dumpInventory() + ourCraftSetup.crafter:dumpInventory() for itemName, count in pairs(ingredientsStacked) do local remainingCount = recipeCraftCount * count while remainingCount > 0 do - local extracted = interface:extract(itemName, 1, remainingCount) + local extracted = ourCraftSetup.interface:extract(itemName, 1, remainingCount) assert(extracted > 0, "somehow we ran out of an item during exporting???") remainingCount = remainingCount - extracted end end - safeCraft(actualIngredients, recipe.result, recipeCraftCount, false) + safeCraft(ourCraftSetup, actualIngredients, recipe.result, recipeCraftCount, false) return true end end @@ -280,7 +354,7 @@ while true do skipSleep = false for _, packedRecipe in ipairs(recipesToAutocraft) do local recipe = packedRecipe.recipe - local maxCraft = (recipe.result:find("fuel") and 1 or 10) -- craft 10 stacks at once to speed things up, unless this is a fuel recipe + local maxCraft = (recipe.result:find("fuel") and 1 or 40) -- craft 10 stacks at once to speed things up, unless this is a fuel recipe for _ = 1, maxCraft do if packedRecipe.condition == nil or packedRecipe.condition() then local success = tryCraftRecipeAsOftenAsPossible(packedRecipe.recipe)