Esempio n. 1
0
def main(filein, fileout, width, height, gap):
    d = dxfgrabber.read(filein)

    def flipxy(p):
        return (p[1], p[0])

    layers = {}
    for r in d.entities:
        if not r.layer in layers:
            layers[r.layer] = []
        layers[r.layer].append(map(flipxy, r.points))

    polys_to_cut = []
    for (_, ps) in layers.iteritems():
        polys_to_cut += map(lambda p: geo.extend_poly(gap, p, False), ps)

    h = height / 2.0
    w = width / 2.0

    gndplane = Polygon([(h, w), (-h, w), (-h, -w), (h, -w)])

    for p in polys_to_cut:
        gndplane = gndplane - Polygon(p)

    # Polygon.triStrip() returns a list of tristrips which need to be
    # turned into quads, and the list needs to be flattened.
    layers["GROUND"] = [
            quad for quads in map(
                geo.tristrip_to_quads,
                gndplane.triStrip())
            for quad in quads]

    drawing = DXFEngine.drawing(fileout)
    for (l, qs) in layers.iteritems():
        for q in qs:
            drawing.add(DXFEngine.face3d(map(flipxy, q), layer=l))
    drawing.save()
Esempio n. 2
0
    def parse(self, dxfInput, forced_unit):
        dxfStream = io.StringIO(str(dxfInput.replace('\r\n', '\n')))
        dwg = dxfgrabber.read(dxfStream)
        if not dwg:
            raise RuntimeError("dxfgrabber.read() failed")

        # TODO: check DXF version to see if INSUNITS is expected
        # TODO: try and guess mm vs in based on max x/y
        # set up unit conversion
        #
        # 0 unitless
        # 1 inches
        # 2 feet
        # 3 miles
        # 4 mm
        # 5 cm
        # 6 m
        # 7 km
        # 8 microinches
        # 9 mils
        # 10 yards
        # 11 angstroms
        # 12 nanometeres
        # 13 microns
        # 14 decimeters
        # 15 decameters
        # 16 hectometers
        # 17 gigameters
        # 18 au
        # 19 light years
        # 20 parsecs

        if forced_unit == 0 or forced_unit == None:
            self.units = dwg.header.setdefault('$INSUNITS', 0)
        else:
            print(("using forced_unit", forced_unit))
            self.units = forced_unit
        if self.verbose:
            print(("dxf units read %s, default 0 " % self.units))
        if self.units == 0:
            self.unitsString = "unitless"
        elif self.units == 1:
            self.unitsString = "inches"
        elif self.units == 2:
            self.unitsString = "feet"
        elif self.units == 3:
            self.unitsString = "miles"
        elif self.units == 4:
            self.unitsString = "mm"
        elif self.units == 5:
            self.unitsString = "cm"
        elif self.units == 6:
            self.unitsString = "m"
        elif self.units == 7:
            self.unitsString = "km"
        elif self.units == 8:
            self.unitsString = "microinch"
        elif self.units == 9:
            self.unitsString = "mils"
        elif self.units == 10:
            self.unitsString = "yards"
        elif self.units == 11:
            self.unitsString = "angstroms"
        elif self.units == 12:
            self.unitsString = "nanometers"
        elif self.units == 13:
            self.unitsString = "microns"
        elif self.units == 14:
            self.unitsString = "decimeters"
        elif self.units == 15:
            self.unitsString = "decameters"
        elif self.units == 16:
            self.unitsString = "hectometers"
        elif self.units == 17:
            self.unitsString = "gigameters"
        elif self.units == 18:
            self.unitsString = "astronomical units"
        elif self.units == 19:
            self.unitsString = "light years"
        elif self.units == 20:
            self.unitsString = "parsecs"
        else:
            print(("DXF units: >%s< unsupported" % self.units))
            raise RuntimeError

        if self.verbose:
            print(("dxfgrabber release: ", self.dxfgrabber_version))
            print(("DXF file format version: {}".format(dwg.dxfversion)))
            print(("header var count: ", len(dwg.header)))
            print(("layer count: ", len(dwg.layers)))
            print(("block def count: ", len(dwg.blocks)))
            print(("entitiy count: ", len(dwg.entities)))
            print(("units: ", self.unitsString))

        for entity in dwg.entities:
            if entity.color == dxfgrabber.BYLAYER:
                layer = dwg.layers[entity.layer]
                entity.color = layer.color
                if self.debug:
                    print(("set entity color to layer color %d" % layer.color))

            if entity.dxftype == "LINE":
                self.addLine(entity)
            elif entity.dxftype == "ARC":
                self.addArc(entity)
            elif entity.dxftype == "CIRCLE":
                self.addCircle(entity)
            elif entity.dxftype == "LWPOLYLINE":
                self.addPolyLine(entity)
            elif entity.dxftype == "SPLINE":
                print(("TODO ADD: ", entity.dxftype))
                #self.addSpline(entity)
            else:
                if self.verbose:
                    print(("unknown entity: ", entity.dxftype))

        print("Done!")

        if self.verbose:
            print("pre flipped")
            print(("x min %f" % self.x_min))
            print(("x max %f" % self.x_max))
            print(("y min %f" % self.y_min))
            print(("y max %f" % self.y_max))

        # remember that Y is in negative space relative to our bed,
        # CAD software has 0,0 and bottom left, lasersaur has
        # it at top left.
        if self.x_min < 0 or self.y_max > -self.bedwidth[1]:
            if self.verbose:
                print("doing shiftPositive")
            self.shiftPositive()

        self.validateBoundaries()

        self.returnColorLayers = {}
        for color in self.colorLayers:
            if len(self.colorLayers[color]) > 0:
                if self.debug:
                    print(("returning color ", color))
                self.returnColorLayers[color] = self.colorLayers[color]

        # format: {'#ff0000': [[[x,y], [x,y], ...], [], ..], '#0000ff':[]}
        job = {'head': {}, 'passes': [], 'items': [], 'defs': []}
        #job['units'] = self.unitsString
        for color, path in self.returnColorLayers.items():
            job['defs'].append({"kind": "path", "data": path})
            job['items'].append({"def": len(job['defs']) - 1, "color": color})
        print("Done!")
        return job
