def perform_union_mesh(self, list_objects_names, name, verbose=False):
        """
        Perform the union of all shapes given in list_objects_names.
        The final shape is called name. Intermediate shapes are called shape_n,
        where n is an indice that indicates how many fusions left to do
        """

        number_of_shapes = len(list_objects_names)  # 2 (3) shapes
        number_of_fusions = number_of_shapes - 1    # is 1 (2) fusions to do

        if verbose:
            print "Number of fusions to do: " + str(number_of_fusions)

        if not number_of_fusions > 0:
            raise("Not enough shapes to do a fusion!")

        # take care of the intermediate fusions
        while number_of_fusions > 1:  # if 2 fusions, the first is the -1
            # intermediate shape name
            intermediate_shape_name = name + "_minus" + str(number_of_fusions - 1)

            if verbose:
                print "Generate intermediate shape: " + intermediate_shape_name
                print "Object 1 for fusion: " + list_objects_names[0]
                print "Object 2 for fusion: " + list_objects_names[1]

            # create intermediate shape
            mesh_1 = self.document.getObject(list_objects_names[0]).Mesh
            mesh_2 = self.document.getObject(list_objects_names[1]).Mesh
            mesh_interm = OpenSCADUtils.meshoptempfile('union', (mesh_1, mesh_2))
            self.document.addObject("Mesh::Feature", intermediate_shape_name)
            self.document.getObject(intermediate_shape_name).Mesh = mesh_interm

            self.document.recompute()

            # add it at the end of the list of shapes to fusion
            list_objects_names.append(intermediate_shape_name)

            # take away the two first elements of the list to fusion
            list_objects_names = list_objects_names[2:]

            # one less fusion to do
            number_of_fusions -= 1

        # take care of the last fusion
        if verbose:
            print "Do last fusion"
            print "Object 1 for fusion: " + list_objects_names[0]
            print "Object 2 for fusion: " + list_objects_names[1]

        # create intermediate shape
        mesh_1 = self.document.getObject(list_objects_names[0]).Mesh
        mesh_2 = self.document.getObject(list_objects_names[1]).Mesh
        mesh_interm = OpenSCADUtils.meshoptempfile('union', (mesh_1, mesh_2))
        self.document.addObject("Mesh::Feature", name)
        self.document.getObject(name).Mesh = mesh_interm

        self.document.recompute()
def fuse(meshes):
    meshes1 = []
    meshes2 = []
    for mesh in meshes:
        o = orientation(mesh)
        if o == "Forward":
            meshes1.append(mesh)
        elif o == "Reversed":
            meshes2.append(complement(mesh))
        else:
            raise TypeError

    # # broken
    # mesh1 = None
    # if len(meshes1) > 0:
    #     mesh1 = reduce(Mesh.Mesh.unite, meshes1)
    # mesh2 = None
    # if len(meshes2) > 0:
    #     mesh2 = reduce(Mesh.Mesh.intersect, meshes2)

    # if mesh1 is None and mesh2 is None:
    #     return None
    # elif mesh1 is None:
    #     return complement(mesh2)
    # elif mesh2 is None:
    #     return mesh1
    # else:
    #     return complement(mesh2.difference(mesh1))

    mesh1 = None
    if len(meshes1) > 1:
        mesh1 = OpenSCADUtils.meshoptempfile('union', meshes1)
    elif len(meshes1) == 1:
        mesh1 = meshes1[0]
    mesh2 = None
    if len(meshes2) > 1:
        mesh2 = OpenSCADUtils.meshoptempfile('intersection', meshes2)
    elif len(meshes2) == 1:
        mesh2 = meshes2[0]

    if mesh1 is None and mesh2 is None:
        return None
    elif mesh1 is None:
        return complement(mesh2)
    elif mesh2 is None:
        return mesh1
    else:
        return complement(OpenSCADUtils.meshoptempfile('difference', [mesh2, mesh1]))
Beispiel #3
0
 def Activated(self):
     selection = FreeCADGui.Selection.getSelectionEx()
     for selobj in selection:
         newobj = selobj.Document.addObject("Mesh::Feature", 'resize')
         newobj.Label = 'resize_%s' % selobj.Object.Label
         msh = selobj.Object.Mesh
         items = ["[1;1;1]"]
         item, ok = QtGui.QInputDialog.getItem(
             QtGui.QApplication.activeWindow(),
             'Resize about which Axis?',
             'Enter resizing value:',
             items,
             editable=True)
         if ok:
             splits = list(
                 item.replace('[', '').replace(']', '').split(';'))
             x = float(splits[0])
             y = float(splits[1])
             z = float(splits[2])
             vec = FreeCAD.Base.Vector(x, y, z)
             newmesh = OpenSCADUtils.resizemesh(msh, vec)
             newobj.Mesh = newmesh
             selobj.Object.ViewObject.hide()
         else:
             selobj.Document.removeObject(newobj.Name)
     FreeCAD.ActiveDocument.recompute()
