Example #1
0
        public static List <global::Revit.Elements.Element> IntersectingElementsInRoom(global::Revit.Elements.Room room, global::Revit.Elements.Category category)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;

            Autodesk.DesignScript.Geometry.Solid roomSolid = Autodesk.DesignScript.Geometry.Solid.ByUnion(room.Solids);

            //get built in category from user viewable category
            BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());

            //start the transaction
            TransactionManager.Instance.EnsureInTransaction(doc);
            //builds an id collection for later deletion
            ICollection <ElementId> idCollection = new List <ElementId>();

            global::Revit.Elements.DirectShape directShape = global::Revit.Elements.DirectShape.ByGeometry(roomSolid, global::Revit.Elements.Category.ByName("Generic Models"), global::Revit.Elements.DirectShape.DynamoPreviewMaterial, "DirectShape");
            idCollection.Add(directShape.InternalElement.Id);
            TransactionManager.Instance.TransactionTaskDone();
            doc.Regenerate();
            ElementIntersectsElementFilter filter = new ElementIntersectsElementFilter(directShape.InternalElement);
            //build a collector
            FilteredElementCollector          collector = new FilteredElementCollector(doc);
            IList <Autodesk.Revit.DB.Element> intersectingElementsInternaList = collector.OfCategory(myCatEnum).WhereElementIsNotElementType().WherePasses(filter).ToElements();
            //build a list to output geometry
            List <global::Revit.Elements.Element> intersectingElements = new List <global::Revit.Elements.Element>();

            //append the intersecting elements to the output list
            foreach (Autodesk.Revit.DB.Element thing in intersectingElementsInternaList)
            {
                intersectingElements.Add(thing.ToDSType(true));
            }
            //delete the direct shapes as we do not need them any longer
            TransactionManager.Instance.EnsureInTransaction(doc);
            foreach (ElementId id in idCollection)
            {
                doc.Delete(id);
            }
            TransactionManager.Instance.TransactionTaskDone();

            return(intersectingElements);
        }
        public static List <global::Revit.Elements.Element> ByCategory(List <global::Revit.Elements.Element> elements, object category, string filterMethod)
        {
            List <string> potentialFilterMethod = new List <string>(new string[] { "Contains", "DoesNotContain", "StartsWith", "DoesNotStartWith", "EndsWith", "DoesNotEndWith", "Equals", "DoesNotEqual", "==", "!=" });
            List <global::Revit.Elements.Element> filteredElements = null;
            string     filterMethodToUse = null;
            List <int> values            = new List <int>();
            string     value             = null;

            foreach (string i in potentialFilterMethod)
            {
                values.Add(StringComparisonUtilities.Compute(filterMethod, i));
            }
            int minIndex = values.IndexOf(values.Min());

            filterMethodToUse = potentialFilterMethod[minIndex];
            //assign the value based on if the input is a string or category
            if (category is string)
            {
                value = category as string;
            }
            else
            {
                global::Revit.Elements.Category cat = (global::Revit.Elements.Category)category;
                value = cat.Name;
            }

            //scenarios
            if (filterMethodToUse == "Contains")
            {
                filteredElements = new List <Element>(elements.Where(e => e.GetCategory.Name.Contains(value)).ToArray());
            }
            if (filterMethodToUse == "DoesNotContain")
            {
                filteredElements = new List <Element>(elements.Where(e => !e.GetCategory.Name.Contains(value)).ToArray());
            }
            if (filterMethodToUse == "StartsWith")
            {
                filteredElements = new List <Element>(elements.Where(e => e.GetCategory.Name.StartsWith(value)).ToArray());
            }
            if (filterMethodToUse == "DoesNotStartWith")
            {
                filteredElements = new List <Element>(elements.Where(e => !e.GetCategory.Name.StartsWith(value)).ToArray());
            }
            if (filterMethodToUse == "EndsWith")
            {
                filteredElements = new List <Element>(elements.Where(e => e.GetCategory.Name.EndsWith(value)).ToArray());
            }
            if (filterMethodToUse == "DoesNotEndWith")
            {
                filteredElements = new List <Element>(elements.Where(e => !e.GetCategory.Name.EndsWith(value)).ToArray());
            }
            if (filterMethodToUse == "Equals" || filterMethodToUse == "==")
            {
                filteredElements = new List <Element>(elements.Where(e => e.GetCategory.Name.Equals(value)).ToArray());
            }
            if (filterMethodToUse == "DoesNotEqual" || filterMethodToUse == "!=")
            {
                filteredElements = new List <Element>(elements.Where(e => !e.GetCategory.Name.Equals(value)).ToArray());
            }

            return(filteredElements);
        }
