t8rt0t

fern-scanner-2.0.lua

Jul 3rd, 2024 (edited)
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 11.61 KB | None | 0 0
  1. --paths
  2. regionAssignment = "metadata/.region.json"
  3. validFuelsPath = "metadata/fuels.json"
  4. regionPathFormat = "regions/%d_%d.dat"
  5. --constants
  6. local datlib = require("datlib")
  7. local sps = require("sps")
  8. local modemID = "computercraft:wireless_modem_advanced"
  9. local environmentID = "advancedperipherals:environment_detector"
  10. local validFuels = {
  11.     ["minecraft:coal"] = 80,
  12.     ["minecraft:coal_block"] = 800,
  13.     ["createaddition:biomass_pellet_block"] = 2880,
  14.     ["createaddition:biomass_pellet"] = 320,
  15.     ["quark:blaze_lantern"] = 1200,
  16.     ["quark:charcoal_block"] = 800
  17. }
  18. local fuelLimit = turtle.getFuelLimit()
  19. local dat = {}
  20. local scanHeight = 310
  21.  
  22. local REGION,HOME
  23.  
  24.  
  25. --Util Functions
  26. local function selectSlot(slot)
  27.     return (turtle.getSelectedSlot() == slot) or turtle.select(slot)
  28. end
  29. local function selectItem(name)
  30.     for i=1,16 do
  31.         if (turtle.getItemDetail(i) or {}).name == name then
  32.             selectSlot(i)
  33.             return i
  34.         end
  35.     end
  36.     return false
  37. end
  38. local function equipModem()
  39.     if peripheral.getType("left") == "modem" then
  40.         rednet.open("left")
  41.         return rednet.isOpen()
  42.     elseif selectItem(modemID) then
  43.         turtle.equipLeft()
  44.         rednet.open("left")
  45.         return rednet.isOpen()
  46.     end
  47.     return false
  48. end
  49. local function equipEnvironment()
  50.     if peripheral.getType("left") == "environmentDetector" then
  51.         return peripheral.wrap("left")
  52.     elseif selectItem(environmentID) then
  53.         turtle.equipLeft()
  54.         return peripheral.wrap("left")
  55.     end
  56.     return false
  57. end
  58. local function dist(x,y,z,a,b,c)
  59.     return math.abs(x-a) + math.abs(y-b) + math.abs(z-c)
  60. end
  61. local function refuel()
  62.     local x,y,z = sps.locate()
  63.     local distance = dist(x,y,z,HOME[1],HOME[2],HOME[3])
  64.     if turtle.getFuelLevel() > distance*1.5 and turtle.getFuelLevel() * 2 > fuelLimit then
  65.         print("Skipping refuel, have enough to make it to HOME 1.5 times")
  66.         return true
  67.     end
  68.     for i=1,16 do
  69.         if turtle.getItemCount(i) > 0 and validFuels[turtle.getItemDetail(i).name] then
  70.             local amount = math.min( (fuelLimit - turtle.getFuelLevel())/validFuels[turtle.getItemDetail(i).name],64)
  71.             selectSlot(i)
  72.             turtle.refuel(amount)
  73.             if amount < 64 then
  74.                 print("Refuelled to max value!")
  75.                 return true
  76.             end
  77.         end
  78.     end
  79.     if turtle.getFuelLevel() > distance*1.5 and turtle.getFuelLevel() * 2 > fuelLimit then
  80.         print("Refuelled enough to make it to HOME 1.5 times")
  81.         return true
  82.     end
  83.     print("Refuel failure, no fuel found!")
  84.     return false
  85. end
  86.  
  87. --------------------Init
  88. term.clear()
  89. --Init checks
  90. print("Init Checks")
  91. assert(turtle,"This computer is not a turtle!")
  92. assert(peripheral.getType("right") == "chunky","Make sure you put a chunkloader inside the right slot!")
  93. assert(equipModem(),"Make sure to provide a modem for gps and communication")
  94. assert(equipEnvironment(),"Make sure to provide an environment detector so the turtle can actually scan!")
  95. --SPS init
  96. print("Init SPS")
  97. if not sps.init() then
  98.     equipModem()
  99.     local s,x,y,z = pcall(gps.locate)
  100.     if not s or not x then
  101.         print("Please enter the coordinates as `[x] [y] [z]`")
  102.         x,y,z = read():gsub("[%s,]+"," "):match("(%-?%d+) (%-?%d+) (%-?%d+)")
  103.         if not tonumber(x) or not tonumber(y) or not tonumber(z) then error("Please provide valid coordinates") end
  104.     end
  105.     print("Please enter the direction the turtle is facing (use f3) as `north|south|east|west`)")
  106.     local facing = read():lower()
  107.     assert(sps.init(facing,tonumber(x),tonumber(y),tonumber(z)),"Could not initialize Safe Positioning System")
  108. end
  109. --Metadata init
  110. print("loading metadata")
  111. if fs.exists(regionAssignment) then
  112.     local file = fs.open(regionAssignment,"r")
  113.     local data = textutils.unserialiseJSON(file.readAll())
  114.     if data then REGION,HOME = data[1],data[2] end
  115.     file.close()
  116. end
  117. do
  118.     local updateFileFlag
  119.     if not HOME then
  120.         HOME = {sps.locate()}
  121.         updateFileFlag = true
  122.     end
  123.     if not REGION then
  124.         print("Please enter the region you wish the turtle to scan in in the format `regionX,regionZ`")
  125.         local x,z = read():gsub("%s+",""):match("(%-?%d+),(%-?%d+)")
  126.         if not tonumber(x) or not tonumber(z) then error("Please provide a valid region") end
  127.         REGION = {tonumber(x),tonumber(z)}
  128.         updateFileFlag = true
  129.     end
  130.     if updateFileFlag then
  131.         local file = fs.open(regionAssignment,"w+")
  132.         file.write(textutils.serialiseJSON({REGION,HOME}))
  133.         file.close()
  134.     end
  135. end
  136. print("Loaded metadata")
  137. print("REGION:",textutils.serialise(REGION,{compact=true}))
  138. print("HOME:",textutils.serialise(HOME,{compact=true}))
  139. --Fuel init
  140. if fs.exists(validFuelsPath) then
  141.     print("Loading valid fuels")
  142.     local file = fs.open(validFuelsPath,"r")
  143.     local fuels = textutils.unserialiseJSON(file.readAll())
  144.     file.close()
  145.     for k,v in pairs(fuels or {}) do
  146.         validFuels[k] = v
  147.     end
  148. else
  149.     print("No valid fuels overrides to load, skipping")
  150. end
  151. --dat file init
  152. print("loading dat file")
  153. dat = datlib:open(regionPathFormat:format(REGION[1],REGION[2]))
  154. print("Initial refuel")
  155. repeat
  156.     sleep(1)
  157. until refuel()
  158. print("Initial refuel complete!")
  159.  
  160. -------Data Functions
  161. local function getRegionPos(x,z)
  162.     return math.floor(x/2048),math.floor(z/2048)
  163. end
  164. local function isInRegion(x,z)
  165.     local rx,rz = getRegionPos(x,z)
  166.     return rx == REGION[1] and rz == REGION[2]
  167. end
  168. local function getLocalChunk(x,z)
  169.     return math.floor(x/16)%128,math.floor(z/16)%128
  170. end
  171. local function scanBroadcastAndWrite()
  172.     local environmentDetector = assert(equipEnvironment())
  173.     local biome = environmentDetector.getBiome()
  174.     local x,y,z = sps.locate()
  175.     equipModem()
  176.     rednet.broadcast({x,y,z,biome},"DATA")
  177.     print("DATA:",x,y,z,biome)
  178.     if isInRegion(x,z) then
  179.         local cX,cZ = getLocalChunk(x,z)
  180.         print("data is within region, adding to file at chunk indices:",cX,cZ)
  181.         dat:setBiome(cX,cZ,biome)
  182.     end
  183.     return true
  184. end
  185.  
  186. -------Movement Functions
  187. local function gpsPing()
  188.     equipModem()
  189.     local s,x,y,z = pcall(gps.locate)
  190.     if s and x and y and z then
  191.         sps.updatePosition(x,y,z)
  192.     end
  193.     local f = fs.open("metadata/position.txt","w+")
  194.     f.write(x .. ", ".. y .. ", " .. z)
  195.     f.close()
  196. end
  197.  
  198. local function rotate(dir)
  199.     local _,facing = sps.facing()
  200.     if (dir-facing)%4 > 2 then
  201.         return turtle.turnLeft()
  202.     end
  203.     while facing ~= dir do
  204.         turtle.turnRight()
  205.         _,facing = sps.facing()
  206.     end
  207.     return true
  208. end
  209. local up = turtle.up
  210. local down = turtle.down
  211. local forward = turtle.forward
  212. -- for k,v in ipairs({forward=turtle.forward,back=turtle.back,up=turtle.up,down=turtle.down}) do
  213. --     _G[k] = v
  214. -- end
  215. local function moveToPos(x,y,z)
  216.     print("Moving to pos:",x,y,z)
  217.     local x0,y0,z0 = sps.locate()
  218.     local stuckIndex = 0
  219.     print("Current Pos:",x0,y0,z0)
  220.     while y0 < y do
  221.         if math.random(100) == 69 then
  222.             gpsPing()
  223.         end
  224.         if not up() then
  225.             stuckIndex = stuckIndex + 1
  226.             refuel()
  227.             if stuckIndex > 5 then
  228.                 forward()
  229.                 sleep(math.random(10))
  230.                 back()
  231.             end
  232.         else
  233.             stuckIndex = 0
  234.         end
  235.         x0,y0 = sps.locate()
  236.     end
  237.     while y0 > y do
  238.         if math.random(100) == 69 then
  239.             gpsPing()
  240.         end
  241.         if not down() then
  242.             stuckIndex = stuckIndex + 1
  243.             refuel()
  244.             if stuckIndex > 5 then
  245.                 forward()
  246.                 sleep(math.random(10))
  247.                 back()
  248.             end
  249.         else
  250.             stuckIndex = 0
  251.         end
  252.         x0,y0 = sps.locate()
  253.     end
  254.     local index = 0
  255.     if z0 < z then rotate(2)
  256.     elseif z0 > z then rotate(0) end
  257.     while z0 ~= z do
  258.         if math.random(100) == 69 then
  259.             gpsPing()
  260.         end
  261.         if not forward() then
  262.             stuckIndex = stuckIndex + 1
  263.             refuel()
  264.             if stuckIndex > 5 then
  265.                 sleep(math.random(5))
  266.                 up()
  267.                 sleep(math.random(10))
  268.                 down()
  269.             end
  270.         else
  271.             stuckIndex = 0
  272.         end
  273.         x0,y0,z0 = sps.locate()
  274.         index = index + 1
  275.         if index == 16 then
  276.             scanBroadcastAndWrite()
  277.             index = 0
  278.             assert(refuel())
  279.         end
  280.     end
  281.     if x0 < x then rotate(1) --x after z to simplify dat pathfinding
  282.     elseif x0 > x then rotate(3) end
  283.     while x0 ~= x do
  284.         if math.random(100) == 69 then
  285.             gpsPing()
  286.         end
  287.         if not forward() then
  288.             stuckIndex = stuckIndex + 1
  289.             refuel()
  290.             if stuckIndex > 5 then
  291.                 sleep(math.random(5))
  292.                 up()
  293.                 sleep(math.random(10))
  294.                 down()
  295.             end
  296.         else
  297.             stuckIndex = 0
  298.         end
  299.         x0 = sps.locate()
  300.         index = index + 1
  301.         if index == 16 then
  302.             scanBroadcastAndWrite()
  303.             index = 0
  304.             assert(refuel())
  305.         end
  306.     end
  307.     scanBroadcastAndWrite()
  308.     if x0 ~= x or y0 ~= y or z0 ~= z then error("Coordinates do not match") end
  309.     return true
  310. end
  311.  
  312. local function goHome()
  313.     print("Going home!")
  314.     moveToPos(HOME[1],scanHeight,HOME[3])
  315.     moveToPos(HOME[1],HOME[2],HOME[3])
  316. end
  317.  
  318. local function SOS()
  319.     equipModem()
  320.     local function awaitReboot()
  321.         while true do
  322.             pcall(function()
  323.                     local sndr,msg,prtcl = rednet.receive()
  324.                     if prtcl == "REBOOT" then
  325.                         os.reboot()
  326.                     elseif prtcl == "HOME" then
  327.                         local x,y,z = sps.locate()
  328.                         if dist(x,y,z,HOME[1],HOME[2],HOME[3]) <= turtle.getFuelLevel() then
  329.                             goHome()
  330.                         else
  331.                             rednet.send(sndr,string.format("Lack fuel to go to %d %d %d",HOME[1],HOME[2],HOME[3]),"ERROR")
  332.                         end
  333.                     end
  334.             end)
  335.         end
  336.     end
  337.     local function broadcastPosition()
  338.         while true do
  339.             pcall(function()
  340.                     rednet.broadcast({pos={sps.locate()},fuel=turtle.getFuelLevel(),facing=sps.facing()},"SOS")
  341.                     rednet.broadcast({pos={sps.locate()},fuel=turtle.getFuelLevel(),facing=sps.facing()},"SOS_ERR")
  342.                     sleep(1)
  343.             end)
  344.         end
  345.     end
  346.     local function updatePos()
  347.         while true do
  348.             pcall(function()
  349.                     local s,x,y,z = pcall(gps.locate)
  350.                     if s and x and y and z then
  351.                         sps.updatePosition(x,y,z)
  352.                         return true
  353.                     end
  354.                     sleep(0)
  355.             end)
  356.         end
  357.     end
  358.     parallel.waitForAll(updatePos,broadcastPosition,awaitReboot)
  359. end
  360.  
  361. print("Ready to start main sequence")
  362. --Main
  363. local function cycle()
  364.     local cX,cZ = dat:getNextChunk()
  365.     if not cX then
  366.         goHome()
  367.         fs.delete(regionAssignment)
  368.         os.shutDown()
  369.     else
  370.         print(string.format("Target Chunk at %d %d",cX,cZ))
  371.         moveToPos((REGION[1]*128+cX)*16,scanHeight,(REGION[2]*128+cZ)*16)
  372.     end
  373. end
  374. while true do
  375.     local s,err = pcall(cycle)
  376.     if not s then
  377.         print("SOS",err)
  378.         SOS(tostring(err))
  379.     end
  380.     sleep(0)
  381. end  
Advertisement
Add Comment
Please, Sign In to add comment