public List<XYZ> GetInternalPoints(FamilyInstance adaptiveComponent)
 {
     var pts = new List<XYZ>();
     var ids = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(adaptiveComponent);
     foreach (var id in ids)
     {
         var p = DocumentManager.Instance.CurrentDBDocument.GetElement(id) as Autodesk.Revit.DB.ReferencePoint;
         pts.Add(p.Position);
     }
     return pts;
 }
Example #2
0
 /// <summary>
 /// Internal constructor for existing Elements.
 /// </summary>
 /// <param name="familyInstance"></param>
 private AdaptiveComponent(Autodesk.Revit.DB.FamilyInstance familyInstance)
 {
     InternalSetFamilyInstance(familyInstance);
 }
 /// <summary>
 /// Initialize a FamilyInstance element
 /// </summary>
 /// <param name="instance"></param>
 private void InitFamilyInstance(Autodesk.Revit.DB.FamilyInstance instance)
 {
     InternalSetFamilyInstance(instance);
 }
 /// <summary>
 /// Wrap an existing FamilyInstance.
 /// </summary>
 /// <param name="instance"></param>
 protected FamilyInstance(Autodesk.Revit.DB.FamilyInstance instance)
 {
     SafeInit(() => InitFamilyInstance(instance));
 }
        void ReconstructBeamByCurve
        (
            DB.Document doc,
            ref DB.FamilyInstance element,

            Rhino.Geometry.Curve curve,
            Optional <DB.FamilySymbol> type,
            Optional <DB.Level> level
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            if
            (
                ((curve = curve.ChangeUnits(scaleFactor)) is null) ||
                curve.IsClosed ||
                !curve.TryGetPlane(out var axisPlane, Revit.VertexTolerance) ||
                curve.GetNextDiscontinuity(Rhino.Geometry.Continuity.C2_continuous, curve.Domain.Min, curve.Domain.Max, out var _)
            )
            {
                ThrowArgumentException(nameof(curve), "Curve must be a C2 continuous planar non closed curve.");
            }

            SolveOptionalLevel(doc, curve, ref level, out var bbox);

            var centerLine = curve.ToHost();

            if (type.HasValue)
            {
                ChangeElementTypeId(ref element, type.Value.Id);
            }

            // Try to update Beam
            if (element is object && element.Location is DB.LocationCurve locationCurve && centerLine.IsSameKindAs(locationCurve.Curve))
            {
                var referenceLevel = element.get_Parameter(DB.BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM);
                var updateLevel    = referenceLevel.AsElementId() != level.Value.Id;

                if (!updateLevel || !referenceLevel.IsReadOnly)
                {
                    if (updateLevel)
                    {
                        referenceLevel.Set(level.Value.Id);
                    }

                    locationCurve.Curve = centerLine;
                    return;
                }
            }

            // Reconstruct Beam
            {
                SolveOptionalType(ref type, doc, DB.BuiltInCategory.OST_StructuralFraming, nameof(type));

                var newBeam = doc.Create.NewFamilyInstance
                              (
                    centerLine,
                    type.Value,
                    level.Value,
                    DB.Structure.StructuralType.Beam
                              );

                newBeam.get_Parameter(DB.BuiltInParameter.Y_JUSTIFICATION).Set((int)DB.Structure.YJustification.Origin);
                newBeam.get_Parameter(DB.BuiltInParameter.Z_JUSTIFICATION).Set((int)DB.Structure.ZJustification.Origin);

                if (element is object && DB.Structure.StructuralFramingUtils.IsJoinAllowedAtEnd(element, 0))
                {
                    DB.Structure.StructuralFramingUtils.AllowJoinAtEnd(newBeam, 0);
                }
                else
                {
                    DB.Structure.StructuralFramingUtils.DisallowJoinAtEnd(newBeam, 0);
                }

                if (element is object && DB.Structure.StructuralFramingUtils.IsJoinAllowedAtEnd(element, 1))
                {
                    DB.Structure.StructuralFramingUtils.AllowJoinAtEnd(newBeam, 1);
                }
                else
                {
                    DB.Structure.StructuralFramingUtils.DisallowJoinAtEnd(newBeam, 1);
                }

                var parametersMask = new DB.BuiltInParameter[]
                {
                    DB.BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM,
                    DB.BuiltInParameter.ELEM_FAMILY_PARAM,
                    DB.BuiltInParameter.ELEM_TYPE_PARAM,
                    DB.BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM
                };

                ReplaceElement(ref element, newBeam, parametersMask);
            }
        }