Esempio n. 3
0
def loads(data, filename=None):
    if sys.version_info.major == 2:
        data = unicode(data)
    stream = io.StringIO(data)
    dxf = dxfgrabber.read(stream)
    return DxfFile.from_dxf(dxf)
Esempio n. 4
0
    def parse(self, dxfInput, forced_unit):
        dxfStream = io.StringIO(unicode(dxfInput.replace('\r\n','\n')))
        dwg = dxfgrabber.read(dxfStream)
        if not dwg:
            raise RuntimeError("dxfgrabber.read() failed")

        # TODO: check DXF version to see if INSUNITS is expected
        # TODO: try and guess mm vs in based on max x/y
        # set up unit conversion
        #
        # 0 unitless
        # 1 inches
        # 2 feet
        # 3 miles
        # 4 mm
        # 5 cm
        # 6 m
        # 7 km
        # 8 microinches
        # 9 mils
        # 10 yards
        # 11 angstroms
        # 12 nanometeres
        # 13 microns
        # 14 decimeters
        # 15 decameters
        # 16 hectometers
        # 17 gigameters
        # 18 au
        # 19 light years
        # 20 parsecs

        
        if forced_unit == 0 or forced_unit == None:
            self.units = dwg.header.setdefault('$INSUNITS', 0)
        else:
            print("using forced_unit", forced_unit)
            self.units = forced_unit
        if self.verbose:
            print("dxf units read %s, default 0 " % self.units)
        if self.units == 0:
            self.unitsString = "unitless"
        elif self.units == 1:
            self.unitsString = "inches"
        elif self.units == 2:
            self.unitsString = "feet"
        elif self.units == 3:
            self.unitsString = "miles"
        elif self.units == 4:
            self.unitsString = "mm"
        elif self.units == 5:
            self.unitsString = "cm"
        elif self.units == 6:
            self.unitsString = "m"
        elif self.units == 7:
            self.unitsString = "km"
        elif self.units == 8:
            self.unitsString = "microinch"
        elif self.units == 9:
            self.unitsString = "mils"
        elif self.units == 10:
            self.unitsString = "yards"
        elif self.units == 11:
            self.unitsString = "angstroms"
        elif self.units == 12:
            self.unitsString = "nanometers"
        elif self.units == 13:
            self.unitsString = "microns"
        elif self.units == 14:
            self.unitsString = "decimeters"
        elif self.units == 15:
            self.unitsString = "decameters"
        elif self.units == 16:
            self.unitsString = "hectometers"
        elif self.units == 17:
            self.unitsString = "gigameters"
        elif self.units == 18:
            self.unitsString = "astronomical units"
        elif self.units == 19:
            self.unitsString = "light years"
        elif self.units == 20:
            self.unitsString = "parsecs"
        else:
            print("DXF units: >%s< unsupported" % self.units)
            raise RuntimeError
            
        if self.verbose:
            print("dxfgrabber release: ", self.dxfgrabber_version)
            print("DXF file format version: {}".format(dwg.dxfversion))
            print("header var count: ", len(dwg.header))
            print("layer count: ", len(dwg.layers)) 
            print("block def count: ", len(dwg.blocks))
            print("entitiy count: ", len(dwg.entities))
            print("units: ", self.unitsString)

        for entity in dwg.entities:
            if entity.color == dxfgrabber.BYLAYER:
                layer = dwg.layers[entity.layer]
                entity.color = layer.color
                if self.debug:
                    print("set entity color to layer color %d" % layer.color)

            if entity.dxftype == "LINE":
                self.addLine(entity)
            elif entity.dxftype == "ARC":
                self.addArc(entity)
            elif entity.dxftype == "CIRCLE":
                self.addCircle(entity)
            elif entity.dxftype == "LWPOLYLINE":
                self.addPolyLine(entity)
            elif entity.dxftype == "SPLINE":
                print("TODO ADD: ", entity.dxftype)
                #self.addSpline(entity)
            else:
                if self.verbose:
                    print("unknown entity: ", entity.dxftype)

        print "Done!"

        if self.verbose:
            print ("pre flipped");
            print ("x min %f" % self.x_min)
            print ("x max %f" % self.x_max)
            print ("y min %f" % self.y_min)
            print ("y max %f" % self.y_max)

        # remember that Y is in negative space relative to our bed,
        # CAD software has 0,0 and bottom left, lasersaur has
        # it at top left.
        if self.x_min < 0 or self.y_max > -self.bedwidth[1]:
            if self.verbose:
                print("doing shiftPositive")
            self.shiftPositive()

        self.validateBoundaries()

        self.returnColorLayers = {}
        for color in self.colorLayers:
            if len(self.colorLayers[color]) > 0:
                if self.debug:
                    print ("returning color ", color)
                self.returnColorLayers[color] = self.colorLayers[color]

        # format: {'#ff0000': [[[x,y], [x,y], ...], [], ..], '#0000ff':[]}
        job = {'head':{}, 'passes':[], 'items':[], 'defs':[]}
        #job['units'] = self.unitsString
        for color, path in self.returnColorLayers.iteritems():
            job['defs'].append({"kind":"path",
                                "data":path})
            job['items'].append({"def":len(job['defs'])-1, "color":color})
        print "Done!"
        return job
