public static int CreateDirectShape(Geometry geo,  Revit.Elements.Material mat, string name)
 {
     List<Autodesk.DesignScript.Geometry.Point> points;
     List<IndexGroup> indexGroups;
     MeshUtils.TessellateGeoToMesh(geo, out points, out indexGroups);
     return NewDirectShape(points.ToArray(), indexGroups.ToArray(), RevitServices.Persistence.DocumentManager.Instance.CurrentDBDocument, ElementId.InvalidElementId,new ElementId(mat.Id), Guid.NewGuid().ToString(), name);
 }
Example #2
1
        /// <summary>
        /// Appends a Bar to an existing Rebar container (or creates it if no container is supplied)
        /// </summary>
        /// <param name="rebars">List of Bars to add</param>
        /// <param name="container">Optional: Existing Rebar Container</param>
        public static Revit.Elements.RebarContainer AppendBar(List<Revit.Elements.Rebar> rebars, Revit.Elements.RebarContainer container = null)
        {
            if (container == null)
            {
                container = Revit.Elements.RebarContainer.ByBars(rebars);
            }
            else
            {
                foreach (Revit.Elements.Rebar rebar in rebars) container.InternalRebarContainer.AppendItemFromRebar(rebar.InternalRebar);
            }

            return container;
        }
Example #3
1
        /// <summary>
        /// Create Curves using Isolines of a Surface
        /// </summary>
        /// <param name="face">Surface</param>
        /// <param name="isoDirection">Iso Line Direction</param>
        /// <param name="parameters">Parameters to Evaluate</param>
        /// <returns>List of IsoCurves</returns>
        //public static List<Curve> FollowingIsoLineSurface(Surface face, int isoDirection, List<double> parameters)
        //{
        //    List<Curve> result = new List<Curve>();
        //
        //    foreach (double parameter in parameters)
        //        result.Add(face.GetIsoline(isoDirection, parameter));
        //
        //    return result;
        //}

        /// <summary>
        /// Cuts a set of Rebars by Plane
        /// </summary>
        /// <param name="plane">Plane to cut by</param>
        /// <param name="rebarContainerElement">Rebar Container</param>
        /// <param name="firstPart">Return the first or the last part of the splitted elements</param>
        public static void Cut(Surface plane, Revit.Elements.Element rebarContainerElement, bool firstPart)
        {
            // Get Rebar Container Element
            Autodesk.Revit.DB.Structure.RebarContainer rebarContainer = (Autodesk.Revit.DB.Structure.RebarContainer)rebarContainerElement.InternalElement;

            // Get the active Document
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;

            // Open a new Transaction
            TransactionManager.Instance.EnsureInTransaction(document);

            // Get all single Rebar elements from the container
            List<Autodesk.Revit.DB.Structure.RebarContainerItem> rebars = rebarContainer.ToList();

            // Walk through all rebar elements
            foreach (Autodesk.Revit.DB.Structure.RebarContainerItem rebar in rebars)
            {
                // Buffer Rebar properties for recreation
                RVT.Structure.RebarBarType barType = (RVT.Structure.RebarBarType)document.GetElement(rebar.BarTypeId);
                RVT.Structure.RebarHookType hookTypeStart = (RVT.Structure.RebarHookType)document.GetElement(rebar.GetHookTypeId(0));
                RVT.Structure.RebarHookType hookTypeEnd = (RVT.Structure.RebarHookType)document.GetElement(rebar.GetHookTypeId(1));
                RVT.Structure.RebarHookOrientation hookOrientationStart = rebar.GetHookOrientation(0);
                RVT.Structure.RebarHookOrientation hookOrientationEnd = rebar.GetHookOrientation(1);

                // create a list to store the remaining part of the curve after cutting it
                List<RVT.Curve> result = new List<RVT.Curve>();

                // get the center line curves of the rebar elements
                foreach (RVT.Curve curve in rebar.GetCenterlineCurves(false, true, true))
                {
                    // if the curve is a line or an arc consider it being valid
                    if (curve.GetType() == typeof(RVT.Line) || curve.GetType() == typeof(RVT.Arc))
                    {
                        // Get a DesignScript Curve from the Revit curve
                        Curve geocurve = curve.ToProtoType();

                        // Intersect the selected plane with the curve
                        foreach (Geometry geometry in plane.Intersect(geocurve))
                        {
                            // if the intersection is a point
                            if (geometry.GetType() == typeof(Point))
                            {
                                // Get the closest point to the intersection on the curve
                                Point p = geocurve.ClosestPointTo((Point)geometry);

                                // Split the curve at this point
                                Curve[] curves = geocurve.ParameterSplit(geocurve.ParameterAtPoint(p));

                                // If the curve has been split into two parts
                                if (curves.Length == 2)
                                {
                                    // return the first or the second part of the splitted curve
                                    if (firstPart)
                                        result.Add(curves[0].ToRevitType());
                                    else
                                        result.Add(curves[1].ToRevitType());
                                }
                            }
                        }
                    }
                }

                // If the result has some elements, create a new rebar container from those curves
                // using the same properties as the initial one.
                if (result.Count > 0)
                {
                    rebar.SetFromCurves(RVT.Structure.RebarStyle.Standard, barType, hookTypeStart, hookTypeEnd, rebar.Normal, result, hookOrientationStart, hookOrientationEnd, true, false);
                }
            }

            // Commit and Dispose the transaction
            TransactionManager.Instance.TransactionTaskDone();
        }
        private static ElementCurveReference TryGetCurveReference(Revit.Elements.Element curveObject, string nodeTypeString = "This node")
        {
            var cs = curveObject.InternalGeometry().OfType<Autodesk.Revit.DB.Curve>();
            if (cs.Any()) return new ElementCurveReference(cs.First());

            throw new ArgumentException(nodeTypeString + " requires a ElementCurveReference extracted from a Revit Element! " +
                             "You supplied an " + curveObject.ToString() + ", but we could not extract a CurveReference from it!");
        }
Example #5
0
        /// <summary>
        /// Cover value to Offset value
        /// </summary>
        /// <param name="cover">Cover Value</param>
        /// <param name="barType">Rebar Bar Type</param>
        /// <returns>Offset</returns>
        public static double CoverToOffset(double cover, Revit.Elements.Element barType)
        {
            double offset = cover;

            if (barType.InternalElement != null)
            {
                Autodesk.Revit.DB.Structure.RebarBarType revitBarType = (Autodesk.Revit.DB.Structure.RebarBarType)barType.InternalElement;
                offset = cover + revitBarType.BarDiameter / 2;            
            }

            return offset;
        }
Example #6
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Brep brep = null;
            if (!DA.GetData("Brep", ref brep))
            {
                return;
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, (Rhino.Geometry.Brep)brep?.DuplicateShallow()));
        }
Example #7
0
        //******************************************************************************************
        /// <summary>
        /// Create sub dialogs
        /// </summary>
        public override void OnCreateDialogs()
        {
            base.OnCreateDialogs();
            m_ExpImpMng = new REXExpImpMng(this);
            m_RevitData = new REXRevitData(Revit.CommandData());
            m_RevitData.Initialize();
            m_ErrorType = 0;

            System.LoadFromFile(false);
            FreezeControl    = new FreezeMainCtr(this);
            dlgOptions       = new DialogOptions(this);
            dlgExportOptions = new DialogExportOptions(this);
            dlgViewSel       = new DialogViewSel(this);
        }
Example #8
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var point = new Rhino.Geometry.Point3d(double.NaN, double.NaN, double.NaN);

            if (!DA.GetData("Point", ref point))
            {
                return;
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, point));
        }
Example #9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var points = new List <Rhino.Geometry.Point3d>();

            if (!DA.GetDataList("Points", points))
            {
                return;
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, points));
        }
