コード例 #1
0
        GetSortedFragments(ModelItemCollection modelItems)
        {
            ComApi.InwOpState     oState = ComBridge.State;
            ComApi.InwOpSelection oSel   = ComBridge.ToInwOpSelection(modelItems);

            // To be most efficient, you need to lookup an efficient
            // EqualityComparer for the int[] key

            var pathDict = new Dictionary <int[], Stack <ComApi.InwOaFragment3> >();

            foreach (ComApi.InwOaPath3 path in oSel.Paths())
            {
                // This yields ONLY unique fragments
                // ordered by geometry they belong to

                foreach (ComApi.InwOaFragment3 frag in path.Fragments())
                {
                    int[] pathArr = ((Array)frag.path.ArrayData).ToArray <int>();
                    if (!pathDict.TryGetValue(pathArr,
                                              out Stack <ComApi.InwOaFragment3> frags))
                    {
                        frags             = new Stack <ComApi.InwOaFragment3>();
                        pathDict[pathArr] = frags;
                    }
                    frags.Push(frag);
                }
            }
            return(pathDict);
        }
コード例 #2
0
 public NavisGeometry()
 {
     // Add Selected Items to oModelColl Property
     oModelColl = NavisApplication.ActiveDocument.CurrentSelection.SelectedItems;
     //convert to COM selection
     oSel = ComBridge.ToInwOpSelection(oModelColl);
 }
コード例 #3
0
        private void AddURL(string name, string link, string category, List <stringedLink> exLinks)
        {
            ComApi.InwOpState10 state = ComApiBridge.ComApiBridge.State;

            // create the hyperlink collection
            ComApi.InwURLOverride oMyURLOoverride = (ComApi.InwURLOverride)state.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURLOverride, null, null);

            foreach (var ex in exLinks)
            {
                // create one hyperlink
                ComApi.InwURL2 oMyURL = (ComApi.InwURL2)state.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);

                oMyURL.name = ex.Link_Name;
                oMyURL.URL  = ex.Link_URL;
                oMyURL.SetCategory(ex.Link_Category, "LcOaURL" + ex.Link_Category + "Hyperlink");

                // add the new hyperlink to the hyperlink collection
                ComApi.InwURLColl oURLColl = oMyURLOoverride.URLs();
                oURLColl.Add(oMyURL);

                // get current selected items
                ModelItemCollection modelItemCollectionIn = new ModelItemCollection(navisApp.ActiveDocument.CurrentSelection.SelectedItems);
                //convert to InwOpSelection of COM API
                ComApi.InwOpSelection comSelectionOut = ComApiBridge.ComApiBridge.ToInwOpSelection(modelItemCollectionIn);
                // set the hyplerlink of the model items
                state.SetOverrideURL(comSelectionOut, oMyURLOoverride);
                // enable to the hyperlinks visible
                state.URLsEnabled = true;
            }

            // create recent hyperlink
            {
                ComApi.InwURL2 oMyURL = (ComApi.InwURL2)state.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);

                oMyURL.name = name;
                oMyURL.URL  = link;
                oMyURL.SetCategory(category, "LcOaURL" + category + "Hyperlink");

                // add the new hyperlink to the hyperlink collection
                ComApi.InwURLColl oURLColl = oMyURLOoverride.URLs();
                oURLColl.Add(oMyURL);

                // get current selected items
                ModelItemCollection modelItemCollectionIn = new ModelItemCollection(navisApp.ActiveDocument.CurrentSelection.SelectedItems);
                //convert to InwOpSelection of COM API
                ComApi.InwOpSelection comSelectionOut = ComApiBridge.ComApiBridge.ToInwOpSelection(modelItemCollectionIn);
                // set the hyplerlink of the model items
                state.SetOverrideURL(comSelectionOut, oMyURLOoverride);
                // enable to the hyperlinks visible
                state.URLsEnabled = true;
            }
        }
コード例 #4
0
        private void AddURL(ModelItem modelItem, string[] urls, string[] titleUrls)
        {
            ComApi.InwOpState10 state;
            state = ComApiBridge.ComApiBridge.State;
            // create the hyperlink collection
            ComApi.InwURLOverride oMyURLOoverride = (ComApi.InwURLOverride)state.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURLOverride, null, null);
            // get current selected items
            ModelItemCollection modelItemCollectionIn = new ModelItemCollection();

            modelItemCollectionIn.Add(modelItem);
            // add the new hyperlink to the hyperlink collection
            ComApi.InwURLColl oURLColl = oMyURLOoverride.URLs();

            for (int i = 0; i < urls.Count(); i++)
            {
                // create one hyperlink
                ComApi.InwURL2 oMyURL = (ComApi.InwURL2)state.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);
                // create Hyperlink
                oMyURL.SetCategory("Hyperlink", "LcOaURLCategoryHyperlink");
                // Attachment Point of the hyperlink
                ComApi.InwLPos3f oNewP = (ComApi.InwLPos3f)state.ObjectFactory(ComApi.nwEObjectType.eObjectType_nwLPos3f, null, null);
                oNewP.data1 = modelItemCollectionIn.BoundingBox().Center.X;
                oNewP.data2 = modelItemCollectionIn.BoundingBox().Center.Y;
                oNewP.data3 = modelItemCollectionIn.BoundingBox().Center.Z;

                oMyURL.AttachmentPoints().Add(oNewP);
                // name of the hyperlink
                oMyURL.name = titleUrls[i];
                // site of the hyperlink
                oMyURL.URL = urls[i];

                oURLColl.Add(oMyURL);
            }

            //convert to InwOpSelection of COM API
            ComApi.InwOpSelection comSelectionOut = ComApiBridge.ComApiBridge.ToInwOpSelection(modelItemCollectionIn);
            // set the hyplerlink of the model items
            state.SetOverrideURL(comSelectionOut, oMyURLOoverride);
            // enable to the hyperlinks visible
            state.URLsEnabled = true;

            modelItemCollectionIn.Remove(modelItem);
        }