Esempio n. 5
0
    def parse(self, dxfInput, forced_unit):
        dxfStream = io.StringIO(unicode(dxfInput.replace('\r\n','\n')))
        dwg = dxfgrabber.read(dxfStream)
        if not dwg:
            print ("DXFGRABBER FAIL")
            raise ValueError

        # TODO: check DXF version to see if INSUNITS is expected
        # TODO: try and guess mm vs in based on max x/y
        # set up unit conversion
        if forced_unit == 0 or forced_unit == None:
            self.units = dwg.header.setdefault('$INSUNITS', 0)
        else:
            print("using forced_unit", forced_unit)
            self.units = forced_unit
        if self.verbose:
            print("dxf units read %s, default 0 " % self.units)
        if self.units == 0:
            self.unitsString = "unitless"
        elif self.units == 1:
            self.unitsString = "inches"
        elif self.units == 4:
            self.unitsString = "mm"
        else:
            print("DXF units: >%s< unsupported" % self.units)
            raise ValueError
            
        if self.verbose:
            print("DXF version: {}".format(dwg.dxfversion))
            print("header var count: ", len(dwg.header))
            print("layer count: ", len(dwg.layers)) 
            print("block def count: ", len(dwg.blocks))
            print("entitiy count: ", len(dwg.entities))
            print("units: ", self.unitsString)

        for entity in dwg.entities:
            if entity.color == dxfgrabber.BYLAYER:
                layer = dwg.layers[entity.layer]
                entity.color = layer.color
                if self.debug:
                    print("set entity color to layer color %d" % layer.color)

            if entity.dxftype == "LINE":
                self.addLine(entity)
            elif entity.dxftype == "ARC":
                self.addArc(entity)
            elif entity.dxftype == "CIRCLE":
                self.addCircle(entity)
            elif entity.dxftype == "LWPOLYLINE":
                self.addPolyLine(entity)
            elif entity.dxftype == "SPLINE":
                print("TODO ADD: ", entity.dxftype)
                #self.addSpline(entity)
            else:
                if self.verbose:
                    print("unknown entity: ", entity.dxftype)

        print "Done!"

        if self.verbose:
            print ("pre flipped");
            print ("x min %f" % self.x_min)
            print ("x max %f" % self.x_max)
            print ("y min %f" % self.y_min)
            print ("y max %f" % self.y_max)

        if self.x_min < 0 or self.y_max > -self.bedwidth[1]:
            if self.verbose:
                print("doing shiftPositive")
            self.shiftPositive()

        self.validateBoundaries()

        self.returnColorLayers = {}
        for color in self.colorLayers:
            if len(self.colorLayers[color]) > 0:
                if self.debug:
                    print ("returning color ", color)
                self.returnColorLayers[color] = self.colorLayers[color]
        #TODO: teach the UI to report units read in the file
        return {'boundaries':self.returnColorLayers, 'units':self.unitsString}