Example #10
0
        private static void UpdateViewConstructionPlanes(Rhino.RhinoDoc rhinoDoc, Document revitDoc)
        {
            if (!string.IsNullOrEmpty(rhinoDoc.TemplateFileUsed))
            {
                return;
            }

            if (rhinoDoc.IsCreating)
            {
                Revit.EnqueueAction(doc => UpdateViewConstructionPlanes(rhinoDoc, doc));
                return;
            }

            bool imperial = rhinoDoc.ModelUnitSystem == Rhino.UnitSystem.Feet || rhinoDoc.ModelUnitSystem == Rhino.UnitSystem.Inches;

            var modelGridSpacing = imperial ?
                                   1.0 * Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Yards, rhinoDoc.ModelUnitSystem) :
                                   1.0 * Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Meters, rhinoDoc.ModelUnitSystem);

            var modelSnapSpacing = imperial ?
                                   1 / 16.0 * Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Inches, rhinoDoc.ModelUnitSystem) :
                                   1.0 * Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Millimeters, rhinoDoc.ModelUnitSystem);

            var modelThickLineFrequency = imperial ? 6 : 5;

            // Views
            {
                foreach (var view in rhinoDoc.Views)
                {
                    var cplane = view.MainViewport.GetConstructionPlane();

                    cplane.GridSpacing        = modelGridSpacing;
                    cplane.SnapSpacing        = modelSnapSpacing;
                    cplane.ThickLineFrequency = modelThickLineFrequency;

                    view.MainViewport.SetConstructionPlane(cplane);

                    var min  = cplane.Plane.PointAt(-cplane.GridSpacing * cplane.GridLineCount, -cplane.GridSpacing * cplane.GridLineCount, 0.0);
                    var max  = cplane.Plane.PointAt(+cplane.GridSpacing * cplane.GridLineCount, +cplane.GridSpacing * cplane.GridLineCount, 0.0);
                    var bbox = new Rhino.Geometry.BoundingBox(min, max);

                    // Zoom to grid
                    view.MainViewport.ZoomBoundingBox(bbox);

                    // Adjust to extens in case There is anything in the viewports like Grasshopper previews.
                    view.MainViewport.ZoomExtents();
                }
            }
        }
Example #11
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve axis = null;
            DA.GetData("Axis", ref axis);

            WallType wallType = null;

            if (!DA.GetData("Type", ref wallType) && Params.Input[1].Sources.Count == 0)
            {
                wallType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.WallType)) as WallType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null && axis != null)
            {
                level = Revit.ActiveDBDocument.FindLevelByElevation(axis.PointAtStart.Z / Revit.ModelUnits);
            }

            bool structural = true;

            DA.GetData("Structural", ref structural);

            double height = 0.0;

            if (!DA.GetData("Height", ref height))
            {
                height = LiteralLengthValue(3.0);
            }

            var locationLine      = WallLocationLine.WallCenterline;
            int locationLineValue = (int)locationLine;

            if (DA.GetData("LocationLine", ref locationLineValue))
            {
                if ((int)WallLocationLine.WallCenterline > locationLineValue || locationLineValue > (int)WallLocationLine.CoreInterior)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' range is [0, 5].", Params.Input[5].Name));
                    return;
                }

                locationLine = (WallLocationLine)locationLineValue;
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, wallType, level, structural, height, locationLine));
        }
Example #12
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var axis = Rhino.Geometry.Line.Unset;

            if (DA.GetData("Axis", ref axis))
            {
                if (axis.FromZ > axis.ToZ)
                {
                    axis.Flip();
                }
            }

            FamilySymbol familySymbol = null;

            if (!DA.GetData("Type", ref familySymbol) && Params.Input[1].Sources.Count == 0)
            {
                familySymbol = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultFamilyTypeId(new ElementId(BuiltInCategory.OST_StructuralColumns))) as FamilySymbol;
            }

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

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null)
            {
                using (var collector = new FilteredElementCollector(Revit.ActiveDBDocument))
                {
                    foreach (var levelN in collector.OfClass(typeof(Level)).ToElements().Cast <Level>().OrderBy(c => c.Elevation))
                    {
                        if (level == null)
                        {
                            level = levelN;
                        }
                        else if (axis.FromZ > levelN.Elevation)
                        {
                            level = levelN;
                        }
                    }
                }
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, familySymbol, level));
        }
Example #13
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve axis = null;
            DA.GetData("Axis", ref axis);

            WallType wallType = null;

            if (!DA.GetData("Type", ref wallType) && Params.Input[1].Sources.Count == 0)
            {
                wallType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.WallType)) as WallType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null && axis != null)
            {
                using (var collector = new FilteredElementCollector(Revit.ActiveDBDocument))
                {
                    foreach (var levelN in collector.OfClass(typeof(Level)).ToElements().Cast <Level>().OrderBy(c => c.Elevation))
                    {
                        if (level == null)
                        {
                            level = levelN;
                        }
                        else if (axis.PointAtStart.Z >= levelN.Elevation)
                        {
                            level = levelN;
                        }
                    }
                }
            }

            bool structural = true;

            DA.GetData("Structural", ref structural);

            double height = 0.0;

            if (!DA.GetData("Height", ref height))
            {
                height = LiteralLengthValue(3.0);
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, wallType, level, structural, height));
        }
    /// <summary>
    /// This procedure contains the user code. Input parameters are provided as regular arguments,
    /// Output parameters as ref arguments. You don't have to assign output parameters,
    /// they will have a default value.
    /// </summary>
    private void RunScript(bool Update, ref object A)
    {
        if (!Update)
        {
            A = ghbreps;
        }
        else
        {
            Revit.EnqueueAction((uido) => UpdateTopographySurface(uido));
            A = ghbreps;

            foreach (string s in outVals)
            {
                Print(s);
            }
        }
    }
        public override Result Execute(ExternalCommandData data, ref string message, DB.ElementSet elements)
        {
            GH_Document.EnableSolutions = !GH_Document.EnableSolutions;

            if (GH_Document.EnableSolutions)
            {
                if (Instances.ActiveCanvas?.Document is GH_Document definition)
                {
                    definition.NewSolution(false);
                }
            }
            else
            {
                Revit.RefreshActiveView();
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var ifLoad = true;

            DA.GetData(0, ref ifLoad);
            //var outputGeos = new List<Brep>();


            if (!ifLoad)
            {
                DA.SetDataList(0, ghbreps);
            }

            else
            {
                Revit.EnqueueAction((uido) => GetSelectedRevitElements(uido));
            }
        }
            public static Preview OrderNew(GeometricElement element)
            {
                if (!element.IsValid)
                {
                    return(null);
                }

                if (previewsQueue is null)
                {
                    previewsQueue = new List <Preview>();
                    Revit.EnqueueReadAction((doc, cancel) => BuildPreviews(doc, cancel));
                }

                var preview = new Preview(element);

                previewsQueue.Add(preview);
                return(preview);
            }
Example #18
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var boundaries = new List <Rhino.Geometry.Curve>();

            if (!DA.GetDataList("Boundaries", boundaries))
            {
                return;
            }

            Autodesk.Revit.DB.BuildingPadType buildingPadType = null;
            if (!DA.GetData("Type", ref buildingPadType) && Params.Input[1].Sources.Count == 0)
            {
                buildingPadType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.BuildingPadType)) as BuildingPadType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null && boundaries.Count != 0)
            {
                foreach (var boundary in boundaries.OfType <Rhino.Geometry.Curve>())
                {
                    var boundaryBBox = boundary.GetBoundingBox(true);
                    using (var collector = new FilteredElementCollector(Revit.ActiveDBDocument))
                    {
                        foreach (var levelN in collector.OfClass(typeof(Level)).ToElements().Cast <Level>().OrderBy(c => c.Elevation))
                        {
                            if (level == null)
                            {
                                level = levelN;
                            }
                            else if (boundaryBBox.Min.Z >= levelN.Elevation)
                            {
                                level = levelN;
                            }
                        }
                    }
                }
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, boundaries, buildingPadType, level));
        }
            static void BuildPreviews(DB.Document document, bool cancelled, List <Preview> previews)
            {
                if (cancelled)
                {
                    return;
                }

                var stopWatch = new Stopwatch();

                int count = 0;

                while ((count = previews.Count) > 0)
                {
                    // Draw the biggest elements first.
                    // The biggest element ia at the end of previews List, this way no realloc occurs when removing it

                    int last    = count - 1;
                    var preview = previews[last];
                    previews.RemoveAt(last);

                    stopWatch.Start();
                    preview.Build(document);
                    stopWatch.Stop();

                    // If building those previews take use more than 200 ms we return to Revit, to keep it 'interactive'.
                    if (stopWatch.ElapsedMilliseconds > 200)
                    {
                        break;
                    }
                }

                // RhinoDoc.ActiveDoc.Views.Redraw is synchronous :(
                // better use RhinoView.Redraw that just invalidate the view, the OS will update it when possible
                foreach (var view in Rhino.RhinoDoc.ActiveDoc.Views)
                {
                    view.Redraw();
                }

                // If there are pending previews to generate enqueue BuildPreviews again
                if (previews.Count > 0)
                {
                    Revit.EnqueueReadAction((doc, cancel) => BuildPreviews(doc, cancel, previews));
                }
            }
