Пример #1
0
        /// <summary>
        /// Adds a component to the Component Property Dictionary.
        /// </summary>
        /// <param name="ComponentID"></param>
        /// <param name="Component"></param>
        public static void AddComponents(string ComponentID, ComponentOccurrence Component)
        {
            switch (Component.DefinitionDocumentType)
            {
            case DocumentTypeEnum.kPartDocumentObject:
                CompPropertyDictionary.Add(Component.Name, ComponentID);
                break;

            case DocumentTypeEnum.kAssemblyDocumentObject:
                AssemblyComponentDefinition AsmDef = (AssemblyComponentDefinition)Component.Definition;
                List <string> AssemblyPartList     = new List <string>();
                foreach (ComponentOccurrence Comp in AsmDef.Occurrences.AllLeafOccurrences)
                {
                    try
                    {
                        AssemblyPartList.Add(Comp.Name);
                        CompPropertyDictionary.Add(Comp.Name, ComponentID);
                    }
                    catch (ArgumentException) { }
                }
                try
                {
                    AssemblyDictionary.Add(Component.Name, AssemblyPartList);
                }
                catch (ArgumentException)
                {
                    AssemblyDictionary.Remove(Component.Name);
                    AssemblyDictionary.Add(Component.Name, AssemblyPartList);
                }
                break;

            default:
                throw new ArgumentException("ERROR: Component not an assembly or part", "Component");
            }
        }