Example #6
0
        public void init()
        {
            SetDoorOffsetForm form   = new SetDoorOffsetForm();
            DialogResult      result = form.ShowDialog();

            if (result == DialogResult.OK)
            {
                offsetValue = form.getOffset();
            }


            List <Tuple <Autodesk.Revit.DB.FamilyInstance, Autodesk.Revit.DB.Wall> > selectedDoorsAndWalls = new List <Tuple <FamilyInstance, Wall> >();

            try
            {
                while (true)
                {
                    Autodesk.Revit.DB.FamilyInstance selectedDoor = null;
                    Autodesk.Revit.DB.Wall           selectedWall = null;

                    while (selectedDoor == null)
                    {
                        Reference selectedReference = uidoc.Selection.PickObject(ObjectType.Element, "Select doors in order to set offset. Press ESC key when finished.");
                        if (selectedReference != null)
                        {
                            ElementId selectedElementId = selectedReference.ElementId;
                            if (selectedElementId != null)
                            {
                                Element selectedElement = this.doc.GetElement(selectedElementId);
                                if (selectedElement != null)
                                {
                                    if (selectedElement.Category.Name == "Doors")
                                    {
                                        if (selectedElement is FamilyInstance)
                                        {
                                            selectedDoor = selectedElement as FamilyInstance;
                                        }
                                    }
                                    else
                                    {
                                        TaskDialog.Show("Info", "Your selection is not a door, it will not be counted.");
                                    }
                                }
                            }
                        }
                    }

                    while (selectedWall == null)
                    {
                        Reference selectedReference = uidoc.Selection.PickObject(ObjectType.Element, "Select a wall in order to set offset. Press ESC key when finished.");
                        if (selectedReference != null)
                        {
                            ElementId selectedElementId = selectedReference.ElementId;
                            if (selectedElementId != null)
                            {
                                Element selectedElement = this.doc.GetElement(selectedElementId);
                                if (selectedElement != null)
                                {
                                    if (selectedElement is Wall)
                                    {
                                        selectedWall = selectedElement as Wall;
                                    }
                                    else
                                    {
                                        TaskDialog.Show("Info", "Your selection is not a wall it will not be counted.");
                                    }
                                }
                            }
                        }
                    }


                    if ((selectedDoor != null) && (selectedWall != null))
                    {
                        selectedDoorsAndWalls.Add(new Tuple <FamilyInstance, Wall>(selectedDoor, selectedWall));
                    }
                }
            }
            catch (Exception ex)
            {
            }

            if (selectedDoorsAndWalls.Count > 0)
            {
                SetDoorOffsetHandler handler = new SetDoorOffsetHandler(selectedDoorsAndWalls, this.offsetValue);
                ExternalEvent        exEvent = ExternalEvent.Create(handler);
                exEvent.Raise();
            }
        }
Example #7
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);
        }
Example #8
0
 public Panel(DB.FamilyInstance value) : base(value)
 {
 }