Example #20
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve boundary = null;
            DA.GetData("Boundary", ref boundary);

            Autodesk.Revit.DB.FloorType floorType = null;
            if (!DA.GetData("Type", ref floorType) && Params.Input[1].Sources.Count == 0)
            {
                floorType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.FloorType)) as FloorType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null && boundary != null)
            {
                var boundaryBBox = boundary.GetBoundingBox(true);
                using (var collector = new FilteredElementCollector(Revit.ActiveDBDocument))
                {
                    foreach (var levelN in collector.OfClass(typeof(Level)).ToElements().Cast <Level>().OrderBy(c => c.Elevation))
                    {
                        if (level == null)
                        {
                            level = levelN;
                        }
                        else if (boundaryBBox.Min.Z >= levelN.Elevation)
                        {
                            level = levelN;
                        }
                    }
                }
            }

            bool structural = true;

            DA.GetData("Structural", ref structural);

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, boundary, floorType, level, structural));
        }
Example #21
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var geometry = new List <Rhino.Geometry.GeometryBase>();

            DA.GetDataList("Geometry", geometry);

            Autodesk.Revit.DB.Category category = null;
            if (!DA.GetData("Category", ref category) && Params.Input[1].Sources.Count == 0)
            {
                category = Autodesk.Revit.DB.Category.GetCategory(Revit.ActiveDBDocument, BuiltInCategory.OST_GenericModel);
            }

            string name = string.Empty;

            DA.GetData("Name", ref name);

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, geometry, category, name));
        }
Example #22
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve boundary = null;
            DA.GetData("Boundary", ref boundary);

            Autodesk.Revit.DB.FloorType floorType = null;
            if (!DA.GetData("Type", ref floorType) && Params.Input[1].Sources.Count == 0)
            {
                floorType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.FloorType)) as FloorType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);

            bool structural = true;

            DA.GetData("Structural", ref structural);

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, boundary, floorType, level, structural));
        }
Example #23
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var geometry = new List <IGH_GeometricGoo>();

            DA.GetDataList("Geometry", geometry);

            Autodesk.Revit.DB.Category category = null;
            if (!DA.GetData("Category", ref category) && Params.Input[1].Sources.Count == 0)
            {
                category = Autodesk.Revit.DB.Category.GetCategory(Revit.ActiveDBDocument, BuiltInCategory.OST_GenericModel);
            }

            string name = null;

            if (!DA.GetData("Name", ref name) && geometry.Count == 1 && (geometry[0]?.IsReferencedGeometry ?? false))
            {
                name = Rhino.RhinoDoc.ActiveDoc.Objects.FindId(geometry[0].ReferenceID)?.Name;
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, geometry, category, name));
        }
Example #24
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var axis = Rhino.Geometry.Line.Unset;

            if (DA.GetData("Axis", ref axis))
            {
                if (axis.FromZ > axis.ToZ)
                {
                    axis.Flip();
                }
            }

            FamilySymbol familySymbol = null;

            if (!DA.GetData("Type", ref familySymbol) && Params.Input[1].Sources.Count == 0)
            {
                familySymbol = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultFamilyTypeId(new ElementId(BuiltInCategory.OST_StructuralColumns))) as FamilySymbol;
            }

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

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null)
            {
                level = Revit.ActiveDBDocument.FindLevelByElevation(axis.FromZ / Revit.ModelUnits);
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, familySymbol, level));
        }
Example #25
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve axis = null;
            DA.GetData("Curve", ref axis);

            GridType gridType = null;

            if (!DA.GetData("Type", ref gridType) && Params.Input[1].Sources.Count == 0)
            {
                gridType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.GridType)) as GridType;
            }

            if (gridType == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("Parameter '{0}' There is no default level type loaded.", Params.Input[1].Name));
                DA.AbortComponentSolution();
                return;
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, gridType));
        }
Example #26
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Rhino.Geometry.Curve boundary = null;
            DA.GetData("Boundary", ref boundary);

            Autodesk.Revit.DB.RoofType roofType = null;
            if (!DA.GetData("Type", ref roofType) && Params.Input[1].Sources.Count == 0)
            {
                roofType = Revit.ActiveDBDocument.GetElement(Revit.ActiveDBDocument.GetDefaultElementTypeId(ElementTypeGroup.RoofType)) as RoofType;
            }

            Autodesk.Revit.DB.Level level = null;
            DA.GetData("Level", ref level);
            if (level == null && boundary != null)
            {
                var boundaryBBox = boundary.GetBoundingBox(true);
                level = Revit.ActiveDBDocument.FindLevelByElevation(boundaryBBox.Min.Z / Revit.ModelUnits);
            }

            DA.DisableGapLogic();
            int Iteration = DA.Iteration;

            Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, boundary, roofType, level));
        }
Example #27
0
        /// <summary>
        /// Create a brace.
        /// </summary>
        /// <param name="curve">The cruve which defines the center line of the brace.</param>
        /// <param name="level">The level with which you'd like the brace to be associated.</param>
        /// <param name="structuralFramingType">The structural framing type representing the brace.</param>
        /// <returns></returns>
        public static StructuralFraming BraceByCurve(Autodesk.DesignScript.Geometry.Curve curve, Revit.Elements.Level level, Revit.Elements.FamilySymbol structuralFramingType)
        {
            if (curve == null)
            {
                throw new System.ArgumentNullException("curve");
            }

            if (level == null)
            {
                throw new System.ArgumentNullException("level");
            }

            if (structuralFramingType == null)
            {
                throw new System.ArgumentNullException("structuralFramingType");
            }

            return new StructuralFraming(curve.ToRevitType(), level.InternalLevel, Autodesk.Revit.DB.Structure.StructuralType.Brace, structuralFramingType.InternalFamilySymbol);
        }
Example #28
0
        public static DividedPath ByCurvesAndDivisions(Revit.Elements.Element[] elements, int divisions)
        {
            if (elements == null)
            {
                throw new ArgumentNullException("elements");
            }

            if (divisions < 2)
            {
                throw new Exception("The number of divisions must be greater than 2!");
            }

            if (elements.Any(x => x == null))
            {
                throw new ArgumentNullException(String.Format("curves[{0}]", Array.FindIndex(elements, x => x == null)));
            }

            return new DividedPath(elements.Select(x => ElementCurveReference.TryGetCurveReference(x)).ToArray(), divisions);
        }
Example #29
0
 public static double InternalElevation(Revit.Elements.Level level)
 {
     return (level.InternalElement as Autodesk.Revit.DB.Level).Elevation;
 }
