dadragon84

turtleQuarry

Feb 18th, 2025 (edited)
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 99.33 KB | Source Code | 0 0
  1. --MrJohnDowe's Quarry Program--
  2.   VERSION = "3.6.4.5"
  3.  
  4. if fs.exists("turtleQuarry")then
  5.   shell.run("rename turtleQuarry startup")
  6. end
  7.  
  8. --[[
  9. Recent Changes:
  10.   Parameter Files! Create a file of parameters, and use -file to load it!
  11.     Works will with -forcePrompt
  12.   Quarry no longer goes to start at end of row!
  13.   Turtle can go left!
  14.   QuadCopters! Check Lyqyd's thread
  15. New Parameters:
  16.     -overfuel/fuelMultiplier [number]: This number is is what neededFuel is multiplied by when fuel is low.
  17.     -version: This will display the current version number and end the program
  18.     -file [fileName]: This will load a custom configuration file (basically a list of parameters). "##" starts comment lines. In the future "#" will start programs to run (but only through shell)
  19.     -preciseTotals [t/f]: If true, turtle will write exactly what it mined to the logs. It may also transmit it over rednet.
  20.     -forcePrompt [param]: This will add to a list of parameters to force prompt for. So if you say "-forcePrompt doRefuel" it will prompt you "Length","Width","Height","Invert","Do Refuel" etc.
  21. ]]
  22. --Defining things
  23. civilTable = nil; _G.civilTable = {}; setmetatable(civilTable, {__index = getfenv()}); setfenv(1,civilTable)
  24. originalDay = os.day() --Used in logging
  25. numResumed = 0 --Number of times turtle has been resumed
  26. -------Defaults for Arguments----------
  27. --Arguments assignable by text
  28. x,y,z = 3,3,3 --These are just in case tonumber fails
  29. inverted = false --False goes from top down, true goes from bottom up [Default false]
  30. rednetEnabled = true --Default rednet on or off  [Default false]
  31. --Arguments assignable by tArgs
  32. dropSide = "front" --Side it will eject to when full or done [Default "front"]
  33. careAboutResources = true --Will not stop mining once inventory full if false [Default true]
  34. doCheckFuel = true --Perform fuel check [Default true]
  35. doRefuel = false --Whenever it comes to start location will attempt to refuel from inventory [Default false]
  36. keepOpen = 1 --How many inventory slots it will attempt to keep open at all times [Default 1]
  37. fuelSafety = "moderate" --How much fuel it will ask for: safe, moderate, and loose [Default moderate]
  38. excessFuelAmount = math.huge --How much fuel the turtle will get maximum. Limited by turtle.getFuelLimit in recent CC [Default math.huge]
  39. fuelMultiplier = 1 --How much extra fuel turtle will ask for when it does need fuel [Default 1]
  40. saveFile = "Dowe_Quarry_Restore" --Where it saves restore data [Default "Dowe_Quarry_Restore"]
  41. autoResume = true --If true, turtle will auto-restart when loaded. [Default true]
  42. startupRename = "quarry.lua" --What the startup is temporarily renamed to [Default "oldStartup.quarry"]
  43. startupName = "startup.lua" --What the turtle auto-resumes with [Default "startup"]
  44. doBackup = true --If it will keep backups for session persistence [Default true]
  45. uniqueExtras = 8 --How many different items (besides cobble) the turtle expects. [Default 8]
  46. maxTries = 200 --How many times turtle will try to dig a block before it "counts" bedrock [Default 200]
  47. gpsEnabled = false -- If option is enabled, will attempt to find position via GPS api [Default false]
  48. gpsTimeout = 3 --The number of seconds the program will wait to get GPS coords. Not in arguments [Default 3]
  49. legacyRednet = false --Use this if playing 1.4.7
  50. logging = true --Whether or not the turtle will log mining runs. [Default ...still deciding]
  51. logFolder = "Quarry_Logs" --What folder the turtle will store logs in [Default "Quarry_Logs"]
  52. logExtension = ".log" --The extension of the file (e.g. ".txt") [Default ""]
  53. flatBedrock = false --If true, will go down to bedrock to set startDown [Default false]
  54. startDown = 0 --How many blocks to start down from the top of the mine [Default 0]
  55. preciseTotals = true --If true, will record exact totals and names for all materials [Default false]
  56. goLeftNotRight = false --Quarry to left, not right (parameter is "left") [Default false]
  57. oreQuarry = false --Enables ore quarry functionality [Default false]
  58. oreQuarryBlacklistName = "oreQuarryBlacklist.txt" --This is the file that will be parsed for item names [Default "oreQuarryBlacklist"]
  59. dumpCompareItems = true --If ore quarry, the turtle will dump items compared to (like cobblestone) [Default true]
  60. frontChest = false --If oreQuarry and chest checking, you can turn this on to make turtle check in front of itself for chests as well [Default false]
  61. lavaBuffer = 500 --If using a lava bucket, this is the buffer it will wait for before checking for lava [Default 500]
  62. inventoryMax = 16 --The max number of slots in the turtle inventory [Default 16] (Not assignable by parameter)
  63. quadEnabled = false --Whether or not to request a quadRotor when out of fuel [Default false]
  64. quadTimeout = 60 * 5 --How long the turtle will wait for a quadRotor [Default 5 minutes]
  65. --Standard number slots for fuel (you shouldn't care)
  66. fuelTable = { --Will add in this amount of fuel to requirement.
  67. safe = 1000,
  68. moderate = 200,
  69. loose = 0 } --Default 1000, 200, 0
  70. --Standard rednet channels
  71. channels = {
  72. send = os.getComputerID() + 1  ,
  73. receive = os.getComputerID() + 101 ,
  74. confirm = "Turtle Quarry Receiver",
  75. message = "Dowe's Quarry",
  76. fingerprint = "quarry"
  77. }
  78.  
  79. --AVERAGE USER: YOU DON'T CARE BELOW THIS POINT
  80.  
  81. local help_paragraph = [[
  82. Welcome!: Welcome to quarry help. Below are help entries for all parameters. Examples and tips are at the bottom.
  83. -default: This will force no prompts. If you use this and nothing else, only defaults will be used.
  84. -dim: [length] [width] [height] This sets the dimensions for the quarry
  85. -invert: [t/f] If true, quarry will be inverted (go up instead of down)
  86. -rednet: [t/f] If true and you have a wireless modem on the turtle, will attempt to make a rednet connection for sending important information to a screen
  87. -restore / -resume: If your quarry stopped in the middle of its run, use this to resume at the point where the turtle was. Not guarenteed to work properly. For more accurate location finding, check out the -GPS parameter
  88. -autoResume / autoRestore: Turtle will automatically resume if stopped. Replaces startup
  89. -oreQuarry: [t/f] If true, the turtle will use ore quarry mode. It will not mine the blocks that are placed in the turtle initially. So if you put in stone, it will ignore stone blocks and only mine ores.
  90. -oreQuarry: [t/f] If you are using a newer version of CC, you won't have to put in any compare blocks. (CC 1.64+)
  91. -blacklist: [file name] If using oreQuarry, this is the blacklist file it will read. Example --
  92.  minecraft:stone
  93.  minecraft:sand
  94.  ThermalExpansion:Sponge
  95.  ThermalFoundation:Storage
  96.  
  97.  Note: If you have bspkrsCore, look
  98.  for "UniqueNames.txt" in your config
  99. -file: [file name] Will load a file of parameters. One parameter per line. # is a comment line (See the forum thread for more detailed directions)
  100. -atChest: [force] This is for use with "-restore," this will tell the restarting turtle that it is at its home chest, so that if it had gotten lost, it now knows where it is.
  101. -doRefuel: [t/f] If true, the turtle will refuel itself with coal and planks it finds on its mining run
  102. -doCheckFuel: [t/f] If you for some reason don't want the program to check fuel usage, set to false. This is honestly a hold-over from when the refueling algorithm was awful...
  103. -overfuel: [number] When fuel is below required, fuel usage is multiplied by this. Large numbers permit more quarries without refueling
  104. -fuelMultiplier: [number] See overfuel
  105. -uniqueExtras: [number] The expected number of slots filled with low-stacking items like ore. Higher numbers request more fuel.
  106. -maxFuel: [number] How much the turtle will fuel to max (limited by turtle in most cases)
  107. -chest: [side] This specifies what side the chest at the end will be on. You can say "top", "bottom", "front", "left", or "right"
  108. -enderChest: [slot] This one is special. If you use "-enderChest true" then it will use an enderChest in the default slot. However, you can also do "-enderChest [slot]" then it will take the ender chest from whatever slot you tell it to. Like 7... or 14... or whatever.
  109. -fuelChest: [slot] See the above, but for a fueling chest. Reccommend use with -maxFuel and -doCheckFuel false
  110. -lava: [slot] If using an oreQuarry, will fill itself with lava it finds to maxFuel
  111. -lavaBuffer: [number] The amount of fuel below maxFuel the turtle will wait for before using lava again
  112. -GPS: [force] If you use "-GPS" and there is a GPS network, then the turtle will record its first two positions to precisly calculate its position if it has to restart. This will only take two GPS readings
  113. -quad: [t/f] This forces the use of GPS. Make sure you have a network set up. This will request to be refueled by a quadrotor from Lyqyd's mod if the turtle is out of fuel
  114. -quadTimeout: [number] The amount of time the turtle will wait for a quadRotor
  115. -sendChannel: [number] This is what channel your turtle will send rednet messages on
  116. -receiveChannel: [number] This is what channel your turtle will receive rednet messages on
  117. -legacyRednet: [t/f] Check true if using 1.4.7
  118. -startY: [current Y coord] Randomly encountering bedrock? This is the parameter for you! Just give it what y coordinate you are at right now. If it is not within bedrock range, it will never say it found bedrock
  119. -startupRename: [file name] What to rename any existing startup to.
  120. -startupName: [file name] What the turtle will save its startup file to.
  121. -extraDropItems: [force] If oreQuarry then this will prompt the user for extra items to drop, but not compare to (like cobblestone)
  122. -dumpCompareItems: [t/f] If oreQuarry and this is true, the turtle will dump off compare blocks instead of storing them in a chest
  123. -oldOreQuarry: [t/f] If you are using new CC versions, you can use this to use the old oreQuarry.
  124. -compareChest: [slot] If using oldOreQuarry, this will allow you to check for dungeon chests and suck from them.
  125. -frontChest: [t/f] If using oreQuarry/oldOreQuarry, this will check in front of itself for chests as well.
  126. -left: [t/f] If true, turtle will quarry to the left instead of the right
  127. -maxTries: [number] This is the number of times the turtle will try to dig before deciding its run into bedrock.
  128. -forcePrompt: [parameter] Whatever parameter you specify, it will always prompt you, like it does now for invert and dim.
  129. -logging: [t/f] If true, will record information about its mining run in a folder at the end of the mining run
  130. -preciseTotals: [t/f] If true (and turtle.inspect exists), it will log a detailed record of every block the turtle mines and send it over rednet
  131. -doBackup: [t/f] If false, will not back up important information and cannot restore, but will not make an annoying file (Actually I don't really know why anyone would use this...)
  132. -saveFile: [word] This is what the backup file will be called
  133. -logFolder: [word] The folder that quarry logs will be stored in
  134. -logExtension: [word] The extension given to each quarry log (e.g. ".txt" or ".notepad" or whatever)
  135. -keepOpen: [number] This is the number of the slots the turtle will make sure are open. It will check every time it mines
  136. -careAboutResources: [t/f] Who cares about the materials! If set to false, it will just keep mining when its inventory is full
  137. -startDown: [number] If you set this, the turtle will go down this many blocks from the start before starting its quarry
  138.   =
  139.   C _ |
  140.       |
  141.       |
  142.       |
  143.       |_ _ _ _ >
  144. -flatBedrock: [t/f] If true, turtle will find bedrock and "zero" itself so it ends on bedrock level
  145. -promptAll: This is the opposite of -Default, it prompts for everything
  146. -listParams: This will list out all your selected parameters and end quarry. Good for testing
  147. -manualPos: [xPos] [zPos] [yPos] [facing] This is for advanced use. If the server reset when the turtle was in the middle of a 100x100x100 quarry, fear not, you can now manually set the position of the turtle. yPos is always positive. The turtle's starting position is 0, 1, 1, 0. Facing is measured 0 - 3. 0 is forward, and it progresses clockwise. Example- "-manualPos 65 30 30 2"
  148. -version: Displays the current quarry version and stops the program
  149. -help: Thats what this is :D
  150. Examples: Everything below is examples and tips for use
  151. Important Note:
  152.  None of the above parameters are necessary. They all have default values, and the above are just if you want to change them.
  153. Examples [1]:
  154.  Want to just start a quarry from the interface, without going through menus? It's easy! Just use some parameters. Assume you called the program "quarry." To start a 10x6x3 quarry, you just type in "quarry -dim 10 6 3 -default".
  155.   You just told it to start a quarry with dimensions 10x6x3, and "-default" means it won't prompt you about invert or rednet. Wasn't that easy?
  156. Examples [2]:
  157.   Okay, so you've got the basics of this now, so if you want, you can type in really long strings of stuff to make the quarry do exactly what you want. Now, say you want a 40x20x9, but you want it to go down to diamond level, and you're on the surface (at y = 64). You also want it to send rednet messages to your computer so you can see how its doing.
  158. Examples [2] [cont.]:
  159.   Oh yeah! You also want it to use an ender chest in slot 12 and restart if the server crashes. Yeah, you can do that. You would type
  160.   "quarry -dim 40x20x9 -invert false -startDown 45 -rednet true -enderChest 12 -restore"
  161.   BAM. Now you can just let that turtle do it's thing
  162. Tips:
  163.  The order of the parameters doesn't matter. "quarry -invert false -rednet true" is the same as "quarry -rednet true -invert false"
  164.  
  165.   Capitalization doesn't matter. "quarry -iNVErt FALSe" does the same thing as "quarry -invert false"
  166. Tips [cont.]:
  167.  For [t/f] parameters, you can also use "yes" and "no" so "quarry -invert yes"
  168.  
  169.  For [t/f] parameters, it only cares about the first letter. So you can use "quarry -invert t" or "quarry -invert y"
  170. Tips [cont.]:
  171.  If you are playing with fuel turned off, the program will automatically change settings for you so you don't have to :D
  172.  
  173.   If you want, you can load this program onto a computer, and use "quarry -help" so you can have help with the parameters whenever you want.
  174. Internal Config:
  175.   At the top of this program is an internal configuration file. If there is some setup that you use all the time, you can just change the config value at the top and run "quarry -default" for a quick setup.
  176.  
  177.   You can also use this if there are settings that you don't like the default value of.
  178. ]]
  179. --NOTE: BIOS 114 MEANS YOU FORGOT A COLON
  180. --NOTE: THIS ALSO BREAKS IF YOU REMOVE "REDUNDANT" WHITESPACE
  181. --Parsing help for display
  182. --[[The way the help table works:
  183. All help indexes are numbered. There is a help[i].title that contains the title,
  184. and the other lines are in help[i][1] - help[i][#help[i] ]
  185. Different lines (e.g. other than first) start with a space.
  186. As of now, the words are not wrapped, fix that later]]
  187. local help = {}
  188. local i = 0
  189. local titlePattern = ".-%:" --Find the beginning of the line, then characters, then a ":"
  190. local textPattern = "%:.+" --Find a ":", then characters until the end of the line
  191. for a in help_paragraph:gmatch("\n?.-\n") do --Matches in between newlines
  192.  local current = string.sub(a,1,-2).."" --Concatenate Trick
  193.  if string.sub(current,1,1) ~= " " then
  194.    i = i + 1
  195.    help[i] = {}
  196.    help[i].title = string.sub(string.match(current, titlePattern),1,-2)..""
  197.    help[i][1] = string.sub(string.match(current,textPattern) or " ",3,-1)
  198.  elseif string.sub(current,1,1) == " " then
  199.    table.insert(help[i], string.sub(current,2, -1).."")
  200.  end
  201. end
  202.  
  203. local supportsRednet
  204. if peripheral.find then
  205.  supportsRednet = peripheral.find("modem") or false
  206. else
  207.  supportsRednet = (peripheral.getType("right") == "modem") or false
  208. end
  209.  
  210. --Pre-defining variables that need to be saved
  211.      xPos,yPos,zPos,facing,percent,mined,moved,relxPos, rowCheck, connected, isInPath, layersDone, attacked, startY, chestFull, gotoDest, atChest, fuelLevel, numDropOffs, allowedItems, compareSlots, dumpSlots, selectedSlot, extraDropItems, oldOreQuarry, specialSlots, relzPos, eventInsertionPoint
  212.    = 0,   1,   1,   0,     0,      0,    0,    1,       true   ,  false,     true,     1,          0,        0,      false,     "",       false,   0,         0,           {},             {},           {},      1,            false,          false,        {explicit = {}},    0, 1
  213.  
  214. --These are slot options that need to exist as variables for parameters to work.
  215.  enderChest, fuelChest, lavaBucket, compareChest
  216. = false,      false,     false,      false
  217.  
  218. local chestID, lavaID, lavaMeta = "minecraft:chest", "minecraft:flowing_lava", 0
  219.  
  220. local statusString
  221.  
  222. --Initializing various inventory management tables
  223. for i=1, inventoryMax do
  224.  allowedItems[i] = 0 --Number of items allowed in slot when dropping items
  225.  dumpSlots[i] = false --Does this slot contain junk items?
  226. end --compareSlots is a table of the compare slots, not all slots with a condition
  227. totals = {cobble = 0, fuel = 0, other = 0} -- Total for display (cannot go inside function), this goes up here because many functions use it
  228.  
  229. local function newSpecialSlot(index, value, explicit) --If isn't explicit, it will move whatever is already in the slot around to make room.
  230.   value = tonumber(value) or 0 --We only want numerical indexes
  231.   local flag = false --Used in slot moving, moved slot is returned for ease of use
  232.   local function check(num) return num >= 1 and num <= inventoryMax end
  233.   if not check(value) then error("from newSpecialSlot: number "..value.." out of range",2) end
  234.   local function getFirstFree(start)
  235.     for i=1, math.max(inventoryMax-value,value-1) do
  236.       for a=-1,1,2 do
  237.         local num = value + (a*i)
  238.         if check(num) and not specialSlots[num] then return num end
  239.       end
  240.     end
  241.     return false
  242.   end
  243.   if specialSlots[value] and specialSlots[value] ~= index then --If we aren't trying to override the same slot :P
  244.     if not explicit then
  245.       value = getFirstFree(value) or error("from newSpecialSlots: all slots full, could not add")
  246.     elseif explicit and not specialSlots.explicit[value] then --Moving around other slots
  247.       flag = getFirstFree(value)
  248.       if not flag then error("from newSpecialSlots: could not add explicit in slot: "..index.." "..value.." Taken by "..specialSlots[value],2) end
  249.       specialSlots[flag] = specialSlots[value]
  250.       specialSlots[specialSlots[value]] = flag --These will get set to the new thing later
  251.     else
  252.       error('You cannot put a "'..index..'" in the same slot as a "'..specialSlots.explicit[value]..'" (Slot '..value..")",0) --Show the user an understandable error :)
  253.     end
  254.   end
  255.   specialSlots[index] = value
  256.   specialSlots[value] = index
  257.   if explicit then
  258.     specialSlots.explicit[value] = index
  259.   end
  260.   return value, flag
  261. end
  262.  
  263. function resetDumpSlots()
  264.     for i=1, inventoryMax do
  265.       if oldOreQuarry then
  266.         if turtle.getItemCount(i) > 0 and i~= specialSlots.enderChest then
  267.           dumpSlots[i] = true
  268.         else
  269.           dumpSlots[i] = false
  270.         end
  271.       else
  272.         dumpSlots[i] = false
  273.       end
  274.     end
  275.     if not oldOreQuarry and specialSlots.enderChest == 1 then
  276.       dumpSlots[2] = true
  277.     elseif not oldOreQuarry then
  278.       dumpSlots[1] = true
  279.     end
  280. end
  281.  
  282. local function copyTable(tab) if type(tab) ~= "table" then error("copyTable received "..type(tab)..", expected table",2) end local toRet = {}; for a, b in pairs(tab) do toRet[a] = b end; return toRet end --This goes up here because it is a basic utility
  283.  
  284. --NOTE: rowCheck is a bit. true = "right", false = "left"
  285.  
  286. local foundBedrock = false
  287.  
  288. local checkFuel, checkFuelLimit
  289. if turtle then --Function inits
  290.   checkFuel = turtle.getFuelLevel
  291.   if turtle.getFuelLevel() == "unlimited" then --Fuel is disabled --Unlimited screws up my calculations
  292.     checkFuel = function() return math.huge end --Infinite Fuel
  293.   end --There is no "else" because it will already return the regular getFuel
  294.   if turtle.getFuelLimit then
  295.     checkFuelLimit = function() return math.min(turtle.getFuelLimit(), excessFuelAmount) end --Return the limiting one
  296.     if turtle.getFuelLimit() == "unlimited" then
  297.       checkFuelLimit = function() return math.huge end
  298.     end
  299.   else
  300.     checkFuelLimit = function() return excessFuelAmount end --If the function doesn't exist
  301.   end
  302.  
  303.  
  304.   turtle.select(1) --To ensure this is correct
  305. end
  306.  
  307.  
  308. function select(slot)
  309.   if slot ~= selectedSlot and slot > 0 and slot <= inventoryMax then
  310.     selectedSlot = slot
  311.     return turtle.select(slot), selectedSlot
  312.   end
  313. end
  314.  
  315.  
  316.  -----------------------------------------------------------------
  317. --Input Phase
  318. local function screen(xPos,yPos)
  319. xPos, yPos = xPos or 1, yPos or 1
  320. term.setCursorPos(xPos,yPos); term.clear(); end
  321. local function screenLine(xPos,yPos)
  322. term.setCursorPos(xPos,yPos); term.clearLine(); end
  323.  
  324. screen(1,1)
  325. print("----- Welcome to Quarry! -----")
  326. print("")
  327.  
  328. local sides = {top = "top", right = "right", left = "left", bottom = "bottom", front = "front"} --Used to whitelist sides
  329. local tArgs --Will be set in initializeArgs
  330. local originalArgs = {...}
  331. local changedT, tArgsWithUpper, forcePrompts = {}, {}, {}
  332. changedT.new = function(key, value, name) table.insert(changedT,{key, value, name}); if name then changedT[name] = #changedT end end --Numeric list of lists
  333. changedT.remove = function(num) changedT[num or #changedT].hidden = true end --Note actually remove, just hide :)
  334. local function capitalize(text) return (string.upper(string.sub(text,1,1))..string.sub(text,2,-1)) end
  335. local function initializeArgs()
  336.   tArgs = copyTable(originalArgs) --"Reset" tArgs
  337.   for i=1, #tArgs do --My signature key-value pair system, now with upper
  338.     tArgsWithUpper[i] = tArgs[i]
  339.     tArgsWithUpper[tArgsWithUpper[i]] = i
  340.     tArgs[i] = tArgs[i]:lower()
  341.     tArgs[tArgs[i]] = i
  342.     if tArgs[i] == "-forceprompt" and i ~= #tArgs then --If the prompt exists then add it to the list of prompts
  343.       forcePrompts[tArgs[i+1]:lower()] = true
  344.     end
  345.   end
  346. end
  347. initializeArgs()
  348.  
  349. local restoreFound, restoreFoundSwitch = false --Initializing so they are in scope
  350. function parseParam(name, displayText, formatString, forcePrompt, trigger, variableOverride, variableExists) --Beware confusion, all ye who enter here
  351.   --[[ Guide to Variables
  352.     originalValue: what the variable was before the function
  353.     givenValue: This is the value after the parameter. So -invert fAlSe, givenValue is "fAlSe"
  354.   ]]
  355.   if variableExists ~= false then variableExists = true end --Almost all params should have the variable exist. Some don't exist unless invoked
  356.   if trigger == nil then trigger = true end --Defaults to being able to run
  357.   if not trigger then return end --This is what the trigger is for. Will not run if trigger not there
  358.   if restoreFoundSwitch or tArgs["-default"] then forcePrompt = false end --Don't want to prompt if these. Default is no variable because resuming
  359.   if not restoreFoundSwitch and (tArgs["-promptall"] or forcePrompts[name:lower()]) then forcePrompt = true end --Won't prompt if resuming, can prompt all or checks list of prompts
  360.   local toGetText = name:lower() --Because all params are now lowered
  361.   local formatType = formatString:match("^%a+"):lower() or error("Format String Unknown: "..formatString) --Type of format string
  362.   local args = formatString:match(" (.+)") or "".."" --Everything in formatString after the type
  363.   local variable = variableOverride or name --Goes first to the override for name
  364.   local func = loadstring("return "..variable) --Note to future self: If you want to remove loadstring, this breaks on tables. You will have to remove tables or figure something else out
  365.   setfenv(func,getfenv(1))
  366.   local originalValue = assert(func)() --This is the default value, for checking to add to changed table
  367.   if originalValue == nil and variableExists then error("From addParam, \""..variable.."\" returned nil",2) end --I may have gotten a wrong variable name
  368.   local givenValue, toRet, values --Initializing for use
  369.   if tArgs["-"..toGetText] then
  370.     givenValue = tArgsWithUpper[tArgs["-"..toGetText]+1] --This is the value after the desired parameter
  371.   elseif forcePrompt then
  372.     write(displayText.."? ")
  373.     givenValue = io.read()
  374.   end
  375.   if formatType == "force" then --This is the one exception. Should return true if givenValue is nothing
  376.     toRet = (tArgs["-"..toGetText] and true) or false --Will return true if param exists, otherwise false
  377.   end
  378.   if not (givenValue or toRet) or (type(givenValue) == "string" and #givenValue == 0) then return end --Don't do anything if you aren't given anything. Leave it as default, except for "force". Also don't want empty strings
  379.   if formatType == "boolean" then --All the format strings will be basically be put through a switch statement
  380.     toRet = givenValue:sub(1,1):lower() ~= "n" and givenValue:sub(1,1):lower() ~= "f" --Accepts anything but false or no
  381.   elseif formatType == "string" then
  382.     toRet = givenValue:match("^[%w%./]+") --Basically anything not a space or control character etc
  383.   elseif formatType == "number" or formatType == "float" then
  384.     toRet = tonumber(givenValue) --Note this is a local, not the above so we don't change anything
  385.     if not toRet then return end --We need a number... Otherwise compare errors
  386.     if formatType == "number" then toRet = math.floor(toRet) end --Get proper integers
  387.     local startNum, endNum = formatString:match("(%d+)%-(%d+)") --Gets range of numbers
  388.     startNum, endNum = tonumber(startNum), tonumber(endNum)
  389.     if not ((toRet >= startNum) and (toRet <= endNum)) then return end --Can't use these
  390.   elseif formatType == "side" then
  391.     local exclusionTab = {} --Ignore the wizardry here. Just getting arguments without format string
  392.     for a in args:gmatch("%S+") do exclusionTab[a] = true end --This makes a list of the sides to not include
  393.     if not exclusionTab[givenValue] then toRet = sides[givenValue] end --If side is not excluded
  394.   elseif formatType == "list" then
  395.     toRet = {}
  396.     for a in args:gmatch("[^,]") do
  397.       table.insert(toRet,a)
  398.     end
  399.   elseif formatType == "slot" then
  400.     if givenValue:sub(1,1):lower() == "n" or givenValue:sub(1,1):lower() == "f" then --Copied from boolean
  401.       toRet = false
  402.     else
  403.       local userNumber, correction = givenValue:match("^%d+$") --This makes sure the value is a number | Locally initialize correction
  404.       toRet, correction = newSpecialSlot(variable, tonumber(userNumber or args), userNumber) --If givenValue was "true", it won't be explicit and will use default number
  405.       if correction then changedT[changedT[specialSlots[correction]]][2] = tostring(correction) end --This changes the value field of the changedT index taken from the named pointer (which is the value in specialSlots under correction)
  406.     end
  407.   elseif formatType == "force" then --Do nothing, everything is already done
  408.   else error("Improper formatType",2)
  409.   end
  410.   if toRet == nil then return end --Don't want to set variables to nil... That's bad
  411.   tempParam = toRet --This is what loadstring will see :D
  412.   local func = loadstring(variable.." = tempParam")
  413.   setfenv(func, getfenv(1)) --Note to future self: If you want to remove loadstring, this breaks on tables. You will have to remove tables or figure something else out
  414.   func()
  415.   tempParam = nil --Cleanup of global
  416.   if toRet ~= originalValue and displayText ~= "" then
  417.     changedT.new(displayText, tostring(toRet), variable)
  418.   end
  419.   return toRet
  420. end
  421.  
  422. local paramLookup = {}
  423. local function addParam(...)
  424.   local args = {...}
  425.   if not paramLookup[args[1]] then
  426.     local toRet = copyTable(args)
  427.     for i=2, table.maxn(toRet) do --Have to do this because table.remove breaks on nil
  428.       toRet[i-1] = toRet[i]
  429.     end
  430.     table.remove(toRet)
  431.     paramLookup[args[1]] = toRet
  432.   end
  433.   return parseParam(unpack(args, 1, table.maxn(args)))
  434. end
  435.  
  436. local function paramAlias(original, alias)
  437.   local a = paramLookup[original]
  438.   if a then
  439.     if a[5] == nil then a[5] = original end --This is variableOverride because the originals won't put a variable override
  440.     return parseParam(alias, unpack(a, 1, table.maxn(a)))
  441.   else
  442.     error("In paramAlias: '"..original.."' did not exist",2)
  443.   end
  444. end
  445.  
  446. --Check if it is a turtle
  447. if not(turtle or tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"]) then --If all of these are false then
  448.   print("This is not a turtle, you might be looking for the \"Companion Rednet Program\" \nCheck My forum thread for that")
  449.   print("Press 'q' to quit, or any other key to start help ")
  450.   if ({os.pullEvent("char")})[2] ~= "q" then tArgs.help = true else error("",0) end
  451. end
  452.  
  453. if tArgs["help"] or tArgs["-help"] or tArgs["-?"] or tArgs["?"] then
  454.   print("You have selected help, press any key to continue"); print("Use arrow keys to navigate, q to quit"); os.pullEvent("key")
  455.   local pos = 1
  456.   local key = 0
  457.   while pos <= #help and key ~= keys.q do
  458.     if pos < 1 then pos = 1 end
  459.     screen(1,1)
  460.     print(help[pos].title)
  461.     for a=1, #help[pos] do print(help[pos][a]) end
  462.     repeat
  463.       _, key = os.pullEvent("key")
  464.     until key == 200 or key == 208 or key == keys.q
  465.     if key == 200 then pos = pos - 1 end
  466.     if key == 208 then pos = pos + 1 end
  467.   end
  468.   error("",0)
  469. end
  470.  
  471. if tArgs["-version"] or tArgs["version"] then
  472.   print("QUARRY VERSION: ",VERSION)
  473.   error("",0) --Exit not so gracefully
  474. end
  475.  
  476. --Loading custom parameter lists
  477. local function split(str, sep)
  478.   assert(#sep == 1, "Split seperator too long. Got '"..sep.."'")
  479.   if not str:match(sep) then return {str} end --So everything else isn't pointless
  480.   local toRet = {}
  481.   toRet[1] = str:match("^([^"..sep.."]-)"..sep)
  482.   for i in str:gmatch(sep.."([^"..sep.."]*)") do --Matches not seperator chars
  483.     toRet[#toRet+1] = i
  484.   end
  485.   return toRet
  486. end
  487.  
  488. if addParam("file","Custom Parameters","string", false, nil, "parameterFile", false) and parameterFile then --This will not load when resuming because there is no "file" parameter when resuming.
  489.   if not fs.exists(parameterFile) then
  490.     print("WARNING: '"..parameterFile.."' DOES NOT EXIST. FILE NOT LOADED")
  491.     sleep(3)
  492.     changedT.remove()
  493.   else
  494.     local file = fs.open(parameterFile, "r")
  495.     local text = file.readAll()
  496.     file.close()
  497.     text = text.."\n" --So that all replacements work properly
  498.     text = text:gsub("#[^\n]-\n","") --Replace program codes/comment lines+
  499.     local commands = {} --Contains all the parameters
  500.     local append = table.insert
  501.     for _, a in pairs(split(text,"\n")) do
  502.       local words = split(a," ")
  503.       if not a:match("-") then --This means only one command per line
  504.         append(originalArgs,"-"..words[1])
  505.         for i=2, #words do
  506.           append(originalArgs, words[i])
  507.         end
  508.       else --Otherwise the dashes are already ordered where we want!
  509.         for i=1, #words do
  510.           append(originalArgs, words[i])
  511.         end
  512.       end
  513.     end
  514.     initializeArgs() --Manipulate the args again, because we modified them
  515.     print("Finished loading file: ",tArgs[tArgs["-file"]+1])
  516.     sleep(0.5) --Give em a sec
  517.   end
  518. end
  519.  
  520.  
  521.  
  522. --Saving
  523. addParam("doBackup", "Backup Save File", "boolean")
  524. addParam("saveFile", "Save File Name", "string")
  525.  
  526. restoreFound = fs.exists(saveFile)
  527. restoreFoundSwitch = (tArgs["-restore"] or tArgs["-resume"] or tArgs["-atchest"]) and restoreFound and doBackup
  528. if restoreFoundSwitch then
  529.   local file = fs.open(saveFile,"r")
  530.   local test = file.readAll() ~= ""
  531.   file.close()
  532.   if test then
  533.     local temp = shell and copyTable(shell) --For whatever reason, the shell table doesn't survive resuming. shell and ... so that copyTable doesn't error
  534.     os.run(getfenv(1),saveFile) --This is where the actual magic happens
  535.     shell = temp
  536.     numResumed = numResumed + 1
  537.     if checkFuel() ~= math.huge then --If turtle uses fuel
  538.       if fuelLevel - checkFuel() == 1 then
  539.         if facing == 0 then xPos = xPos + 1
  540.         elseif facing == 2 then xPos = xPos - 1
  541.         elseif facing == 1 then zPos = zPos + 1
  542.         elseif facing == 3 then zPos = zPos - 1 end
  543.       elseif fuelLevel - checkFuel() ~= 0 then
  544.         print("Very Strange Fuel in Restore Section...")
  545.         print("Current: ",checkFuel())
  546.         print("Saved: ",fuelLevel)
  547.         print("Difference: ",fuelLevel - checkFuel())
  548.         os.pullEvent("char")
  549.       end
  550.      end
  551.     if gpsEnabled then --If it had saved gps coordinates
  552.       print("Found GPS Start Coordinates")
  553.       local currLoc = {gps.locate(gpsTimeout)} or {}
  554.       local backupPos = {xPos, yPos, zPos} --This is for comparing to later
  555.       if #currLoc > 0 and #gpsStartPos > 0 and #gpsSecondPos > 0 then --Cover all the different positions I'm using
  556.         print("GPS Position Successfully Read")
  557.         if currLoc[1] == gpsStartPos[1] and currLoc[3] == gpsStartPos[3] then --X coord, y coord, z coord in that order
  558.           xPos, yPos, zPos = 0,1,1
  559.           if facing ~= 0 then turnTo(0) end
  560.           print("Is at start")
  561.         else
  562.           if inverted then --yPos setting
  563.           ------------------------------------------------FIX THIS
  564.           end
  565.           local a, b = copyTable(gpsStartPos), copyTable(gpsSecondPos) --For convenience
  566.           local flag = true --So we can account for left quarry
  567.           if b[3] - a[3] == -1 then--If went north (-Z)
  568.             a[1] = a[1] - 1 --Shift x one to west to create a "zero"
  569.             xPos, zPos = -currLoc[3] + a[3], currLoc[1] + -a[1]
  570.           elseif b[1] - a[1] == 1 then--If went east (+X)
  571.             a[3] = a[3] - 1 --Shift z up one to north to create a "zero"
  572.             xPos, zPos = currLoc[1] + -a[1], currLoc[3] + -a[3]
  573.           elseif b[3] - a[3] == 1 then--If went south (+Z)
  574.             a[1] = a[1] + 1 --Shift x one to east to create a "zero"
  575.             xPos, zPos = currLoc[3] + a[3], -currLoc[1] + a[3]
  576.           elseif b[1] - a[1] == -1 then--If went west (-X)
  577.             a[3] = a[3] + 1 --Shift z down one to south to create a "zero"
  578.             xPos, zPos = -currLoc[1] + a[1], -currLoc[3] + a[3]
  579.           else
  580.             flag = false
  581.             print("Improper Coordinates")
  582.             print("GPS Locate Failed, Using Standard Methods")        ----Maybe clean this up a bit to use flags instead.
  583.           end
  584.           if flag and goLeftNotRight then --This accounts for left quarry (barred to left only because there might be errors in a regular, causing neg/0
  585.             zPos = math.abs(zPos-1) + 1
  586.           end
  587.         end
  588.         print("X Pos: ",xPos)
  589.         print("Y Pos: ",yPos)
  590.         print("Z Pos: ",zPos)
  591.         print("Facing: ",facing)
  592.         for i=1, 3, 2 do --We want 1 and 3, but 2 could be coming back to start.
  593.           if backupPos[i] ~= currLoc[i] then
  594.             events = {} --We want to remove event queue if not in proper place, so won't turn at end of row or things.
  595.           end
  596.         end
  597.       else
  598.         print("GPS Locate Failed, Using Standard Methods")
  599.       end
  600.     print("Restore File read successfully. Starting in 3"); sleep(3)
  601.     end
  602.   else
  603.     fs.delete(saveFile)
  604.     print("Restore file was empty, sorry, aborting")
  605.     error("",0)
  606.   end
  607. else --If turtle is just starting
  608.   events = {} --This is the event queue :D
  609.   originalFuel = checkFuel() --For use in logging. To see how much fuel is REALLY used
  610. end
  611.  
  612. --Dimensions
  613. if tArgs["-dim"] then
  614.   local a,b,c = x,y,z
  615.   local num = tArgs["-dim"]
  616.   x = tonumber(tArgs[num + 1]) or x; z = tonumber(tArgs[num + 2]) or z; y = tonumber(tArgs[num + 3]) or y
  617.   if a ~= x then changedT.new("Length", x) end
  618.   if c ~= z then changedT.new("Width", z) end
  619.   if b ~= y then changedT.new("Height", y) end
  620. elseif not (tArgs["-default"] or restoreFoundSwitch) then
  621.   print("What dimensions?")
  622.   print("")
  623.   --This will protect from negatives, letters, and decimals
  624.   term.write("Length? ")
  625.   x = math.floor(math.abs(tonumber(io.read()) or x))
  626.   term.write("Width? ")
  627.   z = math.floor(math.abs(tonumber(io.read()) or z))
  628.   term.write("Height? ")
  629.   y = math.floor(math.abs(tonumber(io.read()) or y))
  630.   changedT.new("Length",x); changedT.new("Width",z); changedT.new("Height",y)
  631. end
  632. --Params: parameter/variable name, display name, type, force prompt, boolean condition, variable name override
  633. --Invert
  634. addParam("flatBedrock","Go to bedrock", "boolean") --Not done before GPS because GPS only runs on restart
  635. addParam("invert", "Inverted","boolean", true, not flatBedrock, "inverted") --Not flat bedrock, because invert will be set to false
  636. addParam("startDown","Start Down","number 1-256", nil, not flatBedrock)
  637. addParam("left","Left Quarry","boolean", nil, nil, "goLeftNotRight")
  638. --Inventory
  639. addParam("chest", "Chest Drop Side", "side front", nil, nil, "dropSide")
  640. addParam("enderChest","Ender Chest Slot","slot 16") --Note: All slots can be 16 and they will auto-assign, but I feel it is less confusing if they are always the same
  641. addParam("fuelChest","Fuel Chest Slot","slot 15")
  642. --Rednet
  643. addParam("rednet", "Rednet Enabled","boolean",true, supportsRednet, "rednetEnabled")
  644. addParam("sendChannel", "Rednet Send Channel", "number 1-65535", false, supportsRednet, "channels.send")
  645. addParam("receiveChannel","Rednet Receive Channel", "number 1-65535", false, supportsRednet, "channels.receive")
  646. addParam("fingerprint","Sending Fingerprint", "string", false, supportsRednet, "channels.fingerprint")
  647. addParam("legacyRednet","Legacy Rednet","boolean", false, supportsRednet)
  648. --Quad Rotor --Must be before GPS
  649. if addParam("quad", "Quad Rotor Enabled","boolean",nil, rednetEnabled, "quadEnabled") then --This returns true if param found :3
  650.   gpsEnabled = true
  651. end
  652. addParam("quadTimeout","Quad Rotor Timeout","number 1-1000000", nil, quadEnabled) --The amount of time to wait for a quadRotor
  653. --GPS
  654. addParam("gps", "GPS Location Services", "force", nil, (not restoreFoundSwitch) and supportsRednet and not quadEnabled, "gpsEnabled" ) --Has these triggers so that does not record position if restarted.
  655. if gpsEnabled and not restoreFoundSwitch then
  656.   gpsStartPos = {gps.locate(gpsTimeout)} --Stores position in array
  657.   gpsEnabled = #gpsStartPos > 0 --Checks if location received properly. If not, position is not saved
  658.   if quadEnabled and not gpsEnabled then
  659.     error("You have no GPS network. You may not use Quad Rotors",0)
  660.   end
  661. end
  662. --Fuel
  663. addParam("uniqueExtras","Unique Items", "number 0-15")
  664. addParam("doRefuel", "Refuel from Inventory","boolean", nil, checkFuel() ~= math.huge) --math.huge due to my changes
  665. addParam("doCheckFuel", "Check Fuel", "boolean", doCheckFuel and fuelChest, checkFuel() ~= math.huge) --Will prompt if doCheckFuel and fuelChest are on. Probably don't want
  666. excessFuelAmount = excessFuelAmount or math.huge --Math.huge apparently doesn't save properly (Without saving, this is the config, on save it is actually set to nil if math.huge)
  667. addParam("maxFuel", "Max Fuel", "number 1-999999999", maxFuel == checkFuelLimit() and fuelChest, checkFuel() ~= math.huge, "excessFuelAmount") --Will prompt if fuel chest and the limit isn't changed
  668. addParam("fuelMultiplier", "Fuel Multiplier", "float 1-9001", nil, checkFuel() ~= math.huge)
  669. paramAlias("fuelMultiplier","fuelRequestMultiplier")
  670. paramAlias("fuelMultiplier","overFuel")
  671. --Logging
  672. addParam("logging", "Logging", "boolean")
  673. addParam("logFolder", "Log Folder", "string")
  674. addParam("logExtension","Log Extension", "string")
  675. --Misc
  676. addParam("startY", "Start Y","number 1-256")
  677. addParam("maxTries","Tries Before Bedrock", "number 1-9001")
  678. --Inventory
  679. addParam("keepOpen", "Slots to Keep Open", "number 1-15")
  680. addParam("careAboutResources", "Care About Resources","boolean")
  681. addParam("preciseTotals","Precise Totals","boolean", rednetEnabled and turtle.inspect, turtle.getItemDetail ~= nil)
  682. if preciseTotals and not restoreFoundSwitch then
  683.   exactTotals = {} --Don't want to initialize if we aren't using this
  684. end
  685. --Auto Startup
  686. addParam("autoResume", "Auto Resume", "boolean", nil, doBackup)
  687. paramAlias("autoResume","autoRestart")
  688. addParam("startupRename", "Startup Rename","string", nil, autoResume)
  689. addParam("startupName", "Startup File", "string", nil, autoResume)
  690. --Ore Quarry
  691. addParam("oreQuarry", "Ore Quarry", "boolean" )
  692. if oreQuarry and not turtle.inspect then
  693.   oldOreQuarry = true
  694.   oreQuarry = false
  695. end
  696. addParam("lavaBucket","Lava Bucket Slot", "slot 14", nil, oreQuarry)
  697. paramAlias("lavaBucket","lava")
  698. paramAlias("lavaBucket","lavaRefuel")
  699. addParam("lavaBuffer","Lava Buffer","number 1-19999", nil, lavaBucket)
  700. --Old Ore
  701. addParam("oldOreQuarry", "Old Ore Quarry", "boolean")
  702. addParam("dumpCompareItems", "Dump Compare Items", "boolean", nil, oldOreQuarry) --Do not dump compare items if not oreQuarry
  703. addParam("extraDropItems", "", "force", nil, oldOreQuarry) --Prompt for extra dropItems
  704. paramAlias("extraDropItems","extraDumpItems") --changed to Dump
  705. addParam("compareChest","Compare Chest Slot","slot 13", nil, oldOreQuarry)
  706. addParam("frontChest","Front Chest Check","boolean", nil, compareChest or turtle.insepect) --Does not need oreQuarry, but is similar (does need inspect if not compareChest)
  707. --New Ore
  708. addParam("blacklist","Ore Blacklist", "string", nil, oreQuarry, "oreQuarryBlacklistName")
  709. paramAlias("blacklist","blacklistFile")
  710. --Mod Related
  711.  
  712. --Extra
  713. if tArgs["-testparams"] then
  714.   screen()
  715.   print("KEY: VALUE (VARIABLE)")
  716.   for key, val in ipairs(changedT) do
  717.     if not val.hidden then
  718.       print(val[1],": ",val[2],"  (",val[3] or "",")")
  719.     end
  720.   end
  721.   error("Done",0)
  722. end
  723.  
  724.  
  725. --for flatBedrock
  726. if flatBedrock then
  727.   inverted = false
  728. end
  729.  
  730. --Auto Startup functions
  731. local function doAutoResumeStuff()
  732.   if fs.exists(startupName) then
  733.     if fs.exists(startupRename) then fs.delete(startupRename) end
  734.     fs.move(startupName, startupRename)
  735.   end
  736.   local file = fs.open(startupName,"w") --Startup File
  737.   file.writeLine( --The below is on the left because spacing
  738. [[
  739. --This is an auto-generated startup
  740. --Made by MrJohnDowe's Variable Size Quarry
  741. print("Now Resuming Quarry")
  742. print("Press any key to quit. You have 5 seconds.")
  743. function deleteStuff()
  744.   fs.delete("]]..startupName..[[")
  745.   if fs.exists("]]..startupRename..[[") then
  746.     fs.move("]]..startupRename.."\",\""..startupName..[[")
  747.  end
  748. end
  749. local event
  750. if fs.exists("]]..saveFile..[[") then
  751.  for i=5,1,-1 do
  752.    print(i)
  753.    os.startTimer(1)
  754.    event = os.pullEvent()
  755.    if event == "key" then break end
  756.  end
  757.  if event == "timer" then
  758.    os.run({},"]]..shell.getRunningProgram()..[[","-resume")
  759.  else
  760.  
  761.    deleteStuff()
  762.  end
  763. else
  764.  print("Never mind, no save file found")
  765.  deleteStuff()
  766. end
  767.  ]])
  768.  file.close()
  769. end
  770. if autoResume and not restoreFoundSwitch then --Don't do for restore because would overwrite renamed thing. Can't edit mid-run because no shell in restarted
  771.  doAutoResumeStuff()
  772. end
  773. --oreQuarry blacklist
  774. local blacklist = { "minecraft:air",  "minecraft:bedrock", "minecraft:cobblestone", "minecraft:dirt", "minecraft:ice", "minecraft:ladder", "minecraft:netherrack", "minecraft:sand", "minecraft:sandstone",
  775.  "minecraft:snow", "minecraft:snow_layer", "minecraft:stone", "minecraft:gravel", "minecraft:grass", "minecraft:torch" }
  776. for a,b in pairs(copyTable(blacklist)) do
  777.  blacklist[b], blacklist[a] = true, nil --Switch
  778. end
  779. if fs.exists(oreQuarryBlacklistName) then --Loading user-defined blacklist
  780.  local file = fs.open(oreQuarryBlacklistName, "r")
  781.  blacklist = {}
  782.  for a in file:readAll():gmatch("[^,\n]+") do
  783.    blacklist[a:match("[%w_.]+:[%w_.]+")] = true --Grab only the actual characters, not whitespaces
  784.  end
  785.  file:close()
  786. end
  787.  
  788. --Manual Position
  789. if tArgs["-manualpos"] then --Gives current coordinates in xPos,zPos,yPos, facing
  790.  local a = tArgs["-manualpos"]
  791.  xPos, zPos, yPos, facing = tonumber(tArgs[a+1]) or xPos, tonumber(tArgs[a+2]) or zPos, tonumber(tArgs[a+3]) or yPos, tonumber(tArgs[a+4]) or facing
  792.  changedT.new("xPos",xPos); changedT.new("zPos",zPos); changedT.new("yPos",yPos); changedT.new("facing",facing)
  793.  restoreFoundSwitch = true --So it doesn't do beginning of quarry behavior
  794.  for i=0,4 do tArgs[a+i] = "" end --Get rid of this argument from future restores
  795. end
  796. if addParam("atChest", "Is at Chest", "force") then --This sets position to 0,1,1, facing forward, and queues the turtle to go back to proper row.
  797.  local neededLayer = math.floor((yPos+1)/3)*3-1 --Make it a proper layer, +- because mining rows are 2, 5, etc.
  798.  if neededLayer > 2 and neededLayer%3 ~= 2 then --If turtle was not on a proper mining layer
  799.    print("Last known pos was not in proper layer, restarting quarry")
  800.    sleep(4)
  801.    neededLayer = 2
  802.  end
  803.  xPos, zPos, yPos, facing, rowCheck, layersDone = 0,1,1, 0, true, math.ceil(neededLayer/3)
  804.  doAutoResumeStuff() --This was probably deleted when they hit a key to launch with -atChest
  805.  events = {{"goto",1,1,neededLayer, 0}}
  806. end
  807.  
  808.  
  809. local function saveProgress(extras) --Session persistence
  810. exclusions = { modem = true, shell = true, _ENV = true}
  811. if doBackup then
  812. local toWrite = ""
  813. for a,b in pairs(getfenv(1)) do
  814.  if not exclusions[a] then
  815.      --print(a ,"   ", b, "   ", type(b)) --Debug
  816.    if type(b) == "string" then b = "\""..b.."\"" end
  817.     if type(b) == "table" then b = textutils.serialize(b) end
  818.     if type(b) ~= "function" then
  819.       toWrite = toWrite..a.." = "..tostring(b).."\n"
  820.     end
  821.   end
  822. end
  823. toWrite = toWrite.."doCheckFuel = false\n" --It has already used fuel, so calculation unnecessary
  824. local file
  825. repeat
  826.   file = fs.open(saveFile,"w")
  827. until file
  828. file.write(toWrite)
  829. if type(extras) == "table" then
  830.   for a, b in pairs(extras) do
  831.     file.write(a.." = "..tostring(b).."\n")
  832.   end
  833. end
  834. if checkFuel() ~= math.huge then --Used for location comparing
  835.   file.write("fuelLevel = "..tostring(checkFuel()).."\n")
  836. end
  837. file.close()
  838. end
  839. end
  840.  
  841. local area = x*z
  842. local volume = x*y*z
  843. local lastHeight = y%3
  844. layers = math.ceil(y/3)
  845. local yMult = layers --This is basically a smart y/3 for movement
  846. local moveVolume = (area * yMult) --Kept for display percent
  847. --Calculating Needed Fuel--
  848. do --Because many local variables unneeded elsewhere
  849.   local changeYFuel = 2*(y + startDown)
  850.   local dropOffSupplies = 2*(x + z + y + startDown) --Assumes turtle as far away as possible, and coming back
  851.   local frequency = math.ceil(((moveVolume/(64*(15-uniqueExtras) + uniqueExtras)) ) ) --This is complicated: volume / inventory space of turtle, defined as 64*full stacks + 1 * unique stacks.
  852.                                                                                      --max of 15 full stacks because once one item is picked up, slot is "full". Ceil to count for initial back and forth
  853.   if enderChest then frequency = 0 end --Never goes back to start
  854.   neededFuel = moveVolume + changeYFuel + (frequency * dropOffSupplies) + ((x + z) * layers) --x + z *layers because turtle has to come back from far corner every layer
  855.   neededFuel = neededFuel + fuelTable[fuelSafety] --For safety
  856. end
  857.  
  858. if neededFuel > checkFuelLimit() and doCheckFuel then--Checks for if refueling goes over turtle fuel limit
  859.   if not (doRefuel or fuelChest) then
  860.     screen()
  861.     print("Turtle cannot hold enough fuel\n")
  862.     print("Options: \n1. Select a smaller size \n2. Enable Mid-Run Refueling (RECOMMENDED) \n3. Turn fuel checking off (only if fuel chest) \n4. Do nothing")
  863.     local _, key = os.pullEvent("char")
  864.     if key == "1" then
  865.       screen(); print("Okay"); error("",0)
  866.     elseif key == "3" then
  867.       doCheckFuel = false
  868.     elseif key == "4" then
  869.       --pass
  870.     else --Not for number two because this is default
  871.       doRefuel = true
  872.     end
  873.   end
  874.   neededFuel = checkFuelLimit()-checkFuel()-1
  875. end
  876.  
  877.  
  878. --Getting Fuel
  879. local hasRefueled --This is for oldOreQuarry prompting
  880. if doCheckFuel and checkFuel() < neededFuel then
  881.   neededFuel = math.min(math.floor(neededFuel * fuelMultiplier), checkFuelLimit()-checkFuel()-1) --Does the same as above, but not verbose because optional
  882.   hasRefueled = true
  883.   print("Not enough fuel")
  884.   print("Current: ",checkFuel()," Needed: ",neededFuel)
  885.   print("Starting SmartFuel...")
  886.   sleep(2) --So they can read everything.
  887.   term.clear()
  888.   local oneFuel, neededFuelItems = 0,0 --Initializing Variables
  889.   local currSlot = 0
  890.   local function output(text, x, y) --For displaying fuel statistics
  891.     local currX, currY = term.getCursorPos()
  892.     term.setCursorPos(x,y)
  893.     term.clearLine()
  894.     term.write(text)
  895.     term.setCursorPos(currX,currY)
  896.   end
  897.   local function roundTo(num, target) --For stacks of fuel and turtle slots when undergoing addition/subtraction
  898.     if num >= target then return target elseif num < 0 then return 0 else return num end
  899.   end
  900.   local function updateScreen()
  901.     output("Welcome to SmartFuel! Now Refueling...", 1,1)
  902.     output("Fuel Request Multiplier: "..tostring(fuelMultiplier).."x",1,2)
  903.     output("Currently taking fuel from slot "..currSlot,1,3)
  904.     output("Current single fuel: "..tostring(oneFuel or 0),1,4)
  905.     output("Current estimate of needed fuel: ",1,4)
  906.     output("Single Items: "..math.ceil(neededFuelItems),4,6)
  907.     output("Stacks:       "..math.ceil(neededFuelItems / 64),4,7)
  908.     output("Needed Fuel: "..tostring(neededFuel),1,12)
  909.     output("Current Fuel: "..tostring(checkFuel()),1,13)
  910.   end
  911.   while checkFuel() < neededFuel do
  912.     currSlot = currSlot + 1
  913.     select(currSlot)
  914.     if currSlot ~= 1 and not turtle.refuel(0) then --If it's not the first slot, and not fuel, go back to start
  915.       currSlot = 1; select(currSlot)
  916.     end
  917.     updateScreen()
  918.     while turtle.getItemCount(currSlot) == 0 do
  919.       sleep(1.5)
  920.     end
  921.     repeat --TODO: Probably unnecessary loop, remove later
  922.       local previous = checkFuel()
  923.       turtle.refuel(1)
  924.       oneFuel = checkFuel() - previous
  925.       updateScreen()
  926.     until (oneFuel or 0) > 0 --Not an if to prevent errors if fuel taken out prematurely.
  927.     neededFuelItems = math.ceil((neededFuel - checkFuel()) / oneFuel)
  928.     turtle.refuel(roundTo(neededFuelItems, 64)) --Change because can only think about 64 at once.
  929.     if turtle.getItemCount(roundTo(currSlot + 1, inventoryMax)) == 0 then --Resets if no more fuel
  930.       currSlot = 0
  931.     end
  932.     neededFuelItems = math.ceil((neededFuel - checkFuel()) / oneFuel) --This line is not repeated uselessly, it's for the display function
  933.   end
  934.   select(1)
  935. end
  936. --Ender Chest Obtaining
  937. function promptSpecialSlot(specialSlot, name, limit)
  938.   local function isInRange(toCheck, lower, upper) return toCheck <= upper and toCheck >= lower end
  939.   while not isInRange(turtle.getItemCount(specialSlots[specialSlot]), 1, limit or 1) do
  940.     screen(1,1)
  941.     print("You have decided to use a ",name,"!")
  942.     print("Please place one ",name," in slot ",specialSlots[specialSlot])
  943.     sleep(1)
  944.   end
  945.   print(name," in slot ",specialSlots[specialSlot], " checks out")
  946. end
  947. function checkSpecialSlot(specialSlot, name, allowed)
  948.  if restoreFoundSwitch and turtle.getItemCount(specialSlots[specialSlot]) == 0 then --If the turtle was stopped while dropping off items.
  949.     select(specialSlots[specialSlot])
  950.     turtle.dig()
  951.     select(1)
  952.   end
  953.   promptSpecialSlot(specialSlot, name, allowed)
  954.   allowedItems[specialSlots[specialSlot]] = 1
  955.   sleep(1)
  956. end
  957. if enderChest then
  958.   checkSpecialSlot("enderChest","Ender Chest")
  959. end
  960. if fuelChest then
  961.   checkSpecialSlot("fuelChest","Fuel Chest")
  962. end
  963. if lavaBucket then
  964.   checkSpecialSlot("lavaBucket","Empty Bucket")
  965.   select(specialSlots.lavaBucket)
  966.   if turtle.refuel(1) then --Just in case they actually put in a lava bucket >:(
  967.     print("No! You're supposed to put in an empty bucket") --This doubles as emptying the lava bucket if mid-run
  968.     sleep(2)
  969.   end
  970.   select(1)
  971. end
  972. if compareChest then
  973.   checkSpecialSlot("compareChest","Chest", 64)
  974. end
  975.  
  976. --Setting which slots are marked as compare slots
  977. if oldOreQuarry then
  978.   if not restoreFoundSwitch then --We don't want to reset compare blocks every restart
  979.     local counter = 0
  980.     for i=1, inventoryMax do if turtle.getItemCount(i) > 0 and not specialSlots[i] then counter = counter+1 end end --If the slot has items, but isn't enderChest slot if it is enabled
  981.  
  982.     screen(1,1)
  983.     print("You have selected an Ore Quarry!")
  984.     if counter == 0 or hasRefueled then --If there are no compare slots, or the turtle has refueled, and probably has fuel in inventory
  985.       print("Please place your compare blocks in the first slots\n")
  986.  
  987.       print("Press Enter when done")
  988.       repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  989.     else
  990.       print("Registering slots as compare slots")
  991.       sleep(1)
  992.     end
  993.     for i=1, inventoryMax do
  994.       if turtle.getItemCount(i) > 0 then
  995.         if not specialSlots[i] then
  996.           table.insert(compareSlots, i) --Compare slots are ones compared to while mining. Conditions are because we Don't want to compare to enderChest
  997.           allowedItems[i] = 1 --Blacklist is for dropping off items. The number is maximum items allowed in slot when dropping off
  998.           dumpSlots[i] = true --We also want to ignore all excess of these items, like dirt
  999.         end
  1000.       end
  1001.     end
  1002.     if extraDropItems then
  1003.       screen(1,1)
  1004.       print("Put in extra drop items now\n")
  1005.       print("Press Enter when done")
  1006.       repeat until ({os.pullEvent("key")})[2] == 28 --Should wait for enter key to be pressed
  1007.       for i=1,inventoryMax do
  1008.         if not dumpSlots[i] and turtle.getItemCount(i) > 0 then --I don't want to modify from above, so I check it hasn't been assigned.
  1009.           dumpSlots[i] = true
  1010.           allowedItems[i] = 1
  1011.         end
  1012.       end
  1013.     end
  1014.     --This is could go very wrong if this isn't here
  1015.     if #compareSlots >= inventoryMax-keepOpen then screen(1,1); error("You have more quarry compare items than keep open slots, the turtle will continuously come back to start. Please fix.",0) end
  1016.   end
  1017.   local counter = 0
  1018.   for a, b in pairs(compareSlots) do if  turtle.getItemCount(b) > 0 then counter = counter + 1 end end
  1019.   if counter == 0 then
  1020.     screen(1,1)
  1021.     print("You have an ore quarry without any compare slots. Continue? y/n")
  1022.     if ({os.pullEvent("char")})[2] ~= "y" then error("",0) end
  1023.   end
  1024. elseif not oreQuarry then --This was screwing up dumpCompareItems
  1025.   dumpCompareItems = false --If not an ore quarry, this should definitely be false
  1026.   if specialSlots.enderChest == 1 then
  1027.     dumpSlots[2] = true
  1028.   else
  1029.     dumpSlots[1] = true
  1030.   end
  1031. end
  1032.  
  1033. --Rednet Handshake
  1034. function newMessageID()
  1035.   return math.random(1,2000000000)
  1036. end
  1037. function sendMessage(send, receive, message)
  1038.   if legacyRednet then
  1039.     if type(message) == "table" then message = textutils.serialize(message) end
  1040.     return modem.transmit(send, receive, message)
  1041.   end
  1042.   return modem.transmit(send , receive, {fingerprint = channels.fingerprint, id = newMessageID(), message = message})
  1043. end
  1044. if rednetEnabled then
  1045.   screen(1,1)
  1046.   print("Rednet is Enabled")
  1047.   print("The Channel to open is "..channels.send)
  1048.   if peripheral.find then
  1049.     modem = peripheral.find("modem")
  1050.   else
  1051.     modem = peripheral.wrap("right")
  1052.   end
  1053.   modem.open(channels.receive)
  1054.   local i = 0
  1055.     repeat
  1056.       local id = os.startTimer(3)
  1057.       i=i+1
  1058.       print("Sending Initial Message "..i)
  1059.       sendMessage(channels.send, channels.receive, channels.message)
  1060.       local message = {} --Have to initialize as table to prevent index nil
  1061.       repeat
  1062.         local event, idCheck, channel,_,locMessage, distance = os.pullEvent()
  1063.         if locMessage then message = locMessage end
  1064.         if legacyRednet then --For that one guy that uses 1.4.7
  1065.           message = {message = message}
  1066.         end
  1067.       until (event == "timer" and idCheck == id) or (event == "modem_message" and channel == channels.receive and type(message) == "table")
  1068.     until message.message == channels.confirm
  1069.   connected = true
  1070.   print("Connection Confirmed!")
  1071.   sleep(1.5)
  1072. end
  1073. function biometrics(isAtBedrock, requestQuad)
  1074.   if not rednetEnabled then return end --This function won't work if rednet not enabled :P
  1075.   local toSend = { label = os.getComputerLabel() or "No Label", id = os.getComputerID(),
  1076.     percent = percent, zPos = relzPos, xPos = relxPos, yPos = yPos,
  1077.     layersDone = layersDone, x = x, z = z, layers = layers,
  1078.     openSlots = getNumOpenSlots(), mined = mined, moved = moved,
  1079.     chestFull = chestFull, isAtChest = (xPos == 0 and yPos == 1 and zPos == 1),
  1080.     isGoingToNextLayer = (gotoDest == "layerStart"), foundBedrock = foundBedrock,
  1081.     fuel = checkFuel(), volume = volume, status = statusString,
  1082.     }
  1083.   if requestQuad and isInPath then --If we are requesting a quadRotor to send help
  1084.     if not gps.locate(gpsTimeout) then
  1085.       print("\nOH NOES! Trying to reach quadrotor, but can't get GPS position!")
  1086.       sleep(1)
  1087.     else
  1088.       toSend.firstPos = gpsStartPos
  1089.       toSend.secondPos = gpsSecondPos
  1090.       toSend.emergencyLocation = {gps.locate(gpsTimeout)}
  1091.     end
  1092.   end
  1093.   sendMessage(channels.send, channels.receive, toSend)
  1094.   id = os.startTimer(0.1)
  1095.   local event, received
  1096.   repeat
  1097.     local locEvent, idCheck, confirm, _, locMessage, distance = os.pullEvent()
  1098.     event, received = locEvent, locMessage or {message = ""}
  1099.     if legacyRednet and type(received) == "string" then
  1100.       received = {message = received}
  1101.     end
  1102.   until (event == "timer" and idCheck == id) or (event == "modem_message" and confirm == channels.receive and type(received) == "table")
  1103.   if event == "modem_message" then connected = true else connected = false end
  1104.   local message = received.message:lower()
  1105.   if message == "stop" or message == "quit" or message == "kill" then
  1106.     count(true)
  1107.     display()
  1108.     error("Rednet said to stop...",0)
  1109.   end
  1110.   if message == "return" then
  1111.     endingProcedure()
  1112.     error('Rednet said go back to start...',0)
  1113.   end
  1114.   if message == "drop" then
  1115.     dropOff()
  1116.   end
  1117.   if message == "pause" then
  1118.     print("\nTurtle is paused. Send 'resume' or press any character to resume")
  1119.     statusString = "Paused"
  1120.     toSend.status = statusString
  1121.     os.startTimer(3)
  1122.     repeat --The turtle sends out periodic messages, which will clear the receiver's queue and send a message (if it exists)
  1123.      --This may be a bit overkill, sending the whole message again, but whatever.
  1124.       local event, idCheck, confirm, _, message, distance = os.pullEvent()
  1125.       if event == "timer" then os.startTimer(3); sendMessage(channels.send, channels.receive, toSend) end --Only send messages on the timer. This prevents ridiculous spam
  1126.     until (event == "modem_message" and confirm == channels.receive and (message.message == "resume" or message.message == "unpause" or message.message == "pause")) or (event == "char")
  1127.     statusString = nil
  1128.   end
  1129.   if message == "refuel" then
  1130.     print("\nEngaging in emergency refueling")
  1131.     emergencyRefuel(true)
  1132.   end
  1133.  
  1134. end
  1135. --Showing changes to settings
  1136. screen(1,1)
  1137. print("Your selected settings:")
  1138. if #changedT == 0 then
  1139.   print("Completely Default")
  1140.   else
  1141.   for i=1, #changedT do
  1142.     if not changedT[i].hidden then
  1143.       print(changedT[i][1],": ",changedT[i][2]) --Name and Value
  1144.     end
  1145.   end
  1146. end
  1147. print("\nStarting in 3"); sleep(1); print("2"); sleep(1); print("1"); sleep(1.5) --Dramatic pause at end
  1148.  
  1149.  
  1150.  
  1151. ----------------------------------------------------------------
  1152. --Define ALL THE FUNCTIONS
  1153. --Event System Functions
  1154. function eventSetInsertionPoint(num)
  1155.   eventInsertionPoint = num or 1
  1156. end
  1157. function eventAddAt(pos, ...)
  1158.   return table.insert(events,pos, {...}) or true
  1159. end
  1160. function eventAdd(...) --Just a wrapper
  1161.   return eventAddAt(eventInsertionPoint, ...)
  1162. end
  1163. function eventGet(pos)
  1164.   return events[tonumber(pos) or #events]
  1165. end
  1166. function eventPop(pos)
  1167.   return table.remove(events,tonumber(pos) or #events) or false --This will return value popped, tonumber returns nil if fail, so default to end
  1168. end
  1169. function eventRun(value, ...)
  1170.   local argsList = {...}
  1171.   if type(value) == "string" then
  1172.     if value:sub(-1) ~= ")" then --So supports both "up()" and "up"
  1173.       value = value .. "("
  1174.       for a, b in pairs(argsList) do --Appending arguments
  1175.         local toAppend
  1176.         if type(b) == "table" then toAppend = textutils.serialize(b)
  1177.         elseif type(b) == "string" then toAppend = "\""..tostring(b).."\"" --They weren't getting strings around them
  1178.         else toAppend = tostring(b) end
  1179.         value = value .. (toAppend or "true") .. ", "
  1180.       end
  1181.       if value:sub(-1) ~= "(" then --If no args, do not want to cut off
  1182.         value = value:sub(1,-3)..""
  1183.       end
  1184.       value = value .. ")"
  1185.     end
  1186.     --print(value) --Debug
  1187.     local func = loadstring(value)
  1188.     setfenv(func, getfenv(1))
  1189.     return func()
  1190.   end
  1191. end
  1192. function eventClear(pos)
  1193.   if pos then events[pos] = nil else events = {} end
  1194. end
  1195. function runAllEvents()
  1196.   while #events > 0 do
  1197.     local toRun = eventGet()
  1198.     --print(toRun[1]) --Debug
  1199.     eventRun(unpack(toRun))
  1200.     eventPop()
  1201.   end
  1202. end
  1203.  
  1204. --Display Related Functions
  1205. function display() --This is just the last screen that displays at the end
  1206.   screen(1,1)
  1207.   print("Total Blocks Mined: "..mined)
  1208.   print("Current Fuel Level: "..checkFuel())
  1209.   print("Cobble: "..totals.cobble)
  1210.   print("Usable Fuel: "..totals.fuel)
  1211.   print("Other: "..totals.other)
  1212.   if rednetEnabled then
  1213.     print("")
  1214.     print("Sent Stop Message")
  1215.     if legacyRednet then --This was the traditional stopping signal
  1216.       print("Sent Legacy Stop")
  1217.       sendMessage(channels.send, channels.receive, "stop")
  1218.     end
  1219.     local finalTable = {mined = mined, cobble = totals.cobble, fuelblocks = totals.fuel,
  1220.         other = totals.other, fuel = checkFuel(), isDone = true }
  1221.     if preciseTotals then
  1222.       finalTable.preciseTotals = exactTotals --This table doubles as a flag.
  1223.     end
  1224.     sendMessage(channels.send,channels.receive, finalTable)
  1225.     modem.close(channels.receive)
  1226.   end
  1227.   if doBackup then
  1228.     fs.delete(saveFile)
  1229.     if autoResume then --Getting rid of the original startup files and replacing
  1230.       fs.delete(startupName)
  1231.       if fs.exists(startupRename) then
  1232.         fs.move(startupRename, startupName)
  1233.       end
  1234.     end
  1235.   end
  1236. end
  1237. function updateDisplay() --Runs in Mine(), display information to the screen in a certain place
  1238. screen(1,1)
  1239. print("Blocks Mined")
  1240. print(mined)
  1241. print("Percent Complete")
  1242. print(percent.."%")
  1243. print("Fuel")
  1244. print(checkFuel())
  1245.   -- screen(1,1)
  1246.   -- print("Xpos: ")
  1247.   -- print(xPos)
  1248.   -- print("RelXPos: ")
  1249.   -- print(relxPos)
  1250.   -- print("Z Pos: ")
  1251.   -- print(zPos)
  1252.   -- print("Y pos: ")
  1253.   -- print(yPos)
  1254. if rednetEnabled then
  1255. screenLine(1,7)
  1256. print("Connected: "..tostring(connected))
  1257. end
  1258. end
  1259. --Utility functions
  1260. local function pad(str, length, side)
  1261.   toRet = ""
  1262.   if side == "right" then
  1263.     toRet = str
  1264.   end
  1265.   for i=1, length-#str do
  1266.     toRet = toRet.." "
  1267.   end
  1268.   if side == "left" then
  1269.     toRet = toRet..str
  1270.   end
  1271.   return toRet
  1272. end
  1273. function logMiningRun(textExtension, extras) --Logging mining runs
  1274.   if not logging then return end
  1275.   local number, name = 0
  1276.   if not fs.isDir(logFolder) then
  1277.     fs.delete(logFolder)
  1278.     fs.makeDir(logFolder)
  1279.   end
  1280.   repeat
  1281.     number = number + 1 --Number will be at least 2
  1282.     name = logFolder.."/Quarry_Log_"..tostring(number)..(textExtension or "")
  1283.   until not fs.exists(name)
  1284.   local handle = fs.open(name,"w")
  1285.   local function write(...)
  1286.     for a, b in ipairs({...}) do
  1287.       handle.write(tostring(b))
  1288.     end
  1289.     handle.write("\n")
  1290.   end
  1291.   local function boolToText(bool) if bool then return "Yes" else return "No" end end
  1292.   write("Welcome to the Quarry Logs!")
  1293.   write("Entry Number: ",number)
  1294.   write("Quarry Version: ",VERSION)
  1295.   write("Dimensions (X Z Y): ",x," ",z," ", y)
  1296.   write("Blocks Mined: ", mined)
  1297.   write("  Cobble: ", totals.cobble)
  1298.   write("  Usable Fuel: ", totals.fuel)
  1299.   write("  Other: ",totals.other)
  1300.   write("Total Fuel Used: ",  (originalFuel or (neededFuel + checkFuel()))- checkFuel()) --Protect against errors with some precision
  1301.   write("Expected Fuel Use: ", neededFuel)
  1302.   write("Days to complete mining run: ",os.day()-originalDay)
  1303.   write("Day Started: ", originalDay)
  1304.   write("Number of times resumed: ", numResumed)
  1305.   write("Was an ore quarry? ",boolToText(oreQuarry or oldOreQuarry))
  1306.   write("Was inverted? ",boolToText(invert))
  1307.   write("Was using rednet? ",boolToText(rednetEnabled))
  1308.   write("Chest was on the ",dropSide," side")
  1309.   if startDown > 0 then write("Started ",startDown," blocks down") end
  1310.   if exactTotals then
  1311.     write("\n==DETAILED TOTALS==")
  1312.     for a,b in pairs(exactTotals) do
  1313.       write(pad(a, 15, "right"),":",pad(tostring(b),({term.getSize()})[1]-15-1, "left"))
  1314.     end
  1315.   end
  1316.   handle.close()
  1317. end
  1318. --Inventory related functions
  1319. function isFull(slots) --Checks if there are more than "slots" used inventory slots.
  1320.   slots = slots or inventoryMax
  1321.   local numUsed = 0
  1322.   sleep(0)
  1323.   for i=1, inventoryMax do
  1324.     if turtle.getItemCount(i) > 0 then numUsed = numUsed + 1 end
  1325.   end
  1326.   if numUsed > slots then
  1327.     return true
  1328.   end
  1329.   return false
  1330. end
  1331. function countUsedSlots() --Returns number of slots with items in them, as well as a table of item counts
  1332.   local toRet, toRetTab = 0, {}
  1333.   for i=1, inventoryMax do
  1334.     local a = turtle.getItemCount(i)
  1335.     if a > 0 then toRet = toRet + 1 end
  1336.     table.insert(toRetTab, a)
  1337.   end
  1338.   return toRet, toRetTab
  1339. end
  1340. function getSlotsTable() --Just get the table from above
  1341.   local _, toRet = countUsedSlots()
  1342.   return toRet
  1343. end
  1344. function getChangedSlots(tab1, tab2) --Returns a table of changed slots. Format is {slotNumber, numberChanged}
  1345.   local toRet = {}
  1346.   for i=1, math.min(#tab1, #tab2) do
  1347.     diff = math.abs(tab2[i]-tab1[i])
  1348.     if diff > 0 then
  1349.       table.insert(toRet, {i, diff})
  1350.     end
  1351.   end
  1352.   return toRet
  1353. end
  1354. function getFirstChanged(tab1, tab2) --Just a wrapper. Probably not needed
  1355.   local a = getChangedSlots(tab1,tab2)
  1356.   return (a[1] or {"none"})[1]
  1357. end
  1358.  
  1359. function getRep(which, list) --Gets a representative slot of a type. Expectation is a sequential table of types
  1360.   for a,b in pairs(list) do
  1361.     if b == which then return a end
  1362.   end
  1363.   return false
  1364. end
  1365. function assignTypes(types, count) --The parameters allow a preexisting table to be used, like a table from the original compareSlots...
  1366.   types, count = types or {1}, count or 1 --Table of types and current highest type
  1367.   for i=1, inventoryMax do
  1368.     if turtle.getItemCount(i) > 0 and not specialSlots[i] then --Not special slots so we don't count ender chests
  1369.       select(i)
  1370.       for k=1, count do
  1371.         if turtle.compareTo(getRep(k, types)) then types[i] = k end
  1372.       end
  1373.       if not types[i] then
  1374.         count = count + 1
  1375.         types[i] = count
  1376.       end
  1377.       if oreQuarry then
  1378.         if blacklist[turtle.getItemDetail().name] then
  1379.           dumpSlots[i] = true
  1380.         else
  1381.           dumpSlots[i] = false
  1382.         end
  1383.       end
  1384.     end
  1385.   end
  1386.   select(1)
  1387.   return types, count
  1388. end
  1389. function getTableOfType(which, list) --Returns a table of all the slots of which type
  1390.   local toRet = {}
  1391.   for a, b in pairs(list) do
  1392.     if b == which then
  1393.       table.insert(toRet, a)
  1394.     end
  1395.   end
  1396.   return toRet
  1397. end
  1398.  
  1399. --This is so the turtle will properly get types, otherwise getRep of a type might not be a dumpSlot, even though it should be.
  1400. if not restoreFoundSwitch then --We only want this to happen once
  1401.   if oldOreQuarry then --If its not ore quarry, this screws up type assigning
  1402.     initialTypes, initialCount = assignTypes()
  1403.   else
  1404.     initialTypes, initialCount = {1}, 1
  1405.   end
  1406. end
  1407.  
  1408. function count(add) --Done any time inventory dropped and at end, true=add, false=nothing, nil=subtract
  1409.   local mod = -1
  1410.   if add then mod = 1 end
  1411.   if add == false then mod = 0 end
  1412.   slot = {}        --1: Filler 2: Fuel 3:Other --[1] is type, [2] is number
  1413.   for i=1, inventoryMax do
  1414.     slot[i] = {}
  1415.     slot[i][2] = turtle.getItemCount(i)
  1416.   end
  1417.  
  1418.   local function iterate(toSet , rawTypes, set)
  1419.     for _, a in pairs(getTableOfType(toSet, rawTypes)) do --Get all slots matching type
  1420.       slot[a][1] = set --Set official type to "set"
  1421.     end
  1422.   end
  1423.  
  1424.   --This assigns "dumb" types to all slots based on comparing, then based on knowledge of dump type slots, changes all slots matching a dump type to one. Otherwise, if the slot contains fuel, it is 2, else 3
  1425.   local rawTypes, numTypes = assignTypes(copyTable(initialTypes), initialCount) --This gets increasingly numbered types, copyTable because assignTypes will modify it
  1426.  
  1427.   for i=1, numTypes do
  1428.     if (select(getRep(i, rawTypes)) or true) and turtle.refuel(0) then --Selects the rep slot, checks if it is fuel
  1429.       iterate(i, rawTypes, 2) --This type is fuel
  1430.     elseif dumpSlots[getRep(i,(oreQuarry and rawTypes) or initialTypes)] then --If the rep of this slot is a dump item. This is initial types so that the rep is in dump slots. rawTypes if oreQuarry to get newly assigned dumps
  1431.       iterate(i, rawTypes, 1) --This type is cobble/filler
  1432.     else
  1433.       iterate(i, rawTypes, 3) --This type is other
  1434.     end
  1435.   end
  1436.  
  1437.   for i=1,inventoryMax do
  1438.     if not specialSlots[i] then --Do nothing for specialSlots!
  1439.       if exactTotals and slot[i][2] > 0 then
  1440.         local data = turtle.getItemDetail(i)
  1441.         exactTotals[data.name] = (exactTotals[data.name] or 0) + (data.count * mod)
  1442.       end
  1443.       if slot[i][1] == 1 then totals.cobble = totals.cobble + (slot[i][2] * mod)
  1444.       elseif slot[i][1] == 2 then totals.fuel = totals.fuel + (slot[i][2] * mod)
  1445.       elseif slot[i][1] == 3 then totals.other = totals.other + (slot[i][2] * mod) end
  1446.     end
  1447.   end
  1448.  
  1449.   select(1)
  1450. end
  1451.  
  1452. --Refuel Functions
  1453. function emergencyRefuel(forceBasic)
  1454.   local continueEvac = true --This turns false if more fuel is acquired
  1455.   if fuelChest then --This is pretty much the only place that this will be used
  1456.     if not fuelChestPhase then --Since I want to do things with return of enderRefuel, I will just make a special system. All of this is for backup safety.
  1457.       fuelChestPhase = 0 --Global variable will be saved
  1458.       fuelChestProperFacing = facing
  1459.     end
  1460.     if fuelChestPhase == 0 then
  1461.       turnTo(coterminal(fuelChestProperFacing+2))
  1462.       dig(false)
  1463.       fuelChestPhase = 1
  1464.       saveProgress()
  1465.     end
  1466.     if fuelChestPhase == 1 then
  1467.       select(specialSlots.fuelChest)
  1468.       turtle.place()
  1469.       fuelChestPhase = 2
  1470.       saveProgress()
  1471.     end
  1472.     if fuelChestPhase == 2 then
  1473.       if not enderRefuel() then --Returns false if slots are full
  1474.         select(specialSlots.fuelChest)
  1475.         turtle.drop() --Somehow stuff got in here...
  1476.       end
  1477.       fuelChestPhase = 3
  1478.       saveProgress()
  1479.     end
  1480.     if fuelChestPhase == 3 then
  1481.       select(specialSlots.fuelChest)
  1482.       dig(false)
  1483.       select(1)
  1484.       fuelChestPhase = 4
  1485.       saveProgress()
  1486.     end
  1487.     if fuelChestPhase == 4 then
  1488.       turnTo(fuelChestProperFacing)
  1489.       fuelChestProperFacing = nil --Getting rid of saved values
  1490.       fuelChestPhase = nil
  1491.       continueEvac = false
  1492.     end
  1493.   elseif quadEnabled then --Ask for a quadRotor
  1494.     screen()
  1495.     print("Attempting an emergency Quad Rotor refuel")
  1496.     print("The turtle will soon send a message, then wait ",quadTimeout," seconds before moving on")
  1497.     print("Press any key to break timer")
  1498.     biometrics(nil, true)
  1499.     local timer, counter, counterID, event, id  = os.startTimer(quadTimeout), 0, os.startTimer(1)
  1500.     local startInventory = getSlotsTable()
  1501.     repeat
  1502.       if id == counterID then counter = counter + 1; counterID = os.startTimer(1) end
  1503.       screenLine(1,6)
  1504.       print("Seconds elapsed: ",counter)
  1505.       event, id = os.pullEvent() --Waits for a key or fuel or the timer
  1506.     until (event == "timer" and id == timer) or event == "key" or event == "turtle_inventory" --Key event just makes turtle go back to start
  1507.     if event == "turtle_inventory" then --If fuel was actually delivered
  1508.       local slot = getFirstChanged(startInventory, getSlotsTable())
  1509.       select(slot)
  1510.       local initialFuel = checkFuel()
  1511.       midRunRefuel(slot)
  1512.       if checkFuel() > initialFuel then
  1513.         print("Fuel delivered! Evac aborted")
  1514.         continueEvac = false
  1515.       else
  1516.         print("What did you send the turtle? Not fuel >:(")
  1517.         print("Continuing evac")
  1518.       end
  1519.       sleep(1)
  1520.     end
  1521.   elseif doRefuel or forceBasic then --Attempt an emergency refueling
  1522.     screen()
  1523.     print("Attempting an emergency refuel")
  1524.     print("Fuel Level:    ",checkFuel())
  1525.     print("Distance Back: ",(xPos+zPos+yPos+1))
  1526.     print("Categorizing Items")
  1527.     count(false) --Do not add count, but categorize
  1528.     local fuelSwitch, initialFuel = false, checkFuel() --Fuel switch so we don't go over limit (in emergency...)
  1529.     print("Going through available fuel slots")
  1530.     for i=1, inventoryMax do
  1531.       if fuelSwitch then break end
  1532.       if turtle.getItemCount(i) > 0 and slot[i][1] == 2 then --If there are items and type 2 (fuel)
  1533.         select(i)
  1534.         fuelSwitch = midRunRefuel(i) --See above "function drop" for usage
  1535.       end
  1536.     end
  1537.     select(1) --Cleanup
  1538.     print("Done fueling")
  1539.     if checkFuel() > initialFuel then
  1540.       continueEvac = false
  1541.       print("Evac Aborted")
  1542.     else
  1543.       print("Evac is a go, returning to base")
  1544.       sleep(1.5) --Pause for reading
  1545.     end
  1546.   end
  1547.   return continueEvac
  1548. end
  1549.  
  1550. function lavaRefuel(suckDir)
  1551.   if checkFuel() + lavaBuffer >= checkFuelLimit() then return false end -- we don't want to constantly over-fuel the turtle.
  1552.   local suckFunc
  1553.   if suckDir == "up" then suckFunc = turtle.placeUp
  1554.   elseif suckDir == "down" then suckFunc = turtle.placeDown
  1555.   else suckFunc = turtle.place end
  1556.  
  1557.   select(specialSlots.lavaBucket)
  1558.   if suckFunc() then
  1559.     midRunRefuel(specialSlots.lavaBucket, 0) --0 forces it to refuel, even though allowed items[slot] is 1
  1560.   end
  1561.   select(1)
  1562.   return true
  1563. end
  1564.  
  1565. --Mining functions
  1566. function dig(doAdd, mineFunc, inspectFunc, suckDir) --Note, turtle will not bother comparing if not given an inspectFunc
  1567.   if doAdd == nil then doAdd = true end
  1568.   mineFunc = mineFunc or turtle.dig
  1569.   local function retTab(tab) if type(tab) == "table" then return tab end end --Please ignore the stupid one-line trickery. I felt special writing that. (Unless it breaks, then its cool)
  1570.     --Mine if not in blacklist. inspectFunc returns success and (table or string) so retTab filters out the string and the extra table prevents errors.
  1571.   local mineFlag = false
  1572.   if oreQuarry and inspectFunc then
  1573.     local worked, data = inspectFunc()
  1574.     if data then
  1575.       mineFlag = not blacklist[data.name]
  1576.       if data.name == chestID then
  1577.         emptyChest(suckDir)
  1578.       end
  1579.       if lavaBucket and data.name == lavaID and data.metadata == lavaMeta then
  1580.         lavaRefuel(suckDir)
  1581.       end
  1582.     end
  1583.   end
  1584.   if not oreQuarry or not inspectFunc or mineFlag then --Mines if not oreQuarry, or if the inspect passed
  1585.    if mineFunc() then
  1586.      if doAdd then
  1587.        mined = mined + 1
  1588.      end
  1589.      return true
  1590.    else
  1591.      return false
  1592.    end
  1593.   end
  1594.   return true --This only runs if oreQuarry but item not in blacklist. true means succeeded in duty, not necessarily dug block
  1595. end
  1596.  
  1597. function digUp(doAdd, ignoreInspect)--Regular functions :) I switch definitions for optimization (I think)
  1598.   return dig(doAdd, turtle.digUp, (not ignoreInspect and turtle.inspectUp) or nil, "up")
  1599. end
  1600. function digDown(doAdd, ignoreInspect)
  1601.   return dig(doAdd, turtle.digDown, (not ignoreInspect and turtle.inspectDown) or nil, "down")
  1602. end
  1603. if inverted then --If inverted, switch the options
  1604.   digUp, digDown = digDown, digUp
  1605. end
  1606.  
  1607. function smartDig(doDigUp, doDigDown) --This function is used only in mine when oldOreQuarry
  1608.   if inverted then doDigUp, doDigDown = doDigDown, doDigUp end --Switching for invert
  1609.   local blockAbove, blockBelow = doDigUp and turtle.detectUp(), doDigDown and turtle.detectDown() --These control whether or not the turtle digs
  1610.   local index = 1
  1611.   for i=1, #compareSlots do
  1612.     if not (blockAbove or blockBelow) then break end --We don't want to go selecting if there is nothing to dig
  1613.     index = i --To access out of scope
  1614.     select(compareSlots[i])
  1615.     if blockAbove and turtle.compareUp() then blockAbove = false end
  1616.     if blockBelow and turtle.compareDown() then blockBelow = false end
  1617.   end
  1618.   if compareChest then
  1619.     local flag = false
  1620.     select(specialSlots.compareChest)
  1621.     if turtle.compareUp() then emptyChest("up") end --Impressively, this actually works with session persistence. I'm gooood (apparently :P )
  1622.     if turtle.compareDown() then emptyChest("down") end --Looking over the code, I see no reason why that works... Oh well.
  1623.   end
  1624.   table.insert(compareSlots, 1, table.remove(compareSlots, index)) --This is so the last selected slot is the first slot checked, saving a select call
  1625.   if blockAbove then dig(true, turtle.digUp) end
  1626.   if blockBelow then dig(true, turtle.digDown) end
  1627. end
  1628.  
  1629. function relxCalc()
  1630.   if layersDone % 2 == 1 then
  1631.     relzPos = zPos
  1632.   else
  1633.     relzPos = (z-zPos) + 1
  1634.   end
  1635.   if relzPos % 2 == 1 then
  1636.     relxPos = xPos
  1637.   else
  1638.     relxPos = (x-xPos)+1
  1639.   end
  1640.   if layersDone % 2 == 0 and z % 2 == 1 then
  1641.     relxPos = (x-relxPos)+1
  1642.   end
  1643. end
  1644. function horizontalMove(movement, posAdd, doAdd)
  1645.   if doAdd == nil then doAdd = true end
  1646.   if movement() then
  1647.     if doAdd then
  1648.       moved = moved + 1
  1649.     end
  1650.     if facing == 0 then
  1651.       xPos = xPos + 1
  1652.     elseif facing == 1 then
  1653.       zPos = zPos + 1
  1654.     elseif facing == 2 then
  1655.       xPos = xPos - 1
  1656.     elseif facing == 3 then
  1657.       zPos = zPos - 1
  1658.     else
  1659.       error("Function forward, facing should be 0 - 3, got "..tostring(facing),2)
  1660.     end
  1661.     relxCalc()
  1662.     return true
  1663.   end
  1664.   return false
  1665. end
  1666. function forward(doAdd)
  1667.   return horizontalMove(turtle.forward, 1, doAdd)
  1668. end
  1669. function back(doAdd)
  1670.   return horizontalMove(turtle.back, -1, doAdd)
  1671. end
  1672. function verticalMove(moveFunc, yDiff, digFunc, attackFunc)
  1673.   local count = 0
  1674.   while not moveFunc() do
  1675.     if not digFunc(true, true) then --True True is doAdd, and ignoreInspect
  1676.       attackFunc()
  1677.       sleep(0.5)
  1678.       count = count + 1
  1679.       if count > maxTries and yPos > (startY-7) then bedrock() end
  1680.     end
  1681.   end
  1682.   yPos = yDiff + yPos
  1683.   saveProgress()
  1684.   biometrics()
  1685.   return true
  1686. end
  1687. function up() --Uses other function if inverted
  1688.   verticalMove(inverted and turtle.down or turtle.up, -1, digUp, attackUp) --Other functions deal with invert already
  1689. end
  1690. function down()
  1691.   verticalMove(inverted and turtle.up or turtle.down, 1, digDown, attackDown)
  1692. end
  1693.  
  1694.  
  1695. function right(num)
  1696.   num = num or 1
  1697.   for i=1, num do
  1698.     facing = coterminal(facing+1)
  1699.     saveProgress()
  1700.     if not goLeftNotRight then turtle.turnRight() --Normally
  1701.     else turtle.turnLeft() end --Left Quarry
  1702.   end
  1703. end
  1704. function left(num)
  1705.   num = num or 1
  1706.   for i=1, num do
  1707.   facing = coterminal(facing-1)
  1708.   saveProgress()
  1709.   if not goLeftNotRight then turtle.turnLeft() --Normally
  1710.   else turtle.turnRight() end --Left Quarry
  1711. end
  1712. end
  1713.  
  1714. function attack(doAdd, func)
  1715.   doAdd = doAdd or true
  1716.   func = func or turtle.attack
  1717.   if func() then
  1718.     if doAdd then
  1719.       attacked = attacked + 1
  1720.     end
  1721.     return true
  1722.   end
  1723.   return false
  1724. end
  1725. function attackUp(doAdd)
  1726.   if inverted then
  1727.     return attack(doAdd, turtle.attackDown)
  1728.   else
  1729.     return attack(doAdd, turtle.attackUp)
  1730.   end
  1731. end
  1732. function attackDown(doAdd)
  1733.   if inverted then
  1734.     return attack(doAdd, turtle.attackUp)
  1735.   else
  1736.     return attack(doAdd, turtle.attackDown)
  1737.   end
  1738. end
  1739.  
  1740. function detect(func)
  1741.   func = func or turtle.detect
  1742.   return func()
  1743. end
  1744. function detectUp(ignoreInvert)
  1745.   if inverted and not ignoreInvert then return detect(turtle.detectDown)
  1746.   else return detect(turtle.detectUp) end
  1747. end
  1748. function detectDown(ignoreInvert)
  1749.   if inverted and not ignoreInvert then return detect(turtle.detectUp)
  1750.   else return detect(turtle.detectDown) end
  1751. end
  1752.  
  1753.  
  1754.  
  1755. function mine(doDigDown, doDigUp, outOfPath,doCheckInv) -- Basic Move Forward
  1756.   if doCheckInv == nil then doCheckInv = true end
  1757.   if doDigDown == nil then doDigDown = true end
  1758.   if doDigUp == nil then doDigUp = true end
  1759.   if outOfPath == nil then outOfPath = false end
  1760.   isInPath = (not outOfPath) --For rednet
  1761.   if not outOfPath and (checkFuel() <= xPos + zPos + yPos + 5) then --If the turtle can just barely get back to the start, we need to get it there. We don't want this to activate coming back though...
  1762.     local continueEvac = false --It will be set true unless at start
  1763.     if xPos ~= 0 then
  1764.       continueEvac = emergencyRefuel() --This is a huge list of things to do in an emergency
  1765.     end
  1766.     if continueEvac then
  1767.       eventClear() --Clear any annoying events for evac
  1768.       local currPos = yPos
  1769.       endingProcedure() --End the program
  1770.       print("Turtle ran low on fuel so was brought back to start for you :)\n\nTo resume where you left off, use '-startDown "..tostring(currPos-1).."' when you start")
  1771.       error("",0)
  1772.     end
  1773.   end
  1774.   if frontChest and not outOfPath then
  1775.     if turtle.inspect then
  1776.       local check, data = turtle.inspect()
  1777.       if check and data.name == chestID then
  1778.         emptyChest("front")
  1779.       end
  1780.     else
  1781.       local flag = false
  1782.       select(specialSlots.compareChest)
  1783.       if turtle.compare() then flag = true end
  1784.       select(1)
  1785.       if flag then
  1786.         emptyChest("front")
  1787.       end
  1788.     end
  1789.   end
  1790.  
  1791.   local count = 0
  1792.   if not outOfPath then dig() end  --This speeds up the quarry by a decent amount if there are more mineable blocks than air
  1793.   while not forward(not outOfPath) do
  1794.     sleep(0) --Calls coroutine.yield to prevent errors
  1795.     count = count + 1
  1796.     if not dig() then
  1797.       attack()
  1798.     end
  1799.     if count > 10 then
  1800.       attack()
  1801.       sleep(0.2)
  1802.     end
  1803.     if count > maxTries then
  1804.       if checkFuel() == 0 then --Don't worry about inf fuel because I modified this function
  1805.         saveProgress({doCheckFuel = true, doRefuel = true}) --This is emergency because this should never really happen.
  1806.         os.reboot()
  1807.       elseif yPos > (startY-7) and turtle.detect() then --If it is near bedrock
  1808.         bedrock()
  1809.       else --Otherwise just sleep for a bit to avoid sheeps
  1810.         sleep(1)
  1811.       end
  1812.     end
  1813.   end
  1814.   checkSanity() --Not kidding... This is necessary
  1815.   saveProgress(tab)
  1816.  
  1817.   if not oldOreQuarry then
  1818.     if doDigUp then--The digging up and down part
  1819.       sleep(0) --Calls coroutine.yield
  1820.       if not digUp(true) and detectUp() then --This is relative: will dig down first on invert
  1821.         if not attackUp() then
  1822.           if yPos > (startY-7) then bedrock() end --Checking for bedrock, but respecting user wishes
  1823.         end
  1824.       end
  1825.     end
  1826.     if doDigDown then
  1827.      digDown(true) --This needs to be absolute as well
  1828.     end
  1829.   else --If oldQuarry
  1830.     smartDig(doDigUp,doDigDown)
  1831.   end
  1832.   percent = math.ceil(moved/moveVolume*100)
  1833.   updateDisplay()
  1834.   if doCheckInv and careAboutResources then
  1835.     if isFull(inventoryMax-keepOpen) then
  1836.       if not ((oreQuarry or oldOreQuarry) and dumpCompareItems) then
  1837.         dropOff()
  1838.       else
  1839.         local currInv = getSlotsTable()
  1840.         drop(nil, false, true) --This also takes care of counting.
  1841.         if #getChangedSlots(currInv, getSlotsTable()) <= 2 then --This is so if the inventory is full of useful stuff, it still has to drop it
  1842.           dropOff()
  1843.         end
  1844.       end
  1845.     end
  1846.   end
  1847.   biometrics()
  1848. end
  1849. --Insanity Checking
  1850. function checkSanity()
  1851.   if not isInPath then --I don't really care if its not in the path.
  1852.     return true
  1853.   end
  1854.   if not (facing == 0 or facing == 2) and #events == 0 then --If mining and not facing proper direction and not in a turn
  1855.     turnTo(0)
  1856.     rowCheck = true
  1857.   end
  1858.   if xPos < 0 or xPos > x or zPos < 0 or zPos > z or yPos < 0 then
  1859.     saveProgress()
  1860.     print("I have gone outside boundaries, attempting to fix (maybe)")
  1861.     if xPos > x then goto(x, zPos, yPos, 2) end --I could do this with some fancy math, but this is much easier
  1862.     if xPos < 0 then goto(1, zPos, yPos, 0) end
  1863.     if zPos > z then goto(xPos, z, yPos, 3) end
  1864.     if zPos < 0 then goto(xPos, 1, yPos, 1) end
  1865.     relxCalc() --Get relxPos properly
  1866.     eventClear()
  1867.  
  1868.     --[[
  1869.     print("Oops. Detected that quarry was outside of predefined boundaries.")
  1870.     print("Please go to my forum thread and report this with a short description of what happened")
  1871.     print("If you could also run \"pastebin put Civil_Quarry_Restore\" and give me that code it would be great")
  1872.     error("",0)]]
  1873.   end
  1874. end
  1875.  
  1876. local function fromBoolean(input) --Like a calculator
  1877. if input then return 1 end
  1878. return 0
  1879. end
  1880. local function multBoolean(first,second) --Boolean multiplication
  1881. return (fromBoolean(first) * fromBoolean(second)) == 1
  1882. end
  1883. function coterminal(num, limit) --I knew this would come in handy :D
  1884. limit = limit or 4 --This is for facing
  1885. return math.abs((limit*fromBoolean(num < 0))-(math.abs(num)%limit))
  1886. end
  1887. if tArgs["-manualpos"] then
  1888.   facing = coterminal(facing) --Done to improve support for "-manualPos"
  1889.   if facing == 0 then rowCheck = true elseif facing == 2 then rowCheck = false end --Ditto
  1890.   relxCalc() --Ditto
  1891. end
  1892.  
  1893. --Direction: Front = 0, Right = 1, Back = 2, Left = 3
  1894. function turnTo(num)
  1895.   num = num or facing
  1896.   num = coterminal(num) --Prevent errors
  1897.   local turnRight = true
  1898.   if facing-num == 1 or facing-num == -3 then turnRight = false end --0 - 1 = -3, 1 - 0 = 1, 2 - 1 = 1
  1899.   while facing ~= num do          --The above is used to smartly turn
  1900.     if turnRight then
  1901.       right()
  1902.     else
  1903.       left()
  1904.     end
  1905.   end
  1906. end
  1907. function goto(x,z,y, toFace, destination)
  1908.   --Will first go to desired z pos, then x pos, y pos varies
  1909.   x = x or 1; y = y or 1; z = z or 1; toFace = toFace or facing
  1910.   gotoDest = destination or "" --This is used by biometrics.
  1911.   statusString = "Going to ".. (destination or "somewhere")
  1912.   --Possible destinations: layerStart, quarryStart
  1913.   if yPos > y then --Will go up first if below position
  1914.     while yPos~=y do up() end
  1915.   end
  1916.   if zPos > z then
  1917.     turnTo(3)
  1918.   elseif zPos < z then
  1919.     turnTo(1)
  1920.   end
  1921.   while zPos ~= z do mine(false,false,true,false) end
  1922.   if xPos > x then
  1923.     turnTo(2)
  1924.   elseif xPos < x then
  1925.     turnTo(0)
  1926.   end
  1927.   while xPos ~= x do mine(false,false,true,false) end
  1928.   if yPos < y then --Will go down after if above position
  1929.     while yPos~=y do down() end
  1930.   end
  1931.   turnTo(toFace)
  1932.   saveProgress()
  1933.   gotoDest = ""
  1934.   statusString = nil
  1935. end
  1936. function getNumOpenSlots()
  1937.   local toRet = 0
  1938.   for i=1, inventoryMax do
  1939.     if turtle.getItemCount(i) == 0 then
  1940.       toRet = toRet + 1
  1941.     end
  1942.   end
  1943.   return toRet
  1944. end
  1945. function emptyChest(suckDirection)
  1946.   eventAdd("emptyChest",suckDirection)
  1947.   eventSetInsertionPoint(2) --Because dropOff adds events we want to run first
  1948.   local suckFunc
  1949.   if suckDirection == "up" then
  1950.     suckFunc = turtle.suckUp
  1951.   elseif suckDirection == "down" then
  1952.     suckFunc = turtle.suckDown
  1953.   else
  1954.     suckFunc = turtle.suck
  1955.   end
  1956.   repeat
  1957.     if inventoryMax - countUsedSlots() <= 0 then --If there are no slots open, need to empty
  1958.       dropOff()
  1959.     end
  1960.   until not suckFunc()
  1961.   eventClear()
  1962.   eventSetInsertionPoint()
  1963. end
  1964.  
  1965. --Ideas: Bring in inventory change-checking functions, count blocks that have been put in, so it will wait until all blocks have been put in.
  1966. local function waitDrop(slot, allowed, whereDrop) --This will just drop, but wait if it can't
  1967.   allowed = allowed or 0
  1968.   while turtle.getItemCount(slot) > allowed do --No more half items stuck in slot!
  1969.     local tries = 1
  1970.     while not whereDrop(turtle.getItemCount(slot)-allowed) do --Drop off only the amount needed
  1971.       screen(1,1)
  1972.       print("Chest Full, Try "..tries)
  1973.       chestFull = true
  1974.       biometrics()--To send that the chest is full
  1975.       tries = tries + 1
  1976.       sleep(2)
  1977.     end
  1978.     chestFull = false
  1979.   end
  1980. end
  1981.  
  1982. function midRunRefuel(i, allowed)
  1983.   allowed = allowed or allowedItems[i]
  1984.   local numToRefuel = turtle.getItemCount(i)-allowed
  1985.   if checkFuel() >= checkFuelLimit() then return true end --If it doesn't need fuel, then signal to not take more
  1986.   local firstCheck = checkFuel()
  1987.   if numToRefuel > 0 then turtle.refuel(1)  --This is so we can see how many fuel we need.
  1988.     else return false end --Bandaid solution: If won't refuel, don't try.
  1989.   local singleFuel
  1990.   if checkFuel() - firstCheck > 0 then singleFuel = checkFuel() - firstCheck else singleFuel = math.huge end --If fuel is 0, we want it to be huge so the below will result in 0 being taken
  1991.   --Refuel      The lesser of   max allowable or         remaining fuel space         /    either inf or a single fuel (which can be 0)
  1992.   turtle.refuel(math.min(numToRefuel-1, math.ceil((checkFuelLimit()-checkFuel()) / singleFuel))) --The refueling part of the the doRefuel option
  1993.   if checkFuel() >= checkFuelLimit() then return true end --Do not need any more fuel
  1994.   return false --Turtle can still be fueled
  1995. end
  1996.  
  1997. function enderRefuel() --Assumes a) An enderchest is in front of it b) It needs fuel
  1998.   local slot
  1999.   for a,b in ipairs(getSlotsTable()) do
  2000.     if b == 0 then slot = a; break end
  2001.   end
  2002.   if not slot then return false end --No room for fueling
  2003.   select(slot)
  2004.   repeat
  2005.     print("Required Fuel: ",checkFuelLimit())
  2006.     print("Current Fuel: ",checkFuel())
  2007.     local tries = 0
  2008.     while not turtle.suck() do
  2009.       sleep(1)
  2010.       statusString = "No Fuel in Ender Chest"
  2011.       biometrics() --Let user know that fuel chest is empty
  2012.       print(statusString,". Try: ",tries)
  2013.       tries = tries + 1
  2014.     end
  2015.     statusString = nil
  2016.   until midRunRefuel(slot, 0) --Returns true when should not refuel any more
  2017.   if not turtle.drop() then turtle.dropDown() end --If cannot put fuel back, just drop it, full fuel chest = user has too much fuel already
  2018.   return true -- :D
  2019. end
  2020.  
  2021.  
  2022. function drop(side, final, compareDump)
  2023.   side = sides[side] or "front"
  2024.   local dropFunc, detectFunc, dropFacing = turtle.drop, turtle.detect, facing+2
  2025.   if side == "top" then dropFunc, detectFunc = turtle.dropUp, turtle.detectUp end
  2026.   if side == "bottom" then dropFunc, detectFunc = turtle.dropDown, turtle.detectDown end
  2027.   if side == "right" then turnTo(1); dropFacing = 0 end
  2028.   if side == "left" then turnTo(3); dropFacing = 0 end
  2029.   local properFacing = facing --Capture the proper direction to be facing
  2030.  
  2031.   count(true) --Count number of items before drop. True means add. This is before chest detect, because could be final
  2032.  
  2033.   while not compareDump and not detectFunc() do
  2034.     if final then return end --If final, we don't need a chest to be placed, but there can be
  2035.     chestFull = true
  2036.     biometrics() --Let the user know there is a problem with chest
  2037.     screen(1,1) --Clear screen
  2038.     print("Waiting for chest placement on ",side," side (when facing quarry)")
  2039.     sleep(2)
  2040.   end
  2041.   chestFull = false
  2042.  
  2043.   local fuelSwitch = false --If doRefuel, this can switch so it won't overfuel
  2044.   for i=1,inventoryMax do
  2045.     --if final then allowedItems[i] = 0 end --0 items allowed in all slots if final ----It is already set to 1, so just remove comment if want change
  2046.     if turtle.getItemCount(i) > 0 then --Saves time, stops bugs
  2047.       if slot[i][1] == 1 and dumpCompareItems then turnTo(dropFacing) --Turn around to drop junk, not store it. dumpComapareItems is global config
  2048.       else turnTo(properFacing) --Turn back to proper position... or do nothing if already there
  2049.       end
  2050.       select(i)
  2051.       if slot[i][1] == 2 then --Intelligently refuels to fuel limit
  2052.         if doRefuel and not fuelSwitch then --Not in the conditional because we don't want to waitDrop excess fuel. Not a break so we can drop junk
  2053.           fuelSwitch = midRunRefuel(i)
  2054.         else
  2055.           waitDrop(i, allowedItems[i], dropFunc)
  2056.         end
  2057.         if fuelSwitch then
  2058.           waitDrop(i, allowedItems[i], dropFunc)
  2059.         end
  2060.       elseif not compareDump or (compareDump and slot[i][1] == 1) then --This stops all wanted items from being dropped off in a compareDump
  2061.         waitDrop(i, allowedItems[i], dropFunc)
  2062.       end
  2063.     end
  2064.   end
  2065.  
  2066.   if compareDump then
  2067.     for i=2, inventoryMax do
  2068.       if not specialSlots[i] then --We don't want to move buckets and things into earlier slots
  2069.         select(i)
  2070.         for j=1, i-1 do
  2071.           if turtle.getItemCount(i) == 0 then break end
  2072.           turtle.transferTo(j)
  2073.         end
  2074.       end
  2075.     end
  2076.     select(1)
  2077.   end
  2078.   if oldOreQuarry or compareDump then count(nil) end--Subtract the items still there if oreQuarry
  2079.   resetDumpSlots() --So that slots gone aren't counted as dump slots next
  2080.  
  2081.   select(1) --For fanciness sake
  2082.  
  2083. end
  2084.  
  2085. function dropOff() --Not local because called in mine()
  2086.   local currX,currZ,currY,currFacing = xPos, zPos, yPos, facing
  2087.   if careAboutResources then
  2088.     if not enderChest then --Regularly
  2089.       eventAdd("goto", 1,1,currY,2, "drop off") --Need this step for "-startDown"
  2090.       eventAdd('goto(0,1,1,2,"drop off")')
  2091.       eventAdd("drop", dropSide,false)
  2092.       eventAdd("turnTo(0)")
  2093.       eventAdd("mine",false,false,true,false)
  2094.       eventAdd("goto(1,1,1, 0)")
  2095.       eventAdd("goto", 1, 1, currY, 0)
  2096.       eventAdd("goto", currX,currZ,currY,currFacing)
  2097.     else --If using an enderChest
  2098.       if turtle.getItemCount(specialSlots.enderChest) ~= 1 then eventAdd("promptSpecialSlot('enderChest','Ender Chest')") end
  2099.       eventAdd("turnTo",currFacing-2)
  2100.       eventAdd("dig",false)
  2101.       eventAdd("select",specialSlots.enderChest)
  2102.       eventAdd("turtle.place")
  2103.       eventAdd("drop","front",false)
  2104.       eventAdd("turnTo",currFacing-2)
  2105.       eventAdd("select", specialSlots.enderChest)
  2106.       eventAdd("dig",false)
  2107.       eventAdd("turnTo",currFacing)
  2108.       eventAdd("select(1)")
  2109.     end
  2110.     runAllEvents()
  2111.     numDropOffs = numDropOffs + 1 --Analytics tracking
  2112.   end
  2113.   return true
  2114. end
  2115. function endingProcedure() --Used both at the end and in "biometrics"
  2116.   eventAdd("goto",1,1,yPos,2,"quarryStart") --Allows for startDown variable
  2117.   eventAdd("goto",0,1,1,2, "quarryStart") --Go back to base
  2118.   runAllEvents()
  2119.   --Output to a chest or sit there
  2120.   if enderChest then
  2121.     if dropSide == "right" then eventAdd("turnTo(1)") end --Turn to proper drop side
  2122.     if dropSide == "left" then eventAdd("turnTo(3)") end
  2123.     eventAdd("dig(false)") --This gets rid of a block in front of the turtle.
  2124.     eventAdd("select",specialSlots.enderChest)
  2125.     eventAdd("turtle.place")
  2126.     eventAdd("select(1)")
  2127.   end
  2128.   eventAdd("drop",dropSide, true)
  2129.   eventAdd("turnTo(0)")
  2130.  
  2131.   --Display was moved above to be used in bedrock function
  2132.   eventAdd("display")
  2133.   --Log current mining run
  2134.   eventAdd("logMiningRun",logExtension)
  2135.   toQuit = true --I'll use this flag to clean up (legacy)
  2136.   runAllEvents()
  2137. end
  2138. function bedrock()
  2139.   foundBedrock = true --Let everyone know
  2140.   if rednetEnabled then biometrics() end
  2141.   if checkFuel() == 0 then error("No Fuel",0) end
  2142.   local origin = {x = xPos, y = yPos, z = zPos}
  2143.   print("Bedrock Detected")
  2144.   if turtle.detectUp() and not turtle.digUp() then
  2145.     print("Block Above")
  2146.     turnTo(facing+2)
  2147.     repeat
  2148.       if not forward(false) then --Tries to go back out the way it came
  2149.         if not attck() then --Just making sure not mob-blocked
  2150.           if not dig() then --Now we know its bedrock
  2151.             turnTo(facing+1) --Try going a different direction
  2152.           end
  2153.         end
  2154.       end
  2155.     until not turtle.detectUp() or turtle.digUp() --These should be absolute and we don't care about about counting resources here.
  2156.   end
  2157.   up() --Go up two to avoid any bedrock.
  2158.   up()
  2159.   eventClear() --Get rid of any excess events that may be run. Don't want that.
  2160.   endingProcedure()
  2161.   print("\nFound bedrock at these coordinates: ")
  2162.   print(origin.x," Was position in row\n",origin.z," Was row in layer\n",origin.y," Blocks down from start")
  2163.   error("",0)
  2164. end
  2165.  
  2166. function endOfRowTurn(startZ, wasFacing, mineFunctionTable)
  2167. local halfFacing = ((layersDone % 2 == 1) and 1) or 3
  2168. local toFace = coterminal(wasFacing + 2) --Opposite side
  2169. if zPos == startZ then
  2170.   if facing ~= halfFacing then turnTo(halfFacing) end
  2171.   mine(unpack(mineFunctionTable or {}))
  2172. end
  2173. if facing ~= toFace then
  2174.   turnTo(toFace)
  2175. end
  2176. end
  2177.  
  2178.  
  2179. -------------------------------------------------------------------------------------
  2180. --Pre-Mining Stuff dealing with session persistence
  2181. runAllEvents()
  2182. if toQuit then error("",0) end --This means that it was stopped coming for its last drop
  2183.  
  2184. local doDigDown, doDigUp = (lastHeight ~= 1), (lastHeight == 0) --Used in lastHeight
  2185. if not restoreFoundSwitch then --Regularly
  2186.   --Check if it is a mining turtle
  2187.   if not isMiningTurtle then
  2188.     local a, b = turtle.dig()
  2189.     if a then
  2190.       mined = mined + 1
  2191.       isMiningTurtle = true
  2192.     elseif b == "Nothing to dig with" or b == "No tool to dig with" then
  2193.       print("This is not a mining turtle. To make a mining turtle, craft me together with a diamond pickaxe")
  2194.       error("",0)
  2195.     end
  2196.   end
  2197.  
  2198.   if checkFuel() == 0 then --Some people forget to start their turtles with fuel
  2199.     screen(1,1)
  2200.     print("I have no fuel and doCheckFuel is off!")
  2201.     print("Starting emergency fueling procedures!\n")
  2202.     emergencyRefuel()
  2203.     if checkFuel() == 0 then
  2204.       print("I have no fuel and can't get more!")
  2205.       print("Try using -doRefuel or -fuelChest")
  2206.       print("I have no choice but to quit.")
  2207.       error("",0)
  2208.     end
  2209.   end
  2210.  
  2211.   mine(false,false,true) --Get into quarry by going forward one
  2212.   if gpsEnabled and not restoreFoundSwitch then --The initial locate is done in the arguments. This is so I can figure out what quadrant the turtle is in.
  2213.     gpsSecondPos = {gps.locate(gpsTimeout)} --Note: Does not run this if it has already been restarted.
  2214.   end
  2215.   for i = 1, startDown do
  2216.     eventAdd("down") --Add a bunch of down events to get to where it needs to be.
  2217.   end
  2218.   runAllEvents()
  2219.   if flatBedrock then
  2220.     while (detectDown() and digDown(false, true)) or not detectDown() do --None of these functions are non-invert protected because inverse always false here
  2221.       down()
  2222.       startDown = startDown + 1
  2223.     end
  2224.     startDown = startDown - y + 1
  2225.     for i=1, y-2 do
  2226.       up() --It has hit bedrock, now go back up for proper 3 wide mining
  2227.     end
  2228.   elseif not(y == 1 or y == 2) then
  2229.     down() --Go down to align properly. If y is one or two, it doesn't need to do this.
  2230.   end
  2231. else --restore found
  2232.   if not(layersDone == layers and not doDigDown) then digDown() end
  2233.   if not(layersDone == layers and not doDigUp) then digUp() end  --Get blocks missed before stopped
  2234. end
  2235. --Mining Loops--------------------------------------------------------------------------
  2236. select(1)
  2237. while layersDone <= layers do -------------Height---------
  2238. local lastLayer = layersDone == layers --If this is the last layer
  2239. local secondToLastLayer = (layersDone + 1) == layers --This is a check for going down at the end of a layer.
  2240. moved = moved + 1 --To account for the first position in row as "moved"
  2241. if not(layersDone == layers and not doDigDown) then digDown() end --This is because it doesn't mine first block in layer
  2242. if not restoreFoundSwitch and layersDone % 2 == 1 then rowCheck = true end
  2243. relxCalc()
  2244. while relzPos <= z do -------------Width----------
  2245. while relxPos < x do ------------Length---------
  2246. mine(not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)) --This will be the idiom that I use for the mine function
  2247. end ---------------Length End-------
  2248. if relzPos ~= z then --If not on last row of section
  2249.   local func
  2250.   if rowCheck == true then --Switching to next row
  2251.   func = "right"; rowCheck = false; else func = false; rowCheck = true end --Which way to turn
  2252.     eventAdd("endOfRowTurn", zPos, facing , {not lastLayer or (doDigDown and lastLayer), not lastLayer or (doDigUp and lastLayer)}) --The table is passed to the mine function
  2253.     runAllEvents()
  2254. else break
  2255. end
  2256. end ---------------Width End--------
  2257. if layersDone % 2 == 0 then --Will only go back to start on non-even layers
  2258.   eventAdd("goto",1,1,yPos,0, "layerStart") --Goto start of layer
  2259. else
  2260.   eventAdd("turnTo",coterminal(facing-2))
  2261. end
  2262. if not lastLayer then --If there is another layer
  2263.   for i=1, 2+fromBoolean(not(lastHeight~=0 and secondToLastLayer)) do eventAdd("down()") end --The fromBoolean stuff means that if lastheight is 1 and last and layer, will only go down two
  2264. end
  2265. eventAdd("relxCalc")
  2266. layersDone = layersDone + 1
  2267. restoreFoundSwitch = false --This is done so that rowCheck works properly upon restore
  2268. runAllEvents()
  2269. end ---------------Height End-------
  2270.  
  2271. endingProcedure() --This takes care of getting to start, dropping in chest, and displaying ending screen
  2272.  
Add Comment
Please, Sign In to add comment