Advertisement
Guest User

3dprint.lua

a guest
Aug 18th, 2016
15,899
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 8.70 KB | None | 0 0
  1. -- Libraries
  2. local component = require("component")
  3. local fs = require("filesystem")
  4. local serial = require("serialization")
  5. local text = require("text")
  6. local shell = require("shell")
  7. local term = require("term")
  8. -- Componentes
  9. local gpu = component.gpu
  10. local printer = nil
  11. -- Constants
  12. local PROGRESS_BAR_LENGTH = 30
  13. local SCREEN_X, SCREEN_Y = gpu.getResolution()
  14. local WAITING = 2
  15. local COPIES = 1
  16. -- Global variables
  17. local args = shell.parse(...)
  18. -- Functions
  19. function normalizeModel(model)
  20.   local nModel = {}
  21.   for _, i in pairs(model) do
  22.     if (#i.shapes > 0) then
  23.       table.insert(nModel, i)
  24.     end
  25.   end
  26.   return nModel
  27. end
  28.  
  29. function getArgumnet(index)
  30.   if ((#args > 0) and (#args >= index)) then
  31.     return args[index]
  32.   else
  33.     return nil
  34.   end
  35. end
  36.  
  37. function getFile(text)
  38.   if (fs.exists(text)) then
  39.     return text
  40.   else
  41.     if (fs.exists(shell.getWorkingDirectory() .. "/" .. text)) then
  42.       return shell.getWorkingDirectory() .. "/" .. text
  43.     end
  44.   end
  45.   return nil
  46. end
  47.  
  48. function getModel(path)
  49.   local object
  50.   if (fs.exists(path)) then
  51.     local text = ""
  52.     local file = fs.open(path)
  53.     while true do
  54.       local temp = file:read(9999999)
  55.       if (temp) then
  56.         text = text .. temp
  57.       else
  58.         break
  59.       end
  60.     end
  61.     text2 = "{" .. text .. "}"
  62.     object = serial.unserialize(text2)
  63.     if (object) then
  64.       if (#object > 1) then
  65.       return true, serial.unserialize(text2)
  66.     else
  67.       return true, serial.unserialize(text)
  68.     end
  69.     else
  70.       return false, "Ошибка чтения файла! Файл поврежден!"
  71.     end
  72.   else
  73.     return false, "Файл по указанному пути не найден!"
  74.   end
  75. end
  76.  
  77. function isValid(model)
  78.   if (model.shapes) then
  79.     return true, "SIMPLE"
  80.   else
  81.     for _, i in pairs(model) do
  82.       if (not i.shapes) then
  83.         return false
  84.       end
  85.     end
  86.     return true, "ADVANCED"
  87.   end
  88. end
  89.  
  90. function getBar(status)
  91.   local bar = ""
  92.   if (status == 100) then
  93.     for i = 1,PROGRESS_BAR_LENGTH do
  94.       bar = bar .. "="
  95.     end
  96.   else
  97.     local one = 100 / PROGRESS_BAR_LENGTH
  98.     local prg = status / one
  99.     for i = 1,prg do
  100.       bar = bar .. "="
  101.     end
  102.     bar = text.padRight(bar, PROGRESS_BAR_LENGTH)
  103.   end
  104.   return bar
  105. end
  106.  
  107. function write(text)
  108.   local x, y = term.getCursor()
  109.   term.setCursor(1, y)
  110.   term.write(text)
  111. end
  112.  
  113. function drawStatus(modelName, count, status, length)
  114.   if (status == -1) then
  115.     write(text.padRight(text.padRight("[" .. count .. "] ", length + 3) .. modelName .. ": [" .. text.padRight("", PROGRESS_BAR_LENGTH) .. "] 0%   Подготовка...", SCREEN_X))
  116.   elseif ((status < 100) and (status >= 0)) then
  117.     write(text.padRight(text.padRight("[" .. count .. "] ", length + 3) .. modelName .. ": [" .. getBar(status) .. "] " .. text.padRight(tostring(status) .. "%", 4) .. " Печать...", SCREEN_X))
  118.   elseif (status == 100) then
  119.     write(text.padRight(text.padRight("[" .. count .. "] ", length + 3) .. modelName .. ": [" .. getBar(status) .. "] 100% Распечатано.", SCREEN_X))
  120.   end
  121. end
  122.  
  123. function setupShapes(shapes)
  124.   for _, shape in pairs(shapes) do
  125.     printer.addShape(shape[1], shape[2], shape[3], shape[4], shape[5], shape[6], shape.texture, shape.state, shape.tint)
  126.   end
  127. end
  128.  
  129. function setupPrinter(model, count)
  130.   printer.reset()
  131.   if (model.label) then printer.setLabel(model.label) end
  132.   if (model.tooltip) then printer.setTooltip("[" .. count .. "] " .. model.tooltip) else printer.setTooltip("[" .. count .. "]") end
  133.   if (model.emitRedstone) then printer.setRedstoneEmitter(model.emitRedstone) end
  134.   if (model.buttonMode) then printer.setButtonMode(model.buttonMode) end
  135.   if (model.shapes) then setupShapes(model.shapes) end
  136. end
  137.  
  138. function printModel(model, count, length)
  139.   setupPrinter(model, count)
  140.   local status, valid = printer.status()
  141.   if (not valid) then
  142.     if (#model.shapes > printer.getMaxShapeCount()) then
  143.       write(text.padRight("[" .. count .. "] ", length + 3) .. "Печать модели: '" .. model.label .. "' невозможно, всвязи с превышением кол-ва shape'ов!")
  144.     else
  145.       write(text.padRight("[" .. count .. "] ", length + 3) .. "Печать модели: '" .. model.label .. "' (" .. count .. ") невозможно! Пропуск...")
  146.     end
  147.   else
  148.     drawStatus(model.label, count, -1, length)
  149.     os.sleep(WAITING)
  150.     if (not printer.commit(1)) then
  151.       return false, "В принтере закончились материалы для создания 3D модели."
  152.     end
  153.     while true do
  154.       local status, progress = printer.status()
  155.       if (status == "idle") then
  156.         drawStatus(model.label, count, 100, length)
  157.         break
  158.       elseif (status == "busy") then
  159.         drawStatus(model.label, count, progress, length)
  160.       end
  161.     end
  162.   end
  163.   io.write("\n")
  164.   return true, 1
  165. end
  166.  
  167. function printModels(models)
  168.   for i, model in pairs(models) do
  169.     local status, reason = printModel(model, i, string.len(tostring(#models)))
  170.     if (not status) then
  171.       return false, i, model.label, reason
  172.     end
  173.   end
  174.   return true, #models
  175. end
  176.  
  177. -- Check system requirements
  178. print("Активация...")
  179. print("Чтение аргументов...")
  180. if (getArgumnet(3)) then COPIES = tonumber(getArgumnet(3)) end
  181. if (COPIES > 1) then print("Будет произведена печать " .. COPIES .. " копий указанной 3D модели!") end
  182.  
  183. for i = 1,COPIES do
  184.   print("\nПечать " .. i .. " копии...")
  185.   if (not component.isAvailable("printer3d")) then
  186.     print("Для использования программы необходим 3D принтер.")
  187.     print("Подключите 3D принтер и перезапустите программу.")
  188.   else
  189.     printer = component.printer3d
  190.     if (getArgumnet(2)) then WAITING = tonumber(getArgumnet(2)) end
  191.     print("Поиск файла...")
  192.     if (getArgumnet(1)) then
  193.       print("Чтение файла...")
  194.       local file = getFile(getArgumnet(1))
  195.       if (file) then
  196.         local status, model = getModel(file)
  197.         if (status) then
  198.           print("Загрузка модели завершена!")
  199.           print("Валидация...")
  200.           local status, modelType = isValid(model)
  201.           if (status) then
  202.             print("Модель прошла проверку!")        
  203.             if (modelType == "ADVANCED") then
  204.               if (not getArgumnet(4)) then
  205.                 print("Сложность модели: " .. #model .. " объектов.")
  206.                 print("Печать...")
  207.                 local status, count, name, reason = printModels(normalizeModel(model))
  208.                 if (status) then
  209.                   print("Печать завершена. Напечатано " .. count .. " моделей!")
  210.                 else
  211.                   print("Ошибка печати на модели: '" .. name .. "' (" .. count .. "). Ошибка: " .. reason)
  212.                 end
  213.               else
  214.                 print("Печать указанного объекта модели...")
  215.                 print("Выбранный объект: " .. normalizeModel(model)[tonumber(getArgumnet(4))].label .. " (" .. getArgumnet(4) .. ")")
  216.                 print("Печать...")
  217.               local status, reason = printModel(normalizeModel(model)[tonumber(getArgumnet(4))], tonumber(getArgumnet(4)), string.len(getArgumnet(4)))
  218.               if (status) then
  219.                 print("Печать завершена!")
  220.               else
  221.                 print("Ошибка печати на модели: '" .. name .. "'. Ошибка: " .. reason)
  222.               end
  223.               end
  224.             elseif (modelType == "SIMPLE") then
  225.               print("Сложность модели: 1 объект.")
  226.               print("Печать...")
  227.               local status, reason = printModel(model, 1, 1)
  228.               if (status) then
  229.                 print("Печать завершена. Напечатана 1 модель!")
  230.               else
  231.                 print("Ошибка печати на модели: '" .. name .. "'. Ошибка: " .. reason)
  232.               end
  233.             end
  234.           else
  235.             print("Файл не является шаблоном 3D модели или поврежден!")
  236.             print("Вероятно проблема в том, что в одной из моделей отсутствует хотя бы один shape!")
  237.           end
  238.         else
  239.           print("Ошибка чтения файла! Ошибка: " .. model)
  240.         end
  241.       else
  242.         print("Ошибка! Файл не найден!")
  243.       end
  244.     else
  245.       print("Укажите путь к модели!")
  246.       print("Пример: 3dprint /home/model.3dm")
  247.     end
  248.   end
  249. end
  250.  
  251. print("\nЗавершение печати...")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement