def main():
    parser = OptionParser()
    parser.add_option(
        "-n",
        "--name",
        dest="name",
        help=
        "Name of the hinge.  Program will load file called <name>.json and output <name>-face.dxf and <name>-temple.dxf.",
        metavar="HINGENAME")

    (options, args) = parser.parse_args()

    if options.name == None:
        sys.stderr.write("Not enough arguments")
        parser.print_help()
        sys.exit(0)

    name = options.name
    infile = open(name + ".json")
    hinge = json.loads(infile.read())

    face = hinge["face_contour"]
    temple = hinge["temple_contour"]
    face_hole_diam = hinge["drill_dia"]
    temple_hole_diam = hinge["drill_dia"]
    face_holes = hinge["face_holes"]
    temple_holes = hinge["temple_holes"]

    face_drawing = dxf.drawing("./%s-face.dxf" % name)
    temple_drawing = dxf.drawing("./%s-temple.dxf" % name)
    face_drawing.add_layer("OUTLINE", color=1)
    face_drawing.add_layer("HOLES", color=2)
    temple_drawing.add_layer("OUTLINE", color=1)
    temple_drawing.add_layer("HOLES", color=2)

    face_outline = dxf.polyline(layer="OUTLINE", thickness=0.1)
    face_outline.add_vertices(face)
    face_drawing.add(face_outline)
    for hole in face_holes:
        circ = dxf.circle(face_hole_diam / 2.0,
                          hole,
                          layer="HOLES",
                          thickness=0.1)
        face_drawing.add(circ)
    face_drawing.save()

    temple_outline = dxf.polyline(layer="OUTLINE", thickness=0.1)
    temple_outline.add_vertices(temple)
    temple_drawing.add(temple_outline)
    for hole in temple_holes:
        circ = dxf.circle(temple_hole_diam / 2.0,
                          hole,
                          layer="HOLES",
                          thickness=0.1)
        temple_drawing.add(circ)
    temple_drawing.save()
示例#2
0
def dxf_code(file_name, table_point, table_line, table_chain, table_shaft,
             table_slider, table_rod):
    mechanism = dxf.drawing(file_name)
    for i in range(len(table_point)):
        pt = dxf.point((table_point[i][3], table_point[i][4]))
        mechanism.add(pt)
    for i in range(len(table_line)):
        ln = dxf.line((table_point[table_line[i][0]][3],
                       table_point[table_line[i][0]][4]),
                      (table_point[table_line[i][1]][3],
                       table_point[table_line[i][1]][4]))
        mechanism.add(ln)
    for i in range(len(table_chain)):
        ln1 = dxf.line((table_point[table_chain[i][0]][3],
                        table_point[table_chain[i][0]][4]),
                       (table_point[table_chain[i][1]][3],
                        table_point[table_chain[i][1]][4]))
        ln2 = dxf.line((table_point[table_chain[i][1]][3],
                        table_point[table_chain[i][1]][4]),
                       (table_point[table_chain[i][2]][3],
                        table_point[table_chain[i][2]][4]))
        ln3 = dxf.line((table_point[table_chain[i][0]][3],
                        table_point[table_chain[i][0]][4]),
                       (table_point[table_chain[i][2]][3],
                        table_point[table_chain[i][2]][4]))
        mechanism.add(ln1)
        mechanism.add(ln2)
        mechanism.add(ln3)
    mechanism.save()
    def SaveDXF(self):

        # Creates a dxf-file with the name written in the FileInput widget, adding the extension .dxf if it's not
        # present. Then creates a polyline entity in that file resembling the planned trajectory of the list, ignoring 
        # all instructions in the list other than those with the 'go to: '-tag. Finally, the list of the ActionInputBox
        # widget is refreshed. 

        filename = self._widget.FileInput.text()
        l = len(filename)
        if l > 3:
            if filename[(l-4):l] != '.dxf':
                filename = filename + '.dxf'
        else:
            filename = filename + '.dxf'
        drawing = dxfE.drawing(self.pwd + '/src/kampala/gui/src/gui/DXFFiles/' + filename)

        trajectory_points = []
        for point in self.pointlist:
            if point[0] == 'go to: ':
                trajectory_points.append(point[1])

        drawing.add(dxfE.polyline(trajectory_points))
        drawing.save()
        self.filelist = os.listdir(self.pwd + '/src/kampala/gui/src/gui/DXFFiles')
        self._widget.DXFInputBox.clear()
        self._widget.DXFInputBox.insertItems(0,self.filelist)
示例#4
0
def main():
	anguloIni=0
	anguloFin=300
	base=40
	altura=80
	anguloIni1=60
	anguloFin1=100
	base1=40
	altura1=60
	drawing = dxf.drawing('capa.dxf')
	drawCircleColouredLayer(drawing,80,105,148.5,1,currentLayer)
	drawCircleColouredLayer(drawing,40,105,148.5,2,'sector1')
	drawArcColouredLayer(drawing,105,148.5,60,anguloIni,anguloFin,3,'sector2')
	escribeEnArcoCapa(drawing,'adios',105,148.5,base,anguloIni,anguloFin,colorLine3,24.0,currentLayer,2,254.0)
#set value
#	drawing.header['$ANGBASE'] = 90
#	drawing.header['$ANGDIR'] = 1
	#px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,anguloIni,anguloFin,base,altura,colorLine3,'sector1')
	#px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,anguloIni1,anguloFin1,base1,altura1,colorLine2,'sector2')
	# px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoCono(drawing,anguloIni,anguloFin,base,altura,colorLine3)
	# px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoCono(drawing,anguloIni1,anguloFin1,base1,altura1,colorLine2
	#--------------------------------
	#writeTextNoAling(drawing,'universidad',px0,py0,12,5,currentLayer,0)
	#escribeEnArco(drawing,'universidad',centroX,centroY,base,anguloIni,anguloFin,colorLine,5)
	drawing.save()
示例#5
0
def create_dxf(filename):
    dxf_drawing = dxf.drawing(filename)

    for y in range(0, 5):
        x = 0
        dxf_drawing.add(dxf.circle(radius=y, center=(x, y * 2)))
    dxf_drawing.save()
示例#6
0
文件: project.py 项目: Cipahi/albion
    def export_elementary_volume_dxf(self,
                                     graph_id,
                                     cell_ids,
                                     outdir,
                                     closed_only=False):
        with self.connect() as con:
            cur = con.cursor()
            cur.execute("""
                select cell_id, row_number() over(partition by cell_id order by closed desc), geom, closed
                from (
                    select cell_id, triangulation as geom, albion.is_closed_volume(triangulation) as closed
                    from albion.volume
                    where cell_id in ({}) and graph_id='{}'
                    ) as t
                """.format(','.join(["'{}'".format(c) for c in cell_ids]),
                           graph_id))

            for cell_id, i, wkb_geom, closed in cur.fetchall():
                geom = wkb.loads(bytes.fromhex(wkb_geom))
                if closed_only and not closed:
                    continue
                filename = '{}_{}_{}_{}.dxf'.format(
                    cell_id, graph_id, "closed" if closed else "opened", i)
                path = os.path.join(outdir, filename)
                drawing = dxf.drawing(path)

                for p in geom:
                    r = p.exterior.coords
                    drawing.add(
                        dxf.face3d([tuple(r[0]),
                                    tuple(r[1]),
                                    tuple(r[2])],
                                   flags=1))
                drawing.save()
