Exemple #1
0
        public static void GetChildrenComp(ModelDoc2 Doc)
        {
            if (Doc.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
            {
                AssemblyDoc Assem = (AssemblyDoc)Doc;

                #region 顶底层零部件
                StringBuilder topsb = new StringBuilder("顶层部件:\r\n");
                object[]      Comps = Assem.GetComponents(true);
                foreach (object cp in Comps)
                {
                    topsb.Append(((Component2)cp).Name2 + "\r\n");
                }
                #endregion

                #region 所有零部件
                StringBuilder allsb = new StringBuilder("所有部件:\r\n");
                Comps = Assem.GetComponents(false);
                foreach (object cp in Comps)
                {
                    allsb.Append(((Component2)cp).Name2 + "\r\n");
                }
                #endregion

                System.Windows.MessageBox.Show(topsb + "\r\n" + allsb);
            }
        }
Exemple #2
0
        public List <Item> GetItems()
        {
            var list = new List <Item>();

            assembly.ResolveAllLightWeightComponents(false);

            var assemblyComponents = ((Array)assembly.GetComponents(TopLevelOnly))
                                     .Cast <Component2>()
                                     .Where(c => !c.IsHidden(true));

            var componentGroups = assemblyComponents
                                  .GroupBy(c => c.GetTitle() + c.ReferencedConfiguration);

            foreach (var group in componentGroups)
            {
                var component = group.First();
                var model     = component.GetModelDoc2() as ModelDoc2;

                if (model == null)
                {
                    continue;
                }

                var name = GetComponentName(component);

                list.Add(new Item
                {
                    PartName  = name,
                    Quantity  = group.Count(),
                    Component = component
                });
            }

            return(list);
        }
        public void TestHideComponents(string modelName)
        {
            ModelDoc2         doc     = OpenSWDocument(modelName);
            AssemblyDoc       assyDoc = (AssemblyDoc)doc;
            List <string>     hiddenComponentNames = Common.FindHiddenComponents(assyDoc.GetComponents(false));
            List <Component2> hiddenComponents     =
                hiddenComponentNames.Select(name => assyDoc.GetComponentByName(name)).ToList();

            Common.ShowAllComponents(doc, new List <string>());
            Common.HideComponents(doc, hiddenComponents);
            List <string> hiddenComponentNames2 = Common.FindHiddenComponents(assyDoc.GetComponents(false));

            Assert.Equal(hiddenComponentNames.Count, hiddenComponentNames2.Count);

            SwApp.CloseAllDocuments(true);
        }
Exemple #4
0
        private SWglTFModel ConvertAssemblyToglTF(ModelDoc2 swModel)
        {
            SWglTFModel Model = new SWglTFModel();

            AssemblyDoc swAssDoc = (AssemblyDoc)swModel;

            object[] comps = swAssDoc.GetComponents(false);
            foreach (Component2 item in comps)
            {
                double[] MaterialValue = item.MaterialPropertyValues;
                if (MaterialValue == null)
                {
                    ModelDoc2 swCompModel = item.GetModelDoc2();
                    if (swCompModel != null)
                    {
                        MaterialValue = swCompModel.MaterialPropertyValues;
                    }
                }
                object[] bodys = item.GetBodies2((int)swBodyType_e.swAllBodies);
                if (bodys != null)
                {
                    foreach (Body2 swBody in bodys)
                    {
                        var bodymodel = GetglTFBodyModel(swBody);
                        if (bodymodel.BodyMaterialValue == null && MaterialValue != null)
                        {
                            bodymodel.BodyMaterialValue = MaterialValue;
                        }
                        bodymodel.SWMathTran = item.Transform2;
                        Model.BodyList.Add(bodymodel);
                    }
                }
            }
            return(Model);
        }
Exemple #5
0
        private void ReplaceBolsaCP(Coletor coletor)
        {
            swApp.ActivateDoc(coletor.CodigoColetor + ".SLDASM");
            swModel = swApp.ActiveDoc;

            AssemblyDoc swAssembly = (AssemblyDoc)swModel;

            Object[] components = swAssembly.GetComponents(true);

            foreach (var componente in components)
            {
                Component2 component = (Component2)componente;

                swModel = component.GetModelDoc2();

                string nomeCompletoDoComponente = swModel.GetPathName();
                string nomeComExtensao          = Path.GetFileName(nomeCompletoDoComponente);

                if (String.Equals(nomeComExtensao, "BOLSA SOLDA SUCCAO CP TEMPLATE.SLDPRT"))
                {
                    component.Select(true);
                    break;
                }
            }

            swAssembly.ReplaceComponents($@"C:\ELETROFRIO\ENGENHARIA SMR\PRODUTOS FINAIS ELETROFRIO\MECÂNICA\RACK PADRAO\COLETOR SUCCAO\{coletor.CodigoBolsaSoldaSuccaoCompressor}.SLDPRT",
                                         "", true, true);

            swModel = swApp.ActiveDoc;
            swModel.Save();
        }
        /// <summary>
        /// Выполняет метод для компонентов сборки (подсборки и детали)
        /// </summary>
        /// <param name="assemblyDoc">Сборка</param>
        /// <param name="actionForPart">Метод для детали</param>
        /// <param name="actionForAssembly">Метод для подсборок</param>
        public static void DoSmthForEachComponent(AssemblyDoc assemblyDoc, Action<ModelDoc2> actionForPart, Action<ModelDoc2> actionForAssembly)
        {
            object[] components = (object[])assemblyDoc.GetComponents(true);

            if (components.Length == 0)
                return;

            foreach (var item in components)
            {
                Component2 component = (Component2)item;
                ModelDoc2 model = component.IGetModelDoc();
                if (model != null)
                {
                    AssemblyDoc ad = model as AssemblyDoc;
                    if (ad != null)
                    {
                        actionForAssembly(model);
                        DoSmthForEachComponent(ad, actionForPart, actionForAssembly);
                        continue;
                    }

                    PartDoc pd = model as PartDoc;
                    if (pd != null)
                        actionForPart(model);
                }
            }
        }
Exemple #7
0
        // Beginning method for exporting the full package
        public void exportRobot()
        {
            //Setting up the progress bar

            int progressBarBound = Common.getCount(mRobot.BaseLink);

            progressBar.Start(0, progressBarBound, "Creating package directories");

            //Creating package directories
            URDFPackage package = new URDFPackage(mPackageName, mSavePath);

            package.createDirectories();
            mRobot.name = mPackageName;
            string windowsURDFFileName     = package.WindowsRobotsDirectory + mRobot.name + ".URDF";
            string windowsManifestFileName = package.WindowsPackageDirectory + "manifest.xml";

            //Creating manifest file
            manifestWriter manifestWriter = new manifestWriter(windowsManifestFileName);
            manifest       Manifest       = new manifest(mPackageName);

            Manifest.writeElement(manifestWriter);

            //Creating RVIZ launch file
            Rviz rviz = new Rviz(mPackageName, mRobot.name + ".URDF");

            rviz.writeFiles(package.WindowsLaunchDirectory);

            //Creating Gazebo launch file
            Gazebo gazebo = new Gazebo(this.mRobot.name, this.mPackageName, mRobot.name + ".URDF");

            gazebo.writeFile(package.WindowsLaunchDirectory);


            //Customizing STL preferences to how I want them
            saveUserPreferences();
            setSTLExportPreferences();

            //Saving part as STL mesh
            AssemblyDoc   assyDoc          = (AssemblyDoc)ActiveSWModel;
            List <string> hiddenComponents = Common.findHiddenComponents(assyDoc.GetComponents(false));

            ActiveSWModel.Extension.SelectAll();
            ActiveSWModel.HideComponent2();
            string filename = exportFiles(mRobot.BaseLink, package, 0);

            mRobot.BaseLink.Visual.Geometry.Mesh.filename    = filename;
            mRobot.BaseLink.Collision.Geometry.Mesh.filename = filename;

            Common.showAllComponents(ActiveSWModel, hiddenComponents);
            //Writing URDF to file

            URDFWriter uWriter = new URDFWriter(windowsURDFFileName);

            mRobot.writeURDF(uWriter.writer);

            resetUserPreferences();
            progressBar.End();
        }
        public void TestFindHiddenComponens(string modelName, int expected)
        {
            ModelDoc2   doc     = OpenSWDocument(modelName);
            AssemblyDoc assyDoc = (AssemblyDoc)doc;

            Assert.Equal(expected, Common.FindHiddenComponents(assyDoc.GetComponents(false)).Count);

            SwApp.CloseAllDocuments(true);
        }
Exemple #9
0
        /// <summary>
        /// action for each of component in assemblydoc
        /// </summary>
        /// <param name="doc">assemblydoc instance</param>
        /// <param name="action">action you need todo</param>
        /// <param name="topOnly">toponly option</param>
        public static void UsingAllComponents(this  AssemblyDoc doc, Action <Component2> action, bool topOnly = false)
        {
            var comps = doc.GetComponents(topOnly) as Object[];

            foreach (Component2 comp in comps)
            {
                action(comp);
            }
        }
        public void TestShowAllComponents(string modelName)
        {
            ModelDoc2   doc     = OpenSWDocument(modelName);
            AssemblyDoc assyDoc = (AssemblyDoc)doc;

            Common.ShowAllComponents(doc, new List <string>());
            Assert.Equal(0, Common.FindHiddenComponents(assyDoc.GetComponents(false)).Count);

            SwApp.CloseAllDocuments(true);
        }
        public void TestShowComponents(string modelName)
        {
            ModelDoc2   doc     = OpenSWDocument(modelName);
            AssemblyDoc assyDoc = (AssemblyDoc)doc;

            // AssemblyDoc.GetComponentsByName only works on top level components.
            List <string>     hiddenComponentNames = Common.FindHiddenComponents(assyDoc.GetComponents(true));
            List <Component2> hiddenComponents     = new List <Component2>();

            foreach (string name in hiddenComponentNames)
            {
                Component2 hiddenComp = assyDoc.GetComponentByName(name);
                Assert.NotNull(hiddenComp);
                hiddenComponents.Add(hiddenComp);
            }
            Common.ShowComponents(doc, hiddenComponents);
            Assert.Equal(0, Common.FindHiddenComponents(assyDoc.GetComponents(true)).Count);

            SwApp.CloseAllDocuments(true);
        }
Exemple #12
0
        public static void Set_transparency(ModelDoc2 swModel, string name)
        {
            AssemblyDoc swAssembly = null;

            Component2 swComp     = null;
            ModelDoc2  swCompDoc  = null;
            bool       boolstatus = false;

            try
            {
                if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                {
                    swModel.ClearSelection2(true);
                    //  boolstatus = swModel.Extension.SelectByID2(name + "@" + docname, "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    //  SelectionMgr SwSelMgr = swModel.SelectionManager;
                    swAssembly = (AssemblyDoc)swModel;
                    var Components = swAssembly.GetComponents(false);

                    for (int i = 0; i < Components.Length; i++)
                    {
                        //swComp = swAssembly.GetComponentByName(name);
                        swComp = Components[i];
                        if (swComp != null)
                        {
                            if (swComp.Name2.Contains(name))
                            {
                                //   MessageBox.Show(name);

                                var vMatProps = swComp.MaterialPropertyValues;
                                if (vMatProps == null)
                                {
                                    swCompDoc = swComp.GetModelDoc();
                                    if (swCompDoc == null)
                                    {
                                        return;
                                    }
                                    vMatProps = swCompDoc.MaterialPropertyValues;
                                }
                                vMatProps[7] = 1; //Transparency

                                swComp.MaterialPropertyValues = vMatProps;
                                swModel.ClearSelection2(true);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        public void TestSaveSWComponentsList(string modelName)
        {
            ModelDoc2   doc     = OpenSWDocument(modelName);
            AssemblyDoc assyDoc = (AssemblyDoc)doc;

            object[]          componentObjs = assyDoc.GetComponents(false);
            List <Component2> components    = componentObjs.Cast <Component2>().ToList();
            List <byte[]>     pids          = Common.SaveSWComponents(doc, components);

            Assert.Equal(pids.Count, components.Count);

            SwApp.CloseAllDocuments(true);
        }
Exemple #14
0
        //Except for an exclusionary list, this shows all the components
        public static void ShowAllComponents(ModelDoc2 model, List <string> hiddenComponents)
        {
            AssemblyDoc       assyDoc          = (AssemblyDoc)model;
            List <Component2> componentsToShow = new List <Component2>();

            object[] varComps = assyDoc.GetComponents(false);
            foreach (Component2 comp in varComps)
            {
                if (!hiddenComponents.Contains(comp.Name2))
                {
                    componentsToShow.Add(comp);
                }
            }
            ShowComponents(model, componentsToShow);
        }
Exemple #15
0
        /// <summary>
        /// Gets the children for the document
        /// Document must be an assembly document
        /// </summary>
        /// <param name="toplevelOnly">If true only the direct children of the document</param>
        /// <param name="refresh">If collection should be refreshed</param>
        /// <returns></returns>
        public SolidworksComponents Children(bool toplevelOnly = false, bool refresh = false)
        {
            if (!IsAssemblyDoc)
            {
                return(null);
            }

            if (_children == null || refresh)
            {
                AssemblyDoc adoc = _doc as AssemblyDoc;

                if (adoc == null)
                {
                    return(null);
                }

                _children = new SolidworksComponents(adoc.GetComponents(toplevelOnly));
            }

            return(_children);
        }
Exemple #16
0
        public static List <Comp> GetColl(AssemblyDoc swAssy, SldWorks swApp)
        {
            Comp        component;
            List <Comp> coll;

            object[]              comps;
            Component2            comp;
            ModelDoc2             compDoc, swModel;
            CustomPropertyManager prpMgr;
            ModelDocExtension     swModelDocExt;
            swDocumentTypes_e     docType = swDocumentTypes_e.swDocPART;
            ConfigurationManager  confManager;
            string configuration;

            double[] aTrans;
            string   path;

            coll = new List <Comp>();

            swAssy.ResolveAllLightWeightComponents(false);

            comps = (object[])swAssy.GetComponents(true);

            for (int i = 0; i < comps.Length; i++)
            {
                component     = new Comp();
                swModel       = (ModelDoc2)swAssy;
                swModelDocExt = swModel.Extension;


                confManager   = (ConfigurationManager)swModel.ConfigurationManager;
                configuration = confManager.ActiveConfiguration.Name;
                prpMgr        = swModelDocExt.get_CustomPropertyManager(configuration);
                prpMgr.Get4("Обозначение", true, out string valOut, out _);
                component.used = valOut;

                comp = (Component2)comps[i];
                path = comp.GetPathName();
                if ((comp.GetSuppression() != (int)swComponentSuppressionState_e.swComponentSuppressed) & (comps[i] != null))
                {
                    aTrans = (double[])comp.Transform2.ArrayData;
                    if (path.ToUpper().EndsWith(".SLDASM"))
                    {
                        docType = (swDocumentTypes_e)swDocumentTypes_e.swDocASSEMBLY;
                    }
                    if (path.ToUpper().EndsWith(".SLDPRT"))
                    {
                        docType = (swDocumentTypes_e)swDocumentTypes_e.swDocPART;
                    }
                    int errs = 0, wrns = 0;
                    compDoc = swApp.OpenDoc6(path, (int)docType, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errs, ref wrns);
                    if (compDoc == null)
                    {
                        compDoc = (ModelDoc2)comp.GetModelDoc2();
                    }
                    if (compDoc == null)
                    {
                        swApp.SendMsgToUser2("Не могу загрузить " + path, 4, 2);
                        swApp.ExitApp();
                        System.Environment.Exit(0);
                    }
                    configuration = (string)comp.ReferencedConfiguration;
                    swModelDocExt = (ModelDocExtension)compDoc.Extension;
                    prpMgr        = (CustomPropertyManager)swModelDocExt.get_CustomPropertyManager(configuration);

                    prpMgr.Get4("Формат", true, out valOut, out _);
                    component.format = valOut;
                    prpMgr.Get4("Обозначение", true, out valOut, out _);
                    component.designation = valOut;
                    prpMgr.Get4("Наименование", true, out valOut, out _);
                    component.name = valOut;
                    prpMgr.Get4("Примечание", true, out valOut, out _);
                    component.note = valOut;
                    prpMgr.Get4("Раздел", true, out valOut, out _);
                    component.chapter = valOut;
                    prpMgr.Get4("Перв.Примен.", true, out valOut, out _);
                    component.included = valOut;

                    if ((component.chapter == "Стандартные изделия") | (component.chapter == "Прочие изделия"))
                    {
                        prpMgr.Get4("Документ на поставку", true, out valOut, out _);
                        component.doc  = valOut;
                        component.type = component.name.Substring(0, component.name.IndexOf((char)32));
                    }

                    component.x        = Math.Round((aTrans[9] * 1000), 2);
                    component.y        = Math.Round((aTrans[10] * 1000), 2);
                    component.z        = Math.Round((aTrans[11] * 1000), 2);
                    component.rotation = Euler(aTrans);
                    component.quantity = 1;

                    coll.Add(component);
                }
            }

            foreach (Comp k in coll)
            {
                if (k.chapter != "Сборочные единицы" & k.chapter != "Детали" & k.chapter != "Документация" & k.chapter != "Комплекты")
                {
                    k.format = "";
                }

                if (k.chapter != "Сборочные единицы" & k.chapter != "Детали" & k.chapter != "Документация" & k.chapter != "Комплекты" & k.chapter != "Стандартные изделия")
                {
                    k.designation = "";
                }

                if (k.format.Contains("*)"))
                {
                    k.note   = k.format.Substring(2);
                    k.format = "*)";
                }
            }

            return(coll);
        }
Exemple #17
0
        public static void Change_Color(ModelDoc2 swModel, string name, string color)
        {
            AssemblyDoc swAssembly = null;

            Component2 swComp       = null;
            ModelDoc2  swCompDoc    = null;
            string     compare_name = "";

            string[] Componentsubstring;
            bool     boolstatus = false;

            try
            {
                if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                {
                    swModel.ClearSelection2(true);
                    //  boolstatus = swModel.Extension.SelectByID2(name + "@" + docname, "COMPONENT", 0, 0, 0, true, 0, null, 0);
                    //  SelectionMgr SwSelMgr = swModel.SelectionManager;
                    swAssembly = (AssemblyDoc)swModel;
                    var Components = swAssembly.GetComponents(false);
                    // MessageBox.Show(Components.Length.ToString());
                    for (int i = 0; i < Components.Length; i++)
                    {
                        //swComp = swAssembly.GetComponentByName(name);
                        swComp = Components[i];
                        //  MessageBox.Show(swComp.Name2);
                        if (swComp != null)
                        {
                            if (swComp.Name2.Contains(name))
                            {
                                var vMatProps = swComp.MaterialPropertyValues;
                                if (vMatProps == null)
                                {
                                    swCompDoc = swComp.GetModelDoc();
                                    if (swCompDoc == null)
                                    {
                                        return;
                                    }
                                    vMatProps = swCompDoc.MaterialPropertyValues;
                                }
                                if (color != "")
                                {
                                    switch (color)
                                    {
                                    case "Green":
                                        vMatProps[0] = 0;      //Red
                                        vMatProps[1] = 1;      //Green
                                        vMatProps[2] = 0;      //Blue
                                        break;

                                    case "Blue":
                                        vMatProps[0] = 0;      //Red
                                        vMatProps[1] = 0;      //Green
                                        vMatProps[2] = 1;      //Blue
                                        break;

                                    case "Red":
                                        vMatProps[0] = 1;      //Red
                                        vMatProps[1] = 0;      //Green
                                        vMatProps[2] = 0;      //Blue
                                        break;

                                    default:
                                        vMatProps[0] = 1;     //Red
                                        vMatProps[1] = 0;     //Green
                                        vMatProps[2] = 0;     //Blue
                                        break;
                                    }
                                }

                                swComp.MaterialPropertyValues = vMatProps;
                                swModel.ClearSelection2(true);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }

            //  boolstatus = swDoc.Extension.SelectByID2("195599_GRLA_F_1_8_QS_8_D-3@toolbox-tutorial", "COMPONENT", 0, 0, 0, false, 0, null, 0);
        }
        public void CeilingAssyToPackingList(SldWorks swApp, string assyPath, Project objProject, int userId)
        {
            swApp.CommandInProgress = true;
            List <CeilingAccessory> celingAccessories = new List <CeilingAccessory>();

            try
            {
                //打开模型
                ModelDoc2 swModel = swApp.OpenDoc6(assyPath, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                   (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2;
                if (swModel == null)
                {
                    MessageBox.Show("模型不存在,请认真检查", "模型不存在");
                    return;
                }
                swModel.ForceRebuild3(true);
                AssemblyDoc swAssy = swModel as AssemblyDoc;
                //获取所有零部件集合
                var compList = swAssy.GetComponents(false);


                //遍历集合中的所有零部件对象
                foreach (var swComp in compList)
                {
                    //判断零件是否被压缩,不显示,封套,零件名称不是以sldprt或SLDPRT结尾,(导出发货清单无需判断可见,封套,无需判断钣金,只要没有被压缩就行了)
                    if (!swComp.IsSuppressed() && (swComp.GetPathName().EndsWith(".sldprt") || swComp.GetPathName().EndsWith(".SLDPRT")))
                    {
                        Component2 swParentComp = swComp.GetParent();
                        //总装没有父装配体
                        if (swParentComp == null)
                        {
                            ConfigurationManager swConfigMgr = swModel.ConfigurationManager;
                            Configuration        swConfig2   = swConfigMgr.ActiveConfiguration;
                            swParentComp = swConfig2.GetRootComponent3(true);
                        }

                        //判断父装配体是否可视,并且不封套(导出发货清单无需判断可见,封套,无需判断钣金,只要没有被压缩就行了)
                        if (swParentComp.Visible == 1 && !swComp.IsSuppressed())
                        {
                            //过滤需要的零件,全部转换成大写
                            if (swComp.GetPathName().Contains("["))
                            {
                                //截取关键字
                                string keyWord = swComp.GetPathName();
                                if (keyWord.Contains(")"))
                                {
                                    keyWord = keyWord.Substring(0, keyWord.IndexOf(")") + 1);
                                    keyWord = keyWord.Substring(keyWord.IndexOf("[")).ToUpper();
                                }
                                else if (keyWord.Contains("}"))
                                {
                                    keyWord = keyWord.Substring(0, keyWord.IndexOf("}") + 1);
                                    keyWord = keyWord.Substring(keyWord.IndexOf("[")).ToUpper();
                                }
                                else
                                {
                                    keyWord = keyWord.Substring(0, keyWord.IndexOf("]") + 1);
                                    keyWord = keyWord.Substring(keyWord.IndexOf("[")).ToUpper();
                                }

                                if (sheetMetaDic.ContainsKey(keyWord))
                                {
                                    sheetMetaDic[keyWord] += 1;
                                }
                                else
                                {
                                    sheetMetaDic.Add(keyWord, 1);
                                }
                            }
                        }
                    }
                }
                //关闭装配体零件
                //swApp.CloseDoc(assyPath);
                foreach (var item in sheetMetaDic)
                {
                    //获取关键字,查找对象
                    string partNo = "";
                    string length = "";
                    string width  = "";
                    if (item.Key.Contains("-"))
                    {
                        partNo = item.Key.Substring(1, item.Key.IndexOf("-") - 1);
                    }
                    else
                    {
                        partNo = item.Key.Substring(1, item.Key.IndexOf("]") - 1);
                    }
                    CeilingAccessory objCeilingAccessory = objCeilingAccessoryService.GetCeilingAccessoryByPartNo(partNo);
                    if (objCeilingAccessory == null)
                    {
                        continue;
                    }
                    //给对象赋值
                    objCeilingAccessory.PartNo    = item.Key.Substring(1, item.Key.IndexOf("]") - 1);
                    objCeilingAccessory.Quantity  = item.Value;
                    objCeilingAccessory.ProjectId = objProject.ProjectId;
                    objCeilingAccessory.UserId    = userId;
                    objCeilingAccessory.Location  = objDrawingPlanService.GetDrawingPlanByProjectId(objProject.ProjectId.ToString())[0].Item;

                    if (item.Key.Contains(")"))
                    {
                        width = item.Key.Substring(0, item.Key.IndexOf(")"));
                        width = width.Substring(width.IndexOf("(") + 1);
                        objCeilingAccessory.Width = width;
                    }
                    if (item.Key.Contains("}"))
                    {
                        length = item.Key.Substring(0, item.Key.IndexOf("}"));
                        length = length.Substring(length.IndexOf("{") + 1);
                        objCeilingAccessory.Length = length;
                    }
                    //添加list
                    ceilingAccessories.Add(objCeilingAccessory);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(assyPath + "装配体导出发货清单过程发生异常,详细:" + ex.Message);
            }
            finally
            {
                sheetMetaDic.Clear();
                swApp.CloseDoc(assyPath);        //关闭,很快
                swApp.CommandInProgress = false; //及时关闭外部命令调用,否则影响SolidWorks的使用
            }
            //基于事务ceilingCutLists提交SQLServer
            if (ceilingAccessories.Count == 0)
            {
                return;
            }
            try
            {
                if (objCeilingAccessoryService.ImportCeilingPackingListByTran(ceilingAccessories))
                {
                    ceilingAccessories.Clear();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Cutlist导入数据库失败" + ex.Message);
            }
        }
Exemple #19
0
        // Beginning method for exporting the full package
        public void ExportRobot(bool exportSTL = true)
        {
            //Setting up the progress bar
            logger.Info("Beginning the export process");
            int progressBarBound = Common.GetCount(URDFRobot.BaseLink);

            iSwApp.GetUserProgressBar(out progressBar);
            progressBar.Start(0, progressBarBound, "Creating package directories");

            //Creating package directories
            logger.Info("Creating package directories with name " + PackageName + " and save path " + SavePath);
            URDFPackage package = new URDFPackage(PackageName, SavePath);

            package.CreateDirectories();
            URDFRobot.Name = PackageName;
            string windowsURDFFileName       = package.WindowsRobotsDirectory + URDFRobot.Name + ".urdf";
            string windowsCSVFileName        = package.WindowsRobotsDirectory + URDFRobot.Name + ".csv";
            string windowsPackageXMLFileName = package.WindowsPackageDirectory + "package.xml";

            //Create CMakeLists
            logger.Info("Creating CMakeLists.txt at " + package.WindowsCMakeLists);
            package.CreateCMakeLists();

            //Create Config joint names, not sure how this is used...
            logger.Info("Creating joint names config at " + package.WindowsConfigYAML);
            package.CreateConfigYAML(URDFRobot.GetJointNames(false));

            //Creating package.xml file
            logger.Info("Creating package.xml at " + windowsPackageXMLFileName);
            PackageXMLWriter packageXMLWriter = new PackageXMLWriter(windowsPackageXMLFileName);
            PackageXML       packageXML       = new PackageXML(PackageName);

            packageXML.WriteElement(packageXMLWriter);

            //Creating RVIZ launch file
            Rviz rviz = new Rviz(PackageName, URDFRobot.Name + ".urdf");

            logger.Info("Creating RVIZ launch file in " + package.WindowsLaunchDirectory);
            rviz.WriteFiles(package.WindowsLaunchDirectory);

            //Creating Gazebo launch file
            Gazebo gazebo = new Gazebo(URDFRobot.Name, PackageName, URDFRobot.Name + ".urdf");

            logger.Info("Creating Gazebo launch file in " + package.WindowsLaunchDirectory);

            gazebo.WriteFile(package.WindowsLaunchDirectory);

            //Customizing STL preferences to how I want them
            logger.Info("Saving existing STL preferences");
            SaveUserPreferences();

            logger.Info("Modifying STL preferences");
            SetSTLExportPreferences();

            //Saving part as STL mesh
            AssemblyDoc   assyDoc          = (AssemblyDoc)ActiveSWModel;
            List <string> hiddenComponents = Common.FindHiddenComponents(assyDoc.GetComponents(false));

            logger.Info("Found " + hiddenComponents.Count + " hidden components " + String.Join(", ", hiddenComponents));
            logger.Info("Hiding all components");
            ActiveSWModel.Extension.SelectAll();
            ActiveSWModel.HideComponent2();

            bool success = false;

            try
            {
                logger.Info("Beginning individual files export");
                ExportFiles(URDFRobot.BaseLink, package, 0, exportSTL);
                success = true;
            }
            catch (Exception e)
            {
                logger.Error("An exception was thrown attempting to export the URDF", e);
            }
            finally
            {
                logger.Info("Showing all components except previously hidden components");
                Common.ShowAllComponents(ActiveSWModel, hiddenComponents);

                logger.Info("Resetting STL preferences");
                ResetUserPreferences();
            }

            if (!success)
            {
                MessageBox.Show("Exporting the URDF failed unexpectedly. Email your maintainer " +
                                "with the log file found at " + Logger.GetFileName());
                return;
            }

            logger.Info("Writing URDF file to " + windowsURDFFileName);
            URDFWriter uWriter = new URDFWriter(windowsURDFFileName);

            URDFRobot.WriteURDF(uWriter.writer);

            ImportExport.WriteRobotToCSV(URDFRobot, windowsCSVFileName);

            logger.Info("Copying log file");
            CopyLogFile(package);

            logger.Info("Resetting STL preferences");
            ResetUserPreferences();
            progressBar.End();
        }
Exemple #20
0
        /// <summary>
        /// 天花子装配导出DXF图纸
        /// </summary>
        /// <param name="swApp"></param>
        /// <param name="tree"></param>
        /// <param name="dxfPath"></param>
        /// <param name="userId"></param>
        public void CeilingAssyToDxf(SldWorks swApp, SubAssy subAssy, string dxfPath, int userId)
        {
            swApp.CommandInProgress = true;
            List <CeilingCutList> celingCutLists = new List <CeilingCutList>();
            string assyPath = subAssy.SubAssyPath;

            if (assyPath.Length == 0)
            {
                return;
            }
            try
            {
                //打开模型
                ModelDoc2 swModel = swApp.OpenDoc6(assyPath, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                   (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2;
                if (swModel == null)
                {
                    MessageBox.Show("模型不存在,请认真检查", "模型不存在");
                    return;
                }
                string modulePath = dxfPath + @"\" + subAssy.SubAssyName;
                if (!Directory.Exists(modulePath))
                {
                    Directory.CreateDirectory(modulePath);
                }
                swModel.ForceRebuild3(true);
                AssemblyDoc swAssy = swModel as AssemblyDoc;
                //获取所有零部件集合
                var compList = swAssy.GetComponents(false);
                //遍历集合中的所有零部件对象
                foreach (var swComp in compList)
                {
                    //判断零件是否被压缩,不显示,封套,零件名称不是以sldprt或SLDPRT结尾
                    if (swComp.Visible == 1 && !swComp.IsEnvelope() && !swComp.IsSuppressed() &&
                        (swComp.GetPathName().EndsWith(".sldprt") || swComp.GetPathName().EndsWith(".SLDPRT")))
                    {
                        Component2 swParentComp = swComp.GetParent();
                        //总装没有父装配体
                        if (swParentComp == null)
                        {
                            ConfigurationManager swConfigMgr = swModel.ConfigurationManager;
                            Configuration        swConfig2   = swConfigMgr.ActiveConfiguration;
                            swParentComp = swConfig2.GetRootComponent3(true);
                        }
                        //判断父装配体是否可视,并且不封套
                        if (swParentComp.Visible == 1 && !swParentComp.IsEnvelope() && !swComp.IsSuppressed())
                        {
                            PartDoc swPart = swComp.GetModelDoc2();
                            //获取文档中的额Body对象集合
                            var bodyList = swPart.GetBodies2(0, false);
                            //遍历集合中的所有Body对象,判断是否为钣金
                            foreach (var swBody in bodyList)
                            {
                                //如果是钣金则将零件地址添加到列表中
                                if (swBody.IsSheetMetal())
                                {
                                    if (sheetMetaDic.ContainsKey(swComp.GetPathName()))
                                    {
                                        sheetMetaDic[swComp.GetPathName()] += 1;
                                    }
                                    else
                                    {
                                        sheetMetaDic.Add(swComp.GetPathName(), 1);
                                    }
                                }
                            }
                        }
                    }
                }
                //关闭装配体零件
                swApp.CloseDoc(assyPath);
                //遍历钣金零件
                foreach (var sheetMeta in sheetMetaDic)
                {
                    //打开模型
                    ModelDoc2 swPart = swApp.OpenDoc6(sheetMeta.Key, (int)swDocumentTypes_e.swDocPART,
                                                      (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2;
                    Feature        swFeat    = (Feature)swPart.FirstFeature();
                    CeilingCutList cutRecord = new CeilingCutList()
                    {
                        SubAssyId = subAssy.SubAssyId,
                        Quantity  = sheetMeta.Value,
                        UserId    = userId
                    };
                    while (swFeat != null)
                    {
                        var suppStatus = swFeat.IsSuppressed2((int)swInConfigurationOpts_e.swThisConfiguration, null);
                        if (suppStatus[0] == false && swFeat.GetTypeName() == "SolidBodyFolder")
                        {
                            BodyFolder swBodyFolder = (BodyFolder)swFeat.GetSpecificFeature2();
                            swBodyFolder.SetAutomaticCutList(true);
                            swBodyFolder.SetAutomaticUpdate(true);
                            Feature SubFeat = swFeat.GetFirstSubFeature();
                            if (SubFeat != null)
                            {
                                Feature    ownerFeature    = SubFeat.GetOwnerFeature();
                                BodyFolder swSubBodyFolder = ownerFeature.GetSpecificFeature2();
                                swSubBodyFolder.UpdateCutList();
                                string val         = string.Empty;
                                string valout      = string.Empty;
                                bool   wasResolved = false;
                                bool   linkToProp  = false;
                                SubFeat.CustomPropertyManager.Get4("Bounding Box Length", false, out val, out valout);
                                cutRecord.Length = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Bounding Box Width", false, out val, out valout);
                                cutRecord.Width = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Sheet Metal Thickness", false, out val, out valout);
                                cutRecord.Thickness = Convert.ToDecimal(valout);
                                SubFeat.CustomPropertyManager.Get4("Material", false, out val, out valout);
                                cutRecord.Materials = valout;
                                swPart.GetActiveConfiguration().CustomPropertyManager.Get6("Description", false, out valout, out val, out wasResolved, out linkToProp);
                                cutRecord.PartDescription = valout;
                                cutRecord.PartNo          = swPart.GetTitle().Substring(0, swPart.GetTitle().Length - 7);
                                celingCutLists.Add(cutRecord);//将信息添加到集合中
                            }
                        }
                        swFeat = swFeat.GetNextFeature();
                    }
                    PartToDxf(swApp, swPart, modulePath);
                    //关闭零件
                    swApp.CloseDoc(sheetMeta.Key);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(assyPath + "导图过程发生异常,详细:" + ex.Message);
            }
            finally
            {
                sheetMetaDic.Clear();
                swApp.CloseDoc(assyPath);        //关闭,很快
                swApp.CommandInProgress = false; //及时关闭外部命令调用,否则影响SolidWorks的使用
            }
            //基于事务ceilingCutLists提交SQLServer
            if (celingCutLists.Count == 0)
            {
                return;
            }
            try
            {
                if (objCeilingCutListService.ImportCutList(celingCutLists))
                {
                    celingCutLists.Clear();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Cutlist导入数据库失败" + ex.Message);
            }
        }
Exemple #21
0
        public void Main()
        {
            swSuccess = false; errors = 0; warnings = 0;
            string swSourcePath = swApp.GetCurrentWorkingDirectory();
            string swExportPath = Path.Combine(swSourcePath, "IGS");

            string[] tmp = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly);

            if (Directory.Exists(swExportPath))
            {
                Directory.Delete(swExportPath, true);
            }

            Directory.CreateDirectory(swExportPath);
            ModelDoc2 swModel = swApp.ActiveDoc as ModelDoc2;

            AssemblyDoc swAssem = (AssemblyDoc)swModel;

            #region TopLevel
            string igsFileName = MakeFileName(swModel.Extension.Document.GetTitle());
            swModel.Extension.SaveAs(Path.Combine(swExportPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings);
            //PrintSaveResults();
            #endregion TopLevel

            #region Subassemblies
            string swExportSubPath = Path.Combine(swExportPath, "Subassemblies");
            Directory.CreateDirectory(swExportSubPath);
            object[]  objComps = (object[])swAssem.GetComponents(true);
            ModelDoc2 igsModel;

            foreach (object obj in objComps)
            {
                swComponent = obj as Component2;
                Debug.WriteLine(String.Format("Working on {0}.. \n\t {1}", swComponent.Name2, swComponent.GetPathName()));
                igsModel = swApp.OpenDoc6(swComponent.GetPathName(), (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings);
                swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors);
                igsFileName = MakeFileName(igsModel.Extension.Document.GetTitle());
                igsModel.Extension.SaveAs(Path.Combine(swExportSubPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings);
                swApp.CloseDoc(igsModel.GetTitle());
            }
            #endregion Subassemblies

            #region Parts
            string swExportPartPath = Path.Combine(swExportPath, "Parts");
            Directory.CreateDirectory(swExportPartPath);
            string[] swPartFiles = Directory.GetFiles(swSourcePath, "*.SLDPRT", SearchOption.TopDirectoryOnly);
            foreach (string partFile in swPartFiles)
            {
                try
                {
                    igsModel = swApp.OpenDoc6(partFile, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly, null, ref errors, ref warnings);
                    swApp.ActivateDoc2(igsModel.GetTitle(), true, ref errors);
                    string[] swConfigs     = (string[])igsModel.GetConfigurationNames();
                    int      swConfigCount = igsModel.GetConfigurationCount();
                    string   swConfigFilename;

                    for (int i = 0; i < swConfigCount; i++)
                    {
                        igsModel.ShowConfiguration2(swConfigs[i]);
                        swConfigFilename = igsModel.Extension.Document.GetTitle();
                        if (swConfigCount > 1)
                        {
                            swConfigFilename += String.Format("-CFG{0}", (i + 1).ToString());
                        }
                        igsFileName = MakeFileName(swConfigFilename);
                        igsModel.Extension.SaveAs(Path.Combine(swExportPartPath, igsFileName), (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Copy, null, ref errors, ref warnings);
                    }
                    swApp.CloseDoc(igsModel.GetTitle());
                }
                catch (NullReferenceException e)
                {
                    Debug.WriteLine(e.Message);
                }
            }
            #endregion Parts

            string timeFilename = Path.Combine(swExportPath, "Timestamp.txt");

            using (StreamWriter swTimeStamper = new StreamWriter(timeFilename))
            {
                swTimeStamper.WriteLine("Exported on {0} at {1}", System.DateTime.Now.ToShortDateString(), System.DateTime.Now.ToShortTimeString());
                swTimeStamper.Flush();
            }
        }
Exemple #22
0
        // Beginning method for exporting the full package
        public void exportRobot()
        {
            //Setting up the progress bar
            System.Diagnostics.Debug.WriteLine("Beginning the export process");
            int progressBarBound = Common.getCount(mRobot.BaseLink);

            progressBar.Start(0, progressBarBound, "Creating package directories");

            //Creating package directories
            System.Diagnostics.Debug.WriteLine("Creating package directories");
            URDFPackage package = new URDFPackage(mPackageName, mSavePath);

            package.createDirectories();
            mRobot.name = mPackageName;
            string windowsURDFFileName       = package.WindowsRobotsDirectory + mRobot.name + ".urdf";
            string windowsPackageXMLFileName = package.WindowsPackageDirectory + "package.xml";

            //Create CMakeLists
            System.Diagnostics.Debug.WriteLine("Creating CMakeLists.txt at " + package.WindowsCMakeLists);
            package.createCMakeLists();

            //Create Config joint names, not sure how this is used...
            System.Diagnostics.Debug.WriteLine("Creating joint names config at " + package.WindowsConfigYAML);
            package.createConfigYAML(mRobot.getJointNames(false));

            //Creating package.xml file
            PackageXMLWriter packageXMLWriter = new PackageXMLWriter(windowsPackageXMLFileName);
            PackageXML       packageXML       = new PackageXML(mPackageName);

            packageXML.writeElement(packageXMLWriter);

            //Creating RVIZ launch file
            Rviz rviz = new Rviz(mPackageName, mRobot.name + ".urdf");

            System.Diagnostics.Debug.WriteLine("Creating RVIZ launch file");
            rviz.writeFiles(package.WindowsLaunchDirectory);

            //Creating Gazebo launch file
            System.Diagnostics.Debug.WriteLine("Creating Gazebo launch file");
            Gazebo gazebo = new Gazebo(this.mRobot.name, this.mPackageName, mRobot.name + ".urdf");

            gazebo.writeFile(package.WindowsLaunchDirectory);


            //Customizing STL preferences to how I want them
            saveUserPreferences();
            setSTLExportPreferences();

            //Saving part as STL mesh
            AssemblyDoc   assyDoc          = (AssemblyDoc)ActiveSWModel;
            List <string> hiddenComponents = Common.findHiddenComponents(assyDoc.GetComponents(false));

            ActiveSWModel.Extension.SelectAll();
            ActiveSWModel.HideComponent2();
            string filename = exportFiles(mRobot.BaseLink, package, 0);

            mRobot.BaseLink.Visual.Geometry.Mesh.filename    = filename;
            mRobot.BaseLink.Collision.Geometry.Mesh.filename = filename;

            Common.showAllComponents(ActiveSWModel, hiddenComponents);
            //Writing URDF to file

            URDFWriter uWriter = new URDFWriter(windowsURDFFileName);

            mRobot.writeURDF(uWriter.writer);

            resetUserPreferences();
            progressBar.End();
        }