Example #30
0
        public override Result Execute(ExternalCommandData data, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            var    result   = Result.Failed;
            string rhinoTab = Addin.RhinoVersionInfo?.ProductName ?? "Rhinoceros";

            if (RhinoCommand.Availability.Available)
            {
                if (Keyboard.IsKeyDown(Key.LeftCtrl))
                {
                    return(Rhinoceros.RunCommandAbout());
                }

                using (var modal = new Rhinoceros.ModalScope())
                    result = modal.Run(false, true);

                // If no windows are visible we show the Ribbon tab
                if (result == Result.Cancelled)
                {
                    result = data.Application.ActivateRibbonTab(rhinoTab) ? Result.Succeeded : Result.Failed;
                }

                return(result);
            }

            result = Addin.CheckSetup();
            if (result != Result.Succeeded)
            {
                return(result);
            }

            result = Revit.OnStartup(Revit.ApplicationUI);
            if (RhinoCommand.Availability.Available = result == Result.Succeeded)
            {
                // Update Rhino button Tooltip
                Button.ToolTip         = $"Restores previously visible Rhino windows on top of Revit window";
                Button.LongDescription = $"Use CTRL key to open a Rhino model";

                // Register UI on Revit
                data.Application.CreateRibbonTab(rhinoTab);

                var RhinocerosPanel = data.Application.CreateRibbonPanel(rhinoTab, "Rhinoceros");
                HelpCommand.CreateUI(RhinocerosPanel);
                RhinocerosPanel.AddSeparator();
                CommandRhino.CreateUI(RhinocerosPanel);
                CommandPython.CreateUI(RhinocerosPanel);

                var GrasshopperPanel = data.Application.CreateRibbonPanel(rhinoTab, "Grasshopper");
                CommandGrasshopper.CreateUI(GrasshopperPanel);
                CommandGrasshopperPlayer.CreateUI(GrasshopperPanel);
                CommandGrasshopperPreview.CreateUI(GrasshopperPanel);
                CommandGrasshopperRecompute.CreateUI(GrasshopperPanel);
                CommandGrasshopperBake.CreateUI(GrasshopperPanel);

                var SamplesPanel = data.Application.CreateRibbonPanel(rhinoTab, "Samples");
                Samples.Sample1.CreateUI(SamplesPanel);
                Samples.Sample4.CreateUI(SamplesPanel);
                Samples.Sample6.CreateUI(SamplesPanel);
                Samples.Sample8.CreateUI(SamplesPanel);
            }

            if (result == Result.Succeeded)
            {
                // Activate Rhinoceros Tab
                result = data.Application.ActivateRibbonTab(rhinoTab) ? Result.Succeeded : Result.Failed;
            }
            else
            {
                // No more loads in this session
                Button.Enabled = false;
                Button.ToolTip = "Failed to load.";
            }

            return(result);
        }
Example #31
0
 private static ElementCurveReference TryGetCurveReference(Revit.Elements.CurveElement curveObject)
 {
     return curveObject.ElementCurveReference;
 }
Example #32
0
 static void Document_DefaultPreviewColourChanged(System.Drawing.Color colour) => Revit.RefreshActiveView();
Example #33
0
 internal XYZ InternalPosition(Revit.Elements.ReferencePoint point)
 {
     return (point.InternalElement as Autodesk.Revit.DB.ReferencePoint).Position;
 }
Example #34
0
        /// <summary>
        /// Create an element based Tag
        /// </summary>
        /// <param name="view">View to Tag</param>
        /// <param name="element">Element to tag</param>
        /// <param name="horizontal">Horizontal alignment</param>
        /// <param name="addLeader">Add a leader</param>
        /// <param name="offset">Offset Vector</param>
        /// <param name="horizontalAlignment">Horizontal Alignment</param>
        /// <param name="verticalAlignment">Vertical Alignment</param>
        /// <returns></returns>
        public static Tag ByElement(Revit.Elements.Views.View view, Element element, bool horizontal, bool addLeader, Autodesk.DesignScript.Geometry.Vector offset = null, string horizontalAlignment = "Center", string verticalAlignment = "Middle")
        {
            if (offset == null) offset = Autodesk.DesignScript.Geometry.Vector.ByCoordinates(0, 0, 0);

            Autodesk.Revit.DB.HorizontalAlignmentStyle alignHorizontal = Autodesk.Revit.DB.HorizontalAlignmentStyle.Center;
            Enum.TryParse<Autodesk.Revit.DB.HorizontalAlignmentStyle>(horizontalAlignment, out alignHorizontal);

            Autodesk.Revit.DB.VerticalAlignmentStyle alignVertical = Autodesk.Revit.DB.VerticalAlignmentStyle.Middle;
            Enum.TryParse<Autodesk.Revit.DB.VerticalAlignmentStyle>(verticalAlignment, out alignVertical);

            //Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;
            Autodesk.Revit.DB.View revitView = (Autodesk.Revit.DB.View)view.InternalElement;
            Autodesk.Revit.DB.XYZ point = null;
            Autodesk.Revit.DB.TagMode tagMode = TagMode.TM_ADDBY_CATEGORY;
            Autodesk.Revit.DB.TagOrientation orientation = (horizontal)? TagOrientation.Horizontal : TagOrientation.Vertical;

            if (revitView.ViewType != ViewType.FloorPlan &&
                revitView.ViewType != ViewType.EngineeringPlan &&
                revitView.ViewType != ViewType.Detail &&
                revitView.ViewType != ViewType.Section &&
                revitView.ViewType != ViewType.Elevation &&
                revitView.ViewType != ViewType.CeilingPlan)
                throw new ArgumentException("Cannot place a Tag on active View");

                //if (element.InternalElement.Location.GetType() == typeof(LocationPoint))
                //{
                //    LocationPoint locationPoint = (LocationPoint)element.InternalElement.Location;
                //    point = locationPoint.Point;
                //}
                //else if (element.InternalElement.Location.GetType() == typeof(LocationCurve))
                //{
                //    LocationCurve locationCurve = (LocationCurve)element.InternalElement.Location;
                //    point = locationCurve.Curve.GetEndPoint(0);
                //}
                //else
                //{
                    BoundingBoxXYZ box = element.InternalElement.get_BoundingBox(revitView);
                    if (box == null) box = element.InternalElement.get_BoundingBox(null);
                    if (box != null)
                    {
                        double Y, X = 0;

                        switch (alignVertical)
                        {
                            case VerticalAlignmentStyle.Bottom: Y = box.Min.Y; break;
                            case VerticalAlignmentStyle.Top: Y = box.Max.Y; break;
                            default: Y = box.Min.Y + ((box.Max.Y - box.Min.Y) / 2); break;
                        }

                        switch (alignHorizontal)
                        {
                            case HorizontalAlignmentStyle.Left: X = box.Min.X; break;
                            case HorizontalAlignmentStyle.Right: X = box.Max.X; break;
                            default: X = box.Min.X + ((box.Max.X - box.Min.X) / 2); break;
                        }

                        point = new XYZ(X + offset.X, Y + offset.Y, 0 + offset.Z);
                    }
                    else throw new ArgumentNullException("Cannot determine location");
                //}

                return new Tag(revitView, element.InternalElement, orientation, tagMode, addLeader, point);
        }
Example #35
0
 public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
 {
     GH.PreviewServer.PreviewMode = Grasshopper.Kernel.GH_PreviewMode.Shaded;
     Revit.RefreshActiveView();
     return(Result.Succeeded);
 }
Example #36
0
        private void SetParameterValue(Autodesk.Revit.DB.Parameter param, Revit.Elements.Element value)
        {
            if (param.StorageType != StorageType.ElementId)
                throw new Exception("The parameter's storage type is not an Element.");

            param.Set(value.InternalElementId);
        }
Example #37
0
 void ActiveDefinition_SolutionEnd(object sender, GH_SolutionEventArgs e)
 {
     Clear();
     Revit.RefreshActiveView();
 }
