Exemplo n.º 1
1
def ImportElement():
  doc=FreeCAD.ActiveDocument;
  FreeCAD.Console.PrintMessage("Try to import...\n");
  (fname1,fdir1) = QtGui.QFileDialog.getOpenFileName(None,'Open file','');
  ImportGui.insert(fname1,doc.Name);
  doc.recompute();
  ob1=doc.Objects[-1];
    # create groupe and add element to it
  if (hasattr(doc,'OpticalSystem')==False):
    gr1=doc.addObject("App::DocumentObjectGroup","OpticalSystem");
    gr1.newObject("App::DocumentObjectGroup","Rays");
    gr1_e=gr1.newObject("App::DocumentObjectGroup","Elements");
    gr1_e.addObject(ob1);
  else:
    gr1_e=getattr(doc,'Elements');
    gr1_e.addObject(ob1);
  # end if
  ob1.Label="IMPR";
  ob1.ViewObject.ShapeColor=(0.5,0.5,0.5);
  ob1.ViewObject.Transparency=80;
  An=ob1.Placement.Rotation.toEuler();
  P1=ob1.Placement.Base;
  l1=["","Imported",ob1.Name,ob1.Label, \
      P1.x,P1.y,P1.z, \
      An[2],An[1],An[0],None,None,None,1.,1.52,None,None];
  # add lens to list of optical system elements
  OptElementsGui.AddToOSData(l1,"Element");
  doc.recompute();
  if (str(FreeCADGui.ActiveDocument.activeView())=='View3DInventor'):
    FreeCADGui.activeDocument().activeView().viewRear();
    FreeCADGui.activeDocument().activeView().viewRotateRight();
    FreeCADGui.activeDocument().activeView().fitAll();
  # end if
  FreeCAD.Console.PrintMessage("Element is imported\n");
Exemplo n.º 2
0
def import_stpz(fn,fc,doc):

    # sayz(fn)
    ext = os.path.splitext(os.path.basename(fn))[1]
    fname=os.path.splitext(os.path.basename(fn))[0]
    basepath=os.path.split(fn)[0]
    filepath = os.path.join(basepath,fname + u'.stp')
    
    tempdir = tempfile.gettempdir() # get the current temporary directory
    tempfilepath = os.path.join(tempdir,fname + u'.stp')

    #with six.builtins.open(tempfilepath, 'wb') as f: #py3
    with builtin.open(tempfilepath, 'wb') as f: #py3
        f.write(fc)
    #ImportGui.insert(filepath)
    if doc is None:
        ImportGui.open(tempfilepath)
    else:
        ImportGui.open(tempfilepath,doc.Name)
    FreeCADGui.SendMsgToActiveView("ViewFit")
    try:
        os.remove(tempfilepath)
    except OSError:
        sayzerr("error on removing "+tempfilepath+" file")
        pass
Exemplo n.º 3
0
    def load(self, path):
        """ Loads FC, STEP, or STL file into document object. Will return cadpath and format
            properties to store into Part/Assembly class if desired. """
        cadpath = os.path.join('..', '..', path)  # For test bench runs (..\..\ takes you to project root)
        if not os.path.exists(cadpath):
            cadpath = path
            if not os.path.exists(cadpath):
                exitwitherror('Can\'t find cad file!')
        fileformat = cadpath.rsplit('.')[-1].lower()

        try:
            if fileformat in ["step", "stp"]:
                ImportGui.insert(cadpath, self.Name)
            elif fileformat == 'stl':
                Mesh.insert(cadpath, self.Name)
            elif fileformat == "fcstd":
                # Loading a FC file will always open a new doc, so close the current one and set to the new one.
                self.close()
                self.document = FreeCAD.openDocument(cadpath)
                self.Name = self.document.Name
            else:
                exitwitherror('Unsupported file format {0} for file {1}.'.format(str(fileformat), str(path)))

        except (Exception, IOError) as err:
            logger.error(err)
            exitwitherror('Error attempting to import {0}'.format(cadpath))

        logger.info('Imported CAD file {0}'.format(cadpath))

        return cadpath, fileformat
Exemplo n.º 4
0
def import_cad(path, doc):
    """ Imports cad file at path into document doc. May produce more than one FreeCAD object! """
    cadpath = os.path.join('..', '..', path)  # For test bench runs (..\..\ takes you to project root)
    if not os.path.exists(cadpath):
        cadpath = path
        if not os.path.exists(cadpath):
            exitwitherror('Can\'t find cad file!')
    fileformat = cadpath.rsplit('.')[-1].lower()

    newdoc = None
    try:
        if fileformat in ["step", "stp"]:
            ImportGui.insert(cadpath, doc)
        elif fileformat == 'stl':
            Mesh.insert(cadpath, doc)
        elif fileformat == "fcstd":
            # This will create a new doc and ignore doc operator
            newdoc = open_document(cadpath)
        else:
            exitwitherror('Unsupported file format {0} for file to import {1}.'.format(str(fileformat), str(path)))

    except (Exception, IOError) as err:
        logger.error(err)
        exitwitherror('Error attempting to import {0}'.format(cadpath))

    logger.info('Imported CAD file {0}'.format(cadpath))
    return cadpath, fileformat, newdoc
Exemplo n.º 5
0
def GetSTEPAssembly():
    deviceProperties = clsConnectToEB.ConnectToEB().GetShapeProperties()
    file_path = deviceProperties[2]
    exists = os.path.isfile(file_path)
    if exists:
        ImportGui.insert(file_path, FreeCAD.ActiveDocument.Name)
    else:
        EB_Auxiliaries.MsgDialog("STEP file doesn't exist!")
Exemplo n.º 6
0
def read(filename):
    "reads the file and creates objects in the active document"
    #import importZip; reload(importZip)
    print("open Zip STEP version " + ___ZipVersion___)

    z = zipfile.ZipFile(filename)
    l = z.printdir()
    #il = z.infolist()
    nl = z.namelist()
    print("file list: ", nl)
    import ImportGui, FreeCADGui

    for f in nl:
        if '.stp' in f.lower() or '.step' in f.lower():  #\
            #or '.igs' in f.lower() or '.iges' in f.lower():
            file_content = z.read(f)
            #sfe = z.extract(f)
            #print ('extracted ',sfe)
            print('extracted ', f)
            # fname=os.path.splitext(os.path.basename(filename))[0]
            # ext = os.path.splitext(os.path.basename(filename))[1]
            fname = f
            print('fname ', f)
            tempdir = tempfile.gettempdir(
            )  # get the current temporary directory
            tempfilepath = os.path.join(tempdir, fname)  # + ext)
            z.extract(fname, tempdir)
            doc = FreeCAD.ActiveDocument
            ImportGui.insert(tempfilepath, doc.Name)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            try:
                os.remove(tempfilepath)
            except OSError:
                FreeCAD.Console.PrintError("error on removing " +
                                           tempfilepath + " file")
            pass
        elif '.fcstd' in f.lower():  #\
            fname = f
            tempdir = tempfile.gettempdir(
            )  # get the current temporary directory
            tempfilepath = os.path.join(tempdir, fname)  # + ext)
            z.extract(fname, tempdir)
            doc = FreeCAD.ActiveDocument
            i = 0
            for obj in FreeCAD.ActiveDocument.Objects:
                i += 1
            if i == 0:
                FreeCAD.closeDocument(doc.Name)
            FreeCAD.open(tempfilepath)
            #ImportGui.insert(tempfilepath,doc.Name)
            FreeCADGui.SendMsgToActiveView("ViewFit")
            try:
                os.remove(tempfilepath)
            except OSError:
                FreeCAD.Console.PrintError("error on removing " +
                                           tempfilepath + " file")
            pass
Exemplo n.º 7
0
def place_steps(doc,placement,board_thickness):
    """ place_steps(doc,placement,board_thickness)->place step models on board 

        list of models and path to step files is set at start of this script
                 model_tab_filename= "" &   step_path="" """
    model_file=pythonopen(model_tab_filename, "r")
    model_lines=model_file.readlines()
    model_file.close()   
    model_dict=[]
    if IDF_diag==1:
        model_file=pythonopen(IDF_diag_path+"/missing_models.lst", "w")
    keys=[]
    #prev_step="*?.*?" #hope nobody will insert this step filename
    step_dict=[]
    for model_line in model_lines:
        model_records=split_records(model_line)  
        if len(model_records)>1 and model_records[0] and not model_records[0] in keys:
           keys.append(model_records[0])  
           model_dict.append((str(model_records[0]).replace('"',''),str(model_records[1]).replace('"','')))
    model_dict=dict(model_dict)
    validkeys=filter(lambda x:x in  [place_item[2] for place_item in placement], model_dict.keys())
    FreeCAD.Console.PrintMessage("Step models to be loaded for footprints: "+str(validkeys)+"\n")
    grp=doc.addObject("App::DocumentObjectGroup", "Step Lib")
    for validkey in validkeys:
         ImportGui.insert(step_path+model_dict[validkey],FreeCAD.ActiveDocument.Name)
         #partName=FreeCAD.ActiveDocument.ActiveObject.Name
         impPart=FreeCAD.ActiveDocument.ActiveObject
         #impPart.Shape=FreeCAD.ActiveDocument.ActiveObject.Shape
         #impPart.ViewObject.DiffuseColor=FreeCAD.ActiveDocument.ActiveObject.ViewObject.DiffuseColor
         impPart.ViewObject.Visibility=0
         impPart.Label=validkey
         grp.addObject(impPart)
         step_dict.append((validkey,impPart))
         FreeCAD.Console.PrintMessage("Reading step file "+str(model_dict[validkey])+" for footprint "+str(validkey)+"\n")
    step_dict=dict(step_dict)
    grp=doc.addObject("App::DocumentObjectGroup", "Step Models")
    for place_item in placement:
      if place_item[2] in step_dict:
        step_model=doc.addObject("Part::Feature",place_item[0]+"_s")
        FreeCAD.Console.PrintMessage("Adding STEP model "+str(place_item[0])+"\n")
        #if prev_step!=place_item[2]:
        #   model0=Part.read(step_path+"/"+model_dict[place_item[2]])
        #   prev_step=place_item[2]
        step_model.Shape=step_dict[place_item[2]].Shape
        step_model.ViewObject.DiffuseColor=step_dict[place_item[2]].ViewObject.DiffuseColor
        z_pos=0
        rotateY=0
        if place_item[6]=='BOTTOM':
           rotateY=pi
           z_pos=-board_thickness
        placmnt=Base.Placement(Base.Vector(place_item[3],place_item[4],z_pos),toQuaternion(rotateY,place_item[5]*pi/180,0))
        step_model.Placement=placmnt
        grp.addObject(step_model)
      else: 
        if IDF_diag==1:
            model_file.writelines(str(place_item[0])+" "+str(place_item[2])+"\n")
            model_file.close() 
Exemplo n.º 8
0
def place_steps(doc,placement,board_thickness):
    """ place_steps(doc,placement,board_thickness)->place step models on board 

        list of models and path to step files is set at start of this script
                 model_tab_filename= "" &   step_path="" """
    model_file=pythonopen(model_tab_filename, "r")
    model_lines=model_file.readlines()
    model_file.close()   
    model_dict=[]
    if IDF_diag==1:
        model_file=pythonopen(IDF_diag_path+"/missing_models.lst", "w")
    keys=[]
    #prev_step="*?.*?" #hope nobody will insert this step filename
    step_dict=[]
    for model_line in model_lines:
        model_records=split_records(model_line)  
        if len(model_records)>1 and model_records[0] and not model_records[0] in keys:
           keys.append(model_records[0])  
           model_dict.append((str(model_records[0]).replace('"',''),str(model_records[1]).replace('"','')))
    model_dict=dict(model_dict)
    validkeys=filter(lambda x:x in  [place_item[2] for place_item in placement], model_dict.keys())
    FreeCAD.Console.PrintMessage("Step models to be loaded for footprints: "+str(validkeys)+"\n")
    grp=doc.addObject("App::DocumentObjectGroup", "Step Lib")
    for validkey in validkeys:
         ImportGui.insert(step_path+model_dict[validkey],FreeCAD.ActiveDocument.Name)
         #partName=FreeCAD.ActiveDocument.ActiveObject.Name
         impPart=FreeCAD.ActiveDocument.ActiveObject
         #impPart.Shape=FreeCAD.ActiveDocument.ActiveObject.Shape
         #impPart.ViewObject.DiffuseColor=FreeCAD.ActiveDocument.ActiveObject.ViewObject.DiffuseColor
         impPart.ViewObject.Visibility=0
         impPart.Label=validkey
         grp.addObject(impPart)
         step_dict.append((validkey,impPart))
         FreeCAD.Console.PrintMessage("Reading step file "+str(model_dict[validkey])+" for footprint "+str(validkey)+"\n")
    step_dict=dict(step_dict)
    grp=doc.addObject("App::DocumentObjectGroup", "Step Models")
    for place_item in placement:
      if place_item[2] in step_dict:
        step_model=doc.addObject("Part::Feature",place_item[0]+"_s")
        FreeCAD.Console.PrintMessage("Adding STEP model "+str(place_item[0])+"\n")
        #if prev_step!=place_item[2]:
        #   model0=Part.read(step_path+"/"+model_dict[place_item[2]])
        #   prev_step=place_item[2]
        step_model.Shape=step_dict[place_item[2]].Shape
        step_model.ViewObject.DiffuseColor=step_dict[place_item[2]].ViewObject.DiffuseColor
        z_pos=0
        rotateY=0
        if place_item[6]=='BOTTOM':
           rotateY=pi
           z_pos=-board_thickness
        placmnt=Base.Placement(Base.Vector(place_item[3],place_item[4],z_pos),toQuaternion(rotateY,place_item[5]*pi/180,0))
        step_model.Placement=placmnt
        grp.addObject(step_model)
      else: 
        if IDF_diag==1:
            model_file.writelines(str(place_item[0])+" "+str(place_item[2])+"\n")
            model_file.close() 