Пример #2
0
    public void Assembly()
    {
        Inventor.Application InventorApplication = (Inventor.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Inventor.Application");
        AssemblyDocument     assemblyDoc         = InventorApplication.Documents.Add(DocumentTypeEnum.kAssemblyDocumentObject, "", true) as AssemblyDocument;

        assDefinition = assemblyDoc.ComponentDefinition;
        Inventor.Matrix matrix = InventorApplication.TransientGeometry.CreateMatrix();
        matrix.SetTranslation(InventorApplication.TransientGeometry.CreateVector(0, 0, 0));
        string[] pathName = new string[10];
        pathName[0] = @"C:\BearingDetails\Внешнее кольцо подшипника.ipt";
        pathName[1] = @"C:\BearingDetails\Внутреннее кольцо подшипника.ipt";
        pathName[2] = @"C:\BearingDetails\Первый ряд шариков.ipt";
        pathName[3] = @"C:\BearingDetails\Второй ряд шариков.ipt";
        pathName[4] = @"C:\BearingDetails\Сепаратор1.ipt";
        pathName[5] = @"C:\BearingDetails\Сепаратор2.ipt";
        for (int i = 0; i < 6; i++)
        {
            assDefinition.Occurrences.Add(pathName[i], matrix);
        }
        Rotate();
        for (int i = 1; i < 4; i++)
        {
            Tangent(i, 2, 3, 7);
        }
        Tangent(1, 5, 3, 1);
        Tangent(3, 5, 3, 5);
        Tangent(5, 5, 3, 9);
        //Tangent(1, 6, 4, 1);
        //Tangent(3, 6, 4, 5);
        //Tangent(5, 6, 4, 9);
        //for (int i = 2; i < 5; i++)
        //    Tangent(i, 2, 4, 1);
        assemblyDoc.SaveAs(@"C:\BearingDetails\Сборка_подшипника.iam", false);
    }
Пример #3
0
 public Sticker(Inventor.Document pDoc, Inventor.Application m_InvApp)
 {
     InitializeComponent();
     invApp = m_InvApp;
     m_TG   = invApp.TransientGeometry;
     if (pDoc.DocumentType == DocumentTypeEnum.kPartDocumentObject)
     {
         m_Doc = (PartDocument)pDoc;
     }
     if (pDoc.DocumentType == DocumentTypeEnum.kAssemblyDocumentObject)
     {
         m_Asm   = (AssemblyDocument)pDoc;
         compDef = m_Asm.ComponentDefinition;
         box     = compDef.RangeBox;
     }
     valXML  = new List <string>();
     attrXML = new List <string>();
     if (System.IO.File.Exists(@"C:\ProgramData\Autodesk\Inventor Addins\Stickers.xml"))
     {
         tbl = new InvDoc.XML(@"C:\ProgramData\Autodesk\Inventor Addins\Stickers.xml");
         tbl.ReadXML("Sticker", ref valXML, ref attrXML);
         if (attrXML.Count != 0)
         {
             for (int i = 0; i < attrXML.Count; i++)
             {
                 if (attrXML[i].StartsWith("Name="))
                 {
                     string XMLVal = tbl.substring(attrXML[i], "Name=");
                     this.comboBox1.Items.Add(XMLVal);
                 }
             }
         }
     }
 }
Пример #4
0
        public double[] FindOrigin(ComponentOccurrence oCompOccur)
        {
            UnitsOfMeasure oUOM = _invApp.ActiveDocument.UnitsOfMeasure;
            AssemblyComponentDefinition oCompDef = (AssemblyComponentDefinition)oCompOccur.Definition;
            object oWorkPointProxy;

            double[]  c   = new double[3];
            WorkPoint oWP = oCompDef.WorkPoints[1];

            oCompOccur.CreateGeometryProxy(oWP, out oWorkPointProxy);

            c[0] = ((WorkPointProxy)oWorkPointProxy).Point.X;
            c[1] = ((WorkPointProxy)oWorkPointProxy).Point.Y;
            c[2] = ((WorkPointProxy)oWorkPointProxy).Point.Z;

            for (int k = 0; k < 3; k++)
            {
                c[k] = oUOM.ConvertUnits(c[k], "cm", "m");
            }

            string AbsolutePosition, name;

            name = FormatName(oCompOccur.Name);

            return(c);
        }
Пример #5
0
 public ParameterList(Inventor.Application currentApp)
 {
     invApp             = currentApp;
     assemblyDoc        = (AssemblyDocument)invApp.ActiveDocument;
     currentAssembly    = assemblyDoc.ComponentDefinition;
     assemblyParameters = currentAssembly.Parameters.UserParameters;
 }
Пример #6
0
        private InvApplication(InvApplication invApplication)
        {
            InternalApplication = invApplication.InternalApplication;

            //get a reference to the active application obtained in addin startup
            Inventor.Application invApp = InternalApplication;


            AssemblyDocument assDoc = (AssemblyDocument)invApp.ActiveDocument;

            Inventor.Point transPoint = invApp.TransientGeometry.CreatePoint(0, 0, 0);

            WorkPoint wp = assDoc.ComponentDefinition.WorkPoints.AddFixed(transPoint, false);

            //get the active document
            Document activeDoc = invApp.ActiveDocument;

            //cast to the right type
            AssemblyDocument assemblyDocument = (AssemblyDocument)activeDoc;

            //get the ComponentDefinition
            AssemblyComponentDefinition assCompDef = (AssemblyComponentDefinition)assemblyDocument.ComponentDefinition;

            //get the WorkPoints collection
            WorkPoints workPoints = assCompDef.WorkPoints;

            //create an Inventor.Point transient geometry object
            Inventor.Point transientPoint = invApp.TransientGeometry.CreatePoint(0, 0, 0);

            //add WorkPoint
            WorkPoint workPoint = workPoints.AddFixed(transientPoint, false);
        }
Пример #7
0
        public void BomAccess()
        {
            AssemblyDocument            oDoc = (AssemblyDocument)_InvApplication.ActiveDocument;
            AssemblyComponentDefinition oDef = oDoc.ComponentDefinition;

            BOM oBOM = default(BOM);

            oBOM = oDef.BOM;

            oBOM.StructuredViewEnabled = true;

            BOMView oBomView = oBOM.BOMViews["Structured"];

            int rowIdx = 0;

            for (rowIdx = 1; rowIdx <= oBomView.BOMRows.Count; rowIdx++)
            {
                BOMRow oRow = oBomView.BOMRows[rowIdx];

                Debug.Print("ItemNumber: " + oRow.ItemNumber + " TotalQuantity = " + oRow.TotalQuantity);

                ComponentDefinition oCompDef = oRow.ComponentDefinitions[1];

                PropertySet oDesignPropSet = default(PropertySet);
                oDesignPropSet = oCompDef.Document.PropertySets("Design Tracking Properties");
            }
        }
Пример #8
0
        private void recoverAssembly()
        {
            compDef = (AssemblyComponentDefinition)m_AsmDoc.ComponentDefinition;

            for (int i = 1; i < compDef.Constraints.Count; i++)
            {
                if (compDef.Constraints[i].Type != ObjectTypeEnum.kInsertConstraintObject)
                {
                    continue;
                }
                insConstr = (InsertConstraint)compDef.Constraints[i];
                if (insConstr.HealthStatus == HealthStatusEnum.kDriverLostHealth)
                {
                    ao           = insConstr.AxesOpposed;
                    offsetDouble = (double)insConstr.Distance.Value;
                    e1           = (EdgeProxy)insConstr.EntityOne;
                    pt           = e1.PointOnEdge;
                    min          = 0.03;
                    max          = 0.15;
                    do
                    {
                        objs = compDef.FindUsingPoint(pt, ref sel, min);
                        min  = objs.Count > 2 ? min - delta : min + delta;
                    }while (objs.Count != 2 || objs.Count < max);

                    if (objs.Count == 2)
                    {
                        e2 = (EdgeProxy)objs[1];
                        insConstr.Delete();
                        insConstr = e1.ContainingOccurrence.Name == e2.ContainingOccurrence.Name ? compDef.Constraints.AddInsertConstraint(e1, (EdgeProxy)objs[2], ao, offsetDouble)
                            : compDef.Constraints.AddInsertConstraint(e1, (EdgeProxy)objs[1], ao, offsetDouble);
                    }
                }
            }
        }
Пример #9
0
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //// Sample
        ////
        //// Use: Copy & Replace assembly references (1st Level refs only)
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public void ReplaceReference()
        {
            AssemblyDocument            oAsmDoc = (AssemblyDocument)_InvApplication.ActiveDocument;
            AssemblyComponentDefinition oAsmDef = oAsmDoc.ComponentDefinition;

            Document oNewRefDoc = default(Document);
            string   filename   = null;


            foreach (FileDescriptor oFileDesc in oAsmDoc.File.ReferencedFileDescriptors)
            {
                oNewRefDoc = oFileDesc.ReferencedFile.AvailableDocuments(1);

                filename = "C:\\Temp\\Copy-" + oNewRefDoc.DisplayName;

                oNewRefDoc.SaveAs(filename, true);

                oFileDesc.ReplaceReference(filename);
            }

            filename = "C:\\Temp\\Copy-" + oAsmDoc.DisplayName;
            oAsmDoc.SaveAs(filename, true);

            oAsmDoc.Close(true);
        }
Пример #10
0
        }  //Main form closing

        private void assemble()
        {
            try
            {
                path = var_es._Doc.FullFileName.Remove(var_es._Doc.FullFileName.Length - 4);

                //создаём новый AssemblyDocument
                assemb_doc = (AssemblyDocument)var_es.InventorApp.Documents.Add(DocumentTypeEnum.kAssemblyDocumentObject, var_es.InventorApp.FileManager.GetTemplateFile(DocumentTypeEnum.kAssemblyDocumentObject), false);
                AssemblyComponentDefinition assemb_doc_Comp = assemb_doc.ComponentDefinition;

                //сохраняем созданий AssemblyDocument
                assemb_doc.SaveAs(path + @"/Shaft.iam", true);

                //Создаём матрицу
                TransientGeometry TG     = var_es.InventorApp.TransientGeometry;
                Matrix            matrix = TG.CreateMatrix();

                //привязываем наш AssemblyDocument в браузере к AssemblyDocument, который открыл пользователь
                var_es.part_doc = (PartDocument)var_es.InventorApp.Documents.Add(DocumentTypeEnum.kPartDocumentObject, var_es.InventorApp.FileManager.GetTemplateFile(DocumentTypeEnum.kPartDocumentObject), true);
                PartComponentDefinition doc_def = var_es.part_doc.ComponentDefinition;
            }
            catch (Exception e3)
            {
                MessageBox.Show(e3.ToString());
            }
        }
