本文整理汇总了Python中CNC.Block类的典型用法代码示例。如果您正苦于以下问题:Python Block类的具体用法?Python Block怎么用?Python Block使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Block类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: insertBlock
def insertBlock(self, event=None):
active = self.index(ACTIVE)
if self._items:
bid, lid = self._items[active]
bid += 1
else:
bid = 0
block = Block()
block.expand = True
block.append("G0 X0 Y0")
block.append("G1 Z0")
block.append(CNC.zsafe())
self.gcode.addUndo(self.gcode.addBlockUndo(bid,block))
self.selection_clear(0,END)
self.fill()
# find location of new block
while active < self.size():
if self._items[active][0] == bid:
break
active += 1
self.selection_set(active)
self.see(active)
self.activate(active)
self.edit()
self.app.event_generate("<<Modified>>")
示例2: execute
def execute(self, app):
#print("go!")
blocks = []
paths_base = []
paths_isl = []
for bid in app.editor.getSelectedBlocks():
if app.gcode[bid].operationTest('island'):
paths_isl.extend(app.gcode.toPath(bid))
else:
paths_base.extend(app.gcode.toPath(bid))
for island in paths_isl:
paths_newbase = []
while len(paths_base) > 0:
base = paths_base.pop()
base.intersectPath(island)
island.intersectPath(base)
newbase = Path("diff")
#Add segments from outside of islands:
for i,seg in enumerate(base):
if not island.isInside(seg.midPoint()):
newbase.append(seg)
#Add segments from islands to base
for i,seg in enumerate(island):
if base.isInside(seg.midPoint()): #and base.isInside(seg.A) and base.isInside(seg.B):
newbase.append(seg)
#Eulerize
paths_newbase.extend(newbase.eulerize())
#paths_newbase.extend(newbase.split2contours())
paths_base = paths_newbase
for base in paths_base:
print(base)
#base = base.eulerize(True)
block = Block("diff")
block.extend(app.gcode.fromPath(base))
blocks.append(block)
#active = app.activeBlock()
app.gcode.insBlocks(-1, blocks, "Diff") #<<< insert blocks over active block in the editor
app.refresh() #<<< refresh editor
app.setStatus(_("Generated: Diff")) #<<< feed back result
示例3: joinBlocks
def joinBlocks(self, event=None):
if not self._items: return
all_items = self._items
sel_items = list(map(int,self.curselection()))
change = True
bl = Block(self.gcode[sel_items[0]].name())
for bid in sel_items:
for line in self.gcode[bid]:
bl.append(line)
bl.append("( ---------- cut-here ---------- )")
del bl[-1]
self.gcode.addUndo(self.gcode.addBlockUndo(bid+1,bl))
if change: self.fill()
self.deleteBlock()
self.winfo_toplevel().event_generate("<<Modified>>")
示例4: make
def make(self):
d = self.thick
# Convert to external dimensions
if self.dx<0:
dx = -self.dx - d*2 # external to internal
else:
dx = self.dx
if self.dy<0:
dy = -self.dy - d*2 # external to internal
else:
dy = self.dy
if self.dz<0:
dz = -self.dz - d*2 # external to internal
else:
dz = self.dz
blocks = []
block = Block("%s-Bottom"%(self.name))
block.append("(Box: %g x %g x %g)"%(self.dx,self.dy,self.dz))
block.append("(Fingers: %d x %d x %d)"%(self.nx,self.ny,self.nz))
self._rectangle(block, 0.,-d, dx,dy, self.nx,-self.ny, 0,d)
blocks.append(block)
block = Block("%s-Left"%(self.name))
self._rectangle(block, -(dz+5*d),-d, dz,dy, self.nz,self.ny, d,d)
blocks.append(block)
block = Block("%s-Right"%(self.name))
self._rectangle(block, dx+3*d,-d, dz,dy, self.nz,self.ny, d,d)
blocks.append(block)
block = Block("%s-Front"%(self.name))
self._rectangle(block, 0,-(dz+4*d), dx,dz, -self.nx,-self.nz, 0,0)
blocks.append(block)
block = Block("%s-Back"%(self.name))
self._rectangle(block, 0,dy+4*d, dx,dz, -self.nx,-self.nz, 0,0)
blocks.append(block)
block = Block("%s-Top"%(self.name))
self._rectangle(block, dx+dz+8*d,-d, dx,dy, self.nx,-self.ny, 0,d)
blocks.append(block)
return blocks
示例5: splitBlocks
def splitBlocks(self, event=None):
if not self._items: return
all_items = self._items
sel_items = list(map(int,self.curselection()))
change = True
newblocks = []
for bid in sel_items:
bl = Block(self.gcode[bid].name())
for line in self.gcode[bid]:
if line == "( ---------- cut-here ---------- )":
#newblocks.append(bl)
#self.insertBlock(bl)
self.gcode.addUndo(self.gcode.addBlockUndo(bid+1,bl))
bl = Block(self.gcode[bid].name())
else:
bl.append(line)
self.gcode.addUndo(self.gcode.addBlockUndo(bid+1,bl))
#newblocks.append(bl)
#self.gcode.extend(newblocks)
if change: self.fill()
self.deleteBlock()
self.winfo_toplevel().event_generate("<<Modified>>")
示例6: execute
def execute(self, app):
#print("go!")
blocks = []
bid = app.editor.getSelectedBlocks()[0]
xbasepath = app.gcode.toPath(bid)[0]
bid = app.editor.getSelectedBlocks()[1]
xislandpath = app.gcode.toPath(bid)[0]
xbasepath.intersectPath(xislandpath)
xislandpath.intersectPath(xbasepath)
#xnewisland = self.pathBoolIntersection(xbasepath, xislandpath)
xnewisland = self.pathBoolIntersection(xislandpath, xbasepath)
#pth = Path("temp")
#basepath.invert()
#pth.extend(basepath)
#pth.extend(basepath)
##pth.invert()
block = Block("intersect")
block.extend(app.gcode.fromPath(xnewisland))
blocks.append(block)
#block = Block("diff")
#block.extend(app.gcode.fromPath(pth))
#blocks.append(block)
active = app.activeBlock()
app.gcode.insBlocks(active, blocks, "Intersect") #<<< insert blocks over active block in the editor
app.refresh() #<<< refresh editor
app.setStatus(_("Generated: Intersect")) #<<< feed back result
示例7: slice
def slice(self, verts, faces, z, zout=None, axis='z'):
tags = '[slice]'
if axis=='z': tags = '[slice,minz:%f]'%(float(z))
block = Block("slice %s%f %s"%(axis,float(z),tags))
#FIXME: slice along different axes
if axis == 'x':
plane_orig = (z, 0, 0)
plane_norm = (1, 0, 0)
elif axis == 'y':
plane_orig = (0, z, 0)
plane_norm = (0, 1, 0)
else:
plane_orig = (0, 0, z) #z height to slice
plane_norm = (0, 0, 1)
#Crosscut
contours = meshcut.cross_section(verts, faces, plane_orig, plane_norm)
#Flatten contours
if zout is not None:
for contour in contours:
for segment in contour:
segment[2] = zout
#Contours to G-code
for contour in contours:
#print(contour)
gtype = 0
for segment in contour:
block.append("g%s x%f y%f z%f"%(gtype, segment[0],segment[1],segment[2]))
gtype = 1
block.append("g1 x%f y%f z%f"%(contour[0][0],contour[0][1],contour[0][2])) #Close shape
block.append("( ---------- cut-here ---------- )")
if block: del block[-1]
if not block: block = None
return block
示例8: calc
def calc(self, D, res, pocket):
blocks = []
block = Block(self.name)
# Load tool and material settings
toolDiam = CNC.vars['diameter']
toolRadius = toolDiam/2.
stepz = CNC.vars['stepz']
stepxy = toolDiam*(CNC.vars['stepover']/100.)
if toolDiam <= 0 or stepxy <= 0 or stepz <= 0 or D <= 0 or res <= 0:
return blocks
currDepth = 0.
def setCutFeedrate():
block.append(CNC.gcode(1, [("f",CNC.vars["cutfeed"])]))
def addCircumference(radius):
block.append(CNC.garc(2,radius, 0., i=-radius))
# Mills a circle, pocketing it if needed
def addSingleCircle(radius, depth):
if pocket:
block.append(CNC.grapid(0., 0.))
block.append(CNC.zenter(depth))
setCutFeedrate()
currRadius = 0.
while radius > currRadius+stepxy:
currRadius += stepxy
block.append(CNC.gline(currRadius, 0))
addCircumference(currRadius)
if radius-currRadius > 0:
block.append(CNC.gline(radius, 0))
addCircumference(radius)
else:
block.append(CNC.grapid(radius, 0.))
block.append(CNC.zenter(depth))
setCutFeedrate()
addCircumference(radius)
# Mills a circle in steps of height "stepz"
def addCircle(radius, depth, currDepth):
while depth < currDepth-stepz:
currDepth -= stepz
addSingleCircle(radius, currDepth)
if currDepth-depth > 0:
addSingleCircle(radius, depth)
return depth
block.append(CNC.zsafe())
r = D/2.
r -= toolRadius # Removes offset of ball-end tool
angleInc = res
currAngle = 0.
angle = math.pi/2. # 90 degrees
while angle > currAngle+angleInc:
currAngle += angleInc
radius = r * math.cos(-currAngle)
depth = r * math.sin(-currAngle) - toolRadius # Removes vertical offset (centers the ball tool in Z=0, rather than the tip)
currDepth = addCircle(radius, depth, currDepth)
if angle-currAngle > 0:
radius = r * math.cos(-angle)
depth = r * math.sin(-angle) - toolRadius
currDepth = addCircle(radius, depth, currDepth)
blocks.append(block)
return blocks
示例9: make
def make(self,n = 2, size = 100, depth = 0):
self.n = n
self.size = size
self.depth = depth
blocks = []
block = Block(self.name)
xi,yi = zip(*(self.hilbert(0.0,0.0,size,0.0,0.0,size,n)))
block.append(CNC.zsafe())
block.append(CNC.grapid(xi[0],yi[0]))
currDepth = 0.
stepz = CNC.vars['stepz']
if stepz==0 : stepz=0.001 #avoid infinite while loop
while True:
currDepth -= stepz
if currDepth < self.depth : currDepth = self.depth
block.append(CNC.zenter(currDepth))
block.append(CNC.gcode(1, [("f",CNC.vars["cutfeed"])]))
for x,y in zip(xi,yi):
block.append(CNC.gline(x,y))
if currDepth <= self.depth : break
block.append(CNC.zsafe())
blocks.append(block)
return blocks
示例10: calc
def calc(self, N, phi, Pc):
N = abs(N)
# Pitch Circle
D = N * Pc / math.pi
R = D / 2.0
# Diametrical pitch
Pd = N / D
# Base Circle
Db = D * math.cos(phi)
Rb = Db / 2.0
# Addendum
a = 1.0 / Pd
# Outside Circle
Ro = R + a
Do = 2.0 * Ro
# Tooth thickness
T = math.pi*D / (2*N)
# undercut?
U = 2.0 / (math.sin(phi) * (math.sin(phi)))
needs_undercut = N < U
# sys.stderr.write("N:%s R:%s Rb:%s\n" % (N,R,Rb))
# Clearance
c = 0.0
# Dedendum
b = a + c
# Root Circle
Rr = R - b
Dr = 2.0*Rr
two_pi = 2.0*math.pi
half_thick_angle = two_pi / (4.0*N)
pitch_to_base_angle = self.involute_intersect_angle(Rb, R)
pitch_to_outer_angle = self.involute_intersect_angle(Rb, Ro) # pitch_to_base_angle
points = []
for x in range(1,N+1):
c = x * two_pi / N
# angles
pitch1 = c - half_thick_angle
base1 = pitch1 - pitch_to_base_angle
outer1 = pitch1 + pitch_to_outer_angle
pitch2 = c + half_thick_angle
base2 = pitch2 + pitch_to_base_angle
outer2 = pitch2 - pitch_to_outer_angle
# points
b1 = self.point_on_circle(Rb, base1)
p1 = self.point_on_circle(R, pitch1)
o1 = self.point_on_circle(Ro, outer1)
o2 = self.point_on_circle(Ro, outer2)
p2 = self.point_on_circle(R, pitch2)
b2 = self.point_on_circle(Rb, base2)
if Rr >= Rb:
pitch_to_root_angle = pitch_to_base_angle - self.involute_intersect_angle(Rb, Rr)
root1 = pitch1 - pitch_to_root_angle
root2 = pitch2 + pitch_to_root_angle
r1 = self.point_on_circle(Rr, root1)
r2 = self.point_on_circle(Rr, root2)
points.append(r1)
points.append(p1)
points.append(o1)
points.append(o2)
points.append(p2)
points.append(r2)
else:
r1 = self.point_on_circle(Rr, base1)
r2 = self.point_on_circle(Rr, base2)
points.append(r1)
points.append(b1)
points.append(p1)
points.append(o1)
points.append(o2)
points.append(p2)
points.append(b2)
points.append(r2)
first = points[0]
del points[0]
blocks = []
block = Block(self.name)
blocks.append(block)
block.append(CNC.grapid(first.x(), first.y()))
block.append(CNC.zenter(0.0))
#print first.x(), first.y()
for v in points:
block.append(CNC.gline(v.x(), v.y()))
#.........这里部分代码省略.........
示例11: execute
def execute(self, app):
#Get inputs
fontSize = self.fromMm("FontSize")
depth = self.fromMm("Depth")
textToWrite = self["Text"]
fontFileName = self["FontFile"]
imageFileName = self["ImageToAscii"]
charsWidth = self["CharsWidth"]
#Check parameters!!!
if fontSize <=0:
app.setStatus(_("Text abort: please input a Font size > 0"))
return
if fontFileName == "":
app.setStatus(_("Text abort: please select a font file"))
return
if imageFileName != "":
try:
textToWrite = self.asciiArt(imageFileName,charsWidth)
except:
pass
if textToWrite == "":
textToWrite = "Nel mezzo del cammin di nostra vita..."
return
#Init blocks
blocks = []
n = self["name"]
if not n or n == "default": n = "Text"
block = Block(n)
if(u'\n' in textToWrite):
block.append("(Text:)")
for line in textToWrite.splitlines():
block.append("(%s)" % line)
else:
block.append("(Text: %s)" % textToWrite)
try:
import ttf
font = ttf.TruetypeInfo(fontFileName)
except:
app.setStatus(_("Text abort: That embarrassing, I can't read this font file!"))
return
cmap = font.get_character_map()
kern = None
try:
kern = font.get_glyph_kernings()
except:
pass
adv = font.get_glyph_advances()
xOffset = 0
yOffset = 0
glyphIndxLast = cmap[' ']
for c in textToWrite:
#New line
if c == u'\n':
xOffset = 0.0
yOffset -= 1#offset for new line
continue
if c in cmap:
glyphIndx = cmap[c]
if (kern and (glyphIndx,glyphIndxLast) in kern):
k = kern[(glyphIndx,glyphIndxLast)] #FIXME: use kern for offset??
#Get glyph contours as line segmentes and draw them
gc = font.get_glyph_contours(glyphIndx)
if(not gc):
gc = font.get_glyph_contours(0)#standard glyph for missing glyphs (complex glyph)
if(gc and not c==' '): #FIXME: for some reason space is not mapped correctly!!!
self.writeGlyphContour(block, font, gc, fontSize, depth, xOffset, yOffset)
if glyphIndx < len(adv):
xOffset += adv[glyphIndx]
else:
xOffset += 1
glyphIndxLast = glyphIndx
#Remeber to close Font
font.close()
#Gcode Zsafe
block.append(CNC.zsafe())
blocks.append(block)
active = app.activeBlock()
if active==0: active=1
app.gcode.insBlocks(active, blocks, "Text")
app.refresh()
app.setStatus("Generated Text")
示例12: paste
def paste(self, event=None):
try: clipboard = self.selection_get(selection='CLIPBOARD')
except: return
ypos = self.yview()[0]
# paste them after the last selected item
# bid,lid push them to self so it can be accessed from addLines()
# python3 might fix this with the inner scope
try:
self.__bid, self.__lid = self._items[self.curselection()[-1]]
except:
try:
self.__bid, self.__lid = self._items[-1]
except:
self.__bid = 0
self.__lid = None
selitems = []
undoinfo = []
def addLines(lines):
for line in lines.splitlines():
# Create a new block
if self.__lid is None:
self.__bid += 1
self.__lid = sys.maxint
block = Block()
undoinfo.append(self.gcode.addBlockUndo(self.__bid,block))
selitems.append((self.__bid, None))
else:
block = self.gcode.blocks[self.__bid]
if self.__lid == sys.maxint:
selitems.append((self.__bid, len(block)))
else:
self.__lid += 1
selitems.append((self.__bid, self.__lid))
undoinfo.append(self.gcode.insLineUndo(self.__bid, self.__lid, line))
try:
# try to unpickle it
unpickler = pickle.Unpickler(StringIO(clipboard))
try:
while True:
obj = unpickler.load()
if isinstance(obj,tuple):
block = Block.load(obj)
self.__bid += 1
undoinfo.append(self.gcode.addBlockUndo(self.__bid, block))
selitems.append((self.__bid,None))
self.__lid = None
else:
addLines(obj)
except EOFError:
pass
except pickle.UnpicklingError:
# Paste as text
addLines(clipboard)
if not undoinfo: return
self.gcode.addUndo(undoinfo)
self.selection_clear(0,END)
self.fill()
self.yview_moveto(ypos)
self.select(selitems, clear=True)
#self.selection_set(ACTIVE)
#self.see(ACTIVE)
self.app.event_generate("<<Modified>>")
示例13: execute
def execute(self, app):
if Image is None:
app.setStatus(_("Halftone abort: This plugin requires PIL/Pillow to read image data"))
return
n = self["name"]
if not n or n=="default": n="Halftone"
#Calc desired size
channel = self["Channel"]
invert = self["Invert"]
drawSize = self["DrawSize"]
cellSize = self["CellSize"]
dMax = self["DiameterMax"]
dMin = self["DiameterMin"]
angle = self["Angle"]
drawBorder = self["DrawBorder"]
depth = self["Depth"]
conical = self["Conical"]
#Check parameters
if drawSize < 1:
app.setStatus(_("Halftone abort: Size too small to draw anything!"))
return
if dMin > dMax:
app.setStatus(_("Halftone abort: Minimum diameter must be minor then Maximum"))
return
if dMax < 1:
app.setStatus(_("Halftone abort: Maximum diameter too small"))
return
if cellSize < 1:
app.setStatus(_("Halftone abort: Cell size too small"))
return
tool = app.tools["EndMill"]
tool_shape = tool["shape"]
if conical:
if tool_shape== "V-cutting":
try:
v_angle = float(tool["angle"])
except:
app.setStatus(_("Halftone abort: Angle in V-Cutting end mill is missing"))
return
else:
app.setStatus(_("Halftone abort: Conical path need V-Cutting end mill"))
return
#Open picture file
fileName = self["File"]
try:
img = Image.open(fileName)
except:
app.setStatus(_("Halftone abort: Can't read image file"))
return
#Create a scaled image to work faster with big image and better with small ones
squareNorm = True
if channel == 'Blue(sqrt)':
img = img.convert('RGB')
img = img.split()[0]
elif channel == 'Green(sqrt)':
img = img.convert('RGB')
img = img.split()[1]
elif channel == 'Red(sqrt)':
img = img.convert('RGB')
img = img.split()[2]
else:
img = img.convert ('L') #to calculate luminance
squareNorm = False
#flip image to ouput correct coordinates
img = img.transpose(Image.FLIP_TOP_BOTTOM)
#Calc divisions for halftone
divisions = drawSize / cellSize
#Get image size
self.imgWidth, self.imgHeight = img.size
if (self.imgWidth > self.imgHeight):
scale = drawSize / float(self.imgWidth)
sample = int(self.imgWidth / divisions)
else:
scale = drawSize / float(self.imgHeight)
sample = int(self.imgHeight / divisions)
self.ratio = scale
#Halftone
circles = self.halftone(img, sample, scale, angle, squareNorm, invert)
#Init blocks
blocks = []
#Border block
if drawBorder:
block = Block("%s-border"%(self.name))
block.append(CNC.zsafe())
block.append(CNC.grapid(0,0))
block.append(CNC.zenter(depth))
#.........这里部分代码省略.........
示例14: execute
#.........这里部分代码省略.........
maxy = image_h
midx = (minx + maxx) / 2
midy = (miny + maxy) / 2
# Force origin, we can move it later
origin = "Bot-Left"
CASE = str(origin)
if CASE == "Top-Left":
x_zero = minx
y_zero = maxy
elif CASE == "Top-Center":
x_zero = midx
y_zero = maxy
elif CASE == "Top-Right":
x_zero = maxx
y_zero = maxy
elif CASE == "Mid-Left":
x_zero = minx
y_zero = midy
elif CASE == "Mid-Center":
x_zero = midx
y_zero = midy
elif CASE == "Mid-Right":
x_zero = maxx
y_zero = midy
elif CASE == "Bot-Left":
x_zero = minx
y_zero = miny
elif CASE == "Bot-Center":
x_zero = midx
y_zero = miny
elif CASE == "Bot-Right":
x_zero = maxx
y_zero = miny
elif CASE == "Arc-Center":
x_zero = 0
y_zero = 0
else: # "Default"
x_zero = 0
y_zero = 0
xoffset = xoffset - x_zero
yoffset = yoffset - y_zero
######################################################
invert = self["Invert"]
if invert:
MAT.mult(-1.0)
else:
MAT.minus(depth)
######################################################
gcode = []
MAT.pad_w_zeros(TOOL)
header = ""
postscript = ""
gcode = convert(
self,
MAT,
units,
TOOL,
pixel_size,
step,
safe_z,
tolerance,
feed_rate,
convert_rows,
convert_cols,
columns_first,
cutperim,
Entry_cut,
zStep,
rough_feed,
xoffset,
yoffset,
splitstep,
header,
postscript,
edge_offset,
disable_arcs,
)
# Gcode
n = self["name"]
if not n or n == "default":
n = "Heightmap"
block = Block(n)
block.append("(Size: %d x %d x %d)" % (image_w, image_h, depth))
block.append("(Endmill shape: %s , Diameter: %.3f)" % (tool_shape, tool_diameter))
for line in gcode:
block.append(line)
blocks = []
blocks.append(block)
active = app.activeBlock()
app.gcode.insBlocks(active, blocks, n)
app.refresh()
app.setStatus(_("Generated Heightmap %d x %d x %d ") % (image_w, image_h, depth))
示例15: create_block
def create_block(self, holes, name):
targetDepth = self.fromMm("TargetDepth")
peck = self.fromMm("Peck")
dwell = self["Dwell"]
block = Block(name)
holesCount = 0
for bid in holes:
for xH,yH,zH in bid:
holesCount += 1
block.append(CNC.zsafe())
block.append(CNC.grapid(xH,yH))
if (peck != 0) :
z = 0
while z > targetDepth:
z = max(z-peck, targetDepth)
block.append(CNC.zenter(zH + z))
block.append(CNC.zsafe())
block.append(CNC.zenter(zH + targetDepth))
#dwell time only on last pass
if dwell != 0:
block.append(CNC.gcode(4, [("P",dwell)]))
#Gcode Zsafe on finish
block.append(CNC.zsafe())
return (block,holesCount)