Example #38
0
        //******************************************************************************************
        /// <summary>
        /// Run process calculations and etc.
        /// </summary>
        public override void OnRun()
        {
            base.OnRun();
            List <ViewPath> fileNames = new List <ViewPath>();

            Autodesk.Revit.DB.DWGExportOptions dwgOpt = dlgExportOptions.GetExportOptions(dlgOptions.Copy);
            dwgOpt.FileVersion = dlgOptions.GetVersion();

            Autodesk.Revit.DB.DWGImportOptions dwgImpOpt = dlgOptions.GetImportOptions();
            dwgImpOpt.Unit = dlgExportOptions.GetExportUnits(dlgOptions.Copy);

            m_ExpImpMng.Clean();


            try //for demo mode
            {
                List <Autodesk.Revit.DB.View> viewList;
                if (FreezeControl.CurrentView)
                {
                    Autodesk.Revit.DB.View v = Revit.CommandData().Application.ActiveUIDocument.Document.ActiveView;

                    if (!(v.ViewType == Autodesk.Revit.DB.ViewType.Internal || v.ViewType == Autodesk.Revit.DB.ViewType.DrawingSheet || !v.CanBePrinted))
                    {
                        viewList = new List <Autodesk.Revit.DB.View>();
                        viewList.Add(Revit.CommandData().Application.ActiveUIDocument.Document.ActiveView);
                    }
                    else
                    {
                        viewList = new List <Autodesk.Revit.DB.View>();
                    }
                }
                else
                {
                    viewList = dlgViewSel.GetSelectedViews();
                }

                if (viewList.Count > 0)
                {
                    IREXProgress Progress = System.SystemBase.Tools.Prograss;
                    Progress.Steps = 2 * viewList.Count;
                    Progress.Show(GetForm());
                    GetForm().Hide();

                    fileNames = m_ExpImpMng.Export(viewList, dwgOpt, Progress);
                    m_ExpImpMng.Import(dlgOptions.Copy, dlgOptions.Browse, dlgOptions.BaseName, dwgImpOpt, fileNames, Progress);

                    if (dlgOptions.DeleteView)
                    {
                        m_ExpImpMng.DeleteViews(viewList);
                    }

                    Progress.Hide();
                    global::System.Windows.Forms.MessageBox.Show(GetForm(), Resources.Strings.Texts.FreezingFinSuccesfull, Resources.Strings.Texts.REX_ModuleDescription);
                }
            }
            catch
            {
            }

            m_ExpImpMng.Clean();
            DataRef.OptionPath = dlgOptions.Browse;
            System.SaveToFile(false, false);
        }
Example #39
0
        public static DividedPath ByCurveAndDivisions(Revit.Elements.Element element, int divisions)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            if (divisions < 2)
            {
                throw new Exception("The number of divisions must be greater than 2!");
            }

            return new DividedPath(new[] { ElementCurveReference.TryGetCurveReference(element) }, divisions);
        }
Example #40
0
        /// <summary>
        /// Create Rebar by Curves
        /// </summary>
        /// <param name="curves">Input Curves</param>
        /// <param name="hostElementId">Host Element Id</param>
        /// <param name="rebarStyle">Rebar Style</param>
        /// <param name="rebarBarType">Bar Type</param>
        /// <param name="startHookOrientation">Hokk orientation at the start</param>
        /// <param name="endHookOrientation">Hook orientation at the end</param>
        /// <param name="startHookType">Hook type at the start</param>
        /// <param name="startHookType">Hook type at the start</param>
        /// <param name="endHookType">Hook type at the end</param>
        /// <param name="vector">Normal Vectors</param>
        /// <returns></returns>
        public static Rebar ByCurve(
            Autodesk.DesignScript.Geometry.Curve curve,
            int hostElementId,
            string rebarStyle,
            Revit.Elements.Element rebarBarType,
            string startHookOrientation,
            string endHookOrientation,
            Revit.Elements.Element startHookType,
            Revit.Elements.Element endHookType,
            Autodesk.DesignScript.Geometry.Vector vector
            )
        {
            if (curve == null) throw new ArgumentNullException("Input Curve missing");
            if (hostElementId == null) throw new ArgumentNullException("Host ElementId missing");
            if (rebarStyle == null) throw new ArgumentNullException("Rebar Style missing");
            if (rebarBarType == null) throw new ArgumentNullException("Rebar Bar Type missing");
            if (startHookOrientation == null) throw new ArgumentNullException("Start Hook Orientation missing");
            if (endHookOrientation == null) throw new ArgumentNullException("End Hook Orientation missing");
            //if (startHookType == null) throw new ArgumentNullException("Start Hook Type missing");
            //if (endHookType == null) throw new ArgumentNullException("End Hook Type missing");
            if (vector == null) throw new ArgumentNullException("Normal Vector missing");

            ElementId elementId = new ElementId(hostElementId);
            if (elementId == ElementId.InvalidElementId) throw new ArgumentNullException("Host ElementId error");

            Autodesk.Revit.DB.Element host = DocumentManager.Instance.CurrentDBDocument.GetElement(elementId);

            Autodesk.Revit.DB.Structure.RebarStyle barStyle = Autodesk.Revit.DB.Structure.RebarStyle.StirrupTie;
            Enum.TryParse<Autodesk.Revit.DB.Structure.RebarStyle>(rebarStyle, out barStyle);

            Autodesk.Revit.DB.Structure.RebarHookOrientation startOrientation = Autodesk.Revit.DB.Structure.RebarHookOrientation.Left;
            Enum.TryParse<Autodesk.Revit.DB.Structure.RebarHookOrientation>(startHookOrientation, out startOrientation);
            Autodesk.Revit.DB.Structure.RebarHookOrientation endOrientation = Autodesk.Revit.DB.Structure.RebarHookOrientation.Left;
            Enum.TryParse<Autodesk.Revit.DB.Structure.RebarHookOrientation>(endHookOrientation, out endOrientation);

            Autodesk.Revit.DB.Structure.RebarHookType startHookT = (startHookType == null) ? null : (Autodesk.Revit.DB.Structure.RebarHookType)startHookType.InternalElement;
            Autodesk.Revit.DB.Structure.RebarHookType endHookT = (endHookType == null) ? null : (Autodesk.Revit.DB.Structure.RebarHookType)endHookType.InternalElement;

            return new Rebar(curve.Approximate(), (Autodesk.Revit.DB.Structure.RebarBarType)rebarBarType.InternalElement, barStyle, host, startHookT, endHookT
                , startOrientation, endOrientation, vector.ToRevitType(), true, true);
        }
Example #41
0
        /// <summary>
        /// Create a column.
        /// </summary>
        /// <param name="curve">The curve which defines the center line of the column.</param>
        /// <param name="level">The level with which you'd like the column to be associated.</param>
        /// <param name="structuralColumnType">The structural column type representing the column.</param>
        /// <returns></returns>
        public static StructuralFraming ColumnByCurve(
            Autodesk.DesignScript.Geometry.Curve curve, Revit.Elements.Level level, Revit.Elements.FamilySymbol structuralColumnType)
        {
            if (curve == null)
            {
                throw new System.ArgumentNullException("curve");
            }

            if (level == null)
            {
                throw new System.ArgumentNullException("level");
            }

            if (structuralColumnType == null)
            {
                throw new System.ArgumentNullException("structuralColumnType");
            }

            var start = curve.PointAtParameter(0);
            var end = curve.PointAtParameter(1);

            // Revit will throw an exception if you attempt to create a column whose 
            // base is above its top. 
            if (end.Z <= start.Z)
            {
                throw new Exception("The end of the curve for creating a column should be above the start of the curve.");
            }

            return new StructuralFraming(curve.ToRevitType(), level.InternalLevel, Autodesk.Revit.DB.Structure.StructuralType.Column, structuralColumnType.InternalFamilySymbol);
        }
Example #42
0
 public static Form ByLoftCrossSections(Revit.Elements.Element[] curves, bool isSolid = true)
 {
     if (curves == null) throw new ArgumentNullException("curves");
     return ByLoftCrossSectionsInternal(curves, isSolid);
 }
Example #43
0
        /// <summary>
        /// Create a solid by extracting solids from an element.
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public static Solid FromElement(Revit.Elements.Element element)
        {
            if (element == null)
            {
                throw new ArgumentException("element");
            }

            return new Solid(element.InternalElement);
        }
Example #44
0
 void ActiveDefinition_SolutionEnd(object sender, GH_SolutionEventArgs e)
 {
     RebuildPrimitives = 1;
     Revit.RefreshActiveView();
 }