Пример #11
0
        /**
         * C#读取和修改Inventor模型的属性
         */
        private static void AFunction()
        {
            Inventor.Application inventorApp = null;
            try
            {
                inventorApp = Marshal.GetActiveObject("Inventor.Application") as Inventor.Application;
            }
            catch
            {
                var inventorType = Type.GetTypeFromProgID("Inventor.Application");
                inventorApp         = Activator.CreateInstance(inventorType) as Inventor.Application;
                inventorApp.Visible = true;
            }

            AssemblyDocument asmDoc = (AssemblyDocument)inventorApp.Documents.Open(@"Path", true);

            AssemblyComponentDefinition asmDef = asmDoc.ComponentDefinition;

            foreach (ComponentOccurrence oOcc in asmDef.Occurrences)
            {
                Document oDoc = (Document)oOcc.Definition.Document;
                // using GUID to find the "Summary Information"
                PropertySet oPS = oDoc.PropertySets["{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"];
                // using proID to find TITLE
                Inventor.Property oP = oPS.ItemByPropId[(int)PropertiesForSummaryInformationEnum.kTitleSummaryInformation];
                oP.Value = oP.Value + "new";
            }
        }
Пример #12
0
        public void AssemblyFeature()
        {
            AssemblyDocument            oAssDoc = (AssemblyDocument)_InvApplication.ActiveDocument;
            AssemblyComponentDefinition oAsmDef = oAssDoc.ComponentDefinition;

            // Create a sketch on the XY workplane.
            PlanarSketch oSketch = default(PlanarSketch);

            oSketch = oAsmDef.Sketches.Add(oAsmDef.WorkPlanes[3]);

            TransientGeometry oTG = default(TransientGeometry);

            oTG = _InvApplication.TransientGeometry;

            // Draw a rectangle.
            oSketch.SketchLines.AddAsTwoPointRectangle(oTG.CreatePoint2d(0.1, 0.1), oTG.CreatePoint2d(1, 0.5));
            // Create a profile
            Profile oProfile = default(Profile);

            oProfile = oSketch.Profiles.AddForSolid();

            // Create the extrusion.
            ExtrudeDefinition oExtrudeDef = default(ExtrudeDefinition);

            oExtrudeDef = oAsmDef.Features.ExtrudeFeatures.CreateExtrudeDefinition(oProfile, PartFeatureOperationEnum.kCutOperation);
            oExtrudeDef.SetDistanceExtent("2 cm", PartFeatureExtentDirectionEnum.kSymmetricExtentDirection);

            oAsmDef.Features.ExtrudeFeatures.Add(oExtrudeDef);
        }
Пример #13
0
        public void AddAssemblyBrowserFolder()
        {
            AssemblyDocument oDoc = (AssemblyDocument)_InvApplication.ActiveDocument;

            AssemblyComponentDefinition oDef = oDoc.ComponentDefinition;

            BrowserPane oPane = default(BrowserPane);

            oPane = oDoc.BrowserPanes.ActivePane;

            // Create an object collection
            ObjectCollection oOccurrenceNodes = default(ObjectCollection);

            oOccurrenceNodes = _InvApplication.TransientObjects.CreateObjectCollection();

            foreach (ComponentOccurrence oOcc in oDef.Occurrences)
            {
                // Get the node associated with this occurrence.
                BrowserNode oNode = default(BrowserNode);
                oNode = oPane.GetBrowserNodeFromObject(oOcc);

                // Add the node to the collection.
                oOccurrenceNodes.Add(oNode);
            }

            // Add the folder to the browser and specify the nodes to be grouped within it.
            BrowserFolder oFolder = default(BrowserFolder);

            oFolder = oPane.AddBrowserFolder("My Occurrences Folder", oOccurrenceNodes);
        }
Пример #14
0
        /// <summary>
        /// Casts the source document as an assembly document, assembly component definition, and setup the features
        /// </summary>
        /// <param name="document"></param>
        public InventorAssemblyDocument(Document document) : base(document)
        {
            _adoc = document as AssemblyDocument;

            _adef = _adoc.ComponentDefinition;

            var f = _adef.Features;
        }
Пример #15
0
 private void MakeJoints(AssemblyComponentDefinition oAsmCompDef)
 {
     foreach (AssemblyJoint ost in oAsmCompDef.Joints)
     {
         Joint temp = new Joint(ost, Links);
         Joints.Add(temp);
     }
 }
Пример #16
0
        public void WriteURDF(string xmlfilename)
        {
            UnitsOfMeasure              oUOM        = _invApp.ActiveDocument.UnitsOfMeasure;
            AssemblyDocument            oAsmDoc     = (AssemblyDocument)_invApp.ActiveDocument;
            AssemblyComponentDefinition oAsmCompDef = oAsmDoc.ComponentDefinition;
            ComponentOccurrence         Parent;
            string ParentName, AbsolutePosition, name, mirname, mirParentName;

            double[] ParentCOM, Offset;

            Robot hubo = new Robot("HuboPlus");

            foreach (ComponentOccurrence oCompOccur in oAsmCompDef.Occurrences)
            {
                // Generate links from available subassemblies in main assembly.
                hubo.Links.Add(new Link(oCompOccur.Name));
                int c = hubo.Links.Count - 1;
                for (int i = 0; i < hubo.Links.Count; i++)
                {
                    if (String.Equals(hubo.Links[i].Name, ReturnParentName(oCompOccur)))
                    {
                        hubo.Links[c].Parent = hubo.Links[i];
                    }
                }

                if (hubo.Links[c].Parent != null)
                {
                    hubo.Joints.Add(new Joint(FormatJointName(hubo.Links[c].Name), JointType.Revolute, hubo.Links[c].Parent, hubo.Links[c]));
                    int j = hubo.Joints.Count - 1;
                    switch (hubo.Joints[j].Name[hubo.Joints[j].Name.Length - 1])
                    {
                    case 'R':
                        hubo.Joints[j].Axis = new double[] { 1, 0, 0 };
                        break;

                    case 'P':
                        hubo.Joints[j].Axis = new double[] { 0, 1, 0 };
                        break;

                    case 'Y':
                        hubo.Joints[j].Axis = new double[] { 0, 0, 1 };
                        break;

                    default:
                        break;
                    }
                }

                // Get mass properties for each link.
                double[] iXYZ = new double[6];
                oCompOccur.MassProperties.XYZMomentsOfInertia(out iXYZ[0], out iXYZ[3], out iXYZ[5], out iXYZ[1], out iXYZ[4], out iXYZ[2]); // Ixx, Iyy, Izz, Ixy, Iyz, Ixz -> Ixx, Ixy, Ixz, Iyy, Iyz, Izz
                hubo.Links[c].Inertial     = new Inertial(oCompOccur.MassProperties.Mass, iXYZ);
                hubo.Links[c].Inertial.XYZ = FindCenterOfMassOffset(oCompOccur);

                // Set shape properties for each link.
                hubo.Links[c].Visual = new Visual(new Mesh("package://" + hubo.Name + "/" + hubo.Links[c].Name + ".stl"));
            }
        }
