summaryrefslogtreecommitdiff
path: root/trunk/reprap/miscellaneous/python-beanshell-scripts/skeinforge_tools/craft_plugins/drill.py
blob: 94c0ef8bdc52a15e9412073998075dedbe98f4bf (plain)
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
"""
This page is in the table of contents.
Drill is a script to drill down small holes.

==Operation==
The default 'Activate Drill' checkbox is on.  When it is on, the functions described below will work, when it is off, the functions will not be called.

==Settings==
===Drilling Margin===
The drill script will move the tool from the top of the hole plus the 'Drilling Margin on Top', to the bottom of the hole minus the 'Drilling Margin on Bottom'.

===Drilling Margin on Top===
Default is three millimeters.

===Drilling Margin on Bottom===
Default is one millimeter.

==Examples==
The following examples drill the file Screw Holder Bottom.stl.  The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and drill.py.


> python drill.py
This brings up the drill dialog.


> python drill.py Screw Holder Bottom.stl
The drill tool is parsing the file:
Screw Holder Bottom.stl
..
The drill tool has created the file:
.. Screw Holder Bottom_drill.gcode


> python
Python 2.5.1 (r251:54863, Sep 22 2007, 01:43:31)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import drill
>>> drill.main()
This brings up the drill dialog.


>>> drill.writeOutput( 'Screw Holder Bottom.stl' )
The drill tool is parsing the file:
Screw Holder Bottom.stl
..
The drill tool has created the file:
.. Screw Holder Bottom_drill.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 skeinforge_tools import profile
from skeinforge_tools.meta_plugins import polyfile
from skeinforge_tools.skeinforge_utilities import consecution
from skeinforge_tools.skeinforge_utilities import euclidean
from skeinforge_tools.skeinforge_utilities import gcodec
from skeinforge_tools.skeinforge_utilities import intercircle
from skeinforge_tools.skeinforge_utilities import interpret
from skeinforge_tools.skeinforge_utilities import settings
import sys


__author__ = "Enrique Perez (perez_enrique@yahoo.com)"
__date__ = "$Date: 2008/21/04 $"
__license__ = "GPL 3.0"

def getCraftedText( fileName, text, repository = None ):
	"Drill a gcode linear move file or text."
	return getCraftedTextFromText( gcodec.getTextIfEmpty( fileName, text ), repository )

def getCraftedTextFromText( gcodeText, repository = None ):
	"Drill a gcode linear move text."
	if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'drill' ):
		return gcodeText
	if repository == None:
		repository = settings.getReadRepository( DrillRepository() )
	if not repository.activateDrill.value:
		return gcodeText
	return DrillSkein().getCraftedGcode( gcodeText, repository )

def getNewRepository():
	"Get the repository constructor."
	return DrillRepository()

def getPolygonCenter( polygon ):
	"Get the centroid of a polygon."
	pointSum = complex()
	areaSum = 0.0
	for pointIndex in xrange( len( polygon ) ):
		pointBegin = polygon[ pointIndex ]
		pointEnd  = polygon[ ( pointIndex + 1 ) % len( polygon ) ]
		area = pointBegin.real * pointEnd.imag - pointBegin.imag * pointEnd.real
		areaSum += area
		pointSum += complex( pointBegin.real + pointEnd.real, pointBegin.imag + pointEnd.imag ) * area
	return pointSum / 3.0 / areaSum

def writeOutput( fileName = '' ):
	"Drill a gcode linear move file."
	fileName = interpret.getFirstTranslatorFileNameUnmodified( fileName )
	if fileName != '':
		consecution.writeChainTextWithNounMessage( fileName, 'drill' )


class ThreadLayer:
	"A layer of loops and paths."
	def __init__( self, z ):
		"Thread layer constructor."
		self.points = []
		self.z = z

	def __repr__( self ):
		"Get the string representation of this thread layer."
		return '%s, %s' % ( self.z, self.points )


class DrillRepository:
	"A class to handle the drill settings."
	def __init__( self ):
		"Set the default settings, execute title & settings fileName."
		profile.addListsToCraftTypeRepository( 'skeinforge_tools.craft_plugins.drill.html', self )
		self.fileNameInput = settings.FileNameInput().getFromFileName( interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Drill', self, '' )
		self.activateDrill = settings.BooleanSetting().getFromValue( 'Activate Drill', self, True )
		self.drillingMarginOnBottom = settings.FloatSpin().getFromValue( 0.0, 'Drilling Margin on Bottom (millimeters):', self, 5.0, 1.0 )
		self.drillingMarginOnTop = settings.FloatSpin().getFromValue( 0.0, 'Drilling Margin on Top (millimeters):', self, 20.0, 3.0 )
		self.executeTitle = 'Drill'

	def execute( self ):
		"Drill button has been clicked."
		fileNames = polyfile.getFileOrDirectoryTypesUnmodifiedGcode( self.fileNameInput.value, interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled )
		for fileName in fileNames:
			writeOutput( fileName )


class DrillSkein:
	"A class to drill a skein of extrusions."
	def __init__( self ):
		self.boundary = None
		self.distanceFeedRate = gcodec.DistanceFeedRate()
		self.extruderActive = False
		self.halfLayerThickness = 0.4
		self.isDrilled = False
		self.lineIndex = 0
		self.lines = None
		self.maximumDistance = 0.06
		self.oldLocation = None
		self.threadLayer = None
		self.threadLayers = []

	def addDrillHoles( self ):
		"Parse a gcode line."
		self.isDrilled = True
		if len( self.threadLayers ) < 1:
			return
		topThreadLayer = self.threadLayers[ 0 ]
		drillPoints = topThreadLayer.points
		for drillPoint in drillPoints:
			zTop = topThreadLayer.z + self.halfLayerThickness + self.repository.drillingMarginOnTop.value
			drillingCenterDepth = self.getDrillingCenterDepth( topThreadLayer.z, drillPoint )
			zBottom = drillingCenterDepth - self.halfLayerThickness - self.repository.drillingMarginOnBottom.value
			self.addGcodeFromVerticalThread( drillPoint, zTop, zBottom )

	def addGcodeFromVerticalThread( self, point, zBegin, zEnd ):
		"Add a thread to the output."
		self.distanceFeedRate.addGcodeMovementZ( point, zBegin )
		self.distanceFeedRate.addLine( "M101" ) # Turn extruder on.
		self.distanceFeedRate.addGcodeMovementZ( point, zEnd )
		self.distanceFeedRate.addLine( "M103" ) # Turn extruder off.

	def addThreadLayerIfNone( self ):
		"Add a thread layer if it is none."
		if self.threadLayer != None:
			return
		self.threadLayer = ThreadLayer( self.layerZ )
		self.threadLayers.append( self.threadLayer )

	def getCraftedGcode( self, gcodeText, repository ):
		"Parse gcode text and store the drill gcode."
		self.lines = gcodec.getTextLines( gcodeText )
		self.repository = repository
		self.parseInitialization()
		for line in self.lines[ self.lineIndex : ]:
			self.parseSurroundingLoop( line )
		for line in self.lines[ self.lineIndex : ]:
			self.parseLine( line )
		return self.distanceFeedRate.output.getvalue()

	def getDrillingCenterDepth( self, drillingCenterDepth, drillPoint ):
		"Get the drilling center depth."
		for threadLayer in self.threadLayers[ 1 : ]:
			if self.isPointClose( drillPoint, threadLayer.points ):
				drillingCenterDepth = threadLayer.z
			else:
				return drillingCenterDepth
		return drillingCenterDepth

	def isPointClose( self, drillPoint, points ):
		"Determine if a point on the thread layer is close."
		for point in points:
			if abs( point - drillPoint ) < self.maximumDistance:
				return True
		return False

	def linearMove( self, splitLine ):
		"Add a linear move to the loop."
		self.addThreadLayerIfNone()
		location = gcodec.getLocationFromSplitLine( self.oldLocation, splitLine )
		if self.extruderActive:
			self.boundary = None
		self.oldLocation = location

	def parseInitialization( self ):
		"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.addLine( '(<procedureDone> drill </procedureDone>)' )
				return
			elif firstWord == '(<layerThickness>':
				self.halfLayerThickness = 0.5 * float( splitLine[ 1 ] )
			elif firstWord == '(<perimeterWidth>':
				self.maximumDistance = 0.1 * float( splitLine[ 1 ] )
			self.distanceFeedRate.addLine( line )

	def parseLine( self, line ):
		"Parse a gcode line."
		splitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )
		if len( splitLine ) < 1:
			return
		firstWord = splitLine[ 0 ]
		self.distanceFeedRate.addLine( line )
		if firstWord == '(<layer>':
			if not self.isDrilled:
				self.addDrillHoles()

	def parseSurroundingLoop( self, line ):
		"Parse a surrounding loop."
		splitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )
		if len( splitLine ) < 1:
			return
		firstWord = splitLine[ 0 ]
		if firstWord == 'G1':
			self.linearMove( splitLine )
		if firstWord == 'M101':
			self.extruderActive = True
		elif firstWord == 'M103':
			self.extruderActive = False
		elif firstWord == '(<boundaryPoint>':
			location = gcodec.getLocationFromSplitLine( None, splitLine )
			if self.boundary == None:
				self.boundary = []
			self.boundary.append( location.dropAxis( 2 ) )
		elif firstWord == '(<layer>':
			self.layerZ = float( splitLine[ 1 ] )
			self.threadLayer = None
		elif firstWord == '(<boundaryPerimeter>)':
			self.addThreadLayerIfNone()
		elif firstWord == '(</boundaryPerimeter>)':
			if self.boundary != None:
				self.threadLayer.points.append( getPolygonCenter( self.boundary ) )
				self.boundary = None


def main():
	"Display the drill dialog."
	if len( sys.argv ) > 1:
		writeOutput( ' '.join( sys.argv[ 1 : ] ) )
	else:
		settings.startMainLoopFromConstructor( getNewRepository() )

if __name__ == "__main__":
	main()