Exemplo n.º 1
0
        public Autodesk.Revit.UI.Result Execute
            (Autodesk.Revit.UI.ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Get access to the active uidoc and doc
            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = commandData.Application.ActiveUIDocument.Document;

            Autodesk.Revit.UI.Selection.Selection sel = uidoc.Selection;

            try {
                Reference r =
                    sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
                Element elem = doc.GetElement(r);

                IList <ElementId> elemsWithinBBox = WallJoinerCmd
                                                    .GetWallsIntersectBoundingBox(doc, elem)
                                                    .Select(e => e.Id)
                                                    .ToList();

                sel.SetElementIds(elemsWithinBBox);

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (Exception ex) {
                Autodesk.Revit.UI.TaskDialog.Show("Exception",
                                                  string.Format("Message: {0}\nStackTrace: {1}",
                                                                ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <remarks>get all categories of this document. check its visibility for
        /// the active document, and initialize a hashtable.</remarks>
        public VisibilityCtrl(Autodesk.Revit.UI.UIDocument document)
        {
            if (null == document)
            {
                throw new ArgumentNullException("document");
            }
            else
            {
                m_document = document;
            }

            // initialize the two table
            m_allCategories      = new Hashtable();
            m_categoriesWithName = new Hashtable();

            // fill out the two table
            foreach (Category category in m_document.Document.Settings.Categories)
            {
                if (category.get_AllowsVisibilityControl(m_document.Document.ActiveView))
                {
                    m_allCategories.Add(category.Name, category.get_Visible(m_document.Document.ActiveView));
                    m_categoriesWithName.Add(category.Name, category);
                }
            }
        }
Exemplo n.º 3
0
        internal static void Clear(Autodesk.Revit.UI.UIDocument uiDoc)
        {
            Document    doc = uiDoc.Document;
            Transaction t   = null;

            if (doc.IsModifiable == false)
            {
                t = new Transaction(doc, "Clear Visualizations");
                t.Start();
            }
            SpatialFieldManager sfm = null;

            sfm = SpatialFieldManager.GetSpatialFieldManager(uiDoc.ActiveGraphicalView);
            if (sfm == null)
            {
                sfm = SpatialFieldManager.CreateSpatialFieldManager(uiDoc.ActiveGraphicalView, 1);
            }

            sfm.Clear();

            if (t != null)
            {
                t.Commit();
            }
        }
Exemplo n.º 4
0
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.
                                                ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Tracer.Listeners.Add(new System.Diagnostics.EventLogTraceListener("Application"));

            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;

            try {
                IList <Wall> walls = new FilteredElementCollector(doc)
                                     .OfClass(typeof(Wall))
                                     .WhereElementIsNotElementType()
                                     .Cast <Wall>()
                                     .ToList();

                Tracer.Write("All the walls in the project: " + walls.Count);

                foreach (Wall wall in walls)
                {
                    IList <Element> intrudingWalls =
                        GetWallsIntersectBoundingBox(doc, wall);

                    Tracer.Write(string.Format("Wall {0} is intersected by {1} walls",
                                               wall.Id.ToString(), intrudingWalls.Count));

                    using (Transaction t = new Transaction(doc, "Join walls")) {
                        t.Start();
                        foreach (Element elem in intrudingWalls)
                        {
                            if (((Wall)elem).WallType.Kind == WallKind.Curtain)
                            {
                                continue;
                            }
                            try {
                                if (!JoinGeometryUtils.AreElementsJoined(doc, wall, elem))
                                {
                                    JoinGeometryUtils.JoinGeometry(doc, wall, elem);
                                }
                            }
                            catch (Exception ex) {
                                Tracer.Write(string.Format("{0}\nWall: {1} cannot be joined to {2}",
                                                           ex.Message, wall.Id.ToString(), elem.Id.ToString()));
                                continue;
                            }
                        }
                        t.Commit();
                    }
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (Exception ex) {
                Tracer.Write(string.Format("{0}\n{1}",
                                           ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Exemplo n.º 5
0
        private IsolateMode m_isolateMode; // the mode to select element(s)

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <remarks>get all categories of this document. check its visibility for 
        /// the active document, and initialize a hashtable.</remarks>
        public VisibilityCtrl(Autodesk.Revit.UI.UIDocument document)
        {
            if (null == document)
            {
                throw new ArgumentNullException("document");
            }
            else
            {
                m_document = document;
            }

            // initialize the two table
            m_allCategories = new Hashtable();
            m_categoriesWithName = new Hashtable();

            // fill out the two table
            foreach (Category category in m_document.Document.Settings.Categories)
            {
                if(category.get_AllowsVisibilityControl(m_document.Document.ActiveView))
                {
                    m_allCategories.Add(category.Name, category.get_Visible(m_document.Document.ActiveView));
                    m_categoriesWithName.Add(category.Name, category);
                }
            }
        }
Exemplo n.º 6
0
 //private void AddFaceMaterial(Material materialElement, UIDocument doc)
 public void Test_303_AddFaceMaterial()
 {
     ExeWriter.CF_WriterUtils     Target          = new ExeWriter.CF_WriterUtils();
     Autodesk.Revit.DB.Material   materialElement = new Autodesk.Revit.DB.Material();
     Autodesk.Revit.UI.UIDocument doc             = new Autodesk.Revit.UI.UIDocument();
     Target.AddFaceMaterial(materialElement, doc);
     Assert.IsNotNull(Target);
 }
Exemplo n.º 7
0
 /// <summary>
 /// Try to found an open <see cref="Autodesk.Revit.UI.UIView"/> that is referencing the specified <see cref="Autodesk.Revit.DB.View"/> element.
 /// </summary>
 /// <param name="view"></param>
 /// <param name="uiView"></param>
 /// <returns>true on succes.</returns>
 public static bool TryGetOpenUIView(this Autodesk.Revit.DB.View view, out Autodesk.Revit.UI.UIView uiView)
 {
     using (var uiDocument = new Autodesk.Revit.UI.UIDocument(view.Document))
     {
         uiView = uiDocument.GetOpenUIViews().Where(x => x.ViewId == view.Id).FirstOrDefault();
         return(uiView is object);
     }
 }
Exemplo n.º 8
0
        internal ImportedDWGForm(Autodesk.Revit.UI.UIDocument uidoc, List <ImportedDWG> dwg)
        {
            InitializeComponent();

            this.uidoc   = uidoc;
            this.doc     = uidoc.Document;
            this.dwgList = dwg;

            InitializeList();
        }
Exemplo n.º 9
0
        public DRInterface(Autodesk.Revit.UI.UIDocument uidoc, Command cmd)
        {
            this.uidoc = uidoc;
            this.doc   = uidoc.Document;
            this.cmd   = cmd;

            InitializeComponent();
            InitializeUI();

            doorTypes = new List <string>();
        }
Exemplo n.º 10
0
        /// <summary>
        /// Try to found an open <see cref="Autodesk.Revit.UI.UIDocument"/> that is referencing the specified <see cref="Autodesk.Revit.DB.Document"/>.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="uiDocument"></param>
        /// <returns>true on succes.</returns>
        public static bool TryGetOpenUIDocument(this Autodesk.Revit.DB.Document document, out Autodesk.Revit.UI.UIDocument uiDocument)
        {
            uiDocument = new Autodesk.Revit.UI.UIDocument(document);
            if (uiDocument.GetOpenUIViews().Count == 0)
            {
                uiDocument.Dispose();
                uiDocument = default;
                return(false);
            }

            return(true);
        }
Exemplo n.º 11
0
        public static bool Release(this Document doc)
        {
            using (var uiDocument = new Autodesk.Revit.UI.UIDocument(doc))
            {
                if (uiDocument.GetOpenUIViews().Count == 0)
                {
                    return(doc.Close(false));
                }
            }

            return(true);
        }
Exemplo n.º 12
0
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            System.Diagnostics.Trace.Listeners.
            Add(new System.Diagnostics.EventLogTraceListener("Application"));

            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Autodesk.Revit.DB.Document   doc   = uidoc.Document;

            try {
                CreateSharedParamWin hwnd =
                    new CreateSharedParamWin(doc);
                hwnd.ShowDialog();

                if (hwnd.ParameterName == null ||
                    hwnd.ParameterName.Length == 0)
                {
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }

                SharedParametersManager spManager =
                    new SharedParametersManager(doc);
                spManager.CreateSharedParameter(
                    hwnd.ParameterName,
                    hwnd.ParameterType,
                    new List <BuiltInCategory>
                {
                    hwnd.Category
                },
                    hwnd.ParameterGroup,
                    hwnd.IsInstance,
                    hwnd.IsModifiable,
                    hwnd.IsVisible,
                    hwnd.GroupName
                    );

                if (hwnd.CanVaryBtwGroups)
                {
                    spManager.CanVaryBtwGroups(hwnd.ParameterName, true);
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (System.Exception ex) {
                Autodesk.Revit.UI.TaskDialog.Show("Exception",
                                                  string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Gets the active Graphical <see cref="Autodesk.Revit.DB.View"/> of the provided <see cref="Autodesk.Revit.DB.Document"/>.
        /// </summary>
        /// <param name="doc"></param>
        /// <returns>The active graphical <see cref="Autodesk.Revit.DB.View"/></returns>
        public static View GetActiveGraphicalView(this Document doc)
        {
            using (var uiDocument = new Autodesk.Revit.UI.UIDocument(doc))
            {
                var activeView = uiDocument.ActiveGraphicalView;
                if (activeView is null)
                {
                    var openViews = Rhinoceros.InvokeInHostContext(() => uiDocument.GetOpenUIViews()).
                                    Select(x => doc.GetElement(x.ViewId) as View).
                                    Where(x => x.ViewType.IsGraphicalViewType());

                    activeView = openViews.FirstOrDefault();
                }

                return(activeView);
            }
        }
Exemplo n.º 14
0
        public static IEnumerable <ElementId> CopyElements(this Document document, string path, Func <Document, FilteredElementCollector> function, CopyPasteOptions copyPasteOptions = null)
        {
            if (document == null || string.IsNullOrWhiteSpace(path) || !System.IO.File.Exists(path) || function == null)
            {
                return(null);
            }

            Document document_source = null;

            try
            {
                document_source = new Autodesk.Revit.UI.UIDocument(document).Application.Application.OpenDocumentFile(path);
            }
            catch (Exception exception)
            {
                if (document_source != null)
                {
                    document_source.Close(false);
                }

                return(null);
            }

            IEnumerable <ElementId> result = null;

            if (document_source != null)
            {
                FilteredElementCollector filteredElementCollector = function.Invoke(document_source);
                List <ElementId>         elementIds = filteredElementCollector?.ToElementIds()?.ToList();
                if (elementIds != null && elementIds.Count != 0)
                {
                    if (copyPasteOptions == null)
                    {
                        copyPasteOptions = new CopyPasteOptions();
                        copyPasteOptions.SetDuplicateTypeNamesHandler(new DestinationDuplicateTypeNamesHandler());
                    }

                    result = ElementTransformUtils.CopyElements(document_source, elementIds, document, null, copyPasteOptions);
                }
            }

            document_source.Close(false);

            return(result);
        }
Exemplo n.º 15
0
        public static bool Release(this Document doc)
        {
            if (doc.IsValid())
            {
                try
                {
                    using (var uiDocument = new Autodesk.Revit.UI.UIDocument(doc))
                    {
                        if (uiDocument.GetOpenUIViews().Count == 0)
                        {
                            return(doc.Close(false));
                        }
                    }
                }
                catch (Autodesk.Revit.Exceptions.ArgumentException) { }
            }

            return(false);
        }
        public ModelSetupWizardViewModel(Autodesk.Revit.UI.UIDocument uidoc)
        {
            doc = uidoc.Document;
            ProjectInformation          = new BindableCollection <ProjectInformationParameter>(ElementCollectors.GetProjectInformationParameters(doc));
            Worksets                    = new BindableCollection <WorksetParameter>(ElementCollectors.GetWorksetParameters(doc));
            SelectedWorksets            = new List <WorksetParameter>();
            SelectedProjectInformations = new List <ProjectInformationParameter>();
            optionsVm                   = new ModelSetupWizardOptionsViewModel();
            NominatedArchitects         = optionsVm.NominatedArchitects;
            ColourSchemes               = optionsVm.ColourSchemes;
            NominatedArchitects.Insert(0, new NominatedArchitect("Architects Name", "0000"));
            selectedNominatedArchitect = NominatedArchitects[0];
            selectedColourScheme       = ColourSchemes[0];
            FileName = doc.PathName;

            var iniFile = IniIO.GetIniFile(doc);

            if (iniFile.Length > 0)
            {
                var colors = IniIO.ReadColours(iniFile);
                Colours = new BindableCollection <System.Windows.Media.Color>(colors);
            }
            else
            {
                SCaddinsApp.WindowManager.ShowMessageBox(iniFile + " does not exist");
            }

            var fileNameParam = ProjectInformation.Where(p => p.Name == ModelSetupWizardSettings.Default.FileNameParameterName);

            if (fileNameParam.Count() == 1)
            {
                if (string.IsNullOrEmpty(doc.PathName))
                {
                    SCaddinsApp.WindowManager.ShowMessageBox("Document not saved... filename cannot be assigned.");
                }
                var path = System.IO.Path.GetFileName(doc.PathName);
                fileNameParam.First().Value = path;
            }

            foreach (var pinf in optionsVm.ProjectInformationReplacements)
            {
                var match = ProjectInformation.Where(p => p.Name == pinf.ParamaterName);
                if (match.Count() == 1)
                {
                    match.First().Format = pinf.ReplacementFormat;
                    match.First().Value  = pinf.ReplacementValue;
                }
            }
            foreach (var winf in optionsVm.Worksets)
            {
                if (Worksets.Select(w => w.Name.Trim()).Contains(winf.Name.Trim()))
                {
                    continue;
                }
                if (!Worksets.Select(w => w.Name).Contains(winf.ExistingName.Trim()))
                {
                    Worksets.Add(winf);
                }
                var match = Worksets.Where(w => w.Name.Trim() == winf.ExistingName.Trim());
                if (match.Any())
                {
                    match.First().Name = winf.Name;
                }
            }
        }
Exemplo n.º 17
0
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            System.Diagnostics.Trace.Listeners.
            Add(new System.Diagnostics.EventLogTraceListener("Application"));

            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Autodesk.Revit.DB.Document   doc   = uidoc.Document;


            try {
                // set the location of a new .txt file
                string filePath = System.Environment
                                  .GetFolderPath(Environment.SpecialFolder.Personal) +
                                  "\\" + doc.Title + ".txt";

                // Create the .txt file containing shared parameter definitions
                using (System.IO.Stream s = System.IO.File.Create(filePath)) {
                    s.Close();
                }

                // set the file as a shared parameter source file to the application
                doc.Application.SharedParametersFilename = filePath;

                // Get access to the file
                Autodesk.Revit.DB.DefinitionFile defFile =
                    doc.Application.OpenSharedParameterFile();

                // Create a new group called 'ReadOnly'
                Autodesk.Revit.DB.DefinitionGroup defGroup =
                    defFile.Groups.Create("ReadOnly");

                // Create a new defintion
                Autodesk.Revit.DB.ExternalDefinitionCreationOptions defCrtOptns =
                    new Autodesk.Revit.DB.ExternalDefinitionCreationOptions
                        ("RM_BLOCK", Autodesk.Revit.DB.ParameterType.Text);
                defCrtOptns.UserModifiable = false;
                defCrtOptns.Visible        = true;

                // Insert the definition into the group
                Autodesk.Revit.DB.Definition def =
                    defGroup.Definitions.Create(defCrtOptns);

                // Lay out the categories to which the param
                // will be bound
                Autodesk.Revit.DB.CategorySet catSet =
                    new Autodesk.Revit.DB.CategorySet();
                catSet.Insert(doc.Settings.Categories
                              .get_Item(Autodesk.Revit.DB.BuiltInCategory.OST_Rooms));

                // Define a binding type
                Autodesk.Revit.DB.InstanceBinding instBnd =
                    new Autodesk.Revit.DB.InstanceBinding(catSet);

                // Bind the parameter to the active document
                using (Autodesk.Revit.DB.Transaction t =
                           new Autodesk.Revit.DB.Transaction(doc)) {
                    t.Start("Add Param");
                    Autodesk.Revit.DB.SubTransaction st =
                        new Autodesk.Revit.DB.SubTransaction(doc);
                    doc.ParameterBindings.Insert
                        (def, instBnd, Autodesk.Revit.DB.BuiltInParameterGroup.PG_DATA);
                    t.Commit();
                }

                Autodesk.Revit.DB.DefinitionBindingMapIterator itr =
                    doc.ParameterBindings.ForwardIterator();

                //
                while (itr.MoveNext())
                {
                    Autodesk.Revit.DB.InternalDefinition intDef = itr.Current as
                                                                  Autodesk.Revit.DB.InternalDefinition;
                }

                Autodesk.Revit.UI.TaskDialog.Show("Success",
                                                  string.Format("The parameter called {0} has been successfully added to the document",
                                                                def.Name));

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (System.Exception ex) {
                Autodesk.Revit.UI.TaskDialog.Show("Exception",
                                                  string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Exemplo n.º 18
0
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Trace.Listeners
            .Add(new System.Diagnostics.EventLogTraceListener("Application"));

            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Autodesk.Revit.DB.Document   doc   = uidoc.Document;

            try {
                // get hold of the print manager
                Autodesk.Revit.DB.PrintManager printManager =
                    doc.PrintManager;

                // select the printer
                printManager.SelectNewPrintDriver("Adobe PDF");
                printManager.PrintRange = Autodesk.Revit.DB.PrintRange.Select;
                if (printManager.IsVirtual != Autodesk.Revit.DB.VirtualPrinterType.AdobePDF)
                {
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // access the in-session print settings
                Autodesk.Revit.DB.IPrintSetting printSetting =
                    printManager.PrintSetup.InSession;

                printSetting.PrintParameters.PaperPlacement =
                    Autodesk.Revit.DB.PaperPlacementType.Margins;
                printSetting.PrintParameters.MarginType =
                    Autodesk.Revit.DB.MarginType.NoMargin;
                printSetting.PrintParameters.ZoomType = Autodesk.Revit.DB.ZoomType.Zoom;
                printSetting.PrintParameters.Zoom     = 100;

                //
                IList <Autodesk.Revit.DB.ViewSheetSet> viewSheetSets = GetViewSheetSet(doc);
                System.Text.StringBuilder strBld = new System.Text.StringBuilder();
                foreach (Autodesk.Revit.DB.ViewSheetSet vss in viewSheetSets)
                {
                    strBld.AppendLine(string.Format("Name:{0}; Views.Count={1}", vss.Name, vss.Views.Size));
                }
                Trace.Write(strBld.ToString());
                return(Autodesk.Revit.UI.Result.Succeeded);

                //

                // apply the updated settings and print
                foreach (Autodesk.Revit.DB.View view in printManager.ViewSheetSetting.AvailableViews)
                {
                    if (view.ViewType == Autodesk.Revit.DB.ViewType.DrawingSheet)
                    {
                        SetUpSizeAndPrint((ViewSheet)view, printManager, printSetting);
                    }
                }
                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (System.Exception ex) {
                Trace.Write(string.Format("Command Exception:\n{0}\n{1}",
                                          ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Exemplo n.º 19
0
        /***************************************************/
        /****             Protected Methods             ****/
        /***************************************************/

        protected override IEnumerable <IBHoMObject> Read(IRequest request, ActionConfig actionConfig = null)
        {
            Autodesk.Revit.UI.UIDocument uiDocument = this.UIDocument;
            Document document = this.Document;

            ICollection <ElementId> selected = uiDocument.Selection.GetElementIds();

            if (request == null)
            {
                BH.Engine.Reflection.Compute.RecordError("BHoM objects could not be read because provided IRequest is null.");
                return(new List <IBHoMObject>());
            }

            RevitPullConfig pullConfig = actionConfig as RevitPullConfig;

            if (pullConfig == null)
            {
                BH.Engine.Reflection.Compute.RecordError("BHoM objects could not be read because provided actionConfig is not a valid RevitPullConfig.");
                return(new List <IBHoMObject>());
            }

            Discipline?requestDiscipline = request.Discipline(pullConfig.Discipline);

            if (requestDiscipline == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Conflicting disciplines have been detected.");
                return(new List <IBHoMObject>());
            }

            IEnumerable <ElementId> worksetPrefilter = null;

            if (!pullConfig.IncludeClosedWorksets)
            {
                worksetPrefilter = document.ElementIdsByWorksets(document.OpenWorksetIds().Union(document.SystemWorksetIds()).ToList());
            }

            List <ElementId> elementIds = request.IElementIds(uiDocument, worksetPrefilter).RemoveGridSegmentIds(document).ToList <ElementId>();

            if (elementIds == null)
            {
                return(new List <IBHoMObject>());
            }

            Discipline discipline = requestDiscipline.Value;

            if (discipline == Discipline.Undefined)
            {
                discipline = Discipline.Physical;
            }

            RevitSettings revitSettings = RevitSettings.DefaultIfNull();

            PullGeometryConfig geometryConfig = pullConfig.GeometryConfig;

            if (geometryConfig == null)
            {
                geometryConfig = new PullGeometryConfig();
            }

            PullRepresentationConfig representationConfig = pullConfig.RepresentationConfig;

            if (representationConfig == null)
            {
                representationConfig = new PullRepresentationConfig();
            }

            if (pullConfig.IncludeNestedElements)
            {
                List <ElementId> elemIds = new List <ElementId>();
                foreach (ElementId id in elementIds)
                {
                    Element element = document.GetElement(id);
                    if (element is FamilyInstance)
                    {
                        FamilyInstance          famInst       = element as FamilyInstance;
                        IEnumerable <ElementId> nestedElemIds = famInst.ElementIdsOfMemberElements();
                        elemIds.AddRange(nestedElemIds);
                    }
                }
                elementIds.AddRange(elemIds);
            }

            Options geometryOptions   = BH.Revit.Engine.Core.Create.Options(ViewDetailLevel.Fine, geometryConfig.IncludeNonVisible, false);
            Options meshOptions       = BH.Revit.Engine.Core.Create.Options(geometryConfig.MeshDetailLevel.ViewDetailLevel(), geometryConfig.IncludeNonVisible, false);
            Options renderMeshOptions = BH.Revit.Engine.Core.Create.Options(representationConfig.DetailLevel.ViewDetailLevel(), representationConfig.IncludeNonVisible, false);

            List <IBHoMObject> result = new List <IBHoMObject>();
            Dictionary <string, List <IBHoMObject> > refObjects = new Dictionary <string, List <IBHoMObject> >();

            foreach (ElementId id in elementIds)
            {
                Element element = document.GetElement(id);
                if (element == null)
                {
                    continue;
                }

                IEnumerable <IBHoMObject> iBHoMObjects = Read(element, discipline, revitSettings, refObjects);
                if (iBHoMObjects != null && iBHoMObjects.Any())
                {
                    if (pullConfig.PullMaterialTakeOff)
                    {
                        foreach (IBHoMObject iBHoMObject in iBHoMObjects)
                        {
                            RevitMaterialTakeOff takeoff = element.MaterialTakeoff(revitSettings, refObjects);
                            if (takeoff != null)
                            {
                                iBHoMObject.Fragments.AddOrReplace(takeoff);
                            }
                        }
                    }

                    List <ICurve> edges = null;
                    if (geometryConfig.PullEdges)
                    {
                        edges = element.Curves(geometryOptions, revitSettings, true).FromRevit();
                    }

                    List <ISurface> surfaces = null;
                    if (geometryConfig.PullSurfaces)
                    {
                        surfaces = element.Faces(geometryOptions, revitSettings).Select(x => x.IFromRevit()).ToList();
                    }

                    List <oM.Geometry.Mesh> meshes = null;
                    if (geometryConfig.PullMeshes)
                    {
                        meshes = element.MeshedGeometry(meshOptions, revitSettings);
                    }

                    if (geometryConfig.PullEdges || geometryConfig.PullSurfaces || geometryConfig.PullMeshes)
                    {
                        RevitGeometry geometry = new RevitGeometry(edges, surfaces, meshes);
                        foreach (IBHoMObject iBHoMObject in iBHoMObjects)
                        {
                            iBHoMObject.Fragments.AddOrReplace(geometry);
                        }
                    }

                    if (representationConfig.PullRenderMesh)
                    {
                        List <RenderMesh>   renderMeshes   = element.RenderMeshes(renderMeshOptions, revitSettings);
                        RevitRepresentation representation = new RevitRepresentation(renderMeshes);
                        foreach (IBHoMObject iBHoMObject in iBHoMObjects)
                        {
                            iBHoMObject.Fragments.AddOrReplace(representation);
                        }
                    }

                    result.AddRange(iBHoMObjects);
                }
            }

            bool[] activePulls = new bool[] { geometryConfig.PullEdges, geometryConfig.PullSurfaces, geometryConfig.PullMeshes, representationConfig.PullRenderMesh };
            if (activePulls.Count(x => x == true) > 1)
            {
                BH.Engine.Reflection.Compute.RecordWarning("Pull of more than one geometry/representation type has been specified in RevitPullConfig. Please consider this can be time consuming due to the amount of conversions.");
            }

            uiDocument.Selection.SetElementIds(selected);

            return(result);
        }
Exemplo n.º 20
0
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Trace.Listeners
            .Add(new System.Diagnostics.EventLogTraceListener("Application"));

            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;

            try {
                // get hold of the print manager
                Autodesk.Revit.DB.PrintManager printManager =
                    doc.PrintManager;

                // select the printer
                printManager.SelectNewPrintDriver("Adobe PDF");
                printManager.PrintRange   = Autodesk.Revit.DB.PrintRange.Select;
                printManager.CombinedFile = false;
                if (printManager.IsVirtual != Autodesk.Revit.DB.VirtualPrinterType.AdobePDF)
                {
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // access the in-session print settings
                Autodesk.Revit.DB.IPrintSetting printSetting =
                    printManager.PrintSetup.InSession;

                printSetting.PrintParameters.PaperPlacement =
                    Autodesk.Revit.DB.PaperPlacementType.Margins;
                printSetting.PrintParameters.MarginType =
                    Autodesk.Revit.DB.MarginType.NoMargin;
                printSetting.PrintParameters.ZoomType      = Autodesk.Revit.DB.ZoomType.Zoom;
                printSetting.PrintParameters.Zoom          = 100;
                printSetting.PrintParameters.ColorDepth    = Autodesk.Revit.DB.ColorDepthType.BlackLine;
                printSetting.PrintParameters.RasterQuality = Autodesk.Revit.DB.RasterQualityType.High;
                //printManager.Apply();

                // Promt the user to select the sets to print out
                PrintWnd hwnd = new PrintWnd(doc);
                hwnd.ShowDialog();

                IList <RvtElement> sets = hwnd.SelectedSets;

                for (int i = 0; i < sets.Count; ++i)
                {
                    ViewSheetSet set = sets[i] as ViewSheetSet;

                    foreach (Autodesk.Revit.DB.View view in set.Views)
                    {
                        if (view is ViewSheet)
                        {
                            SetUpSizeAndPrint((ViewSheet)view, printManager, printSetting);
                        }
                    }
                }
                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (System.Exception ex) {
                Trace.Write(string.Format("Command Exception:\n{0}\n{1}",
                                          ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="rvtDoc">Revit active document</param>
 public CreationMgr(Autodesk.Revit.UI.UIDocument rvtDoc)
 {
     m_rvtDoc = rvtDoc;
 }
Exemplo n.º 22
0
        /// <summary>
        /// Duplicates A Sheet.
        /// </summary>
        /// <param name="sheet">The Sheet to be Duplicated.</param>
        /// <param name="duplicateWithContents">Set to true that Duplicate sheet with contents</param>
        /// <param name="duplicateWithView">Set to true that Duplicate sheet with views.</param>
        /// <param name="viewDuplicateOption">Enter View Duplicate Option: 0 = Duplicate. 1 = AsDependent. 2 = WithDetailing.</param>
        /// <param name="prefix"></param>
        /// <param name="suffix">When prefix and suffix are both empty, suffix will set a default value - " - Copy".</param>
        /// <returns></returns>
        public static Sheet DuplicateSheet(Sheet sheet, bool duplicateWithContents = false, bool duplicateWithView = false, int viewDuplicateOption = 0, string prefix = "", string suffix = "")
        {
            if (sheet == null)
            {
                throw new ArgumentNullException(nameof(sheet));
            }

            ViewDuplicateOption Option = 0;

            switch (viewDuplicateOption)
            {
            case 0:
                Option = ViewDuplicateOption.Duplicate;
                break;

            case 1:
                Option = ViewDuplicateOption.AsDependent;
                break;

            case 2:
                Option = ViewDuplicateOption.WithDetailing;
                break;

            default:
                throw new ArgumentException(Properties.Resources.ViewDuplicateOptionOutofRange);
            }

            if (String.IsNullOrEmpty(prefix) && String.IsNullOrEmpty(suffix))
            {
                suffix = " - Copy";
            }

            Sheet newSheet = null;

            try
            {
                RevitServices.Transactions.TransactionManager.Instance.EnsureInTransaction(Application.Document.Current.InternalDocument);

                var oldElements             = ElementBinder.GetElementsFromTrace <Autodesk.Revit.DB.Element>(Document);
                List <ElementId> elementIds = new List <ElementId>();
                var newSheetNumber          = prefix + sheet.SheetNumber + suffix;
                var newSheetName            = sheet.SheetName;
                List <Autodesk.Revit.DB.Element> TraceElements = new List <Autodesk.Revit.DB.Element>();

                if (oldElements != null)
                {
                    foreach (var element in oldElements)
                    {
                        elementIds.Add(element.Id);
                        if (element is ViewSheet)
                        {
                            var oldSheet = (element as ViewSheet).ToDSType(false) as Sheet;
                            if (oldSheet.SheetNumber.Equals(newSheetNumber))
                            {
                                if ((duplicateWithView && oldElements.Count() > 1) || (!duplicateWithView && oldElements.Count() == 1))
                                {
                                    newSheet = oldSheet;
                                    TraceElements.AddRange(oldElements);
                                }
                                if (newSheet != null)
                                {
                                    if (duplicateWithContents)
                                    {
                                        DuplicateSheetAnnotations(sheet, newSheet);
                                    }
                                    else
                                    {
                                        DeleteSheetAnnotations(newSheet);
                                    }
                                }
                            }
                        }
                    }
                    if (newSheet == null)
                    {
                        Autodesk.Revit.UI.UIDocument uIDocument = new Autodesk.Revit.UI.UIDocument(Document);
                        var openedViews       = uIDocument.GetOpenUIViews().ToList();
                        var shouldClosedViews = openedViews.FindAll(x => elementIds.Contains(x.ViewId));
                        if (shouldClosedViews.Count > 0)
                        {
                            foreach (var v in shouldClosedViews)
                            {
                                if (uIDocument.GetOpenUIViews().ToList().Count() > 1)
                                {
                                    v.Close();
                                }
                                else
                                {
                                    throw new InvalidOperationException(string.Format(Properties.Resources.CantCloseLastOpenView, v.ToString()));
                                }
                            }
                        }
                        Document.Delete(elementIds);
                    }
                }

                if (newSheet == null && TraceElements.Count == 0)
                {
                    // Create a new Sheet with different SheetNumber
                    var          titleBlockElement    = sheet.TitleBlock.First() as FamilyInstance;
                    FamilySymbol TitleBlock           = titleBlockElement.InternalFamilyInstance.Symbol;
                    FamilyType   titleBlockFamilyType = ElementWrapper.Wrap(TitleBlock, true);

                    if (!CheckUniqueSheetNumber(newSheetNumber))
                    {
                        throw new ArgumentException(String.Format(Properties.Resources.SheetNumberExists, newSheetNumber));
                    }

                    var viewSheet = Autodesk.Revit.DB.ViewSheet.Create(Document, TitleBlock.Id);
                    newSheet = new Sheet(viewSheet);
                    newSheet.InternalSetSheetName(newSheetName);
                    newSheet.InternalSetSheetNumber(newSheetNumber);

                    TraceElements.Add(newSheet.InternalElement);

                    // Copy Annotation Elements from sheet to new sheet by ElementTransformUtils.CopyElements
                    if (duplicateWithContents)
                    {
                        DuplicateSheetAnnotations(sheet, newSheet);
                    }

                    if (duplicateWithView)
                    {
                        // Copy ScheduleSheetInstance except RevisionSchedule from sheet to new sheet by ElementTransformUtils.CopyElements
                        DuplicateScheduleSheetInstance(sheet, newSheet);

                        // Duplicate Viewport in sheet and place on new sheet
                        TraceElements.AddRange(DuplicateViewport(sheet, newSheet, Option, prefix, suffix));
                    }
                }

                ElementBinder.SetElementsForTrace(TraceElements);
                RevitServices.Transactions.TransactionManager.Instance.TransactionTaskDone();
            }
            catch (Exception e)
            {
                if (newSheet != null)
                {
                    newSheet.Dispose();
                }
                throw e;
            }

            return(newSheet);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="rvtDoc">Revit active document</param>
 public CreationMgr(Autodesk.Revit.UI.UIDocument rvtDoc)
 {
     m_rvtDoc = rvtDoc;
 }
Exemplo n.º 24
0
 /// <summary>
 /// Constructor with Revit.Document as parameter.
 /// </summary>
 /// <param name="rvtDoc">Revit document</param>
 public GutterCreator(Autodesk.Revit.UI.UIDocument rvtDoc)
     : base(rvtDoc)
 {
 }
Exemplo n.º 25
0
 /// <summary>
 /// Constructor takes Revit.Document as parameter.
 /// </summary>
 /// <param name="rvtDoc">Revit document</param>
 public SlabEdgeCreator(Autodesk.Revit.UI.UIDocument rvtDoc)
     : base(rvtDoc)
 {
 }
Exemplo n.º 26
0
        /// <summary>
        /// Duplicates A view.
        /// </summary>
        /// <param name="view">The View to be Duplicated</param>
        /// <param name="viewDuplicateOption">Enter View Duplicate Option: Duplicate, AsDependent or WithDetailing.</param>
        /// <param name="prefix"></param>
        /// <param name="suffix"></param>
        /// <returns></returns>
        public static Revit.Elements.Views.View DuplicateView(View view, string viewDuplicateOption = "Duplicate", string prefix = "", string suffix = "")
        {
            View newView = null;

            if (view == null)
            {
                throw new ArgumentNullException(nameof(view));
            }
            if (view is Sheet)
            {
                throw new ArgumentException(Properties.Resources.DuplicateViewCantApplySheet);
            }

            ViewDuplicateOption Option = (ViewDuplicateOption)Enum.Parse(typeof(ViewDuplicateOption), viewDuplicateOption);

            try
            {
                RevitServices.Transactions.TransactionManager.Instance.EnsureInTransaction(Application.Document.Current.InternalDocument);
                var viewElement = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.View>(Document);

                int    count       = 0;
                string newViewName = "";
                if (!String.IsNullOrEmpty(prefix) || !String.IsNullOrEmpty(suffix))
                {
                    newViewName = prefix + view.Name + suffix;
                }
                Autodesk.Revit.UI.UIDocument uIDocument = new Autodesk.Revit.UI.UIDocument(Document);
                var openedViews = uIDocument.GetOpenUIViews().ToList();

                if (viewElement != null)
                {
                    count++;
                    var oldViewName = viewElement.Name;
                    if (oldViewName.Equals(newViewName))
                    {
                        newView = viewElement.ToDSType(false) as View;
                    }
                    else
                    {
                        count--;
                    }
                }

                if (count == 0)
                {
                    if (!CheckUniqueViewName(newViewName))
                    {
                        throw new ArgumentException(String.Format(Properties.Resources.ViewNameExists, newViewName));
                    }
                    if (view.InternalView.CanViewBeDuplicated(Option))
                    {
                        var viewID  = view.InternalView.Duplicate(Option);
                        var viewEle = Document.GetElement(viewID) as Autodesk.Revit.DB.View;
                        newView = ElementWrapper.ToDSType(viewEle, false) as View;
                    }
                    else
                    {
                        throw new Exception(String.Format(Properties.Resources.ViewCantBeDuplicated, view.Name));
                    }

                    if (!String.IsNullOrEmpty(newViewName))
                    {
                        var param = newView.InternalView.get_Parameter(BuiltInParameter.VIEW_NAME);
                        param.Set(newViewName);
                    }
                    if (viewElement != null)
                    {
                        var shouldClosedViews = openedViews.FindAll(x => viewElement.Id == x.ViewId);
                        if (shouldClosedViews.Count > 0)
                        {
                            foreach (var v in shouldClosedViews)
                            {
                                if (uIDocument.GetOpenUIViews().ToList().Count() > 1)
                                {
                                    v.Close();
                                }
                                else
                                {
                                    throw new InvalidOperationException(string.Format(Properties.Resources.CantCloseLastOpenView, viewElement.ToString()));
                                }
                            }
                        }
                    }
                }

                ElementBinder.CleanupAndSetElementForTrace(Document, newView.InternalElement);

                RevitServices.Transactions.TransactionManager.Instance.TransactionTaskDone();
            }
            catch (Exception e)
            {
                //if (e is Autodesk.Revit.Exceptions.InvalidOperationException)
                //    throw e;
                if (newView != null)
                {
                    newView.Dispose();
                }
                throw e;
            }

            return(newView);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Constructor which take Revit.Document as parameter.
 /// </summary>
 /// <param name="rvtDoc">Revit document</param>
 public FasciaCreator(Autodesk.Revit.UI.UIDocument rvtDoc)
     : base(rvtDoc)
 {
 }
Exemplo n.º 28
0
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.
                                                ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Tracer.Listeners.Add(new System.Diagnostics.EventLogTraceListener("Application"));

            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;

            try {
                // Set the minimum wall width
                double minWallWidth = UnitUtils
                                      .ConvertToInternalUnits(400, DisplayUnitType.DUT_MILLIMETERS); // 400mm

                // Select all walls wider than 400 mm
                ElementParameterFilter widthFilter =
                    new ElementParameterFilter(ParameterFilterRuleFactory
                                               .CreateGreaterOrEqualRule(new ElementId(BuiltInParameter.WALL_ATTR_WIDTH_PARAM),
                                                                         minWallWidth, 0.1));

                IList <Wall> walls = new FilteredElementCollector(doc)
                                     .OfClass(typeof(Wall))
                                     .WhereElementIsNotElementType()
                                     .WherePasses(widthFilter)
                                     .Cast <Wall>()
                                     .ToList();

                Tracer.Write("The number of walls in the project: " + walls.Count);

                using (Transaction t = new Transaction(doc, "Join walls")) {
                    FailureHandlingOptions handlingOptions = t.GetFailureHandlingOptions();
                    handlingOptions.SetFailuresPreprocessor(new AllWarningSwallower());
                    t.SetFailureHandlingOptions(handlingOptions);
                    t.Start();

                    foreach (Wall wall in walls)
                    {
                        IList <Element> intrudingWalls =
                            GetWallsIntersectBoundingBox(doc, wall, minWallWidth);

                        Tracer.Write(string.Format("Wall {0} is intersected by {1} walls",
                                                   wall.Id.ToString(), intrudingWalls.Count));

                        foreach (Element elem in intrudingWalls)
                        {
                            if (//((Wall)elem).WallType.Width < minWallWidth ||
                                ((Wall)elem).WallType.Kind == WallKind.Curtain)
                            {
                                continue;
                            }
                            try {
                                if (!JoinGeometryUtils.AreElementsJoined(doc, wall, elem))
                                {
                                    JoinGeometryUtils.JoinGeometry(doc, wall, elem);
                                }
                            }
                            catch (Exception ex) {
                                Tracer.Write(string.Format("{0}\nWall: {1} cannot be joined to {2}",
                                                           ex.Message, wall.Id.ToString(), elem.Id.ToString()));
                                continue;
                            }
                        }
                    }
                    t.Commit();
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (Exception ex) {
                Tracer.Write(string.Format("{0}\n{1}",
                                           ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }