-
Notifications
You must be signed in to change notification settings - Fork 368
/
fillet.py
396 lines (340 loc) · 18.3 KB
/
fillet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""
This page is in the table of contents.
Fillet rounds the corners slightly in a variety of ways. This is to reduce corner blobbing and sudden extruder acceleration.
The fillet manual page is at:
http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Fillet
==Operation==
The default 'Activate Fillet' checkbox is off. When it is on, the functions described below will work, when it is off, nothing will be done.
==Settings==
===Fillet Procedure Choice===
Default is 'Bevel''.
====Arc Point====
When selected, the corners will be filleted with an arc using the gcode point form.
====Arc Radius====
When selected, the corners will be filleted with an arc using the gcode radius form.
====Arc Segment====
When selected, the corners will be filleted with an arc composed of several segments.
====Bevel====
When selected, the corners will be beveled.
===Corner Feed Rate Multiplier===
Default: 1.0
Defines the ratio of the feed rate in corners over the original feed rate. With a high value the extruder will move quickly in corners, accelerating quickly and leaving a thin extrusion. With a low value, the extruder will move slowly in corners, accelerating gently and leaving a thick extrusion.
===Fillet Radius over Perimeter Width===
Default is 0.35.
Defines the width of the fillet.
===Reversal Slowdown over Perimeter Width===
Default is 0.5.
Defines how far before a path reversal the extruder will slow down. Some tools, like nozzle wipe, double back the path of the extruder and this option will add a slowdown point in that path so there won't be a sudden jerk at the end of the path. If the value is less than 0.1 a slowdown will not be added.
===Use Intermediate Feed Rate in Corners===
Default is on.
When selected, the feed rate entering the corner will be the average of the old feed rate and the new feed rate.
==Examples==
The following examples fillet the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and fillet.py.
> python fillet.py
This brings up the fillet dialog.
> python fillet.py Screw Holder Bottom.stl
The fillet tool is parsing the file:
Screw Holder Bottom.stl
..
The fillet tool has created the file:
.. Screw Holder Bottom_fillet.gcode
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret
from fabmetheus_utilities.vector3 import Vector3
from fabmetheus_utilities import archive
from fabmetheus_utilities import euclidean
from fabmetheus_utilities import gcodec
from fabmetheus_utilities import settings
from skeinforge_application.skeinforge_utilities import skeinforge_craft
from skeinforge_application.skeinforge_utilities import skeinforge_polyfile
from skeinforge_application.skeinforge_utilities import skeinforge_profile
import math
import sys
__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__date__ = '$Date: 2008/21/04 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
def getCraftedText( fileName, gcodeText, repository = None ):
"Fillet a gcode linear move file or text."
return getCraftedTextFromText( archive.getTextIfEmpty( fileName, gcodeText ), repository )
def getCraftedTextFromText( gcodeText, repository = None ):
"Fillet a gcode linear move text."
if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'fillet'):
return gcodeText
if repository == None:
repository = settings.getReadRepository( FilletRepository() )
if not repository.activateFillet.value:
return gcodeText
if repository.arcPoint.value:
return ArcPointSkein().getCraftedGcode( repository, gcodeText )
elif repository.arcRadius.value:
return ArcRadiusSkein().getCraftedGcode( repository, gcodeText )
elif repository.arcSegment.value:
return ArcSegmentSkein().getCraftedGcode( repository, gcodeText )
elif repository.bevel.value:
return BevelSkein().getCraftedGcode( repository, gcodeText )
return gcodeText
def getNewRepository():
'Get new repository.'
return FilletRepository()
def writeOutput(fileName, shouldAnalyze=True):
"Fillet a gcode linear move file. Depending on the settings, either arcPoint, arcRadius, arcSegment, bevel or do nothing."
skeinforge_craft.writeChainTextWithNounMessage(fileName, 'fillet', shouldAnalyze)
class BevelSkein:
"A class to bevel a skein of extrusions."
def __init__(self):
self.distanceFeedRate = gcodec.DistanceFeedRate()
self.extruderActive = False
self.feedRateMinute = 960.0
self.filletRadius = 0.2
self.lineIndex = 0
self.lines = None
self.oldFeedRateMinute = None
self.oldLocation = None
self.shouldAddLine = True
def addLinearMovePoint( self, feedRateMinute, point ):
"Add a gcode linear move, feedRate and newline to the output."
self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( feedRateMinute, point.dropAxis(), point.z ) )
def getCornerFeedRate(self):
"Get the corner feed rate, which may be based on the intermediate feed rate."
feedRateMinute = self.feedRateMinute
if self.repository.useIntermediateFeedRateInCorners.value:
if self.oldFeedRateMinute != None:
feedRateMinute = 0.5 * ( self.oldFeedRateMinute + self.feedRateMinute )
return feedRateMinute * self.cornerFeedRateMultiplier
def getCraftedGcode( self, repository, gcodeText ):
"Parse gcode text and store the bevel gcode."
self.cornerFeedRateMultiplier = repository.cornerFeedRateMultiplier.value
self.lines = archive.getTextLines(gcodeText)
self.repository = repository
self.parseInitialization( repository )
for self.lineIndex in xrange(self.lineIndex, len(self.lines)):
line = self.lines[self.lineIndex]
self.parseLine(line)
return self.distanceFeedRate.output.getvalue()
def getExtruderOffReversalPoint( self, afterSegment, afterSegmentComplex, beforeSegment, beforeSegmentComplex, location ):
"If the extruder is off and the path is reversing, add intermediate slow points."
if self.repository.reversalSlowdownDistanceOverEdgeWidth.value < 0.1:
return None
if self.extruderActive:
return None
reversalBufferSlowdownDistance = self.reversalSlowdownDistance * 2.0
afterSegmentComplexLength = abs( afterSegmentComplex )
if afterSegmentComplexLength < reversalBufferSlowdownDistance:
return None
beforeSegmentComplexLength = abs( beforeSegmentComplex )
if beforeSegmentComplexLength < reversalBufferSlowdownDistance:
return None
afterSegmentComplexNormalized = afterSegmentComplex / afterSegmentComplexLength
beforeSegmentComplexNormalized = beforeSegmentComplex / beforeSegmentComplexLength
if euclidean.getDotProduct( afterSegmentComplexNormalized, beforeSegmentComplexNormalized ) < 0.95:
return None
slowdownFeedRate = self.feedRateMinute * 0.5
self.shouldAddLine = False
beforePoint = euclidean.getPointPlusSegmentWithLength( self.reversalSlowdownDistance * abs( beforeSegment ) / beforeSegmentComplexLength, location, beforeSegment )
self.addLinearMovePoint( self.feedRateMinute, beforePoint )
self.addLinearMovePoint( slowdownFeedRate, location )
afterPoint = euclidean.getPointPlusSegmentWithLength( self.reversalSlowdownDistance * abs( afterSegment ) / afterSegmentComplexLength, location, afterSegment )
self.addLinearMovePoint( slowdownFeedRate, afterPoint )
return afterPoint
def getNextLocation(self):
"Get the next linear move. Return none is none is found."
for afterIndex in xrange( self.lineIndex + 1, len(self.lines) ):
line = self.lines[ afterIndex ]
splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
if gcodec.getFirstWord(splitLine) == 'G1':
nextLocation = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine)
return nextLocation
return None
def linearMove( self, splitLine ):
"Bevel a linear move."
location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine)
self.feedRateMinute = gcodec.getFeedRateMinute( self.feedRateMinute, splitLine )
if self.oldLocation != None:
nextLocation = self.getNextLocation()
if nextLocation != None:
location = self.splitPointGetAfter( location, nextLocation )
self.oldLocation = location
self.oldFeedRateMinute = self.feedRateMinute
def parseInitialization( self, repository ):
'Parse gcode initialization and store the parameters.'
for self.lineIndex in xrange(len(self.lines)):
line = self.lines[self.lineIndex]
splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
firstWord = gcodec.getFirstWord(splitLine)
self.distanceFeedRate.parseSplitLine(firstWord, splitLine)
if firstWord == '(</extruderInitialization>)':
self.distanceFeedRate.addTagBracketedProcedure('fillet')
return
elif firstWord == '(<edgeWidth>':
edgeWidth = abs(float(splitLine[1]))
self.curveSection = 0.7 * edgeWidth
self.filletRadius = edgeWidth/2
self.minimumRadius = 0.1 * edgeWidth
self.reversalSlowdownDistance = edgeWidth * repository.reversalSlowdownDistanceOverEdgeWidth.value
self.distanceFeedRate.addLine(line)
def parseLine(self, line):
"Parse a gcode line and add it to the bevel gcode."
self.shouldAddLine = True
splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
if len(splitLine) < 1:
return
firstWord = splitLine[0]
if firstWord == 'G1':
self.linearMove(splitLine)
elif firstWord == 'M101':
self.extruderActive = True
elif firstWord == 'M103':
self.extruderActive = False
if self.shouldAddLine:
self.distanceFeedRate.addLine(line)
def splitPointGetAfter( self, location, nextLocation ):
"Bevel a point and return the end of the bevel. should get complex for radius"
if self.filletRadius < 2.0 * self.minimumRadius:
return location
afterSegment = nextLocation - location
afterSegmentComplex = afterSegment.dropAxis()
afterSegmentComplexLength = abs( afterSegmentComplex )
thirdAfterSegmentLength = 0.333 * afterSegmentComplexLength
if thirdAfterSegmentLength < self.minimumRadius:
return location
beforeSegment = self.oldLocation - location
beforeSegmentComplex = beforeSegment.dropAxis()
beforeSegmentComplexLength = abs( beforeSegmentComplex )
thirdBeforeSegmentLength = 0.333 * beforeSegmentComplexLength
if thirdBeforeSegmentLength < self.minimumRadius:
return location
extruderOffReversalPoint = self.getExtruderOffReversalPoint( afterSegment, afterSegmentComplex, beforeSegment, beforeSegmentComplex, location )
if extruderOffReversalPoint != None:
return extruderOffReversalPoint
bevelRadius = min( thirdAfterSegmentLength, self.filletRadius )
bevelRadius = min( thirdBeforeSegmentLength, bevelRadius )
self.shouldAddLine = False
beforePoint = euclidean.getPointPlusSegmentWithLength( bevelRadius * abs( beforeSegment ) / beforeSegmentComplexLength, location, beforeSegment )
self.addLinearMovePoint( self.feedRateMinute, beforePoint )
afterPoint = euclidean.getPointPlusSegmentWithLength( bevelRadius * abs( afterSegment ) / afterSegmentComplexLength, location, afterSegment )
self.addLinearMovePoint( self.getCornerFeedRate(), afterPoint )
return afterPoint
class ArcSegmentSkein( BevelSkein ):
"A class to arc segment a skein of extrusions."
def addArc( self, afterCenterDifferenceAngle, afterPoint, beforeCenterSegment, beforePoint, center ):
"Add arc segments to the filleted skein."
absoluteDifferenceAngle = abs( afterCenterDifferenceAngle )
# steps = int( math.ceil( absoluteDifferenceAngle * 1.5 ) )
steps = int( math.ceil( min( absoluteDifferenceAngle * 1.5, absoluteDifferenceAngle * abs( beforeCenterSegment ) / self.curveSection ) ) )
stepPlaneAngle = euclidean.getWiddershinsUnitPolar( afterCenterDifferenceAngle / steps )
for step in xrange( 1, steps ):
beforeCenterSegment = euclidean.getRoundZAxisByPlaneAngle( stepPlaneAngle, beforeCenterSegment )
arcPoint = center + beforeCenterSegment
self.addLinearMovePoint( self.getCornerFeedRate(), arcPoint )
self.addLinearMovePoint( self.getCornerFeedRate(), afterPoint )
def splitPointGetAfter( self, location, nextLocation ):
"Fillet a point into arc segments and return the end of the last segment."
if self.filletRadius < 2.0 * self.minimumRadius:
return location
afterSegment = nextLocation - location
afterSegmentComplex = afterSegment.dropAxis()
thirdAfterSegmentLength = 0.333 * abs( afterSegmentComplex )
if thirdAfterSegmentLength < self.minimumRadius:
return location
beforeSegment = self.oldLocation - location
beforeSegmentComplex = beforeSegment.dropAxis()
thirdBeforeSegmentLength = 0.333 * abs( beforeSegmentComplex )
if thirdBeforeSegmentLength < self.minimumRadius:
return location
extruderOffReversalPoint = self.getExtruderOffReversalPoint( afterSegment, afterSegmentComplex, beforeSegment, beforeSegmentComplex, location )
if extruderOffReversalPoint != None:
return extruderOffReversalPoint
bevelRadius = min( thirdAfterSegmentLength, self.filletRadius )
bevelRadius = min( thirdBeforeSegmentLength, bevelRadius )
self.shouldAddLine = False
beforePoint = euclidean.getPointPlusSegmentWithLength( bevelRadius * abs( beforeSegment ) / abs( beforeSegmentComplex ), location, beforeSegment )
self.addLinearMovePoint( self.feedRateMinute, beforePoint )
afterPoint = euclidean.getPointPlusSegmentWithLength( bevelRadius * abs( afterSegment ) / abs( afterSegmentComplex ), location, afterSegment )
afterPointComplex = afterPoint.dropAxis()
beforePointComplex = beforePoint.dropAxis()
locationComplex = location.dropAxis()
midpoint = 0.5 * ( afterPoint + beforePoint )
midpointComplex = midpoint.dropAxis()
midpointMinusLocationComplex = midpointComplex - locationComplex
midpointLocationLength = abs( midpointMinusLocationComplex )
if midpointLocationLength < 0.01 * self.filletRadius:
self.addLinearMovePoint( self.getCornerFeedRate(), afterPoint )
return afterPoint
midpointAfterPointLength = abs( midpointComplex - afterPointComplex )
midpointCenterLength = midpointAfterPointLength * midpointAfterPointLength / midpointLocationLength
radius = math.sqrt( midpointCenterLength * midpointCenterLength + midpointAfterPointLength * midpointAfterPointLength )
centerComplex = midpointComplex + midpointMinusLocationComplex * midpointCenterLength / midpointLocationLength
center = Vector3( centerComplex.real, centerComplex.imag, midpoint.z )
afterCenterComplex = afterPointComplex - centerComplex
beforeCenter = beforePoint - center
angleDifference = euclidean.getAngleDifferenceByComplex( afterCenterComplex, beforeCenter.dropAxis() )
self.addArc( angleDifference, afterPoint, beforeCenter, beforePoint, center )
return afterPoint
class ArcPointSkein( ArcSegmentSkein ):
"A class to arc point a skein of extrusions."
def addArc( self, afterCenterDifferenceAngle, afterPoint, beforeCenterSegment, beforePoint, center ):
"Add an arc point to the filleted skein."
if afterCenterDifferenceAngle == 0.0:
return
afterPointMinusBefore = afterPoint - beforePoint
centerMinusBefore = center - beforePoint
firstWord = 'G3'
if afterCenterDifferenceAngle < 0.0:
firstWord = 'G2'
centerMinusBeforeComplex = centerMinusBefore.dropAxis()
if abs( centerMinusBeforeComplex ) <= 0.0:
return
radius = abs( centerMinusBefore )
arcDistanceZ = complex( abs( afterCenterDifferenceAngle ) * radius, afterPointMinusBefore.z )
distance = abs( arcDistanceZ )
if distance <= 0.0:
return
line = self.distanceFeedRate.getFirstWordMovement( firstWord, afterPointMinusBefore ) + self.getRelativeCenter( centerMinusBeforeComplex )
cornerFeedRate = self.getCornerFeedRate()
if cornerFeedRate != None:
line += ' F' + self.distanceFeedRate.getRounded(cornerFeedRate)
self.distanceFeedRate.addLine(line)
def getRelativeCenter( self, centerMinusBeforeComplex ):
"Get the relative center."
return ' I%s J%s' % ( self.distanceFeedRate.getRounded( centerMinusBeforeComplex.real ), self.distanceFeedRate.getRounded( centerMinusBeforeComplex.imag ) )
class ArcRadiusSkein( ArcPointSkein ):
"A class to arc radius a skein of extrusions."
def getRelativeCenter( self, centerMinusBeforeComplex ):
"Get the relative center."
radius = abs( centerMinusBeforeComplex )
return ' R' + ( self.distanceFeedRate.getRounded(radius) )
class FilletRepository:
"A class to handle the fillet settings."
def __init__(self):
"Set the default settings, execute title & settings fileName."
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.fillet.html', self )
self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File to be Filleted', self, '')
self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Fillet')
self.activateFillet = settings.BooleanSetting().getFromValue('Activate Fillet', self, False )
self.filletProcedureChoiceLabel = settings.LabelDisplay().getFromName('Fillet Procedure Choice: ', self )
filletLatentStringVar = settings.LatentStringVar()
self.arcPoint = settings.Radio().getFromRadio( filletLatentStringVar, 'Arc Point', self, False )
self.arcRadius = settings.Radio().getFromRadio( filletLatentStringVar, 'Arc Radius', self, False )
self.arcSegment = settings.Radio().getFromRadio( filletLatentStringVar, 'Arc Segment', self, False )
self.bevel = settings.Radio().getFromRadio( filletLatentStringVar, 'Bevel', self, True )
self.cornerFeedRateMultiplier = settings.FloatSpin().getFromValue(0.8, 'Corner Feed Rate Multiplier (ratio):', self, 1.2, 1.0)
# self.filletRadiusOverEdgeWidth = settings.FloatSpin().getFromValue( 0.25, 'Fillet Radius over Perimeter Width (ratio):', self, 0.65, 0.35 )
self.reversalSlowdownDistanceOverEdgeWidth = settings.FloatSpin().getFromValue( 0.3, 'Reversal Slowdown Distance over Perimeter Width (ratio):', self, 0.7, 0.5 )
self.useIntermediateFeedRateInCorners = settings.BooleanSetting().getFromValue('Use Intermediate Feed Rate in Corners', self, True )
self.executeTitle = 'Fillet'
def execute(self):
"Fillet button has been clicked."
fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled)
for fileName in fileNames:
writeOutput(fileName)
def main():
"Display the fillet dialog."
if len(sys.argv) > 1:
writeOutput(' '.join(sys.argv[1 :]))
else:
settings.startMainLoopFromConstructor(getNewRepository())
if __name__ == "__main__":
main()