Exemplo n.º 9
0
def export(objs, filename):
    """exporting to file folder"""

    #sayz(filename)
    sayz("stpZ version " + ___stpZversion___)
    ext = os.path.splitext(os.path.basename(filename))[1]
    fname = os.path.splitext(os.path.basename(filename))[0]
    basepath = os.path.split(filename)[0]
    tempdir = tempfile.gettempdir()  # get the current temporary directory

    filepath = os.path.join(basepath, fname) + u'.stp'
    filepath_base = os.path.join(basepath, fname)

    namefpath = os.path.join(basepath, fname)

    outfpath = os.path.join(basepath, fname) + u'.stpZ'
    outfpath_stp = os.path.join(basepath, fname) + u'.stp'
    outfpath_base = basepath
    #outfpath_str = mkz_string(os.path.join(basepath,fname))
    outfpath_str = os.path.join(basepath, fname)

    if os.path.exists(outfpath_stp):
        sayzw(
            "File cannot be compressed because a file with the same name exists '"
            + outfpath_stp + "'")
        QtGui.QApplication.restoreOverrideCursor()
        reply = QtGui.QMessageBox.information(
            None, "info",
            "File cannot be compressed because\na file with the same name exists\n'"
            + outfpath_stp + "'")
    else:
        ImportGui.export(objs, outfpath_stp)
        if 0:  #os.path.exists(namefpath):
            sayzw(
                "File cannot be compressed because a file with the same name exists '"
                + namefpath + "'")
            QtGui.QApplication.restoreOverrideCursor()
            reply = QtGui.QMessageBox.information(
                None, "info",
                "File cannot be compressed because\na file with the same name exists\n'"
                + namefpath + "'")
        else:
            with six.builtins.open(outfpath_stp, 'rb') as f_in:
                file_content = f_in.read()
                new_f_content = file_content
                f_in.close()
            with gz.open(outfpath_str, 'wb') as f_out:
                f_out.write(new_f_content)
                f_out.close()
            if os.path.exists(outfpath):
                os.remove(outfpath)
                os.rename(outfpath_str, outfpath)
                os.remove(outfpath_stp)
            else:
                os.rename(outfpath_str, outfpath)
                os.remove(outfpath_stp)
    def importNumberRing10(self, modelName):
        """ imports a step file of the ring with numbers (0..9) for the rotary coded switch
        :rtype: ``solid``
        """
        cwd = os.path.dirname(os.path.realpath(__file__)) + "/NumberRing10.step"

        ImportGui.insert(cwd, modelName)

        tmp = FreeCAD.ActiveDocument.Objects[-1]
        tmp.Placement=\
                    FreeCAD.Placement(FreeCAD.Vector(0, 0, self.body_height + self.cover_thickness + self.body_board_distance), FreeCAD.Rotation(FreeCAD.Vector(0,0,0), FreeCAD.Vector(0,0,0)))
        #App.Placement(App.Vector(0,0,5), App.Rotation(App.Vector(0,0,1),0), App.Vector(0,0,0))
        d = os.path.dirname(os.path.realpath(__file__)) + "/NumberRing10.step"
Exemplo n.º 11
0
    def Activated(self):
        a2plib.setAutoSolve(True)  # makes no sense without autosolve = ON
        doc = FreeCAD.activeDocument()
        fileName = doc.FileName
        workingDir, basicFileName = os.path.split(fileName)

        filesToUpdate = []
        subAsmNeedsUpdate, filesToUpdate = createUpdateFileList(
            fileName, workingDir, filesToUpdate, True)

        for f in filesToUpdate:
            #-------------------------------------------
            # update necessary documents
            #-------------------------------------------

            # look only for filenames, not paths, as there are problems on WIN10 (Address-translation??)
            importDoc = None
            importDocIsOpen = False
            requestedFile = os.path.split(f)[1]
            for d in FreeCAD.listDocuments().values():
                recentFile = os.path.split(d.FileName)[1]
                if requestedFile == recentFile:
                    importDoc = d  # file is already open...
                    importDocIsOpen = True
                    break

            if not importDocIsOpen:
                if f.lower().endswith('.fcstd'):
                    importDoc = FreeCAD.openDocument(f)
                elif f.lower().endswith('.stp') or f.lower().endswith('.step'):
                    import ImportGui
                    fname = os.path.splitext(os.path.basename(f))[0]
                    FreeCAD.newDocument(fname)
                    newname = FreeCAD.ActiveDocument.Name
                    FreeCAD.setActiveDocument(newname)
                    ImportGui.insert(filename, newname)
                    importDoc = FreeCAD.ActiveDocument
                else:
                    msg = "A part can only be imported from a FreeCAD '*.fcstd' file"
                    QtGui.QMessageBox.information(
                        QtGui.QApplication.activeWindow(), "Value Error", msg)
                    return

            updateImportedParts(importDoc)
            FreeCADGui.updateGui()
            importDoc.save()
            print(u"==== Assembly '{}' has been updated! =====".format(
                importDoc.FileName))
            if importDoc != doc:
                FreeCAD.closeDocument(importDoc.Name)
Exemplo n.º 12
0
def GetSingleShapeFromSTEP(file_path):
    doc = FreeCAD.ActiveDocument
    current_instances = set(doc.findObjects())
    ImportGui.insert(file_path, doc.Name)
    new_instances = list(set(doc.findObjects()) - current_instances)
    if not len(new_instances) == 1:
        DeleteObjects(doc, new_instances)
        return
    obj = new_instances[0]
    shape = Part.makeCompound(obj.Shape)
    newObj = doc.addObject("Part::Feature", "Test")
    newObj.Shape = obj.Shape.copy()
    newObj.ViewObject.ShapeColor = obj.ViewObject.ShapeColor
    newObj.ViewObject.DiffuseColor = obj.ViewObject.DiffuseColor
    doc.removeObject(obj.Name)
Exemplo n.º 13
0
def exportVRML(doc, modelName, scale, dir):

    ## Export to VRML scaled 1/2.54
    #VrmlFileName='.//'+doc.Label+'.wrl'
    ## outdir=os.path.dirname(os.path.realpath(__file__))+dir
    outdir = dir
    #FreeCAD.Console.PrintMessage('\r\n'+outdir)
    VrmlFileName = outdir + '/' + modelName + '.wrl'
    StepFileName = outdir + '/' + modelName + '.step'
    objs = []
    objs = GetListOfObjects(FreeCAD, doc)
    #objs.append(FreeCAD.getDocument(doc.Name).getObject("Fusion001"))
    FreeCAD.ActiveDocument.addObject('Part::Feature',
                                     'Vrml_model').Shape = objs[0].Shape
    FreeCAD.ActiveDocument.ActiveObject.Label = 'Vrml_model'
    FreeCADGui.ActiveDocument.ActiveObject.ShapeColor = FreeCADGui.getDocument(
        doc.Name).getObject(objs[0].Name).ShapeColor
    FreeCADGui.ActiveDocument.ActiveObject.LineColor = FreeCADGui.getDocument(
        doc.Name).getObject(objs[0].Name).LineColor
    FreeCADGui.ActiveDocument.ActiveObject.PointColor = FreeCADGui.getDocument(
        doc.Name).getObject(objs[0].Name).PointColor
    FreeCADGui.ActiveDocument.ActiveObject.DiffuseColor = FreeCADGui.getDocument(
        doc.Name).getObject(objs[0].Name).DiffuseColor
    FreeCAD.ActiveDocument.recompute()
    newObj = FreeCAD.getDocument(doc.Name).getObject('Vrml_model')
    #scale to export vrml  start
    Draft.scale(newObj,
                delta=FreeCAD.Vector(scale, scale, scale),
                center=FreeCAD.Vector(0, 0, 0),
                legacy=True)

    FreeCAD.activeDocument().recompute()
    #we need to remove object to export only scaled model
    FreeCAD.getDocument(doc.Name).removeObject(objs[0].Name)
    __objs__ = []
    __objs__.append(FreeCAD.getDocument(doc.Name).getObject("Vrml_model"))
    FreeCADGui.export(__objs__, VrmlFileName)
    FreeCAD.activeDocument().recompute()

    #restoring step module
    import ImportGui
    ImportGui.insert(StepFileName, doc.Name)

    FreeCAD.Console.PrintMessage(FreeCAD.ActiveDocument.ActiveObject.Label +
                                 " exported and scaled to Vrml\r\n")
    del __objs__

    return 0
Exemplo n.º 14
0
 def GetShapeWithColor(self, fp, stepFilePath):
     doc = FreeCAD.ActiveDocument
     current_instances = set(doc.findObjects())
     ImportGui.insert(stepFilePath, doc.Name)
     new_instances = list(set(doc.findObjects()) - current_instances)
     if not len(new_instances) == 1:
         self.DeleteObjects(doc, new_instances)
         print("In step file are more as one shapes!")
         self.GetShapeWithoutColor(fp, stepFilePath)
     else:
         print("In step file is one shape!")
         newObj = new_instances[0]
         fp.Shape = newObj.Shape
         fp.ViewObject.ShapeColor = newObj.ViewObject.ShapeColor
         fp.ViewObject.DiffuseColor = newObj.ViewObject.DiffuseColor
         self.DeleteObjects(doc, new_instances)
 def generate_mesh(self, amplification_gap=128):
     FreeCAD.Console.PrintMessage(
         'start generate mesh {}\n'.format(amplification_gap))
     doc = FreeCAD.newDocument()
     FreeCAD.setActiveDocument(doc.Name)
     self.generate_unit_cell(doc, amplification_gap * 1e-3)
     obj = []
     obj.append(doc.getObject('Unit_Cell'))
     ImportGui.export(
         obj,
         u"/localscratch/micromegas/simulation/meshs/normal/{}.step".format(
             amplification_gap))
     FreeCAD.closeDocument(doc.Name)
     FreeCAD.setActiveDocument("")
     FreeCAD.Console.PrintMessage(
         'end generate mesh {}\n'.format(amplification_gap))
Exemplo n.º 16
0
def export(objs,filename):
    """exporting to file folder"""
    
    #sayz(filename)
    sayz("stpZ version "+___stpZversion___)
    ext = os.path.splitext(os.path.basename(filename))[1]
    fname=os.path.splitext(os.path.basename(filename))[0]
    basepath=os.path.split(filename)[0]
    tempdir = tempfile.gettempdir() # get the current temporary directory
    
    filepath = os.path.join(basepath,fname) + u'.stp'
    filepath_base  = os.path.join(basepath,fname)
        
    namefpath = os.path.join(basepath,fname)
        
    outfpath = os.path.join(basepath,fname)+u'.stpZ'
    outfpath_stp = os.path.join(basepath,fname)+u'.stp'
    outfpath_base = basepath
    #outfpath_str = mkz_string(os.path.join(basepath,fname))
    outfpath_str = os.path.join(basepath,fname)
    
        
    if os.path.exists(outfpath_stp):
        sayzw("File cannot be compressed because a file with the same name exists '"+ outfpath_stp +"'")
        QtGui.QApplication.restoreOverrideCursor()
        reply = QtGui.QMessageBox.information(None,"info", "File cannot be compressed because\na file with the same name exists\n'"+ outfpath_stp + "'")
    else:    
        ImportGui.export(objs,outfpath_stp)
        if 0: #os.path.exists(namefpath):
            sayzw("File cannot be compressed because a file with the same name exists '" + namefpath + "'")
            QtGui.QApplication.restoreOverrideCursor()
            reply = QtGui.QMessageBox.information(None,"info", "File cannot be compressed because\na file with the same name exists\n'"+ namefpath+ "'")
        else:
            with six.builtins.open(outfpath_stp, 'rb') as f_in:
                file_content = f_in.read()
                new_f_content = file_content
                f_in.close()
            with gz.open(outfpath_str, 'wb') as f_out:
                f_out.write(new_f_content)
                f_out.close()    
            if os.path.exists(outfpath):
                os.remove(outfpath)
                os.rename(outfpath_str, outfpath)  
                os.remove(outfpath_stp)
            else:
                os.rename(outfpath_str, outfpath)
                os.remove(outfpath_stp)                
Exemplo n.º 17
0
    def convert(self, alpha=None):
        doc = FreeCAD.newDocument("Unnamed")
        FreeCAD.setActiveDocument("Unnamed")
        ImportGui.insert(self._step_file, "Unnamed")
        for rootobj in doc.RootObjects:
            self._handle_object(rootobj)

        scadfile = os.path.join(
            self._out_dir, os.path.basename(self._step_file) + '.scad'
        )
        print(f'Writing SCAD file with import statements to: {scadfile}')
        with open(scadfile, 'w') as fh:
            fh.write(f'imported_alpha = {alpha};\n')
            for f in self._objects:
                fh.write(f.scad(alpha=alpha) + '\n')
        print('\tfile written')
        FreeCAD.closeDocument("Unnamed")
def exportSTEP(doc,modelName, dir):

	## Export to STEP
	## Get cwd

	## outdir=os.path.dirname(os.path.realpath(__file__))+dir
	outdir=dir
	FreeCAD.Console.PrintMessage('\r\n'+outdir)
	StepFileName=outdir+'/'+modelName+'.step'
	objs=[]
	objs=GetListOfObjects(FreeCAD, doc)
	import ImportGui
	FreeCAD.Console.PrintMessage('\r\n'+StepFileName)
	# FreeCAD.Console.PrintMessage(objs)
	FreeCAD.Console.PrintMessage('\r\n'+outdir)
	ImportGui.export(objs,StepFileName)

	return 0
def exportSTEP(doc, modelName, dir):

    ## Export to STEP
    ## Get cwd

    ## outdir=os.path.dirname(os.path.realpath(__file__))+dir
    outdir = dir
    FreeCAD.Console.PrintMessage('\r\n' + outdir)
    StepFileName = outdir + '/' + modelName + '.step'
    objs = []
    objs = GetListOfObjects(FreeCAD, doc)
    import ImportGui
    FreeCAD.Console.PrintMessage('\r\n' + StepFileName)
    # FreeCAD.Console.PrintMessage(objs)
    FreeCAD.Console.PrintMessage('\r\n' + outdir)
    ImportGui.export(objs, StepFileName)

    return 0