Esempio n. 6
0
def Interpret(dxf, VERBOSE=False, origin=[0,0], colorOrder=None):
    drawing = dxfgrabber.read(dxf)
    
    Container = []
    
    validEnts = ['POINT','LINE', 'LWPOLYLINE','ARC','CIRCLE','ELLIPSE','SPLINE']
    
    #
    #LETS SORT BY ALL OF THE COLORS
    #  
    for entity in drawing.entities:
        if entity.dxftype in validEnts:
            newColor = True
            for cg in Container:
                if entity.color == cg.color:
                    if VERBOSE:
                        print str(entity.color) + ' paths belong in ' + str(cg.color) + ' cutgroups.'
                    cg.entities.append(entity) 
                    newColor = False       
            if newColor:
                cg = cutGroup()
                cg.color = entity.color
                Container.append(cg)
                if VERBOSE:
                    print str(entity.color) + ' paths belong in ' + str(cg.color) + ' cutgroups.'
                cg.entities.append(entity)

    #Finding all the start and end points
    startEnd(Container)
    
    
    #Reordering the container by color
    
    #TEST# colorOrder = [256,6,1,6]
    if colorOrder:
        colorOrder.reverse()
        for color in colorOrder:
            for cg in Container:
                if cg.color == color:
                    Container.insert(0,Container.pop(Container.index(cg)))
    
    #
    #LETS OPTIMIZE THE TOOL PATH
    #Start at start point.
    #On each color, find path of least jogging.
    #        
    print 'origin: ' + str(origin)
    startPoint = origin
    
    output = {}
    output['groups'] = []
    
    for cg in Container:
        startPoint, cg = optimize(startPoint, cg)
        
        cg_out = {}
        cg_out['gcode'] = gcode(cg)
        cg_out['color'] = cg.color
        output['groups'].append(cg_out)
        
    print 'endpoint: ' + str(startPoint)
        
    #LETS ACTUALLY WRITE OUT A PROGRAM
    return output

    
    '''   
Esempio n. 7
0
    def parse(self, dxfInput):
        dxfStripped = dxfInput.replace('\r\n','\n')
        dxfStream = io.StringIO(unicode(dxfStripped.replace('\r\n','\n')))
        
        infile = dxfgrabber.read(dxfStream)
        if not infile:
            print ("DXFGRABBER FAIL")
            raise ValueError

        # set up unit conversion
        self.units = infile.header.setdefault('$INSUNITS', 1)
        if self.units == 0:
            self.unitsString = "undefined, assuming inches"
        elif self.units == 1:
            self.unitsString = "inches"
        elif self.units == 4:
            self.unitsString = "mm"
        else:
            print("DXF units: ", self.units, " unsupported")
            raise ValueError
        
        if self.debug:
            print("DXF version: {}".format(infile.dxfversion))
            print("header var count: ", len(infile.header))
            print("layer count: ", len(infile.layers)) 
            print("block def count: ", len(infile.blocks))
            print("entitiy count: ", len(infile.entities))
            print("units: ", self.unitsString)
        
        #Iterate through and print layers name
        global Layer_names
        Layer_names = infile.layers.names()
        if self.debug:
            print("Layer Names: ", Layer_names)
            i = 1
            n = len(infile.layers)
            while i < n:
                print("iter value:", i)
                print("layer name: ", Layer_names[i])
                i = i + 1
        
        for entity in infile.entities:
            if entity.dxftype == "LINE":
                if self.debug:
                    print("Line Entity")
                    print("Entity Layer:", entity.layer)
                self.addLine(entity)
            elif entity.dxftype == "ARC":
                if self.debug:
                    print("Arc Entity")
                    print("Entity Layer:", entity.layer)
                self.addArc(entity)
            elif entity.dxftype == "CIRCLE":
                if self.debug:
                    print("Circle Entity")
                    print("Entity Layer:", entity.layer)
                self.addCircle(entity)
            elif entity.dxftype == "LWPOLYLINE":
                if self.debug:
                    print("LWPolyLine Entity")
                    print("Entity Layer:", entity.layer)
                self.addPolyLine(entity)
            elif entity.dxftype == "SPLINE":
                if self.debug:
                    print("Spline Entity")
                    print("Entity Layer:", entity.layer)
                print("TODO ADD: ", entity.dxftype)
                #self.addSpline(entity)
            else:
                if self.debug:
                    print("unknown entity: ", entity.dxftype)
                    print("Entity Layer:", entity.layer)

                
        print "Done!"
        
        #TODO: teach the UI to report units read in the file
        #return {'boundarys':self.returnColorLayers, 'units':self.unitsString}
        
        #Original snippets from stefanif dxfreader
        return {'boundarys':self.boundarys}