Ejemplo n.º 1
0
        /* loops on all items in the model collection tree (from the root to the leaves) and adds the
         * their string names to the tree view. */

        private void itemLoop(ModelItemEnumerableCollection models, TreeNode tnc, int ii)
        {
            int j = 0;

            foreach (ModelItem m in models)
            {
                MSTreeView.MSTreeNode r = new MSTreeView.MSTreeNode();
                r.Text = m.PropertyCategories.ElementAt(0).Properties[0].Value.ToDisplayString();
                tnc.Nodes.Add(r);

                if (ii == 3 && m.Children.First != null)
                {
                    r.ImageIndex         = ii - 1;
                    r.SelectedImageIndex = ii - 1;
                    itemLoop(m.Children, tnc.Nodes[j], ii);
                }

                else if (m.HasGeometry)
                {
                    r.ImageIndex         = 3;
                    r.SelectedImageIndex = 3;
                }

                else
                {
                    r.ImageIndex         = ii;
                    r.SelectedImageIndex = ii;
                    itemLoop(m.Children, tnc.Nodes[j], ii + 1);
                }

                j++;
            }
        }
Ejemplo n.º 2
0
        private bool treeSelect(ModelItemEnumerableCollection models, TreeNode tnc, List <MSTreeView.MSTreeNode> selectedNodes)
        {
            if (models.First == null)
            {
                return(false);
            }
            int j = 0; bool s = false;

            foreach (ModelItem m in models)
            {
                if (modelSelection.IsSelected(m))
                {
                    s = true;
                    selectedNodes.Add((MSTreeView.MSTreeNode)tnc.Nodes[j]);
                }
                else
                {
                    if (treeSelect(m.Children, tnc.Nodes[j], selectedNodes))
                    {
                        s = true;
                        tnc.Nodes[j].Expand();
                    }
                }
                j++;
            }

            return(s);
        }