Beispiel #4
0
    def Activated(self):
        import Part, OpenSCADFeatures, OpenSCADUtils
        selection = FreeCADGui.Selection.getSelectionEx()
        for selobj in selection:
            newobj = selobj.Document.addObject("Mesh::Feature", 'mirror')
            newobj.Label = 'mirror_%s' % selobj.Object.Label
            msh = selobj.Object.Mesh
            items = [
                "[1,0,0]", "[0,1,0]", "[0,0,1]", "[1,1,0]", "[0,1,1]",
                "[1,0,1]", "[1,1,1]"
            ]
            item, ok = QtGui.QInputDialog.getItem(
                QtGui.QApplication.activeWindow(),
                u'Mirror about which Axis?',
                u'Select Axis (or enter custom value)?',
                items,
                editable=True)
            if ok:
                splits = list(item)
                x = float(splits[1])
                y = float(splits[3])
                z = float(splits[5])
                vec = FreeCAD.Base.Vector(x, y, z)
                newmesh = OpenSCADUtils.mirrormesh(msh, vec)
                newobj.Mesh = newmesh
                selobj.Object.ViewObject.hide()
            else:
                selobj.Document.removeObject(newobj.Name)

        FreeCAD.ActiveDocument.recompute()
Beispiel #5
0
    def Initialize(self):
        def QT_TRANSLATE_NOOP(scope, text):
            return text

        import OpenSCAD_rc, OpenSCADCommands
        commands = [
            'OpenSCAD_ReplaceObject', 'OpenSCAD_RemoveSubtree',
            'OpenSCAD_RefineShapeFeature', 'OpenSCAD_MirrorMeshFeature',
            'OpenSCAD_ScaleMeshFeature', 'OpenSCAD_ResizeMeshFeature',
            'OpenSCAD_IncreaseToleranceFeature', 'OpenSCAD_Edgestofaces',
            'OpenSCAD_ExpandPlacements', 'OpenSCAD_ExplodeGroup'
        ]
        toolbarcommands = [
            'OpenSCAD_ReplaceObject', 'OpenSCAD_RemoveSubtree',
            'OpenSCAD_ExplodeGroup', 'OpenSCAD_RefineShapeFeature',
            'OpenSCAD_IncreaseToleranceFeature'
        ]
        import PartGui
        parttoolbarcommands = [
            'Part_CheckGeometry', 'Part_Primitives', 'Part_Builder',
            'Part_Cut', 'Part_Fuse', 'Part_Common', 'Part_Extrude',
            'Part_Revolve'
        ]
        import FreeCAD
        param = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/OpenSCAD")
        openscadfilename = param.GetString('openscadexecutable')
        if not openscadfilename:

            import OpenSCADUtils
            openscadfilename = OpenSCADUtils.searchforopenscadexe()
            if openscadfilename:  #automatic search was succsessful
                FreeCAD.addImportType("OpenSCAD Format (*.scad)", "importCSG")
                param.SetString('openscadexecutable',
                                openscadfilename)  #save the result
        if openscadfilename:
            commands.extend([
                'OpenSCAD_AddOpenSCADElement', 'OpenSCAD_MeshBoolean',
                'OpenSCAD_Hull', 'OpenSCAD_Minkowski'
            ])

            toolbarcommands.extend([
                'OpenSCAD_AddOpenSCADElement', 'OpenSCAD_MeshBoolean',
                'OpenSCAD_Hull', 'OpenSCAD_Minkowski'
            ])
        else:
            FreeCAD.Console.PrintWarning('OpenSCAD executable not found\n')

        self.appendToolbar(QT_TRANSLATE_NOOP('Workbench', 'OpenSCADTools'),
                           toolbarcommands)
        self.appendMenu('OpenSCAD', commands)
        self.appendToolbar(
            QT_TRANSLATE_NOOP('Workbech', 'OpenSCAD Part tools'),
            parttoolbarcommands)
        #self.appendMenu('OpenSCAD',["AddOpenSCADElement"])
        ###self.appendCommandbar("&Generic Tools",["ColorCodeShape"])
        FreeCADGui.addIconPath(":/icons")
        FreeCADGui.addLanguagePath(":/translations")
        FreeCADGui.addPreferencePage(":/ui/openscadprefs-base.ui", "OpenSCAD")
Beispiel #6
0
    def applyOperationToMesh(self, mesh):
        if not self.Object.Enabled:
            return mesh

        import OpenSCADUtils

        openscadOperation = MODE_MAPPING[self.Object.Mode]

        return OpenSCADUtils.meshoptempfile(openscadOperation, (mesh, self.getMesh()))
 def execute(self,fp):
     #arguments are ignored
     maxmeshpoints = None #TBD: add as property
     import Part,OpenSCADUtils
     shape = OpenSCADUtils.process_ObjectsViaOpenSCADShape(fp.Document,fp.Children,\
             fp.Operation, maxmeshpoints=maxmeshpoints)
     if shape:
         fp.Shape = shape
     else:
         raise ValueError
Beispiel #8
0
 def execute(self, fp):
     #arguments are ignored
     maxmeshpoints = None  #TBD: add as property
     import Part, OpenSCADUtils
     shape = OpenSCADUtils.process_ObjectsViaOpenSCADShape(fp.Document,fp.Children,\
             fp.Operation, maxmeshpoints=maxmeshpoints)
     if shape:
         fp.Shape = shape
     else:
         raise ValueError