Example #9
0
        public static SpeckleObject ColumnToSpeckle(Autodesk.Revit.DB.FamilyInstance myFamily)
        {
            var myColumn = new Column();

            var baseLevel = (Autodesk.Revit.DB.Level)Doc.GetElement(myFamily.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId());
            var topLevel  = (Autodesk.Revit.DB.Level)Doc.GetElement(myFamily.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId());

            var topOffsetParam    = myFamily.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM);
            var bottomOffsetParam = myFamily.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM);

            var topOffset = topOffsetParam != null?UnitUtils.ConvertFromInternalUnits(topOffsetParam.AsDouble(), topOffsetParam.DisplayUnitType) : 0;

            var bottomOffset = bottomOffsetParam != null?UnitUtils.ConvertFromInternalUnits(bottomOffsetParam.AsDouble(), bottomOffsetParam.DisplayUnitType) : 0;

            myColumn.baseLevel = baseLevel?.ToSpeckle();
            myColumn.topLevel  = topLevel?.ToSpeckle();

            try
            {
                myColumn.baseLine = (SpeckleCoreGeometryClasses.SpeckleLine)SpeckleCore.Converter.Serialise(myFamily.GetAnalyticalModel().GetCurve());
            }
            catch
            {
                var basePt = (myFamily.Location as LocationPoint).Point;
                basePt = new XYZ(basePt.X, basePt.Y, basePt.Z + bottomOffset);
                var topPt = new XYZ(basePt.X, basePt.Y, topLevel.Elevation + topOffset);
                myColumn.baseLine = (SpeckleCoreGeometryClasses.SpeckleLine)SpeckleCore.Converter.Serialise(Autodesk.Revit.DB.Line.CreateBound(basePt, topPt));
            }

            myColumn.columnFamily = myFamily.Symbol.FamilyName;
            myColumn.columnType   = Doc.GetElement(myFamily.GetTypeId()).Name;

            myColumn.parameters     = GetElementParams(myFamily);
            myColumn.typeParameters = GetElementTypeParams(myFamily);



            // TODO: Maybe move this column properties in the class defintion
            myColumn.Properties["__facingFlipped"] = myFamily.FacingFlipped;
            myColumn.Properties["__handFlipped"]   = myFamily.HandFlipped;

            if (myFamily.Location is LocationPoint)
            {
                myColumn.Properties["__rotation"] = ((LocationPoint)myFamily.Location).Rotation;
            }
            else if (myFamily.Location is LocationCurve)
            {
                var myAngle = myFamily.get_Parameter(BuiltInParameter.STRUCTURAL_BEND_DIR_ANGLE).AsDouble(); // Stands for cross-section rotation!
                var rads    = UnitUtils.ConvertFromInternalUnits(myAngle, DisplayUnitType.DUT_RADIANS);
                myColumn.Properties["__rotation"] = rads;

                // TODO: Figure this column rotation shit out.
                // For now... Do nothing??
                //var t = myFamily.GetTotalTransform();
            }


            myColumn.GenerateHash();
            myColumn.ApplicationId = myFamily.UniqueId;
            myColumn.elementId     = myFamily.Id.ToString();

            // leaving the mesh out of the hashing process might address the randomatic hash generation we're getting
            // and hence the nuking the usability of local caching and diffing
            var allSolids = GetElementSolids(myFamily, opt: new Options()
            {
                DetailLevel = ViewDetailLevel.Fine, ComputeReferences = true
            });

            (myColumn.Faces, myColumn.Vertices) = GetFaceVertexArrFromSolids(allSolids);

            return(myColumn);
        }
