t8rt0t

fern-scanner.lua

May 2nd, 2024 (edited)
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 19.48 KB | None | 0 0
  1. local fern_data = require("fern-data")
  2. local CHUNK_LIST = {}
  3. local TURTLE
  4. local HOST
  5. local REG_X,REG_Z,REGION
  6. local data_send_queue
  7. if fs.exists("latest.log") then fs.delete("latest.log") end
  8. local log_file = fs.open("latest.log","w+")
  9. local color = colors.yellow
  10.  
  11. local function logAction(...)
  12.     local str = ""
  13.     for k,v in ipairs({...}) do
  14.         if type(v) == "table" then
  15.             temp = textutils.serialiseJSON(v)
  16.             if #temp <= 100 then
  17.                 v = temp
  18.             end
  19.         end
  20.         str = str .. " " .. tostring(v)
  21.     end
  22.     if color == colors.yellow then color = colors.orange else color = colors.yellow end
  23.     term.setTextColor(color)
  24.     print(str)
  25.     pcall(function() log_file.writeLine(os.date("[%H:%M:%S]:") .. str) end)
  26.     log_file.flush()
  27.     if fs.getSize("latest.log") > 100000 then --Log max size reset
  28.         log_file.close()
  29.         fs.delete("latest.log")
  30.         log_file = fs.open("latest.log","w+")
  31.     end
  32. end
  33.  
  34. --Rot: 0=N,1=E,2=S,3=W
  35. local function wrapper()
  36.     local function Turtle(x,y,z,rot)
  37.         local turt = {x=x,y=y,z=z,rot=rot}
  38.         function turt:equipItem(item,side)
  39.             if type(item) ~= "string" then error("Must be an item") end
  40.             logAction("equip",item,side)
  41.             for i=1,16 do
  42.                 if (turtle.getItemDetail(i) or {}).name == item then
  43.                     turtle.select(i)
  44.                     if side == "left" then return turtle.equipLeft() end
  45.                     return turtle.equipRight()
  46.                 end
  47.             end
  48.             return false
  49.         end
  50.         function turt:updatePosition()
  51.             self:equipItem("computercraft:wireless_modem_advanced")
  52.             peripheral.find("modem",rednet.open)
  53.             local x,y,z = gps.locate()
  54.             if not x then error("Can not find turtle") end
  55.             self.x,self.y,self.z = x,y,z
  56.             if turtle.forward() then
  57.                 local x2,y2,z2 = gps.locate()
  58.                 if not x2 then error("Can not find turtle") end
  59.                 if z2 < z then self.rot = 0
  60.                 elseif z2 > z then self.rot = 2
  61.                 elseif x2 > x then self.rot = 1
  62.                 elseif x2 < x then self.rot = 3
  63.                 else error("Could not calculate rotation") end
  64.                 assert(turtle.back())
  65.             elseif turtle.back() then
  66.                 local x2,y2,z2 = gps.locate()
  67.                 if not x2 then error("Can not find turtle") end
  68.                 if z2 < z then self.rot = 2
  69.                 elseif z2 > z then self.rot = 0
  70.                 elseif x2 > x then self.rot = 3
  71.                 elseif x2 < x then self.rot = 1
  72.                 else error("Could not calculate rotation") end
  73.                 assert(turtle.forward())
  74.             else
  75.                 error("Please make sure that turtle has space to move to perform the rotation calculation")
  76.             end
  77.             logAction("update position",x,y,z,self.rot)
  78.         end
  79.         function turt:rotate(dir)
  80.             logAction("rotate",self.rot,dir)
  81.             if tonumber(dir) then
  82.                 local amt = (math.floor(tonumber(dir)) - self.rot)%4
  83.                 if amt == 3 then
  84.                     assert(turtle.turnLeft())
  85.                 else
  86.                     for i=1,amt do
  87.                         assert(turtle.turnRight())
  88.                     end
  89.                 end
  90.                 return true
  91.             elseif type(dir) == "string" then
  92.                 local dirs = {n=0,e=1,s=2,w=3,north=0,east=1,south=2,west=3}
  93.                 local amt = dirs[dir:lower()]
  94.                 if not amt then return false end
  95.                 return self:rotate(amt)
  96.             else
  97.                 return false
  98.             end
  99.         end
  100.         function turt:refuel()
  101.             logAction("refuel")
  102.             if turtle.getFuelLimit() - turtle.getFuelLevel() <= 3000 then return turtle.getFuelLevel() end
  103.             for i=1,16 do
  104.                 turtle.select(i)
  105.                 if turtle.refuel(0) then
  106.                     local oldLvl = turtle.getFuelLevel()
  107.                     turtle.refuel(1)
  108.                     local amt = turtle.getFuelLevel() - oldLvl
  109.                     local itemsToBurn = math.floor((turtle.getFuelLimit() - turtle.getFuelLevel())/amt)
  110.                     turtle.refuel(math.min(turtle.getItemCount(i),itemsToBurn))
  111.                 end
  112.                 if turtle.getFuelLimit() - turtle.getFuelLevel() <= 3000 then return turtle.getFuelLevel() end
  113.             end
  114.             return turtle.getFuelLevel()
  115.         end
  116.         turt:refuel()
  117.         if not tonumber(x) or not tonumber(y) or not tonumber(z) or not tonumber(rot) then turt:updatePosition() end
  118.         function turt:moveToPos(x,y,z,verticalLast)
  119.             logAction("move",x,y or 310,z,self.x,self.y,self.z)
  120.             local index = -1
  121.             if not tonumber(x) or not tonumber(z) then error("Must provide coordinates to travel to") end
  122.             x,y,z = math.floor(tonumber(x)), math.floor(tonumber(y) or 310), math.floor(tonumber(z))
  123.             if not verticalLast then
  124.                 if math.abs(self.y - y) > self:refuel() then error("Lack sufficient fuel") end
  125.                 while self.y < y do
  126.                     assert(turtle.up())
  127.                     self.y = self.y + 1
  128.                     index = index + 1
  129.                     if index%100 == 0 then
  130.                         logAction("pos",self.x,self.y,self.z,self.rot)
  131.                         if fs.exists("pos.txt") then fs.delete("pos.txt") end
  132.                         local file = fs.open("pos.txt","w+")
  133.                         file.write(self.x .. " " .. self.y .. ",, " .. self.z .. ", "..self.rot)
  134.                         file.close()
  135.                         index = 0
  136.                     end
  137.                 end
  138.                 while self.y > y do
  139.                     assert(turtle.down())
  140.                     self.y = self.y - 1
  141.                     index = index + 1
  142.                     if index%100 == 0 then
  143.                         logAction("pos",self.x,self.y,self.z,self.rot)
  144.                         if fs.exists("pos.txt") then fs.delete("pos.txt") end
  145.                         local file = fs.open("pos.txt","w+")
  146.                         file.write(self.x .. " " .. self.y .. ",, " .. self.z .. ", "..self.rot)
  147.                         file.close()
  148.                         index = 0
  149.                     end
  150.                 end
  151.             end
  152.             if math.abs(self.x - x) > self:refuel() then error("Lack sufficient fuel") end
  153.             if self.x > x then
  154.                 self:rotate("W") --Face west if you are more east than your target
  155.                 while self.x ~= x do
  156.                     assert(turtle.forward())
  157.                     self.x = self.x - 1
  158.                     index = index + 1
  159.                     if index%100 == 0 then
  160.                         logAction("pos",self.x,self.y,self.z,self.rot)
  161.                         if fs.exists("pos.txt") then fs.delete("pos.txt") end
  162.                         local file = fs.open("pos.txt","w+")
  163.                         file.write(self.x .. " " .. self.y .. ",, " .. self.z .. ", "..self.rot)
  164.                         file.close()
  165.                         index = 0
  166.                     end
  167.                 end
  168.             elseif self.x < x then
  169.                 self:rotate("E")
  170.                 while self.x ~= x do
  171.                     assert(turtle.forward())
  172.                     self.x = self.x + 1
  173.                     index = index + 1
  174.                     if index%100 == 0 then
  175.                         logAction("pos",self.x,self.y,self.z,self.rot)
  176.                         if fs.exists("pos.txt") then fs.delete("pos.txt") end
  177.                         local file = fs.open("pos.txt","w+")
  178.                         file.write(self.x .. " " .. self.y .. ",, " .. self.z .. ", "..self.rot)
  179.                         file.close()
  180.                         index = 0
  181.                     end
  182.                 end
  183.             end
  184.             if math.abs(self.z - z) > self:refuel() then error("Lack sufficient fuel") end
  185.             if self.z > z then
  186.                 self:rotate("N") --Face north (-z) if you are more south(+z) than your target
  187.                 while self.z ~= z do
  188.                     assert(turtle.forward())
  189.                     self.x = self.x - 1
  190.                     index = index + 1
  191.                     if index%100 == 0 then
  192.                         logAction("pos",self.x,self.y,self.z,self.rot)
  193.                         if fs.exists("pos.txt") then fs.delete("pos.txt") end
  194.                         local file = fs.open("pos.txt","w+")
  195.                         file.write(self.x .. " " .. self.y .. ",, " .. self.z .. ", "..self.rot)
  196.                         file.close()
  197.                         index = 0
  198.                     end
  199.                 end
  200.             elseif self.z < z then
  201.                 self:rotate("S")
  202.                 while self.z ~= z do
  203.                     assert(turtle.forward())
  204.                     self.z = self.z + 1
  205.                     index = index + 1
  206.                     if index%100 == 0 then
  207.                         logAction("pos",self.x,self.y,self.z,self.rot)
  208.                         if fs.exists("pos.txt") then fs.delete("pos.txt") end
  209.                         local file = fs.open("pos.txt","w+")
  210.                         file.write(self.x .. " " .. self.y .. ",, " .. self.z .. ", "..self.rot)
  211.                         file.close()
  212.                         index = 0
  213.                     end
  214.                 end
  215.             end
  216.             if verticalLast then
  217.                 if math.abs(self.y - y) > self:refuel() then error("Lack sufficient fuel") end
  218.                 while self.y < y do
  219.                     assert(turtle.up())
  220.                     self.y = self.y + 1
  221.                     index = index + 1
  222.                     if index%100 == 0 then
  223.                         logAction("pos",self.x,self.y,self.z,self.rot)
  224.                         if fs.exists("pos.txt") then fs.delete("pos.txt") end
  225.                         local file = fs.open("pos.txt","w+")
  226.                         file.write(self.x .. " " .. self.y .. ",, " .. self.z .. ", "..self.rot)
  227.                         file.close()
  228.                         index = 0
  229.                     end
  230.                 end
  231.                 while self.y > y do
  232.                     assert(turtle.down())
  233.                     self.y = self.y - 1
  234.                     index = index + 1
  235.                     if index%100 == 0 then
  236.                         logAction("pos",self.x,self.y,self.z,self.rot)
  237.                         if fs.exists("pos.txt") then fs.delete("pos.txt") end
  238.                         local file = fs.open("pos.txt","w+")
  239.                         file.write(self.x .. " " .. self.y .. ",, " .. self.z .. ", "..self.rot)
  240.                         file.close()
  241.                         index = 0
  242.                     end
  243.                 end
  244.             end
  245.         end
  246.         --Checks and equips the necessary items
  247.         function turt:checkNeededItems()
  248.             logAction("item check")
  249.             if peripheral.getType("left") ~= "chunky" then --If chunkloader not in left slot, try to make sure it is
  250.                 if peripheral.getType("right") == "chunky" then --If chunkloader in the wrong slot, put it in the right slot
  251.                     if self:equipItem("computercraft:wireless_modem_advanced") or self:equipItem("advancedperipherals:environment_detector") then
  252.                         if not self:equipItem("advancedperipherals:chunk_controller","left") then return false end --If you could replace the right slot with its typical peripherals and put the chunk controller in the left slot then you're okay
  253.                     else
  254.                         return false
  255.                     end
  256.                 else
  257.                     if not self:equipItem("advancedperipherals:chunk_controller","left") then return false end
  258.                 end
  259.             end
  260.             if peripheral.getType("right") ~= "environmentDetector" and not self:equipItem("advancedperipherals:environment_detector") then return false end
  261.             if (peripheral.getType("right") ~= "modem" or not peripheral.wrap("right").isWireless()) and not self:equipItem("computercraft:wireless_modem_advanced") then return false end
  262.             return true
  263.         end
  264.         function turt:moveToChunk(cX,cZ)
  265.             logAction("chunkMove",cX,cZ)
  266.             if not tonumber(cX) or not tonumber(cZ) then return false end
  267.             return self:moveToPos(cX*16,nil,cZ*16)
  268.         end
  269.         function turt:openRednet()
  270.             logAction("rednet open")
  271.             self:equipItem("computercraft:wireless_modem_advanced")
  272.             peripheral.find("modem",rednet.open)
  273.             local s = rednet.isOpen()
  274.             local _,r = pcall(function()
  275.                     local regions = fs.list("region")
  276.                     return regions[1] end)
  277.             if s then pcall(function() rednet.host("fern-scanner-turtle",r or ""..os.getComputerID()) end) end
  278.             return s
  279.         end
  280.         function turt:getBiome()
  281.             logAction("get biome")
  282.             self:equipItem("advancedperipherals:environment_detector")
  283.             local envDet = peripheral.find("environmentDetector")
  284.             if not envDet then error("No environment detector found") end
  285.             return envDet.getBiome()
  286.         end
  287.         function turt:getChunk()
  288.             logAction("calc chunk")
  289.             return {math.floor(self.x/16),math.floor(self.z/16)}
  290.         end
  291.         function turt:diagnostics()
  292.             logAction("diagnostics")
  293.             self:openRednet()
  294.             local pos = {gps.locate()} --gps locate pos
  295.             local ipos = {self.x,self.y,self.z} --What the turtle thinks its at
  296.             local fuel = turtle.getFuelLevel()
  297.             local items = {}
  298.             for i=1,16 do
  299.                 items[i] = turtle.getItemDetail(i)
  300.             end
  301.             return {pos=pos,fuel=fuel,items=items,ipos=ipos}
  302.         end
  303.         return turt
  304.     end
  305.    
  306.     TURTLE = Turtle()
  307.     if not TURTLE:checkNeededItems() then error("Lacking items to start") end
  308.     assert(TURTLE:openRednet())
  309.     HOST = assert(rednet.lookup("FERN-HOST"),"No host found")
  310.    
  311.     local ss_receive,ss_send
  312.    
  313.     ss_receive = function()
  314.         TURTLE:openRednet()
  315.         --@2m80_
  316.         local sender,message,protocol = rednet.receive() --temporary solution
  317.         if protocol == "ping" then
  318.             ss_send(s,TURTLE:diagnostics(),"pong")
  319.         elseif protocol == "update" then
  320.             error("Update")
  321.         end
  322.         logAction("ss_receive",sender,message,protocol)
  323.         return sender, message, protocol --Just like rednet?
  324.     end
  325.    
  326.     ss_send = function(target,message,protocol,response_protocol)
  327.         logAction("ss_send",target,message,protocol,response_protocol)
  328.         TURTLE:openRednet()
  329.         rednet.send(target,message,protocol) --temporary solution
  330.         --@2m80_
  331.         if response_protocol then
  332.             local s,m,p = ss_receive()
  333.             while s ~= target and p ~= response_protocol do
  334.                 s,m,p = ss_receive()
  335.                 if s == target and p == "error" then error(message) end
  336.             end
  337.             return s,m,p
  338.         end
  339.         return success --Should include?
  340.     end
  341.    
  342.     local function requireRegion()
  343.         while not fs.isDir("region") or #fs.list("region") <= 0 do
  344.             local _,message = ss_send(HOST,"","get_region","region_assignment")
  345.             if type(message) == "table" and #message == 2 and tonumber(message[1]) and tonumber(message[2]) then
  346.                 fern_data.readDat(string.format("region/%d_%d.dat",tonumber(message[1]),tonumber(message[2])),0,0)
  347.             end
  348.         end
  349.         local region = assert(fs.list("region")[1],"failed to get region")
  350.         local rX,rZ = region:match("(-?%d+)_(-?%d+)")
  351.         rX,rZ = assert(tonumber(rX)),assert(tonumber(rZ))
  352.         logAction("region requirement",rX,rZ,region)
  353.         return rX,rZ,region
  354.     end
  355.     REG_X,REG_Z,REGION = requireRegion()
  356.    
  357.     --Gets the chunk list of chunks needed to explore
  358.     local function getChunkList()
  359.         if not fs.exists("region/"..REGION) then error("No region file") end
  360.         local file = fs.open("region/"..REGION,"rb")
  361.         local chunkList = {}
  362.         --region file
  363.         for x=0,127 do
  364.             local row = {}
  365.             for z=0,127 do
  366.                 local char = file.read()
  367.                 if not char then error("invalid region file") end --If the file doesnt contain all 16384 chunks, error
  368.                 if char == 0 then table.insert(row,{REG_X + x,REG_Z+z}) --If chunk isnt filled out yet, add to list
  369.                 elseif char == 256 then --If variable char, continue eating bytes until you are at the next char
  370.                     repeat
  371.                         char = file.read()
  372.                     until char ~= 256
  373.                 end
  374.             end
  375.             local lb,ub,step = 1,#row,1
  376.             if x%2 == 0 then lb,ub,step = #row,1,-1 end --switch order so the turtle follows a snake path through a region
  377.             for i=lb,ub,step do
  378.                 table.insert(chunkList,row[i])
  379.             end
  380.         end
  381.         return chunkList
  382.     end
  383.     CHUNK_LIST = getChunkList()
  384.    
  385.     local function synchronize_data()
  386.         logAction("synchronize")
  387.         local data = fern_data.readDat("region/"..REGION)
  388.         local file = fs.open(fern_data.BIOME_METADATA_PATH,"r")
  389.         local metadata = {}
  390.         if file then
  391.             metadata = textutils.unserialiseJSON(file.readAll()) or {}
  392.             file.close()
  393.         end
  394.         local _,message = ss_send(HOST,{data=data,metadata=metadata},"synchronize","synchronize_response")
  395.         if type(message) == "table" and message.sync then
  396.             if type(message.data) == "string" and type(message.metadata) == table then
  397.                 local file = fs.open(fern_data.BIOME_METADATA_PATH,"w+")
  398.                 file.write(textutils.serialiseJSON(message.metadata))
  399.                 file.close()
  400.                 local file = fs.open("region/"..REGION,"w+")
  401.                 file.write(message.data)
  402.                 file.close()
  403.             end
  404.         end
  405.     end
  406.    
  407.     local function sendData()
  408.         local biome = TURTLE:getBiome()
  409.         logAction("data send")
  410.         local chunk = TURTLE:getChunk()
  411.         fern_data.writeDat("region/"..REGION,chunk[1],chunk[2],biome)
  412.         local _,message = ss_send(HOST,{chunk=chunk,biome=biome},"data","data_success")
  413.     end
  414.    
  415.     local function main()
  416.         synchronize_data()
  417.         while #CHUNK_LIST > 0 do
  418.             local chunk = table.remove(CHUNK_LIST)
  419.             parallel.waitForAny(function() TURTLE:moveToChunk(chunk[1],chunk[2]) end,function() while true do ss_receive() end end)
  420.             sendData()
  421.         end
  422.         synchronize_data()
  423.     end
  424.     main()
  425. end
  426.  
  427. local s,errMsg = pcall(wrapper)
  428. if not s then
  429.     logAction("ERROR",errMsg)
  430.     pcall(function()
  431.             local turtleStats = {}
  432.             for k,v in pairs(TURTLE) do
  433.                 if type(v) ~= "function" then
  434.                     table.insert(turtleStats,k .. tostring(v))
  435.                 end
  436.             end
  437.             logAction("stats",unpack(turtleStats))
  438.         end)
  439.     pcall(function() logAction("gps",gps.locate()) end)
  440.     pcall(function() logAction("diagnostics",TURTLE:diagnostics()) end)
  441.     pcall(function() TURTLE:openRednet() ss_send(rednet.CHANNEL_BROADCAST,errMsg,"scanner crash") end)
  442. end
Advertisement
Add Comment
Please, Sign In to add comment