def checkOpenscadInstalled():
    found = True

    try:
        import OpenSCADUtils

        found = OpenSCADUtils.getopenscadversion() is not None
    except:
        found = False
    
    if not found:
        qtutils.showInfo('OpenSCAD import failed', 'The import of OpenSCADUtils failed. Make sure you have OpenSCAD installed and configured in the preferences.')
    
    return found
    def perform_cut_mesh(self, base, tool, name, verbose=False):
        """
        Perform the cut (substraction) of tool on base as the name object
        """

        if verbose:
            print "Doing a cut on " + base + " using " + tool

        mesh_1 = self.document.getObject(base).Mesh
        mesh_2 = self.document.getObject(tool).Mesh
        mesh_interm = OpenSCADUtils.meshoptempfile('difference', (mesh_1, mesh_2))
        self.document.addObject("Mesh::Feature", name)
        self.document.getObject(name).Mesh = mesh_interm

        self.document.recompute()
 def addelement(self):
     scadstr = unicode(self.form.textEdit.toPlainText())
     asmesh = self.form.checkboxmesh.checkState()
     import OpenSCADUtils, os
     extension = 'stl' if asmesh else 'csg'
     tmpfilename = OpenSCADUtils.callopenscadstring(scadstr, extension)
     if tmpfilename:
         doc = FreeCAD.activeDocument() or FreeCAD.newDocument()
         if asmesh:
             import Mesh
             Mesh.insert(tmpfilename, doc.Name)
         else:
             import importCSG
             importCSG.insert(tmpfilename, doc.Name)
         os.unlink(tmpfilename)
     else:
         FreeCAD.Console.PrintError('Running OpenSCAD failed\n')
 def addelement(self):
     scadstr=unicode(self.form.textEdit.toPlainText())
     asmesh=self.form.checkboxmesh.checkState()
     import OpenSCADUtils, os
     extension= 'stl' if asmesh else 'csg'
     tmpfilename=OpenSCADUtils.callopenscadstring(scadstr,extension)
     if tmpfilename:
         doc=FreeCAD.activeDocument() or FreeCAD.newDocument()
         if asmesh:
             import Mesh
             Mesh.insert(tmpfilename,doc.Name)
         else:
             import importCSG
             importCSG.insert(tmpfilename,doc.Name)
         os.unlink(tmpfilename)
     else:
         FreeCAD.Console.PrintError(unicode(translate('OpenSCAD','Running OpenSCAD failed'))+u'\n')
Beispiel #13
0
    def Initialize(self):
        def QT_TRANSLATE_NOOP(scope, text):
            return text
        import OpenSCAD_rc,OpenSCADCommands
        commands=['OpenSCAD_ReplaceObject','OpenSCAD_RemoveSubtree',\
            'OpenSCAD_RefineShapeFeature',\
            'OpenSCAD_IncreaseToleranceFeature', 'OpenSCAD_Edgestofaces', \
            'OpenSCAD_ExpandPlacements','OpenSCAD_ExplodeGroup']
        toolbarcommands=['OpenSCAD_ReplaceObject','OpenSCAD_RemoveSubtree',\
            'OpenSCAD_ExplodeGroup','OpenSCAD_RefineShapeFeature']
            #'OpenSCAD_IncreaseToleranceFeature' #icon still missing
        import PartGui
        parttoolbarcommands = ['Part_CheckGeometry',"Part_Primitives",\
            "Part_Builder",'Part_Cut','Part_Fuse','Part_Common',\
            'Part_Extrude',"Part_Revolve"]
        import FreeCAD
        param = FreeCAD.ParamGet(\
            "User parameter:BaseApp/Preferences/Mod/OpenSCAD")
        openscadfilename = param.GetString('openscadexecutable')
        if not openscadfilename:

            import OpenSCADUtils
            openscadfilename = OpenSCADUtils.searchforopenscadexe()
            if openscadfilename: #automatic search was succsessful
                FreeCAD.addImportType("OpenSCAD Format (*.scad)","importCSG") 
                param.SetString('openscadexecutable',openscadfilename) #save the result
        if openscadfilename:
            commands.extend(['OpenSCAD_AddOpenSCADElement',
                'OpenSCAD_MeshBoolean','OpenSCAD_Hull','OpenSCAD_Minkowski'])
            toolbarcommands.extend(['OpenSCAD_AddOpenSCADElement',
                'OpenSCAD_MeshBoolean','OpenSCAD_Hull','OpenSCAD_Minkowski'])
        else:
            FreeCAD.Console.PrintWarning('OpenSCAD executable not found\n')

        self.appendToolbar(QT_TRANSLATE_NOOP('Workbench','OpenSCADTools'),toolbarcommands)
        self.appendMenu('OpenSCAD',commands)
        self.appendToolbar(QT_TRANSLATE_NOOP('Workbech','OpenSCAD Part tools'),parttoolbarcommands)
        #self.appendMenu('OpenSCAD',["AddOpenSCADElement"])
        ###self.appendCommandbar("&Generic Tools",["ColorCodeShape"])
        FreeCADGui.addIconPath(":/icons")
        FreeCADGui.addLanguagePath(":/translations")
        FreeCADGui.addPreferencePage(":/ui/openscadprefs-base.ui","OpenSCAD")