Exemplo n.º 20
0
def export(format, parts, exportdir=None, name=None):
    """ 
    Export components back out to given format in their assembled positions. 
    STEP files can be exported to STL, but not the other way around.

    This is not in the Part class since it allows for the export of any number of objects.

    If exportDir is None, the assembly will be exported to one STL.
    If exportDir is specified, the individual components will be exported to STL.
    """
    exportpath = os.getcwd()
    export_individual = False
    if exportdir is not None:
        export_individual = True
        exportpath = os.path.join(os.getcwd(), exportdir)
        if not os.path.isdir(exportpath):
            os.makedirs(exportpath)
    else:
        exportdir = exportpath

    if format.lower() in ['step', 'stp']:
        for obj in parts:
            if obj.isDerivedFrom("Mesh::Feature"):
                logger.warning('Component {0} is derived from an STL file. '.format(obj.Label) +
                               'This can not be exported to the STEP format. This component is being skipped.')
                continue
            ImportGui.export([obj], os.path.join(exportpath, obj.Label + '.step'))
            logger.info('Exported {0}.step to {1}.'.format(obj.Label, exportdir))
    elif format.lower() in ['stl', 'mix']:
        if export_individual:
            for prt in parts:
                Mesh.export([prt], os.path.join(exportpath, prt.Label + '.stl'))
                logger.info('Exported {0}.stl to {1}.'.format(prt.Label, exportdir))
        else:
            Mesh.export(parts, os.path.join(exportpath, FreeCAD.ActiveDocument.Name + '.stl'))
            logger.info('Exported {0}.stl to {1}.'.format(FreeCAD.ActiveDocument.Name, exportdir))
    elif format.lower() == 'fc':
        if name is not None:
            FreeCAD.ActiveDocument.saveAs(os.path.join(exportpath, name + '.FCStd'))
        else:
            FreeCAD.ActiveDocument.saveAs(os.path.join(exportpath, FreeCAD.ActiveDocument.Name + '.FCStd'))
    else:
        exitwitherror('Requested to export parts to unsupported file format {0}.'.format(str(format.lower())))
Exemplo n.º 21
0
def export(objs, filename):
    """exporting to file folder"""

    #sayz(filename)
    sayz("stpZ version " + ___stpZversion___)
    ext = os.path.splitext(os.path.basename(filename))[1]
    fname = os.path.splitext(os.path.basename(filename))[0]
    basepath = os.path.split(filename)[0]
    tempdir = tempfile.gettempdir()  # get the current temporary directory

    filepath = os.path.join(basepath, fname) + u'.stp'
    filepath_base = os.path.join(basepath, fname)

    namefpath = os.path.join(basepath, fname)

    outfpath = os.path.join(basepath, fname) + u'.stpZ'
    outfpathT = os.path.join(tempdir, fname) + u'.stpZ'
    outfpath_stp = os.path.join(basepath, fname) + u'.stp'
    outfpathT_stp = os.path.join(tempdir, fname) + u'.stp'

    outfpath_base = basepath
    #outfpath_str = mkz_string(os.path.join(basepath,fname))
    outfpath_str = os.path.join(basepath, fname) + u'.stp'
    outfpathT_str = os.path.join(tempdir, fname) + u'.stp'

    if os.path.exists(outfpathT_stp):
        os.remove(outfpathT_stp)
        sayzw("Old temp file with the same name removed '" + outfpathT_stp +
              "'")
    ImportGui.export(objs, outfpathT_stp)
    with builtin.open(outfpathT_stp, 'rb') as f_in:
        file_content = f_in.read()
        new_f_content = file_content
        f_in.close()
    with gz.open(outfpathT_str, 'wb') as f_out:
        f_out.write(new_f_content)
        f_out.close()
    if os.path.exists(outfpath):
        shutil.move(outfpathT_str, outfpath)
        #os.remove(outfpathT_stp)
    else:
        shutil.move(outfpathT_str, outfpath)
def exportSTEP(doc, modelName, dir, objectToExport=None):

    ## Export to STEP
    ## Get cwd

    ## outdir=os.path.dirname(os.path.realpath(__file__))+dir
    outdir = dir
    FreeCAD.Console.PrintMessage('\r\n' + outdir)
    StepFileName = outdir + os.sep + modelName + '.step'
    objs = []
    if objectToExport is None:
        objs = GetListOfObjects(FreeCAD, doc)
    else:
        objs.append(objectToExport)
    import ImportGui
    FreeCAD.Console.PrintMessage('\r\n' + StepFileName)
    # FreeCAD.Console.PrintMessage(objs)
    FreeCAD.Console.PrintMessage('\r\n' + outdir)
    ImportGui.export(objs, StepFileName)

    return 0
def exportSTEP(doc,modelName, dir, objectToExport=None):

    ## Export to STEP
    ## Get cwd

    ## outdir=os.path.dirname(os.path.realpath(__file__))+dir
    outdir=dir
    FreeCAD.Console.PrintMessage('\r\n'+outdir)
    StepFileName=outdir+os.sep+modelName+'.step'
    objs=[]
    if objectToExport is None:
        objs=GetListOfObjects(FreeCAD, doc)
    else:
        objs.append(objectToExport)
    import ImportGui
    FreeCAD.Console.PrintMessage('\r\n'+StepFileName)
    # FreeCAD.Console.PrintMessage(objs)
    FreeCAD.Console.PrintMessage('\r\n'+outdir)
    ImportGui.export(objs,StepFileName)

    return 0
def exportVRML(doc,modelName,scale,dir):

	## Export to VRML scaled 1/2.54
	#VrmlFileName='.//'+doc.Label+'.wrl'
	## outdir=os.path.dirname(os.path.realpath(__file__))+dir
	outdir=dir
	FreeCAD.Console.PrintMessage('\r\n'+outdir)
	VrmlFileName=outdir+'/'+modelName+'.wrl'
	StepFileName=outdir+'/'+modelName+'.step'
	objs=[]
	objs=GetListOfObjects(FreeCAD, doc)
	#objs.append(FreeCAD.getDocument(doc.Name).getObject("Fusion001"))
	FreeCAD.ActiveDocument.addObject('Part::Feature','Vrml_model').Shape=objs[0].Shape
	FreeCAD.ActiveDocument.ActiveObject.Label='Vrml_model'
	FreeCADGui.ActiveDocument.ActiveObject.ShapeColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).ShapeColor
	FreeCADGui.ActiveDocument.ActiveObject.LineColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).LineColor
	FreeCADGui.ActiveDocument.ActiveObject.PointColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).PointColor
	FreeCADGui.ActiveDocument.ActiveObject.DiffuseColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).DiffuseColor
	FreeCAD.ActiveDocument.recompute()
	newObj=FreeCAD.getDocument(doc.Name).getObject('Vrml_model')
	#scale to export vrml  start
	Draft.scale(newObj,delta=FreeCAD.Vector(scale,scale,scale),center=FreeCAD.Vector(0,0,0),legacy=True)

	FreeCAD.activeDocument().recompute()
	#we need to remove object to export only scaled model
	FreeCAD.getDocument(doc.Name).removeObject(objs[0].Name)
	__objs__=[]
	__objs__.append(FreeCAD.getDocument(doc.Name).getObject("Vrml_model"))
	FreeCADGui.export(__objs__,VrmlFileName)
	FreeCAD.activeDocument().recompute()

	#restoring step module
	import ImportGui
	ImportGui.insert(StepFileName,doc.Name)

	FreeCAD.Console.PrintMessage(FreeCAD.ActiveDocument.ActiveObject.Label+" exported and scaled to Vrml\r\n")
	del __objs__

	return 0
Exemplo n.º 25
0
def GetShapeFromSTEP(file_path):

    doc = FreeCAD.ActiveDocument
    current_instances = set(doc.findObjects())
    ImportGui.insert(file_path, doc.Name)
    new_instances = set(doc.findObjects()) - current_instances
    shapes = list(new_instances)
    sh = []
    cols = []
    areas = []

    for s in shapes:
        # print(s.TypeId)

        if hasattr(s, "Shape"):
            if hasattr(s.ViewObject, "DiffuseColor"):
                col = list(zip(s.Shape.Faces, s.ViewObject.DiffuseColor))
                print(len(s.Shape.Faces))
                print(len(s.ViewObject.DiffuseColor))
                print(s.ViewObject.DiffuseColor)
                print(len(col))
                cols.append(col)
                # print(s.ViewObject.DiffuseColor)
                sh.append(s.Shape)

    for c in cols:
        for faceshape, colortuple in c:
            areas.append((faceshape.Area, colortuple))

    # for s in shapes:
    #     try:
    #         doc.removeObject(s.Name)
    #     except:
    #         pass
    shape = Part.makeCompound(sh)
    # print(len(shape.Faces))
    # print(len(areas))
    Part.show(shape)
Exemplo n.º 26
0
def open(filename):

    sayz("stpZ version " + ___stpZversion___)
    with gz.open(filename, 'rb') as f:
        file_content = f.read()

    ext = os.path.splitext(os.path.basename(filename))[1]
    fname = os.path.splitext(os.path.basename(filename))[0]
    basepath = os.path.split(filename)[0]
    filepath = os.path.join(basepath, fname + u'.stp')

    tempdir = tempfile.gettempdir()  # get the current temporary directory
    tempfilepath = os.path.join(tempdir, fname + u'.stp')

    with six.builtins.open(tempfilepath, 'wb') as f:  #py3
        f.write(file_content)
    #ImportGui.insert(filepath)
    ImportGui.open(tempfilepath)
    try:
        os.remove(tempfilepath)
    except OSError:
        sayzerr("error on removing " + tempfilepath + " file")
        pass
Exemplo n.º 27
0
def insert(filename,doc):

    sayz("stpZ version "+___stpZversion___)
    with gzip_utf8.open(filename, 'rb') as f:
        file_content = f.read()

    ext = os.path.splitext(os.path.basename(filename))[1]
    fname=os.path.splitext(os.path.basename(filename))[0]
    basepath=os.path.split(filename)[0]
    filepath = os.path.join(basepath,fname + u'.stp')

    tempdir = tempfile.gettempdir() # get the current temporary directory
    tempfilepath = os.path.join(tempdir,fname + u'.stp')
    
    with builtin.open(tempfilepath, 'w') as f: #py3
        f.write(file_content)
    ImportGui.insert(tempfilepath, doc)
    #ImportGui.open(tempfilepath)
    try:
        os.remove(tempfilepath)
    except OSError:
        sayzerr("error on removing "+tempfilepath+" file")
        pass
Exemplo n.º 28
0
def gmshmesh(compound, NG2D, name=""):
    '''
    export, mesh compound at gmsh, reimport as .unv
    (3d to be implemented)
    '''
    if name =="": name="m_"+compound.Label
    #
    ImportGui.export([FreeCAD.activeDocument().getObject(compound.Name)], "/tmp/tmpNO2c.step")
    #
    command="/usr/bin/gmsh /tmp/tmpNO2c.step -2 -format unv -o /tmp/"+name+".unv -algo "+str(NG2D.gmshalgoname)+" -clmax " +str(NG2D.NGParamSetMaxSize)+" -clmin "+str(NG2D.NGParamSetMinSize)+" -string Geometry.OCCSewFaces=1;"
    #command="/usr/bin/gmsh /tmp/tmpNO2c.step -2 -format unv -o /tmp/Compound019_Mesh.unv -algo auto -string Geometry.OCCSewFaces=1;"

    #command="g"
    #
    #print command
    output = subprocess.check_output([command, '-1'], shell=True, stderr=subprocess.STDOUT,)
    FreeCAD.Console.PrintMessage(output)
    #
    Fem.insert("/tmp/"+name+".unv", FreeCAD.ActiveDocument.Name)
    #Fem.insert("/tmp/Compound019_Mesh.unv", FreeCAD.ActiveDocument.Name)
    femmesh=FreeCAD.ActiveDocument.Objects[len(FreeCAD.ActiveDocument.Objects)-1]
    FreeCADGui.ActiveDocument.getObject(femmesh.Name).DisplayMode = "Wireframe"
    return femmesh
Exemplo n.º 29
0
def importPart(filename):
    doc_assembly = App.ActiveDocument
    App.Console.PrintMessage("importing part from %s\n" % filename)
    
    doc_already_open = filename in [ d.FileName for d in App.listDocuments().values() ]
    App.Console.PrintMessage("%s open already %s" % (filename, doc_already_open))
    
    if doc_already_open:
        doc = [ d for d in App.listDocuments().values() if d.FileName == filename][0]
    else:
        if filename.lower().endswith('.fcstd'):
            App.Console.PrintMessage('opening %s' % filename)
            doc = App.openDocument(filename)
            App.Console.PrintMessage('succesfully opened %s' % filename)
        else: #trying shaping import http://forum.freecadweb.org/viewtopic.php?f=22&t=12434&p=99772#p99772x
            import ImportGui
            doc = App.newDocument( os.path.basename(filename) )
            shapeobj=ImportGui.insert(filename,doc.Name)
    
    visibleObjects = [ obj for obj in doc.Objects
                       if hasattr(obj,'ViewObject') and obj.ViewObject.isVisible()
                       and hasattr(obj,'Shape') and len(obj.Shape.Faces) > 0 and 'Body' not in obj.Name] # len(obj.Shape.Faces) > 0 to avoid sketches, skip Body
    App.Console.PrintMessage('Visible objects %s' % visibleObjects)
    
    obj = doc_assembly.addObject("Part::FeaturePython", 'part123456')
    obj.addProperty("App::PropertyFile", "sourceFile", "D3D_ImportPart").sourceFile = filename
    obj.addProperty("App::PropertyFloat", "timeLastImport", "D3D_ImportPart")
    obj.setEditorMode("timeLastImport", 1)
    obj.addProperty("App::PropertyBool", "fixedPosition", "D3D_ImportPart")
    obj.fixedPosition = not any([i.fixedPosition for i in doc_assembly.Objects if hasattr(i, 'fixedPosition') ])
    #obj.addProperty("App::PropertyBool", "updateColors", "importPart").updateColors = True
    obj_to_copy  = visibleObjects[0]
    obj.Shape = obj_to_copy.Shape.copy()
    
    obj.Proxy = Proxy_importPart()
    obj.timeLastImport = os.path.getmtime( filename )
    #clean up
    #if subAssemblyImport:
    #    doc_assembly.removeObject(tempPartName)
    if not doc_already_open: #then close again
        App.closeDocument(doc.Name)
        App.setActiveDocument(doc_assembly.Name)
        App.ActiveDocument = doc_assembly
    return obj