コード例 #5
0
        private void addProperty(NVApi.ModelItem PropModelItem, string strPropName, string strPropValue)
        {
            try
            {
                COM.InwOpState10 state;
                state = ComApiBridge.State;
                // get current selection
                NVApi.ModelItemCollection modelItemCollectionIn = new NVApi.ModelItemCollection();
                modelItemCollectionIn.Add(PropModelItem);
                // get the selection in COM
                Autodesk.Navisworks.Api.Interop.ComApi.InwOpSelection comSelectionOut = ComApiBridge.ToInwOpSelection(modelItemCollectionIn);
                // get paths within the selection
                COM.InwSelectionPathsColl oPaths = comSelectionOut.Paths();
                COM.InwOaPath3            oPath  = (COM.InwOaPath3)oPaths.Last();
                // get properties collection of the path
                COM.InwGUIPropertyNode2 propn = (COM.InwGUIPropertyNode2)state.GetGUIPropertyNode(oPath, true);

                // create new property category
                // (new tab in the properties dialog)
                COM.InwOaPropertyVec newPvec = (COM.InwOaPropertyVec)state.ObjectFactory(COM.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);
                // create new property
                COM.InwOaProperty newP = (COM.InwOaProperty)state.ObjectFactory(COM.nwEObjectType.eObjectType_nwOaProperty, null, null);
                // set the name, username and value of the new property
                newP.name     = "lc" + strPropName;
                newP.UserName = strPropName;
                newP.value    = strPropValue;
                // add the new property to the new property category
                newPvec.Properties().Add(newP);
                // add the new property category to the path
                propn.SetUserDefined(0, "NV-AddedProety", "lcNVAddedProety", newPvec);
            }
            catch
            {
                throw;
            }
        }