Beispiel #14
0
def readfile(filename):
    import os
    global lastimportpath
    lastimportpath,relname = os.path.split(filename)
    isopenscad = relname.lower().endswith('.scad')
    if isopenscad:
        tmpfile=callopenscad(filename)
        if OpenSCADUtils.workaroundforissue128needed():
            lastimportpath = os.getcwd() #https://github.com/openscad/openscad/issues/128
        f = pythonopen(tmpfile)
    else:
        f = pythonopen(filename)
    rootnode=parsenode(f.read())[0]
    f.close()
    if isopenscad and tmpfile:
        try:
            os.unlink(tmpfile)
        except OSError:
            pass
    return rootnode.flattengroups()
    def addelement(self):
        scadstr=unicode(self.form.textEdit.toPlainText()).encode('utf8')
        asmesh=self.form.checkboxmesh.checkState()
        import OpenSCADUtils, os
        extension= 'stl' if asmesh else 'csg'
        try:
            tmpfilename=OpenSCADUtils.callopenscadstring(scadstr,extension)
            doc=FreeCAD.activeDocument() or FreeCAD.newDocument()
            if asmesh:
                import Mesh
                Mesh.insert(tmpfilename,doc.Name)
            else:
                import importCSG
                importCSG.insert(tmpfilename,doc.Name)
            try:
                os.unlink(tmpfilename)
            except OSError:
                pass

        except OpenSCADUtils.OpenSCADError, e:
            FreeCAD.Console.PrintError(e.value)
Beispiel #16
0
    def addelement(self):
        scadstr = self.form.textEdit.toPlainText()
        asmesh = self.form.checkboxmesh.checkState()
        import OpenSCADUtils, os
        extension = 'stl' if asmesh else 'csg'
        try:
            tmpfilename = OpenSCADUtils.callopenscadstring(scadstr, extension)
            doc = FreeCAD.activeDocument() or FreeCAD.newDocument()
            if asmesh:
                import Mesh
                Mesh.insert(tmpfilename, doc.Name)
            else:
                import importCSG
                importCSG.insert(tmpfilename, doc.Name)
            try:
                os.unlink(tmpfilename)
            except OSError:
                pass

        except OpenSCADUtils.OpenSCADError as e:
            FreeCAD.Console.PrintError(e.value)
Beispiel #17
0
def openscadmesh(doc, scadstr, objname):
    import Part, Mesh, os, OpenSCADUtils
    tmpfilename = OpenSCADUtils.callopenscadstring(scadstr, 'stl')
    if tmpfilename:
        #mesh1 = doc.getObject(objname) #reuse imported object
        Mesh.insert(tmpfilename)
        os.unlink(tmpfilename)
        mesh1 = doc.getObject(objname)  #blog
        mesh1.ViewObject.hide()
        sh = Part.Shape()
        sh.makeShapeFromMesh(mesh1.Mesh.Topology, 0.1)
        solid = Part.Solid(sh)
        obj = doc.addObject("Part::FeaturePython", objname)
        ImportObject(obj, mesh1)  #This object is not mutable from the GUI
        ViewProviderTree(obj.ViewObject)
        solid = solid.removeSplitter()
        if solid.Volume < 0:
            solid.complement()
        obj.Shape = solid  #.removeSplitter()
        return obj
    else:
        print scadstr
def openscadmesh(doc,scadstr,objname):
    import Part,Mesh,os,OpenSCADUtils
    tmpfilename=OpenSCADUtils.callopenscadstring(scadstr,'stl')
    if tmpfilename:
        #mesh1 = doc.getObject(objname) #reuse imported object
        Mesh.insert(tmpfilename)
        os.unlink(tmpfilename)
        mesh1=doc.getObject(objname) #blog
        mesh1.ViewObject.hide()
        sh=Part.Shape()
        sh.makeShapeFromMesh(mesh1.Mesh.Topology,0.1)
        solid = Part.Solid(sh)
        obj=doc.addObject("Part::FeaturePython",objname)
        ImportObject(obj,mesh1) #This object is not mutable from the GUI
        ViewProviderTree(obj.ViewObject)
        solid=solid.removeSplitter()
        if solid.Volume < 0:
            solid.complement()
        obj.Shape=solid#.removeSplitter()
        return obj
    else:
        print scadstr
Beispiel #19
0
def expandplacements(obj,placement):
    ownplacement=placement.multiply(obj.Placement)
    if obj.isDerivedFrom('Part::FeaturePython') and isinstance(obj.Proxy,MatrixTransform):
        #expandplacementsmatrix(obj,ownplacement.toMatrix())
        expandplacementsmatrix(obj,placement.toMatrix())
    elif likeprimitive(obj,False):
        obj.Placement=ownplacement
    elif obj.isDerivedFrom('Part::Mirroring'):
        import OpenSCADUtils
        mm  = OpenSCADUtils.mirror2mat(obj.Normal,obj.Base)
        #TODO: set the base to 0,0,0
        innerp=FreeCAD.Placement(mm * ownplacement.toMatrix() *mm)
        expandplacements(obj.Source,innerp)
        obj.Placement=FreeCAD.Placement()
    else:
        for outobj in obj.OutList:
            if obj.isDerivedFrom('Part::Extrusion'):
                obj.Dir=ownplacement.Rotation.multVec(obj.Dir)
            elif obj.isDerivedFrom('Part::Revolution'):
                obj.Axis=ownplacement.Rotation.multVec(obj.Axis)
                #obj.Base=ownplacement.Rotation.multVec(obj.Base)
            expandplacements(outobj,ownplacement)
        obj.Placement=FreeCAD.Placement()
