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