Example #45
0
 internal XYZ InternalLocation(Revit.Elements.ModelText text)
 {
     return ((LocationPoint)text.InternalElement.Location).Point;
 }
        /// <summary>
        /// Exports spatial elements, including rooms, areas and spaces. 2nd level space boundaries.
        /// </summary>
        /// <param name="ifcExporter">The Exporter object.</param>
        /// <param name="exporterIFC"> The ExporterIFC object.</param>
        /// <param name="document">The Revit document.</param>
        /// <returns>The set of exported spaces.  This is used to try to export using the standard routine for spaces that failed.</returns>
        public static ISet<ElementId> ExportSpatialElement2ndLevel(Revit.IFC.Export.Exporter.Exporter ifcExporter, ExporterIFC exporterIFC, Document document)
        {
            ISet<ElementId> exportedSpaceIds = new HashSet<ElementId>();

            using (SubTransaction st = new SubTransaction(document))
            {
                st.Start();

                EnergyAnalysisDetailModel model = null;
                try
                {
                    View filterView = ExporterCacheManager.ExportOptionsCache.FilterViewForExport;
                    IFCFile file = exporterIFC.GetFile();
                    using (IFCTransaction transaction = new IFCTransaction(file))
                    {

                        EnergyAnalysisDetailModelOptions options = new EnergyAnalysisDetailModelOptions();
                        options.Tier = EnergyAnalysisDetailModelTier.SecondLevelBoundaries; //2nd level space boundaries
                        options.SimplifyCurtainSystems = true;
                        try
                        {
                            model = EnergyAnalysisDetailModel.Create(document, options);
                        }
                        catch (System.Exception)
                        {
                            return exportedSpaceIds;
                        }

                        IList<EnergyAnalysisSpace> spaces = model.GetAnalyticalSpaces();
                        foreach (EnergyAnalysisSpace space in spaces)
                        {
                            SpatialElement spatialElement = document.GetElement(space.CADObjectUniqueId) as SpatialElement;

                            if (spatialElement == null)
                                continue;

                            //current view only
                            if (!ElementFilteringUtil.IsElementVisible(spatialElement))
                                continue;

                            if (!ElementFilteringUtil.ShouldElementBeExported(exporterIFC, spatialElement, false))
                                continue;

                            if (ElementFilteringUtil.IsRoomInInvalidPhase(spatialElement))
                                continue;

                            Options geomOptions = GeometryUtil.GetIFCExportGeometryOptions();
                            View ownerView = spatialElement.Document.GetElement(spatialElement.OwnerViewId) as View;
                            if (ownerView != null)
                                geomOptions.View = ownerView;
                            GeometryElement geomElem = spatialElement.get_Geometry(geomOptions);

                            try
                            {
                                exporterIFC.PushExportState(spatialElement, geomElem);

                                using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true))
                                {
                                    using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, spatialElement))
                                    {
                                        // We won't use the SpatialElementGeometryResults, as these are 1st level boundaries, not 2nd level.
                                        SpatialElementGeometryResults results = null;
                                        if (!CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter, out results))
                                            continue;

                                        exportedSpaceIds.Add(spatialElement.Id);

                                        XYZ offset = GetSpaceBoundaryOffset(setter);

                                        //get boundary information from surfaces
                                        IList<EnergyAnalysisSurface> surfaces = space.GetAnalyticalSurfaces();
                                        foreach (EnergyAnalysisSurface surface in surfaces)
                                        {
                                            Element boundingElement = GetBoundaryElement(document, surface.CADLinkUniqueId, surface.CADObjectUniqueId);

                                            IList<EnergyAnalysisOpening> openings = surface.GetAnalyticalOpenings();
                                            IFCAnyHandle connectionGeometry = CreateConnectionSurfaceGeometry(exporterIFC, surface, openings, offset);
                                            CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, boundingElement, setter.LevelId, connectionGeometry);

                                            // try to add doors and windows for host objects if appropriate.
                                            if (boundingElement is HostObject)
                                            {
                                                foreach (EnergyAnalysisOpening opening in openings)
                                                {
                                                    Element openingBoundingElem = GetBoundaryElement(document, opening.CADLinkUniqueId, opening.CADObjectUniqueId);
                                                    IFCAnyHandle openingConnectionGeom = CreateConnectionSurfaceGeometry(exporterIFC, opening, offset);
                                                    CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, openingBoundingElem, setter.LevelId, openingConnectionGeom);
                                                }
                                            }
                                        }
                                        CreateZoneInfos(exporterIFC, file, spatialElement, productWrapper);
                                        CreateSpaceOccupantInfo(exporterIFC, file, spatialElement, productWrapper);

                                        ExporterUtil.ExportRelatedProperties(exporterIFC, spatialElement, productWrapper);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ifcExporter.HandleUnexpectedException(ex, exporterIFC, spatialElement);
                            }
                            finally
                            {
                                exporterIFC.PopExportState();
                            }
                        }
                        transaction.Commit();
                    }
                }
                finally
                {
                    if (model != null)
                        EnergyAnalysisDetailModel.Destroy(model);
                }

                st.RollBack();
                return exportedSpaceIds;
            }
        }
Example #47
0
        /// <summary>
        /// Create Rebar Container by Curves
        /// </summary>
        /// <param name="curves">Input Curves</param>
        /// <param name="hostElementId">Host Element Id</param>
        /// <param name="rebarStyle">Rebar Style</param>
        /// <param name="rebarBarType">Bar Type</param>
        /// <param name="startHookOrientation">Hokk orientation at the start</param>
        /// <param name="endHookOrientation">Hook orientation at the end</param>
        /// <param name="startHookType">Hook type at the start</param>
        /// <param name="endHookType">Hook type at the end</param>
        /// <param name="vectors">Normal Vectors</param>
        /// <returns></returns>
        public static RebarContainer ByCurve(
            System.Collections.Generic.List<Autodesk.DesignScript.Geometry.Curve> curves,
            int hostElementId,
            string rebarStyle,
            Revit.Elements.Element rebarBarType,
            string startHookOrientation,
            string endHookOrientation,            
            Revit.Elements.Element startHookType,
            Revit.Elements.Element endHookType,
            System.Collections.Generic.List<Autodesk.DesignScript.Geometry.Vector> vectors
            )
        {
            if (curves == null) throw new ArgumentNullException("Input Curves missing");
            if (hostElementId == null) throw new ArgumentNullException("Host ElementId missing");
            if (rebarStyle == null) throw new ArgumentNullException("Rebar Style missing");
            if (rebarBarType == null) throw new ArgumentNullException("Rebar Bar Type missing");
            if (startHookOrientation == null) throw new ArgumentNullException("Start Hook Orientation missing");
            if (endHookOrientation == null) throw new ArgumentNullException("End Hook Orientation missing");
            //if (startHookType == null) throw new ArgumentNullException("Start Hook Type missing");
            //if (endHookType == null) throw new ArgumentNullException("End Hook Type missing");
            if (vectors == null) throw new ArgumentNullException("Normal Vector missing");

            ElementId elementId = new ElementId(hostElementId);
            if (elementId == ElementId.InvalidElementId) throw new ArgumentNullException("Host ElementId error");

            Autodesk.Revit.DB.Element host = DocumentManager.Instance.CurrentDBDocument.GetElement(elementId);

            System.Collections.Generic.List<object> revitCurves = new System.Collections.Generic.List<object>();
            foreach (Autodesk.DesignScript.Geometry.Curve curve in curves) revitCurves.Add(curve.Approximate());

            // Parse Rebar Style
            Autodesk.Revit.DB.Structure.RebarStyle barStyle = Autodesk.Revit.DB.Structure.RebarStyle.StirrupTie;
            Enum.TryParse<Autodesk.Revit.DB.Structure.RebarStyle>(rebarStyle, out barStyle);
            
            // Parse Rebar Hook Orientation
            Autodesk.Revit.DB.Structure.RebarHookOrientation startOrientation = Autodesk.Revit.DB.Structure.RebarHookOrientation.Left;
            Enum.TryParse<Autodesk.Revit.DB.Structure.RebarHookOrientation>(startHookOrientation, out startOrientation);

            // Parse Rebar Hook Orientation
            Autodesk.Revit.DB.Structure.RebarHookOrientation endOrientation = Autodesk.Revit.DB.Structure.RebarHookOrientation.Left;
            Enum.TryParse<Autodesk.Revit.DB.Structure.RebarHookOrientation>(endHookOrientation, out endOrientation);

            List<XYZ> normals = new List<XYZ>();
            foreach (Autodesk.DesignScript.Geometry.Vector vector in vectors) normals.Add(vector.ToRevitType());

            Autodesk.Revit.DB.Structure.RebarHookType startHookT = (startHookType == null) ? null : (Autodesk.Revit.DB.Structure.RebarHookType)startHookType.InternalElement;
            Autodesk.Revit.DB.Structure.RebarHookType endHookT = (endHookType == null) ? null : (Autodesk.Revit.DB.Structure.RebarHookType)endHookType.InternalElement;

            return new RebarContainer(revitCurves, (Autodesk.Revit.DB.Structure.RebarBarType)rebarBarType.InternalElement, barStyle, host,
                startHookT,
                endHookT, startOrientation, endOrientation, normals, true, true);
        }