def expandplacements(obj,placement):
    ownplacement=placement.multiply(obj.Placement)
    if obj.isDerivedFrom('Part::FeaturePython') and isinstance(obj.Proxy,MatrixTransform):
        #expandplacementsmatrix(obj,ownplacement.toMatrix())
        expandplacementsmatrix(obj,placement.toMatrix())
    elif likeprimitive(obj,False):
        obj.Placement=ownplacement
    elif obj.isDerivedFrom('Part::Mirroring'):
        import OpenSCADUtils
        mm  = OpenSCADUtils.mirror2mat(obj.Normal,obj.Base)
        #todo: set the base to 0,0,0
        innerp=FreeCAD.Placement(mm * ownplacement.toMatrix() *mm)
        expandplacements(obj.Source,innerp)
        obj.Placement=FreeCAD.Placement()
    else:
        for outobj in obj.OutList:
            if obj.isDerivedFrom('Part::Extrusion'):
                obj.Dir=ownplacement.Rotation.multVec(obj.Dir)
            elif obj.isDerivedFrom('Part::Revolution'):
                obj.Axis=ownplacement.Rotation.multVec(obj.Axis)
                #obj.Base=ownplacement.Rotation.multVec(obj.Base)
            expandplacements(outobj,ownplacement)
        obj.Placement=FreeCAD.Placement()
Beispiel #21
0
    def Initialize(self):
        import OpenSCAD_rc, OpenSCADCommands
        commands=['OpenSCAD_ReplaceObject','OpenSCAD_RemoveSubtree',\
            'OpenSCAD_RefineShapeFeature',"OpenSCAD_Edgestofaces",\
            'OpenSCAD_ExpandPlacements']
        toolbarcommands=['OpenSCAD_ReplaceObject','OpenSCAD_RemoveSubtree',\
            'OpenSCAD_RefineShapeFeature']
        import PartGui
        parttoolbarcommands = ['Part_CheckGeometry',"Part_Primitives",\
            "Part_Builder",'Part_Cut','Part_Fuse','Part_Common',\
            'Part_Extrude',"Part_Revolve"]
        import FreeCAD
        param = FreeCAD.ParamGet(\
            "User parameter:BaseApp/Preferences/Mod/OpenSCAD")
        openscadfilename = param.GetString('openscadexecutable')
        if not openscadfilename:

            import OpenSCADUtils
            openscadfilename = OpenSCADUtils.searchforopenscadexe()
            if openscadfilename:  #automatic search was succsessful
                FreeCAD.addImportType("OpenSCAD Format (*.scad)", "importCSG")
                param.SetString('openscadexecutable',
                                openscadfilename)  #save the result
        if openscadfilename:
            commands.extend(['OpenSCAD_AddOpenSCADElement'])
            toolbarcommands.extend(['OpenSCAD_AddOpenSCADElement'])
        else:
            FreeCAD.Console.PrintWarning('OpenSCAD executable not found\n')

        self.appendToolbar("OpenSCADTools", toolbarcommands)
        self.appendMenu('OpenSCAD', commands)
        self.appendToolbar('OpenSCAD Part tools', parttoolbarcommands)
        #self.appendMenu('OpenSCAD',["AddOpenSCADElement"])
        ###self.appendCommandbar("&Generic Tools",["ColorCodeShape"])
        FreeCADGui.addIconPath(":/icons")
        FreeCADGui.addLanguagePath(":/translations")
        FreeCADGui.addPreferencePage(":/ui/openscadprefs-base.ui", "OpenSCAD")