示例#7
0
文件: project.py 项目: Cipahi/albion
    def export_sections_dxf(self, graph, filename):

        with self.connect() as con:
            cur = con.cursor()
            cur.execute("""
                with hole_idx as (
                    select s.id as section_id, h.id as hole_id
                    from _albion.named_section as s
                    join _albion.hole as h on s.geom && h.geom and st_intersects(s.geom, st_startpoint(h.geom))
                )
                select st_collectionhomogenize(st_collect(ef.geom))
                from albion.all_edge as e
                join hole_idx as hs on hs.hole_id = e.start_
                join hole_idx as he on he.hole_id = e.end_ and he.section_id = hs.section_id
                join albion.edge_face as ef on ef.start_ = e.start_ and ef.end_ = e.end_ and not st_isempty(ef.geom)
                where ef.graph_id='{}'
                """.format(graph))

            drawing = dxf.drawing(filename)
            m = wkb.loads(bytes.fromhex(cur.fetchone()[0]))
            for p in m:
                r = p.exterior.coords
                drawing.add(
                    dxf.face3d(
                        [tuple(r[0]), tuple(r[1]),
                         tuple(r[2])], flags=1))
            drawing.save()
示例#8
0
    def writeDXF(self):
        
        fname = self.ui.lineEditOutputDXF.text()
        file = open(fname, 'w')
        
        rad = 0.25
        scale = 1.0
        col = 7
        dec = self.ui.spinBoxDecimal.value()
        dwg = dxf.drawing(fname)
           
        # create block
        scalarsymbol = dxf.block(name='symbol')
        scalarsymbol.add( dxf.circle(radius=rad, color=0) )

        # define some attributes
        scalarsymbol.add( dxf.attdef(insert=(1.25, -1.25), tag='VAL1', height=1.25, color=0) )

        # add block definition to the drawing
        dwg.blocks.add(scalarsymbol)

        for nID in self.points:
            x = self.points[nID][0]
            y = self.points[nID][1]
            val1 = self.points[nID][2]
            values = {'VAL1': "%.{0}f".format(dec) % val1}
            
            dwg.add(dxf.insert2(blockdef=scalarsymbol, insert=(x, y),
                                attribs=values,
                                xscale=scale,
                                yscale=scale,
                                layer='0',
                                color = col))

        dwg.save()