Пример #17
0
        static public BOM getBOM(Document doc)
        {
            AssemblyComponentDefinition acd = getACD(doc);

            if (acd == null)
            {
                return(null);
            }
            return(acd.BOM);
        }
Пример #18
0
        public static void updateParametersRule(Application currentApp)
        {
            Application                 invApp                 = currentApp;
            AssemblyDocument            currentAssembly        = (AssemblyDocument)invApp.ActiveDocument;
            AssemblyComponentDefinition currentAssemblyCompDef = currentAssembly.ComponentDefinition;
            Parameters currentParameters = currentAssemblyCompDef.Parameters;
            string     ruleName          = "Dimensions to Parts";

            ApplicationAddIn iLogicAddin = invApp.ApplicationAddIns.ItemById[iLogicAddinGuid];

            if (iLogicAddin != null)
            {
                // Get Key Parameters
                UserParameters userParams = currentParameters.UserParameters;

                // Create iLogic code as string
                StringBuilder iLogicCode = new StringBuilder();
                iLogicCode.Append("Dim oDoc As Document\noDoc = ThisDoc.Document\nDim partFile As Document\n");
                iLogicCode.AppendLine("For Each partFile In oDoc.AllReferencedDocuments");
                iLogicCode.AppendLine("Dim fileNameLocation As Long");
                iLogicCode.AppendLine("fileNameLocation = InStrRev(partFile.FullFileName, \"\\\", -1)");
                iLogicCode.Append("Dim oPart As String\noPart = Right(partFile.FullFileName, Len(partFile.FullFileName) - fileNameLocation)\n");
                iLogicCode.Append("Parameter.Quiet = True\nTry\n");

                // Add Parameters to iLogic code
                foreach (UserParameter userParam in userParams)
                {
                    if (userParam.IsKey)
                    {
                        iLogicCode.AppendLine(parameterParser(userParam.Name));
                    }
                }

                iLogicCode.Append("Catch\nEnd Try\nInventorVb.DocumentUpdate()\nNext\n");

                // Enter Addin
                dynamic iLogicAuto = iLogicAddin.Automation;

                //Update Code
                try
                {
                    iLogicAuto.DeleteRule((Document)currentAssembly, ruleName);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
                finally
                {
                    iLogicAuto.AddRule((Document)currentAssembly, ruleName, iLogicCode.ToString());
                }
            }
        }
Пример #19
0
        public Robot(string name, AssemblyComponentDefinition drawing)
        {
            Name = name;

            this.Links.Add(new Link(drawing.WorkPoints[1]));

            MakeLinks(drawing);
            MakeJoints(drawing);

            List <Link> roots = this.Links.Except(this.Joints.Select(x => x.Child.refff)).ToList();

            this.Joints.Add(new Joint("baselink", Joint.JointType.Fixed, roots[0], roots[1]));
        }
Пример #20
0
        public void GenerateShelving(AssemblyComponentDefinition acd, JObject jParams)
        {
            Trace.WriteLine("GenerateShelving, jParams = " + jParams.ToString(Formatting.None));
            string height          = jParams["height"].Value <string>();
            string shelfWidth      = jParams["shelfWidth"].Value <string>();
            string numberOfColumns = jParams["numberOfColumns"].Value <string>();

            acd.Parameters["Height"].Expression     = height;
            acd.Parameters["Columns"].Expression    = numberOfColumns;
            acd.Parameters["ShelfWidth"].Expression = shelfWidth;
            // Kick off the model update
            acd.Parameters["iTrigger0"].Expression = $"{(acd.Parameters["iTrigger0"].Value + 1).ToString()}";
        }
Пример #21
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (_invApp.Documents.Count == 0)
            {
                // Create an instance of the open file dialog box.
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter      = "Inventor assembly (.iam)|*.iam|All Files (*.*)|*.*";
                openFileDialog1.FilterIndex = 1;
                openFileDialog1.Multiselect = false;

                // Call the ShowDialog method to show the dialog box.
                DialogResult dialogResult = openFileDialog1.ShowDialog();

                // Process input if the user clicked OK.
                if (dialogResult == DialogResult.OK)
                {
                    _invApp.Documents.Open(openFileDialog1.FileName);
                }
                else
                {
                    _invApp.Documents.Open("D:\\Workspace\\AutoTurf4_CAD\\Version 4 - Komplet maskine.iam");
                }
            }

            oUOM        = _invApp.ActiveDocument.UnitsOfMeasure;
            oAsmDoc     = (AssemblyDocument)_invApp.ActiveDocument;
            oAsmCompDef = oAsmDoc.ComponentDefinition;

            //Change to master version for massproperties and joints
            repman     = oAsmCompDef.RepresentationsManager;
            lod_master = repman.LevelOfDetailRepresentations["Master"];
            lod_simple = repman.LevelOfDetailRepresentations["Collision"];

            lod_master.Activate();
            robot = new Robot(oAsmDoc.DisplayName, oAsmCompDef);

            textBox1.Text = oAsmDoc.DisplayName;

            dataGridView1.AutoGenerateColumns         = false;
            dataGridView2.AutoGenerateColumns         = false;
            dataGridView1.DataSource                  = robot.Links;
            dataGridView1.Columns[0].DataPropertyName = "Name";
            dataGridView1.Columns[1].DataPropertyName = "Inertial";
            dataGridView2.DataSource                  = robot.Joints;
            dataGridView2.Columns[0].DataPropertyName = "Name";
            dataGridView2.Columns[1].DataPropertyName = "JointType";
            dataGridView2.Columns[2].DataPropertyName = "Origin";
            dataGridView2.Columns[3].DataPropertyName = "Axis";
            dataGridView2.Columns[4].DataPropertyName = "Parent";
            dataGridView2.Columns[5].DataPropertyName = "Child";
        }