Beispiel #22
0
    def Initialize(self):
        def QT_TRANSLATE_NOOP(scope, text):
            return text

        import OpenSCAD_rc, OpenSCADCommands

        commands = [
            "OpenSCAD_ReplaceObject",
            "OpenSCAD_RemoveSubtree",
            "OpenSCAD_RefineShapeFeature",
            "OpenSCAD_MirrorMeshFeature",
            "OpenSCAD_ScaleMeshFeature",
            "OpenSCAD_ResizeMeshFeature",
            "OpenSCAD_IncreaseToleranceFeature",
            "OpenSCAD_Edgestofaces",
            "OpenSCAD_ExpandPlacements",
            "OpenSCAD_ExplodeGroup",
        ]
        toolbarcommands = [
            "OpenSCAD_ReplaceObject",
            "OpenSCAD_RemoveSubtree",
            "OpenSCAD_ExplodeGroup",
            "OpenSCAD_RefineShapeFeature",
            "OpenSCAD_IncreaseToleranceFeature",
        ]
        import PartGui

        parttoolbarcommands = [
            "Part_CheckGeometry",
            "Part_Primitives",
            "Part_Builder",
            "Part_Cut",
            "Part_Fuse",
            "Part_Common",
            "Part_Extrude",
            "Part_Revolve",
        ]
        import FreeCAD
        translate = FreeCAD.Qt.translate

        param = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/OpenSCAD")
        openscadfilename = param.GetString("openscadexecutable")
        if not openscadfilename:
            import OpenSCADUtils

            openscadfilename = OpenSCADUtils.searchforopenscadexe()
            if openscadfilename:  # automatic search was succsessful
                FreeCAD.addImportType("OpenSCAD Format (*.scad)", "importCSG")
                param.SetString("openscadexecutable",
                                openscadfilename)  # save the result
        if openscadfilename:
            commands.extend([
                "OpenSCAD_AddOpenSCADElement",
                "OpenSCAD_MeshBoolean",
                "OpenSCAD_Hull",
                "OpenSCAD_Minkowski",
            ])

            toolbarcommands.extend([
                "OpenSCAD_AddOpenSCADElement",
                "OpenSCAD_MeshBoolean",
                "OpenSCAD_Hull",
                "OpenSCAD_Minkowski",
            ])
        else:
            FreeCAD.Console.PrintWarning("OpenSCAD executable not found\n")

        transferMechanism = param.GetInt("transfermechanism", 0)
        if openscadfilename and transferMechanism == 0:
            # We are using the Python temp-directory creation function
            if "snap" in openscadfilename:
                FreeCAD.Console.PrintMessage(
                    translate(
                        "OpenSCAD",
                        "It looks like you may be using a Snap version of OpenSCAD.",
                    ) + " " + translate(
                        "OpenSCAD",
                        "If OpenSCAD execution fails to load the temporary file, use FreeCAD's OpenSCAD Workbench Preferences to change the transfer mechanism.",
                    ) + "\n")
            elif sys.executable.startswith("/tmp/"):  # Heuristic for AppImages
                FreeCAD.Console.PrintMessage(
                    translate(
                        "OpenSCAD",
                        "It looks like you may be using a sandboxed version of FreeCAD.",
                    ) + " " + translate(
                        "OpenSCAD",
                        "If OpenSCAD execution fails to load the temporary file, use FreeCAD's OpenSCAD Workbench Preferences to change the transfer mechanism.",
                    ) + "\n")

        self.appendToolbar(QT_TRANSLATE_NOOP("Workbench", "OpenSCADTools"),
                           toolbarcommands)
        self.appendMenu("OpenSCAD", commands)
        self.appendToolbar(
            QT_TRANSLATE_NOOP("Workbech", "OpenSCAD Part tools"),
            parttoolbarcommands)
        # self.appendMenu('OpenSCAD',["AddOpenSCADElement"])
        ###self.appendCommandbar("&Generic Tools",["ColorCodeShape"])
        FreeCADGui.addIconPath(":/icons")
        FreeCADGui.addLanguagePath(":/translations")
        FreeCADGui.addPreferencePage(":/ui/openscadprefs-base.ui", "OpenSCAD")
    def Activated(self):
        import OpenSCADUtils, FreeCADGui

        OpenSCADUtils.removesubtree(FreeCADGui.Selection.getSelection())
Beispiel #24
0
    def execute(self, fp):
        global defeat_icon, use_cm
        doc = App.ActiveDocument
        docG = Gui.ActiveDocument
        if len(fp.Faces) > 0:
            if fp.Base and fp.Base.Shape.isValid():
                d_faces = []
                if fp.useFaceNbr:  #not use_cm:
                    cm_list = []
                    for fn in fp.Faces:
                        oname = fp.Base.Name  #fp.Faces[0].split('.')[0]
                        fnbr = int(fn.split('.')[1].strip('Face')) - 1
                        o = doc.getObject(oname)
                        for i, f in enumerate(o.Shape.Faces):
                            if i == fnbr:
                                d_faces.append(f)
                                c = 'x=' + "{0:.3f}".format(
                                    f.CenterOfMass.x
                                ) + ' y=' + "{0:.3f}".format(
                                    f.CenterOfMass.y
                                ) + ' z=' + "{0:.3f}".format(f.CenterOfMass.z)
                                cm_list.append(c)

                        fp.CM = cm_list
                else:
                    oname = fp.Base.Name  #fp.Faces[0].split('.')[0]
                    o = doc.getObject(oname)
                    fc = []
                    for i, c in enumerate(fp.CM):
                        for j, f in enumerate(fp.Base.Shape.Faces):
                            if c == ('x=' +
                                     "{0:.3f}".format(f.CenterOfMass.x) +
                                     ' y=' +
                                     "{0:.3f}".format(f.CenterOfMass.y) +
                                     ' z=' +
                                     "{0:.3f}".format(f.CenterOfMass.z)):
                                d_faces.append(f)
                                fc.append(
                                    str(o.Name) + '.' + 'Face' + str(j + 1))
                check_faces = True
                if not fp.useFaceNbr:  #use_cm:
                    if len(d_faces) != len(fp.CM):
                        check_faces = False
                elif len(d_faces) == 0:
                    check_faces = False
                if check_faces:
                    sh = fp.Base.Shape.defeaturing(d_faces)
                    if fp.Base.Shape.isPartner(sh):
                        App.Console.PrintError('Defeaturing failed 1\n')
                        defeat_icon = os.path.join(
                            Design456Init.DefeaturingWB_icons_path,
                            'error.svg')
                        docG.getObject(fp.Name).ShapeColor = (1.00, 0.00, 0.00)
                        raise NameError('Defeaturing FAILED!')
                    else:
                        fp.Shape = OpenSCADUtils.applyPlacement(sh)
                        if fp.Label.find('_ERR') != -1:
                            fp.Label = fp.Label[:fp.Label.rfind('_ERR')]
                        defeat_icon = os.path.join(
                            Design456Init.DefeaturingWB_icons_path,
                            'DefeaturingParametric.svg')
                        docG.getObject(fp.Name).ShapeColor = docG.getObject(
                            fp.Base.Name).ShapeColor
                        docG.getObject(fp.Name).LineColor = docG.getObject(
                            fp.Base.Name).LineColor
                        docG.getObject(fp.Name).PointColor = docG.getObject(
                            fp.Base.Name).PointColor
                        docG.getObject(fp.Name).DiffuseColor = docG.getObject(
                            fp.Base.Name).DiffuseColor
                        docG.getObject(fp.Name).Transparency = docG.getObject(
                            fp.Base.Name).Transparency
                else:
                    defeat_icon = os.path.join(
                        Design456Init.DefeaturingWB_icons_path, 'error.svg')

                    App.Console.PrintError('Defeaturing failed 2\n')
                    sh = fp.Base.Shape
                    fp.Shape = OpenSCADUtils.applyPlacement(sh)
                    if fp.Label.find('_ERR') == -1:
                        fp.Label = '%s_ERR' % fp.Label
                    docG.getObject(fp.Name).ShapeColor = (1.00, 0.00, 0.00)
                    raise Exception('Defeaturing FAILED!')

        else:
            print('first executing')
