Stretch.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. # This PostProcessingPlugin script is released under the terms of the AGPLv3 or higher.
  2. """
  3. Copyright (c) 2017 Christophe Baribaud 2017
  4. Python implementation of https://github.com/electrocbd/post_stretch
  5. Correction of hole sizes, cylinder diameters and curves
  6. See the original description in https://github.com/electrocbd/post_stretch
  7. WARNING This script has never been tested with several extruders
  8. """
  9. from ..Script import Script
  10. import numpy as np
  11. from UM.Logger import Logger
  12. from UM.Application import Application
  13. import re
  14. from cura.Settings.ExtruderManager import ExtruderManager
  15. def _getValue(line, key, default=None):
  16. """
  17. Convenience function that finds the value in a line of g-code.
  18. When requesting key = x from line "G1 X100" the value 100 is returned.
  19. It is a copy of Stript's method, so it is no DontRepeatYourself, but
  20. I split the class into setup part (Stretch) and execution part (Strecher)
  21. and only the setup part inherits from Script
  22. """
  23. if not key in line or (";" in line and line.find(key) > line.find(";")):
  24. return default
  25. sub_part = line[line.find(key) + 1:]
  26. number = re.search(r"^-?[0-9]+\.?[0-9]*", sub_part)
  27. if number is None:
  28. return default
  29. return float(number.group(0))
  30. class GCodeStep():
  31. """
  32. Class to store the current value of each G_Code parameter
  33. for any G-Code step
  34. """
  35. def __init__(self, step, in_relative_movement: bool = False):
  36. self.step = step
  37. self.step_x = 0
  38. self.step_y = 0
  39. self.step_z = 0
  40. self.step_e = 0
  41. self.step_f = 0
  42. self.in_relative_movement = in_relative_movement
  43. self.comment = ""
  44. def readStep(self, line):
  45. """
  46. Reads gcode from line into self
  47. """
  48. if not self.in_relative_movement:
  49. self.step_x = _getValue(line, "X", self.step_x)
  50. self.step_y = _getValue(line, "Y", self.step_y)
  51. self.step_z = _getValue(line, "Z", self.step_z)
  52. self.step_e = _getValue(line, "E", self.step_e)
  53. self.step_f = _getValue(line, "F", self.step_f)
  54. else:
  55. delta_step_x = _getValue(line, "X", 0)
  56. delta_step_y = _getValue(line, "Y", 0)
  57. delta_step_z = _getValue(line, "Z", 0)
  58. delta_step_e = _getValue(line, "E", 0)
  59. self.step_x += delta_step_x
  60. self.step_y += delta_step_y
  61. self.step_z += delta_step_z
  62. self.step_e += delta_step_e
  63. self.step_f = _getValue(line, "F", self.step_f) # the feedrate is not relative
  64. def copyPosFrom(self, step):
  65. """
  66. Copies positions of step into self
  67. """
  68. self.step_x = step.step_x
  69. self.step_y = step.step_y
  70. self.step_z = step.step_z
  71. self.step_e = step.step_e
  72. self.step_f = step.step_f
  73. self.comment = step.comment
  74. def setInRelativeMovement(self, value: bool) -> None:
  75. self.in_relative_movement = value
  76. # Execution part of the stretch plugin
  77. class Stretcher():
  78. """
  79. Execution part of the stretch algorithm
  80. """
  81. def __init__(self, line_width, wc_stretch, pw_stretch):
  82. self.line_width = line_width
  83. self.wc_stretch = wc_stretch
  84. self.pw_stretch = pw_stretch
  85. if self.pw_stretch > line_width / 4:
  86. self.pw_stretch = line_width / 4 # Limit value of pushwall stretch distance
  87. self.outpos = GCodeStep(0)
  88. self.vd1 = np.empty((0, 2)) # Start points of segments
  89. # of already deposited material for current layer
  90. self.vd2 = np.empty((0, 2)) # End points of segments
  91. # of already deposited material for current layer
  92. self.layer_z = 0 # Z position of the extrusion moves of the current layer
  93. self.layergcode = ""
  94. self._in_relative_movement = False
  95. def execute(self, data):
  96. """
  97. Computes the new X and Y coordinates of all g-code steps
  98. """
  99. Logger.log("d", "Post stretch with line width " + str(self.line_width)
  100. + "mm wide circle stretch " + str(self.wc_stretch)+ "mm"
  101. + " and push wall stretch " + str(self.pw_stretch) + "mm")
  102. retdata = []
  103. layer_steps = []
  104. in_relative_movement = False
  105. current = GCodeStep(0, in_relative_movement)
  106. self.layer_z = 0.
  107. current_e = 0.
  108. for layer in data:
  109. lines = layer.rstrip("\n").split("\n")
  110. for line in lines:
  111. current.comment = ""
  112. if line.find(";") >= 0:
  113. current.comment = line[line.find(";"):]
  114. if _getValue(line, "G") == 0:
  115. current.readStep(line)
  116. onestep = GCodeStep(0, in_relative_movement)
  117. onestep.copyPosFrom(current)
  118. elif _getValue(line, "G") == 1:
  119. current.readStep(line)
  120. onestep = GCodeStep(1, in_relative_movement)
  121. onestep.copyPosFrom(current)
  122. # end of relative movement
  123. elif _getValue(line, "G") == 90:
  124. in_relative_movement = False
  125. current.setInRelativeMovement(in_relative_movement)
  126. # start of relative movement
  127. elif _getValue(line, "G") == 91:
  128. in_relative_movement = True
  129. current.setInRelativeMovement(in_relative_movement)
  130. elif _getValue(line, "G") == 92:
  131. current.readStep(line)
  132. onestep = GCodeStep(-1, in_relative_movement)
  133. onestep.copyPosFrom(current)
  134. onestep.comment = line
  135. else:
  136. onestep = GCodeStep(-1, in_relative_movement)
  137. onestep.copyPosFrom(current)
  138. onestep.comment = line
  139. if line.find(";LAYER:") >= 0 and len(layer_steps):
  140. # Previous plugin "forgot" to separate two layers...
  141. Logger.log("d", "Layer Z " + "{:.3f}".format(self.layer_z)
  142. + " " + str(len(layer_steps)) + " steps")
  143. retdata.append(self.processLayer(layer_steps))
  144. layer_steps = []
  145. layer_steps.append(onestep)
  146. # self.layer_z is the z position of the last extrusion move (not travel move)
  147. if current.step_z != self.layer_z and current.step_e != current_e:
  148. self.layer_z = current.step_z
  149. current_e = current.step_e
  150. if len(layer_steps): # Force a new item in the array
  151. Logger.log("d", "Layer Z " + "{:.3f}".format(self.layer_z)
  152. + " " + str(len(layer_steps)) + " steps")
  153. retdata.append(self.processLayer(layer_steps))
  154. layer_steps = []
  155. retdata.append(";Wide circle stretch distance " + str(self.wc_stretch) + "\n")
  156. retdata.append(";Push wall stretch distance " + str(self.pw_stretch) + "\n")
  157. return retdata
  158. def extrusionBreak(self, layer_steps, i_pos):
  159. """
  160. Returns true if the command layer_steps[i_pos] breaks the extruded filament
  161. i.e. it is a travel move
  162. """
  163. if i_pos == 0:
  164. return True # Begining a layer always breaks filament (for simplicity)
  165. step = layer_steps[i_pos]
  166. prev_step = layer_steps[i_pos - 1]
  167. if step.step_e != prev_step.step_e:
  168. return False
  169. delta_x = step.step_x - prev_step.step_x
  170. delta_y = step.step_y - prev_step.step_y
  171. if delta_x * delta_x + delta_y * delta_y < self.line_width * self.line_width / 4:
  172. # This is a very short movement, less than 0.5 * line_width
  173. # It does not break filament, we should stay in the same extrusion sequence
  174. return False
  175. return True # New sequence
  176. def processLayer(self, layer_steps):
  177. """
  178. Computes the new coordinates of g-code steps
  179. for one layer (all the steps at the same Z coordinate)
  180. """
  181. self.outpos.step_x = -1000 # Force output of X and Y coordinates
  182. self.outpos.step_y = -1000 # at each start of layer
  183. self.layergcode = ""
  184. self.vd1 = np.empty((0, 2))
  185. self.vd2 = np.empty((0, 2))
  186. orig_seq = np.empty((0, 2))
  187. modif_seq = np.empty((0, 2))
  188. iflush = 0
  189. for i, step in enumerate(layer_steps):
  190. if step.step == 0 or step.step == 1:
  191. if self.extrusionBreak(layer_steps, i):
  192. # No extrusion since the previous step, so it is a travel move
  193. # Let process steps accumulated into orig_seq,
  194. # which are a sequence of continuous extrusion
  195. modif_seq = np.copy(orig_seq)
  196. if len(orig_seq) >= 2:
  197. self.workOnSequence(orig_seq, modif_seq)
  198. self.generate(layer_steps, iflush, i, modif_seq)
  199. iflush = i
  200. orig_seq = np.empty((0, 2))
  201. orig_seq = np.concatenate([orig_seq, np.array([[step.step_x, step.step_y]])])
  202. if len(orig_seq):
  203. modif_seq = np.copy(orig_seq)
  204. if len(orig_seq) >= 2:
  205. self.workOnSequence(orig_seq, modif_seq)
  206. self.generate(layer_steps, iflush, len(layer_steps), modif_seq)
  207. return self.layergcode
  208. def stepToGcode(self, onestep):
  209. """
  210. Converts a step into G-Code
  211. For each of the X, Y, Z, E and F parameter,
  212. the parameter is written only if its value changed since the
  213. previous g-code step.
  214. """
  215. sout = ""
  216. if onestep.step_f != self.outpos.step_f:
  217. self.outpos.step_f = onestep.step_f
  218. sout += " F{:.0f}".format(self.outpos.step_f).rstrip(".")
  219. if onestep.step_x != self.outpos.step_x or onestep.step_y != self.outpos.step_y:
  220. assert onestep.step_x >= -1000 and onestep.step_x < 1000 # If this assertion fails,
  221. # something went really wrong !
  222. self.outpos.step_x = onestep.step_x
  223. sout += " X{:.3f}".format(self.outpos.step_x).rstrip("0").rstrip(".")
  224. assert onestep.step_y >= -1000 and onestep.step_y < 1000 # If this assertion fails,
  225. # something went really wrong !
  226. self.outpos.step_y = onestep.step_y
  227. sout += " Y{:.3f}".format(self.outpos.step_y).rstrip("0").rstrip(".")
  228. if onestep.step_z != self.outpos.step_z or onestep.step_z != self.layer_z:
  229. self.outpos.step_z = onestep.step_z
  230. sout += " Z{:.3f}".format(self.outpos.step_z).rstrip("0").rstrip(".")
  231. if onestep.step_e != self.outpos.step_e:
  232. self.outpos.step_e = onestep.step_e
  233. sout += " E{:.5f}".format(self.outpos.step_e).rstrip("0").rstrip(".")
  234. return sout
  235. def generate(self, layer_steps, ibeg, iend, orig_seq):
  236. """
  237. Appends g-code lines to the plugin's returned string
  238. starting from step ibeg included and until step iend excluded
  239. """
  240. ipos = 0
  241. for i in range(ibeg, iend):
  242. if layer_steps[i].step == 0:
  243. layer_steps[i].step_x = orig_seq[ipos][0]
  244. layer_steps[i].step_y = orig_seq[ipos][1]
  245. sout = "G0" + self.stepToGcode(layer_steps[i])
  246. self.layergcode = self.layergcode + sout + "\n"
  247. ipos = ipos + 1
  248. elif layer_steps[i].step == 1:
  249. layer_steps[i].step_x = orig_seq[ipos][0]
  250. layer_steps[i].step_y = orig_seq[ipos][1]
  251. sout = "G1" + self.stepToGcode(layer_steps[i])
  252. self.layergcode = self.layergcode + sout + "\n"
  253. ipos = ipos + 1
  254. else:
  255. self.layergcode = self.layergcode + layer_steps[i].comment + "\n"
  256. def workOnSequence(self, orig_seq, modif_seq):
  257. """
  258. Computes new coordinates for a sequence
  259. A sequence is a list of consecutive g-code steps
  260. of continuous material extrusion
  261. """
  262. d_contact = self.line_width / 2.0
  263. if (len(orig_seq) > 2 and
  264. ((orig_seq[len(orig_seq) - 1] - orig_seq[0]) ** 2).sum(0) < d_contact * d_contact):
  265. # Starting and ending point of the sequence are nearby
  266. # It is a closed loop
  267. #self.layergcode = self.layergcode + ";wideCircle\n"
  268. self.wideCircle(orig_seq, modif_seq)
  269. else:
  270. #self.layergcode = self.layergcode + ";wideTurn\n"
  271. self.wideTurn(orig_seq, modif_seq) # It is an open curve
  272. if len(orig_seq) > 6: # Don't try push wall on a short sequence
  273. self.pushWall(orig_seq, modif_seq)
  274. if len(orig_seq):
  275. self.vd1 = np.concatenate([self.vd1, np.array(orig_seq[:-1])])
  276. self.vd2 = np.concatenate([self.vd2, np.array(orig_seq[1:])])
  277. def wideCircle(self, orig_seq, modif_seq):
  278. """
  279. Similar to wideTurn
  280. The first and last point of the sequence are the same,
  281. so it is possible to extend the end of the sequence
  282. with its beginning when seeking for triangles
  283. It is necessary to find the direction of the curve, knowing three points (a triangle)
  284. If the triangle is not wide enough, there is a huge risk of finding
  285. an incorrect orientation, due to insufficient accuracy.
  286. So, when the consecutive points are too close, the method
  287. use following and preceding points to form a wider triangle around
  288. the current point
  289. dmin_tri is the minimum distance between two consecutive points
  290. of an acceptable triangle
  291. """
  292. dmin_tri = 0.5
  293. iextra_base = np.floor_divide(len(orig_seq), 3) # Nb of extra points
  294. ibeg = 0 # Index of first point of the triangle
  295. iend = 0 # Index of the third point of the triangle
  296. for i, step in enumerate(orig_seq):
  297. if i == 0 or i == len(orig_seq) - 1:
  298. # First and last point of the sequence are the same,
  299. # so it is necessary to skip one of these two points
  300. # when creating a triangle containing the first or the last point
  301. iextra = iextra_base + 1
  302. else:
  303. iextra = iextra_base
  304. # i is the index of the second point of the triangle
  305. # pos_after is the array of positions of the original sequence
  306. # after the current point
  307. pos_after = np.resize(np.roll(orig_seq, -i-1, 0), (iextra, 2))
  308. # Vector of distances between the current point and each following point
  309. dist_from_point = ((step - pos_after) ** 2).sum(1)
  310. if np.amax(dist_from_point) < dmin_tri * dmin_tri:
  311. continue
  312. iend = np.argmax(dist_from_point >= dmin_tri * dmin_tri)
  313. # pos_before is the array of positions of the original sequence
  314. # before the current point
  315. pos_before = np.resize(np.roll(orig_seq, -i, 0)[::-1], (iextra, 2))
  316. # This time, vector of distances between the current point and each preceding point
  317. dist_from_point = ((step - pos_before) ** 2).sum(1)
  318. if np.amax(dist_from_point) < dmin_tri * dmin_tri:
  319. continue
  320. ibeg = np.argmax(dist_from_point >= dmin_tri * dmin_tri)
  321. # See https://github.com/electrocbd/post_stretch for explanations
  322. # relpos is the relative position of the projection of the second point
  323. # of the triangle on the segment from the first to the third point
  324. # 0 means the position of the first point, 1 means the position of the third,
  325. # intermediate values are positions between
  326. length_base = ((pos_after[iend] - pos_before[ibeg]) ** 2).sum(0)
  327. relpos = ((step - pos_before[ibeg])
  328. * (pos_after[iend] - pos_before[ibeg])).sum(0)
  329. if np.fabs(relpos) < 1000.0 * np.fabs(length_base):
  330. relpos /= length_base
  331. else:
  332. relpos = 0.5 # To avoid division by zero or precision loss
  333. projection = (pos_before[ibeg] + relpos * (pos_after[iend] - pos_before[ibeg]))
  334. dist_from_proj = np.sqrt(((projection - step) ** 2).sum(0))
  335. if dist_from_proj > 0.0003: # Move central point only if points are not aligned
  336. modif_seq[i] = (step - (self.wc_stretch / dist_from_proj)
  337. * (projection - step))
  338. return
  339. def wideTurn(self, orig_seq, modif_seq):
  340. '''
  341. We have to select three points in order to form a triangle
  342. These three points should be far enough from each other to have
  343. a reliable estimation of the orientation of the current turn
  344. '''
  345. dmin_tri = self.line_width / 2.0
  346. ibeg = 0
  347. iend = 2
  348. for i in range(1, len(orig_seq) - 1):
  349. dist_from_point = ((orig_seq[i] - orig_seq[i+1:]) ** 2).sum(1)
  350. if np.amax(dist_from_point) < dmin_tri * dmin_tri:
  351. continue
  352. iend = i + 1 + np.argmax(dist_from_point >= dmin_tri * dmin_tri)
  353. dist_from_point = ((orig_seq[i] - orig_seq[i-1::-1]) ** 2).sum(1)
  354. if np.amax(dist_from_point) < dmin_tri * dmin_tri:
  355. continue
  356. ibeg = i - 1 - np.argmax(dist_from_point >= dmin_tri * dmin_tri)
  357. length_base = ((orig_seq[iend] - orig_seq[ibeg]) ** 2).sum(0)
  358. relpos = ((orig_seq[i] - orig_seq[ibeg]) * (orig_seq[iend] - orig_seq[ibeg])).sum(0)
  359. if np.fabs(relpos) < 1000.0 * np.fabs(length_base):
  360. relpos /= length_base
  361. else:
  362. relpos = 0.5
  363. projection = orig_seq[ibeg] + relpos * (orig_seq[iend] - orig_seq[ibeg])
  364. dist_from_proj = np.sqrt(((projection - orig_seq[i]) ** 2).sum(0))
  365. if dist_from_proj > 0.001:
  366. modif_seq[i] = (orig_seq[i] - (self.wc_stretch / dist_from_proj)
  367. * (projection - orig_seq[i]))
  368. return
  369. def pushWall(self, orig_seq, modif_seq):
  370. """
  371. The algorithm tests for each segment if material was
  372. already deposited at one or the other side of this segment.
  373. If material was deposited at one side but not both,
  374. the segment is moved into the direction of the deposited material,
  375. to "push the wall"
  376. Already deposited material is stored as segments.
  377. vd1 is the array of the starting points of the segments
  378. vd2 is the array of the ending points of the segments
  379. For example, segment nr 8 starts at position self.vd1[8]
  380. and ends at position self.vd2[8]
  381. """
  382. dist_palp = self.line_width # Palpation distance to seek for a wall
  383. mrot = np.array([[0, -1], [1, 0]]) # Rotation matrix for a quarter turn
  384. for i in range(len(orig_seq)):
  385. ibeg = i # Index of the first point of the segment
  386. iend = i + 1 # Index of the last point of the segment
  387. if iend == len(orig_seq):
  388. iend = i - 1
  389. xperp = np.dot(mrot, orig_seq[iend] - orig_seq[ibeg])
  390. xperp = xperp / np.sqrt((xperp ** 2).sum(-1))
  391. testleft = orig_seq[ibeg] + xperp * dist_palp
  392. materialleft = False # Is there already extruded material at the left of the segment
  393. testright = orig_seq[ibeg] - xperp * dist_palp
  394. materialright = False # Is there already extruded material at the right of the segment
  395. if self.vd1.shape[0]:
  396. relpos = np.clip(((testleft - self.vd1) * (self.vd2 - self.vd1)).sum(1)
  397. / ((self.vd2 - self.vd1) * (self.vd2 - self.vd1)).sum(1), 0., 1.)
  398. nearpoints = self.vd1 + relpos[:, np.newaxis] * (self.vd2 - self.vd1)
  399. # nearpoints is the array of the nearest points of each segment
  400. # from the point testleft
  401. dist = ((testleft - nearpoints) * (testleft - nearpoints)).sum(1)
  402. # dist is the array of the squares of the distances between testleft
  403. # and each segment
  404. if np.amin(dist) <= dist_palp * dist_palp:
  405. materialleft = True
  406. # Now the same computation with the point testright at the other side of the
  407. # current segment
  408. relpos = np.clip(((testright - self.vd1) * (self.vd2 - self.vd1)).sum(1)
  409. / ((self.vd2 - self.vd1) * (self.vd2 - self.vd1)).sum(1), 0., 1.)
  410. nearpoints = self.vd1 + relpos[:, np.newaxis] * (self.vd2 - self.vd1)
  411. dist = ((testright - nearpoints) * (testright - nearpoints)).sum(1)
  412. if np.amin(dist) <= dist_palp * dist_palp:
  413. materialright = True
  414. if materialleft and not materialright:
  415. modif_seq[ibeg] = modif_seq[ibeg] + xperp * self.pw_stretch
  416. elif not materialleft and materialright:
  417. modif_seq[ibeg] = modif_seq[ibeg] - xperp * self.pw_stretch
  418. # Setup part of the stretch plugin
  419. class Stretch(Script):
  420. """
  421. Setup part of the stretch algorithm
  422. The only parameter is the stretch distance
  423. """
  424. def __init__(self):
  425. super().__init__()
  426. def getSettingDataString(self):
  427. return """{
  428. "name":"Post stretch script",
  429. "key": "Stretch",
  430. "metadata": {},
  431. "version": 2,
  432. "settings":
  433. {
  434. "wc_stretch":
  435. {
  436. "label": "Wide circle stretch distance",
  437. "description": "Distance by which the points are moved by the correction effect in corners. The higher this value, the higher the effect",
  438. "unit": "mm",
  439. "type": "float",
  440. "default_value": 0.1,
  441. "minimum_value": 0,
  442. "minimum_value_warning": 0,
  443. "maximum_value_warning": 0.2
  444. },
  445. "pw_stretch":
  446. {
  447. "label": "Push Wall stretch distance",
  448. "description": "Distance by which the points are moved by the correction effect when two lines are nearby. The higher this value, the higher the effect",
  449. "unit": "mm",
  450. "type": "float",
  451. "default_value": 0.1,
  452. "minimum_value": 0,
  453. "minimum_value_warning": 0,
  454. "maximum_value_warning": 0.2
  455. }
  456. }
  457. }"""
  458. def execute(self, data):
  459. """
  460. Entry point of the plugin.
  461. data is the list of original g-code instructions,
  462. the returned string is the list of modified g-code instructions
  463. """
  464. stretcher = Stretcher(
  465. ExtruderManager.getInstance().getActiveExtruderStack().getProperty("machine_nozzle_size", "value")
  466. , self.getSettingValueByKey("wc_stretch"), self.getSettingValueByKey("pw_stretch"))
  467. return stretcher.execute(data)