コード例 #6
0
        public override int Execute(params string[] parameters)
        {
            DebugMessage DebugP     = new DebugMessage();
            string       EndMessage = "";

            #region "Interop COM Setup"
            /////////////////////////////////////////////////////////////////////////////////////////////////
            // .Net: Setup
            Document openDoc = Autodesk.Navisworks.Api.Application.ActiveDocument;
            Model    model   = openDoc.Models[0];

            // .Net: get current selection from .NET API
            ModelItemCollection ObjectSelectionInNet = openDoc.CurrentSelection.SelectedItems;
            // .Net: get model item
            ModelItem ObjectsModelItem;
            try
            {
                ObjectsModelItem = openDoc.CurrentSelection.SelectedItems[0];
            }
            catch
            {
                MessageBox.Show("No Objects Selected.");
                goto Exit;
            }
            /////////////////////////////////////////////////////////////////////////////////////////////////
            // COM: Declare "InwOpState" (COM API Main Entry) Object
            ComApi.InwOpState InteropState = ComBridge.State; // Analogous To .Net "Document"
                                                              // COM: Convert .Net Selection To COM Selection
            ComApi.InwOpSelection ObjectsSelectionInCOM = ComApiBridge.ToInwOpSelection(ObjectSelectionInNet);
            // COM: Convert .Net Path To Path In COM
            ComApi.InwOaPath ObjectsPathInCOM = ComApiBridge.ToInwOaPath(ObjectsModelItem);

            // convert to model item in .NET
            ModelItem ObjectsItemInNet = ComApiBridge.ToModelItem(ObjectsPathInCOM);
            #endregion

            // zoom in current view to selected objects
            ComApiBridge.State.ZoomInCurViewOnCurSel();

            // ???
            ComApi.InwOpState9 oStateAPI = ComApiBridge.State;
            //convert to COM selection

            ComApi.InwOpSelection CurrentGUISelection = ComApiBridge.ToInwOpSelection(ObjectSelectionInNet);

            // Debug Variables
            uint levelOneIterator = 0, levelTwoIterator = 0;
            // Takeoff Tracking Variables
            uint   existingIDsCount = 0;
            string CurrentTime      = DateTime.Now.ToString("h:mm:ss tt");
            //ComApi.InwSelectionPathsColl ModelObjectsPaths =

            #region "Change Custom Properties"
            //get paths collection within the selection
            ComApi.InwSelectionPathsColl ObjectCurrentSelectPaths = CurrentGUISelection.Paths();
            // Custom Properties Variables
            const string PropertiesNameString  = "Custom_Properties";
            const string NWAttPropIDNameString = "ID";
            uint         PropertyIndex         = 0; // Used To Locate The Node For Updating Properties
            int          IDPropertyIndex       = 0;

            // Find Existing Custom Properties
            //foreach (ComApi.InwOaPath3


            //add custom properties To Selected Objects
            // http://adndevblog.typepad.com/aec/2012/08/addmodifyremove-custom-attribute-using-com-api.html
            foreach (ComApi.InwOaPath3 ObjectPath in ObjectCurrentSelectPaths)
            {
                //// Make Sure All Children Are Iterated Through
                //foreach(ComApi.InwOaPath3 terminalPath in oPath)
                //{ }

                //get property categories
                ComApi.InwGUIPropertyNode2 NWPropertyNode = (ComApi.InwGUIPropertyNode2)oStateAPI.GetGUIPropertyNode(ObjectPath, true);
                //create a new property category
                ComApi.InwOaPropertyVec NewPropertyCategory = (ComApi.InwOaPropertyVec)oStateAPI.ObjectFactory(
                    ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);
                //create a new property
                ComApi.InwOaProperty NewProperty1 = (ComApi.InwOaProperty)oStateAPI.ObjectFactory(
                    ComApi.nwEObjectType.eObjectType_nwOaProperty, null, null);
                NewProperty1.name     = "Time";
                NewProperty1.UserName = "******";
                NewProperty1.value    = CurrentTime;
                // Add To Category
                NewPropertyCategory.Properties().Add(NewProperty1);

                //create a new property
                ComApi.InwOaProperty NewProperty2 = (ComApi.InwOaProperty)oStateAPI.ObjectFactory(
                    ComApi.nwEObjectType.eObjectType_nwOaProperty, null, null);
                NewProperty2.name     = NWAttPropIDNameString;
                NewProperty2.UserName = NWAttPropIDNameString;
                NewProperty2.value    = "ERROR: Unassigned ID";
                // Add To Category
                //NewPropertyCategory.Properties().Add(NewProperty2);


                //////////////////////////////////////////////////////////////////////////////////////////
                // Find User Defined GUIAttributes
                PropertyIndex = 0; // Reset Property Index (0 Indicates New Property Category)
                uint i = 0, j = 0;
                foreach (ComApi.InwGUIAttribute2 NWAttribute in NWPropertyNode.GUIAttributes())
                {
                    if (NWAttribute.UserDefined == true)
                    {
                        ++i;// Move Index Finder
                        // If Particular Category Name (e.g. "Custom_Properties" Or Whatever PropertiesNameString Is Set To)
                        if (NWAttribute.ClassUserName == PropertiesNameString)
                        {
                            PropertyIndex = i;// Set Index
                            //DebugP.Send("NWAttribute.ClassUserName: "******"Loop Here Found: " + NWProperty.name.ToString());
                                }
                                ++j;
                            }
                        }
                    }
                }

                //////////////////////////////////////////////////////////////////////////////////////
                try// Update Takeoff Time (Don't Change ID) If Property Exists
                {
                    //DebugP.Send("Trying To Update With Index: " + PropertyIndex.ToString());
                    //DebugP.Send("Start Property Update");
                    //DebugP.Send("a1 IDPropertyIndex Value: " + IDPropertyIndex.ToString());
                    //DebugP.Send("a2 Current Value: " + NewProperty2.value.ToString());
                    NewProperty2.value = existingIDsCount.ToString();
                    //DebugP.Send("a3 ID Value Changed");
                    //DebugP.Send("a4 Current Value: " + NewProperty2.value.ToString());
                    //NewPropertyCategory.Properties().Remove(IDPropertyIndex);
                    //DebugP.Send("a5 ID Value Changed");
                    //NewPropertyCategory.Properties().Clear();// Works
                    //DebugP.Send("a6 Properties Category Cleared");

                    NewPropertyCategory.Properties().Add(NewProperty2);
                    //DebugP.Send("a7 Properties Re-Added");
                    NWPropertyNode.SetUserDefined((int)PropertyIndex, PropertiesNameString, "Custom_Properties_InteralName", NewPropertyCategory);
                    ++existingIDsCount;
                    //DebugP.Send("a8 Update Properties Complete");
                }
                catch (Exception e)
                {
                    MessageBox.Show("Failed To Change Custom Properties.\nExiting.", "ERROR: Exception Catch");
                    goto Exit;
                }
            }
            #endregion

            //////////////////////////////////////////////////////////////////////////////////////
            // Comb For Existing ID Objects
            // ?ERROR Possibility of Doubling Up Count Because Of Children Nodes
            //++existingIDsCount;

            // Show Location Of Working Directory
            //MessageBox.Show(Directory.GetCurrentDirectory());
            System.IO.File.AppendAllText(@".\" + KANGVars.PrimitivesFileName + ".txt", "File Made At " + CurrentTime + "\n\n");
            System.IO.File.AppendAllText(@".\" + KANGVars.OutputFileName + ".csv", "File Made At " + CurrentTime + "\n\nName,,X,Y,Z\n");

            // create the callback object
            CallbackGeomListener callbkListener = new CallbackGeomListener();
            foreach (ComApi.InwOaPath3 objectPath in CurrentGUISelection.Paths())// Each Object In The Selection As Distinguished By Individual Paths
            {
                // Properties
                KANGVars.strg = levelOneIterator.ToString();

                foreach (PropertyCategory oPC in ObjectSelectionInNet[(int)levelOneIterator].PropertyCategories)
                {
                    //DebugP.Send("Loop Value: " + oPC.DisplayName);
                }

                //MessageBox.Show("Begin Level1: " + levelOneIterator.ToString());
                int TriangleExceptionCount = 0;
                foreach (ComApi.InwOaFragment3 frag in objectPath.Fragments())// Each Fragment Part Of Object
                {
                    //DebugP.Send("Begin Level2: " + levelTwoIterator.ToString());
                    // generate the primitives
                    frag.GenerateSimplePrimitives(ComApi.nwEVertexProperty.eNORMAL, callbkListener);
                    try
                    {
                        callbkListener.Triangle(frag.Geometry, frag.Geometry, frag.Geometry);
                    }
                    catch (Exception e)
                    {
                        //MessageBox.Show("An Error Occurred Calling Callback Method: '{0}'", e.ToString());
                        // Keep Count Of These Exceptions?
                        ++TriangleExceptionCount;
                        if (TriangleExceptionCount > 1)
                        {
                            EndMessage = EndMessage + "\nERROR: Primitives Exceptions Exceed 1!";
                            //DebugP("ERROR: Primitives Exceptions Exceed 1!");
                        }
                    }
                    ++levelTwoIterator;
                }
                ++levelOneIterator;
                // XYZ Lengths From Min Max Values
                string XYZLengths = "";
                float  calcValue;
                calcValue  = KANGlobalMinMaxCoords.maxX - KANGlobalMinMaxCoords.minX;
                XYZLengths = "," + calcValue.ToString();
                calcValue  = KANGlobalMinMaxCoords.maxY - KANGlobalMinMaxCoords.minY;
                XYZLengths = XYZLengths + "," + calcValue.ToString();
                calcValue  = KANGlobalMinMaxCoords.maxZ - KANGlobalMinMaxCoords.minZ;
                XYZLengths = XYZLengths + "," + calcValue.ToString() + "\n";
                System.IO.File.AppendAllText(@".\" + KANGVars.OutputFileName + ".csv", KANGVars.strg + ",");
                System.IO.File.AppendAllText(@".\" + KANGVars.OutputFileName + ".csv", XYZLengths);
                #region Reset Global Min Max
                KANGlobalMinMaxCoords.minX = 100000;
                KANGlobalMinMaxCoords.maxX = -100000;
                KANGlobalMinMaxCoords.minY = 100000;
                KANGlobalMinMaxCoords.maxY = -100000;
                KANGlobalMinMaxCoords.minZ = 100000;
                KANGlobalMinMaxCoords.maxZ = -100000;
                #endregion // Reset Global Min Max
            }


            EndMessage = EndMessage + "\n Objects Evaluated: " + ObjectSelectionInNet.Count.ToString();

Exit:
            EndMessage = EndMessage + "\n\nPlugin Operation Exit.";
            MessageBox.Show(EndMessage);
            return(0);
        }
コード例 #7
0
ファイル: SetProps.cs プロジェクト: Kirill78Z/InfoTools
        public static void SetPropsMethod(ComApi.InwOpState3 oState,
                                          ModelItemCollection modelItemColl, List <DisplayDataTab> displayDataTabs,
                                          List <DisplayURL> displayURLs, bool overwriteUserAttr, bool overwriteLinks,
                                          bool preserveExistingProperties)
        {
            //Удалить пустые строки из наборов
            displayDataTabs.RemoveAll(ddt => String.IsNullOrEmpty(ddt.DisplayName));
            foreach (DisplayDataTab ddt in displayDataTabs)
            {
                ddt.DisplayProperties.RemoveAll(dp => String.IsNullOrEmpty(dp.DisplayName));
            }
            displayURLs.RemoveAll(dUrl =>
                                  String.IsNullOrEmpty(dUrl.DisplayName) || String.IsNullOrEmpty(dUrl.URL));

            //Если пользователь зачем-то ввел значение нередактируемого свойства, то убрать его
            DisplayDataTab idDataTab
                = displayDataTabs.Find(ddt => ddt.DisplayName.Equals(S1NF0_DATA_TAB_DISPLAY_NAME));

            if (idDataTab != null)
            {
                idDataTab.DisplayProperties.RemoveAll(p
                                                      => propsNotModifiable.Contains(p.DisplayName));
            }

            //Конвертировать значения всех свойств
            foreach (DisplayDataTab ddt in displayDataTabs)
            {
                foreach (DisplayProperty dp in ddt.DisplayProperties)
                {
                    dp.ConvertValue();
                }
            }


            #region Старое

            /*
             *  //Заполнить список свойств, которые нужно будет добавить на панель Id
             *  ComApi.InwOaPropertyVec idDataTabPropertyVec = (ComApi.InwOaPropertyVec)oState
             *                  .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec,
             *                  null, null);
             *
             *  //Заполнить список свойств для панели Id
             *  //(в ней хранятся уникальные Id для каждого элемента, которые не должны меняться этой командой)
             *  if (idDataTab != null)
             *  {
             *      foreach (DisplayProperty dp in idDataTab.DisplayProperties)
             *      {
             *          idDataTabPropertyVec.Properties()
             *              .Add(Utils.CreateNewUserProp(oState, dp.DisplayName, dp.Value));
             *      }
             *  }
             */

            //Заполнены ли списки свойств?
            //Если список пустой, то панели должны быть удалена
            //bool userPropsDefined = displayDataTabs.Count > 0;


            //Создание набора для присоединения к объектам модели
            //List<DisplayDataTab> propsToSet = new List<DisplayDataTab>();
            #endregion

            //Словарь свойств, которые добавляются
            Dictionary <string, DisplayProperty> propsDefined = new Dictionary <string, DisplayProperty>();

            //Создать базовые наборы свойств, которые будут привязываться к объектам
            foreach (DisplayDataTab ddt in displayDataTabs)
            {
                //if (!ddt.DisplayName.Equals(S1NF0_DATA_TAB_DISPLAY_NAME))
                //{
                //ddt.InwOaPropertyVec = (ComApi.InwOaPropertyVec)oState
                //        .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec,
                //        null, null);
                //propsToSet.Add(ddt);
                foreach (DisplayProperty dp in ddt.DisplayProperties)
                {
                    //ComApi.InwOaProperty newP
                    //        = Utils.CreateNewUserProp(oState, dp.DisplayName, dp.Value);
                    //// add the new property to the new property category
                    //ddt.InwOaPropertyVec.Properties().Add(newP);

                    string key = ddt.DisplayName + dp.DisplayName;
                    if (!propsDefined.ContainsKey(key))
                    {
                        propsDefined.Add(key, dp);
                    }
                }
                //}
            }

            //словарь ссылок, которые добавляются
            Dictionary <string, string> linksDefined = new Dictionary <string, string>();

            //Создание набора ссылок для привязки к объектам
            //ComApi.InwOpState10 state = ComApiBridge.ComApiBridge.State;
            //ComApi.InwURLOverride urlOverride
            //    = (ComApi.InwURLOverride)state
            //    .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURLOverride, null, null);
            //ComApi.InwURLColl oURLColl = urlOverride.URLs();
            foreach (DisplayURL dUrl in displayURLs)
            {
                //ComApi.InwURL2 oUrl = (ComApi.InwURL2)state
                //    .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);
                //oUrl.name = dUrl.DisplayName;
                //oUrl.URL = dUrl.URL;
                //oUrl.SetCategory("Hyperlink", "LcOaURLCategoryHyperlink");//Тип - всегда гиперссылка
                //oURLColl.Add(oUrl);

                string key = dUrl.DisplayName;
                if (!linksDefined.ContainsKey(key))
                {
                    linksDefined.Add(key, dUrl.URL);
                }
            }


            foreach (ModelItem item in modelItemColl.DescendantsAndSelf)
            {
                //convert the .NET object to COM object
                ComApi.InwOaPath oPath = ComApiBridge.ComApiBridge.ToInwOaPath(item);


                //Переделать панель атрибутов в соответствии с заполненными строками в окне
                if (overwriteUserAttr)//Только если стояла галка в окне!!!
                {
                    //наборы свойств
                    //ключ - имя панели, значение - набор свойств для привязки к объекту
                    Dictionary <string, ComApi.InwOaPropertyVec> propVectorsCurr
                        = new Dictionary <string, ComApi.InwOaPropertyVec>();
                    // Сначала скопировать базовые наборы свойств для каждой из заданных панелей в словарь
                    //foreach (DisplayDataTab ddt in displayDataTabs)
                    //{
                    //    propVectorsCurr.Add(ddt.DisplayName, ddt.InwOaPropertyVec.Copy());
                    //}

                    //Изучаются текущие свойства объекта модели
                    //Сначала в наборы свойств нужно добавить если присутствуют:
                    //- свойства, которые не редактируются данной командой
                    //- если нажата галка "Не удалять свойства", то любые свойства, которых не было в окне SetProps
                    //- свойства которые были заданы в окне SetProps, но они уже присутствуют в модели
                    //  (их значение задается как введено в окне,
                    //  если эти свойства добавлены на этом этапе, то они не должны добавляться на следующем)
                    HashSet <string> alreadyAdded = new HashSet <string>();//набор ключей свойств, которые добавлены на этом этапе

                    ComApi.InwGUIPropertyNode2 propn
                        = (ComApi.InwGUIPropertyNode2)oState.GetGUIPropertyNode(oPath, true);
                    foreach (ComApi.InwGUIAttribute2 attr in propn.GUIAttributes())
                    {
                        if (attr.UserDefined)
                        {
                            foreach (ComApi.InwOaProperty prop in attr.Properties())
                            {
                                string key = attr.ClassUserName + prop.UserName;

                                if (
                                    (attr.ClassUserName.Equals(S1NF0_DATA_TAB_DISPLAY_NAME) && propsNotModifiable.Contains(prop.UserName)) //- свойства, которые не редактируются данной командой
                                    ||
                                    (preserveExistingProperties && !propsDefined.ContainsKey(key))                                         //- если нажата галка Не удалять свойства, то любые свойства, которых не было в окне
                                    ||
                                    propsDefined.ContainsKey(key)                                                                          //- свойства которые были заданы в окне SetProps, но они уже присутствуют в модели
                                    )
                                {
                                    ComApi.InwOaPropertyVec vec = null;
                                    propVectorsCurr.TryGetValue(attr.ClassUserName, out vec);
                                    if (vec == null)
                                    {
                                        vec = (ComApi.InwOaPropertyVec)oState
                                              .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec,
                                                             null, null);
                                        propVectorsCurr.Add(attr.ClassUserName, vec);
                                    }
                                    if (!propsDefined.ContainsKey(key))
                                    {
                                        vec.Properties().Add(Utils.CopyProp(oState, prop));
                                    }
                                    else
                                    {
                                        //Учесть введенное значение
                                        DisplayProperty dp = propsDefined[key];
                                        vec.Properties().Add(Utils.CreateNewUserProp(oState, dp.DisplayName, dp.Value));
                                        alreadyAdded.Add(key);
                                    }
                                }
                            }
                        }
                    }

                    //Затем добавить вновь создаваемые свойства, которых ранее не было в модели
                    //(с учетом тех, которые были добавлены на предыдущем этапе)
                    foreach (DisplayDataTab ddt in displayDataTabs)
                    {
                        ComApi.InwOaPropertyVec vec = null;
                        propVectorsCurr.TryGetValue(ddt.DisplayName, out vec);
                        if (vec == null)
                        {
                            vec = (ComApi.InwOaPropertyVec)oState
                                  .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwOaPropertyVec,
                                                 null, null);
                            propVectorsCurr.Add(ddt.DisplayName, vec);
                        }

                        foreach (DisplayProperty dp in ddt.DisplayProperties)
                        {
                            string key = ddt.DisplayName + dp.DisplayName;
                            if (!alreadyAdded.Contains(key))
                            {
                                ComApi.InwOaProperty newP
                                    = Utils.CreateNewUserProp(oState, dp.DisplayName, dp.Value);
                                // add the new property to the new property category
                                vec.Properties().Add(newP);
                            }
                        }
                    }


                    //Удалить старые панели
                    try
                    { propn.RemoveUserDefined(0); }
                    catch (System.Runtime.InteropServices.COMException) { }
                    //Создать новые
                    foreach (KeyValuePair <string, ComApi.InwOaPropertyVec> kvp in propVectorsCurr)
                    {
                        propn.SetUserDefined(0, kvp.Key, "S1NF0",
                                             kvp.Value);
                    }

                    #region Старое

                    /*
                     *          // get properties collection of the path
                     *          ComApi.InwGUIPropertyNode2 propn
                     *              = (ComApi.InwGUIPropertyNode2)oState.GetGUIPropertyNode(oPath, true);
                     *
                     *
                     *
                     *          ComApi.InwOaPropertyVec idDataTabPropertyVecCurr = idDataTabPropertyVec.Copy();
                     *
                     *          //Добавить нередактируемые свойства если они есть в исходном
                     *          foreach (string dn in propsNotModifiable)
                     *          {
                     *              DataProperty prop = item.PropertyCategories
                     *              .FindPropertyByDisplayName(S1NF0_DATA_TAB_DISPLAY_NAME, dn);
                     *
                     *              if (prop != null)
                     *              {
                     *                  ComApi.InwOaProperty copyProp = Utils.CopyProp(oState, prop);
                     *                  idDataTabPropertyVecCurr.Properties().Add(copyProp);
                     *              }
                     *          }
                     *
                     *
                     *          //Удалить старые панели
                     *          try
                     *          { propn.RemoveUserDefined(0); }
                     *          catch (System.Runtime.InteropServices.COMException) { }
                     *          //Создать новые
                     *          if (userPropsDefined)
                     *          {
                     *              foreach (DisplayDataTab ddt in propsToSet)
                     *              {
                     *                  //Создание одной панели
                     *                  propn.SetUserDefined(0, ddt.DisplayName, "S1NF0",
                     *                      ddt.InwOaPropertyVec);
                     *              }
                     *
                     *              //Создание панели Id
                     *              if (idDataTabPropertyVecCurr.Properties().Count > 0)
                     *              {
                     *                  propn.SetUserDefined(0, S1NF0_DATA_TAB_DISPLAY_NAME, "S1NF0",
                     *                      idDataTabPropertyVecCurr);
                     *              }
                     *
                     *
                     *          }
                     */
                    #endregion
                }



                //Переделать все ссылки в соответствии с заполненными строками в окне
                if (overwriteLinks)//Только если стояла галка в окне!!!
                {
                    ComApi.InwURLOverride urlOverrideCurr = (ComApi.InwURLOverride)oState
                                                            .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURLOverride, null, null);//urlOverride.Copy();

                    //Изучаются текущие ссылки
                    //Сначала в набор ссылок нужно добавить если присутствуют:
                    //- если нажата галка "Не удалять свойства", то любые ссылки, которых не было в окне SetProps
                    //- ссылки которые были заданы в окне SetProps, но они уже присутствуют в модели
                    //  (их значение задается как введено в окне,
                    //  если эти ссылки добавлены на этом этапе, то они не должны добавляться на следующем)
                    HashSet <string> alreadyAdded = new HashSet <string>();//набор ключей ссылок, которые добавлены на этом этапе

                    PropertyCategory linksCat = item.PropertyCategories.FindCategoryByName("LcOaExURLAttribute");
                    if (linksCat != null)
                    {
                        int linksCount = linksCat.Properties.Count / 3;

                        for (int i = 0; i < linksCount; i++)
                        {
                            string       suffix   = i == 0 ? "" : i.ToString();
                            DataProperty nameProp = item.PropertyCategories
                                                    .FindPropertyByName("LcOaExURLAttribute", "LcOaURLAttributeName" + suffix);
                            DataProperty urlProp = item.PropertyCategories
                                                   .FindPropertyByName("LcOaExURLAttribute", "LcOaURLAttributeURL" + suffix);
                            if (nameProp != null && urlProp != null)
                            {
                                string key = nameProp.Value.ToDisplayString();
                                if ((preserveExistingProperties && !linksDefined.ContainsKey(key))//- если нажата галка "Не удалять свойства", то любые ссылки, которых не было в окне SetProps
                                    ||
                                    (linksDefined.ContainsKey(key)))
                                {
                                    ComApi.InwURL2 oUrl = (ComApi.InwURL2)oState
                                                          .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);
                                    oUrl.name = nameProp.Value.ToDisplayString();
                                    if (!linksDefined.ContainsKey(key))
                                    {
                                        oUrl.URL = urlProp.Value.ToDisplayString();//Сохранить существующее значение
                                    }
                                    else
                                    {
                                        oUrl.URL = linksDefined[key];//присвоить заданное в окне значение ссылки
                                        alreadyAdded.Add(key);
                                    }
                                    oUrl.SetCategory("Hyperlink", "LcOaURLCategoryHyperlink");//Тип - всегда гиперссылка

                                    urlOverrideCurr.URLs().Add(oUrl);
                                }
                            }
                        }
                    }


                    foreach (DisplayURL dUrl in displayURLs)
                    {
                        string key = dUrl.DisplayName;
                        if (!alreadyAdded.Contains(key))
                        {
                            ComApi.InwURL2 oUrl = (ComApi.InwURL2)oState
                                                  .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwURL, null, null);
                            oUrl.name = dUrl.DisplayName;
                            oUrl.URL  = dUrl.URL;
                            oUrl.SetCategory("Hyperlink", "LcOaURLCategoryHyperlink");//Тип - всегда гиперссылка
                            urlOverrideCurr.URLs().Add(oUrl);
                        }
                    }


                    ComApi.InwOpSelection comSelectionOut =
                        ComApiBridge.ComApiBridge.ToInwOpSelection(new ModelItemCollection()
                    {
                        item
                    });
                    oState.SetOverrideURL(comSelectionOut, urlOverrideCurr);
                }
            }
        }
コード例 #8
0
        public static int Execute(/*params string[] parameters*/)
        {
            ComApi.InwOpState3 oState = ComApiBridge.ComApiBridge.State;

            Document doc = Application.ActiveDocument;

            ModelItemCollection currSelectionColl = doc.CurrentSelection.SelectedItems;

            if (currSelectionColl.Count > 0)
            {
                foreach (ModelItem item in currSelectionColl.DescendantsAndSelf)
                {
                    if (item.HasGeometry)
                    {
                        ComApi.InwOaPath oPath = ComApiBridge.ComApiBridge.ToInwOaPath(item);

                        Transform3D tr = item.Transform;//TODO: учитывать уже добавленную трансформацию!!!
                        //tr.Factor()
                        Transform3DComponents transform3DComponents = tr.Factor();
                        //transform3DComponents.ScaleOrientation
                        Point3D center = item.Geometry.BoundingBox.Center;

                        double z               = center.Z;
                        double zTransformed    = z * 1.1;
                        double correctionTrans = (z - zTransformed) /*/ 2*/;

                        ComApi.InwOpSelection comSelectionOut =
                            ComApiBridge.ComApiBridge.ToInwOpSelection(new ModelItemCollection()
                        {
                            item
                        });

                        ComApi.InwLTransform3f3 oTrans1
                            = (ComApi.InwLTransform3f3)oState
                              .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwLTransform3f, null, null);
                        //растяжение по Z
                        ComApi.InwLVec3f scale
                            = (ComApi.InwLVec3f)oState
                              .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwLVec3f, null, null);
                        scale.SetValue(1, 1, 1.1);
                        //смещение по Z
                        ComApi.InwLVec3f trans
                            = (ComApi.InwLVec3f)oState
                              .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwLVec3f, null, null);
                        trans.SetValue(0, 0, correctionTrans);

                        //ComApi.InwLRotation3f scaleOrientation
                        //    = (ComApi.InwLRotation3f)oState
                        //    .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwLRotation3f, null, null);
                        //ComApi.InwLUnitVec3f axis
                        //    = (ComApi.InwLUnitVec3f)oState
                        //    .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwLUnitVec3f, null, null);
                        //axis.SetValue(0, 0, 1);
                        //scaleOrientation.SetValue(axis, 0);

                        //ComApi.InwLRotation3f Rotation
                        //    = (ComApi.InwLRotation3f)oState
                        //    .ObjectFactory(ComApi.nwEObjectType.eObjectType_nwLRotation3f, null, null);
                        //Rotation.SetValue(axis, 0);

                        //oTrans1.factor(scale, scaleOrientation, Rotation, trans);
                        //double[] matrix = ConvertDoubleArray((Array)((object)oTrans1.Matrix));

                        //oTrans1.MakeScale(scale);
                        //double[] matrix1 = ConvertDoubleArray((Array)((object)oTrans1.Matrix));
                        //oTrans1.MakeTranslation(trans);
                        //double[] matrix2 = ConvertDoubleArray((Array)((object)oTrans1.Matrix));

                        oTrans1.SetMatrix(new double[]
                        {
                            1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1.1, 0, 0, 0, correctionTrans, 1
                        });


                        //oTrans1.MakeScale(scaleVec);
                        oState.OverrideTransform(comSelectionOut, oTrans1);
                    }
                }
            }

            return(0);
        }