Beispiel #25
0
 def execute(self, fp):
     if fp.Base and fp.Base.Shape.isValid():
         import OpenSCADUtils
         sh = fp.Base.Shape.removeSplitter()
         fp.Shape = OpenSCADUtils.applyPlacement(sh)
 def execute(self, fp):
     global defeat_icon, use_cm
     import OpenSCADUtils, FreeCAD, FreeCADGui, Part, os
     doc = FreeCAD.ActiveDocument
     docG = FreeCADGui.ActiveDocument
     #print(fp.Base.Shape.Faces)
     #if 0: #
     if len(fp.Faces) > 0:
         if fp.Base and fp.Base.Shape.isValid():
             #print (fp.Faces)
             # rh_faces_names -> (selFace.ObjectName+'.'+selFace.SubElementNames[i])
             d_faces = []
             if fp.useFaceNbr:  #not use_cm:
                 cm_list = []
                 for fn in fp.Faces:
                     oname = fp.Base.Name  #fp.Faces[0].split('.')[0]
                     fnbr = int(fn.split('.')[1].strip('Face')) - 1
                     o = doc.getObject(oname)
                     for i, f in enumerate(o.Shape.Faces):
                         if i == fnbr:
                             #print (i)
                             d_faces.append(f)
                             c = 'x=' + "{0:.3f}".format(
                                 f.CenterOfMass.x
                             ) + ' y=' + "{0:.3f}".format(
                                 f.CenterOfMass.y
                             ) + ' z=' + "{0:.3f}".format(f.CenterOfMass.z)
                             cm_list.append(c)
                             #print (c)
                             #print(fp.CM)
                             #print (f.CenterOfMass)
                             #print (f.hashCode())
                     fp.CM = cm_list
             else:
                 oname = fp.Base.Name  #fp.Faces[0].split('.')[0]
                 o = doc.getObject(oname)
                 fc = []
                 #fc.append(fp.Faces[0])
                 for i, c in enumerate(fp.CM):
                     for j, f in enumerate(fp.Base.Shape.Faces):
                         if c == ('x=' +
                                  "{0:.3f}".format(f.CenterOfMass.x) +
                                  ' y=' +
                                  "{0:.3f}".format(f.CenterOfMass.y) +
                                  ' z=' +
                                  "{0:.3f}".format(f.CenterOfMass.z)):
                             d_faces.append(f)
                             #print (f.CenterOfMass)
                             fc.append(
                                 str(o.Name) + '.' + 'Face' + str(j + 1))
             #fp.Faces = fc
             check_faces = True
             if not fp.useFaceNbr:  #use_cm:
                 if len(d_faces) != len(fp.CM):
                     check_faces = False
             elif len(d_faces) == 0:
                 check_faces = False
             if check_faces:
                 sh = fp.Base.Shape.defeaturing(d_faces)
                 if fp.Base.Shape.isPartner(sh):
                     #fp.touch()
                     FreeCAD.Console.PrintError('Defeaturing failed 1\n')
                     defeat_icon = os.path.join(DefeaturingWB_icons_path,
                                                'error.svg')
                     docG.getObject(fp.Name).ShapeColor = (1.00, 0.00, 0.00)
                     raise NameError('Defeaturing FAILED!')
                     #try:
                     #    raise NameError('Defeaturing FAILED!')
                     #except NameError:
                     #    print ('Defeaturing FAILED!')
                     #    raise
                     #raise Exception('Defeaturing FAILED!')
                 else:
                     fp.Shape = OpenSCADUtils.applyPlacement(sh)
                     if fp.Label.find('_ERR') != -1:
                         fp.Label = fp.Label[:fp.Label.rfind('_ERR')]
                     defeat_icon = os.path.join(
                         DefeaturingWB_icons_path,
                         'DefeaturingParametric.svg')
                     docG.getObject(fp.Name).ShapeColor = docG.getObject(
                         fp.Base.Name).ShapeColor
                     docG.getObject(fp.Name).LineColor = docG.getObject(
                         fp.Base.Name).LineColor
                     docG.getObject(fp.Name).PointColor = docG.getObject(
                         fp.Base.Name).PointColor
                     docG.getObject(fp.Name).DiffuseColor = docG.getObject(
                         fp.Base.Name).DiffuseColor
                     docG.getObject(fp.Name).Transparency = docG.getObject(
                         fp.Base.Name).Transparency
             else:
                 defeat_icon = os.path.join(DefeaturingWB_icons_path,
                                            'error.svg')
                 #fp.touch()
                 FreeCAD.Console.PrintError('Defeaturing failed 2\n')
                 sh = fp.Base.Shape
                 fp.Shape = OpenSCADUtils.applyPlacement(sh)
                 if fp.Label.find('_ERR') == -1:
                     fp.Label = '%s_ERR' % fp.Label
                 docG.getObject(fp.Name).ShapeColor = (1.00, 0.00, 0.00)
                 raise Exception('Defeaturing FAILED!')
             #doc.recompute()
     else:
         print('first executing')