Ejemplo n.º 3
0
 private bool ChechHidden(ModelItemEnumerableCollection items)
 {
     if (items.Any(o => o.IsHidden))
     {
         return(false); //an anchestor is hidden, so it the item
     }
     return(true);      // all anchestors are visible
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Нужно пройти по дереву до уровня слоев и затем выполнять выгрузку
        /// Слои раскладывать по папкам в соответствии с названиями файлов и вложенностью файлов
        /// </summary>
        /// <param name="items"></param>
        private void ExportByLayers(ModelItemEnumerableCollection items, string fbxPath, DocumentModels docModels, NativeExportPluginAdaptor FBXplugin)
        {
            //if (n < 20)//TEST
            //{
            int n = 0;

            foreach (ModelItem item in items)
            {
                //Скрывать все кроме текущего элемента
                docModels.SetHidden(items, true);
                docModels.SetHidden(new List <ModelItem> {
                    item
                }, false);
                //item.is

                //Нужно проверить, что у объекта нет свойства путь к источнику
                DataProperty sourceProp = item.PropertyCategories.FindPropertyByName("LcOaNode", "LcOaPartitionSourceFilename");


                if (sourceProp == null)
                {
                    //Выполнять выгрузку
                    if (!Directory.Exists(fbxPath))
                    {
                        Directory.CreateDirectory(fbxPath);
                    }

                    string name = item.DisplayName;
                    if (String.IsNullOrEmpty(name))//Если у объекта нет имени, то подставить цифру
                    {
                        name = n.ToString();
                        n++;
                    }

                    name = name + ".fbx";
                    name = Common.Utils.GetSafeFilename(name);

                    string fileName = Path.Combine(fbxPath, name);
                    if (!File.Exists(fileName))
                    {
                        FBXplugin.Execute(fileName);
                    }

                    //n++;//TEST
                }
                else
                {
                    //Дополнить путь выгрузки новой папкой
                    string name = item.DisplayName;
                    name = Common.Utils.GetSafeFilename(name);
                    name = Path.GetFileNameWithoutExtension(name);
                    string fbxPathToChildren = Path.Combine(fbxPath, name);
                    //Рекурсивный вызов
                    ExportByLayers(item.Children, fbxPathToChildren, docModels, FBXplugin);
                }
            }
            //}
        }
Ejemplo n.º 5
0
        public ItemTree(ModelItemEnumerableCollection mis)
        {
            int n = ItemData.InstanceCount;

            _layers = new List <ItemData>(mis
                                          .Where <ModelItem>(mi => mi.IsLayer)
                                          .Select <ModelItem, ItemData>(
                                              mi => new ItemData(mi)));

            nItems = ItemData.InstanceCount - n;
        }
Ejemplo n.º 6
0
        //int n = 0;//TEST
        public override int Execute(params string[] parameters)
        {
            //n = 0;//TEST

            Win.MessageBoxResult result = Win.MessageBox.Show("Начать выгрузку FBX по слоям?", "Выгрузка FBX", Win.MessageBoxButton.YesNo);

            if (result == Win.MessageBoxResult.Yes)
            {
                try
                {
                    PluginRecord FBXPluginrecord = Application.Plugins.
                                                   FindPlugin("NativeExportPluginAdaptor_LcFbxExporterPlugin_Export.Navisworks");
                    if (FBXPluginrecord != null)
                    {
                        if (!FBXPluginrecord.IsLoaded)
                        {
                            FBXPluginrecord.LoadPlugin();
                        }

                        NativeExportPluginAdaptor FBXplugin = FBXPluginrecord.LoadedPlugin as NativeExportPluginAdaptor;

                        Document doc = Application.ActiveDocument;

                        string fbxPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        string docPath = doc.FileName;
                        if (!String.IsNullOrEmpty(docPath))
                        {
                            fbxPath = Path.GetDirectoryName(docPath);
                        }

                        DocumentModels docModels = doc.Models;
                        ModelItemEnumerableCollection rootItems = docModels.RootItems;
                        ExportByLayers(rootItems, fbxPath, docModels, FBXplugin);

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

            return(0);
        }
Ejemplo n.º 7
0
        public override int Execute(params string[] parameters)
        {
            try
            {
                //Все элементы модели получают свойство Id и Id материала (пустое)
                ComApi.InwOpState3 oState = ComApiBridge.ComApiBridge.State;

                Document doc = Application.ActiveDocument;
                ModelItemEnumerableCollection rootItems = doc.Models.RootItems;
                idCount = 0;
                SetIdsRecurse(rootItems, oState);

                Win.MessageBox.Show("Всего привязано уникальных id - " + idCount, "Готово", Win.MessageBoxButton.OK, Win.MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                CommonException(ex, "Ошибка при раздаче идентификаторов в Navis");
            }

            return(0);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Раздать свойства родитель и правильное имя узла
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public override int Execute(params string[] parameters)
        {
            //Win.MessageBoxResult result = Win.MessageBox.Show("Начать раздачу служебных свойств S1NF0?", "Добавить служебные свойства", Win.MessageBoxButton.YesNo);

            SetS1NF0PropsDialog dialog = new SetS1NF0PropsDialog(
                new Dictionary <string, bool>()
            {
                { ID_PROP_DISPLAY_NAME, false },
                { MATERIAL_ID_PROP_DISPLAY_NAME, false },
                { PROPER_NAME_PROP_DISPLAY_NAME, false },
            }
                );
            bool?result = dialog.ShowDialog();


            if (result.HasValue && result.Value /*result == Win.MessageBoxResult.Yes*/)
            {
                try
                {
                    //Все элементы модели получают свойство Id и Id материала (пустое)
                    ComApi.InwOpState3 oState = ComApiBridge.ComApiBridge.State;

                    Document doc = Application.ActiveDocument;
                    ModelItemEnumerableCollection rootItems = doc.Models.RootItems;
                    editedCount = 0;
                    var toOverwrite = dialog.ToOverwrite;
                    SetTreePropsRecurse(rootItems, oState, "ROOT", toOverwrite);

                    Win.MessageBox.Show("Всего объектов с добавленными свойствами - " + editedCount,
                                        "Готово", Win.MessageBoxButton.OK, Win.MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    CommonException(ex, "Ошибка при раздаче служебных свойств S1NF0 в Navis");
                }
            }


            return(0);
        }
Ejemplo n.º 9
0
        private bool ChechHidden(ModelItemEnumerableCollection items)
        {
            if (items.Any(o => o.IsHidden))
                return false; //an anchestor is hidden, so it the item
            return true; // all anchestors are visible


        }
Ejemplo n.º 10
0
        private void msTreeView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                MSTreeView.MSTreeNode node = msTreeView1.GetNodeAt(e.Location) as MSTreeView.MSTreeNode;

                if (node != null)
                {
                    if (e.Location.X >= node.Bounds.X - (node.TreeView.ImageList.ImageSize.Width + 5) &&
                        e.Location.X <= node.Bounds.Right + 1)
                    {
                        ((mainForm)this.DockPanel.Parent).timeSlider1_Scroll(sender, e);

                        System.Drawing.Color c = System.Drawing.Color.Blue;

                        int[] indexs = new int[10]; int i = 1;

                        indexs[0] = node.Index; System.Windows.Forms.TreeNode n = node;

                        while ((n = n.Parent) != null)
                        {
                            indexs[i] = n.Index; i++;
                        }

                        ModelItem model = doc.Models.RootItems.ElementAt(indexs[i - 1]);

                        for (i = i - 2; i >= 0; i--)
                        {
                            model = model.Children.ElementAt(indexs[i]);
                        }

                        doc.Models.OverridePermanentColor(model.Self, new Autodesk.Navisworks.Api.Color(c.R / 255, c.G / 255, c.B / 255));

                        if (model.PropertyCategories.ElementAt(model.PropertyCategories.Count() - 1).DisplayName == "Dynamics")
                        {
                            this.i = model.PropertyCategories.ElementAt(model.PropertyCategories.Count() - 1).Properties[4].Value.ToInt32();
                            j      = model.PropertyCategories.ElementAt(model.PropertyCategories.Count() - 1).Properties[5].Value.ToInt32();

                            contextMenuStrip1.Items.Clear();

                            contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                                changePropertiesToolStripMenuItem
                            });

                            contextMenuStrip1.Size = new Size(164, 26);
                            contextMenuStrip1.Show(msTreeView1, e.Location);
                        }
                        else
                        {
                            ModelItemCollection           modelC     = new ModelItemCollection();
                            ModelItemEnumerableCollection modelItems = model.Descendants;

                            foreach (ModelItem m in modelItems)
                            {
                                if (m.PropertyCategories.ElementAt(m.PropertyCategories.Count() - 1).DisplayName ==
                                    "Dynamics" && m.Parent.PropertyCategories.ElementAt(m.Parent.PropertyCategories.Count() - 1).DisplayName !=
                                    "Dynamics")
                                {
                                    modelC.Add(m);
                                }
                            }

                            if (modelC.Count > 0)
                            {
                                ai = new int[modelC.Count]; aj = new int[modelC.Count];

                                for (i = 0; i < modelC.Count; i++)
                                {
                                    model = modelC[i];

                                    ai[i] = model.PropertyCategories.ElementAt(model.PropertyCategories.Count() - 1).Properties[4].Value.ToInt32();
                                    aj[i] = model.PropertyCategories.ElementAt(model.PropertyCategories.Count() - 1).Properties[5].Value.ToInt32();
                                }
                                contextMenuStrip1.Items.Clear();
                                contextMenuStrip1.Items.Add(changeDesendantsToolStripMenuItem);
                                contextMenuStrip1.Size = new Size(164, 26);
                                contextMenuStrip1.Show(msTreeView1, e.Location);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public override int Execute(params string[] ps)
        {
            Document doc             = Application.ActiveDocument;
            string   currentFilename = doc.CurrentFileName;
            string   filename        = doc.FileName;
            string   title           = doc.Title;

            Units            units          = doc.Units;
            DocumentModels   models         = doc.Models;
            DocumentInfoPart info           = doc.DocumentInfo;
            string           currentSheetId = info.Value.CurrentSheetId; // "little_house_2021.rvt"
            DocumentDatabase db             = doc.Database;
            bool             ignoreHidden   = true;
            BoundingBox3D    bb             = doc.GetBoundingBox(ignoreHidden);
            Point3D          min            = bb.Min;
            Point3D          max            = bb.Max;
            int nModels = models.Count;

            Debug.Print("{0}: sheet {1}, bounding box {2}, {3} model{4}{5}",
                        title, currentSheetId, Util.BoundingBoxString(bb),
                        nModels, Util.PluralSuffix(nModels), Util.DotOrColon(nModels));

            // First attempt, based on Navisworks-Geometry-Primitives,
            // using walkNode oState.CurrentPartition:

            //WalkPartition wp = new WalkPartition();
            //wp.Execute();

            List <string> Categories = new List <string>();

            foreach (Model model in models)
            {
                ModelItem rootItem = model.RootItem;
                ModelItemEnumerableCollection mis = rootItem.DescendantsAndSelf;
                Debug.Print("  {0}: {1} model items", model.FileName, mis.Count());
                List <ModelItem> migeos = new List <ModelItem>();
                foreach (ModelItem mi in mis)
                {
                    Debug.Print(
                        "    '{0}' '{1}' '{2}' has geo {3}",
                        mi.DisplayName, mi.ClassDisplayName,
                        mi.ClassName, mi.HasGeometry);

                    if (mi.HasGeometry)
                    {
                        migeos.Add(mi);
                    }
                }
                Debug.Print("  {0} model items have geometry:", migeos.Count());
                foreach (ModelItem mi in migeos)
                {
                    Debug.Print(
                        "    '{0}' '{1}' '{2}' {3} bb {4}",
                        mi.DisplayName, mi.ClassDisplayName,
                        mi.ClassName, mi.HasGeometry,
                        Util.BoundingBoxString(mi.BoundingBox()));

                    if ("Floor" == mi.DisplayName)
                    {
                        RvtProperties.DumpProperties(mi);
                        RvtProperties props = new RvtProperties(mi);
                        int           id    = props.ElementId;
                    }
                }
            }
            return(0);
        }
Ejemplo n.º 12
0
        public override int Execute(params string[] parameters)
        {
            Win.MessageBoxResult result = Win.MessageBoxResult.Yes;
            if (ManualUse)
            {
                result = Win.MessageBox.Show("Перед экспортом FBX, нужно скрыть те элементы модели, которые не нужно экспортировать. "
                                             + "А так же нужно настроить параметры экспорта в FBX на экспорт ЛИБО В ФОРМАТЕ ASCII, ЛИБО В ДВОИЧНОМ ФОРМАТЕ ВЕРСИИ НЕ НОВЕЕ 2018. "
                                             + "Рекомендуется так же отключить экспорт источников света и камер. "
                                             + "\n\nНачать выгрузку FBX?", "Выгрузка FBX", Win.MessageBoxButton.YesNo);
            }



            if (result == Win.MessageBoxResult.Yes)
            {
                try
                {
                    PluginRecord FBXPluginrecord = Application.Plugins.
                                                   FindPlugin("NativeExportPluginAdaptor_LcFbxExporterPlugin_Export.Navisworks");
                    if (FBXPluginrecord != null)
                    {
                        if (!FBXPluginrecord.IsLoaded)
                        {
                            FBXPluginrecord.LoadPlugin();
                        }

                        NativeExportPluginAdaptor FBXplugin = FBXPluginrecord.LoadedPlugin as NativeExportPluginAdaptor;

                        Document doc = Application.ActiveDocument;

                        string fbxPath        = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        string docPath        = doc.FileName;
                        string defFBXFileName = "";
                        if (!String.IsNullOrEmpty(docPath))
                        {
                            fbxPath        = Path.GetDirectoryName(docPath);
                            defFBXFileName = Path.GetFileNameWithoutExtension(docPath) + ".fbx";
                        }

                        //Указание пользователем имени файла для fbx
                        string fbxFullFileName = null;
                        if (ManualUse)
                        {
                            WinForms.SaveFileDialog sFD = new WinForms.SaveFileDialog();
                            sFD.InitialDirectory = fbxPath;
                            sFD.Filter           = "fbx files (*.fbx)|*.fbx";
                            sFD.FilterIndex      = 1;
                            sFD.RestoreDirectory = true;
                            if (!String.IsNullOrWhiteSpace(defFBXFileName))
                            {
                                sFD.FileName = defFBXFileName;
                            }
                            sFD.Title = "Укажите файл для записи fbx";
                            if (sFD.ShowDialog() == WinForms.DialogResult.OK)
                            {
                                fbxFullFileName = sFD.FileName;
                            }
                        }
                        else
                        {
                            fbxFullFileName = FBXSavePath;
                            FileAttributes attr = File.GetAttributes(fbxFullFileName);
                            if (attr.HasFlag(FileAttributes.Directory))
                            {
                                //добавить имя файла
                                fbxFullFileName = Path.Combine(fbxFullFileName, FBXFileName);
                            }
                        }


                        if (!String.IsNullOrEmpty(fbxFullFileName))
                        {
                            string notEditedDirectory = Path.Combine(Path.GetDirectoryName(fbxFullFileName), "NotEdited");
                            if (!Directory.Exists(notEditedDirectory))
                            {
                                Directory.CreateDirectory(notEditedDirectory);
                            }
                            string notEditedFileName = Path.Combine(notEditedDirectory,
                                                                    Path.GetFileName(fbxFullFileName));

                            if (ManualUse)
                            {
                                BusyIndicatorHelper.ShowBusyIndicator();
                                BusyIndicatorHelper.SetMessage("Стандартный экспорт FBX");
                            }


                            if (FBXplugin.Execute(notEditedFileName) == 0)//Выполнить экспорт в FBX
                            {
                                if (ManualUse)
                                {
                                    BusyIndicatorHelper.SetMessage("Редактирование FBX");
                                }

                                bool isASCII = IsASCIIFBXFile(notEditedFileName);
                                if (isASCII || GetBinaryVersionNum(notEditedFileName) <= 7500)
                                {
                                    //Прочитать модель, составить очередь имен для подстановки в FBX
                                    Queue <FBX.NameReplacement> replacements = new Queue <FBX.NameReplacement>();
                                    DocumentModels docModels = doc.Models;
                                    ModelItemEnumerableCollection rootItems = docModels.RootItems;
                                    //if (rootItems.Count() > 1)
                                    //{
                                    //    //Если в Navis несколько корневых узлов (как в nwf),
                                    //    //то один узел в самом начале FBX должен быть пропущен
                                    //    //Там появится узел Environment
                                    //    replacements.Enqueue(new FBX.NameReplacement());
                                    //}
                                    ComApi.InwOpState3 oState = ComApiBridge.ComApiBridge.State;
                                    NameReplacementQueue(rootItems, replacements, oState);
                                    if (rootItems.Count() == 1)
                                    {
                                        //Обозначить, что первый узел имеет ненадежное имя.
                                        //В FBX оно всегда - Environment, а в Navis - имя открытого файла
                                        //replacements.Peek().OldNameTrustable = false;

                                        //Если корневой узел один, то убрать его из списка. Его не будет в FBX
                                        replacements.Dequeue();
                                    }

                                    //Первый узел в списке замены должен обязательно иметь верное имя
                                    //(в начале списка могут быть с пустым значением, которые отключены в Navis)
                                    while (!replacements.Peek().OldNameTrustable)
                                    {
                                        replacements.Dequeue();
                                    }


                                    //Отредактировать FBX
                                    FBX.ModelNamesEditor fbxEditor = null;
                                    if (IsASCIIFBXFile(notEditedFileName))
                                    {
                                        fbxEditor = new FBX.ASCIIModelNamesEditor(notEditedFileName, replacements);
                                    }
                                    else /*if (GetBinaryVersionNum(sFD.FileName) <= 7500)*/
                                    {
                                        fbxEditor = new FBX.BinaryModelNamesEditor(notEditedFileName, replacements);
                                    }
                                    fbxEditor.FbxFileNameEdited = fbxFullFileName;
                                    fbxEditor.EditModelNames();



                                    if (ManualUse)
                                    {
                                        BusyIndicatorHelper.CloseBusyIndicator();
                                        Win.MessageBox.Show("Файл FBX с отредактированными именами моделей - " + fbxEditor.FbxFileNameEdited,
                                                            "Готово", Win.MessageBoxButton.OK, Win.MessageBoxImage.Information);
                                    }
                                }
                                else
                                {
                                    throw new Exception("Неподдерживаемый формат FBX");
                                }
                            }
                            else
                            {
                                throw new Exception("При экспорте FBX из NavisWorks произошли ошибки");
                            }


                            if (ManualUse)
                            {
                                //на всякий случай
                                BusyIndicatorHelper.CloseBusyIndicator();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    CommonException(ex, "Ошибка при экспорте в FBX из Navis");
                }
            }

            return(0);
        }
Ejemplo n.º 13
0
        public override int Execute(params string[] parameters)
        {
            Win.MessageBoxResult result = Win.MessageBox.Show("Перед экспортом FBX, нужно скрыть те элементы модели, которые не нужно экспортировать. "
                                                              + "А так же нужно настроить параметры экспорта в FBX на экспорт в формате ASCII"
                                                              + "\n\nНачать выгрузку FBX?", "Выгрузка FBX", Win.MessageBoxButton.YesNo);

            if (result == Win.MessageBoxResult.Yes)
            {
                try
                {
                    //ComApi.InwOpState3 oState = ComApiBridge.ComApiBridge.State;

                    PluginRecord FBXPluginrecord = Application.Plugins.
                                                   FindPlugin("NativeExportPluginAdaptor_LcFbxExporterPlugin_Export.Navisworks");
                    if (FBXPluginrecord != null)
                    {
                        if (!FBXPluginrecord.IsLoaded)
                        {
                            FBXPluginrecord.LoadPlugin();
                        }

                        NativeExportPluginAdaptor FBXplugin = FBXPluginrecord.LoadedPlugin as NativeExportPluginAdaptor;

                        Document doc = Application.ActiveDocument;

                        string fbxPath        = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        string docPath        = doc.FileName;
                        string defFBXFileName = "";
                        if (!String.IsNullOrEmpty(docPath))
                        {
                            fbxPath        = Path.GetDirectoryName(docPath);
                            defFBXFileName = Path.GetFileNameWithoutExtension(docPath) + ".fbx";
                        }

                        //Указание пользователем имени файла для fbx
                        WinForms.SaveFileDialog sFD = new WinForms.SaveFileDialog();
                        sFD.InitialDirectory = fbxPath;
                        sFD.Filter           = "fbx files (*.fbx)|*.fbx";
                        sFD.FilterIndex      = 1;
                        sFD.RestoreDirectory = true;
                        if (!String.IsNullOrWhiteSpace(defFBXFileName))
                        {
                            sFD.FileName = defFBXFileName;
                        }
                        sFD.Title = "Укажите файл для записи fbx";

                        if (sFD.ShowDialog() == WinForms.DialogResult.OK)
                        {
                            //Выполнить экспорт в FBX
                            if (0 == FBXplugin.Execute(sFD.FileName))
                            {
                                if (IsASCIIFBXFile(sFD.FileName))
                                {
                                    DocumentModels docModels = doc.Models;
                                    ModelItemEnumerableCollection rootItems = docModels.RootItems;

                                    string editedFBXFileName = Common.Utils
                                                               .GetNonExistentFileName(Path.GetDirectoryName(sFD.FileName),
                                                                                       Path.GetFileNameWithoutExtension(sFD.FileName) + "_Edited", "fbx");

                                    fBXCurrObjLine = null;
                                    using (StreamWriter sw = new StreamWriter(editedFBXFileName))
                                    {
                                        using (StreamReader sr = new StreamReader(sFD.FileName))
                                        {
                                            OverwriteFBX(rootItems, sw, sr, false);

                                            //Дописать FBX до конца
                                            sw.Write(sr.ReadToEnd());
                                        }
                                    }

                                    Win.MessageBox.Show("Готово", "Готово", Win.MessageBoxButton.OK, Win.MessageBoxImage.Information);
                                }
                                else
                                {
                                    //FBX не ASCII
                                    throw new Exception("FBX не в формате ASCII");
                                }
                            }
                            else
                            {
                                //Ошибки при экспорте
                                throw new Exception("Возникли ошибки при экспорте FBX");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    CommonException(ex, "Ошибка при экспорте в FBX");
                }
            }

            return(0);
        }
Ejemplo n.º 14
0
        /// <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);
        }
Ejemplo n.º 15
0
        public override int Execute(params string[] ps)
        {
            Document doc             = Application.ActiveDocument;
            string   currentFilename = doc.CurrentFileName;
            string   filename        = doc.FileName;
            string   title           = doc.Title;

            Units            units          = doc.Units;
            DocumentModels   models         = doc.Models;
            DocumentInfoPart info           = doc.DocumentInfo;
            string           currentSheetId = info.Value.CurrentSheetId; // "little_house_2021.rvt"
            DocumentDatabase db             = doc.Database;
            bool             ignoreHidden   = true;
            BoundingBox3D    bb             = doc.GetBoundingBox(ignoreHidden);
            Point3D          min            = bb.Min;
            Point3D          max            = bb.Max;
            int n;

            n = models.Count;

            Debug.Print("\n{0}: sheet {1}, bounding box {2}, {3} model{4}{5}\n",
                        title, currentSheetId, Util.BoundingBoxString(bb),
                        n, Util.PluralSuffix(n), Util.DotOrColon(n));

            // First attempt, based on Navisworks-Geometry-Primitives,
            // using walkNode oState.CurrentPartition:

            //WalkPartition wp = new WalkPartition();
            //wp.Execute();

            // Second attempt, retrieving root item descendants:

            Debug.Print("Model item tree structure:");

            foreach (Model model in models)
            {
                string model_filename = Path.GetFileName(
                    model.FileName);

                string path = "C:/tmp/"
                              + model_filename.Replace(".nwd", ".txt");

                ModelItem rootItem = model.RootItem;

                ModelItemEnumerableCollection mis
                    = rootItem.DescendantsAndSelf;

                n = mis.Count();

                Debug.Print(
                    "\nModel {0} contains {1} model items listed in '{2}'\n",
                    model_filename, n, path);

                ItemTree mitree = new ItemTree(mis);

                using (StreamWriter writer
                           = new StreamWriter(path))
                {
                    mitree.WriteTo(writer);
                }

                /*
                 * ItemData.InstanceCount = 0;
                 *
                 * List<ItemData> layers
                 * = new List<ItemData>( mis
                 *  .Where<ModelItem>( mi => mi.IsLayer )
                 *  .Select<ModelItem, ItemData>(
                 *    mi => new ItemData( mi ) ) );
                 *
                 * n = layers.Count();
                 * Debug.Print(
                 * "  {0} layers containing {1} hierarchical model items",
                 * n, ItemData.InstanceCount );
                 *
                 * int iLayer = 0;
                 *
                 * foreach( ItemData layer in layers )
                 * {
                 * List<ItemData> cats = layer.Children;
                 * n = cats.Count();
                 * Debug.Print(
                 *  "    {0}: {1} has {2} categories",
                 *  iLayer++, layer, n );
                 *
                 * int iCategory = 0;
                 *
                 * foreach( ItemData cat in cats )
                 * {
                 *  List<ItemData> fams = cat.Children;
                 *  n = fams.Count();
                 *  Debug.Print(
                 *    "      {0}: {1} has {2} families",
                 *    iCategory++, cat, n );
                 *
                 *  int iFamily = 0;
                 *
                 *  foreach( ItemData fam in fams )
                 *  {
                 *    List<ItemData> types = fam.Children;
                 *    n = types.Count();
                 *    Debug.Print(
                 *      "        {0}: {1} has {2} types",
                 *      iFamily++, fam, n );
                 *
                 *    int iType = 0;
                 *
                 *    foreach( ItemData typ in types )
                 *    {
                 *      List<ItemData> instances = typ.Children;
                 *      n = instances.Count();
                 *      Debug.Print(
                 *        "          {0}: {1} has {2} instances",
                 *        iType++, typ, n );
                 *
                 *      int iInst = 0;
                 *
                 *      foreach( ItemData inst in instances )
                 *      {
                 *        List<ItemData> subinsts = inst.Children;
                 *        n = subinsts.Count();
                 *        Debug.Print(
                 *          "            {0}: {1} has {2} subinstances",
                 *          iInst++, inst, n );
                 *
                 *        int iSubinst = 0;
                 *
                 *        foreach( ItemData subinst in subinsts )
                 *        {
                 *          List<ItemData> children = subinst.Children;
                 *          n = children.Count();
                 *          Debug.Print(
                 *            "              {0}: {1} has {2} children",
                 *            iSubinst++, inst, n );
                 *        }
                 *      }
                 *    }
                 *  }
                 * }
                 * }
                 */

                if (50 > n)
                {
                    List <ModelItem> migeos
                        = new List <ModelItem>();

                    foreach (ModelItem mi in mis)
                    {
                        Debug.Print(
                            "    '{0}' '{1}' '{2}' has geo {3}",
                            mi.DisplayName, mi.ClassDisplayName,
                            mi.ClassName, mi.HasGeometry);

                        if (mi.HasGeometry)
                        {
                            migeos.Add(mi);
                        }
                    }
                    Debug.Print("  {0} model items have geometry:", migeos.Count());
                    foreach (ModelItem mi in migeos)
                    {
                        Debug.Print(
                            "    '{0}' '{1}' '{2}' {3} bb {4}",
                            mi.DisplayName, mi.ClassDisplayName,
                            mi.ClassName, mi.HasGeometry,
                            Util.BoundingBoxString(mi.BoundingBox()));

                        if ("Floor" == mi.DisplayName)
                        {
                            RvtProperties.DumpProperties(mi);
                            RvtProperties props = new RvtProperties(mi);
                            int           id    = props.ElementId;
                        }
                    }
                }
            }
            return(0);
        }