Example #3
0
        public static Dictionary <string, object> ByRoom(string familyTemplatePath, global::Revit.Elements.Room room, string materialName, global::Revit.Elements.Category category, string subcategory = "")
        {
            //variables
            global::Revit.Elements.Element   famInstance = null;
            Autodesk.Revit.DB.FamilyInstance internalFam = null;
            bool fileFound = false;

            //the current document
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            UIApplication uiapp            = new UIApplication(doc.Application);

            //convert the room to an Autodesk.Revit.DB representation
            Autodesk.Revit.DB.Architecture.Room internalRoom = (Autodesk.Revit.DB.Architecture.Room)room.InternalElement;
            string name = internalRoom.Name;

            //we close all of the families because we need to swap documents
            foreach (Document d in uiapp.Application.Documents)
            {
                if (d.IsFamilyDocument)
                {
                    d.Close(false);
                }
            }
            //create the new family document in the background and store it in memory
            Document familyDocument = uiapp.Application.NewFamilyDocument(familyTemplatePath);
            //instantiate a material element id and try to get the material that was specified
            ElementId material = null;
            FilteredElementCollector materialCollector = new FilteredElementCollector(familyDocument).OfClass(typeof(Autodesk.Revit.DB.Material));

            foreach (var m in materialCollector)
            {
                if (m.Name.ToLower().Replace(" ", "") == materialName.ToLower().Replace(" ", ""))
                {
                    material = m.Id;
                }
            }
            //close Dynamo's open transaction, we need to do this because we open a new Revit API transaction in the family document (This is document switching)
            TransactionManager.Instance.ForceCloseTransaction();
            //start creating the families.
            Transaction trans = new Transaction(familyDocument, "Generate Families Ya'll");

            trans.Start();
            //set the family category
            Autodesk.Revit.DB.Category familyCategory = familyDocument.Settings.Categories.get_Item(category.Name);
            familyDocument.OwnerFamily.FamilyCategory = familyCategory;
            //get the subcategory for the solids
            Autodesk.Revit.DB.Category subCategory = null;
            foreach (Autodesk.Revit.DB.Category c in familyCategory.SubCategories)
            {
                if (c.Name.ToLower() == subcategory.ToLower())
                {
                    subCategory = c;
                }
            }
            //get the height of the thing
            double height = room.Height;
            //get the curves
            IList <IList <BoundarySegment> > boundary = internalRoom.GetBoundarySegments(new SpatialElementBoundaryOptions());

            //generate a plane
            Autodesk.Revit.DB.Plane       revitPlane  = Autodesk.Revit.DB.Plane.CreateByNormalAndOrigin(Vector.ZAxis().ToXyz(), new XYZ(0, 0, 0));
            Autodesk.Revit.DB.SketchPlane sketchPlane = SketchPlane.Create(familyDocument, revitPlane);
            //the curve arrays to generate solids and voids in family
            CurveArray    curveArray        = new CurveArray();
            CurveArrArray curveArrArray     = new CurveArrArray();
            CurveArray    curveArrayVoid    = new CurveArray();
            CurveArrArray curveArrArrayVoid = new CurveArrArray();
            //to perform  the cut action on the solid with the voids
            CombinableElementArray ceArray = new CombinableElementArray();
            //transform bizness
            Point            roomCentroid  = room.BoundingBox.ToCuboid().Centroid();
            Point            locationPoint = Point.ByCoordinates(roomCentroid.X, roomCentroid.Y, 0);
            CoordinateSystem oldCS         = CoordinateSystem.ByOrigin(locationPoint);
            CoordinateSystem newCS         = CoordinateSystem.ByOrigin(0, 0, 0);

            //flag to step through the boundaries.
            int flag = 0;

            while (flag < boundary.Count)
            {
                //the first set of curves is the solid's boundary
                if (flag == 0)
                {
                    //generate the solid form which is the first item in the boundary segments.
                    foreach (BoundarySegment b in boundary[flag])
                    {
                        Autodesk.DesignScript.Geometry.Curve c          = b.GetCurve().ToProtoType();
                        Autodesk.DesignScript.Geometry.Curve movedCurve = c.Transform(oldCS, newCS) as Autodesk.DesignScript.Geometry.Curve;
                        curveArray.Append(movedCurve.ToRevitType());
                    }
                    curveArrArray.Append(curveArray);
                    Extrusion solidExtrusion = familyDocument.FamilyCreate.NewExtrusion(true, curveArrArray, sketchPlane, height);
                    if (material != null)
                    {
                        //Set the material
                        Autodesk.Revit.DB.Parameter matParam = solidExtrusion.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM);
                        matParam.Set(material);
                    }
                    //try to set the subcategory
                    if (subCategory != null)
                    {
                        solidExtrusion.Subcategory = subCategory;
                    }
                }
                //subsequent lists of curves are representative of the voids
                else
                {
                    //clear the curves from the collection for all items after the second one. (index 2+)
                    if (!curveArrayVoid.IsEmpty)
                    {
                        curveArrayVoid.Clear();
                        curveArrArrayVoid.Clear();
                        ceArray.Clear();
                    }
                    //generate the void form
                    foreach (BoundarySegment b in boundary[flag])
                    {
                        Autodesk.DesignScript.Geometry.Curve c          = b.GetCurve().ToProtoType();
                        Autodesk.DesignScript.Geometry.Curve movedCurve = c.Transform(oldCS, newCS) as Autodesk.DesignScript.Geometry.Curve;
                        curveArrayVoid.Append(movedCurve.ToRevitType());
                    }
                    curveArrArrayVoid.Append(curveArrayVoid);
                    Extrusion voidExtrusion = familyDocument.FamilyCreate.NewExtrusion(false, curveArrArrayVoid, sketchPlane, height);

                    //try to combine things
                    foreach (Extrusion genericForm in new FilteredElementCollector(familyDocument).OfClass(typeof(Extrusion))
                             .Cast <Extrusion>())
                    {
                        ceArray.Append(genericForm);
                    }
                    //to add the void to the solid
                    familyDocument.CombineElements(ceArray);
                }
                flag++;
            }
            familyDocument.Regenerate();
            trans.Commit();

            Autodesk.Revit.DB.Family fam = null;
            //build the temporary path
            string familyFilePath = Path.GetTempPath() + name + ".rfa";

            SaveAsOptions opt = new SaveAsOptions();

            opt.OverwriteExistingFile = true;
            familyDocument.SaveAs(familyFilePath, opt);
            familyDocument.Close(false);

            TransactionManager.Instance.ForceCloseTransaction();
            Transaction trans2 = new Transaction(doc, "Attempting to place or update Room family instances.");

            trans2.Start();
            IFamilyLoadOptions loadOptions = new FamilyImportOptions();
            bool variable = true;

            loadOptions.OnFamilyFound(true, out variable);
            doc.LoadFamily(familyFilePath, loadOptions, out fam);

            FamilySymbol familySymbol = (FamilySymbol)doc.GetElement(fam.GetFamilySymbolIds().First());
            //try to find if it is placed already
            FilteredElementCollector col = new FilteredElementCollector(doc);
            //get built in category from user viewable category
            BuiltInCategory myCatEnum =
                (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());

            foreach (Autodesk.Revit.DB.Element e in col.WhereElementIsNotElementType().OfCategory(myCatEnum).ToElements())
            {
                Autodesk.Revit.DB.FamilySymbol type = (FamilySymbol)doc.GetElement(e.GetTypeId());
                if (type.FamilyName.Equals(name))
                {
                    fileFound   = true;
                    internalFam = e as Autodesk.Revit.DB.FamilyInstance;
                }
            }
            //place families that are not placed
            if (fileFound == false)
            {
                if (!familySymbol.IsActive)
                {
                    familySymbol.Activate();
                }

                internalFam = doc.Create.NewFamilyInstance(new XYZ(roomCentroid.X, roomCentroid.Y, 0), familySymbol, internalRoom.Level,
                                                           StructuralType.NonStructural);
            }
            trans2.Commit();
            //delete the temp file
            File.Delete(familyFilePath);
            //cast to Dynamo type for output and location updating (if necessary)
            famInstance = internalFam.ToDSType(true);
            if (fileFound)
            {
                famInstance.SetLocation(locationPoint);
            }
            //returns the outputs
            var outInfo = new Dictionary <string, object>
            {
                { "familyInstance", famInstance }
            };

            return(outInfo);
        }
        /// <summary>
        /// This node will collect all elements of the given category from given document.
        /// </summary>
        /// <param name="document">The document to collect from.</param>
        /// <param name="category">The category to collect.</param>
        /// <returns name="element">The elements.</returns>
        /// <search>
        /// All Elements of Category in Document
        /// </search>
        public static List <global::Revit.Elements.Element> ElementsOfCategoryInDocument(Autodesk.Revit.DB.Document document, global::Revit.Elements.Category category)
        {
            //generate the category id from the input user viewable category
            Autodesk.Revit.DB.ElementId categoryId = new ElementId(category.Id);

            FilteredElementCollector coll = new FilteredElementCollector(document);
            List <global::Revit.Elements.Element> elems =
                new List <global::Revit.Elements.Element>(coll.OfCategoryId(categoryId).ToElements()
                                                          .Select(e => e.ToDSType(true)));

            return(elems);
        }