Пример #22
0
        public void addProject()
        {
            try
            {
                m_asmCompDef = asmDoc.ComponentDefinition;
                invApp       = (Inventor.Application)asmDoc.Parent;
                tg           = invApp.TransientGeometry;
                smcd         = (SheetMetalComponentDefinition)m_asmCompDef.Occurrences[1].Definition;
                SheetMetalComponentDefinition smcd2 = (SheetMetalComponentDefinition)m_asmCompDef.Occurrences[2].Definition;
                //m_asmCompDef.Occurrences[1].Edit();
                CommandManager cmdMgr = ((Inventor.Application)asmDoc.Parent).CommandManager;
                FaceProxy      face;
                object         obj = cmdMgr.Pick(SelectionFilterEnum.kPartFacePlanarFilter, "Выберите плоскость эскиза:");
                objCol = invApp.TransientObjects.CreateObjectCollection();
                face   = (FaceProxy)obj;
                asmDoc.SelectSet.Select(m_asmCompDef.Occurrences[2]);
                //((PartDocument)smcd.Document).SelectSet.Select(m_asmCompDef.Occurrences[2].CreateGeometryProxy());
                //double[] pts = {face.PointOnFace.X,face.PointOnFace.Y,face.PointOnFace.Z};
                //double[] normals = {0,0,0};
                //face.Evaluator.GetNormalAtPoint(ref pts, ref normals);
                //Plane pl = invApp.TransientGeometry.CreatePlane(face.PointOnFace, invApp.TransientGeometry.CreateVector(normals[0], normals[1], normals[2]));
                //obj = m_asmCompDef.Occurrences[2].Definition.SurfaceBodies[1];
                //m_PartDoc.SelectSet.Select()
                obj = null;
                WorkPlane wp = smcd2.WorkPlanes[3];
                m_asmCompDef.Occurrences[1].CreateGeometryProxy(face, out obj);
                FaceProxy face2 = (FaceProxy)obj;
                ps = smcd.Sketches.Add(face2);
                ProjectedCut cut = ps.ProjectedCuts.Add();
                PlanarSketch pls = smcd2.Sketches.Add(smcd2.WorkPlanes[3]);
                m_asmCompDef.Occurrences[2].CreateGeometryProxy(pls, out obj);
                psp = (PlanarSketchProxy)obj;
                foreach (var item in ps.SketchLines)
                {
                    m_asmCompDef.Occurrences[1].CreateGeometryProxy(item, out obj);
                    psp.AddByProjectingEntity(obj);
                }
                //m_asmCompDef.Occurrences[2].CreateGeometryProxy(smcd.WorkPlanes[3],out obj);
                //m_asmCompDef.Occurrences[1].CreateGeometryProxy(ps,out obj);

                //psp.ProjectedCuts.Add();
                TransientGeometry tr = invApp.TransientGeometry;
                //cmdMgr.ControlDefinitions["SketchProjectCutEdgesCmd"].Execute();
                //enumerat = invApp.TransientGeometry.SurfaceSurfaceIntersection(m_asmCompDef.Occurrences[2].Definition.SurfaceBodies[1], pl);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #23
0
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            if (_invApp.Documents.Count == 0)
            {
                // Create an instance of the open file dialog box.
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter      = "Inventor assembly (.iam)|*.iam|All Files (*.*)|*.*";
                openFileDialog1.FilterIndex = 1;
                openFileDialog1.Multiselect = false;

                // Call the ShowDialog method to show the dialog box.


                // Process input if the user clicked OK.
                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    _invApp.Documents.Open(openFileDialog1.FileName);
                }
                else
                {
                    _invApp.Documents.Open(Properties.Settings.Default.autoload_file);
                }
            }

            oUOM        = _invApp.ActiveDocument.UnitsOfMeasure;
            oAsmDoc     = (AssemblyDocument)_invApp.ActiveDocument;
            oAsmCompDef = oAsmDoc.ComponentDefinition;

            //Change to master version for massproperties and joints
            repman     = oAsmCompDef.RepresentationsManager;
            lod_master = repman.LevelOfDetailRepresentations["Master"];

            lod_master.Activate();
            robot = new Robot(oAsmDoc.DisplayName, oAsmCompDef);

            if (addbaselinkcheckbox.IsChecked == true)
            {
                addbaselink(ref robot, oAsmCompDef);
            }

            textBox.Text = oAsmDoc.DisplayName.TrimEnd(".iam".ToCharArray());

            dataGridLinks.DataContext  = robot.Links;
            dataGridJoints.DataContext = robot.Joints;

            dataGridLinks.ItemsSource  = robot.Links;
            dataGridJoints.ItemsSource = robot.Joints;
            dataGridLinks.Items.Refresh();
            dataGridJoints.Items.Refresh();
        }