Beispiel #27
0
 def Activated(self):
     import OpenSCADUtils,FreeCADGui
     OpenSCADUtils.removesubtree(FreeCADGui.Selection.getSelection())
Beispiel #28
0
def createHull(group):
    hShape = None
    obj0 = group[0]
    if len(group) == 2:
        obj1 = group[1]
        checkObjShape(obj0)
        checkObjShape(obj1)
        print('Check 2D')
        if chk2D(obj0) and chk2D(obj1):
            if obj0.Radius == obj1.Radius:
                return hullTwoEqCircles(obj0, obj1)
            else:
                return hullTwoCircles(obj0, obj1)

        if obj0.TypeId == 'Part::Sphere' and obj1.TypeId == 'Part::Sphere':
            return hullTwoSpheres(obj0, obj1)

    if chkParallel(group):
        print('Parallel')
        if chkCollinear(group):
            print('Collinear')
            if chkCircular(group):
                print('Circular')
                pointLst = []
                for obj in group:
                    h, r1, r2 = getCircularDetails(obj)
                    #print('h  : '+str(h))
                    ax1 = obj.Placement.Rotation.multVec(
                        FreeCAD.Vector(0, 0, 1))
                    #print('ax1 : '+str(ax1))
                    ax = obj.Placement.Base.dot(ax1)
                    #print('ax  : '+str(ax))
                    bx = ax + h
                    pointLst.append(FreeCAD.Vector(0, 0, ax))
                    pointLst.append(FreeCAD.Vector(0, r1, ax))
                    pointLst.append(FreeCAD.Vector(0, r2, bx))
                    pointLst.append(FreeCAD.Vector(0, 0, bx))
                print(pointLst)
                revHull = createRevolveHull(pointLst)
                # rotate from z-axis to collinear axis
                revHull.Placement.Rotation = obj0.Placement.Rotation
                print(obj0.Placement.Rotation)
                print(revHull.Placement.Rotation)
                return revHull

        if len(group) == 2:
            obj0 = group[0]
            obj1 = group[1]
            if chkOrthoganal(obj0, obj1):
                print('Orthoganal')
                if obj0.TypeId == 'Part::Cylinder' and \
                   obj1.TypeId == 'Part::Cylinder' :
                    if obj0.Height == obj1.Height:
                        print('Hull two Cyls')
                        face = hullTwoCircles(obj0, obj1)
                        return face.extrude(
                            FreeCAD.Vector(0, 0, obj0.Height.Value))

    print('Not directly handled')
    #from OpenSCADFeatures import CGALFeature
    #myObj = FreeCAD.ActiveDocument.addObject('Part::FeaturePython','Fred')
    #CGALFeature(myObj,'hull',obj.Group)
    # import OpenSCADFeatures
    #return myObj.Shape
    import OpenSCADUtils
    print('Process OpenSCAD Shapes via OpenSCAD')
    return OpenSCADUtils.process_ObjectsViaOpenSCADShape(FreeCAD.ActiveDocument,\
    group,'hull',maxmeshpoints=None)
Beispiel #29
0
 def execute(self, fp):
     if fp.Base and fp.Base.Shape.isValid():
         import OpenSCADUtils
         sh=fp.Base.Shape.removeSplitter()
         fp.Shape=OpenSCADUtils.applyPlacement(sh)
Beispiel #30
0
            ])

            toolbarcommands.extend([
                'OpenSCAD_AddOpenSCADElement', 'OpenSCAD_MeshBoolean',
                'OpenSCAD_Hull', 'OpenSCAD_Minkowski'
            ])
        else:
            FreeCAD.Console.PrintWarning('OpenSCAD executable not found\n')

        self.appendToolbar(QT_TRANSLATE_NOOP('Workbench', 'OpenSCADTools'),
                           toolbarcommands)
        self.appendMenu('OpenSCAD', commands)
        self.appendToolbar(
            QT_TRANSLATE_NOOP('Workbech', 'OpenSCAD Part tools'),
            parttoolbarcommands)
        #self.appendMenu('OpenSCAD',["AddOpenSCADElement"])
        ###self.appendCommandbar("&Generic Tools",["ColorCodeShape"])
        FreeCADGui.addIconPath(":/icons")
        FreeCADGui.addLanguagePath(":/translations")
        FreeCADGui.addPreferencePage(":/ui/openscadprefs-base.ui", "OpenSCAD")

    def GetClassName(self):
        return "Gui::PythonWorkbench"


Gui.addWorkbench(OpenSCADWorkbench())

openscadfilename = OpenSCADUtils.searchforopenscadexe()
if openscadfilename:  #automatic search was succsessful
    FreeCAD.__unit_test__ += ["TestOpenSCADGui"]