Example #5
0
        public static List <global::Revit.Elements.Element> ElementsOfCategoryInDocument(object document, global::Revit.Elements.Category category)
        {
            Document doc = null;

            //this enables cross-compatibility with orchid documents by converting them to built in Autodesk.Revit.DB.Documents
            if (document.GetType().ToString().Contains("Orchid"))
            {
                doc = DocumentUtils.OrchidDocumentToDbDocument(document);
            }
            else
            {
                doc = document as Document;
            }

            //generate the category id from the input user viewable category
            Autodesk.Revit.DB.ElementId categoryId = new ElementId(category.Id);

            FilteredElementCollector coll = new FilteredElementCollector(doc);
            List <global::Revit.Elements.Element> elems =
                new List <global::Revit.Elements.Element>(coll.OfCategoryId(categoryId).ToElements()
                                                          .Select(e => e.ToDSType(true)));

            return(elems);
        }
Example #6
0
        public static List <global::Revit.Elements.Element> DependentElementsOfCategory(global::Revit.Elements.Element element, global::Revit.Elements.Category category)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            //obtain the builtin category from the id
            BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());

            //the filter to use
            Autodesk.Revit.DB.ElementFilter elemFilter = new ElementCategoryFilter(myCatEnum);
            //dependent element ids
            IList <ElementId> elemIds = element.InternalElement.GetDependentElements(elemFilter);
            //get the elements
            List <global::Revit.Elements.Element> elems = new List <global::Revit.Elements.Element>(elemIds.Select(e => doc.GetElement(new ElementId(e.IntegerValue)).ToDSType(true)));

            return(elems);
        }