Example #48
0
        /// <summary>
        /// Appends a Bar to an existing Rebar container (or creates it if no container is supplied)
        /// </summary>
        /// <param name="rebars">List of Bars to add</param>
        /// <param name="container">Optional: Existing Rebar Container</param>
        public static Revit.Elements.RebarContainer AppendBar(List<Revit.Elements.Rebar> rebars, Revit.Elements.RebarContainer container = null)
        {
            if (container == null)
            {
                container = Revit.Elements.RebarContainer.ByBars(rebars);
            }
            else
            {
                foreach (Revit.Elements.Rebar rebar in rebars) container.InternalRebarContainer.AppendItemFromRebar(rebar.InternalRebar);
            }


            // Delete Bars from Document

            #region delete Bars

            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;
            TransactionManager.Instance.EnsureInTransaction(document);

            List<ElementId> idsToDelete = new List<ElementId>();
            foreach (Revit.Elements.Rebar rebar in rebars)
                if (rebar.InternalRebar != null && rebar.InternalRebar.Id != ElementId.InvalidElementId) idsToDelete.Add(rebar.InternalRebar.Id);

            document.Delete(idsToDelete);

            TransactionManager.Instance.TransactionTaskDone();

            #endregion

            return container;
        }
Example #49
0
        public override Result Execute(ExternalCommandData data, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            if
            (
                (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) &&
                (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
            )
            {
                return(ShowLoadError(data));
            }

            string rhinoTab = Addin.RhinoVersionInfo?.ProductName ?? "Rhinoceros";

            if (Addin.CurrentStatus == Addin.Status.Ready)
            {
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    return(Rhinoceros.RunCommandAbout());
                }

                if
                (
                    Rhinoceros.MainWindow.Visible ||
                    Rhinoceros.MainWindow.ActivePopup?.IsInvalid == false
                )
                {
                    Rhinoceros.MainWindow.BringToFront();
                    return(Result.Succeeded);
                }

                // If no windows are visible we show the Ribbon tab
                return(data.Application.ActivateRibbonTab(rhinoTab) ? Result.Succeeded : Result.Failed);
            }

            var result = Result.Failed;

            switch (result = Revit.OnStartup(Revit.ApplicationUI))
            {
            case Result.Succeeded:
                // Update Rhino button Tooltip
                Button.ToolTip         = $"Restores previously visible Rhino windows on top of Revit window";
                Button.LongDescription = $"Use CTRL key to open a Rhino model";

                // Register UI on Revit
                data.Application.CreateRibbonTab(rhinoTab);

                var RhinocerosPanel = data.Application.CreateRibbonPanel(rhinoTab, "Rhinoceros");
                HelpCommand.CreateUI(RhinocerosPanel);
                RhinocerosPanel.AddSeparator();
                CommandRhino.CreateUI(RhinocerosPanel);
                CommandRhinoPreview.CreateUI(RhinocerosPanel);
                CommandPython.CreateUI(RhinocerosPanel);

                var GrasshopperPanel = data.Application.CreateRibbonPanel(rhinoTab, "Grasshopper");
                CommandGrasshopper.CreateUI(GrasshopperPanel);
                CommandGrasshopperPlayer.CreateUI(GrasshopperPanel);
                CommandGrasshopperPreview.CreateUI(GrasshopperPanel);
                CommandGrasshopperRecompute.CreateUI(GrasshopperPanel);
                CommandGrasshopperBake.CreateUI(GrasshopperPanel);

                var SamplesPanel = data.Application.CreateRibbonPanel(rhinoTab, "Samples");
                Samples.Sample1.CreateUI(SamplesPanel);
                Samples.Sample4.CreateUI(SamplesPanel);
                Samples.Sample8.CreateUI(SamplesPanel);

                result = data.Application.ActivateRibbonTab(rhinoTab) ? Result.Succeeded : Result.Failed;
                break;

            case Result.Cancelled:
                Button.Enabled = false;

                if (Addin.CurrentStatus == Addin.Status.Unavailable)
                {
                    Button.ToolTip = "Rhino.Inside failed to found a valid copy of Rhino 7 WIP installed.";
                }
                else if (Addin.CurrentStatus == Addin.Status.Obsolete)
                {
                    Button.ToolTip = "Rhino.Inside has expired.";
                }
                else
                {
                    Button.ToolTip = "Rhino.Inside load was cancelled.";
                }

                Button.SetContextualHelp(new ContextualHelp(ContextualHelpType.Url, @"https://www.rhino3d.com/inside/revit"));
                break;

            case Result.Failed:
                Button.Enabled = false;
                Button.ToolTip = "Rhino.Inside failed to load.";
                ShowLoadError(data);
                break;
            }

            return(result);
        }
Example #50
0
        internal static Result Start(RibbonHandler ribbon)
        {
            var result = Result.Failed;
            var button = RestoreButton(CommandName);

            switch (result = Revit.OnStartup(Revit.ApplicationUI))
            {
            case Result.Succeeded:
                // Update Rhino button Tooltip
                button.ToolTip         = $"Restores previously visible Rhino windows on top of Revit window";
                button.LongDescription = $"Use CTRL key to open a Rhino model";
                // hide the button title
                if (button.GetAdwndRibbonButton() is Autodesk.Windows.RibbonButton adwndRadioButton)
                {
                    adwndRadioButton.ShowText = false;
                }

                var assemblies = AppDomain.CurrentDomain.GetAssemblies();

                // Register UI on Revit
                if (assemblies.Any(x => x.GetName().Name == "RhinoCommon"))
                {
                    rhinoPanel = ribbon.CreateAddinPanel(Addin.RhinoVersionInfo?.ProductName ?? "Rhinoceros");
                    CommandRhino.CreateUI(rhinoPanel);
                    CommandImport.CreateUI(rhinoPanel);
                    CommandToggleRhinoPreview.CreateUI(rhinoPanel);
                    CommandPython.CreateUI(rhinoPanel);
                    CommandRhinoOptions.CreateUI(rhinoPanel);
                }

                if (assemblies.Any(x => x.GetName().Name == "Grasshopper"))
                {
                    grasshopperPanel = ribbon.CreateAddinPanel("Grasshopper");
                    CommandGrasshopper.CreateUI(grasshopperPanel);
                    CommandGrasshopperPreview.CreateUI(grasshopperPanel);
                    CommandGrasshopperSolver.CreateUI(grasshopperPanel);
                    CommandGrasshopperRecompute.CreateUI(grasshopperPanel);
                    CommandGrasshopperBake.CreateUI(grasshopperPanel);
                    grasshopperPanel.AddSeparator();
                    CommandGrasshopperPlayer.CreateUI(grasshopperPanel);
                    grasshopperPanel.AddSlideOut();
                    CommandGrasshopperPackageManager.CreateUI(grasshopperPanel);
                    CommandGrasshopperFolders.CreateUI(grasshopperPanel);

                    // Script Packages UI
                    UpdateScriptPkgUI(ribbon);

                    // setup listeners, and in either case, update the packages ui
                    // listed for changes in installed packages
                    CommandGrasshopperPackageManager.CommandCompleted += CommandGrasshopperPackageManager_CommandCompleted;
                    // listen for changes to user-script paths in options
                    AddinOptions.ScriptLocationsChanged += AddinOptions_ScriptLocationsChanged;
                }

                UpdateRibbonCompact();

                result = Result.Succeeded;
                break;

            case Result.Cancelled:
                button.Enabled = false;

                if (Addin.CurrentStatus == Addin.Status.Unavailable)
                {
                    button.ToolTip = "Rhino.Inside failed to found a valid copy of Rhino 7 WIP installed.";
                }
                else if (Addin.CurrentStatus == Addin.Status.Obsolete)
                {
                    button.ToolTip = "Rhino.Inside has expired.";
                }
                else
                {
                    button.ToolTip = "Rhino.Inside load was cancelled.";
                }

                button.SetContextualHelp(new ContextualHelp(ContextualHelpType.Url, @"https://www.rhino3d.com/inside/revit"));
                break;

            case Result.Failed:
                button.Enabled = false;
                button.ToolTip = "Rhino.Inside failed to load.";
                return(Result.Failed);
            }
            return(result);
        }
