Files
AcScripts/genericAutocraft.lua
T
2026-10-04 23:48:21 +02:00

370 lines
15 KiB
Lua

print("AC autocrafter :D")
local function agc(name)
return assert(components:getFirst(name), "failed to get component "..name)
end
local computer = agc("computer")
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<const> = 1000
local currentCraftCondition = nil
local recipesToAutocraft = {}
local function addRecipeDirect(recipe)
assert(type(recipe) == "table", "recipe was not table but "..type(recipe))
assert(recipe.ingredients, "key ingredients was not contained in recipe")
assert(recipe.result, "key result was not contained in recipe")
assert(recipe.resultCount, "key resultCount was not contained in recipe")
table.insert(recipesToAutocraft, {
recipe=recipe,
condition=currentCraftCondition
})
end
local function withCraftCondition(condition, innerBlock)
assert(type(condition) == "function", "condition must be func")
assert(type(innerBlock) == "function", "innerBlock must be func")
currentCraftCondition = condition
innerBlock()
currentCraftCondition = nil
end
local function pred_itemGreaterThan(itemName, amount)
return function()
return anyInterface:getCount(itemName) > amount
end
end
local function pred_itemLessThan(itemName, amount)
return function()
return anyInterface:getCount(itemName) < amount
end
end
local function addSingleRecipeOfItem(name) -- ensures that there is exactly one recipe to use
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 = anyCrafter:searchRecipesWithResult(target)
local filteredRecipes = {}
for index, recipe in ipairs(recipesForItem) do
local recipeIngredients = recipe.ingredients
local currentRecipeIsMatch = true
local referencedFilterIngredientIdxs = {}
for i = 1, 9 do -- make sure all listed ingredients are mentioned in 'ingredients'
if recipeIngredients[i] ~= nil then
local possibleIngredientOptions = table.concat(recipeIngredients[i],";")
local anyIngredientOptionIsListedForEachSlot = false
for j = 1, #ingredients do
if possibleIngredientOptions:find(ingredients[j], 0, true) then
--recipeIngredients[i] = ingredients[j]
referencedFilterIngredientIdxs[j] = true
anyIngredientOptionIsListedForEachSlot = true
break
end
end
if not anyIngredientOptionIsListedForEachSlot then
currentRecipeIsMatch = false
end
end
end
if currentRecipeIsMatch then
-- 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
end
end
end
if currentRecipeIsMatch then
table.insert(filteredRecipes, recipe)
end
end
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])
end
addRecipeDirect(recipe)
end
local function addSingleRecipeWithExactlyNIngredients(name, ingredientCount, justTakeTheFirstRecipeIfTheresMultiple) -- ensures that there is exactly one recipe to use
local recipesForItem = anyCrafter:searchRecipesWithResult(name)
local filtered = {}
for _, recipe in ipairs(recipesForItem) do
local recipeIngredientCount = 0
for i = 1, 9 do
if recipe.ingredients[i] then
recipeIngredientCount = recipeIngredientCount + 1
end
end
if recipeIngredientCount == ingredientCount then
table.insert(filtered, recipe)
end
end
if justTakeTheFirstRecipeIfTheresMultiple and #filtered > 1 then
filtered = {filtered[1]}
end
assert(#filtered == 1, "somehow there was not exactly one recipe for "..tostring(name))
local recipe = filtered[1]
addRecipeDirect(recipe)
end
local function addSingleRecipeForAllCsv(csv, prefixOrNil)
for match in csv:gsub("%s",""):gmatch("[^,]+") do
addSingleRecipeOfItem((prefixOrNil or "")..match)
end
end
local function addSingleRecipeThatUsesItem(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)
end
addSingleRecipeThatUsesItem("mysticalagriculture:sulfur_essence")
addSingleRecipeThatUsesItem("mysticalagriculture:draconium_essence")
addSingleRecipeThatUsesItem("mysticalagriculture:neutronium_essence")
addSingleRecipeThatUsesItem("mysticalagriculture:awakened_draconium_essence")
addSingleRecipeWithExactlyNIngredients("draconicevolution:awakened_draconium_ingot", 9)
addSingleRecipeWithExactlyNIngredients("avaritia:neutronium_ingot", 9)
addSingleRecipeWithExactlyNIngredients("minecraft:copper_ingot", 9, true)
addSingleRecipeWithExactlyNIngredients("minecraft:amethyst_shard", 8)
withCraftCondition(pred_itemGreaterThan("minecraft:gold_nugget",10*k), function()
addSingleRecipeWithExactlyNIngredients("minecraft:gold_ingot", 9)
end)
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
resourceItem = resourceName .. "_ingot"
elseif resourceName == "lapis" then
resourceItem = resourceName .. "_lazuli"
elseif resourceName == "amethyst" then
resourceItem = resourceName .. "_shard"
end
local minimumCount = 50*k
if resourceName == "amethyst" or resourceName == "netherite" then
minimumCount = 1 * k
elseif resourceName == "diamond" or resourceName == "emerald" then
minimumCount = 10 * k
end
withCraftCondition(pred_itemGreaterThan(("minecraft:%s"):format(resourceItem),minimumCount), function() addSingleRecipeOfItem(("minecraft:%s_block"):format(resourceName)) end)
end
-- to be prefixed with nuclearcraft:fuel_
local possibleFuelsRaw = --"leu-235,len-236,hen-236,hecf-249,hecm-245,mix-241,mix-239,lep-241,hep-241,heu-233,lecm-245,leu-233,lecf-249,hecm-243,lep-239,hep-239,lecm-243,heu-235,lea-242,tbu,hea_242,lecf_251,heb_248,leb_248"
([[
uranium_leu_235,neptunium_len_236,neptunium_hen_236,californium_hecf_249,curium_hecm_245,mixed_mix_241,
mixed_mix_239,plutonium_lep_241,plutonium_hep_241,uranium_heu_233,curium_lecm_245,uranium_leu_233,californium_lecf_249,curium_hecm_243,plutonium_lep_239,
plutonium_hep_239,curium_lecm_243,uranium_heu_235,americium_lea_242,thorium_tbu,americium_hea_242,californium_lecf_251,berkelium_heb_248,
berkelium_leb_248,curium_hecm_247,californium_hecf_251,curium_lecm_247
]])
addSingleRecipeForAllCsv(possibleFuelsRaw, "nuclearcraft:fuel_")
addSingleRecipeForAllCsv([[osmium,uranium]], "mekanism:block_raw_")
addSingleRecipeForAllCsv([[iron_block,copper_block,gold_block]], "minecraft:raw_")
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)
print(("%s Recipes loaded."):format(#recipesToAutocraft))
---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
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
local function tryCraftRecipeAsOftenAsPossible(recipe)
local ingredientsStacked = {} -- itemName: count_needed_per_craft
local stockOfIngredientForCraftCountSelection = {} -- itemName: count_in_me_system
local stockOfIngredientForItemSelection = {}
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]
if currentSlotOptions == nil then
actualIngredients[i] = nil
else
local anyInStock = false
for _, slotOption in ipairs(currentSlotOptions) do
if stockOfIngredientForItemSelection[slotOption] == nil then
local x = anyInterface:getCount(slotOption)
stockOfIngredientForItemSelection[slotOption] = x
stockOfIngredientForCraftCountSelection[slotOption] = x
end
local selectionCountOfCurrItem = stockOfIngredientForItemSelection[slotOption]
assert(selectionCountOfCurrItem >= 0, "somehow countOfCurrItem was not >= 0?")
if selectionCountOfCurrItem > 0 then -- select this item and reduce the count
stockOfIngredientForItemSelection[slotOption] = selectionCountOfCurrItem - 1
anyInStock = true
ingredientsStacked[slotOption] = (ingredientsStacked[slotOption] or 0) + 1
actualIngredients[i] = slotOption
break
end
end
if not anyInStock then
print(("We dont have enough to craft %s for slot %d."):format(resultItemName, i))
return false
end
end
end
-- at this point we found an item for every slot; so figure out how many recipes we can craft
local maxStackSize = 64 -- fuels always stack 64, same for ingredients, so in principle we could craft 64 fuel at once
local recipeCraftCount = 64 -- how many recipes to craft
for ingredient, count in pairs(ingredientsStacked) do
local maxCraftForCurrIngredient = math.floor(stockOfIngredientForCraftCountSelection[ingredient]/count) -- how often we could craft with this current ingredient
recipeCraftCount = math.min(recipeCraftCount, maxCraftForCurrIngredient)
end
recipeCraftCount = math.min(recipeCraftCount, math.floor(maxStackSize/recipe.resultCount))
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))
ourCraftSetup.crafter:dumpInventory()
for itemName, count in pairs(ingredientsStacked) do
local remainingCount = recipeCraftCount * count
while remainingCount > 0 do
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(ourCraftSetup, actualIngredients, recipe.result, recipeCraftCount, false)
return true
end
end
local skipSleep = true
while true do
if not skipSleep then print("nothing to craft, waiting 30 seconds"); sleep(30) end
print("New iteration started.")
skipSleep = false
for _, packedRecipe in ipairs(recipesToAutocraft) do
local recipe = packedRecipe.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)
if success then
skipSleep = true
else
break
end
end
end
end
end