コード例 #9
0
ファイル: ChangeAllLinks.cs プロジェクト: Kirill78Z/InfoTools
        /// <summary>
        /// Замена и добавление ссылок только через COM - http://adndevblog.typepad.com/aec/2012/05/create-hyperlinks-for-model-objects-using-net-api.html
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public override int Execute(params string[] parameters)
        {
            try
            {
                ChangeLinksProps changeLinksPropsWindow = new ChangeLinksProps();
                bool?            result = changeLinksPropsWindow.ShowDialog();
                if (result != null && result.Value)
                {
                    Document oDoc = Application.ActiveDocument;

                    ModelItemEnumerableCollection allItems = oDoc.Models.RootItemDescendantsAndSelf;

                    ComApi.InwOpState10 state;
                    state = ComApiBridge.ComApiBridge.State;

                    foreach (ModelItem item in allItems)
                    {
                        DataProperty urlProp = item.PropertyCategories.FindPropertyByName("LcOaExURLAttribute", "LcOaURLAttributeURL");

                        if (urlProp != null)
                        {
                            ComApi.InwOaPath p_path = ComApiBridge.ComApiBridge.ToInwOaPath(item);
                            try
                            {
                                ComApi.InwURLOverride urlOverride = state.GetOverrideURL(p_path);
                                ComApi.InwURLColl     oURLColl    = urlOverride.URLs();
                                bool changed = false;//становится true если была поменяна хотябы 1 ссылка
                                foreach (ComApi.InwURL2 url in oURLColl)
                                {
                                    //Проверять исходный URL
                                    string initialUrl = url.URL;

                                    if (!String.IsNullOrEmpty(initialUrl))
                                    {
                                        string newUrl = null;
                                        if (changeLinksPropsWindow.ChangeAllUrls)
                                        {
                                            //Нужно заменить целиком весь путь до файла
                                            char slash = '\\';
                                            if (initialUrl.Contains("/"))
                                            {
                                                slash = '/';
                                            }
                                            List <string> temp = initialUrl.Split(slash).ToList();
                                            temp.RemoveAt(temp.Count - 1);
                                            string fileName = initialUrl.Split(slash).Last();
                                            newUrl = changeLinksPropsWindow.NewUrlFragment + slash + fileName;
                                        }
                                        else if (initialUrl.Contains(changeLinksPropsWindow.OldUrlFragment))
                                        {
                                            //Если путь содержит подстроку, введенную в окне, то нужно заменить эту подстроку
                                            newUrl = initialUrl.Replace(changeLinksPropsWindow.OldUrlFragment, changeLinksPropsWindow.NewUrlFragment);
                                        }

                                        if (newUrl != null)
                                        {
                                            url.URL = newUrl;
                                            changed = true;
                                        }



                                        /*
                                         * //Получение директории по-разному для локальных путей и для интернета
                                         * string initialDir = null;
                                         * char slash = '\\';
                                         * if (initialUrl.Contains("/"))
                                         * {
                                         *  slash = '/';
                                         *  Uri uri = new Uri(initialUrl);
                                         *  Uri initialDirUri = new Uri(uri, ".");
                                         *  initialDir = initialDirUri.ToString().TrimEnd('/');
                                         * }
                                         * else
                                         * {
                                         *  //Записанный путь может содержать недопустимые символы из-за которых вываливается ошибка в методе GetDirectoryName
                                         *  //initialDir = Path.GetDirectoryName(initialUrl);//выдает ошибку
                                         *  List<string> temp = initialUrl.Split('\\').ToList();
                                         *  temp.RemoveAt(temp.Count - 1);
                                         *  initialDir = String.Join("\\", temp.ToArray());
                                         * }
                                         *
                                         * string oldUrlToCompare = changeLinksPropsWindow.OldUrl;
                                         *
                                         *
                                         * //string fileName = Path.GetFileName(initialUrl);//выдает ошибку
                                         * string fileName = initialUrl.Split(slash).Last();
                                         *
                                         * if (changeLinksPropsWindow.ChangeAllUrls
                                         || oldUrlToCompare
                                         || //.StartsWith(initialDir)
                                         || .Equals(initialDir)
                                         || )
                                         ||{
                                         || //Разделитель может быть либо прямым либо обратным слешем
                                         || string divider = "/";
                                         || string newUrl = changeLinksPropsWindow.NewUrl;
                                         || if (newUrl.Contains("\\"))
                                         || {
                                         ||     divider = "\\";
                                         || }
                                         ||
                                         || url.URL = newUrl + divider + fileName;
                                         || changed = true;
                                         ||}
                                         */
                                    }
                                }
                                if (changed)
                                {
                                    ComApi.InwOpSelection comSelectionOut =
                                        ComApiBridge.ComApiBridge.ToInwOpSelection(new ModelItemCollection()
                                    {
                                        item
                                    });
                                    state.SetOverrideURL(comSelectionOut, urlOverride);
                                }
                            }
                            catch (System.Runtime.InteropServices.COMException)
                            { }
                        }
                    }

                    state.URLsEnabled = true;

                    Win.MessageBox.Show("Готово", "Готово", Win.MessageBoxButton.OK, Win.MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                CommonException(ex, "Ошибка при замене ссылок в Navis");
            }

            return(0);
        }
コード例 #10
0
        public void ViewpointsCreation(out bool ClashTestsResultsExist)
        {
            InwOpGroupView TopGroup = null;

            ProjectionChange_Ort();
            ChangeModelColor();

            ClashTestsResultsExist = false;

            try
            {
                foreach (InwOclClashTest clashTest in m_clash.Tests())
                {
                    clashTest.status = nwEClashTestStatus.eClashTestStatus_OK;

                    if (clashTest.results().Count == 0)
                    {
                        continue;
                    }

                    ClashTestsResultsExist = true;

                    if (TopGroup == null)
                    {
                        TopGroup = TopGroupCreate();
                    }

                    InwOpGroupView SubGroup = SubGroupCreate(clashTest, TopGroup);

                    // get the first Test and its first clash result
                    foreach (InwOclTestResult clashResult in clashTest.results())
                    {
                        if (clashResult.status == nwETestResultStatus.eTestResultStatus_ACTIVE |
                            clashResult.status == nwETestResultStatus.eTestResultStatus_NEW)

                        {
                            ModelItem oItem1 = null;
                            ModelItem oItem2 = null;

                            //Get clashed items
                            oItem1 = ComApiBridge.ToModelItem(clashResult.Path1);
                            oItem2 = ComApiBridge.ToModelItem(clashResult.Path2);

                            //Put clashed items to model collection
                            ModelItemCollection ClashedItems = new ModelItemCollection
                            {
                                oItem1,
                                oItem2
                            };

                            //Overwrite items color
                            oDoc.Models.OverridePermanentColor(new ModelItem[1] {
                                ClashedItems.ElementAtOrDefault(0)
                            },
                                                               Autodesk.Navisworks.Api.Color.Red);
                            oDoc.Models.OverridePermanentColor(new ModelItem[1] {
                                ClashedItems.ElementAtOrDefault(1)
                            },
                                                               Autodesk.Navisworks.Api.Color.Green);

                            // Create a copy of current selection
                            ComApi.InwOpSelection ComClashSelection = ComApiBridge.ToInwOpSelection(ClashedItems);

                            // Create a new empty selection
                            InwOpSelection2 AllModel = oState.ObjectFactory(nwEObjectType.eObjectType_nwOpSelection, null, null) as InwOpSelection2;

                            // Get the new selection to contain the entire model
                            AllModel.SelectAll();

                            // Subtract the current selection, so it contains the unselected part of model
                            AllModel.SubtractContents(ComClashSelection);

                            // create a temporary saved viewpoint
                            InwOpView oSV = oState.ObjectFactory(nwEObjectType.eObjectType_nwOpView);

                            //Apply attributes
                            oSV.ApplyHideAttribs     = true;
                            oSV.ApplyMaterialAttribs = true;

                            oSV.name = clashResult.name;

                            //Get and save viewpoint
                            oSV.anonview.ViewPoint = clashResult.GetSuitableViewPoint().Copy();

                            SubGroup.SavedViews().Add(oSV);

                            oDoc.Models.OverridePermanentColor(new ModelItem[1] {
                                ClashedItems.ElementAtOrDefault(0)
                            },
                                                               Autodesk.Navisworks.Api.Color.FromByteRGB(63, 63, 63));
                            oDoc.Models.OverridePermanentColor(new ModelItem[1] {
                                ClashedItems.ElementAtOrDefault(1)
                            },
                                                               Autodesk.Navisworks.Api.Color.FromByteRGB(63, 63, 63));

                            oDoc.CurrentSelection.Clear();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            if (TopGroup == null)
            {
                return;
            }

            oState.SavedViews().Add(TopGroup);
        }