Example #7
0
        public static List <global::Revit.Elements.Element> GetIntersectingElementsOfCategoryLinkOption(global::Revit.Elements.Element element,
                                                                                                        global::Revit.Elements.Category category, [DefaultArgument("Rhythm.Revit.Elements.Element.GetNull()")] global::Revit.Elements.Element sourceInstance)
        {
            //the current document
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            //get built in category from user viewable category
            BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());
            //build a new list for the intersecting elements to be added to
            List <global::Revit.Elements.Element> intersectingElements = new List <global::Revit.Elements.Element>();

            if (sourceInstance != null)
            {
                Autodesk.Revit.DB.RevitLinkInstance internalInstance =
                    (Autodesk.Revit.DB.RevitLinkInstance)sourceInstance.InternalElement;
                //get the element's geometry.
                GeometryElement geomElement = element.InternalElement.get_Geometry(new Options());
                //transform the solid to where the eff the link is.
                GeometryElement transformedElement = geomElement.GetTransformed(internalInstance.GetTransform());
                //make a solid filter.
                Solid solid = null;
                foreach (GeometryObject geomObj in transformedElement)
                {
                    solid = geomObj as Solid;
                    if (solid != null)
                    {
                        break;
                    }
                }
                //the intersection filter
                ElementIntersectsSolidFilter filter = new ElementIntersectsSolidFilter(solid);
                //build a collector
                FilteredElementCollector collector = new FilteredElementCollector(doc);
                //collect the elements that fall in that category
                IList <Autodesk.Revit.DB.Element> intersectingElementsInternaList =
                    collector.OfCategory(myCatEnum).WhereElementIsNotElementType().WherePasses(filter).ToElements();

                //add each user recognizable element to the list
                foreach (Autodesk.Revit.DB.Element internalElement in intersectingElementsInternaList)
                {
                    intersectingElements.Add(internalElement.ToDSType(true));
                }
            }
            else
            {
                //the intersection filter
                ElementIntersectsElementFilter filter = new ElementIntersectsElementFilter(element.InternalElement);
                //build a collector
                FilteredElementCollector collector = new FilteredElementCollector(doc);
                //collect the elements that fall in that category
                IList <Autodesk.Revit.DB.Element> intersectingElementsInternaList =
                    collector.OfCategory(myCatEnum).WhereElementIsNotElementType().WherePasses(filter).ToElements();

                //add each user recognizable element to the list
                foreach (Autodesk.Revit.DB.Element internalElement in intersectingElementsInternaList)
                {
                    intersectingElements.Add(internalElement.ToDSType(true));
                }
            }

            return(intersectingElements);
        }
Example #8
0
        public static List <global::Revit.Elements.Element> GetIntersectingElementsOfCategory(global::Revit.Elements.Element element,
                                                                                              global::Revit.Elements.Category category)
        {
            //the current document
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            //get built in category from user viewable category
            BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());
            //the intersection filter
            ElementIntersectsElementFilter filter = new ElementIntersectsElementFilter(element.InternalElement);
            //build a collector
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            //collect the elements that fall in that category
            IList <Autodesk.Revit.DB.Element> intersectingElementsInternaList =
                collector.OfCategory(myCatEnum).WhereElementIsNotElementType().WherePasses(filter).ToElements();
            //build a new list for the intersecting elements to be added to
            List <global::Revit.Elements.Element> intersectingElements = new List <global::Revit.Elements.Element>();

            //add each user recognizable element to the list
            foreach (Autodesk.Revit.DB.Element internalElement in intersectingElementsInternaList)
            {
                intersectingElements.Add(internalElement.ToDSType(true));
            }

            return(intersectingElements);
        }