示例#9
0
    def draw(self, start=0, end=None, ext='svg', name=None):
        if end is None:
            end = os.path.getsize(self.source_path)
        if name is None:
            name = self.source_path.name
        name = f"{name}.{ext}"

        if ext == 'svg':
            from svgwrite        import Drawing
            from svgwrite.shapes import Rect
            dwg = Drawing(name, profile='tiny')

        elif ext == 'dxf':
            from dxfwrite import DXFEngine as dxf
            dwg = dxf.drawing(name)

        with open(self.source_path, 'rb') as source_file:
            for i, bit in enumerate(bits(source_file, start, end)):
                if bit == self.invert:
                    x = (i // self.height) * self.scale
                    y = (-i % self.height) * self.scale

                    params = {
                        'insert': (x, y),
                        'size': (self.scale, self.scale)
                    }
                    if ext == 'dxf':
                        rect = DxfRect(**params).to_face3d()
                    else:
                        rect = Rect(**params)
                    dwg.add(rect)
        dwg.save()
示例#10
0
    def SaveDXF(self):

        # Creates a dxf-file with the name written in the FileInput widget, adding the extension .dxf if it's not
        # present. Then creates a polyline entity in that file resembling the planned trajectory of the list, ignoring
        # all instructions in the list other than those with the 'go to: '-tag. Finally, the list of the ActionInputBox
        # widget is refreshed.

        filename = self._widget.FileInput.text()
        l = len(filename)
        if l > 3:
            if filename[(l - 4):l] != '.dxf':
                filename = filename + '.dxf'
        else:
            filename = filename + '.dxf'
        drawing = dxfE.drawing(self.pwd +
                               '/src/kampala/gui/src/gui/DXFFiles/' + filename)

        trajectory_points = []
        for point in self.pointlist:
            if point[0] == 'go to: ':
                trajectory_points.append(point[1])

        drawing.add(dxfE.polyline(trajectory_points))
        drawing.save()
        self.filelist = os.listdir(self.pwd +
                                   '/src/kampala/gui/src/gui/DXFFiles')
        self._widget.DXFInputBox.clear()
        self._widget.DXFInputBox.insertItems(0, self.filelist)
示例#11
0
def ExportDXF(self,param):
    output = cStringIO.StringIO()
    drawing = dxf.drawing('rectTube.dxf')

    cx=0
    cy=0
    cutid=1
    
    nf=[]
    nt=[]
    nl=[]


    #misure utili
    
    xz=0
    yz=0

    #Vista in Pianta
    

    
    # Vista di Fronte
    



    # Vista Laterale

   

    drawing.save_to_fileobj(output)
    dxf_result=[output.getvalue()]
    return dxf_result
示例#12
0
文件: dxf.py 项目: daveansell/camcam
def write_dxf(self,partName, key, output, border, config):
	drawing = dxf.drawing(self.sanitise_filename(str(partName)+"_"+str(key)+config['file_suffix']))
	drawing.header['$LUNITS']=1
	drawing.header['$AUNITS']=0
	drawing.header['$ANGBASE']=0

	drawing.header['$ACADVER']='AC1009'
	drawing.add_layer('LINES')
	if type(output) is not list:
	        for k,o in output.iteritems():
	                if type(o) is list:
	                        for p in o:
	                                if type(p) is list:
	                                        for q in p:
							if type(q) is list:
								for r in q:
	                                                        	drawing.add(r)
							else:
	                                                	drawing.add(q)
	                                else:
	                                        drawing.add(p)
	                else:
				drawing.add(0)
	else:	
		for o in output:
			if type(o) is list:
				for p in o:
					if type(p) is list:
						for q in p:
							drawing.add(q)
					else:
						drawing.add(p)
			else:
				drawing.add(o)
	drawing.save()
示例#13
0
    def draw(s, outfile):

        # Create image
        drawing = dxf.drawing(s.OUTFILE + outfile)
        drawing.add_layer('layer', color=1)

        # Draw text
        if s.includeText:
            text = ''
            text += ''.join(map(str, s.startBand))
            text += '-'
            text += ''.join(map(str, s.code))
            text += '-'
            text += ''.join(map(str, s.stopBand))
            drawing.add(dxf.text(text, height=s.unitWidth))

        # Initial offset
        xOffset = (s.size[0] - s.barWidth) / 2
        yOffset = (s.size[1] - s.barcodeLen) / 2

        # Draw notches
        for d in s.digits:
            newOffset = s.drawBar(drawing, d, xOffset, yOffset)
            yOffset = newOffset[1]

        # Draw final notch
        s.drawNotch(drawing, xOffset, yOffset)

        drawing.save()
示例#14
0
文件: dxfmaker.py 项目: zchlrnr/YoCad
def dxfmaker(Bdata, prof, rim, cup):
    Bmatrix2 = [(
        float(x[0]),
        float(x[1]),
    ) for x in Bdata]
    prof2 = [(
        float(x[0]),
        float(x[1]),
    ) for x in prof]
    rim2 = [(
        float(x[0]),
        float(x[1]),
    ) for x in rim]
    cup2 = [(
        float(x[0]),
        float(x[1]),
    ) for x in cup]
    drawing = dxf.drawing('drawing.dxf')
    polyline = dxf.polyline(linetype='LINE')
    polyline.add_vertices(Bmatrix2)
    polyline.add_vertices(prof2)
    polyline.add_vertices(rim2)
    polyline.add_vertices(cup2)
    drawing.add(polyline)
    drawing.save()
    return
示例#15
0
def output_dxf(box, material, cnc, filename):
    """ Output the drawing """
    drawing = dxf.drawing(filename)

    drawing.add_layer('TOP')
    top = dxf.polyline(flags=const.POLYLINE_CLOSED, layer='TOP')
    top.add_vertices([(0, 0),
                      (box.length, 0),
                      (box.length, box.width),
                      (0, box.width)])
    drawing.add(top)

    drawing.add_layer('BOTTOM')
    bottom = dxf.polyline(flags=const.POLYLINE_CLOSED, layer='BOTTOM')
    bottom_coord = [(0, 0),
                    (box.length, 0),
                    (box.length, box.width),
                    (0, box.width)]
    bottom_coord = [ (x + box.length + margin, y) for x,y in bottom_coord ]
    bottom.add_vertices(bottom_coord)
    drawing.add(bottom)

    drawing.add_layer('SIDE')
    side = dxf.polyline(flags=const.POLYLINE_CLOSED, layer='SIDE')
    perimeter = (box.length + box.width)*2
    side_coord = [(0, 0),
                  (perimeter, 0),
                  (perimeter, box.height),
                  (0, box.height)]
    side_coord = [ (x + 2*(box.length + margin), y) for x,y in side_coord ]
    side.add_vertices(side_coord)
    drawing.add(side)


    drawing.save()
示例#16
0
def run(fpfile, dxffile):
	
	# read the input floorplan
	fp = fp_io.Floorplan(fpfile)

	# prepare the output dxf file
	drawing = dxf.drawing(dxffile)

	# iterate over the rooms of the floor plan
	for room_id in range(fp.num_rooms):

		# make a layer for this room
		room_layer_name = 'room_' + str(room_id+1)
		room_layer = dxf.layer(room_layer_name) 
		room_layer['color'] = 1+room_id # valid colors: [1,255]
		drawing.layers.add(room_layer)
		
		# generate the objects for this room
		obj_arr = room_to_polylines(fp, room_id)

		# draw each object in the room
		for pi in range(len(obj_arr)):
			# add each object to the drawing
			obj_arr[pi]['layer'] = room_layer_name
			obj_arr[pi]['color'] = 256 # color by layer
			obj_arr[pi]['paper_space'] = 0 # put in model space
			drawing.add(obj_arr[pi])

	# save the drawing to file
	drawing.save()
示例#17
0
def create_dxf(p):
    drawing = dxf.drawing('test.dxf')
    drawing.add_layer('OUTLINE', color=1)
    polyline = dxf.polyline(layer="OUTLINE")
    polyline.add_vertices(p)
    drawing.add(polyline)
    drawing.save()
示例#18
0
def gen_dxf(name, c0, c1):

    lines = c1.gen_lines()

    drawing = dxf.drawing(name)

    # base line is the circumfrence of c1
    base = 2.0 * math.pi * c1.r
    drawing.add(dxf.line((0.0, 0.0), (base, 0.0)))

    for i in range(_NDIVS):
        x = i * base / _NDIVS
        t_vals = c0.intersect_line(lines[i])
        if t_vals[0] == 'inf':
            pass
        elif t_vals[0] == '0':
            drawing.add(dxf.line((x, 0.0), (x, c1.l)))
        elif t_vals[0] == '1':
            drawing.add(dxf.line((x, 0.0), (x, c1.l)))
        elif t_vals[0] == '2':
            if t_vals[1] > t_vals[2]:
                y0 = t_vals[2]
                y1 = t_vals[1]
            else:
                y1 = t_vals[2]
                y0 = t_vals[1]
            drawing.add(dxf.line((x, 0.0), (x, y0)))
            drawing.add(dxf.line((x, y1), (x, c1.l)))

    drawing.save()
示例#19
0
 def test_add_anonymous_block(self):
     dwg = dxf.drawing()
     blockname = dwg.add_anonymous_block("TEST")
     self.assertTrue(re.match("^\*U\d*$", blockname))
     block = dwg.blocks.find(blockname)
     entity = block.get_data().pop()
     self.assertEqual(entity, "TEST")
示例#20
0
def main():
    d = dxf.drawing('gear.dxf')
    #g = cycloid_gear(36, 1.5)
    g = involute_gear(32, 169.4, 8)
    g.draw(d)
    d.save()
    print g
def plot_lines(data):  #cad
    def plot_line(x, y, vs, ds, cengshu):
        for v, d in zip(vs, ds):
            line = dxf.line((x, y), end_point(x, y, v, d))
            drawing.add(line)
            line['layer'] = cengshu

    def end_point(x, y, velocity, direction):
        v_east = velocity * np.sin(direction / 180 * np.pi)
        v_north = velocity * np.cos(direction / 180 * np.pi)
        return [x + v_east, y + v_north]

    style = data['tidestyle']
    drawing = dxf.drawing('流速矢量图.dxf')
    x = data['x'].dropna().values[0]
    y = data['y'].dropna().values[0]
    plot_line(x, y, data['v_0'].values, data['d_0'], '表层')
    plot_line(x, y, data['v_2'].values, data['d_2'], '0.2层')
    plot_line(x, y, data['v_4'].values, data['d_4'], '0.4层')
    plot_line(x, y, data['v_6'].values, data['d_6'], '0.6层')
    plot_line(x, y, data['v_8'].values, data['d_8'], '0.8层')
    plot_line(x, y, data['v_10'].values, data['d_10'], '底层')
    plot_line(x, y, data['v_max'].values, data['d_v_max'], '底层')
    plot_line(x, y, data['v_max'].values, data['d_v_max'], '底层')
    plot_line(x, y, data['v'].values, data['d'], '垂线平均')
    drawing.save()
    print('ok')
示例#22
0
 def test_add_anonymous_block(self):
     dwg = dxf.drawing()
     blockname = dwg.add_anonymous_block("TEST")
     self.assertTrue(re.match(r"^\*U\d*$", blockname))
     block = dwg.blocks.find(blockname)
     entity = block.get_data().pop()
     self.assertEqual(entity, "TEST")
示例#23
0
def gen_dxf(name, c0, c1):

    lines = c1.gen_lines()

    drawing = dxf.drawing(name)

    # base line is the circumfrence of c1
    base = 2.0 * math.pi * c1.r
    drawing.add(dxf.line((0.0, 0.0), (base, 0.0)))

    for i in range(_NDIVS):
        x = i * base / _NDIVS
        t_vals = c0.intersect_line(lines[i])
        if t_vals[0] == 'inf':
            pass
        elif t_vals[0] == '0':
            drawing.add(dxf.line((x, 0.0), (x, c1.l)))
        elif t_vals[0] == '1':
            drawing.add(dxf.line((x, 0.0), (x, c1.l)))
        elif t_vals[0] == '2':
            if t_vals[1] > t_vals[2]:
                y0 = t_vals[2]
                y1 = t_vals[1]
            else:
                y1 = t_vals[2]
                y0 = t_vals[1]
            drawing.add(dxf.line((x, 0.0), (x, y0)))
            drawing.add(dxf.line((x, y1), (x, c1.l)))

    drawing.save()
示例#24
0
文件: g2.py 项目: soldocode/g2
 def toDXF(self):
     output = io.StringIO()
     drawing = dxf.drawing('drawing.dxf')
     for id in self.Scene:
         if self.Scene[id]['Class'] == 'PATH':
             path = self.Scene[id]['Path']
             for i in range(0, len(path.geometries)):
                 geo = path.geo(i)
                 geo.writeDXF(drawing, self.Scene[id]['Position'])
         if self.Scene[id]['Class'] == 'GEO':
             geo = self.Scene[id]['Geo']
             geo.writeDXF(drawing, self.Scene[id]['Position'])
         if self.Scene[id]['Class'] == 'TXT':
             text = dxf.text(
                 self.Scene[id]['Txt'],
                 height=self.Scene[id]['Height'],
             )
             text['insert'] = (self.Scene[id]['Position'][0],
                               self.Scene[id]['Position'][1])
             text['layer'] = 'TEXT'
             text['color'] = 7
             drawing.add(text)
     drawing.save_to_fileobj(output)
     dxf_result = output.getvalue()
     return dxf_result
示例#25
0
 def build_dxf(self, scale, offset, diameter):
     drawing = dxf.drawing('Drawing.dxf')
     print('\n' + Fore.RESET + 'Выполняется построение объекта...')
     counter = 0
     for pin in self.pins:
         x = int(pin[0]) * scale
         y = int(pin[1]) * scale
         drawing.add(dxf.circle(diameter / 2, (x, y)))
         counter += 1
         print('item added', x, y)
     drawing.add(dxf.line((min(self.rangex) * scale - offset, min(self.rangey) * scale - offset),
                          (max(self.rangex) * scale + offset, min(self.rangey) * scale - offset),
                          color=1))
     drawing.add(dxf.line((max(self.rangex) * scale + offset, min(self.rangey) * scale - offset),
                          (max(self.rangex) * scale + offset, max(self.rangey) * scale + offset),
                          color=1))
     drawing.add(dxf.line((max(self.rangex) * scale + offset, max(self.rangey) * scale + offset),
                          (min(self.rangex) * scale - offset, max(self.rangey) * scale + offset),
                          color=1))
     drawing.add(dxf.line((min(self.rangex) * scale - offset, max(self.rangey) * scale + offset),
                          (min(self.rangex) * scale - offset, min(self.rangey) * scale - offset),
                          color=1))
     print('Построение завершено.')
     printtable()
     try:
         drawing.save()
         print('Результат сохранен в файл ' + Fore.CYAN + 'Drawing.dxf' + Fore.RESET)
     except PermissionError:
         print(Fore.RED + 'ФАЙЛ ЗАНЯТ ДРУГИМ ПРИЛОЖЕНИЕМ.' + Fore.RESET)
示例#26
0
def generate_dxf(root_path, session_id, lines_dict, sheet_length):
    x_offset = int(sheet_length * 1.1)
    y_offset = 30
    keys = lines_dict.keys()

    drawing = dxf.drawing(root_path + "/data/" + session_id + '/cutout.dxf')
    drawing.add_layer('LINES')

    for i in range(len(keys)):
        key = keys[i]
        for line in lines_dict[key]:
            start = (line[0][0] + x_offset * i, line[0][1] + y_offset)
            end = (line[1][0] + x_offset * i, line[1][1] + y_offset)
            drawing.add(dxf.line(start, end, color=7, layer='LINES'))

    drawing.add_layer('TEXTLAYER', color=2)

    for i in range(len(keys)):
        key = keys[i]
        drawing.add(
            dxf.text(key,
                     insert=(i * x_offset, 0),
                     layer='TEXTLAYER',
                     height=25))

    drawing.add_vport('*ACTIVE',
                      upper_right=(100, 100),
                      center_point=(50, 50),
                      grid_spacing=(1, 1),
                      snap_spacing=(1, 1),
                      aspect_ratio=20)
    drawing.save()
示例#27
0
	def save_traced_scene(self,dxf_file):
		""" write geometry and traced rays to a DXF file for your viewing pleasure. It's no fun with more than a few 100 rays though. 
		 >1000 rays look like sonic the sea urchin."""
		drawing = dxf.drawing(dxf_file)
		drawing.add_layer('Rays', color=3)
		drawing.add_layer('Geometry', color=5)
		
		print "Writing results as DXF file."
		for res in self.results:
			rays_origin	= res[0]
			rays_dest	= res[1]
		
			#draw rays to dxf
			for (r0,rd) in zip(rays_origin,rays_dest):
				drawing.add(dxf.face3d([r0[0:3], 
							rd[0:3], 
							rd[0:3]], layer="Rays"))

		#draw facets
		(m_v0,m_v1,m_v2)=self.geometry
		for (t0,t1,t2) in zip(m_v0,m_v1,m_v2):
			drawing.add(dxf.face3d([t0[0:3], 
						t1[0:3], 
						t2[0:3]], layer="Geometry"))

		drawing.save()	
示例#28
0
def main():
    anguloIni = 0
    anguloFin = 300
    base = 40
    altura = 80
    anguloIni1 = 60
    anguloFin1 = 100
    base1 = 40
    altura1 = 60
    drawing = dxf.drawing('capa.dxf')
    drawCircleColouredLayer(drawing, 80, 105, 148.5, 1, currentLayer)
    drawCircleColouredLayer(drawing, 40, 105, 148.5, 2, 'sector1')
    drawArcColouredLayer(drawing, 105, 148.5, 60, anguloIni, anguloFin, 3,
                         'sector2')
    escribeEnArcoCapa(drawing, 'adios', 105, 148.5, base, anguloIni, anguloFin,
                      colorLine3, 24.0, currentLayer, 2, 254.0)
    #set value
    #	drawing.header['$ANGBASE'] = 90
    #	drawing.header['$ANGDIR'] = 1
    #px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,anguloIni,anguloFin,base,altura,colorLine3,'sector1')
    #px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,anguloIni1,anguloFin1,base1,altura1,colorLine2,'sector2')
    # px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoCono(drawing,anguloIni,anguloFin,base,altura,colorLine3)
    # px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoCono(drawing,anguloIni1,anguloFin1,base1,altura1,colorLine2
    #--------------------------------
    #writeTextNoAling(drawing,'universidad',px0,py0,12,5,currentLayer,0)
    #escribeEnArco(drawing,'universidad',centroX,centroY,base,anguloIni,anguloFin,colorLine,5)
    drawing.save()
示例#29
0
    def create_dxf(self, file_path, polyline_controller, model, calib_controller):
        """ Creates a DXF file at the given 'file_path' location """
        if polyline_controller:
            # Create a DXF object
            drawing = dxf.drawing(file_path)
            points = []

            # Header information
            self.add_header(drawing, '$ACADVER', 'AC1014')

            # Add the polylines
            drawing.add_layer('POLYLINES', color=2)

            # DGZ 16 Aug 2012
            # Bug fix for DXF y-axis flipping error
            # code provided by Adam Childs
            # Convert (0, 0) to bottom-left instead of upper-left for drill program
            #
            sY, sX = model.get_image_shape()

            # Loops through all polylines
            for polyline in polyline_controller.polylines:
                # Loops through all verticies of each polyline
                for vertex in polyline.verticies:
                    try:
                        x = int(vertex.get_xdata())
                        y = int(vertex.get_ydata())
                    except TypeError:
                        # This error is thrown when one of the user's polylines goes outside the coordinates of the image.
                        # For some reason (that I'm not sure of at the moment), the data is put into a 1 element list. So
                        # the fix is to just take the 0th element of the list and then cast it to an integer...
                        # 
                        # Adam Childs (11/17/2012)
                        x = int(vertex.get_xdata()[0])
                        y = int(vertex.get_ydata()[0])

                    y = sY - y
                    
                    x /= float(calib_controller.pixels_per_unit)
                    y /= float(calib_controller.pixels_per_unit)

                    # Set the units in mm
                    if calib_controller.unit == 'cm':
                        x *= 10
                        y *= 10
                    elif calib_controller.unit == 'in':
                        x *= 25.4
                        y *= 25.4

                    points.append((x, y))
                
                # Adds the points to a polyline object, which is added to the DXF file
                drawing.add(dxf.polyline(points))
                points = [] # Reset points for the next polyline to use

            drawing.save()
        else:
            wx.MessageBox('No polylines have been found. Please add some.', 'No polylines!', wx.OK | wx.ICON_ERROR)
            return
示例#30
0
    def writeDxfFile(self,fileName):
        '''Write mesh in a DXF file.

        :param fileName: name of the DXF file to write.
        '''
        drawing= DXFEngine.drawing(fileName)
        self.writeDxf(drawing)
        drawing.save()    
示例#31
0
def WriteDXF(filename, lines, elevations, scaler):
    drawing = DXFEngine.drawing(filename)
    for idx in xrange(len( lines )):
        points = []
        for point in lines[idx]:
            points.append(scaler.inverse((point[0], point[1])))
        drawing.add(DXFEngine.polyline(points, polyline_elevation = (0,0,elevations[idx])))
    drawing.save()
示例#32
0
 def test_properties(self):
     dwg = dxf.drawing()
     self.assertTrue(dwg.linetypes)
     self.assertTrue(dwg.layers)
     self.assertTrue(dwg.styles)
     self.assertTrue(dwg.views)
     self.assertTrue(dwg.viewports)
     self.assertTrue(dwg.ucs)
示例#33
0
def main():
    centroX = 1.0
    centroY = 10.0
    drawing = dxf.drawing("paleta.dxf")
    for i in range(256):
        creaTroncoConoSolidoCapa(drawing, centroX, centroY, 80.0, 90.0, 20, 25, i, "paleta")
        centroY = centroY + 2.0
        print("imprimiendo:", i)
示例#34
0
 def test_properties(self):
     dwg = dxf.drawing()
     self.assertTrue(dwg.linetypes)
     self.assertTrue(dwg.layers)
     self.assertTrue(dwg.styles)
     self.assertTrue(dwg.views)
     self.assertTrue(dwg.viewports)
     self.assertTrue(dwg.ucs)
def main():
    parser = OptionParser()
    parser.add_option("-n", "--name", dest="name",
            help="Name of the hinge.  Program will load file called <name>.json and output <name>-face.dxf and <name>-temple.dxf.", metavar = "HINGENAME")

    (options, args) = parser.parse_args()

    if options.name == None:
        sys.stderr.write("Not enough arguments")
        parser.print_help()
        sys.exit(0)

    name = options.name
    infile = open(name + ".json")
    hinge = json.loads(infile.read())

    face = hinge["face_contour"]
    temple = hinge["temple_contour"]
    face_hole_diam = hinge["drill_dia"]
    temple_hole_diam = hinge["drill_dia"]
    face_holes = hinge["face_holes"]
    temple_holes = hinge["temple_holes"]

    face_drawing = dxf.drawing("./%s-face.dxf" % name)
    temple_drawing = dxf.drawing("./%s-temple.dxf" % name)
    face_drawing.add_layer("OUTLINE", color=1)
    face_drawing.add_layer("HOLES", color=2)
    temple_drawing.add_layer("OUTLINE", color=1)
    temple_drawing.add_layer("HOLES", color=2)

    face_outline = dxf.polyline(layer="OUTLINE", thickness = 0.1)
    face_outline.add_vertices(face)
    face_drawing.add(face_outline)
    for hole in face_holes:
        circ = dxf.circle(face_hole_diam/2.0, hole, layer="HOLES", thickness=0.1)
        face_drawing.add(circ)
    face_drawing.save()

    temple_outline = dxf.polyline(layer="OUTLINE", thickness = 0.1)
    temple_outline.add_vertices(temple)
    temple_drawing.add(temple_outline)
    for hole in temple_holes:
        circ = dxf.circle(temple_hole_diam/2.0, hole, layer="HOLES", thickness=0.1)
        temple_drawing.add(circ)
    temple_drawing.save()
示例#36
0
def main():
    centroX = 1.0
    centroY = 10.0
    drawing = dxf.drawing('paleta.dxf')
    for i in range(256):
        creaTroncoConoSolidoCapa(drawing, centroX, centroY, 80.0, 90.0, 20, 25,
                                 i, 'paleta')
        centroY = centroY + 2.0
        print('imprimiendo:', i)
示例#37
0
文件: drawing.py 项目: uclalemur/roco
 def to_DXF(self, filename=None, labels=False, mode="dxf"):
     """
     """
     from dxfwrite import DXFEngine as dxf
     dwg = dxf.drawing(filename)
     EdgeType.make_linetypes(dwg, dxf)
     for e in self.edges.items():
         e[1].to_drawing(dwg, e[0] if labels else "", mode=mode, engine=dxf)
     dwg.save()
def main(argv):
    filename = '../../ag03.dat'
    chord = [300.0, 290.0, 280.0, 270.0, 260.0, 250.0]

    try:
        opts, args = getopt.getopt(argv, "c:f:o:",
                                   ["chord=", "filename=", "outputfilename="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-c", "chord="):
            chord = float(arg)
        elif opt in ("-f", "filename="):
            filename = str(arg)
        elif opt in ("-o", "outputfilename="):
            outputfilename = str(arg)

    #DXF related INIT
    (root, ext) = os.path.splitext(outputfilename)
    saveName = root + '.dxf'
    drawing = dxf.drawing(saveName)
    #I found the below constant on the internet,  this could use verification
    chordnumber = 1.0
    for c in chord:
        scale = 1.0
        xOffset = 45.0
        yOffset = 45.0

        linePoints = []
        #pts = ""
        line = 0
        # Read airfoil data
        spamReader = csv.reader(open(filename, 'rb'),
                                delimiter=' ',
                                quotechar='|',
                                skipinitialspace="true")
        for row in spamReader:
            #Skip the first line of header information
            if (line != 0):
                #Format and store in a string
                #p= ((float(row[0])*chord+xOffset)*scale, (float(row[1])*-chord+yOffset)*scale)
                #swap the pomits around to orinetate vertically

                p = (float(row[1]) * c + xOffset * chordnumber,
                     float(row[0]) * c)
                linePoints.append(p)
                print p, 'x', (row[0], row[1])
            line = 1

        polyline = dxf.polyline(linetype='CONTINUOUS')
        polyline.add_vertices(linePoints)
        drawing.add(polyline)
        chordnumber = chordnumber + 1.0

    drawing.save()
def main(argv):                         
    filename = '../../ag03.dat'
    chord = [300.0, 290.0, 280.0, 270.0, 260.0, 250.0]
                      
    try:
        opts, args = getopt.getopt(argv, "c:f:o:", ["chord=", "filename=", "outputfilename="])
    except getopt.GetoptError:          
        usage()                         
        sys.exit(2)
    
    for opt, arg in opts:                
        if opt in ("-c", "chord="):      
            chord = float(arg)               
        elif opt in ("-f", "filename="): 
            filename = str(arg)    
        elif opt in ("-o", "outputfilename="): 
            outputfilename = str(arg)          

    #DXF related INIT
    (root, ext) = os.path.splitext(outputfilename)
    saveName = root+'.dxf'    
    drawing = dxf.drawing(saveName)
    #I found the below constant on the internet,  this could use verification
    chordnumber = 1.0
    for c in chord:
        scale = 1.0 
        xOffset = 45.0 
        yOffset = 45.0
        
        
        linePoints = []
        #pts = ""
        line= 0
        # Read airfoil data
        spamReader = csv.reader(open(filename, 'rb'), delimiter=' ', quotechar='|', skipinitialspace="true")
        for row in spamReader:
            #Skip the first line of header information
            if(line!=0):
                #Format and store in a string
                #p= ((float(row[0])*chord+xOffset)*scale, (float(row[1])*-chord+yOffset)*scale)
                #swap the pomits around to orinetate vertically
                
                p = ( float(row[1])*c + xOffset*chordnumber , float(row[0])*c )
                linePoints.append(p)
                print p,'x', (row[0],row[1])
            line=1            
            
    
        
        polyline= dxf.polyline(linetype='CONTINUOUS')
        polyline.add_vertices( linePoints )
        drawing.add(polyline)
        chordnumber = chordnumber + 1.0
    
    
    drawing.save()
示例#40
0
def DrawCreator(name, type, parameter, material, thickness=0, address=dirc):

    file_name = name + '.dxf'  #加一步判据
    file_name = re.sub('[\\\]|[\/]|[\*]', '_', file_name)
    drawing = dxf.drawing(file_name)

    if 'od' in parameter and not ('id' in parameter):

        drawing.add(dxf.circle(radius=(parameter['od']) / 2, center=(0, 0)))
        # drawing.add(dxf.text(file_name,height=parameter[0]/4,alignpoint =(0,0)))
    elif 'od' in parameter and 'id' in parameter and not ('angle'
                                                          in parameter):

        drawing.add(dxf.circle(radius=(parameter['od']) / 2, center=(0, 0)))
        drawing.add(dxf.circle(radius=(parameter['id']) / 2, center=(0, 0)))
        # drawing.add(dxf.text(file_name,height=parameter[1]/4, alignpoint =(0,0)))
    elif 'od' in parameter and 'id' in parameter and 'angle' in parameter:
        drawing.add(
            dxf.arc(radius=parameter['od'] / 2,
                    center=(0, 0),
                    startangle=0,
                    endangle=parameter['angle']))
        drawing.add(
            dxf.arc(radius=(parameter['id']) / 2,
                    center=(0, 0),
                    startangle=0,
                    endangle=parameter['angle']))
        drawing.add(
            dxf.polyline(points=[(parameter['od'] / 2,
                                  0), ((parameter['id']) / 2, 0)]))
        drawing.add(
            dxf.polyline(
                points=[((parameter['od']) / 2 *
                         math.cos(parameter['angle'] * math.pi / 180),
                         (parameter['od']) / 2 *
                         math.sin(parameter['angle'] * math.pi / 180)),
                        ((parameter['id']) / 2 *
                         math.cos(parameter['angle'] * math.pi / 180),
                         (parameter['id']) / 2 *
                         math.sin(parameter['angle'] * math.pi / 180))]))
    elif 'w' in parameter and 'l' in parameter:

        drawing.add(
            dxf.polyline(points=[(0, 0), (
                0, parameter['w']), (parameter['l'],
                                     parameter['w']), (parameter['l'],
                                                       0), (0, 0)]))
    else:
        print(file_name + '无对应图形')
        # 创建对应_厚度_的文件夹
    if not path.exists(address + '//' + '材料_' + material + '_厚度_' +
                       str(thickness)):
        #如果文件夹不存在创建
        mkdir(address + '//' + '材料_' + material + '_厚度_' + str(thickness))
    chdir(address + '\\材料_' + material + '_厚度_' + str(thickness))
    drawing.save()
示例#41
0
def main():

    path = "./coordinate"
    # height of text labels
    text_h = 0.2
    # scale factor for dxf rappresentation
    fs = 100
    l_csv = os.listdir(path)
    df_coord = ReadCSV(path, l_csv)
    l_nomi_pti = NomiPti(df_coord)
    l_dates = Dates(df_coord)
    s_dates_zero = DatesZero(df_coord, l_nomi_pti)
    df_coord_zero = ZeroCoord(df_coord, l_nomi_pti, s_dates_zero)
    [df_delta, df_coord_mean] = DeltaCoord(df_coord, df_coord_zero, l_dates)
    df_delta_rel = DeltaCoordRel(l_dates, df_coord_mean)
    df_coord_rel = RelCoord(fs, l_dates, df_coord_mean, df_delta_rel,
                            df_coord_zero)

    # creation of dxf file of all dispacements
    drawing = dxf.drawing('paratia.dxf')
    PointsLabels(drawing, text_h, df_coord_zero)
    ScaleBarCreation(fs, text_h, drawing)
    DrawDisp(drawing, l_dates, df_coord_zero, df_coord_rel, text_h)

    # creation of plotly time-displacements graphs
    l_nomi_pti_graph = [
        '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'
    ]
    GraphTD(df_delta, l_nomi_pti_graph)

    # creation of plotly normal-displacements graphs
    # definizioni dei punti da rappresentare per ogni verticale
    l_vert_1 = ['07', '04', '01']
    filename_1 = 'graph_vert_1.html'
    l_vert_2 = ['08', '05', '02']
    filename_2 = 'graph_vert_2.html'
    l_vert_3 = ['09', '06', '03']
    filename_3 = 'graph_vert_3.html'
    # calcolo mutue distanze fra punti
    d_cum_1 = DistAlt(df_coord_zero, l_vert_1)
    d_cum_2 = DistAlt(df_coord_zero, l_vert_2)
    d_cum_3 = DistAlt(df_coord_zero, l_vert_3)
    # plotly normal-displacements graphs
    GraphSection(df_delta, d_cum_1, l_vert_1, filename_1)
    GraphSection(df_delta, d_cum_2, l_vert_2, filename_2)
    GraphSection(df_delta, d_cum_3, l_vert_3, filename_3)

    # write DataFrames to csv
    df_coord.to_csv('coordinate.csv',
                    sep='\t',
                    decimal=',',
                    float_format='%.3f')
    df_delta.to_csv('spostamenti.csv',
                    sep='\t',
                    decimal=',',
                    float_format='%.3f')
示例#42
0
	def write_dxf(self,dxf_file):
		""" writes geometry to a file by using the dxfwrite libs."""
		drawing = dxf.drawing(dxf_file)
		drawing.add_layer('0', color=2)
		for tri in self.triangles:
			drawing.add(dxf.face3d([self.vertices[tri[0]][0:3], 
						self.vertices[tri[1]][0:3], 
						self.vertices[tri[2]][0:3]], layer="0"))
		#drawing.add(dxf.text('Test', insert=(0, 0.2), layer='TEXTLAYER'))
		drawing.save()	
示例#43
0
def DXFWrite(edges, filename):
  from dxfwrite import DXFEngine as dxf
  dwg = dxf.drawing(filename)
  for e in edges:
    if e[2] is None:
      kwargs = {"layer": "Cut"}
    else:
      kwargs = {"layer": repr(e[2])}
    dwg.add(dxf.line((e[0][0], e[0][1]), (e[1][0], e[1][1]), **kwargs))
  dwg.save()
示例#44
0
def create_dxf(filename, polys):
    drawing = dxf.drawing(filename)
    drawing.add_layer('OUTLINE', color=1)
    for p in polys:
        polyline = dxf.polyline(layer="OUTLINE")
        p = p + [p[0], p[1]]  # Close the polygon to avoid a cusp
        polyline.add_vertices(p)
        drawing.add(polyline)

    drawing.save()
示例#45
0
def create_dxf(filename, polys):
    drawing = dxf.drawing(filename)
    drawing.add_layer('OUTLINE', color=1)
    for p in polys:
        polyline = dxf.polyline(layer="OUTLINE")
        p = p + [p[0], p[1]]  # Close the polygon to avoid a cusp
        polyline.add_vertices(p)
        drawing.add(polyline)

    drawing.save()
示例#46
0
def dxfSketch(VPointList, VLinkList, fileName):
    edges = v_to_slvs(VPointList, VLinkList)
    mechanism = dxf.drawing(fileName)
    for vpoint in VPointList:
        mechanism.add(dxf.point((vpoint.cx, vpoint.cy)))
    for p1, p2 in edges:
        vp1 = VPointList[p1]
        vp2 = VPointList[p2]
        mechanism.add(dxf.line((vp1.cx, vp1.cy), (vp2.cx, vp2.cy)))
    mechanism.save()
示例#47
0
文件: graph.py 项目: donrv/ROSLab
def DXFWrite(edges, filename):
    from dxfwrite import DXFEngine as dxf
    dwg = dxf.drawing(filename)
    for e in edges:
        if e[2] is None:
            kwargs = {"layer": "Cut"}
        else:
            kwargs = {"layer": repr(e[2])}
        dwg.add(dxf.line((e[0][0], e[0][1]), (e[1][0], e[1][1]), **kwargs))
    dwg.save()
示例#48
0
def main():
	texto='en'
	capa='sector1'
	anguloIni=30.0
	anguloFin=85.0
	base=40
	altura=80
	anguloIni1=60.0
	anguloFin1=100.0
	altura1=60
	altura2=70
	primeraLinea=5
	segundaLinea=10
	drawing = dxf.drawing('curriculo.dxf')
	refRosco=[(altura,anguloIni,anguloFin,texto,colorLine2,capa),(60,85.0,170.0,'supercalifragilistico',3,'sector2'),(70,170.0,180.0,'lugar',4,'sector3'),(65,180.0,210.0,'de',5,'sector4'),(50,210.0,270.0,'la',6,'sector5'),(75,270.0,360.0,'mancha',128,'sector6')]
#set value
#	drawing.header['$ANGBASE'] = 90
#	drawing.header['$ANGDIR'] = 1

	for i in refRosco:
		print ('altura:',i[0])
		print ('anguloIni:',i[1])
		print ('anguloFin:',i[2])
		print ('texto:',i[3])
		print ('color:',i[4])
		print ('capa:',i[5])
		px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,i[1],i[2],base,i[0],i[4],i[5])
		escribeEnArcoCapa(drawing,i[3],centroX,centroY,i[1],i[2],i[0]-primeraLinea,colorLine,3.0,'letras'+ i[5],0)
		testeaAlineacionLetras(drawing,i[1],i[2],centroX,centroY,altura * 2,colorLine,'Guias')
	#px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,30.0,60.0,base,altura,colorLine2,'sector1')
	#escribeEnArcoCapa(drawing,'en',centroX,centroY,30.0,60.0,altura-primeraLinea,colorLine,3.0,'letrasSector1',0)
	'''
	px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,60.0,100.0,base,altura1,colorLine3,'sector2')
	escribeEnArcoCapa(drawing,'supercalifragilistico',centroX,centroY,60.0,100.0,altura1-primeraLinea,colorLine,3.0,'letrasSector2',0)
	px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,100.0,180.0,base,altura2,colorLine4,'sector3')
	escribeEnArcoCapa(drawing,'lugar',centroX,centroY,100.0,180.0,altura2-primeraLinea,colorLine,3.0,'letrasSector3',0)
	px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,180.0,210.0,base,65,colorLine5,'sector4')
	escribeEnArcoCapa(drawing,'de',centroX,centroY,180.0,210.0,65-primeraLinea,colorLine,3.0,'letrasSector4',0)
	px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,210.0,270.0,base,50,colorLine6,'sector5')
	escribeEnArcoCapa(drawing,'la',centroX,centroY,210.0,270.0,50-primeraLinea,colorLine,3.0,'letrasSector5',0)
	px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoConoSolidoCapa(drawing,270.0,360.0,base,75,colorLine7,'sector6')
	escribeEnArcoCapa(drawing,'mancha',centroX,centroY,270.0,360.0,75-primeraLinea,colorLine,3.0,'letrasSector6',0)
	testeaAlineacionLetras(drawing,30.0,60.0,centroX,centroY,altura * 2,colorLine,'Guias')
	testeaAlineacionLetras(drawing,60.0,100.0,centroX,centroY,altura * 2,colorLine,'Guias')
	testeaAlineacionLetras(drawing,100.0,180.0,centroX,centroY,altura * 2,colorLine,'Guias')
	testeaAlineacionLetras(drawing,180.0,210.0,centroX,centroY,altura * 2,colorLine,'Guias')
	testeaAlineacionLetras(drawing,210.0,270.0,centroX,centroY,altura * 2,colorLine,'Guias')
	testeaAlineacionLetras(drawing,270.0,360.0,centroX,centroY,altura * 2,colorLine,'Guias')'''
	#escribeEnArcoCapa(drawing,'hola esta es la creacion',centroX,centroY,base,anguloIni,anguloFin,colorLine3,12,'sector1',0,330)
	# px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoCono(drawing,anguloIni,anguloFin,base,altura,colorLine3)
	# px0,py0,pxd,pyd,px0a,py0a,pxda,pyda=creaTroncoCono(drawing,anguloIni1,anguloFin1,base1,altura1,colorLine2
	#--------------------------------
	#writeTextNoAling(drawing,'universidad',px0,py0,12,5,currentLayer,0)
	#escribeEnArco(drawing,'universidad',centroX,centroY,base,anguloIni,anguloFin,colorLine,5)
	drawing.save()
示例#49
0
def csv_to_trophy(path, filename='output', outpath='', outline=False, logopoints=False):
    """Reads from a csv, trophifying all of the things"""
    try:
        with open(os.path.expanduser(path)) as f:
            reader = csv.reader(f)
            counter = 0
            drawing_counter = 0
            for iteration, line in enumerate(reader):
                if line[0].startswith('##') or line[1].startswith('##'): # comment line
                    continue

                if len(line) != 2:  # invalid line
                    print("Line %d is invalid [%s]" % (iteration+1, line))



                else:
                    name, year = line
                    if len(name) == 0 and len(year) == 0: # empty line,created by EXCLE WHEN YOU PRESS ARROW DOWN COMMAND
                        continue

                    if len(name) == 0 or len(year) == 0:
                        print("Length of line %d, is invalid (one entry is 0 length)" % (iteration+1))
                        continue



                    if counter == 0:
                        _drawing = dxf.drawing()
                        drawing_counter += 1
                        if outline:
                            generate_template(h1,h2,w,_drawing)

                    if counter <= 3:  # trophies on the left, pointing down
                        add_school_trophy(ref_points[counter], _drawing, name, year, 'down')

                    elif counter <= 7:
                        add_school_trophy(ref_points[counter], _drawing, name, year, 'up')

                    elif counter == 8:
                        add_school_trophy(ref_points[counter], _drawing, name, year, 'right')

                    elif counter == 9:
                        add_school_trophy(ref_points[counter], _drawing, name, year, 'left')
                        counter = -1
                        save_file(_drawing, filename, outpath, drawing_counter)

                    counter += 1
            if counter != 0:
                save_file(_drawing, filename, outpath, drawing_counter)
            if logopoints:
                write_points()
    except FileNotFoundError:
        print("file '%s' not found! Aborting"% path)
        sys.exit(-4)
示例#50
0
def comp2dxf(comp, fname, sample_interval, traverse_interval, scale, clip, layer):
    
    """
    comp; Numpy array of shape length, width
    fname; filepath to save dxf
    sample_interval; distance between samples (m)
    traverse_interval; distance between traverses
    scale; z units/cm
    clip; value to clip data at (z units)
    layer; name of dxf layer (string)
    """
    
    #Copies Comp & Flips along horizontal axis
    #Copy to avoid flipping,clipping original data
    #FlipUD due to positional referencing
    comp = np.flipud(np.copy(comp))
    
    #Initiates the dxf using DXFEngine
    drawing = dxf.drawing(fname)
    
    #Creates a layer for the polylines to reside
    drawing.add_layer(str(layer))
    
    #sets the first line position to be the centre of a traverse
    y = 0.5*traverse_interval

    #iterates through the traverses
    for row in comp:
        #Calculates the x position of each data point
        x_pos = np.arange(len(row))
        x_pos = np.multiply(x_pos,sample_interval)
        
        #clips the magnitude according to user input
        y_pos = np.clip(row,-clip,clip)
        
        #scales the magnitude according to user input
        y_pos = np.divide(np.multiply(y_pos,scale),clip*100)
        
        #shifts the magnitude to centre on correct traverse location
        y_pos = np.add(y_pos, y)
        
        #calculates position of next traverse
        y += traverse_interval
        
        #splits traverses on Nan. Polylines cannot bridge Nan
        lines = using_clump(x_pos, y_pos)
        
        #For each traverse section (from nan splitting) creates a polyline & adds to drawing
        for line in lines:
            polyline = dxf.polyline(layer=str(layer))
            polyline.add_vertices(line)
            drawing.add(polyline)
    
    #Saves Drawing
    drawing.save()
示例#51
0
def main():
	centroX = 1.0
	centroY = 10.0
	drawing = dxf.drawing('paleta1.dxf')
	for i in range(256):
		creaTroncoConoSolidoCapa(drawing,centroX,centroY,80.0,90.0,20,25,i,'paleta')
		escribeEnArcoCapa(drawing,str(i),centroX,centroY,80.0,90.0,20,1,3.0,'letras',0)
		centroY = centroY + 10.0
		if (i%25==0): #cada 25 
			centroX = centroX + 20 #salta a la derecha
		print ('imprimiendo:',i)
示例#52
0
def write_figure_in_dxf(ai_figure, ai_filename):
  """ Generate the DXF file ai_filename from the figure ai_figure (list of format B outline)
  """
  print("Generate with mozman dxfwrite the DXF file {:s}".format(ai_filename))
  object_dxf = DXFEngine.drawing(ai_filename)
  #object_dxf.add_layer("my_dxf_layer")
  for i_ol in ai_figure:
    dxf_outline = outline_arc_line(i_ol, 'dxfwrite')
    for one_line_or_arc in dxf_outline:
      object_dxf.add(one_line_or_arc)
  object_dxf.save()
  return(0)
示例#53
0
文件: trees.py 项目: kmartine/trees
def dxf_gen():
    drawing = dxf.drawing(sys.argv[2] + ".dxf")
    drawing.header['$LUNITS'] = 4
    drawing.add_layer('LINES')

    for i in xrange(len(coords)):
       drawing.add(dxf.line((coords[i-1].x, coords[i-1].y),
                                  (coords[i].x,coords[i].y),
                                  color=1,
                                  layer='LINES'))

    drawing.save()
示例#54
0
def export_dxf(glider, path="", midribs=0, numpoints=None, *other):
    outfile = dxf.drawing(path)
    other = glider.copy_complete()
    if numpoints:
        other.numpoints = numpoints
    ribs = other.return_ribs(midribs)
    panels = []
    points = []
    outfile.add_layer('RIBS', color=2)
    for rib in ribs:
        outfile.add(dxf.polyface(rib * 1000, layer='RIBS'))
        outfile.add(dxf.polyline(rib * 1000, layer='RIBS'))
    return outfile.save()
示例#55
0
    def composite_on_dxf_using_polygons(self):
        drawing = dxf.drawing()

        for c in self._polygon.get_palet():
            drawing.add_layer(c.name, color=c.value)
            #print(c.name)
        
        for poly in self._polygon.polygon_list:
            polyline = dxf.polyline(linetype='DOT', layer=poly.color_layer.name)
            polyline.add_vertices(poly.get_points())
            polyline.close()
            drawing.add(polyline)
        return drawing
示例#56
0
 def __init__(self, b, t, h, dis, das, df):
     self.b = b
     self.t = t
     self.h = h
     self.x_off = 0
     self.y_off = 0
     self.dis = dis
     self.das = das
     self.df = df
     self.drawing = dxf.drawing('kast.dxf')
     self.drawing.add_layer('LINES')
     self.hori_schlitze = []
     self.vert_schlitze = []
示例#57
0
def create_dxf_drawing():
    dwg = dxf.drawing() # create a drawing
    # add the active viewport
    dwg.add_vport(
        '*Active',
        center_point=(0, 0),
        height = 30,
        direction_point=(30, 30, 10)
        )
    for x in range(10):
        for y in range(10):
            dwg.add(get_cube((x,y, random()), random()))
    return dwg