Example #10
0
        //TODO
        public static Element ToNative(this Column myCol)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(myCol.ApplicationId, myCol.Type);

            var exclusions = new List <string> {
                "Base Offset", "Top Offset"
            };

            //setting params on myCol from myCol.parameters, if they are missing
            if (myCol.parameters != null)
            {
                if (myCol.bottomOffset == null && myCol.parameters.ContainsKey("Base Offset"))
                {
                    myCol.bottomOffset = myCol.parameters["Base Offset"] as double?;
                }

                if (myCol.topOffset == null && myCol.parameters.ContainsKey("Top Offset"))
                {
                    myCol.topOffset = myCol.parameters["Top Offset"] as double?;
                }
            }

            var baseLine = (Autodesk.Revit.DB.Curve)SpeckleCore.Converter.Deserialise(obj: myCol.baseLine, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo" });
            var start    = baseLine.GetEndPoint(0);
            var end      = baseLine.GetEndPoint(1);

            var isVertical = IsColumnVertical(myCol);

            // get family symbol; it's used throughout
            FamilySymbol familySymbol = TryGetColumnFamilySymbol(myCol.columnFamily, myCol.columnType);

            // Freak out if we don't have a symbol.
            if (familySymbol == null)
            {
                ConversionErrors.Add(new SpeckleConversionError {
                    Message = $"Missing family: {myCol.columnFamily} {myCol.columnType}"
                });
                throw new RevitFamilyNotFoundException($"No 'Column' family found in the project");
            }


            // Activate the symbol yo!
            if (!familySymbol.IsActive)
            {
                familySymbol.Activate();
            }

            if (docObj != null)
            {
                var type = Doc.GetElement(docObj.GetTypeId()) as ElementType;

                // if family changed, tough luck - delete and rewind
                if (myCol.columnFamily != type.FamilyName)
                {
                    Doc.Delete(docObj.Id);
                }
                else
                {
                    // Edit Endpoints and return
                    var existingFamilyInstance = (Autodesk.Revit.DB.FamilyInstance)docObj;

                    // Edit curve only if i'm not vertical
                    if (existingFamilyInstance.Location is LocationCurve)
                    {
                        existingFamilyInstance.get_Parameter(BuiltInParameter.SLANTED_COLUMN_TYPE_PARAM).Set((double)SlantedOrVerticalColumnType.CT_EndPoint);

                        var existingLocationCurve = existingFamilyInstance.Location as LocationCurve;
                        existingLocationCurve.Curve = baseLine;
                    }
                    else if (existingFamilyInstance.Location is LocationPoint)
                    {
                        var existingLocationPoint = existingFamilyInstance.Location as LocationPoint;
                        existingLocationPoint.Point = start;
                    }

                    // check if type changed, and try and change it
                    if (myCol.columnType != null && (myCol.columnType != type.Name))
                    {
                        existingFamilyInstance.ChangeTypeId(familySymbol.Id);
                    }

                    // Final preparations for good measure
                    Autodesk.Revit.DB.Level mytopLevel;
                    if (myCol.topLevel == null)
                    {
                        mytopLevel = Doc.GetElement(existingFamilyInstance.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId()) as Autodesk.Revit.DB.Level;
                    }
                    else
                    {
                        mytopLevel = myCol.topLevel.ToNative() as Autodesk.Revit.DB.Level;
                    }

                    Autodesk.Revit.DB.Level mybaseLevel;
                    if (myCol.baseLevel == null)
                    {
                        mybaseLevel = Doc.GetElement(existingFamilyInstance.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId()) as Autodesk.Revit.DB.Level;
                    }
                    else
                    {
                        mybaseLevel = myCol.baseLevel.ToNative() as Autodesk.Revit.DB.Level;
                    }

                    SetColParams(myCol, existingFamilyInstance, baseLine, exclusions, mytopLevel, mybaseLevel);

                    MatchFlippingAndRotation(existingFamilyInstance, myCol, baseLine);
                    SetElementParams(existingFamilyInstance, myCol.parameters, exclusions);
                    return(existingFamilyInstance);
                }
            }

            // Create base level
            if (myCol.baseLevel == null)
            {
                myCol.baseLevel = new SpeckleElementsClasses.Level()
                {
                    elevation = baseLine.GetEndPoint(0).Z / Scale, levelName = "Speckle Level " + baseLine.GetEndPoint(0).Z / Scale
                }
            }
            ;
            var baseLevel = myCol.baseLevel.ToNative() as Autodesk.Revit.DB.Level;

            Autodesk.Revit.DB.FamilyInstance familyInstance = null;

            if (myCol.parameters != null && myCol.parameters.ContainsKey("Column Style")) // Comes from revit
            {
                if (Convert.ToInt16(myCol.parameters["Column Style"]) == 2)               // SLANTED
                {
                    familyInstance = Doc.Create.NewFamilyInstance(baseLine, familySymbol, baseLevel, Autodesk.Revit.DB.Structure.StructuralType.Column);
                }
                else // NOT SLANTED
                {
                    familyInstance = Doc.Create.NewFamilyInstance(start, familySymbol, baseLevel, Autodesk.Revit.DB.Structure.StructuralType.Column);
                }
            }
            else // Comes from gh
            {
                if (isVertical)
                {
                    familyInstance = Doc.Create.NewFamilyInstance(start, familySymbol, baseLevel, Autodesk.Revit.DB.Structure.StructuralType.Column);
                }
                else
                {
                    familyInstance = Doc.Create.NewFamilyInstance(baseLine, familySymbol, baseLevel, Autodesk.Revit.DB.Structure.StructuralType.Column);
                }
            }


            Autodesk.Revit.DB.Level myTopLevel = null;
            // Set the top level
            if (myCol.topLevel != null)
            {
                myTopLevel = myCol.topLevel.ToNative();
                var param = familyInstance.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM);
                if (param != null)
                {
                    param.Set(myTopLevel.Id);
                }
            }

            SetColParams(myCol, familyInstance, baseLine, exclusions, myTopLevel, baseLevel);

            return(familyInstance);
        }