Exemplo n.º 30
0
    def Activated(cls, idx=0):
        _ = idx
        from .assembly import Assembly

        objs = []
        for obj in FreeCADGui.Selection.getSelection():
            if obj.isDerivedFrom('App::LinkGroup'):
                objs.append(obj)
            else:
                objs = None
                break

        filenames = None
        if not objs:
            filenames = QtGui.QFileDialog.getOpenFileNames(
                QtGui.QApplication.activeWindow(), 'Please select file', None,
                'STEP (*.stp *.step);;All (*.*)')[0]
            if not filenames:
                return

        FreeCAD.setActiveTransaction('Assembly import')

        doc = FreeCAD.ActiveDocument
        if not doc:
            doc = FreeCAD.newDocument()

        if filenames:
            import ImportGui
            for name in filenames:
                obj = ImportGui.insert(name,
                                       doc.Name,
                                       merge=False,
                                       useLinkGroup=True,
                                       mode=cls.importMode())
                if obj:
                    objs.append(obj)

        for obj in objs:
            Assembly.fromLinkGroup(obj)
        FreeCAD.closeActiveTransaction()
        return
                     App.Vector(sr_2x[0], sr_2y[0] - 11, 0)), False)

App.getDocument('Unnamed').recompute()

f = FreeCAD.getDocument('Unnamed').addObject('Part::Extrusion', 'Extrude')
f = App.getDocument('Unnamed').getObject('Extrude')
f.Base = App.getDocument('Unnamed').getObject('Sketch')
f.DirMode = "Custom"
f.Dir = App.Vector(0.000000000000000, 0.000000000000000, 1.000000000000000)
f.DirLink = None
f.LengthFwd = 4.500000000000000
f.LengthRev = 0.000000000000000
f.Solid = True
f.Reversed = False
f.Symmetric = False
f.TaperAngle = 0.000000000000000
f.TaperAngleRev = 0.000000000000000
# Gui.ActiveDocument.Extrude.ShapeColor=Gui.ActiveDocument.Sketch.ShapeColor
# Gui.ActiveDocument.Extrude.LineColor=Gui.ActiveDocument.Sketch.LineColor
# Gui.ActiveDocument.Extrude.PointColor=Gui.ActiveDocument.Sketch.PointColor
f.Base.ViewObject.hide()

App.ActiveDocument.recompute()

__objs__ = []
__objs__.append(FreeCAD.getDocument("Unnamed").getObject("Extrude"))
import ImportGui
ImportGui.export(__objs__, u"C:/Users/asea2/Desktop/imyafila.step")

del __objs__
Exemplo n.º 32
0
def exportStep(objs, filename):
    ImportGui.export(objs,filename)
def MakeHeader(n, model, all_params):
    global formerDOC
    global LIST_license
    ModelName = model.replace('yy', "{n:02}".format(n=n))

    full_path=os.path.realpath(__file__)
    expVRML.say(full_path)
    scriptdir=os.path.dirname(os.path.realpath(__file__))
    expVRML.say(scriptdir)
    sub_path = full_path.split(scriptdir)
    expVRML.say(sub_path)
    sub_dir_name =full_path.split(os.sep)[-2]
    expVRML.say(sub_dir_name)
    sub_path = full_path.split(sub_dir_name)[0]
    expVRML.say(sub_path)
    models_dir=sub_path+"_3Dmodels"
    script_dir=os.path.dirname(os.path.realpath(__file__))
    #models_dir=script_dir+"/../_3Dmodels"
    expVRML.say(models_dir)
    out_dir=models_dir+all_params[model]['output_directory']
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace('(', '').replace(')', '')
   
    newdoc = App.newDocument(CheckedModelName)
    App.setActiveDocument(CheckedModelName)
    App.ActiveDocument=App.getDocument(CheckedModelName)
    Gui.ActiveDocument=Gui.getDocument(CheckedModelName)
    
    header_type = all_params[model]['type']
    pitch = all_params[model]['pitch']
    rows = all_params[model]['rows']
    base_width = all_params[model]['base_width']
    base_height = all_params[model]['base_height']
    base_chamfer = all_params[model]['base_chamfer']
    pin_width = all_params[model]['pin_width']
    pin_length_above_base = all_params[model]['pin_length_above_base']
    
    pin_end_chamfer = all_params[model]['pin_end_chamfer']
    rotation = all_params[model]['rotation']
    
    if base_chamfer == 'auto':
        base_chamfer = pitch/10.

    if pin_end_chamfer == 'auto':
        pin_end_chamfer = pin_width/4.

    if header_type == 'Vertical_THT':
        pin_length_below_board = all_params[model]['pin_length_below_board']
        base = make_Vertical_THT_base(n, pitch, rows, base_width, base_height, base_chamfer)
        pins = make_Vertical_THT_pins(n, pitch, rows, pin_length_above_base, pin_length_below_board, base_height, pin_width, pin_end_chamfer)
    elif header_type == 'Horizontal_THT':
        pin_length_below_board = all_params[model]['pin_length_below_board']
        base_x_offset = all_params[model]['base_x_offset']
        base = make_Horizontal_THT_base(n, pitch, rows, base_width, base_height, base_x_offset, base_chamfer)
        pins = make_Horizontal_THT_pins(n, pitch, rows, pin_length_above_base, pin_length_below_board, base_height, base_width, pin_width, pin_end_chamfer, base_x_offset)
    elif header_type == 'Vertical_SMD':
        pin_length_horizontal = all_params[model]['pin_length_horizontal']
        base_z_offset = all_params[model]['base_z_offset']
        if rows == 1:
            pin_1_start = all_params[model]['pin_1_start']
        else:
            pin_1_start = None
        pins = make_Vertical_SMD_pins(n, pitch, rows, pin_length_above_base, pin_length_horizontal, base_height, base_width, pin_width, pin_end_chamfer, base_z_offset, pin_1_start)
        base = make_Vertical_SMD_base(n, pitch, base_width, base_height, base_chamfer, base_z_offset)
    else:
        print 'Header type: '
        print header_type
        print ' is not recognized, please check parameters'
        stop

    show(base)
    show(pins)

    doc = FreeCAD.ActiveDocument
    objs=GetListOfObjects(FreeCAD, doc)
    
    Color_Objects(Gui,objs[0],body_color)
    Color_Objects(Gui,objs[1],pins_color)
    #Color_Objects(Gui,objs[2],marking_color)

    col_body=Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
    col_pin=Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
    #col_mark=Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
    material_substitutions={
        col_body[:-1]:body_color_key,
        col_pin[:-1]:pins_color_key,
        #col_mark[:-1]:marking_color_key
    }
    expVRML.say(material_substitutions)

    #objs=GetListOfObjects(FreeCAD, doc)
    FuseObjs_wColors(FreeCAD, FreeCADGui,
                   doc.Name, objs[0].Name, objs[1].Name)
    doc.Label=CheckedModelName
    objs=GetListOfObjects(FreeCAD, doc)
    objs[0].Label=CheckedModelName
    restore_Main_Tools()

    if (rotation !=0):
        z_RotateObject(doc, rotation)
    
    #out_dir = models_dir+"/generated_pinheaders"
    
    doc.Label = CheckedModelName
    
    #save the STEP file
    exportSTEP(doc, ModelName, out_dir)
    if LIST_license[0]=="":
        LIST_license=Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)
    
    # scale and export Vrml model
    scale=1/2.54
    #exportVRML(doc,ModelName,scale,out_dir)
    objs=GetListOfObjects(FreeCAD, doc)
    expVRML.say("######################################################################")
    expVRML.say(objs)
    expVRML.say("######################################################################")
    export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions)
    export_file_name=out_dir+os.sep+ModelName+'.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale)
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)

    #save the VRML file
    #scale=0.3937001
    #exportVRML(doc,name,scale,out_dir)
    
    if save_memory == False:
        Gui.SendMsgToActiveView("ViewFit")
        Gui.activeDocument().activeView().viewAxometric()

    # Save the doc in Native FC format 
    saveFCdoc(App, Gui, doc, ModelName, out_dir, False) 
    
    check_Model=True
    if save_memory == True or check_Model==True:
        doc=FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)
    step_path=os.path.join(out_dir,ModelName+u'.step')
    if check_Model==True:
        #ImportGui.insert(step_path,ModelName)
        ImportGui.open(step_path)
        docu = FreeCAD.ActiveDocument
        if cq_cad_tools.checkUnion(docu) == True:
            FreeCAD.Console.PrintMessage('step file is correctly Unioned\n')
        else:
            FreeCAD.Console.PrintError('step file is NOT Unioned\n')
            stop
        FC_majorV=int(FreeCAD.Version()[0])
        FC_minorV=int(FreeCAD.Version()[1])
        if FC_majorV == 0 and FC_minorV >= 17:
            for o in docu.Objects:
                if hasattr(o,'Shape'):
                    chks=cq_cad_tools.checkBOP(o.Shape)
                    print 'chks ',chks
                    print cq_cad_tools.mk_string(o.Label)
                    if chks != True:
                        msg='shape \''+o.Name+'\' \''+cq_cad_tools.mk_string(o.Label)+'\' is INVALID!\n'
                        FreeCAD.Console.PrintError(msg)
                        FreeCAD.Console.PrintWarning(chks[0])
                        stop
                    else:
                        msg='shape \''+o.Name+'\' \''+cq_cad_tools.mk_string(o.Label)+'\' is valid\n'
                        FreeCAD.Console.PrintMessage(msg)
        else:
            FreeCAD.Console.PrintError('BOP check requires FC 0.17+\n')
            # Save the doc in Native FC format
        saveFCdoc(App, Gui, docu, ModelName,out_dir, False)
        doc=FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)
        
    return 0
Exemplo n.º 34
0
def export(ftype, componentName, componentModel, filename, fuse=False, scale=None):
    """ Exports given ComponentModel object using FreeCAD.

    `ftype` : one of "STEP", "VRML", "FREECAD", "X3D"
    `componentModel` : a ComponentModel instance
    `filename` : name of the file, extension is important
    `fuse` : fuse objects together before export (preserves color)
    `scale` : scales the model with this factor before exporting

    X3D exporter doesn't support `fuse` parameter.
    """
    objects = componentModel.parts

    if len(objects) < 1:
        raise Exception("ComponentModel is empty!")

    if len(objects) == 1: # can't fuse if there is only 1 object
        fuse = False

    # export to X3D or Simple VRML, continue for other exporters (VRML, FREECAD, STEP)
    if ftype in ["X3D", "S_VRML"]:
        if fuse: print("%s exporter can't do fuse, ignoring." % ftype)

        from export_x3d import exportX3D, Mesh
        from export_vrml import exportVRML

        meshes = [shapeToMesh(o[0].toFreecad(), o[1], scale) for o in objects]

        if ftype == "X3D":
            exportX3D(meshes, filename)
        else: # S_VRML
            exportVRML(meshes, filename)

        return

    # init FreeCADGui
    try:
        import ImportGui
    except ImportError:
        FreeCADGui.showMainWindow()
        FreeCADGui.getMainWindow().hide() # prevent splash of main window
        import ImportGui # must be after `showMainWindow`

    # make sure RefineShape=False
    pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Part/Boolean")
    usersRSOption = pg.GetBool("RefineModel") # will be restored, we promise
    pg.SetBool("RefineModel", False)

    # create a FreeCAD document
    doc = FreeCAD.newDocument()

    # create objects
    fcobjects = [makeFCObject(doc, componentName+"_"+co[2], co[0], co[1])
                 for co in objects]

    if fuse:
        fuseobj = doc.addObject("Part::MultiFuse", componentName)
        fuseobj.Shapes = fcobjects
        doc.recompute()
        exportObjects = [fuseobj]
    else:
        exportObjects = fcobjects

    if scale:
        import Draft
        v = FreeCAD.Vector(scale, scale, scale)
        vc = FreeCAD.Vector(0,0,0)
        # legacy=False, sometimes fail if scale < 1.0
        exportObjects = [Draft.scale(obj, delta=v, center=vc, legacy=True) for obj in exportObjects]

    doc.recompute()

    if ftype == "STEP":
        # check filename
        if not os.path.splitext(filename)[1] in ['.stp', '.step']:
            raise Exception("Filename for STEP export must end with '.stp' or '.step'.")
        ImportGui.export(exportObjects, filename)

    elif ftype == "VRML":
        # check filename
        if not os.path.splitext(filename)[1] in ['.wrl', '.vrml']:
            raise Exception("Filename for VRML export must end with '.wrl' or '.vrml'.")

        # workaround for not exporting unselected objects (v0.16)
        # http://www.freecadweb.org/tracker/view.php?id=2221
        FreeCADGui.Selection.clearSelection()
        for o in exportObjects: FreeCADGui.Selection.addSelection(o)

        # deal with points and lines
        for o in exportObjects: o.ViewObject.DisplayMode = "Shaded"

        FreeCADGui.export(exportObjects, filename)

    elif ftype == "FREECAD":
        for obj in list(doc.Objects):
            if not (obj in exportObjects): doc.removeObject(obj.Name)
        doc.saveAs(filename)

    else:
        raise Exception("Unknown export file type!")

    # restore RefineShape option
    pg.SetBool("RefineModel", usersRSOption)
Exemplo n.º 35
0
# freecad macro

from pathlib import Path

import ImportGui
import Mesh

step_root = Path('/home/rlha/d/iros-kit-template/STEP_Files')
stl_root = Path('/home/rlha/d/iros-kit-template/stl')

for step_file in step_root.glob('*.STEP'):
    if step_file.name == 'IROS2020_Practice.STEP':
        continue
    ImportGui.open(str(step_file))
    stl_name = step_file.name.replace('.STEP', '.stl')
    Mesh.export(App.ActiveDocument.Objects, str(stl_root / stl_name))
    App.closeDocument(App.ActiveDocument.Name)