Пример #24
0
        //public static class TranslatorAddins
        //{
        //    public const string SAT	= "89162634-02B6-11D5-8E80-0010B541CD80";
        //    public const string STEP = "90AF7F40-0C01-11D5-8E83-0010B541CD80";
        //    public const string IGES = "90AF7F44-0C01-11D5-8E83-0010B541CD80";
        //    public const string CATIAV5ProductExport = "8A88FC01-0C32-4B3E-BE12-DDC8DF6FFF18";
        //    public const string DWG	= "C24E3AC2-122E-11D5-8E91-0010B541CD80";
        //    public const string DXF	= "C24E3AC4-122E-11D5-8E91-0010B541CD80";
        //    public const string STLImport = "81CA7D27-2DBE-4058-8188-9136F85FC859";
        //    public const string DWF	= "0AC6FD95-2F4D-42CE-8BE0-8AEA580399E4";
        //    public const string PDF	= "0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4";
        //    public const string DWFx	= "0AC6FD97-2F4D-42CE-8BE0-8AEA580399E4";
        //    public const string CATIAV5PartExport = "2FEE4AE5-36D3-4392-89C7-58A9CD14D305";
        //    public const string RVT	= "2058EF4F-37A3-4B57-A322-B4E79E7D53E4";
        //    public const string TUFF = "3260333F-3B0D-4812-9274-E94E14A77A16";
        //    public const string ParasolidText = "8F9D3571-3CB8-42F7-8AFF-2DB2779C8465";
        //    public const string Fusion	= "C6B37B88-3CFA-4521-9873-E087B8626C44";
        //    public const string FCADTransServer = "BE52A5E7-58D8-4E3C-A887-06A4C8F29568";
        //    public const string AutodeskIDFTranslator = "6C5BBC04-5D6F-4353-94B1-060CD6554444";
        //    public const string SolidWorks = "402BE503-725D-41CB-B746-D557AB83BAF1";
        //    public const string ProENGINEERGranite = "66CB2667-73AD-401C-A531-64EC701825A1";
        //    public const string NX = "93D506C4-8355-4E28-9C4E-C2B5F1EDC6AE";
        //    public const string SMT	= "B4ECC5EB-9507-46E5-87FB-EBB9479CE1DF";
        //    public const string OBJImport = " C420F7E4-98FD-4A57-BC1E-04D1D683EFDF";
        //    public const string SVF	= "C200B99B-B7DD-4114-A5E9-6557AB5ED8EC";
        //    public const string ParasolidBinary = " A8F8F8E5-BBAB-4F74-8B1B-AC011251F8AC";
        //    public const string ProENGINEERandCreoParametric = "46D96B7A-CF8A-49C9-8703-2F40CFBDF547";
        //    public const string ContentCenterItemTranslator = "A547F528-D239-475F-8FC6-8F97C4DB6746";
        //    public const string SolidEdge = " E2548DAF-D56B-4809-82B9-5F670E6D518B";
        //    public const string ProENGINEERNeutral = "8CEC09E3-D638-4E8F-A6E1-0D1E1A5FC8E3";
        //    public const string CATIAV4Import	= "C6ACD948-E1C5-4B5B-ADEE-3ED968F8CB1A";
        //    public const string Rhino = "2CB23BF0-E2AC-4B32-B0A1-1CC292AF6623";
        //    public const string CATIAV5Import	= "8D1717FA-EB24-473C-8B0F-0F810C4FC5A8";
        //    public const string AutodeskDWFMarkupManager = "55EBD0FA-EF60-4028-A350-502CA148B499";
        //    public const string JT	= "16625A0E-F58C-4488-A969-E7EC4F99CACD";
        //    public const string Alias	= "DC5CD10A-F6D1-4CA3-A6E3-42A6D646B03E";
        //    public const string OBJExport = " F539FB09-FC01-4260-A429-1818B14D6BAC";
        //    public const string STLExport = "533E9A98-FC3B-11D4-8E7E-0010B541CD80";
        //}

        //public AssemblyDocument Import(string fullAssemblyPath)
        //{
        //    LogTrace("Starting Import");
        //    ApplicationAddIns addins = inventorApplication.ApplicationAddIns;
        //    //foreach (ApplicationAddIn addin in addins)
        //    //{
        //    //    if  (addin is )
        //    //}
        //    //If TypeOf addin Is TranslatorAddIn Then
        //    //    LogTrace(addin.DisplayName & Chr(9) & addin.ClassIdString)
        //    //End If
        //    //Next
        //    TranslatorAddIn transAddin = (TranslatorAddIn)addins.ItemById["{" + TranslatorAddins.STEP + "}"];
        //    LogTrace("Get Stp Addin");
        //    TransientObjects transObjects = inventorApplication.TransientObjects;
        //    transAddin.Activate();

        //    LogTrace("Stp Addin Activated");

        //    //Prepare the 1st parameter for Open(), the file name
        //    DataMedium file = transObjects.CreateDataMedium();
        //    file.FileName = fullAssemblyPath;

        //    LogTrace("DataMedium created");

        //    //Prepare the 2nd parameter for Open(), the open type, for convenience set it as drag&drop
        //    TranslationContext context = transObjects.CreateTranslationContext();
        //    context.Type = IOMechanismEnum.kFileBrowseIOMechanism;

        //    LogTrace("TranslationContext created");

        //    //Prepare the 3rd parameter for Open(), the import options
        //    NameValueMap options = transObjects.CreateNameValueMap();

        //    Boolean hasOpt = transAddin.HasOpenOptions[file, context, options];
        //    options.Value["AssociativeImport"] = false;
        //    options.Value["EmbedInDocument "] = false;
        //    options.Value["SaveLocationIndex "] = 0;
        //    options.Value["TessellationDetailIndex"] = 1;

        //    for (int i = 1; i <= options.Count; ++i)
        //    {
        //        string name = options.Name[i];
        //        string value = (string)options.Value[name];
        //        LogTrace(name + " " + value);
        //    }

        //    object sourceObject;
        //    transAddin.Open(file, context, options, out sourceObject);

        //    AssemblyDocument doc = (AssemblyDocument)sourceObject;

        //    return doc;
        //}


        public AssemblyDocument AnyCADImport(string fullAssemblyPath)
        {
            var em = inventorApplication.ErrorManager;

            LogTrace("AnyCADImport called");
            inventorApplication.SaveOptions.TranslatorReportLocation = ReportLocationEnum.kNoReport;
            AssemblyDocument doc = (AssemblyDocument)inventorApplication.Documents.Add(DocumentTypeEnum.kAssemblyDocumentObject);

            LogTrace("New Assembly created");
            AssemblyComponentDefinition        compDef         = doc.ComponentDefinition;
            ImportedGenericComponentDefinition importedCompDef = (ImportedGenericComponentDefinition)compDef.ImportedComponents.CreateDefinition(fullAssemblyPath);

            importedCompDef.ReferenceModel = true;

            string saveFilesLocation = System.IO.Path.GetDirectoryName(fullAssemblyPath) + "\\";

            LogTrace("Imported Files Location = " + saveFilesLocation);
            importedCompDef.SaveFilesLocation = saveFilesLocation;
            ImportedComponent importedComp = compDef.ImportedComponents.Add((ImportedComponentDefinition)importedCompDef);

            try
            {
                LogTrace("Before Update");
                doc.Update2();
                LogTrace("After Update");
                LogTrace("Before Save");

                LogTrace($"Checking ErrorManager before save");
                LogTrace($"HasErrors = {em.HasErrors}");
                LogTrace($"HasWarnings = {em.HasWarnings}");
                LogTrace($"AllMessages = {em.AllMessages}");

                doc.SaveAs(System.IO.Path.Combine(saveFilesLocation, "output.iam"), false);
                LogTrace("After Save");

                LogTrace("Assembly Path = " + doc.FullFileName);

                LogTrace($"Checking ErrorManager after save");
                LogTrace($"HasErrors = {em.HasErrors}");
                LogTrace($"HasWarnings = {em.HasWarnings}");
                LogTrace($"AllMessages = {em.AllMessages}");
            }
            catch (Exception ex)
            {
                LogTrace("Error: " + ex.Message);
            }
            LogTrace("Successfully Imported");
            return(doc);
        }