Example #11
0
 /// <summary>
 /// Initialize an AdaptiveComponent element
 /// </summary>
 /// <param name="familyInstance"></param>
 private void InitAdaptiveComponent(Autodesk.Revit.DB.FamilyInstance familyInstance)
 {
     TransactionManager.Instance.EnsureInTransaction(Document);
     InternalSetFamilyInstance(familyInstance);
     TransactionManager.Instance.TransactionTaskDone();
 }
Example #12
0
 /// <summary>
 /// Internal constructor for existing Elements.
 /// </summary>
 /// <param name="familyInstance"></param>
 private AdaptiveComponent(Autodesk.Revit.DB.FamilyInstance familyInstance)
 {
     SafeInit(() => InitAdaptiveComponent(familyInstance));
 }
Example #13
0
        public static Element StructuralFramingToNative(Beam myBeam, StructuralType structuralType)
        {
            var(docObj, stateObj) = GetExistingElementByApplicationId(myBeam.ApplicationId, myBeam.Type);
            try
            {
                var familySymbol = GetFamilySymbolByFamilyNameAndTypeAndCategory(myBeam.beamFamily, myBeam.beamType, new List <BuiltInCategory> {
                    BuiltInCategory.OST_StructuralFraming, BuiltInCategory.OST_BeamAnalytical
                });

                // Freak out if we don't have a symbol.
                if (familySymbol == null)
                {
                    ConversionErrors.Add(new SpeckleConversionError {
                        Message = $"Missing family: {myBeam.beamFamily} {myBeam.beamType}"
                    });
                    throw new RevitFamilyNotFoundException($"No 'Beam' family found in the project");
                }

                Autodesk.Revit.DB.Curve baseLine = null;
                if (myBeam.baseLine != null)
                {
                    baseLine = (Autodesk.Revit.DB.Curve)SpeckleCore.Converter.Deserialise(obj: myBeam.baseLine, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo" });
                }

                Autodesk.Revit.DB.XYZ basePoint = null;
                if (myBeam.basePoint != null)
                {
                    basePoint = (Autodesk.Revit.DB.XYZ)SpeckleCore.Converter.Deserialise(obj: myBeam.basePoint, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo" });
                }


                //var start = baseLine.GetEndPoint( 0 );
                //var end = baseLine.GetEndPoint( 1 );

                // Activate the symbol yo!
                if (!familySymbol.IsActive)
                {
                    familySymbol.Activate();
                }

                // If we have an existing element we can edit:
                if (docObj != null)
                {
                    var type = Doc.GetElement(docObj.GetTypeId()) as ElementType;

                    // if family changed, tough luck. delete and let us create a new one.
                    if (myBeam.beamFamily != type.FamilyName)
                    {
                        Doc.Delete(docObj.Id);
                    }
                    else
                    {
                        var existingFamilyInstance = (Autodesk.Revit.DB.FamilyInstance)docObj;

                        if (baseLine != null)
                        {
                            var existingLocationCurve = existingFamilyInstance.Location as LocationCurve;
                            existingLocationCurve.Curve = baseLine;
                        }
                        else
                        {
                            var existingLocationPoint = existingFamilyInstance.Location as LocationPoint;
                            existingLocationPoint.Point = basePoint;
                        }

                        // check for a type change
                        if (myBeam.beamType != null && myBeam.beamType != type.Name)
                        {
                            existingFamilyInstance.ChangeTypeId(familySymbol.Id);
                        }

                        SetElementParams(existingFamilyInstance, myBeam.parameters);
                        return(existingFamilyInstance);
                    }
                }

                if (myBeam.level == null)
                {
                    myBeam.level = new SpeckleElementsClasses.Level()
                    {
                        elevation = 0, levelName = "Speckle Level 0"
                    }
                }
                ;
                var myLevel = myBeam.level.ToNative() as Autodesk.Revit.DB.Level;

                Autodesk.Revit.DB.FamilyInstance familyInstance = null;

                if (baseLine != null)
                {
                    familyInstance = Doc.Create.NewFamilyInstance(baseLine, familySymbol, myLevel, structuralType);
                }
                else
                {
                    familyInstance = Doc.Create.NewFamilyInstance(basePoint, familySymbol, myLevel, structuralType);
                }


                SetElementParams(familyInstance, myBeam.parameters);
                return(familyInstance);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Example #14
0
 /// <summary>
 /// Wrap an existing FamilyInstance.
 /// </summary>
 /// <param name="instance"></param>
 private StructuralFraming(Autodesk.Revit.DB.FamilyInstance instance)
 {
     InternalSetFamilyInstance(instance);
 }
 protected void InternalSetFamilyInstance(Autodesk.Revit.DB.FamilyInstance fi)
 {
     this.InternalFamilyInstance = fi;
     this.InternalElementId      = fi.Id;
     this.InternalUniqueId       = fi.UniqueId;
 }
        void ReconstructFamilyInstanceByLocation
        (
            DB.Document doc,
            ref DB.FamilyInstance element,

            [Description("Location where to place the element. Point or plane is accepted.")]
            Plane location,
            DB.FamilySymbol type,
            Optional <DB.Level> level,
            [Optional] DB.Element host
        )
        {
            if (!location.IsValid)
            {
                ThrowArgumentException(nameof(location), "Location is not valid.");
            }

            if (!type.IsActive)
            {
                type.Activate();
            }

            {
                FamilyInstanceCreationData creationData;
                switch (type.Family.FamilyPlacementType)
                {
                case DB.FamilyPlacementType.OneLevelBased:
                    creationData = CreateOneLevelBased(doc, location, type, level, host);
                    break;

                case DB.FamilyPlacementType.OneLevelBasedHosted:
                    creationData = CreateOneLevelBasedHosted(doc, location, type, level, host);
                    break;

                case DB.FamilyPlacementType.TwoLevelsBased:
                    creationData = CreateTwoLevelsBased(doc, location, type, level, host);
                    break;

                case DB.FamilyPlacementType.WorkPlaneBased:
                    creationData = CreateWorkPlaneBased(doc, location, type, level, host);
                    break;

                default:
                    creationData = CreateDefault(doc, location, type, level, host);
                    break;
                }

                var dataList = new List <FamilyInstanceCreationData>()
                {
                    creationData
                };
                var newElementIds = doc.IsFamilyDocument ?
                                    doc.FamilyCreate.NewFamilyInstances2(dataList) :
                                    doc.Create.NewFamilyInstances2(dataList);

                if (newElementIds.Count != 1)
                {
                    doc.Delete(newElementIds);
                    throw new InvalidOperationException();
                }

                var parametersMask = new DB.BuiltInParameter[]
                {
                    DB.BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM,
                    DB.BuiltInParameter.ELEM_FAMILY_PARAM,
                    DB.BuiltInParameter.ELEM_TYPE_PARAM,
                    DB.BuiltInParameter.FAMILY_LEVEL_PARAM,
                    DB.BuiltInParameter.FAMILY_BASE_LEVEL_PARAM,
                    DB.BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM,
                    DB.BuiltInParameter.FAMILY_TOP_LEVEL_PARAM,
                    DB.BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM,
                    DB.BuiltInParameter.SCHEDULE_LEVEL_PARAM,
                    DB.BuiltInParameter.SCHEDULE_BASE_LEVEL_PARAM,
                    DB.BuiltInParameter.SCHEDULE_BASE_LEVEL_OFFSET_PARAM,
                    DB.BuiltInParameter.SCHEDULE_TOP_LEVEL_PARAM,
                    DB.BuiltInParameter.SCHEDULE_TOP_LEVEL_OFFSET_PARAM,
                    DB.BuiltInParameter.INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM,
                    DB.BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM
                };

                ReplaceElement(ref element, doc.GetElement(newElementIds.First()) as DB.FamilyInstance, parametersMask);
                doc.Regenerate();

                if (element.Pinned)
                {
                    try { element.Pinned = false; }
                    catch (Autodesk.Revit.Exceptions.InvalidOperationException) { }
                }
            }

            element?.SetLocation(location.Origin.ToXYZ(), location.XAxis.ToXYZ(), location.YAxis.ToXYZ());
        }
Example #17
0
 /// <summary>
 /// Wrap an existing FamilyInstance.
 /// </summary>
 /// <param name="instance"></param>
 protected FamilyInstance(Autodesk.Revit.DB.FamilyInstance instance)
 {
     InternalSetFamilyInstance(instance);
 }
Example #18
0
        public List <ApplicationPlaceholderObject> BeamToNative(Beam speckleBeam, StructuralType structuralType = StructuralType.Beam)
        {
            if (speckleBeam.baseLine == null)
            {
                throw new Speckle.Core.Logging.SpeckleException("Only line based Beams are currently supported.");
            }

            DB.FamilySymbol familySymbol = GetElementType <FamilySymbol>(speckleBeam);
            var             baseLine     = CurveToNative(speckleBeam.baseLine).get_Item(0);

            DB.Level          level     = null;
            DB.FamilyInstance revitBeam = null;

            //comes from revit or schema builder, has these props
            var speckleRevitBeam = speckleBeam as RevitBeam;

            if (speckleRevitBeam != null)
            {
                level = GetLevelByName(speckleRevitBeam.level.name);
            }

            if (level == null)
            {
                level = LevelToNative(LevelFromCurve(baseLine));
            }

            //try update existing
            var docObj = GetExistingElementByApplicationId(speckleBeam.applicationId);

            if (docObj != null)
            {
                try
                {
                    var revitType = Doc.GetElement(docObj.GetTypeId()) as ElementType;

                    // if family changed, tough luck. delete and let us create a new one.
                    if (familySymbol.FamilyName != revitType.FamilyName)
                    {
                        Doc.Delete(docObj.Id);
                    }
                    else
                    {
                        revitBeam = (DB.FamilyInstance)docObj;
                        (revitBeam.Location as LocationCurve).Curve = baseLine;

                        // check for a type change
                        if (!string.IsNullOrEmpty(familySymbol.FamilyName) && familySymbol.FamilyName != revitType.Name)
                        {
                            revitBeam.ChangeTypeId(familySymbol.Id);
                        }
                    }
                }
                catch
                {
                    //something went wrong, re-create it
                }
            }

            //create family instance
            if (revitBeam == null)
            {
                revitBeam = Doc.Create.NewFamilyInstance(baseLine, familySymbol, level, structuralType);
            }

            //reference level, only for beams
            TrySetParam(revitBeam, BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM, level);

            if (speckleRevitBeam != null)
            {
                SetInstanceParameters(revitBeam, speckleRevitBeam);
            }

            // TODO: get sub families, it's a family!
            var placeholders = new List <ApplicationPlaceholderObject>()
            {
                new ApplicationPlaceholderObject {
                    applicationId = speckleBeam.applicationId, ApplicationGeneratedId = revitBeam.UniqueId, NativeObject = revitBeam
                }
            };

            // TODO: nested elements.

            return(placeholders);
        }
Example #19
0
 public FamilyInstance(DB.FamilyInstance value) : base(value)
 {
 }
 protected void InternalSetFamilyInstance(Autodesk.Revit.DB.FamilyInstance fi)
 {
     this.InternalFamilyInstance = fi;
     this.InternalElementId = fi.Id;
     this.InternalUniqueId = fi.UniqueId;
 }
Example #21
0
        public List <ApplicationPlaceholderObject> ColumnToNative(Column speckleColumn)
        {
            if (speckleColumn.baseLine == null)
            {
                throw new Speckle.Core.Logging.SpeckleException("Only line based Beams are currently supported.");
            }

            DB.FamilySymbol familySymbol = GetElementType <FamilySymbol>(speckleColumn);;
            var             baseLine     = CurveToNative(speckleColumn.baseLine).get_Item(0);

            // If the start point elevation is higher than the end point elevation, reverse the line.
            if (baseLine.GetEndPoint(0).Z > baseLine.GetEndPoint(1).Z)
            {
                baseLine = DB.Line.CreateBound(baseLine.GetEndPoint(1), baseLine.GetEndPoint(0));
            }

            DB.Level          level       = null;
            DB.Level          topLevel    = null;
            DB.FamilyInstance revitColumn = null;
            var structuralType            = StructuralType.Column;
            var isLineBased = true;

            var speckleRevitColumn = speckleColumn as RevitColumn;

            if (speckleRevitColumn != null)
            {
                level          = LevelToNative(speckleRevitColumn.level);
                topLevel       = LevelToNative(speckleRevitColumn.topLevel);
                structuralType = speckleRevitColumn.structural ? StructuralType.Column : StructuralType.NonStructural;
                //non slanted columns are point based
                isLineBased = speckleRevitColumn.isSlanted;
            }

            if (level == null)
            {
                level    = LevelToNative(LevelFromCurve(baseLine));
                topLevel = LevelToNative(LevelFromPoint(baseLine.GetEndPoint(1)));
            }

            //try update existing
            var docObj = GetExistingElementByApplicationId(speckleColumn.applicationId);

            if (docObj != null)
            {
                try
                {
                    var revitType = Doc.GetElement(docObj.GetTypeId()) as ElementType;

                    // if family changed, tough luck. delete and let us create a new one.
                    if (familySymbol.FamilyName != revitType.FamilyName)
                    {
                        Doc.Delete(docObj.Id);
                    }
                    else
                    {
                        revitColumn = (DB.FamilyInstance)docObj;
                        switch (revitColumn.Location)
                        {
                        case LocationCurve crv:
                            crv.Curve = baseLine;
                            break;

                        case LocationPoint pt:
                            pt.Point = baseLine.GetEndPoint(0);
                            break;
                        }

                        // check for a type change
                        if (!string.IsNullOrEmpty(familySymbol.FamilyName) && familySymbol.FamilyName != revitType.Name)
                        {
                            revitColumn.ChangeTypeId(familySymbol.Id);
                        }
                    }
                }
                catch { }
            }

            if (revitColumn == null && isLineBased)
            {
                revitColumn = Doc.Create.NewFamilyInstance(baseLine, familySymbol, level, structuralType);
                StructuralFramingUtils.DisallowJoinAtEnd(revitColumn, 0);
                StructuralFramingUtils.DisallowJoinAtEnd(revitColumn, 1);
            }

            //try with a point based column
            if (speckleRevitColumn != null && revitColumn == null && !isLineBased)
            {
                var start = baseLine.GetEndPoint(0);
                var end   = baseLine.GetEndPoint(1);

                var basePoint = start.Z < end.Z ? start : end; // pick the lowest
                revitColumn = Doc.Create.NewFamilyInstance(basePoint, familySymbol, level, StructuralType.NonStructural);

                //rotate, we know it must be a RevitColumn
                var axis = DB.Line.CreateBound(new XYZ(basePoint.X, basePoint.Y, 0), new XYZ(basePoint.X, basePoint.Y, 1000));
                (revitColumn.Location as LocationPoint).Rotate(axis, speckleRevitColumn.rotation - (revitColumn.Location as LocationPoint).Rotation);
            }

            if (revitColumn == null)
            {
                ConversionErrors.Add(new Exception($"Failed to create column for {speckleColumn.applicationId}."));
                return(null);
            }



            TrySetParam(revitColumn, BuiltInParameter.FAMILY_BASE_LEVEL_PARAM, level);
            TrySetParam(revitColumn, BuiltInParameter.FAMILY_TOP_LEVEL_PARAM, topLevel);


            if (speckleRevitColumn != null)
            {
                if (speckleRevitColumn.handFlipped != revitColumn.HandFlipped)
                {
                    revitColumn.flipHand();
                }

                if (speckleRevitColumn.facingFlipped != revitColumn.FacingFlipped)
                {
                    revitColumn.flipFacing();
                }

                SetOffsets(revitColumn, speckleRevitColumn);

                SetInstanceParameters(revitColumn, speckleRevitColumn);
            }

            var placeholders = new List <ApplicationPlaceholderObject>()
            {
                new ApplicationPlaceholderObject {
                    applicationId = speckleColumn.applicationId, ApplicationGeneratedId = revitColumn.UniqueId, NativeObject = revitColumn
                }
            };

            // TODO: nested elements.

            return(placeholders);
        }