Exemplo n.º 36
0
def importPart( filename, partName=None, doc_assembly=None ):
    if doc_assembly == None:
        doc_assembly = FreeCAD.ActiveDocument
    updateExistingPart = partName != None
    if updateExistingPart:
        FreeCAD.Console.PrintMessage("updating part %s from %s\n" % (partName,filename))
    else:
        FreeCAD.Console.PrintMessage("importing part from %s\n" % filename)
    doc_already_open = filename in [ d.FileName for d in FreeCAD.listDocuments().values() ]
    debugPrint(4, "%s open already %s" % (filename, doc_already_open))
    if doc_already_open:
        doc = [ d for d in FreeCAD.listDocuments().values() if d.FileName == filename][0]
        close_doc = False
    else:
        if filename.lower().endswith('.fcstd'):
            doc = Fcstd_File_Parser( filename )
            close_doc = False
        else: #trying shaping import http://forum.freecadweb.org/viewtopic.php?f=22&t=12434&p=99772#p99772x
            import ImportGui
            doc = FreeCAD.newDocument( os.path.basename(filename) )
            shapeobj = ImportGui.insert(filename,doc.Name)
            close_doc = True

    visibleObjects = [ obj for obj in doc.Objects
                       if hasattr(obj,'ViewObject') and obj.ViewObject.isVisible()
                       and hasattr(obj,'Shape') and len(obj.Shape.Faces) > 0 and 'Body' not in obj.Name] # len(obj.Shape.Faces) > 0 to avoid sketches, skip Body

    debugPrint(3, '%s objects %s' % (doc.Name, doc.Objects))
    if any([ 'importPart' in obj.Content for obj in doc.Objects]) and not len(visibleObjects) == 1:
        subAssemblyImport = True
        debugPrint(2, 'Importing subassembly from %s' % filename)
        tempPartName = 'import_temporary_part'
        obj_to_copy = doc_assembly.addObject("Part::FeaturePython",tempPartName)
        obj_to_copy.Proxy = Proxy_muxAssemblyObj()
        obj_to_copy.ViewObject.Proxy = ImportedPartViewProviderProxy()
        obj_to_copy.Shape =  muxObjects(doc)
        if (not updateExistingPart) or \
                (updateExistingPart and getattr( doc_assembly.getObject(partName),'updateColors',True)):
            muxMapColors(doc, obj_to_copy)
    else:
        subAssemblyImport = False
        if len(visibleObjects) != 1:
            if not updateExistingPart:
                msg = "A part can only be imported from a FreeCAD document with exactly one visible part. Aborting operation"
                QtGui.QMessageBox.information(  QtGui.QApplication.activeWindow(), "Value Error", msg )
            else:
                msg = "Error updating part from %s: A part can only be imported from a FreeCAD document with exactly one visible part. Aborting update of %s" % (partName, filename)
            QtGui.QMessageBox.information(  QtGui.QApplication.activeWindow(), "Value Error", msg )
        #QtGui.QMessageBox.warning( QtGui.QApplication.activeWindow(), "Value Error!", msg, QtGui.QMessageBox.StandardButton.Ok )
            return
        obj_to_copy  = visibleObjects[0]

    if updateExistingPart:
        obj = doc_assembly.getObject(partName)
        prevPlacement = obj.Placement
        if not hasattr(obj, 'updateColors'):
            obj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
        importUpdateConstraintSubobjects( doc_assembly, obj, obj_to_copy )
    else:
        partName = findUnusedObjectName( doc.Label + '_', document=doc_assembly )
        try:
            obj = doc_assembly.addObject("Part::FeaturePython",partName)
        except UnicodeEncodeError:
            safeName = findUnusedObjectName('import_', document=doc_assembly)
            obj = doc_assembly.addObject("Part::FeaturePython", safeName)
            obj.Label = findUnusedLabel( doc.Label + '_', document=doc_assembly )
        obj.addProperty("App::PropertyFile",    "sourceFile",    "importPart").sourceFile = filename
        obj.addProperty("App::PropertyFloat", "timeLastImport","importPart")
        obj.setEditorMode("timeLastImport",1)
        obj.addProperty("App::PropertyBool","fixedPosition","importPart")
        obj.fixedPosition = not any([i.fixedPosition for i in doc_assembly.Objects if hasattr(i, 'fixedPosition') ])
        obj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
    obj.Shape = obj_to_copy.Shape.copy()
    if updateExistingPart:
        obj.Placement = prevPlacement
    else:
        # for Fcstd_File_Parser not all properties are implemented...
        for p in obj_to_copy.ViewObject.PropertiesList: #assuming that the user may change the appearance of parts differently depending on the assembly.
            if hasattr(obj.ViewObject, p) and p not in ['DiffuseColor']:
                try:
                    setattr(obj.ViewObject, p, getattr(obj_to_copy.ViewObject, p))
                except Exception as msg:
                    FreeCAD.Console.PrintWarning('Unable to setattr(obj.ViewObject, %s, %s)\n' % (p, getattr(obj_to_copy.ViewObject, p) ))
        obj.ViewObject.Proxy = ImportedPartViewProviderProxy()
    if getattr(obj,'updateColors',True) and hasattr( obj_to_copy.ViewObject, 'DiffuseColor'):
        obj.ViewObject.DiffuseColor = copy.copy( obj_to_copy.ViewObject.DiffuseColor )
        #obj.ViewObject.Transparency = copy.copy( obj_to_copy.ViewObject.Transparency )   # .Transparency property
        tsp = copy.copy( obj_to_copy.ViewObject.Transparency )   #  .Transparency workaround for FC 0.17 @ Nov 2016
        if tsp < 100 and tsp!=0:
            obj.ViewObject.Transparency = tsp+1
        if tsp == 100:
            obj.ViewObject.Transparency = tsp-1
        obj.ViewObject.Transparency = tsp   # .Transparency workaround end
    obj.Proxy = Proxy_importPart()
    obj.timeLastImport = os.path.getmtime( filename )
    #clean up
    if subAssemblyImport:
        doc_assembly.removeObject(tempPartName)
    if close_doc: 
        FreeCAD.closeDocument( doc.Name )
        FreeCAD.setActiveDocument( doc_assembly.Name )
        FreeCAD.ActiveDocument = doc_assembly
    return obj
            Gui.SendMsgToActiveView("ViewFit")
            Gui.activeDocument().activeView().viewAxometric()

        # Save the doc in Native FC format
        saveFCdoc(App, Gui, doc, ModelName,out_dir, False)


        check_Model=False
        if save_memory == True or check_Model==True:
            doc=FreeCAD.ActiveDocument
            FreeCAD.closeDocument(doc.Name)

        step_path=os.path.join(out_dir,ModelName+u'.step')
        if check_Model==True:
            #ImportGui.insert(step_path,ModelName)
            ImportGui.open(step_path)
            docu = FreeCAD.ActiveDocument
            if cq_cad_tools.checkUnion(docu) == True:
                FreeCAD.Console.PrintMessage('step file is correctly Unioned\n')
            else:
                FreeCAD.Console.PrintError('step file is NOT Unioned\n')
                stop
            FC_majorV=int(FreeCAD.Version()[0])
            FC_minorV=int(FreeCAD.Version()[1])
            if FC_majorV == 0 and FC_minorV >= 17:
                for o in docu.Objects:
                    if hasattr(o,'Shape'):
                        chks=cq_cad_tools.checkBOP(o.Shape)
                        print 'chks ',chks
                        print cq_cad_tools.mk_string(o.Label)
                        if chks != True:
        if save_memory == False:
            Gui.SendMsgToActiveView("ViewFit")
            Gui.activeDocument().activeView().viewAxometric()

        # Save the doc in Native FC format
        saveFCdoc(App, Gui, doc, ModelName, out_dir, False)

        check_Model = True
        if save_memory == True or check_Model == True:
            doc = FreeCAD.ActiveDocument
            FreeCAD.closeDocument(doc.Name)

        step_path = os.path.join(out_dir, ModelName + u'.step')
        if check_Model == True:
            #ImportGui.insert(step_path,ModelName)
            ImportGui.open(step_path)
            docu = FreeCAD.ActiveDocument
            if cq_cad_tools.checkUnion(docu) == True:
                FreeCAD.Console.PrintMessage(
                    'step file is correctly Unioned\n')
            else:
                FreeCAD.Console.PrintError('step file is NOT Unioned\n')
                stop
            FC_majorV = int(FreeCAD.Version()[0])
            FC_minorV = int(FreeCAD.Version()[1])
            if FC_majorV == 0 and FC_minorV >= 17:
                for o in docu.Objects:
                    if hasattr(o, 'Shape'):
                        chks = cq_cad_tools.checkBOP(o.Shape)
                        print('chks ', chks)
                        print(cq_cad_tools.mk_string(o.Label))
def runGeometryCheck(App, Gui, step_path, log,
        modelName, save_memory=True, stop_on_first_error = True):

    FC_majorV=int(FreeCAD.Version()[0])
    FC_minorV=int(FreeCAD.Version()[1])
    try:
        FC_subV=int(FreeCAD.Version()[2].split(" ")[0])
    except Exception:
        FC_subV = 0

    if FC_majorV == 0 and FC_minorV == 16 and FC_subV < 6712:
        raise FreeCADVersionError('0.16-6712', 'old 0.16 releases have a bug in the step exporter.')

    geometry_error_container = GeometryError()

    ImportGui.open(step_path)
    docu = FreeCAD.ActiveDocument
    docu.Label = modelName
    log.write('\n## Checking {:s}\n'.format(modelName))


    if checkUnion(docu):
        FreeCAD.Console.PrintMessage('step file is correctly Unioned\n')
        log.write('\t- Union check:    [    pass    ]\n')
    else:
        #FreeCAD.Console.PrintError('step file is NOT Unioned\n')
        log.write('\t- Union check:    [    FAIL    ]\n')
        geometry_error_container.append(NotUnionedError(modelName))
        #stop
    if FC_majorV == 0 and FC_minorV >= 17:
        if docu.Objects == 0:
            FreeCAD.Console.PrintError('Step import seems to fail. No objects to check\n')
        for o in docu.Objects:
            if hasattr(o,'Shape'):
                o.Shape.fixTolerance(1e-4)
                chks=checkBOP(o.Shape)
                #print 'chks ',chks
                if chks != True:
                    #msg='shape \''+o.Name+'\' \''+ mk_string(o.Label)+'\' is INVALID!\n'
                    msg = 'shape "{name:s}" "{label:s}" is INVALID\n'.format(name=o.Name, label=o.Label)
                    #FreeCAD.Console.PrintError(msg)
                    #FreeCAD.Console.PrintWarning(chks[0])
                    geometry_error_container.append(BOBError(modelName, o.Name, o.Label, chks[0]))
                    log.write('\t- Geometry check: [    FAIL    ]\n')
                    log.write('\t\t- Effected shape: "{name:s}" "{label:s}"\n'.format(name=o.Name, label=o.Label))
                    #stop
                else:
                    #msg='shape \''+o.Name+'\' \''+ mk_string(o.Label)+'\' is valid\n'
                    msg = 'shape "{name:s}" "{label:s}" is valid\n'.format(name=o.Name, label=o.Label)
                    FreeCAD.Console.PrintMessage(msg)
                    log.write('\t- Geometry check: [    pass    ]\n')
    else:
        log.write('\t- Geometry check: [  skipped   ]\n')
        log.write('\t\t- Geometry check needs FC 0.17+\n')
        raise FreeCADVersionError('0.17', 'Geometry check needs FC 0.17')

    if stop_on_first_error and geometry_error_container.error_encountered:
        raise geometry_error_container

    if save_memory == True:
        saveFCdoc(App, Gui, docu, 'temp', './', False)
        docu = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(docu.Name)

    if geometry_error_container.error_encountered:
        raise geometry_error_container
Exemplo n.º 40
0
    subsystem_grp = doc.addObject("App::DocumentObjectGroup", subsystem)
    subsystem_grp.Label = subsystem
    for step,vv in v.items():
        step_name = get_layer_tail(step)
        step_grp = doc.addObject("App::DocumentObjectGroup", step_name)
        step_grp.Label = step_name
        subsystem_grp.addObject(step_grp)
        for partkind,vvv in vv.items():
            partkind_name = "%s::%s" % (step_name,partkind)
            partkind_grp = doc.addObject("App::DocumentObjectGroup", partkind_name)
            partkind_grp.Label = partkind_name
            step_grp.addObject(partkind_grp)

            filename = get_part_filename(subsystem, step_name, partkind)
            FreeCAD.Console.PrintMessage(filename + "\n")
            preimport_obj_count = len(doc.Objects)
            ImportGui.insert(os.path.join(step_dir, filename), doc.Name)
            # group new objects
            for i in range(preimport_obj_count, len(doc.Objects)):
                obj = doc.Objects[i]
                if obj.TypeId == 'Part::Feature':
                    partkind_grp.addObject(obj)


    FreeCAD.Gui.SendMsgToActiveView("ViewFit")
    if not subsystem == "1.frame-bottom":
        subsystem_grp.ViewObject.Visibility=False

    doc.recompute()

