/// <summary> /// 递归创建装配树 /// </summary> /// <param name="component"></param> /// <param name="swComponet"></param> private static void CreateTree(Component2 component, ref SWComponent swComponent) { if (component == null) { return; } /////////复制组件相关信息/////////// //名称 swComponent.Name = component.Name2; //是否根组件 swComponent.IsRoot = component.IsRoot(); //提取配合,存放在RootComponent节点 //if (swComponent.IsRoot) { swComponent.Mates = GetSWMatesOfRootComponent(component); //} //包围盒 double[] box = null; try { box = component.GetBox(false, false); } catch (Exception e) { //发生异常,说明该组件(根组件)没有包围盒 box = null; } if (box == null) { swComponent.BoundingBox = CreateSWBoundingBox(box); } else { swComponent.BoundingBox = new SWBoundingBox(); } //提取Body object bodyInfo; object[] bodies = component.GetBodies3((int)swBodyType_e.swSolidBody, out bodyInfo); if (bodies != null) { foreach (object objBody in bodies) { swComponent.Bodies.Add(CreateSWBody((Body2)objBody)); } } //继续遍历 object[] subComponents = component.GetChildren(); if (subComponents != null) { foreach (object obj in subComponents) { SWComponent newComponent = new SWComponent(); CreateTree((Component2)obj, ref newComponent); swComponent.SubComponents.Add(newComponent); } } }
/// <summary> /// 递归遍历装配体方法 /// </summary> /// <param name="swComp"></param> /// <param name="nLevel"></param> private void TraverseAssembly(Component2 swComp, int nLevel) { object[] vChildComp; Component2 swChildComp; vChildComp = (object[])swComp.GetChildren(); for (int i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; AssemblyDoc swTempModel = (AssemblyDoc)swChildComp; TraverseAssembly(swChildComp, nLevel + 1); //选中要替换掉的零件 SelectData seldate = ((SelectionMgr)swModel.SelectionManager).CreateSelectData(); swChildComp.Select4(false, seldate, false); //替换零部件 swTempModel.ReplaceComponents("", "", true, true);//零件地址 } //object[] compNum = null; //int idex=1; ////_swApp = (SldWorks)MD_SW_ConnectSW.ConnectSW.iSwApp; //compNum = swApp.GetDocumentDependencies2(parentPath, false, false, false); //if (compNum != null) //{ // while (idex <= compNum.GetUpperBound(0)) // { // string path = compNum[idex].ToString(); // idex++; // } //} }
public void TraverseComponent(Component2 swComp, long nLevel) { object[] vChildComp; Component2 swChildComp; string sPadStr = " "; long i = 0; for (i = 0; i <= nLevel - 1; i++) { sPadStr = sPadStr + " "; } vChildComp = (object[])swComp.GetChildren(); for (i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; //TraverseComponentFeatures(swChildComp, nLevel); htComponent.Add(swChildComp.Name, swChildComp.GetPathName()); TraverseComponent(swChildComp, nLevel + 1); } }
public void TraverseComponent(Component2 swComp, long nLevel) { object[] vChildComp; Component2 swChildComp; string sPadStr = " "; long i = 0; for (i = 0; i <= nLevel - 1; i++) { sPadStr = sPadStr + " "; } vChildComp = (object[])swComp.GetChildren(); for (i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; //获得零件 string aa = (sPadStr + "+" + swChildComp.Name2 + " <" + swChildComp.ReferencedConfiguration + ">"); TraverseComponentFeatures(swChildComp, nLevel); TraverseComponent(swChildComp, nLevel + 1); } }
void AddIds(Component2 component, Dictionary <Tuple <object, string, long?>, int> ids, ref int id) { if (component.IsHidden(true)) { return; } var modelDoc = (IModelDoc2)component.GetModelDoc2(); var tuple = GetTuple(component); if (ids.ContainsKey(tuple)) { return; } ids[tuple] = id++; var assembly = modelDoc as IAssemblyDoc; if (assembly != null) { foreach (Component2 c in (object[])component.GetChildren()) { AddIds(c, ids, ref id); } } }
public void PurgeUnused() { ModelDoc2 swModel = iSwApp.ActiveDoc; Configuration swConf = swModel.GetActiveConfiguration(); var cfgNames = swModel.GetConfigurationNames(); ConfigurationManager swCfgMgr = swModel.ConfigurationManager; Component2 swRootComp = swConf.GetRootComponent3(true); Boolean bRet = true; int i; string configName = ""; object ConfigValues = new object(); object ConfigParams = new object(); var vChildComp = swRootComp.GetChildren(); for (i = 0; i <= vChildComp.GetUpperBound(0); i++) { Component2 swChildComp = vChildComp[i]; bRet = swCfgMgr.GetConfigurationParams(configName, out ConfigParams, out ConfigValues); //if (swChildComp.GetSuppression() == 0) //{ // MessageBox.Show(swChildComp.Name2 + " is suppressed"); // swChildComp.Select(true); // swModel.EditDelete(); //} } }
public static void UsingChildren(this Component2 comp, Action <Component2> action) { var child = comp.GetChildren() as Component2[]; if (child != null) { foreach (var item in child) { action(item); } } }
private void traverse(Component2 comp) { object[] childrens = comp.GetChildren(); foreach (Component2 child in childrens) { traverse(child); } ModelDoc2 mdocChild = comp.GetModelDoc2(); if (mdocChild.GetType() == 1) { // Bezeichnung kann über 2 Möglichkeiten erfolgen // Dateiname (mit GetFileName wird nur der Dateiname aus einem Dateipfad extrahiert string entry = System.IO.Path.GetFileName(comp.GetPathName()); // oder string entry2 = comp.Name2; //entfernen der 2 hinteren Zeichen im String entry2 = entry2.Remove(entry2.Length - 2); int Row = 0; // überprüfen, ob aktueller Eintrag bereits vorhanden ist, wenn ja Zeilen-Index speichern for (int i = 2; i < index; i++) { if ((string)exlSheet.Cells[i, 3].Value2 == entry) { Row = i; } } // wenn Zeilen Index gesetzt wurde, Wert für Anzahl aus Zeile lesen und um 1 erhöhen // erhöhten Wert in Zelle schreiben if (Row > 0) { double newCount = (double)exlSheet.Cells[Row, 1].Value2 + 1; exlSheet.Cells[Row, 1] = newCount; } else { // Wenn ZeilenIndex nicht gesetzt wurde, neuen Dateipfad exlSheet.Cells[index, 1] = 1; exlSheet.Cells[index, 2] = "Stück"; exlSheet.Cells[index, 3] = entry; lb_output.Items.Add(entry); index++; } } }
/// <summary> /// 遍历装配体零件 /// </summary> /// <param name="swComp"></param> /// <param name="nLevel"></param> public static void TraverseCompXform(Component2 swComp, long nLevel, bool setcolor = false) { object[] vChild; Component2 swChildComp; string sPadStr = ""; MathTransform swCompXform; long i; for (i = 0; i < nLevel; i++) { sPadStr = sPadStr + " "; } swCompXform = swComp.Transform2; if (swCompXform != null) { ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc2(); if (swModel != null) { Debug.Print("Loading:" + swComp.Name2); if (swModel is PartDoc) { var partDoc = (PartDoc)swModel; var vBodies = (Object[])partDoc.GetBodies2((int)swBodyType_e.swAllBodies, true); for (int index = 0; index < vBodies.Length; index++) { AllBodies.Add((Body2)vBodies[index]); } } } } else { ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc2(); } vChild = (object[])swComp.GetChildren(); for (i = 0; i <= (vChild.Length - 1); i++) { swChildComp = (Component2)vChild[i]; TraverseCompXform(swChildComp, nLevel + 1, setcolor); } }
public static void KL_TraversAssemblyComponents(Component2 swComponent2, int nLevel, SldWorks swApplication) { for (var i = 0; i < nLevel; i++) { if (swComponent2 == null) { continue; } var swChildrenComponent = (Array)swComponent2.GetChildren(); foreach (Component2 component2 in swChildrenComponent) { KL_TraversAssemblyComponents(component2, nLevel + 1, swApplication); KL_GetTransformsOfAssemblyComponents(component2, swApplication); } } }
private void GetChildren(JSolidworksAsemble _JswDoc) { //this.Parts.Add((JSolidworksAsemble)_JswDoc); //先将此文件加入到子零部件列表中 //如果是装配体 if (_JswDoc.swDoc == null) { _JswDoc.Load(); } Configuration swConf = (Configuration)_JswDoc.swDoc.GetActiveConfiguration(); if (swConf == null) { return; } Component2 swRootComp = (Component2)swConf.GetRootComponent(); if (swRootComp == null) { return; } else { object[] Children_List = swRootComp.GetChildren(); foreach (object _doc in Children_List) { ModelDoc2 t_doc = ((Component2)_doc).GetModelDoc2(); if (t_doc.GetType() == (int)swDocumentTypes_e.swDocPART) { //子件是 string _Path = t_doc.GetPathName(); JSolidworksPart JPart = new JSolidworksPart(t_doc.GetPathName()); JPart.Load(); _JswDoc.Parts.Add(JPart); } else { if (t_doc.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { JSolidworksAsemble JPart = new JSolidworksAsemble(t_doc.GetPathName()); JPart.Load(); _JswDoc.Parts.Add(JPart); } } } } return; }
private Component2 findComponent(Component2 swComp, String searchFor) { object[] vChildComp; Component2 swChildComp; int i; vChildComp = (object[])swComp.GetChildren(); for (i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; if (swChildComp.Name2.Contains(searchFor)) { return(swChildComp); } } return(null); }
public void GetParametersFromAssembly(ModelDoc2 doc, ref List <ModelDoc2> Parameters_List) { if (doc == null) { return; } int docType = doc.GetType(); if (docType == (int)swDocumentTypes_e.swDocPART) { Parameters_List.Add(doc); return; } //object haha = doc.get; Configuration swConf = (Configuration)doc.GetActiveConfiguration(); if (swConf == null) { return; } Component2 swRootComp = (Component2)swConf.GetRootComponent(); int swRootComp1 = (int)swConf.GetParameterCount(); if (swRootComp1 == null) { return; } else { Parameters_List.Add(doc); object[] haha = swRootComp.GetChildren(); foreach (object hh in haha) { Component2 hh2 = (Component2)hh; ModelDoc2 hhhh = hh2.GetModelDoc2(); GetParametersFromAssembly(hhhh, ref Parameters_List); } } }
private List <Component2> getAllComponents() { List <Component2> allComponents = new List <Component2>(); Component2 swComp = swConf.GetRootComponent3(true); object[] vChildComp; Component2 swChildComp; int i; vChildComp = (object[])swComp.GetChildren(); for (i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; if (Utilities.isBody(swChildComp)) { allComponents.Add(swChildComp); } } return(allComponents); }
public void TraverseComponent(Component2 swComp) { string name = swComp.Name2; object[] vChildComp; Component2 swChildComp; vChildComp = (object[])swComp.GetChildren(); for (int i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; TraverseComponent(swChildComp); } try { ModelDoc2 compMdl = (ModelDoc2)swComp.GetModelDoc2(); if (compMdl != null) { string mdlName = Path.GetFileName(compMdl.GetPathName()); string refCfg = swComp.ReferencedConfiguration; string newConfig = GetNewConfig(mdlName, refCfg); if (!string.IsNullOrEmpty(newConfig)) { ModifyComponent comp = new ModifyComponent(swComp, refCfg, newConfig); comp.Change(); swComp.Select(false); AssemblyDoc assem = (AssemblyDoc)iSwApp.ActiveDoc; assem.CompConfigProperties4(2, 0, true, true, newConfig, false); } } } catch { } }
private List <ComponentIdentifier> getAllOurComponents() { List <ComponentIdentifier> found = new List <ComponentIdentifier>(); Component2 swComp = swConf.GetRootComponent3(true); object[] vChildComp; Component2 swChildComp; int i; vChildComp = (object[])swComp.GetChildren(); for (i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; foreach (String compName in ourComponentNames) { if (swChildComp.Name2.StartsWith(compName) && !swChildComp.Equals(mainBody) && !swChildComp.IsSuppressed()) { ComponentIdentifier ci = new ComponentIdentifier(swChildComp); found.Add(ci); } } } return(found); }
/// <summary> /// 获取组件的子组件 /// </summary> /// <param name="comp"></param> /// <returns></returns> public static IEnumerable <Component2> GetChildrenEx(this Component2 comp) { return(comp.GetChildren().CastObj <object[]>().Cast <Component2>()); }
public void DumpTraverseComponent(Component2 swComp, long nLevel, ref string asciitext) { // *** SCAN THE COMPONENT FEATURES if (!swComp.IsRoot()) { Feature swFeat; swFeat = (Feature)swComp.FirstFeature(); DumpTraverseFeatures(swFeat, nLevel, ref asciitext); } // *** RECURSIVE SCAN CHILDREN COMPONENTS object[] vChildComp; Component2 swChildComp; string sPadStr = " "; long i = 0; for (i = 0; i <= nLevel - 1; i++) { sPadStr = sPadStr + " "; } vChildComp = (object[])swComp.GetChildren(); for (i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; asciitext += sPadStr + "+" + swChildComp.Name2 + " <" + swChildComp.ReferencedConfiguration + ">" +"\n"; // DumpTraverseComponentFeatures(swChildComp, nLevel, ref asciitext); DumpTraverseComponent(swChildComp, nLevel + 1, ref asciitext); } }
public void PythonTraverseComponent_for_visualizationshapes(Component2 swComp, long nLevel, ref string asciitext, int nbody, ref int nvisshape, Component2 chbody_comp) { CultureInfo bz = new CultureInfo("en-BZ"); object[] bodies; object bodyInfo; bodies = (object[])swComp.GetBodies3((int)swBodyType_e.swAllBodies, out bodyInfo); if (bodies != null) if (bodies.Length > 0) { // Export the component shape to a .OBJ file representing its SW body(s) nvisshape += 1; string bodyname = "body_" + nbody; string shapename = "body_" + nbody + "_" + nvisshape; string obj_filename = this.save_dir_shapes + "\\" + shapename + ".obj"; ModelDoc2 swCompModel = (ModelDoc2)swComp.GetModelDoc(); if (!this.saved_shapes.ContainsKey(swCompModel.GetPathName())) { try { FileStream ostream = new FileStream(obj_filename, FileMode.Create, FileAccess.ReadWrite); StreamWriter writer = new StreamWriter(ostream); //, new UnicodeEncoding()); string asciiobj = ""; if (this.swProgress != null) this.swProgress.UpdateTitle("Exporting " + swComp.Name2 + " (tesselate) ..."); // Write the OBJ converted visualization shapes: TesselateToObj.Convert(swComp, ref asciiobj, this.checkBox_saveUV.Checked, ref this.swProgress); writer.Write(asciiobj); writer.Flush(); ostream.Close(); this.saved_shapes.Add(swCompModel.GetPathName(), shapename); } catch (Exception) { System.Windows.Forms.MessageBox.Show("Cannot write to file: " + obj_filename); } } else { // reuse the already-saved shape name shapename = (String)saved_shapes[swCompModel.GetPathName()]; } asciitext += String.Format(bz, "\n# Visualization shape \n", bodyname); asciitext += String.Format(bz, "{0}_shape = chrono.ChObjShapeFile() \n", shapename); asciitext += String.Format(bz, "{0}_shape.SetFilename(shapes_dir +'{0}.obj') \n", shapename); object foo = null; double[] vMatProperties = (double[])swComp.GetMaterialPropertyValues2((int)swInConfigurationOpts_e.swThisConfiguration, foo); if (vMatProperties != null) if (vMatProperties[0] != -1) { asciitext += String.Format(bz, "{0}_shape.SetColor(chrono.ChColor({1},{2},{3})) \n", shapename, vMatProperties[0], vMatProperties[1], vMatProperties[2]); asciitext += String.Format(bz, "{0}_shape.SetFading({1}) \n", shapename, vMatProperties[7]); } MathTransform absframe_chbody = chbody_comp.GetTotalTransform(true); MathTransform absframe_shape = swComp.GetTotalTransform(true); MathTransform absframe_chbody_inv = absframe_chbody.IInverse(); MathTransform relframe_shape = absframe_shape.IMultiply(absframe_chbody_inv); // row-ordered transf. -> reverse mult.order! double[] amatr = (double[])relframe_shape.ArrayData; double[] quat = GetQuaternionFromMatrix(ref relframe_shape); asciitext += String.Format(bz, "{0}_level = chrono.ChAssetLevel() \n", shapename); asciitext += String.Format(bz, "{0}_level.GetFrame().SetPos(chrono.ChVectorD({1},{2},{3})) \n", shapename, amatr[9] *ChScale.L, amatr[10]*ChScale.L, amatr[11]*ChScale.L); asciitext += String.Format(bz, "{0}_level.GetFrame().SetRot(chrono.ChQuaternionD({1},{2},{3},{4})) \n", shapename, quat[0], quat[1], quat[2], quat[3]); asciitext += String.Format(bz, "{0}_level.GetAssets().push_back({0}_shape) \n", shapename); asciitext += String.Format(bz, "{0}.GetAssets().push_back({1}_level) \n", bodyname, shapename); } // Recursive scan of subcomponents Component2 swChildComp; object[] vChildComp = (object[])swComp.GetChildren(); for (long i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; if (swChildComp.Visible == (int)swComponentVisibilityState_e.swComponentVisible) PythonTraverseComponent_for_visualizationshapes(swChildComp, nLevel + 1, ref asciitext, nbody, ref nvisshape, chbody_comp); } }
public void PythonTraverseComponent_for_massbodies(Component2 swComp, ref object[] obodies, ref int addedb) { // Add bodies of this component to the list object[] bodies; object bodyInfo; bodies = (object[])swComp.GetBodies3((int)swBodyType_e.swAllBodies, out bodyInfo); if (bodies != null) { // note: some bodies might be collision shapes and must not enter the mass computation: for (int ib = 0; ib < bodies.Length; ib++) { Body2 abody = (Body2)bodies[ib]; if (!(abody.Name.StartsWith("COLL."))) { obodies[addedb] = bodies[ib]; addedb += 1; } } } // Recursive scan of subcomponents Component2 swChildComp; object[] vChildComp = (object[])swComp.GetChildren(); for (long i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; PythonTraverseComponent_for_massbodies(swChildComp, ref obodies, ref addedb); } }
/// <summary> /// Adds all sub bodies in component comp to bodies /// </summary> /// <param name="bodies">List to add bodies to</param> /// <param name="comp">Component2 that has subcomponments</param> private void GetSubBodies(List<Body2> bodies, Component2 comp) { object[] childrenComps = (object[])comp.GetChildren(); if (childrenComps.Length>0) { object obj; foreach (Component2 c in childrenComps) { if (((object[])c.GetChildren()).Length>0) { GetSubBodies(bodies, c); } else { var tempBodies = c.GetBodies3((int)swBodyType_e.swSolidBody, out obj); if (tempBodies != null) // handles for surface bodies { foreach (Object b in tempBodies) { bodies.Add((Body2)b); } } } } } }
/// <summary> /// gets all subComponents if a component is a subassembly /// </summary> /// <param name="comp">The component to find its subComponents of</param> /// <param name="comps">A List to store the subComponents in</param> private void GetSubComponents(Component2 comp, List<Component2> comps) { object[] childrenComps = (object[])comp.GetChildren(); if (childrenComps.Length>0) { foreach (Component2 c in childrenComps) { if (((object[])c.GetChildren()).Length > 0) { GetSubComponents(c, comps); } else { comps.Add(c); } } } }
public void PythonTraverseComponent_for_collshapes(Component2 swComp, long nLevel, ref string asciitext, int nbody, ref MathTransform chbodytransform, ref bool found_collisionshapes, Component2 swCompBase) { // Look if component contains collision shapes (customized SW solid bodies): PythonTraverseFeatures_for_collshapes(swComp, nLevel, ref asciitext, nbody, ref chbodytransform, ref found_collisionshapes, swCompBase); // Recursive scan of subcomponents Component2 swChildComp; object[] vChildComp = (object[])swComp.GetChildren(); for (long i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; PythonTraverseComponent_for_collshapes(swChildComp, nLevel + 1, ref asciitext, nbody, ref chbodytransform, ref found_collisionshapes, swCompBase); } }
public void PythonTraverseComponent_for_ChBody(Component2 swComp, long nLevel, ref string asciitext, int nbody) { CultureInfo bz = new CultureInfo("en-BZ"); object[] vmyChildComp = (object[])swComp.GetChildren(); bool found_chbody_equivalent = false; if (nLevel > 1) if (nbody == -1) if ((swComp.Solving == (int)swComponentSolvingOption_e.swComponentRigidSolving) || (vmyChildComp.Length == 0)) { // OK! this is a 'leaf' of the tree of ChBody equivalents (a SDW subassebly or part) found_chbody_equivalent = true; this.num_comp++; nbody = this.num_comp; // mark the rest of recursion as 'n-th body found' if (this.swProgress != null) { this.swProgress.UpdateTitle("Exporting " + swComp.Name2 + " ..."); this.swProgress.UpdateProgress(this.num_comp % 5); } // fetch SW attribute with Chrono parameters SolidWorks.Interop.sldworks.Attribute myattr = (SolidWorks.Interop.sldworks.Attribute)swComp.FindAttribute(this.mSWintegration.defattr_chbody, 0); MathTransform chbodytransform = swComp.GetTotalTransform(true); double[] amatr; amatr = (double[])chbodytransform.ArrayData; string bodyname = "body_" + this.num_comp; // Write create body asciitext += "# Rigid body part\n"; asciitext += bodyname + "= chrono.ChBodyAuxRef()" + "\n"; // Write name asciitext += bodyname + ".SetName('" + swComp.Name2 + "')" + "\n"; // Write position asciitext += bodyname + ".SetPos(chrono.ChVectorD(" + (amatr[9] * ChScale.L).ToString("g", bz) + "," + (amatr[10]* ChScale.L).ToString("g", bz) + "," + (amatr[11]* ChScale.L).ToString("g", bz) + "))" + "\n"; // Write rotation double[] quat = GetQuaternionFromMatrix(ref chbodytransform); asciitext += String.Format(bz, "{0}.SetRot(chrono.ChQuaternionD({1:g},{2:g},{3:g},{4:g}))\n", bodyname, quat[0], quat[1], quat[2], quat[3]); // Compute mass int nvalid_bodies = 0; PythonTraverseComponent_for_countingmassbodies(swComp, ref nvalid_bodies); int addedb = 0; object[] bodies_nocollshapes = new object[nvalid_bodies]; PythonTraverseComponent_for_massbodies(swComp, ref bodies_nocollshapes, ref addedb); MassProperty swMass; swMass = (MassProperty)swComp.IGetModelDoc().Extension.CreateMassProperty(); bool boolstatus = false; boolstatus = swMass.AddBodies((object[])bodies_nocollshapes); swMass.SetCoordinateSystem(chbodytransform); swMass.UseSystemUnits = true; //note: do not set here the COG-to-REF position because here SW express it in absolute coords // double cogX = ((double[])swMass.CenterOfMass)[0]; // double cogY = ((double[])swMass.CenterOfMass)[1]; // double cogZ = ((double[])swMass.CenterOfMass)[2]; double mass = swMass.Mass; double[] Itensor = (double[])swMass.GetMomentOfInertia((int)swMassPropertyMoment_e.swMassPropertyMomentAboutCenterOfMass); double Ixx = Itensor[0]; double Iyy = Itensor[4]; double Izz = Itensor[8]; double Ixy = Itensor[1]; double Izx = Itensor[2]; double Iyz = Itensor[5]; MassProperty swMassb; swMassb = (MassProperty)swComp.IGetModelDoc().Extension.CreateMassProperty(); bool boolstatusb = false; boolstatusb = swMassb.AddBodies(bodies_nocollshapes); swMassb.UseSystemUnits = true; double cogXb = ((double[])swMassb.CenterOfMass)[0]; double cogYb = ((double[])swMassb.CenterOfMass)[1]; double cogZb = ((double[])swMassb.CenterOfMass)[2]; asciitext += String.Format(bz, "{0}.SetMass({1:g})\n", bodyname, mass * ChScale.M); // Write inertia tensor asciitext += String.Format(bz, "{0}.SetInertiaXX(chrono.ChVectorD({1:g},{2:g},{3:g}))\n", bodyname, Ixx * ChScale.M * ChScale.L * ChScale.L, Iyy * ChScale.M * ChScale.L * ChScale.L, Izz * ChScale.M * ChScale.L * ChScale.L); // Note: C::E assumes that's up to you to put a 'minus' sign in values of Ixy, Iyz, Izx asciitext += String.Format(bz, "{0}.SetInertiaXY(chrono.ChVectorD({1:g},{2:g},{3:g}))\n", bodyname, -Ixy * ChScale.M * ChScale.L * ChScale.L, -Izx * ChScale.M * ChScale.L * ChScale.L, -Iyz * ChScale.M * ChScale.L * ChScale.L); // Write the position of the COG respect to the REF asciitext += String.Format(bz, "{0}.SetFrame_COG_to_REF(chrono.ChFrameD(chrono.ChVectorD({1:g},{2:g},{3:g}),chrono.ChQuaternionD(1,0,0,0)))\n", bodyname, cogXb * ChScale.L, cogYb * ChScale.L, cogZb * ChScale.L); // Write 'fixed' state if (swComp.IsFixed()) asciitext += String.Format(bz, "{0}.SetBodyFixed(True)\n", bodyname); // Write shapes (saving also Wavefront files .obj) if (this.checkBox_surfaces.Checked) { int nvisshape = 0; if (swComp.Visible == (int)swComponentVisibilityState_e.swComponentVisible) PythonTraverseComponent_for_visualizationshapes(swComp, nLevel, ref asciitext, nbody, ref nvisshape, swComp); } // Write markers (SW coordsystems) contained in this component or subcomponents // if any. PythonTraverseComponent_for_markers(swComp, nLevel, ref asciitext, nbody); // Write collision shapes (customized SW solid bodies) contained in this component or subcomponents // if any. bool param_collide = true; if (myattr != null) param_collide = Convert.ToBoolean(((Parameter)myattr.GetParameter("collision_on")).GetDoubleValue()); if (param_collide) { bool found_collisionshapes = false; PythonTraverseComponent_for_collshapes(swComp, nLevel, ref asciitext, nbody, ref chbodytransform, ref found_collisionshapes, swComp); if (found_collisionshapes) { asciitext += String.Format(bz, "{0}.GetCollisionModel().BuildModel()\n", bodyname); asciitext += String.Format(bz, "{0}.SetCollide(True)\n", bodyname); } } // Insert to a list of exported items asciitext += String.Format(bz, "\n" +"exported_items.append({0})\n", bodyname); // End writing body in Python- asciitext += "\n\n\n"; } // end if ChBody equivalent (tree leaf or non-flexible assembly) // Things to do also for sub-components of 'non flexible' assemblies: // // store in hashtable, will be useful later when adding constraints if ((nLevel > 1) && (nbody != -1)) try { string bodyname = "body_" + this.num_comp; ModelDocExtension swModelDocExt = default(ModelDocExtension); ModelDoc2 swModel = (ModelDoc2)this.mSWApplication.ActiveDoc; //if (swModel != null) swModelDocExt = swModel.Extension; this.saved_parts.Add(swModelDocExt.GetPersistReference3(swComp), bodyname); } catch { System.Windows.Forms.MessageBox.Show("Cannot add part to hashtable?"); } // Traverse all children, proceeding to subassemblies and parts, if any // object[] vChildComp; Component2 swChildComp; vChildComp = (object[])swComp.GetChildren(); for (long i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; PythonTraverseComponent_for_ChBody(swChildComp, nLevel + 1, ref asciitext, nbody); } }
private static void DeleteCavities(Component2 swComp) { var childComps = (object[])swComp.GetChildren(); foreach (var oChildComp in childComps) { var childComp = (Component2)oChildComp; var swCompModel = (ModelDoc2)childComp.GetModelDoc(); if (swCompModel != null) { var swModExt = swCompModel.Extension; Feature swFeat = swCompModel.FirstFeature(); int i = 0; while (swFeat != null) { if (swFeat.GetTypeName2() == "Cavity") { swFeat.Select2(true, i); i++; } swFeat = swFeat.IGetNextFeature(); } swModExt.DeleteSelection2((int)swDeleteSelectionOptions_e.swDelete_Absorbed); DeleteCavities(childComp); } } }
private static Feature FindEdge(Component2 inComponent, string featureName) { var childComps = (object[])inComponent.GetChildren(); foreach (var oChildComp in childComps) { var childComp = (Component2)oChildComp; var swCompModel = (ModelDoc2)childComp.GetModelDoc(); if (swCompModel != null) { Feature swFeat = swCompModel.FirstFeature(); while (swFeat != null) { if (swFeat.Name == featureName) //"OffsetRefSurface" swFeat.GetTypeName2() == "ICE" && { return swFeat; } swFeat = swFeat.IGetNextFeature(); } FindEdge(childComp, featureName); } } return null; }
private void btnAssembly_Click_1(object sender, EventArgs e) { if (swApp == null) { ConnectSw(); } List <string> fileAssem1 = new List <string>(); //文件路径集合 int Rows = this.lBoxFile3.Items.Count; //行的数量 if (Rows == 0) { MessageBox.Show("请选择装配零部件!"); return; } string FaLan = string.Empty; //电机法兰路径 string InnerGearPath = string.Empty; //内齿轮路径 string standPath = string.Empty; //机座路径 string subAssemPath = string.Empty; //子装配体路径 foreach (object item in lBoxFile3.Items) { fileAssem1.Add(item.ToString()); //界面中的文件 } foreach (string file in fileAssem1) //遍历文件获取路径 { string fileName = file.Substring(file.LastIndexOf("\\") + 1); if (fileName.Contains("法兰")) { FaLan = file; } if (fileName.Contains("内齿")) { InnerGearPath = file; } if (fileName.Contains("机座")) { standPath = file; } if (fileName.Contains("子装配")) { subAssemPath = file; } } swModel = (ModelDoc2)swApp.OpenDoc6(_exePath + "PrtAndAsmTemp\\总装配体.sldasm", (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); //遍历装配体选择零部件 swModel = (ModelDoc2)swApp.ActiveDoc; swConfMgr = (SolidWorks.Interop.sldworks.ConfigurationManager)swModel.ConfigurationManager; swConf = (SolidWorks.Interop.sldworks.Configuration)swConfMgr.ActiveConfiguration; swRootComp = (Component2)swConf.GetRootComponent(); object[] vChildComp; Component2 swChildComp; vChildComp = (object[])swRootComp.GetChildren(); AssemblyDoc swTempAssem = (AssemblyDoc)swModel; for (int i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; string compName = swChildComp.Name2; ModelDoc2 swModelTemp = swChildComp.GetModelDoc2();//转换成ModelDoc2 //选中要替换掉的零件 SelectData seldate = ((SelectionMgr)swModelTemp.SelectionManager).CreateSelectData(); swChildComp.Select4(false, seldate, false); //替换零部件 if (compName == "电机法兰-1") { bool isTrue = swTempAssem.ReplaceComponents(FaLan, "", true, true);//零件地址 } if (compName == "内齿轮-1") { swTempAssem.ReplaceComponents(InnerGearPath, "", true, true);//零件地址 } if (compName == "立机座-1") { swTempAssem.ReplaceComponents(standPath, "", true, true);//零件地址 } if (compName == "子装配2-1") { swTempAssem.ReplaceComponents(subAssemPath, "", true, true);//轴套子装配地址 } if (compName == "subAssemly-1") { swTempAssem.ReplaceComponents("", "", true, true);//行星架子装配 } } swModel.EditRebuild3(); }
private void btnAssem1_Click(object sender, EventArgs e) { if (swApp == null) { swApp = (SldWorks)ConnectSW.iSwApp; } List <string> fileAssem1 = new List <string>(); //文件路径集合 string carrerPath = string.Empty; //行星架路径 string planetaryPath = string.Empty; //行星轮路径 string outShaftPath = string.Empty; //输出轴路径 string pineShaftPath = string.Empty; //销轴路径 //获取界面中的文件并打开 int Rows = this.lBoxAssem1.Items.Count; //行的数量 if (Rows == 0) { MessageBox.Show("请选择装配零部件!"); return; } foreach (object item in lBoxAssem1.Items) { fileAssem1.Add(item.ToString()); //界面中的文件 } foreach (string file in fileAssem1) //遍历文件获取路径 { string fileName = file.Substring(file.LastIndexOf("\\") + 1); if (fileName.Contains("架")) { carrerPath = file; } if (fileName.Contains("行星轮")) { planetaryPath = file; } if (fileName.Contains("输出")) { outShaftPath = file; } if (fileName.Contains("销轴")) { pineShaftPath = file; } //swModel = (ModelDoc2)swApp.OpenDoc6(file, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); } //实现装配 //打开装配模板(行星架+输出轴+销轴+行星轮+行星轮垫片+轴承)然后替换相关零部件 swModel = (ModelDoc2)swApp.OpenDoc6(_exePath + "PrtAndAsmTemp\\subAssemly.sldasm", (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings); //遍历装配体选择零部件 swModel = (ModelDoc2)swApp.ActiveDoc; swConfMgr = (SolidWorks.Interop.sldworks.ConfigurationManager)swModel.ConfigurationManager; swConf = (SolidWorks.Interop.sldworks.Configuration)swConfMgr.ActiveConfiguration; swRootComp = (Component2)swConf.GetRootComponent(); //TraverseAssembly(swRootComp, 1); object[] vChildComp; Component2 swChildComp; vChildComp = (object[])swRootComp.GetChildren(); AssemblyDoc swTempAssem = (AssemblyDoc)swModel; for (int i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; string compName = swChildComp.Name2; ModelDoc2 swModelTemp = swChildComp.GetModelDoc2(); //转换成ModelDoc2 //选中要替换掉的零件 SelectData seldate = ((SelectionMgr)swModelTemp.SelectionManager).CreateSelectData(); swChildComp.Select4(false, seldate, false); //替换零部件 if (compName == "行星架-1") { bool isTrue = swTempAssem.ReplaceComponents(carrerPath, "", true, true); //零件地址 } if (compName == "行星轮-1") { swTempAssem.ReplaceComponents(planetaryPath, "", true, true); //零件地址 } if (compName == "输出轴-1") { swTempAssem.ReplaceComponents(outShaftPath, "", true, true); //零件地址 } if (compName == "销轴-1") { swTempAssem.ReplaceComponents(pineShaftPath, "", true, true); //零件地址 } if (compName == "行星架垫片-1") { swTempAssem.ReplaceComponents("", "", true, true); //零件地址 } } swModel.EditRebuild3(); }
//This function takes a component and decomposes it in all the existing children. //For every children a MyTransformMatrix is computed. The computed transform matrix refers //to the given children component respect to its position in the original file //(such a matrix is obtained composing the MyTransformMatrix referred to the component //position respect to its father and the father's MyTransformMatrix). //If a children has other children it decomposes it too. public static void TraversAssemblyComponents(Component2 swComponent2, MyTransformMatrix fatherTransformMatrix, SldWorks swApplication) { //List of the lists of instances of the same file object: var ListOfMyListOfInstances = new List <MyListOfInstances>(); if (swComponent2 == null) { return; } var nameFile = "ClassifyComponents.txt"; //I take the children of the root component var swChildrenComponent = (Array)swComponent2.GetChildren(); int i = 0; foreach (Component2 component2 in swChildrenComponent) { //for each son I create a new ComputeNewRepeatedComponent var newRelativeTransformMatrix = AssemblyTraverse.GetTransformMatrix(component2, swApplication); var newTransformMatrix = fatherTransformMatrix.ComposeTwoTransformMatrix(newRelativeTransformMatrix, swApplication); bool newIsLeaf = component2.IGetChildrenCount() == 0; //If the current son is not a "leaf" component the function is recalled again: if (component2.IGetChildrenCount() != 0) { TraversAssemblyComponents(component2, newTransformMatrix, swApplication); } else { var newMyComponent = ComputeNewRepeatedComponent(swApplication, component2, 0, newRelativeTransformMatrix, i, newIsLeaf); //I verify if the list corresponding to this component already exists: //KLdebug.Print("-Componente # " + indexRepEntity + " di " + swComponent2.Name2, nameFile); string namePath = component2.GetPathName(); string nameFileComponent = namePath.Split('\\').Last(); //to get the last name after the last "\" //namePath = namePath.TrimEnd('-'); //string nameFileComponent = namePath.Remove((namePath.LastIndexOf('-') + 1)); //KLdebug.Print(" --->> namePath: " + namePath, "nomi.txt"); //KLdebug.Print(" --->> nameFileComponent: " + nameFileComponent, "nomi.txt"); //KLdebug.Print(" Matrice relativa", nameFile); //KLdebug.PrintTransformMatrix(newRelativeTransformMatrix, nameFile, swApplication); //KLdebug.Print(" Matrice assoluta", nameFile); //KLdebug.PrintTransformMatrix(newTransformMatrix, nameFile, swApplication); var indexOfFind = ListOfMyListOfInstances.FindIndex(list => list.Name == nameFileComponent); if (indexOfFind != -1) { //The list referred to this component already exists. I add it to the corresponding list //var newMyComponent = new ComputeNewRepeatedComponent(); //var newIndex = // ListOfMyListOfInstances[indexOfFind].ListOfMyComponent.Count + 1; //newMyComponent.RepeatedEntity.idRE = newIndex; ListOfMyListOfInstances[indexOfFind].ListOfMyComponent.Add(newMyComponent); //KLdebug.Print(" AGGIORNATA LISTA ESISTENTE: " + newMyComponent.Name + " con id" +newMyComponent.RepeatedEntity.idRE, nameFile); } //else //{ // //Check of the component satisfy other shape criteria (volume and percentage of type of surfaces) // var shapeComparison = AssemblyTraverse.KL_GetShapePart(component2, swApplication); // var statisticComparison = AssemblyTraverse.KL_GetStatisticPart(component2, // shapeComparison.Surface, swApplication); // var addCompForShape = false; // foreach (MyListOfInstances instance in ListOfMyListOfInstances) // { // var component = (Component2)instance.ListOfMyComponent.First().Component; // var shapeOriginal = AssemblyTraverse.KL_GetShapePart(component, swApplication); // var statisticOriginal = AssemblyTraverse.KL_GetStatisticPart(component, // shapeOriginal.Surface, // swApplication); // if (KLcriteriaCheck.Size.Volume(shapeOriginal, shapeComparison, swApplication)) // { // if (KLcriteriaCheck.Size.PercentageSurfacesType(statisticOriginal, statisticComparison, // swApplication)) // { // namePath = component.GetPathName(); // nameFileComponent = namePath.Split('\\').Last(); // //nameFileComponent = namePath; // indexOfFind = // ListOfMyListOfInstances.FindIndex(list => list.Name == nameFileComponent); // ListOfMyListOfInstances[indexOfFind].ListOfMyComponent.Add(newMyComponent); // addCompForShape = true; // break; // } // } // } // //The list referred to this component does not exist yet. I create it // if (!addCompForShape) // { // List<MyRepeatedComponent> newListOfComponentsOfListOfInstances = new List // <MyRepeatedComponent> // { // newMyComponent // }; // var newListOfInstances = new MyListOfInstances(nameFileComponent, // newListOfComponentsOfListOfInstances); // ListOfMyListOfInstances.Add(newListOfInstances); // //KLdebug.Print(" CREATA NUOVA LISTA nome:" + newListOfInstances.Name, nameFile); // } //} i++; } } }
/// <summary> /// Gets the first component thatwould work as a display reference /// </summary> /// <param name="comp">component to work from</param> /// <returns>A component that would be valid for display</returns> private static Component2 getComponentForDisplay(Component2 comp) { object[] Comps; if (comp == null) Comps = ModelDoc.ConfigurationManager.ActiveConfiguration.GetRootComponent3(false).GetChildren(); else Comps = comp.GetChildren(); foreach (Component2 c in Comps) { if (c.GetChildren().Length <= 0 && c.GetSuppression() != (int)swComponentSuppressionState_e.swComponentSuppressed) { return c; } } foreach (Component2 c in Comps) { object[] subComps = c.GetChildren(); if(c.GetChildren().Length > 0 && c.GetSuppression() != (int)swComponentSuppressionState_e.swComponentSuppressed) { Component2 newComp = getComponentForDisplay(c); if (newComp != null) return newComp; } } return null; }
// // LINK EXPORTING FUNCTIONS // public void PythonTraverseComponent_for_links(Component2 swComp, long nLevel, ref string asciitext, ref MathTransform roottrasf) { // Scan assembly features and save mating info if (nLevel > 1) { Feature swFeat = (Feature)swComp.FirstFeature(); PythonTraverseFeatures_for_links(swFeat, nLevel, ref asciitext, ref roottrasf, ref swComp); } // Recursive scan of subassemblies object[] vChildComp; Component2 swChildComp; vChildComp = (object[])swComp.GetChildren(); for (long i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; if (swChildComp.Solving == (int)swComponentSolvingOption_e.swComponentFlexibleSolving) PythonTraverseComponent_for_links(swChildComp, nLevel + 1, ref asciitext, ref roottrasf); } }
// // BODY EXPORTING FUNCTIONS // public void PythonTraverseComponent_for_markers(Component2 swComp, long nLevel, ref string asciitext, int nbody) { // Look if component contains markers Feature swFeat = (Feature)swComp.FirstFeature(); MathTransform swCompTotalTrasf = swComp.GetTotalTransform(true); PythonTraverseFeatures_for_markers(swFeat, nLevel, ref asciitext, nbody, swCompTotalTrasf); // Recursive scan of subcomponents Component2 swChildComp; object[] vChildComp = (object[])swComp.GetChildren(); for (long i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; PythonTraverseComponent_for_markers(swChildComp, nLevel + 1, ref asciitext, nbody); } }
public void OutputCompXformTemp(Component2 swComp, long nLevel, string parents) { object[] vChild; Component2 swChildComp; string sPadStr = ""; string tempSelectID = ""; MathTransform swCompXform; // object vXform; long i; for (i = 0; i < nLevel; i++) { sPadStr = sPadStr + "."; } swCompXform = swComp.Transform2; if (swCompXform != null) { ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc2(); Boolean tempSupp = swComp.IsSuppressed(); Boolean tempHide = swComp.IsHidden(false); if (swModel != null && tempSupp == false) { StatusLab.Text = "Loading:" + swComp.Name; string tempCode = Path.GetFileNameWithoutExtension(swModel.GetPathName()); string swMateDB = ""; string tempMaterial = ""; if (swModel.GetType() == 1) { tempMaterial = ((PartDoc)swModel).GetMaterialPropertyName2("", out swMateDB); } else { tempMaterial = ""; } string tempSize = swModel.GetCustomInfoValue("", "零件尺寸"); string tempComment = swModel.GetCustomInfoValue("", "其它说明"); string tempblanktype = swModel.GetCustomInfoValue("", "下料方式"); string tempName = CodetoName(tempCode); string tempName2 = GetName(tempCode); tempSelectID = swComp.GetSelectByIDString(); int tempblanqty = 1; if (ignore != "" && tempSelectID.Contains(ignore) == true) { } else { var q = bomItems.Where(x => x.name == tempName && x.parents == parents).ToList(); if (q.Count == 0 && tempCode.Contains("镜向") == false && tempCode.Contains("复制") == false) { bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 1, "", tempComment, tempName, tempblanqty, tempName2, tempSelectID, parents, tempblanktype)); } else if (tempCode.Contains("镜向")) { if (q.Count == 0) { if (sPadStr.Length == 1) { bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 0, "", tempComment, tempName, 1, tempName, tempSelectID, parents, tempblanktype)); } bomItems.Add(new BomItem(sPadStr, tempCode, "", "", 1, "", tempComment, "", 0, tempName2, tempSelectID, parents, tempblanktype)); } else { if (bomItems[bomItems.IndexOf(q[0])].parents == parents) { bomItems[bomItems.IndexOf(q[0])].blankqty = bomItems[bomItems.IndexOf(q[0])].blankqty + 1; // bomItems[bomItems.IndexOf(q[0])] = new BomItem(sPadStr, bomItems[bomItems.IndexOf(q[0])].code, bomItems[bomItems.IndexOf(q[0])].material, bomItems[bomItems.IndexOf(q[0])].size, bomItems[bomItems.IndexOf(q[0])].qty, bomItems[bomItems.IndexOf(q[0])].blanksize, tempComment, bomItems[bomItems.IndexOf(q[0])].name, bomItems[bomItems.IndexOf(q[0])].blankqty + 1, bomItems[bomItems.IndexOf(q[0])].name2); var q2 = bomItems.Where(x => x.name2 == tempName2).ToList(); if (q2.Count == 0) { //bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 0, tempBlankSize, tempComment, tempName, 0, tempName2)); bomItems.Add(new BomItem(sPadStr, tempCode, "", "", 1, "", tempComment, "", 0, tempName2, tempSelectID, parents, tempblanktype)); } else { bomItems[bomItems.IndexOf(q2[0])].qty = bomItems[bomItems.IndexOf(q2[0])].qty + 1; } } else { bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 1, "", tempComment, tempName, tempblanqty, tempName2, tempSelectID, parents, tempblanktype)); } } } else if (tempCode.Contains("复制")) { if (q.Count == 0) { bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 1, "", tempComment, tempName, 1, tempName, tempSelectID, parents, tempblanktype)); } else { bomItems[bomItems.IndexOf(q[0])].qty = bomItems[bomItems.IndexOf(q[0])].qty + 1; bomItems[bomItems.IndexOf(q[0])].blankqty = bomItems[bomItems.IndexOf(q[0])].blankqty + 1; if (swModel.GetType() == 2) { ignore = tempSelectID; } } } else if (q.Count > 0 && tempCode.Contains("镜向") == false && tempCode.Contains("复制") == false && bomItems[bomItems.IndexOf(q[0])].parents == parents) { bomItems[bomItems.IndexOf(q[0])].qty = bomItems[bomItems.IndexOf(q[0])].qty + 1; bomItems[bomItems.IndexOf(q[0])].blankqty = bomItems[bomItems.IndexOf(q[0])].blankqty + 1; if (swModel.GetType() == 2) { ignore = tempSelectID; } } else { bomItems.Add(new BomItem(sPadStr, tempCode, tempMaterial, tempSize, 1, "", tempComment, tempName, tempblanqty, tempName2, tempSelectID, parents, tempblanktype)); } } } } ; vChild = (object[])swComp.GetChildren(); for (i = 0; i <= (vChild.Length - 1); i++) { swChildComp = (Component2)vChild[i]; OutputCompXformTemp(swChildComp, nLevel + 1, tempSelectID); if (i == vChild.Length - 1) { ignore = ""; } } }
public static AdjacencyGraph <KLgraph.KLnode, KLgraph.KLedge> KL_GetGraphOfAssemblyComponents (Component2 fatherComponent, KLgraph.KLnode father, ref List <KLgraph.KLnode> listVertices, List <KLgraph.KLedge> listEdges, ref List <MyListOfInstances> listOfMyListOfInstances, SldWorks swApplication) { var graph = new AdjacencyGraph <KLgraph.KLnode, KLgraph.KLedge>(true); var fatherId = father.HashCode; //var fatherComponent = father.Comp; graph.AddVertexRange(listVertices); graph.AddEdgeRange(listEdges); { if (fatherComponent != null) { var swChildrenComponent = (Array)fatherComponent.GetChildren(); var rootNode = listVertices.FirstOrDefault(v => v.Name.Equals(father.Name)); int i = 0; try { var index = 0; //Console.WriteLine("Number of elements to analyze: " + swChildrenComponent.Length); foreach (Component2 component in swChildrenComponent) { index++; Console.WriteLine(String.Format("Processing component {0} over {1}", index, swChildrenComponent.Length)); //if (!component.Name2.Contains("Arbre satellite BV")) { var transforation = (Array)KL_GetTransformsOfAssemblyComponents(component, swApplication); var fatherName = fatherComponent.Name2; var componentName = component.Name2; object vBodyInfo; var bodyList = (Array)(component.GetBodies3((int)swBodyType_e.swAllBodies, out vBodyInfo)); //var componentName = pathComponent.Split('\\').Last(); var nameLastPart = componentName.TrimEnd('-'); nameLastPart = nameLastPart.Remove(nameLastPart.LastIndexOf('-') + 1); var componentPath = component.GetPathName(); var hashCode = component.GetHashCode(); //var nodeId = component.GetID(); var nodeId = 0; var childrenNumber = component.IGetChildrenCount(); if (childrenNumber == 0) { //Console.WriteLine("Single"); //var shape = KL_GetShapePart(component, swApplication); //var statistic = KL_GetStatisticPart(component, shape.Surface, swApplication); //swApplication.SendMsgToUser(componentName + " " + statistic.Genus); var nodePart = new KLgraph.KLnodePart(hashCode, transforation, fatherName, fatherId, component, componentName, nameLastPart, componentPath, nodeId, null, null); var edgeStructure = new KLgraph.KLedgeStructure(rootNode, nodePart, 0); listVertices.Add(nodePart); listEdges.Add(edgeStructure); graph.AddVertex(nodePart); graph.AddEdge(edgeStructure); // Per ogni parte vengono aggiornate le entità ripetute. bool newIsLeaf = component.IGetChildrenCount() == 0; var newRelativeTransformMatrix = GetTransformMatrix(component, swApplication); var newMyComponent = LC_AssemblyTraverse.ComputeNewRepeatedComponent(swApplication, component, nodeId, newRelativeTransformMatrix, i, newIsLeaf); //if (!newMyComponent.RepeatedEntity.listOfFaces.Any()) //{ // if (nodePart.NodeShapeIsSphere(swApplication)) // { // newMyComponent.IsSphere = true; // } // else // { // newMyComponent.IsSphere = false; // } //} string namePath = component.Name2; //Console.WriteLine("Nome completo " + namePath); string nameFileComponent = namePath.Split('/').Last(); //Console.WriteLine("Nome splittato " + nameFileComponent); //to get the last name after the last "\" namePath = namePath.TrimEnd('-'); nameFileComponent = nameFileComponent.Remove((nameFileComponent.LastIndexOf('-') + 1)); //Console.WriteLine("Analizzo componente " + nameFileComponent); var indexOfFind = listOfMyListOfInstances.FindIndex(list => list.Name == nameFileComponent); if (indexOfFind != -1) { //Console.WriteLine("Trovata componente con lo stesso nome " + nameFileComponent); //The list referred to this component already exists. I add it to the corresponding list //var newMyComponent = new ComputeNewRepeatedComponent(); //var newIndex = // ListOfMyListOfInstances[indexOfFind].ListOfMyComponent.Count + 1; //newMyComponent.RepeatedEntity.idRE = newIndex; listOfMyListOfInstances[indexOfFind].ListOfMyComponent.Add(newMyComponent); //KLdebug.Print(" AGGIORNATA LISTA ESISTENTE: " + newMyComponent.Name + " con id" +newMyComponent.RepeatedEntity.idRE, "Istances.txt"); } else { // //Check of the component satisfy other shape criteria (volume and percentage of type of surfaces) // var addCompForShape = false; // foreach (MyListOfInstances instance in listOfMyListOfInstances) // { // var comparisonComponent = instance.ListOfMyComponent.First().Component; // string comparisonComponentPath = comparisonComponent.Name2; // //string nameFileComparisonComponent = comparisonComponentPath.Split('\\').Last(); // string nameFileComparisonComponent = comparisonComponentPath.TrimEnd('-'); // nameFileComparisonComponent = // nameFileComparisonComponent.Remove( // (nameFileComparisonComponent.LastIndexOf('-') + 1)); // var comparisonNode = // (KLgraph.KLnodePart) // listVertices.Find( // part => part.NameLastPart == nameFileComparisonComponent); // if (comparisonNode != null) // { // var comparisonShape = comparisonNode.KLshape; // var comparisonStatistic = comparisonNode.KLstatistic; // if (KLcriteriaCheck.Size.Volume(comparisonShape, shape, swApplication)) // { // if (KLcriteriaCheck.Size.PercentageSurfacesType // (comparisonStatistic, // statistic, // swApplication)) // { // namePath = comparisonComponent.Name2; // nameFileComponent = namePath.TrimEnd('-'); // nameFileComponent = // nameFileComponent.Remove( // (nameFileComponent.LastIndexOf('-') + 1)); // //nameFileComponent = namePath.Split('\\').Last(); // //nameFileComponent = namePath; // indexOfFind = // listOfMyListOfInstances.FindIndex( // list => list.Name == nameFileComponent); // listOfMyListOfInstances[indexOfFind].ListOfMyComponent.Add( // newMyComponent); // //KLdebug.Print(" AGGIORNATA LISTA ESISTENTE: " + newMyComponent.Name + " con id" + newMyComponent.RepeatedEntity.idRE, "Istances.txt"); // addCompForShape = true; // break; // } // } // } // else // { // swApplication.SendMsgToUser("Nodo ripetuto non recuperato"); // } // } // //The list referred to this component does not exist yet. I create it // if (!addCompForShape) // { List <MyRepeatedComponent> newListOfComponentsOfListOfInstances = new List <MyRepeatedComponent> { newMyComponent }; var newListOfInstances = new MyListOfInstances(nameFileComponent, newListOfComponentsOfListOfInstances); listOfMyListOfInstances.Add(newListOfInstances); // //KLdebug.Print(" CREATA NUOVA LISTA nome:" + newListOfInstances.Name, "Istances.txt"); // } } i++; } else { var shape = KL_GetShapeAssembly(component, swApplication); var statistic = KL_GetStatisticAssembly(component, swApplication); var nodeAssembly = new KLgraph.KLnodeAssembly(hashCode, transforation, fatherName, fatherId, component, componentName, nameLastPart, componentPath, nodeId, childrenNumber, statistic, shape); var edgeStructure = new KLgraph.KLedgeStructure(rootNode, nodeAssembly, 0); listVertices.Add(nodeAssembly); listEdges.Add(edgeStructure); graph.AddVertex(nodeAssembly); graph.AddEdge(edgeStructure); graph = KL_GetGraphOfAssemblyComponents(component, nodeAssembly, ref listVertices, listEdges, ref listOfMyListOfInstances, swApplication); } } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.Source); throw; } } else { Console.WriteLine("Padre nullo"); } } //Console.WriteLine("Ritorno il grafo"); return(graph); }
/// <summary> /// 递归创建装配树 /// </summary> /// <param name="component"></param> /// <param name="swComponet"></param> private static void CreateTree(Component2 component, ref SWComponent swComponent) { if (component == null) { return; } /////////复制组件相关信息/////////// //名称 swComponent.Name = component.Name2; //是否根组件 swComponent.IsRoot = component.IsRoot(); //提取配合,存放在RootComponent节点 //if (swComponent.IsRoot) { swComponent.Mates = GetSWMatesOfRootComponent(component); //} //包围盒 double[] box = null; try { box = component.GetBox(false, false); } catch (Exception e) { //发生异常,说明该组件(根组件)没有包围盒 box = null; } if (box == null) { swComponent.BoundingBox = CreateSWBoundingBox(box); } else { swComponent.BoundingBox = new SWBoundingBox(); } //提取Body object bodyInfo; object[] bodies = component.GetBodies3((int)swBodyType_e.swSolidBody, out bodyInfo); if (bodies != null) { foreach (object objBody in bodies) { swComponent.Bodies.Add(CreateSWBody((Body2)objBody)); } } //继续遍历 object[] subComponents = component.GetChildren(); if (subComponents != null) { foreach (object obj in subComponents) { SWComponent newComponent = new SWComponent(); CreateTree((Component2)obj, ref newComponent); swComponent.SubComponents.Add(newComponent); } } }
/// <summary> /// 遍历装配体零件 /// </summary> /// <param name="swComp"></param> /// <param name="nLevel"></param> public static void TraverseCompXform(Component2 swComp, long nLevel, bool setcolor = false) { object[] vChild; Component2 swChildComp; string sPadStr = ""; MathTransform swCompXform; // object vXform; long i; for (i = 0; i < nLevel; i++) { sPadStr = sPadStr + " "; } swCompXform = swComp.Transform2; if (swCompXform != null) { ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc2(); try { //子零件文件名 //Debug.Print(sPadStr + swComp.Name2); if (swComp.GetSelectByIDString() == "") { //选择id //Debug.Print(swComp.GetSelectByIDString()); } else { } } catch { } if (swModel != null) { Debug.Print("Loading:" + swComp.Name2); //获取零件的一些信息,如属性,名字路径。 string tempPartNum = swModel.get_CustomInfo2(swComp.ReferencedConfiguration, "PartNum"); string tempName2 = swComp.Name2; string tempName = swModel.GetPathName(); string tempConfigName = swComp.ReferencedConfiguration; string tempComponentRef = swComp.ComponentReference; //如果要设定颜色 if (setcolor == true) { double[] matPropVals = (double[])swModel.MaterialPropertyValues; var tempC = GetRadomColor(System.IO.Path.GetFileNameWithoutExtension(swModel.GetPathName())); matPropVals[0] = Convert.ToDouble(tempC.R) / 255; matPropVals[1] = Convert.ToDouble(tempC.G) / 255; matPropVals[2] = Convert.ToDouble(tempC.B) / 255; swModel.MaterialPropertyValues = matPropVals; swModel.WindowRedraw(); } } } else { ModelDoc2 swModel; swModel = (ModelDoc2)swComp.GetModelDoc2(); } vChild = (object[])swComp.GetChildren(); for (i = 0; i <= (vChild.Length - 1); i++) { swChildComp = (Component2)vChild[i]; TraverseCompXform(swChildComp, nLevel + 1, setcolor); } }
public bool GetComponents(Component2 inParseComponent, LinkedList<Component2> outComponents, bool isGetSubComponents, bool isRecursive) { bool ret = false; try { if (!isRecursive) outComponents.Clear(); if (inParseComponent != null) { var subComponents = (object[])inParseComponent.GetChildren(); // GetChildren ������ �� ���������� �������������. ���������� ����������� GetComponents�� if (subComponents != null && subComponents.Length == 0) { var swCompModel = (ModelDoc2)inParseComponent.GetModelDoc(); var tt = ((AssemblyDoc)swCompModel).GetComponents(true); if (tt.Length != 0) subComponents = tt; } if (subComponents != null) foreach (Component2 subSwComp in subComponents) { outComponents.AddLast(subSwComp); if (isGetSubComponents) GetComponents(subSwComp, outComponents, true, true); } } ret = true; } catch { } return ret; }