Пример #25
0
        /// <summary>
        /// Inserts a member (part/Subassembly or 3D model) in assembly and returns the created occurance
        /// </summary>
        /// <param name="assy"></param>
        /// <param name="inventor">inventor assembly</param>
        /// <param name="member">any of the supported <see cref="Document"/> types to insert into assembly</param>
        /// <param name="position">position of the member relative to assembly's origin</param>
        /// <param name="rotation">rotation about the X and Y and Z axis</param>
        /// <returns><see cref="ComponentOccurrence"/> that is created inside the assembly</returns>
        /// <remarks>remeber that Inventors internal units for length are centimeters</remarks>
        public static ComponentOccurrence AddMemeber(this AssemblyDocument assy, Application inventor, Document member, double[] position, double[] rotation)
        {
            if (member.DocumentType == DocumentTypeEnum.kDrawingDocumentObject ||
                member.DocumentType == DocumentTypeEnum.kNoDocument ||
                member.DocumentType == DocumentTypeEnum.kPresentationDocumentObject ||
                member.DocumentType == DocumentTypeEnum.kUnknownDocumentObject)
            {
                throw new ArgumentException("documnet type is not supported", nameof(member));
            }

            if (member.FullFileName == "")
            {
                throw new Exception("FullFileName of the part object was null, you need to save the part before passing to this method");
            }

            if (position.Length > 3 || rotation.Length > 3)
            {
                throw new ArgumentOutOfRangeException("position or rotaion array cannot have more than three memebers");
            }

            // Set a reference to the assembly component definition.
            AssemblyComponentDefinition oAsmCompDef = assy.ComponentDefinition;

            // Set a reference to the transient geometry object.
            TransientGeometry oTG = inventor.TransientGeometry;

            // Create a matrix.  A new matrix is initialized with an identity matrix.
            Matrix tempMatrix  = oTG.CreateMatrix();
            Matrix transMatrix = oTG.CreateMatrix();

            //for all rotational directions . . .
            for (int i = 0; i < rotation.Length; i++)
            {
                var index = new List <int>(new[] { 0, 0, 0 });
                index[i] = 1;
                var origin = oTG.CreatePoint(0, 0, 0);

                //rotate about an axis that goeas through origin point and is along the rotaional direction
                tempMatrix.SetToRotation(MathHelper.ToRadian(rotation[i]), oTG.CreateVector(index[0], index[1], index[2]), origin);
                transMatrix.TransformBy(tempMatrix);
                tempMatrix.SetToIdentity();
            }

            //move the object to the position
            transMatrix.SetTranslation(oTG.CreateVector(position[0], position[1], position[2]));

            // Add the occurrence.
            return(oAsmCompDef.Occurrences.Add(member.FullFileName, transMatrix));
        }