Exemplo n.º 41
0
	def proceed(self):
		temp_file = tempfile.mkstemp(suffix='.step')[1]
		selection = FreeCADGui.Selection.getSelection()
		if not selection:
			QtGui.QMessageBox.critical(None, "GMSHMesh macro", "An object has to be selected to run gmsh!")
			return
		# Export a part in step format
		ImportGui.export(selection, temp_file)
		selection_name = selection[0].Name
		# Mesh temporaly file
		file_format = self.cmb_format.currentText()
		temp_mesh_file = os.path.join(tempfile.tempdir, selection_name + '_Mesh.' + file_format)
		# OPTIONS GMSH:
		clmax = self.sb_max_element_size.text()
		clmin = self.sb_min_element_size.text()
		cmd_line_opt = self.le_cmd_line_opt.text()
		algo = self.cmb_algorithm.currentText()
		mesh_order = self.sb_mesh_order.text()

		if self.cb_optimized.isChecked():
			cmd_optimize = ' -optimize'
		else:
			cmd_optimize = ''

		if self.rb_3D.isChecked():
			dim = ' -3 '
		if self.rb_2D.isChecked():
			dim = ' -2 '
		if self.rb_1D.isChecked():
			dim = ' -1 '
		if self.cb_max_elme_size.isChecked():
			max_size = ' -clmax ' + clmax
		else:
			max_size = ''
		if self.cb_min_elme_size.isChecked():
			min_size = ' -clmin ' + clmin
		else:
			min_size = ''
		if self.cb_mesh_order.isChecked():
			order = ' -order ' + mesh_order
		else:
			order = ''

		options = ' -algo ' + algo + max_size + min_size + cmd_optimize + order + cmd_line_opt
		# RUN GMSH
		command = gmsh_bin + ' ' + temp_file + dim + '-format ' + file_format + ' -o ' + temp_mesh_file  + '' + options
		FreeCAD.Console.PrintMessage("Running: \"{}\"\n".format(command))
		try:
			output = subprocess.check_output([command, '-1'], shell=True, stderr=subprocess.STDOUT,)
			for line in output.split('\n'):
				if "Error" in line:
					FreeCAD.Console.PrintError("{}\n".format(line))
				elif "Warning" in line:
					FreeCAD.Console.PrintWarning("{}\n".format(line))
			#FreeCAD.Console.PrintMessage("Output: \"{}\"\n".format(output))
			if file_format in ('unv', 'med'):
				Fem.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name)
			if file_format == 'stl':
				Mesh.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name)
			if file_format == 'msh':
				out_mesh_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "geometry.msh")
				shutil.move(temp_mesh_file, out_mesh_file)
				FreeCAD.Console.PrintMessage("Output file written to: {}\n".format(out_mesh_file))
			if self.cb_mec_anal.isChecked():
				FMesh = App.activeDocument().ActiveObject
				MechanicalAnalysis.makeMechanicalAnalysis('MechanicalAnalysis')
				FemGui.setActiveAnalysis(App.activeDocument().ActiveObject)
				App.activeDocument().ActiveObject.Member = App.activeDocument().ActiveObject.Member + [FMesh]
			if self.rb_1D.isChecked():
				FMeshG = Gui.ActiveDocument.ActiveObject
				FMeshG.DisplayMode = "Elements & Nodes"
		except:
			FreeCAD.Console.PrintError("Unexpected error in GMSHMesh macro: {} {}\n".format(sys.exc_info()[0], sys.exc_info()[1]))
		finally:
			try: del temp_file
			except: pass
			try: del temp_mesh_file
			except: pass
Exemplo n.º 42
0
def export(variant, overwrite=False, saveFCStd=False, exportDXF=False):
    partPrefix = variant[:-4]
    partPostfix = variant[5:]
    pinCount = int(variant[5:7])

    srcName = srcDir+variant+'.stp'
    if not os.path.isfile(srcName):
        FreeCAD.Console.PrintMessage('missing ' + variant + '.stp\n')
        return

    if not os.path.exists(dstDir):
        os.makedirs(dstDir)

    bodyCutName = 'body-' + partPrefix + '#'

    bodyCut = None
    try:
        tmpl = App.getDocument(tmplName)
    except:
        tmpl = App.openDocument(tmplName+'.FCStd')
    for obj in tmpl.Objects:
        if obj.Label.startswith(bodyCutName):
            bodyCut = obj
            break

    if bodyCut == None:
        FreeCAD.Console.PrintMessage('missing template for ' + partPrefix + '\n')
        return

    FreeCAD.Console.PrintMessage('cehcking  ' + variant + '\n')

    names = [x for x in obj.Label.split('#')]
    pitch = float(names[2])
    dstName = dstDir+names[3]\
            .replace('%e',partPrefix)\
            .replace('%o',partPostfix)\
            .replace('%c','%02d'%pinCount)\
            .replace('%p','%.2f'%pitch)


    if os.path.isfile(dstName+'.stp'):
        if not overwrite:
            FreeCAD.Console.PrintMessage(dstName + ' already exists, skip!\n')
            return

    FreeCAD.Console.PrintMessage('exporting ' + dstName + '\n')

    newDoc = App.newDocument(variant+'_'+str(random.randrange(10000,99999)))
    guiDoc = Gui.getDocument(newDoc.Name)

    bodyCut = newDoc.copyObject(bodyCut,True)
    guiDoc.getObject(bodyCut.Name).Visibility = False;

    ImportGui.insert(srcName,newDoc.Name)

    objs = newDoc.getObjectsByLabel(bodyName)
    if not objs:
        FreeCAD.Console.PrintMessage('missing body for ' + partPrefix + '\n')
        return
    part = objs[0]
    guiDoc.getObject(part.Name).Visibility = False;

    objs = newDoc.getObjectsByLabel(fpName)
    if not objs:
        FreeCAD.Console.PrintMessage('missing footprint for ' + partPrefix + '\n')
        return
    footprint = objs[0]

    placement = bodyCut.Placement
    bodyCut.Placement = App.Placement()

    for obj in bodyCut.Shapes:
        # any better way to id array object?
        if 'ArrayType' in obj.PropertiesList:
            # TODO, we assum interval x sets the pitch, add more check later
            obj.IntervalX.x = pitch
            obj.NumberX = pinCount
            obj.Placement.Base.x -= (pinCount-2)*pitch/2
        else:
            for sobj in obj.Shapes:
                if sobj.TypeId == 'Part::Mirroring':
                    sobj.Source.Placement.Base.x -= (pinCount-2)*pitch/2

    newDoc.recompute()

    colors = []
    objs = []
    shapes = []

    def make_part(obj,isCut):
        names = [x for x in obj.Label.split('#')]
        newObj = newDoc.addObject("Part::Feature", names[0])
        if isCut:
            newObj.Shape = part.Shape.cut(obj.Shape).removeSplitter()
        else:
            newObj.Shape = part.Shape.common(obj.Shape).removeSplitter()
        color = names[1]
        if not color in shaderColors.named_colors:
            FreeCAD.Console.PrintWarning('unknown color : ' + color + '\n')
            color = None
        else:
            newObj.ViewObject.ShapeColor = shaderColors.named_colors[color].getDiffuseFloat()
            if not color in colors:
                colors.append(color)
        newObj.Placement = placement
        shapes.append(newObj)
        objs.append(expVRML.exportObject(freecad_object = newObj, shape_color=color, face_colors=None))

    make_part(bodyCut,True)

    for obj in bodyCut.Shapes:
        make_part(obj,False)

    newDoc.recompute()

    ImportGui.export(shapes,dstName+'.stp')

    if exportDXF:
        shapes = []
        shapes.append(footprint)
        importDXF.export(shapes,dstName+'.dxf')

    scale=1/2.54
    colored_meshes = expVRML.getColoredMesh(Gui, objs , scale)
    expVRML.writeVRMLFile(colored_meshes, dstName+'.wrl', colors)

    if saveFCStd:
        newDoc.saveAs(dstName+'.FCStd')
    App.closeDocument(newDoc.Name)
Exemplo n.º 43
0
# Set the directory variable before running

import FreeCAD
import ImportGui
import FreeCADGui
import os

# directory = "/home/mikael/kicad_ws/osrf_hw/kicad_3dmodels/BGA"
directory = os.getcwd()
print directory
if not os.path.isdir(directory):
    print "ERROR directory " + directory + " doesn't exist"
    exit(1)
for root, subdirs, files in os.walk(directory):
    for filename in files:
        if filename.lower().endswith(".stp") or filename.lower().endswith(".step"):
            file_path = os.path.join(root, filename)
            ImportGui.open(file_path)
            wrlname = file_path[0 : file_path.rfind(file_path[file_path.rfind(".") :])] + ".wrl"
            Gui.export(App.ActiveDocument.findObjects("Part::Feature"), wrlname)
            App.closeDocument(App.ActiveDocument.Name)

exit(1)
Exemplo n.º 44
0
# Set the directory variable before running

import FreeCAD
import ImportGui
import FreeCADGui
import os

#directory = "/home/mikael/kicad_ws/osrf_hw/kicad_3dmodels/BGA"
directory = os.getcwd()
print directory
if not os.path.isdir(directory):
    print "ERROR directory " + directory + " doesn't exist"
    exit(1)
for root, subdirs, files in os.walk(directory):
    for filename in files:
        if filename.lower().endswith('.stp') or filename.lower().endswith(
                '.step'):
            file_path = os.path.join(root, filename)
            ImportGui.open(file_path)
            wrlname = file_path[
                0:file_path.rfind(file_path[file_path.rfind('.'):])] + ".wrl"
            Gui.export(App.ActiveDocument.findObjects("Part::Feature"),
                       wrlname)
            App.closeDocument(App.ActiveDocument.Name)

exit(1)
Exemplo n.º 45
0
def export(variant, fuse=False, overwrite=False, saveFCStd=False, exportDXF=False):
    partPrefix = variant[:-4]
    partPostfix = variant[5:]
    pinCount = int(variant[5:7])

    srcName = srcDir+variant+'.stp'
    if not os.path.isfile(srcName):
        FreeCAD.Console.PrintMessage('missing ' + variant + '.stp\n')
        return

    if not os.path.exists(dstDir):
        os.makedirs(dstDir)

    bodyCutName = 'body-' + partPrefix + '#'

    bodyCut = None
    try:
        tmpl = App.getDocument(libName)
    except:
        tmpl = App.openDocument(tmplDir+libName+'.FCStd')
    for obj in tmpl.Objects:
        if obj.Label.startswith(bodyCutName):
            bodyCut = obj
            break

    if bodyCut == None:
        FreeCAD.Console.PrintMessage('missing template for ' + partPrefix + '\n')
        return

    FreeCAD.Console.PrintMessage('cehcking  ' + variant + '\n')

    names = [x for x in obj.Label.split('#')]
    pitch = float(names[2])
    dstName = dstDir+names[3]\
            .replace('%e',partPrefix)\
            .replace('%o',partPostfix)\
            .replace('%c','%02d'%pinCount)\
            .replace('%p','%.2f'%pitch)

    settings = { 'align':'' }

    if len(names) > 4:
        for i in range(4,len(names)):
            if names[i] == '': continue
            option = [x for x in names[i].split(':')]
            if not option[0] in settings:
                FreeCAD.Console.PrintWarning('unknown setting : ' + option[0] + '\n')
            else:
                settings[option[0]] = option[1]

    if os.path.isfile(dstName+'.stp'):
        if not overwrite:
            FreeCAD.Console.PrintMessage(dstName + ' already exists, skip!\n')
            return

    FreeCAD.Console.PrintMessage('exporting ' + dstName + '\n')

    newDoc = App.newDocument(variant+'_'+str(random.randrange(10000,99999)))
    guiDoc = Gui.getDocument(newDoc.Name)

    bodyCut = newDoc.copyObject(bodyCut,True)
    FreeCAD.Console.PrintMessage(bodyCut.Name +  '\n')
    guiDoc.getObject(bodyCut.Name).Visibility = False;

    ImportGui.insert(srcName,newDoc.Name)

    objs = newDoc.getObjectsByLabel(bodyName)
    if not objs:
        FreeCAD.Console.PrintMessage('missing body for ' + partPrefix + '\n')
        return
    part = objs[0]
    guiDoc.getObject(part.Name).Visibility = False;

    objs = newDoc.getObjectsByLabel(fpName)
    if not objs:
        FreeCAD.Console.PrintMessage('missing footprint for ' + partPrefix + '\n')
        return
    footprint = objs[0]

    # NOTE!!! If we don't use Placement.copy here, we will be getting a surprise
    # from FreeCAD. Even if we reset the bodyCut.Placement below, whenever we change
    # the non-copied placement, bodyCut.Placement will get an update, too! Spooky!!
    # There seems to be some dangling internal reference bug here.
    placement = bodyCut.Placement.copy()
    bodyCut.Placement = App.Placement()

    offset = (pinCount-2)*pitch/2

    if settings['align'] == 'pin':
        placement.Base.x += offset

    footprint.Placement = placement.copy()

    for obj in bodyCut.Shapes:
        # any better way to id array object?
        if 'ArrayType' in obj.PropertiesList:
            # TODO, we assum interval x sets the pitch, add more check later
            obj.IntervalX.x = pitch
            obj.NumberX = pinCount
            obj.Placement.Base.x -= offset
        else:
            for sobj in obj.Shapes:
                if sobj.TypeId == 'Part::Mirroring':
                    sobj.Source.Placement.Base.x -= offset

    newDoc.recompute()

    colors = []
    objs = []
    shapes = []

    def make_part(obj,isCut):
        names = [x for x in obj.Label.split('#')]
        newObj = newDoc.addObject("Part::Feature", names[0])
        if isCut:
            newObj.Shape = part.Shape.cut(obj.Shape).removeSplitter()
        else:
            newObj.Shape = part.Shape.common(obj.Shape).removeSplitter()
        color = names[1]
        if not color in shaderColors.named_colors:
            FreeCAD.Console.PrintWarning('unknown color : ' + color + '\n')
            color = None
        else:
            newObj.ViewObject.ShapeColor = shaderColors.named_colors[color].getDiffuseFloat()
            if not color in colors:
                colors.append(color)
        newObj.Placement = placement.copy()
        shapes.append(newObj)
        objs.append(expVRML.exportObject(freecad_object = newObj, shape_color=color, face_colors=None))

    make_part(bodyCut,True)

    for obj in bodyCut.Shapes:
        make_part(obj,False)

    if fuse:
        newObj = newDoc.addObject("Part::MultiFuse", 'part')
        newObj.Shapes = shapes
        shapes = [newObj]

    newDoc.recompute()

    ImportGui.export(shapes,dstName+'.stp')

    if exportDXF:
        shapes = []
        shapes.append(footprint)
        importDXF.export(shapes,dstName+'.dxf')

    scale=1/2.54
    colored_meshes = expVRML.getColoredMesh(Gui, objs , scale)
    expVRML.writeVRMLFile(colored_meshes, dstName+'.wrl', colors)

    if saveFCStd:
        newDoc.saveAs(dstName+'.FCStd')
    App.closeDocument(newDoc.Name)