Example #51
0
        /// <summary>
        /// Set unobscured in specified View
        /// </summary>
        /// <param name="rebarContainer">Rebar Container</param>
        /// <param name="view">View</param>
        /// <param name="unobscured">Unobscured</param>
        public static void SetUnobscuredInView(RebarContainer rebarContainer, Revit.Elements.Views.View view, bool unobscured)
        {
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;
            TransactionManager.Instance.EnsureInTransaction(document);

            Autodesk.Revit.DB.Structure.RebarContainer rebarElement = (Autodesk.Revit.DB.Structure.RebarContainer)rebarContainer.InternalElement;
            Autodesk.Revit.DB.View viewElement = (Autodesk.Revit.DB.View)view.InternalElement;
            rebarElement.SetUnobscuredInView(viewElement, unobscured);

            TransactionManager.Instance.TransactionTaskDone();
        }
        public static int StructuralFramingFromFilePath(string filepath,Revit.Elements.FamilyType type,int lengthTol)
        {
            var document = DocumentManager.Instance.CurrentDBDocument;
            FilteredElementCollector collector = new FilteredElementCollector(document);
               ICollection<Autodesk.Revit.DB.Element> collection = collector.OfClass(typeof(Autodesk.Revit.DB.Level)).ToElements();
               var level = (collection.First() as Autodesk.Revit.DB.Level);
               var count = 0;
            var returnlibrary = new Dictionary<string, Tuple<Autodesk.Revit.DB.Curve,int>>();

            var BatchframeDatas = new List<FamilyInstanceCreationData>();

              using (StreamReader r = new StreamReader(filepath))
            {
                BatchframeDatas.Clear();
                //we are going to chunk our CSV file as well, so we will not load the entire csv into memory at once...
                TransactionManager.Instance.EnsureInTransaction(DocumentManager.Instance.CurrentDBDocument);
                while (!r.EndOfStream)
                {

                    var line = r.ReadLine();
                    var cells = line.Split(',');
                    var startPoint = Autodesk.DesignScript.Geometry.Point.ByCoordinates(double.Parse(cells[0]), double.Parse(cells[1]), double.Parse(cells[2]));
                    var endPoint = Autodesk.DesignScript.Geometry.Point.ByCoordinates(double.Parse(cells[3]), double.Parse(cells[4]), double.Parse(cells[5]));

                    //create a line from start to end
                    var geoline = Autodesk.DesignScript.Geometry.Line.ByStartPointEndPoint(startPoint, endPoint);
                    var alignedline = geoline.Transform(geoline.CoordinateSystemAtParameter(.5).Inverse());
                    var key = Math.Round(geoline.Length, lengthTol).ToString();
                    var dubkey = Math.Round(geoline.Length, lengthTol);

                    var cs = geoline.CoordinateSystemAtParameter(.5);

                    //if the library doesnt have this key then generate some new geometry
                    if (!returnlibrary.ContainsKey(key))
                    {
                        returnlibrary.Add(key, Tuple.Create((alignedline as Autodesk.DesignScript.Geometry.Curve).ToRevitType(),0));
                    }

                    //now store the new count in the retur dict
                    var oldval = returnlibrary[key];
                    returnlibrary[key] = Tuple.Create(oldval.Item1, oldval.Item2 + 1);

                    var creationData = familyInstanceHelpers.GetCreationData(returnlibrary[key].Item1.CreateTransformed(cs.ToTransform()), level, Autodesk.Revit.DB.Structure.StructuralType.Beam, type.InternalElement as FamilySymbol);
                    BatchframeDatas.Add(creationData);

                    count = count + 1;
                    geoline.Dispose();
                    alignedline.Dispose();
                }

                    if (BatchframeDatas.Count > 0)
                    {
                        var elementIds = DocumentManager.Instance.CurrentDBDocument.Create.NewFamilyInstances2(BatchframeDatas);
                        foreach (var elementid in elementIds )
                        {
                            var ele = DocumentManager.Instance.CurrentDBDocument.GetElement(elementid);
                            Autodesk.Revit.DB.Structure.StructuralFramingUtils.DisallowJoinAtEnd(ele as Autodesk.Revit.DB.FamilyInstance,0);
                            Autodesk.Revit.DB.Structure.StructuralFramingUtils.DisallowJoinAtEnd(ele as Autodesk.Revit.DB.FamilyInstance, 1);
                        }
                    }

                }
                TransactionManager.Instance.TransactionTaskDone();
                return count;
        }
Example #53
0
        /// <summary>
        /// Construct a FreeFrom element from a solid
        /// </summary>
        /// <param name="solid"></param>
        /// <returns></returns>
        public static FreeForm BySolid(Revit.GeometryObjects.Solid solid)
        {
            if (solid == null)
            {
                throw new ArgumentNullException("solid");
            }

            if (!Document.IsFamilyDocument)
            {
                throw new Exception("You can only create a FreeForm element in the Family editor.  You can then import" +
                                    "this family into a Project environment as a family.");
            }

            return new FreeForm(solid.InternalSolid);
        }
Example #54
0
        public static AdaptiveComponent ByParametersOnCurveReference(double[] parameters, Revit.Elements.Element revitCurve, FamilySymbol familySymbol)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (revitCurve == null)
            {
                throw new ArgumentNullException("revitCurve");
            }

            if (familySymbol == null)
            {
                throw new ArgumentNullException("familySymbol");
            }

            return new AdaptiveComponent(parameters, ElementCurveReference.TryGetCurveReference(revitCurve).InternalReference, familySymbol);
        }
Example #55
0
        /// <summary>
        /// Set Solid In View
        /// </summary>
        /// <param name="rebar">Single Rebar</param>
        /// <param name="view">3D View</param>
        /// <param name="solid">Solid</param>
        public static void SetSolidInView(Rebar rebar, Revit.Elements.Views.View3D view, bool solid)
        {
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;
            TransactionManager.Instance.EnsureInTransaction(document);

            Autodesk.Revit.DB.Structure.Rebar rebarElement = (Autodesk.Revit.DB.Structure.Rebar)rebar.InternalElement;
            Autodesk.Revit.DB.View3D viewElement = (Autodesk.Revit.DB.View3D)view.InternalElement;
            rebarElement.SetSolidInView(viewElement, solid);

            TransactionManager.Instance.TransactionTaskDone();
        }
Example #56
0
 internal double InternalDepth(Revit.Elements.ModelText text)
 {
     return (text.InternalElement as Autodesk.Revit.DB.ModelText).Depth;
 }
Example #57
0
        /// <summary>
        /// Get Material Names from a Revit Element
        /// </summary>
        /// <param name="element">Revit Element</param>
        /// <param name="paintMaterials">Paint Materials</param>
        /// <returns>List of Names</returns>
        public static List<string> GetMaterialNames(Revit.Elements.Element element, bool paintMaterials = false)
        {
            // Get the active Document
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;

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

            foreach (Autodesk.Revit.DB.ElementId id in element.InternalElement.GetMaterialIds(paintMaterials))
            {
                RVT.Material material = (RVT.Material)document.GetElement(id);
                
                if (!materialnames.Contains(material.Name))
                    materialnames.Add(material.Name);
            }

            return materialnames;
        }
 public static int CreateDirectShapeByMesh(Autodesk.DesignScript.Geometry.Mesh mesh, Revit.Elements.Material mat, string name)
 {
     return NewDirectShape(mesh.VertexPositions,mesh.FaceIndices, RevitServices.Persistence.DocumentManager.Instance.CurrentDBDocument,ElementId.InvalidElementId, new ElementId(mat.Id), Guid.NewGuid().ToString(), name);
 }
Example #59
0
 static void Editor_VisibleChanged(object sender, EventArgs e) => Revit.RefreshActiveView();