Пример #26
0
        private void CalculateHoleB_Click(object sender, EventArgs e)
        {
            if (inventor == null)
            {
                MessageBox.Show("No inventor instance detected", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            AssemblyDocument doc = inventor.ActiveDocument as AssemblyDocument;

            if (doc == null || doc.ComponentDefinition == null)
            {
                return;
            }

            AssemblyComponentDefinition partComponentDefinition = doc.ComponentDefinition;
            var wall   = partComponentDefinition.Occurrences.get_ItemByName("wall:1");
            var weight = partComponentDefinition.Occurrences.get_ItemByName("weight:1");
            PartComponentDefinition weightDefinition = weight.Definition as PartComponentDefinition;
            PartComponentDefinition wallDefinition   = wall.Definition as PartComponentDefinition;
            SurfaceBody             surfaceBody2     = inventor.TransientBRep.Copy(weight.SurfaceBodies[1]);
            Vector rotationVector = inventor.TransientGeometry.CreateVector(0, 1, 0);

            Inventor.Point point = inventor.TransientGeometry.CreatePoint(0, 0, 0);



            var collection = inventor.TransientObjects.CreateObjectCollection();

            for (int i = 1; i <= 120; i++)
            {
                Matrix wallMatrix = wall.Transformation, weigthMatrix = weight.Transformation;
                weigthMatrix.Invert();
                wallMatrix.PreMultiplyBy(weigthMatrix);
                SurfaceBody surfaceBody = inventor.TransientBRep.Copy(weight.SurfaceBodies[1]);
                wallMatrix.SetToRotation(i * Math.PI / 180, rotationVector, point);
                inventor.TransientBRep.Transform(surfaceBody, wallMatrix);
                inventor.TransientBRep.DoBoolean(surfaceBody2, surfaceBody, BooleanTypeEnum.kBooleanTypeUnion);
            }

            NonParametricBaseFeatureDefinition featureDefinition = weightDefinition.Features.NonParametricBaseFeatures.CreateDefinition();

            featureDefinition.OutputType = BaseFeatureOutputTypeEnum.kSolidOutputType;

            collection.Add(surfaceBody2);
            featureDefinition.BRepEntities = collection;
            NonParametricBaseFeature baseFeature = weightDefinition.Features.NonParametricBaseFeatures.AddByDefinition(featureDefinition);

            //CombineFeature combineFeature = doc.Features.CombineFeatures.Add(wall.SurfaceBodies[1], collection, PartFeatureOperationEnum.kCutOperation);
        }
Пример #27
0
        public void SendPicture(AssemblyComponentDefinition acd, JObject jParams)
        {
            Trace.WriteLine("SendPicture, jParams = " + jParams.ToString(Formatting.None));
            var width  = jParams["width"].Value <int>();
            var height = jParams["height"].Value <int>();

            TransientGeometry tg  = m_server.TransientGeometry;
            Camera            cam = m_server.TransientObjects.CreateCamera();

            cam.SceneObject = acd;

            cam.ViewOrientationType = ViewOrientationTypeEnum.kIsoTopRightViewOrientation;
            cam.Fit();
            cam.ApplyWithoutTransition();
            cam.SaveAsBitmap("output.png", width, height, Type.Missing, Type.Missing);
        }
Пример #28
0
        private InvWorkPoint(double x, double y, double z)
        {
            //this.VerifyContextSettings();
            AssemblyDocument            assDoc  = InventorPersistenceManager.ActiveAssemblyDoc;
            AssemblyComponentDefinition compDef = (AssemblyComponentDefinition)assDoc.ComponentDefinition;

            Inventor.Point     point = InventorPersistenceManager.InventorApplication.TransientGeometry.CreatePoint(x, y, z);
            Inventor.WorkPoint wp    = compDef.WorkPoints.AddFixed(point, false);

            byte[] refKey = new byte[] { };
            //wp.GetReferenceKey(ref refKey, (int)InventorSettings.KeyContext);
            //wp.GetReferenceKey(ref refKey, (int)ReferenceManager.KeyContext);
            //ComponentOccurrenceKeys.Add(refKey);
            //return wp;
            InternalSetWorkPoint(wp);
        }
Пример #29
0
        /// <summary>
        /// it create a JSON file with BOM Data
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="eBomViewType"></param>
        public void GetBom(Document doc, BOMViewTypeEnum eBomViewType)
        {
            doc.Update();

            try
            {
                string                      viewType     = "Structured";
                AssemblyDocument            assemblyDoc  = doc as AssemblyDocument;
                AssemblyComponentDefinition componentDef = assemblyDoc.ComponentDefinition;

                LogTrace("Create BOM Object");
                BOM bom = componentDef.BOM;

                if (eBomViewType == BOMViewTypeEnum.kStructuredBOMViewType)
                {
                    bom.StructuredViewEnabled        = true;
                    bom.StructuredViewFirstLevelOnly = false;
                }
                else
                {
                    bom.PartsOnlyViewEnabled = true;
                    viewType = "Parts Only";
                }

                LogTrace("Create BOM Views");
                BOMViews bomViews = bom.BOMViews;

                LogTrace("Create BOM View");
                BOMView structureView = bomViews[viewType];

                JArray bomRows = new JArray();

                LogTrace("Get BOM Rows to Json");
                BOMRowsEnumerator rows = structureView.BOMRows;

                LogTrace("Start to generate BOM data ...");
                GetBomRowProperties(structureView.BOMRows, bomRows);

                LogTrace("Writing out bomRows.json");
                File.WriteAllText(currentDirectory + "/bomRows.json", bomRows.ToString());
                GetListOfDirectory(currentDirectory);
            }
            catch (Exception e)
            {
                LogError("Bom failed: " + e.ToString());
            }
        }
Пример #30
0
        private void insertPartsAndMateEdges()
        {
            // create an assembly
            AssemblyDocument            oAssDoc = (AssemblyDocument)mApp.Documents.Add(DocumentTypeEnum.kAssemblyDocumentObject);
            AssemblyComponentDefinition oAssDef = oAssDoc.ComponentDefinition;

            Matrix oM = mApp.TransientGeometry.CreateMatrix();

            //place the two parts
            ComponentOccurrence oOcc1 = oAssDef.Occurrences.Add("c:\\temp\\test1.ipt", oM);
            ComponentOccurrence oOcc2 = oAssDef.Occurrences.Add("c:\\temp\\test2.ipt", oM);

            // find the two faces to mate
            PartDocument     oDoc1          = (PartDocument)oOcc1.Definition.Document;
            ObjectCollection oObjCollection = oDoc1.AttributeManager.FindObjects("demoAttset", "demoAtt");

            Face oFace1 = null;

            if (oObjCollection[1] is Face)
            {
                oFace1 = (Face)oObjCollection[1];
            }

            PartDocument oDoc2 = (PartDocument)oOcc2.Definition.Document;

            oObjCollection = oDoc2.AttributeManager.FindObjects("demoAttset", "demoAtt");

            Face oFace2 = null;

            if (oObjCollection[1] is Face)
            {
                oFace2 = (Face)oObjCollection[1];
            }

            Object tempObj;

            //create the proxy objects for the two faces

            oOcc1.CreateGeometryProxy(oFace1, out tempObj);
            FaceProxy oAsmProxyFace1 = (FaceProxy)tempObj;

            oOcc2.CreateGeometryProxy(oFace2, out tempObj);
            FaceProxy oAsmProxyFace2 = (FaceProxy)tempObj;

            // add the mate constraint
            oAssDef.Constraints.AddMateConstraint(oAsmProxyFace1, oAsmProxyFace2, 0);
        }
 public InventorController()
 {
     isConstructed=false;
     try
     {
         inventorApplication = (Inventor.Application)
         System.Runtime.InteropServices.Marshal.
         GetActiveObject("Inventor.Application");
         assemblyDoc = (AssemblyDocument)inventorApplication.ActiveDocument;
         assemblyComp = assemblyDoc.ComponentDefinition;
         parameterList = getParameterList();
         isConstructed = true;
         createConstraintList();
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.Write(ex.Message);
         return;
     }
     isConstructed = true;
 }