Exemplo n.º 46
0
def runGeometryCheck(App,
                     Gui,
                     step_path,
                     log,
                     modelName,
                     save_memory=True,
                     stop_on_first_error=True):

    FC_majorV = int(FreeCAD.Version()[0])
    FC_minorV = int(FreeCAD.Version()[1])
    try:
        FC_subV = int(FreeCAD.Version()[2].split(" ")[0])
    except Exception:
        FC_subV = 0

    if FC_majorV == 0 and FC_minorV == 16 and FC_subV < 6712:
        raise FreeCADVersionError(
            '0.16-6712', 'old 0.16 releases have a bug in the step exporter.')

    geometry_error_container = GeometryError()

    ImportGui.open(step_path)
    docu = FreeCAD.ActiveDocument
    docu.Label = modelName
    log.write('\n## Checking {:s}\n'.format(modelName))

    if checkUnion(docu):
        FreeCAD.Console.PrintMessage('step file is correctly Unioned\n')
        log.write('\t- Union check:    [    pass    ]\n')
    else:
        #FreeCAD.Console.PrintError('step file is NOT Unioned\n')
        log.write('\t- Union check:    [    FAIL    ]\n')
        geometry_error_container.append(NotUnionedError(modelName))
        #stop
    if FC_majorV == 0 and FC_minorV >= 17:
        if docu.Objects == 0:
            FreeCAD.Console.PrintError(
                'Step import seems to fail. No objects to check\n')
        for o in docu.Objects:
            if hasattr(o, 'Shape'):
                o.Shape.fixTolerance(1e-4)
                chks = checkBOP(o.Shape)
                #print 'chks ',chks
                if chks != True:
                    #msg='shape \''+o.Name+'\' \''+ mk_string(o.Label)+'\' is INVALID!\n'
                    msg = 'shape "{name:s}" "{label:s}" is INVALID\n'.format(
                        name=o.Name, label=o.Label)
                    #FreeCAD.Console.PrintError(msg)
                    #FreeCAD.Console.PrintWarning(chks[0])
                    geometry_error_container.append(
                        BOBError(modelName, o.Name, o.Label, chks[0]))
                    log.write('\t- Geometry check: [    FAIL    ]\n')
                    log.write('\t\t- Effected shape: "{name:s}" "{label:s}"\n'.
                              format(name=o.Name, label=o.Label))
                    #stop
                else:
                    #msg='shape \''+o.Name+'\' \''+ mk_string(o.Label)+'\' is valid\n'
                    msg = 'shape "{name:s}" "{label:s}" is valid\n'.format(
                        name=o.Name, label=o.Label)
                    FreeCAD.Console.PrintMessage(msg)
                    log.write('\t- Geometry check: [    pass    ]\n')
    else:
        log.write('\t- Geometry check: [  skipped   ]\n')
        log.write('\t\t- Geometry check needs FC 0.17+\n')
        raise FreeCADVersionError('0.17', 'Geometry check needs FC 0.17')

    if stop_on_first_error and geometry_error_container.error_encountered:
        raise geometry_error_container

    if save_memory == True:
        saveFCdoc(App, Gui, docu, 'temp', './', False)
        docu = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(docu.Name)

    if geometry_error_container.error_encountered:
        raise geometry_error_container
Exemplo n.º 47
0
exp_objects = []
for obj in FreeCAD.ActiveDocument.Objects:
  # select all but indivudial Spheres and Sketch
  if (obj.Name.find("Pin") == -1) and (obj.Name.find("Sketch") == -1):
    Gui.Selection.addSelection(obj)
    exp_objects.append(obj)
  else:
    FreeCAD.ActiveDocument.removeObject(obj.Name)

App.activeDocument().addObject("Part::MultiFuse","Fusion2")
App.activeDocument().Fusion2.Shapes = exp_objects
App.ActiveDocument.recompute()
for obj in exp_objects:
    FreeCAD.ActiveDocument.removeObject(obj.Name) 
exp_objects= []

exp_objects.append(FreeCAD.ActiveDocument.getObject("Fusion2"))
ImportGui.export(exp_objects,os.path.join(directory, name + '.step'))
del exp_objects
# Scale to mil before export to VRML for KiCAD use
Draft.scale(FreeCAD.ActiveDocument.ActiveObject,
    FreeCAD.Vector(MMTOMIL, MMTOMIL, MMTOMIL))
FreeCAD.ActiveDocument.removeObject("Fusion2") 

### Export as a VRML model
exp_objects = []
exp_objects.append(FreeCAD.ActiveDocument.getObject("Scale"))
FreeCADGui.export(exp_objects,os.path.join(directory, name + '.wrl'))
del exp_objects
exit(1)
Exemplo n.º 48
0
def convertModel(group, docName):
    global _fileName
    acis = getReader()
    bodies = _resolveNodes(acis)
    stepfile = export(acis.name, acis.header, bodies)
    ImportGui.insert(stepfile, docName)
    App.ActiveDocument.recompute()
    sk2.addConstraint(Sketcher.Constraint("DistanceY", 4, 2, 0, 2, 1.750603))
    sk2.setDatum(18, App.Units.Quantity(str(data[10]) + " mm"))
    App.ActiveDocument.recompute()
    sk2.addConstraint(Sketcher.Constraint("Coincident", 6, 3, -1, 1))
    App.ActiveDocument.recompute()

    poc = App.activeDocument().addObject("PartDesign::Pocket", "Pocket")
    poc.Sketch = sk2
    poc.Length = data[10]
    poc.Label = name

    FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Pocket").LineColor = (0.0, 0.0, 0.0)
    FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Pocket").ShapeColor = (0.31, 0.73, 0.76)

    Gui.getDocument(App.ActiveDocument.Name).getObject("Sketch").Visibility = False
    Gui.getDocument(App.ActiveDocument.Name).getObject("Sketch001").Visibility = False
    Gui.getDocument(App.ActiveDocument.Name).getObject("Revolve").Visibility = False
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")

    App.ActiveDocument.saveAs(directory + name + ".FCStd")
    __objs__ = []
    __objs__.append(FreeCAD.getDocument(App.ActiveDocument.Name).getObject("Pocket"))
    ImportGui.export(__objs__, directory + name + ".step")
    Mesh.export(__objs__, directory + name + ".stl")
    del __objs__
    App.closeDocument(App.ActiveDocument.Name)

print "End"
Exemplo n.º 50
0
import sys
sys.path.append("C:\\Program Files\\FreeCAD 0.19\\bin")

import FreeCAD
import FreeCADGui
FreeCADGui.setupWithoutGUI()
import Part
import ImportGui

print (FreeCAD.listDocuments())

test = FreeCAD.newDocument("testDoc")

ImportGui.insert("C:\\temp\\JMA(KAE-10D).STEP",test.Name)
ImportGui.insert("C:\\temp\\stift.STEP",test.Name)

doc = FreeCAD.ActiveDocument
objs = FreeCAD.ActiveDocument.Objects

print("objects before cutting")
print("----------------------")
for obj in objs:
    a = obj.Name
    b = obj.Label
    try:
        c = obj.LabelText
        print(a +" "+ (b) +" "+ (c) + "\n")
    except:
        print((a) +" "+ (b) + "\n")
print("----------------------")
                        HDLR_stepfile_w = open(PATH_toStepFiles + FNME_stepfile, 'w') # open
                    except:
                        print "broken_3"
                    else:
                        # overwrite with new preamble
                        for line in LIST_PMBL:
                            HDLR_stepfile_w.write(line + "\n")
                        # add old data section
                        for line in PMBL_stepfile[(DICT_positions["A"]-1):]:
                            HDLR_stepfile_w.write(line.strip() + "\n")
                        HDLR_stepfile_w.close()

                    # load STEP model, manipulate and save as VRML
                    FreeCAD.newDocument("Unnamed")
                    FreeCAD.setActiveDocument("Unnamed")
                    ImportGui.insert(PATH_toStepFiles + FNME_stepfile,"Unnamed")
                    FNME_vrmlfile = FNME_stepfile[:-4] + ".wrl"
                    # change display mode and scale down
                    for part in FreeCAD.ActiveDocument.Objects:
                        part.ViewObject.DisplayMode = 1 #Shaded
                        Draft.scale(part,delta=App.Vector(0.3937,0.3937,0.3937),center=App.Vector(0,0,0),legacy=True)
                    if FLAG_makeTransparent: # if transparency is needed
                        
#                        from PySide import QtGui
#                        QtGui.QInputDialog.getText(None, "Get text", "Input:")[0]
                        pass
                    __objs__=[] # select all parts (again)
                    for part in FreeCAD.ActiveDocument.Objects:                    
                        __objs__.append(part)
                    FreeCADGui.export(__objs__,(PATH_toVrmlFiles + FNME_vrmlfile))
                    del __objs__
    myEx=App.ActiveDocument.addObject("Part::Extrusion","Extrude")
    myEx.Base = sk1
    myEx.Dir = (0,0,50)
    myEx.Solid = (True)
    myEx.TaperAngle = (0)
    myEx.Label = data[0]

    FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Extrude").LineColor = (0.0,0.0,0.0)
    FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Extrude").ShapeColor = (0.96,0.93,0.76)

    Gui.getDocument(App.ActiveDocument.Name).getObject("Sketch").Visibility=False
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")

    App.ActiveDocument.saveAs(directory+data[0]+'.FCStd')
    __objs__=[]
    __objs__.append(FreeCAD.getDocument(App.ActiveDocument.Name).getObject("Extrude"))
    ImportGui.export(__objs__,directory+data[0]+'.step')
    Mesh.export(__objs__,directory+data[0]+'.stl')
    del __objs__
    App.closeDocument(App.ActiveDocument.Name)

print 'End'

 

 
 

