serafim7

3dprint [OpenComputers]

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