Exemplo n.º 53
0
def CreateTantalumCapacitor(L, W, H, F, S, B, X, P, R, T, A, G, E,
                            Tf, maDeg, Lamb, Hamb,
                            newModelName,
                            newModelPathNameExt,
                            newStepPathNameExt,
                            bodyName,
                            pinsName,
                            pin1MarkName):
    
    # Constant pi
    pi = 3.141592654

    # Mold angle (in radians)
    ma = math.radians(maDeg)

    # Length of body after we subtract off 2 termination sheet metal thicknesses
    Lb = (L - (2*T))

    # Pivot point height (not specified in datasheet--make something up)
    ppH = (H * 0.45)

    # Create new document
    App.newDocument(newModelName)
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    
    # Create box to model tantalum capacitor body
    App.ActiveDocument.addObject("Part::Box","Box")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")

    # Set body size
    FreeCAD.getDocument(newModelName).getObject("Box").Length = Lb
    FreeCAD.getDocument(newModelName).getObject("Box").Width = W
    FreeCAD.getDocument(newModelName).getObject("Box").Height = H
    FreeCAD.getDocument(newModelName).getObject("Box").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,0,1))

    # Center the body at (0,0)
    FreeCAD.getDocument(newModelName).getObject("Box").Placement = App.Placement(App.Vector(-1*(Lb/2),-1*(W/2),0),App.Rotation(0,0,0,1))
    
    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box001")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box001").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box001").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box001").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box001").Placement = App.Placement(App.Vector(-1*(Lb/2),(W/2),ppH),App.Rotation(math.sin(ma/2),0,0,math.cos(ma/2)))

    # Perform 1st cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut")
    App.activeDocument().Cut.Base = App.activeDocument().Box
    App.activeDocument().Cut.Tool = App.activeDocument().Box001
    Gui.activeDocument().hide('Box')
    Gui.activeDocument().hide('Box001')
    App.ActiveDocument.recompute()

    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box002")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box002").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box002").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box002").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box002").Placement = App.Placement(App.Vector(-1*(Lb/2),(W/2),ppH),App.Rotation(math.sin(((3*pi)/4)-(ma/2)),0,0,math.cos(((3*pi)/4)-(ma/2))))

    # Perform 2nd cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut001")
    App.activeDocument().Cut001.Base = App.activeDocument().Cut
    App.activeDocument().Cut001.Tool = App.activeDocument().Box002
    Gui.activeDocument().hide('Cut')
    Gui.activeDocument().hide('Box002')
    App.ActiveDocument.recompute()

    ###################################################################
    # Rotate body to 180 degrees and get ready for next 2 cuts
    FreeCAD.getDocument(newModelName).getObject("Cut001").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,1,0))
    ###################################################################

    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box003")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box003").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box003").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box003").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box003").Placement = App.Placement(App.Vector(-1*(Lb/2),(W/2),ppH),App.Rotation(math.sin(ma/2),0,0,math.cos(ma/2)))

    ## Perform 3rd cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut002")
    App.activeDocument().Cut002.Base = App.activeDocument().Cut001
    App.activeDocument().Cut002.Tool = App.activeDocument().Box003
    Gui.activeDocument().hide('Cut001')
    Gui.activeDocument().hide('Box003')
    App.ActiveDocument.recompute()

    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box004")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box004").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box004").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box004").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box004").Placement = App.Placement(App.Vector(-1*(Lb/2),(W/2),ppH),App.Rotation(math.sin(((3*pi)/4)-(ma/2)),0,0,math.cos(((3*pi)/4)-(ma/2))))

    # Perform 4th cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut003")
    App.activeDocument().Cut003.Base = App.activeDocument().Cut002
    App.activeDocument().Cut003.Tool = App.activeDocument().Box004
    Gui.activeDocument().hide('Cut002')
    Gui.activeDocument().hide('Box004')
    App.ActiveDocument.recompute()

    ###################################################################
    # Rotate body to 90 degrees and get ready for next 2 cuts
    FreeCAD.getDocument(newModelName).getObject("Cut003").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,0.707107,0.707107))
    ###################################################################

    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box005")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box005").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box005").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box005").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box005").Placement = App.Placement(App.Vector(-1*(W/2),(Lb/2),ppH),App.Rotation(math.sin(ma/2),0,0,math.cos(ma/2)))

    ## Perform 5th cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut004")
    App.activeDocument().Cut004.Base = App.activeDocument().Cut003
    App.activeDocument().Cut004.Tool = App.activeDocument().Box005
    Gui.activeDocument().hide('Cut003')
    Gui.activeDocument().hide('Box005')
    App.ActiveDocument.recompute()

    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box006")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box006").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box006").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box006").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box006").Placement = App.Placement(App.Vector(-1*(W/2),(Lb/2),ppH),App.Rotation(math.sin(((3*pi)/4)-(ma/2)),0,0,math.cos(((3*pi)/4)-(ma/2))))

    # Perform 6th cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut005")
    App.activeDocument().Cut005.Base = App.activeDocument().Cut004
    App.activeDocument().Cut005.Tool = App.activeDocument().Box006
    Gui.activeDocument().hide('Cut004')
    Gui.activeDocument().hide('Box006')
    App.ActiveDocument.recompute()


    ###################################################################
    # Rotate body to 270 degrees and get ready for next 2 cuts
    FreeCAD.getDocument(newModelName).getObject("Cut005").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,1,0))
    ###################################################################

    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box007")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box007").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box007").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box007").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box007").Placement = App.Placement(App.Vector(-1*(W/2),(Lb/2),ppH),App.Rotation(math.sin(ma/2),0,0,math.cos(ma/2)))

    ## Perform 7th cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut006")
    App.activeDocument().Cut006.Base = App.activeDocument().Cut005
    App.activeDocument().Cut006.Tool = App.activeDocument().Box007
    Gui.activeDocument().hide('Cut005')
    Gui.activeDocument().hide('Box007')
    App.ActiveDocument.recompute()

    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box008")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box008").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box008").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box008").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box008").Placement = App.Placement(App.Vector(-1*(W/2),(Lb/2),ppH),App.Rotation(math.sin(((3*pi)/4)-(ma/2)),0,0,math.cos(((3*pi)/4)-(ma/2))))

    # Perform 8th cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut007")
    App.activeDocument().Cut007.Base = App.activeDocument().Cut006
    App.activeDocument().Cut007.Tool = App.activeDocument().Box008
    Gui.activeDocument().hide('Cut006')
    Gui.activeDocument().hide('Box008')
    App.ActiveDocument.recompute()


    ###################################################################
    # Prepare to make the bevel cut at the anode end.
    ###################################################################

    # The anode bevel needs to start at the cut-away body, not at the rectangular prism prior to all the cuts.
    # x === offset due to 8 degree mold angle
    # tan (8deg) = x / (H-ppH)
    # x = (H-pph) * tan(8deg)
    x = (H-ppH) * math.tan(ma)

    # Create box to use to cut away at body
    App.ActiveDocument.addObject("Part::Box","Box009")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box009").Length = L
    FreeCAD.getDocument(newModelName).getObject("Box009").Width = L
    FreeCAD.getDocument(newModelName).getObject("Box009").Height = L
    FreeCAD.getDocument(newModelName).getObject("Box009").Placement = App.Placement(App.Vector(-1*(W/2),((Lb/2)-x-B),H),App.Rotation(-0.382683,0,0,0.92388))

    # Perform 9th cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut008")
    App.activeDocument().Cut008.Base = App.activeDocument().Cut007
    App.activeDocument().Cut008.Tool = App.activeDocument().Box009
    Gui.activeDocument().hide('Cut007')
    Gui.activeDocument().hide('Box009')
    App.ActiveDocument.recompute()


    ###################################################################
    # Rotate cap body into final position and prepare to add terminations.
    ###################################################################

    # Rotate into final orientation
    FreeCAD.getDocument(newModelName).getObject("Cut008").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,0.707107,0.707107))

    # Create box to use to cut away at underside of body
    App.ActiveDocument.addObject("Part::Box","Box010")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box010").Length = Lb
    FreeCAD.getDocument(newModelName).getObject("Box010").Width = W
    FreeCAD.getDocument(newModelName).getObject("Box010").Height = T
    FreeCAD.getDocument(newModelName).getObject("Box010").Placement = App.Placement(App.Vector(-1*(Lb/2),-1*(W/2),(-1*T)),App.Rotation(0,0,0,1))

    # Create box to use to cut a hole in that box to accommodate the G dimension
    App.ActiveDocument.addObject("Part::Box","Box011")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box011").Length = G
    FreeCAD.getDocument(newModelName).getObject("Box011").Width = E
    FreeCAD.getDocument(newModelName).getObject("Box011").Height = T
    FreeCAD.getDocument(newModelName).getObject("Box011").Placement = App.Placement(App.Vector(-1*(G/2),-1*(E/2),(-1*T)),App.Rotation(0,0,0,1))

    # Make cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut009")
    App.activeDocument().Cut009.Base = App.activeDocument().Box010
    App.activeDocument().Cut009.Tool = App.activeDocument().Box011
    Gui.activeDocument().hide('Box010')
    Gui.activeDocument().hide('Box011')
    App.ActiveDocument.recompute()

    # Now that we have a template to use for all the material we need to remove underneath the cap, proceed to do so.

    # Position template coincident with cap
    FreeCAD.getDocument(newModelName).getObject("Cut009").Placement = App.Placement(App.Vector(0,0,T),App.Rotation(0,0,0,1))

    # Make cut
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::Cut","Cut011")
    App.activeDocument().Cut011.Base = App.activeDocument().Cut008
    App.activeDocument().Cut011.Tool = App.activeDocument().Cut009
    Gui.activeDocument().hide('Cut008')
    Gui.activeDocument().hide('Cut009')
    App.ActiveDocument.recompute()

    # Copy this object and call the copy "Body"
    newTermShape = FreeCAD.getDocument(newModelName).getObject("Cut011").Shape.copy()
    newTermObj = App.activeDocument().addObject("Part::Feature",bodyName)
    newTermObj.Shape = newTermShape


    ###################################################################
    # Add terminations
    ###################################################################

    # Create box to be left side (anode) termination
    App.ActiveDocument.addObject("Part::Box","Box012")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box012").Length = S
    FreeCAD.getDocument(newModelName).getObject("Box012").Width = F
    FreeCAD.getDocument(newModelName).getObject("Box012").Height = T
    FreeCAD.getDocument(newModelName).getObject("Box012").Placement = App.Placement(App.Vector(-1*(L/2),-1*(F/2),0),App.Rotation(0,0,0,1))

    # Create box to be left side (anode) termination
    App.ActiveDocument.addObject("Part::Box","Box013")
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject("Box013").Length = T
    FreeCAD.getDocument(newModelName).getObject("Box013").Width = F
    FreeCAD.getDocument(newModelName).getObject("Box013").Height = (ppH-T)
    FreeCAD.getDocument(newModelName).getObject("Box013").Placement = App.Placement(App.Vector(-1*(L/2),-1*(F/2),T),App.Rotation(0,0,0,1))

    # Fuse the two parts of termination together
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.activeDocument().addObject("Part::MultiFuse","Fusion")
    App.activeDocument().Fusion.Shapes = [App.activeDocument().Box013,App.activeDocument().Box012,App.activeDocument().Box012]
    Gui.activeDocument().Box013.Visibility=False
    Gui.activeDocument().Box012.Visibility=False
    Gui.activeDocument().Box012.Visibility=False
    App.ActiveDocument.recompute()

    # Fillet the sharp edges of the termination sheet metal
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    Gui.activateWorkbench("PartDesignWorkbench")
    App.activeDocument().addObject("PartDesign::Fillet","Fillet")
    App.activeDocument().Fillet.Base = (App.ActiveDocument.Fusion,["Edge1","Edge14"])
    Gui.activeDocument().hide("Fusion")
    Gui.activeDocument().Fusion.Visibility=False
    Gui.activeDocument().setEdit('Fillet')
    App.ActiveDocument.Fillet.Radius = Tf
    App.ActiveDocument.recompute()
    Gui.activeDocument().resetEdit()

    # Copy the termination to cathode
    newTermShape = FreeCAD.getDocument(newModelName).getObject("Fillet").Shape.copy()
    newTermObj = App.activeDocument().addObject("Part::Feature","Pin2")
    newTermObj.Shape = newTermShape
    FreeCAD.getDocument(newModelName).getObject("Pin2").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,1,0))


    ###################################################################
    # Cut a notch in anode termination
    ###################################################################

    # If P parameter is 0, then no notch to cut
    if (P == 0) :
        
        # Copy fillet object and call the copy "Pin1"
        newTermShape = FreeCAD.getDocument(newModelName).getObject("Fillet").Shape.copy()
        newTermObj = App.activeDocument().addObject("Part::Feature","Pin1")
        newTermObj.Shape = newTermShape

    else:
    
        # Create box to use to cut away at anode termination
        App.ActiveDocument.addObject("Part::Box","Box014")
        App.ActiveDocument.recompute()
        Gui.SendMsgToActiveView("ViewFit")
        FreeCAD.getDocument(newModelName).getObject("Box014").Length = T
        FreeCAD.getDocument(newModelName).getObject("Box014").Width = R
        FreeCAD.getDocument(newModelName).getObject("Box014").Height = H
        FreeCAD.getDocument(newModelName).getObject("Box014").Placement = App.Placement(App.Vector(-1*(L/2),-1*(R/2),P),App.Rotation(0,0,0,1))

        # Perform cut
        App.ActiveDocument=None
        Gui.ActiveDocument=None
        App.setActiveDocument(newModelName)
        App.ActiveDocument=App.getDocument(newModelName)
        Gui.ActiveDocument=Gui.getDocument(newModelName)
        App.activeDocument().addObject("Part::Cut","Cut010")
        App.activeDocument().Cut010.Base = App.activeDocument().Fillet
        App.activeDocument().Cut010.Tool = App.activeDocument().Box014
        Gui.activeDocument().hide('Fillet')
        Gui.activeDocument().hide('Box014')
        App.ActiveDocument.recompute()

        # Copy this object and call the copy "Pin1"
        newTermShape = FreeCAD.getDocument(newModelName).getObject("Cut010").Shape.copy()
        newTermObj = App.activeDocument().addObject("Part::Feature","Pin1")
        newTermObj.Shape = newTermShape


    ###################################################################
    # Fuse the pins together to minimize the number of objects in the final assembly
    ###################################################################

    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    Gui.activateWorkbench("PartWorkbench")
    App.activeDocument().addObject("Part::MultiFuse","Fusion001")
    App.activeDocument().Fusion001.Shapes = [App.activeDocument().Pin1,App.activeDocument().Pin2]
    App.ActiveDocument.recompute()

    # Copy this object and call the copy "Pins"
    newTermShape = FreeCAD.getDocument(newModelName).getObject("Fusion001").Shape.copy()
    newTermObj = App.activeDocument().addObject("Part::Feature",pinsName)
    newTermObj.Shape = newTermShape


    ###################################################################
    # Add anode marker bar
    ###################################################################

    # Create box to be anode marker bar
    App.ActiveDocument.addObject("Part::Box",pin1MarkName)
    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Length = Lamb
    FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Width = W-(2*x)
    FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Height = Hamb
    FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Placement = App.Placement(App.Vector((-1*(Lb/2))+x+B,((-1*(W/2))+x),H),App.Rotation(0,0,0,1))



    ###################################################################
    # Wrap things up
    ###################################################################

    # Kill off various no-longer-needed objects
    App.getDocument(newModelName).removeObject("Pin1")
    App.getDocument(newModelName).removeObject("Pin2")
    App.getDocument(newModelName).removeObject("Cut")
    App.getDocument(newModelName).removeObject("Cut001")
    App.getDocument(newModelName).removeObject("Cut002")
    App.getDocument(newModelName).removeObject("Cut003")
    App.getDocument(newModelName).removeObject("Cut004")
    App.getDocument(newModelName).removeObject("Cut005")
    App.getDocument(newModelName).removeObject("Cut006")
    App.getDocument(newModelName).removeObject("Cut007")
    App.getDocument(newModelName).removeObject("Cut008")
    App.getDocument(newModelName).removeObject("Cut009")
    App.getDocument(newModelName).removeObject("Cut011")
    App.getDocument(newModelName).removeObject("Fusion")
    App.getDocument(newModelName).removeObject("Fusion001")
    App.getDocument(newModelName).removeObject("Box")
    App.getDocument(newModelName).removeObject("Box001")
    App.getDocument(newModelName).removeObject("Box002")
    App.getDocument(newModelName).removeObject("Box003")
    App.getDocument(newModelName).removeObject("Box004")
    App.getDocument(newModelName).removeObject("Box005")
    App.getDocument(newModelName).removeObject("Box006")
    App.getDocument(newModelName).removeObject("Box007")
    App.getDocument(newModelName).removeObject("Box008")
    App.getDocument(newModelName).removeObject("Box009")
    App.getDocument(newModelName).removeObject("Box010")
    App.getDocument(newModelName).removeObject("Box011")
    App.getDocument(newModelName).removeObject("Box012")
    App.getDocument(newModelName).removeObject("Box013")
    App.getDocument(newModelName).removeObject("Fillet")

    # If P parameter wasn't 0, clean up objects that were created
    if (P != 0) :

        App.getDocument(newModelName).removeObject("Box014")
        App.getDocument(newModelName).removeObject("Cut010")
        

    # Set view and zoom in
    Gui.activeDocument().activeView().viewFront()
    Gui.SendMsgToActiveView("ViewFit")
    #Gui.activateWorkbench("DraftWorkbench")

    # Color body yellow
    FreeCADGui.getDocument(newModelName).getObject(bodyName).ShapeColor = (0.89,0.96,0.33)

    # Color pins bright tin
    FreeCADGui.getDocument(newModelName).getObject(pinsName).ShapeColor = (0.80,0.80,0.75)

    # Color anode marker rust orange
    FreeCADGui.getDocument(newModelName).getObject(pin1MarkName).ShapeColor = (0.67,0.42,0.22)

    # Save to disk in native format
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.getDocument(newModelName).FileName = newModelPathNameExt
    App.getDocument(newModelName).Label = newModelName
    Gui.SendMsgToActiveView("Save")
    App.getDocument(newModelName).save()

    # Export to STEP
    App.ActiveDocument=None
    Gui.ActiveDocument=None
    App.setActiveDocument(newModelName)
    App.ActiveDocument=App.getDocument(newModelName)
    Gui.ActiveDocument=Gui.getDocument(newModelName)
    App.getDocument(newModelName).save()
    __objs__=[]
    __objs__.append(FreeCAD.getDocument(newModelName).getObject(bodyName))
    __objs__.append(FreeCAD.getDocument(newModelName).getObject(pinsName))
    __objs__.append(FreeCAD.getDocument(newModelName).getObject(pin1MarkName))
    import ImportGui
    ImportGui.export(__objs__,newStepPathNameExt)
    del __objs__

##    # Close all documents
###    App.closeDocument(newModelName)
###    App.setActiveDocument("")
###    App.ActiveDocument=None
###    Gui.ActiveDocument=None

    return 0