Пример #1
0
        /// <summary>
        /// Tag the beam's start and end.
        /// </summary>
        /// <param name="tagMode">Mode of tag</param>
        /// <param name="tagSymbol">Tag symbol wrapper</param>
        /// <param name="leader">Whether the tag has leader</param>
        /// <param name="tagOrientation">Orientation of tag</param>
        public void CreateTag(TagMode tagMode,
                              FamilySymbolWrapper tagSymbol, bool leader,
                              TagOrientation tagOrientation)
        {
            foreach (FamilyInstance beam in m_beamList)
            {
                //Get the start point and end point of the selected beam.
                Autodesk.Revit.DB.LocationCurve location = beam.Location as Autodesk.Revit.DB.LocationCurve;
                Autodesk.Revit.DB.Curve         curve    = location.Curve;

                Transaction t = new Transaction(m_revitDoc.Document);
                t.Start("Create new tag");
                //Create tag on the beam's start and end.
                Reference      beamRef = new Reference(beam);
                IndependentTag tag1    = IndependentTag.Create(m_revitDoc.Document,
                                                               m_view.Id, beamRef, leader, tagMode, tagOrientation, curve.GetEndPoint(0));
                IndependentTag tag2 = IndependentTag.Create(m_revitDoc.Document,
                                                            m_view.Id, beamRef, leader, tagMode, tagOrientation, curve.GetEndPoint(1));

                //Change the tag's object Type.
                tag1.ChangeTypeId(tagSymbol.FamilySymbol.Id);
                tag2.ChangeTypeId(tagSymbol.FamilySymbol.Id);
                t.Commit();
            }
        }
Пример #2
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            var curveRef = ((Value.Container)args[0]).Item as Reference;

            Curve curve = null;

            var el = ((Value.Container)args[0]).Item as CurveElement;

            if (el != null)
            {
                var crvEl = el;
                curve = crvEl.GeometryCurve;
            }
            else
            {
                curve = curveRef == null
                              ? (Curve)((Value.Container)args[0]).Item
                              : (Curve)
                        dynRevitSettings.Doc.Document.GetElement(curveRef.ElementId)
                        .GetGeometryObjectFromReference(curveRef);
            }


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

            return(Value.NewContainer(DSCoreNodes.Domain.ByMinimumAndMaximum(start, end)));
        }
Пример #3
0
        public static Autodesk.Revit.DB.CurveLoop ToRevitType(this Autodesk.DesignScript.Geometry.PolyCurve pcrv,
                                                              bool performHostUnitConversion = true)
        {
            if (!pcrv.IsClosed)
            {
                throw new Exception("The input PolyCurve must be closed");
            }

            Autodesk.DesignScript.Geometry.Curve[] crvs = null;
            if (performHostUnitConversion)
            {
                pcrv = pcrv.InHostUnits();
                crvs = pcrv.Curves();
                pcrv.Dispose();
            }
            else
            {
                crvs = pcrv.Curves();
            }

            var cl = new CurveLoop();

            foreach (Autodesk.DesignScript.Geometry.Curve curve in crvs)
            {
                using (var nc = curve.ToNurbsCurve())
                {
                    Autodesk.Revit.DB.Curve converted = nc.ToRevitType(false);
                    cl.Append(converted);
                }
            }

            crvs.ForEach(x => x.Dispose());

            return(cl);
        }
Пример #4
0
        public static Autodesk.DesignScript.Geometry.Curve ToProtoType(this Autodesk.Revit.DB.Curve revitCurve,
                                                                       bool performHostUnitConversion = true, Reference referenceOverride = null)
        {
            if (revitCurve == null)
            {
                throw new ArgumentNullException("revitCurve");
            }
            dynamic dyCrv = revitCurve;

            Autodesk.DesignScript.Geometry.Curve converted = RevitToProtoCurve.Convert(dyCrv);
            if (converted == null)
            {
                throw new Exception("An unexpected failure occurred when attempting to convert the curve");
            }
            if (performHostUnitConversion)
            {
                UnitConverter.ConvertToDynamoUnits(ref converted);
            }

            // If possible, add a geometry reference for downstream Element creation
            var revitRef = referenceOverride ?? revitCurve.Reference;

            if (revitRef != null)
            {
                converted.Tags.AddTag(ElementCurveReference.DefaultTag, revitRef);
            }

            return(converted);
        }
Пример #5
0
        public static void DrawCurve(RenderDescription description, object obj)
        {
            Autodesk.Revit.DB.Curve curve = obj as Autodesk.Revit.DB.Curve;

            if (curve == null)
            {
                return;
            }

            IList <XYZ> points = curve.Tessellate();

            for (int i = 0; i < points.Count; ++i)
            {
                XYZ xyz = points[i];

                description.lines.Add(new Point3D(xyz.X, xyz.Y, xyz.Z));

                if (i == 0 || i == (points.Count - 1))
                {
                    continue;
                }

                description.lines.Add(new Point3D(xyz.X, xyz.Y, xyz.Z));
            }
        }
Пример #6
0
        public static Elements.Element RevitWallToHyparWall(Wall revitWall)
        {
            Polygon        outerPolygon = null;
            List <Polygon> voids        = new List <Polygon>();

            var polygons = revitWall.GetProfile();

            if (polygons == null)
            {
                return(null);
            }

            outerPolygon = polygons[0];
            if (polygons.Count > 1)
            {
                voids.AddRange(polygons.Skip(1));
            }

            //build our profile
            Profile prof = new Profile(outerPolygon, voids, Guid.NewGuid(), "revit Wall");
            //get the location curve as an Elements.Line
            Curve curve = (revitWall.Location as LocationCurve).Curve;
            Line  line  = new Line(curve.GetEndPoint(0).ToVector3(true), curve.GetEndPoint(1).ToVector3(true));

            //return a neat Hypar wall
            return(new WallByProfile(prof, revitWall.Width, line));
        }
Пример #7
0
        /// <summary>
        /// Init a new detail curve from curve
        /// </summary>
        /// <param name="view"></param>
        /// <param name="curve"></param>
        private void Init(Autodesk.Revit.DB.View view, Autodesk.Revit.DB.Curve curve)
        {
            // Open Transaction and get document
            Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument;
            TransactionManager.Instance.EnsureInTransaction(document);

            // Get exsiting element
            var element = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.DetailCurve>(document);

            if (element == null)
            {
                if (document.IsFamilyDocument)
                {
                    element = document.FamilyCreate.NewDetailCurve(view, curve);
                }
                else
                {
                    element = document.Create.NewDetailCurve(view, curve);
                }
            }
            else
            {
                element.SetGeometryCurve(curve, true);
            }

            InternalSetCurveElement(element);

            // Set transaction task done & element for trace
            TransactionManager.Instance.TransactionTaskDone();
            ElementBinder.SetElementForTrace(this.InternalElement);
        }
Пример #8
0
        private static FamilyInstanceCreationData GetCreationData(Autodesk.Revit.DB.Curve curve, Autodesk.Revit.DB.XYZ upVector, Autodesk.Revit.DB.Level level, Autodesk.Revit.DB.Structure.StructuralType structuralType, Autodesk.Revit.DB.FamilySymbol symbol)
        {
            //calculate the desired rotation
            //we do this by finding the angle between the z axis
            //and vector between the start of the beam and the target point
            //both projected onto the start plane of the beam.
            var zAxis = new XYZ(0, 0, 1);
            var yAxis = new XYZ(0, 1, 0);

            //flatten the beam line onto the XZ plane
            //using the start's z coordinate
            var start  = curve.GetEndPoint(0);
            var end    = curve.GetEndPoint(1);
            var newEnd = new XYZ(end.X, end.Y, start.Z); //drop end point to plane

            //catch the case where the end is directly above
            //the start, creating a normal with zero length
            //in that case, use the Z axis
            XYZ planeNormal = newEnd.IsAlmostEqualTo(start) ? zAxis : (newEnd - start).Normalize();

            double gamma = upVector.AngleOnPlaneTo(zAxis.IsAlmostEqualTo(planeNormal) ? yAxis : zAxis, planeNormal);

            return(new FamilyInstanceCreationData(curve, symbol, level, structuralType)
            {
                RotateAngle = gamma
            });
        }
Пример #9
0
        /// <summary>
        /// This node will select grids along a model curve element ordered based on the start of the model curve.
        /// This works in the active view. So whatever plan representation your grids have, that is what is used.
        /// </summary>
        /// <param name="modelCurve">Revit model curve to select grids along.</param>
        /// <returns name="orderedGrids">The intersecting grids ordered from beginning to end of the line.</returns>
        public static List <global::Revit.Elements.Grid> IntersectingGridsByModelCurve(global::Revit.Elements.ModelCurve modelCurve)
        {
            ModelCurve mCurve = modelCurve.InternalElement as ModelCurve;

            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;

            List <global::Revit.Elements.Grid> intersectingGrids = new List <global::Revit.Elements.Grid>();

            IList <Autodesk.Revit.DB.Element> grids = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Grids).WhereElementIsNotElementType().ToElements();

            foreach (var grid in grids)
            {
                Grid  g  = grid as Grid;
                Curve c  = g.GetCurvesInView(DatumExtentType.ViewSpecific, doc.ActiveView).First();
                Curve c2 = mCurve.GeometryCurve;

                Point pt1 = Point.ByCoordinates(0, 0, c.GetEndPoint(0).Z);
                Point pt2 = Point.ByCoordinates(0, 0, c2.GetEndPoint(0).Z);
                XYZ   vec = Vector.ByTwoPoints(pt2, pt1).ToRevitType();

                var transformed = c2.CreateTransformed(Transform.CreateTranslation(vec));

                SetComparisonResult test = c.Intersect(transformed);

                if (test == SetComparisonResult.Overlap ||
                    test == SetComparisonResult.Subset ||
                    test == SetComparisonResult.Superset ||
                    test == SetComparisonResult.Equal)
                {
                    intersectingGrids.Add(g.ToDSType(true) as global::Revit.Elements.Grid);
                }
            }

            return(intersectingGrids.OrderBy(g => g.Curve.DistanceTo(modelCurve.Curve.StartPoint)).ToList());
        }
 internal ElementCurveReference(Autodesk.Revit.DB.Curve curve)
 {
     if (curve.Reference == null)
     {
         throw new Exception(Properties.Resources.CurveReferenceFailure);
     }
     this.InternalReference = curve.Reference;
 }
Пример #11
0
        /// <summary>
        /// 点投影到线
        /// </summary>
        /// <param name="po"></param>
        /// <param name="l"></param>
        /// <returns></returns>
        public static Point ProjectTo(this Point po, Line l)
        {
            XYZ     dbpo   = po.ToXyz();
            DBcurve dbline = l.ToRevitType();
            XYZ     newpo  = dbline.Project(dbpo).XYZPoint;

            return(Point.ByCoordinates(newpo.X, newpo.Y, newpo.Z));
        }
Пример #12
0
        /// <summary>
        /// Initialize a Wall element
        /// </summary>
        /// <param name="curve"></param>
        /// <param name="wallType"></param>
        /// <param name="baseLevel"></param>
        /// <param name="height"></param>
        /// <param name="offset"></param>
        /// <param name="flip"></param>
        /// <param name="isStructural"></param>
        private void InitWall(Curve curve, Autodesk.Revit.DB.WallType wallType, Autodesk.Revit.DB.Level baseLevel, double height, double offset, bool flip, bool isStructural)
        {
            // This creates a new wall and deletes the old one
            TransactionManager.Instance.EnsureInTransaction(Document);

            //Phase 1 - Check to see if the object exists and should be rebound
            var wallElem =
                ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.Wall>(Document);

            bool successfullyUsedExistingWall = false;

            //There was a modelcurve, try and set sketch plane
            // if you can't, rebuild
            if (wallElem != null && wallElem.Location is Autodesk.Revit.DB.LocationCurve)
            {
                var wallLocation = wallElem.Location as Autodesk.Revit.DB.LocationCurve;
                if ((wallLocation.Curve is Autodesk.Revit.DB.Line == curve is Autodesk.Revit.DB.Line) ||
                    (wallLocation.Curve is Autodesk.Revit.DB.Arc == curve is Autodesk.Revit.DB.Arc) ||
                    (wallLocation.Curve is Autodesk.Revit.DB.Ellipse == curve is Autodesk.Revit.DB.Ellipse))
                {
                    if (!CurveUtils.CurvesAreSimilar(wallLocation.Curve, curve))
                    {
                        wallLocation.Curve = curve;
                    }

                    Autodesk.Revit.DB.Parameter baseLevelParameter =
                        wallElem.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.WALL_BASE_CONSTRAINT);
                    Autodesk.Revit.DB.Parameter topOffsetParameter =
                        wallElem.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM);
                    Autodesk.Revit.DB.Parameter wallTypeParameter =
                        wallElem.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.ELEM_TYPE_PARAM);
                    if (baseLevelParameter.AsElementId() != baseLevel.Id)
                    {
                        baseLevelParameter.Set(baseLevel.Id);
                    }
                    if (Math.Abs(topOffsetParameter.AsDouble() - height) > 1.0e-10)
                    {
                        topOffsetParameter.Set(height);
                    }
                    if (wallTypeParameter.AsElementId() != wallType.Id)
                    {
                        wallTypeParameter.Set(wallType.Id);
                    }
                    successfullyUsedExistingWall = true;
                }
            }

            var wall = successfullyUsedExistingWall ? wallElem :
                       Autodesk.Revit.DB.Wall.Create(Document, curve, wallType.Id, baseLevel.Id, height, offset, flip, isStructural);

            InternalSetWall(wall);

            TransactionManager.Instance.TransactionTaskDone();

            // delete the element stored in trace and add this new one
            ElementBinder.CleanupAndSetElementForTrace(Document, InternalWall);
        }
Пример #13
0
 /// <summary>
 /// Set the geometry curve used by the ModelCurve
 /// </summary>
 /// <param name="c"></param>
 protected void InternalSetCurve(Autodesk.Revit.DB.Curve c)
 {
     if (!this.InternalCurveElement.GeometryCurve.IsBound && c.IsBound)
     {
         c = c.Clone();
         c.MakeUnbound();
     }
     setCurveMethod(this.InternalCurveElement, c);
 }
Пример #14
0
 internal ElementCurveReference(Autodesk.Revit.DB.Curve curve)
 {
     if (curve.Reference == null)
     {
         throw new Exception("A Curve Reference can only be obtained "
                             + "from an Element.");
     }
     this.InternalReference = curve.Reference;
 }
Пример #15
0
        public JObject ConvertToDTO(Autodesk.Revit.DB.Wall source)
        {
            Autodesk.Revit.DB.Curve curve = (source.Location as LocationCurve).Curve;
            Autodesk.Revit.DB.Line  line  = curve as Autodesk.Revit.DB.Line;

            if (line == null)
            {
                return(null);
            }

            BoundingBoxXYZ bb = source.get_BoundingBox(null);

            Autodesk.Revit.DB.XYZ origin   = line.Tessellate().First();
            Autodesk.Revit.DB.XYZ endpoint = line.Tessellate().Last(); /// origin + line.Direction * line.Length;

            List <LMAStudio.StreamVR.Common.Models.Face> wallFaces = new List <LMAStudio.StreamVR.Common.Models.Face>();

            Autodesk.Revit.DB.GeometryElement defaultGeometry = source.get_Geometry(new Options());
            if (defaultGeometry != null)
            {
                Solid solidGeometry = defaultGeometry.FirstOrDefault() as Solid;

                if (solidGeometry != null)
                {
                    wallFaces = GeometryConversion.ConvertToDTO(source, solidGeometry);
                }
            }

            LMAStudio.StreamVR.Common.Models.Wall dest = new LMAStudio.StreamVR.Common.Models.Wall
            {
                Id          = source.Id.ToString(),
                Name        = source.Name,
                Depth       = source.Width,
                Orientation = new LMAStudio.StreamVR.Common.Models.XYZ
                {
                    X = source.Orientation.X,
                    Y = source.Orientation.Y,
                    Z = source.Orientation.Z,
                },
                Endpoint0 = new LMAStudio.StreamVR.Common.Models.XYZ
                {
                    X = origin.X,
                    Y = origin.Y,
                    Z = bb.Min.Z,
                },
                Endpoint1 = new LMAStudio.StreamVR.Common.Models.XYZ
                {
                    X = endpoint.X,
                    Y = endpoint.Y,
                    Z = bb.Max.Z,
                },
                Faces = wallFaces
            };

            return(JObject.FromObject(dest));
        }
Пример #16
0
        public static re.Element WallByProfile(List <dg.PolyCurve> closedProfiles, re.WallType wallType, re.Level level)
        {
            rdb.Document doc = DocumentManager.Instance.CurrentDBDocument;

            // Try to get a wall from trace
            var wallElem = ElementBinder.GetElementFromTrace <rdb.Wall>(doc);

            dg.PolyCurve closedProfile = closedProfiles[0];
            if (!closedProfile.IsClosed || !closedProfile.IsPlanar)
            {
                DeleteWall(wallElem, true);
                return(null);
            }

            // Verify the wall profile is vertical
            dg.Plane basePlane = closedProfile.BasePlane();
            if (Math.Abs(basePlane.Normal.Z) > 0.0001)
            {
                DeleteWall(wallElem, true);
                return(null);
            }

            // Convert Polycurve segments to a list of Revit curves;
            List <rdb.Curve> rCrvs = new List <rdb.Curve>();

            foreach (dg.PolyCurve pCrv in closedProfiles)
            {
                List <dg.Curve> dCrvs = pCrv.Curves().ToList();
                foreach (dg.Curve dCrv in dCrvs)
                {
                    rdb.Curve rCrv = dCrv.ToRevitType();
                    rCrvs.Add(rCrv);
                }
            }


            TransactionManager.Instance.EnsureInTransaction(doc);
            DeleteWall(wallElem, false);

            // Build a wall
            try
            {
                rdb.Wall w     = rdb.Wall.Create(doc, rCrvs, new rdb.ElementId(wallType.Id), new rdb.ElementId(level.Id), false);
                re.Wall  rWall = re.ElementWrapper.ToDSType(w, true) as re.Wall;
                TransactionManager.Instance.TransactionTaskDone();
                ElementBinder.CleanupAndSetElementForTrace(doc, w);
                return(rWall);
            }
            catch (Exception ex)
            {
                TransactionManager.Instance.TransactionTaskDone();

                ElementBinder.CleanupAndSetElementForTrace(doc, null);
            }
            return(null);
        }
Пример #17
0
        /// <summary>
        /// Initialize a StructuralFraming element
        /// </summary>
        private void InitStructuralFraming(Autodesk.Revit.DB.Curve curve, Autodesk.Revit.DB.XYZ upVector, Autodesk.Revit.DB.Level level, Autodesk.Revit.DB.Structure.StructuralType structuralType, Autodesk.Revit.DB.FamilySymbol symbol)
        {
            //Phase 1 - Check to see if the object exists and should be rebound
            var oldFam =
                ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.FamilyInstance>(Document);

            //There was a point, rebind to that, and adjust its position
            if (oldFam != null)
            {
                InternalSetFamilyInstance(oldFam);
                InternalSetFamilySymbol(symbol);
                InternalSetCurve(curve);
                return;
            }

            //Phase 2- There was no existing point, create one
            TransactionManager.Instance.EnsureInTransaction(Document);

            var creationData = GetCreationData(curve, upVector, level, structuralType, symbol);

            Autodesk.Revit.DB.FamilyInstance fi;
            if (Document.IsFamilyDocument)
            {
                var elementIds = Document.FamilyCreate.NewFamilyInstances2(new List <FamilyInstanceCreationData>()
                {
                    creationData
                });

                if (elementIds.Count == 0)
                {
                    throw new Exception(Properties.Resources.FamilyInstanceCreationFailure);
                }

                fi = (Autodesk.Revit.DB.FamilyInstance)Document.GetElement(elementIds.First());
            }
            else
            {
                var elementIds = Document.Create.NewFamilyInstances2(new List <FamilyInstanceCreationData>()
                {
                    creationData
                });

                if (elementIds.Count == 0)
                {
                    throw new Exception(Properties.Resources.FamilyInstanceCreationFailure);
                }

                fi = (Autodesk.Revit.DB.FamilyInstance)Document.GetElement(elementIds.First());
            }

            InternalSetFamilyInstance(fi);

            TransactionManager.Instance.TransactionTaskDone();

            ElementBinder.SetElementForTrace(this.InternalElement);
        }
Пример #18
0
        private static Autodesk.Revit.DB.SketchPlane GetSketchPlaneFromCurve(Curve c)
        {
            Plane plane = GetPlaneFromCurve(c, false);

            Autodesk.Revit.DB.SketchPlane sp = null;
            sp = Document.IsFamilyDocument ?
                 Document.FamilyCreate.NewSketchPlane(plane) :
                 Document.Create.NewSketchPlane(plane);

            return(sp);
        }
Пример #19
0
        private void InternalSetCurve(Autodesk.Revit.DB.Curve crv)
        {
            TransactionManager.Instance.EnsureInTransaction(Document);

            //update the curve
            var locCurve = InternalFamilyInstance.Location as LocationCurve;

            locCurve.Curve = crv;

            TransactionManager.Instance.TransactionTaskDone();
        }
Пример #20
0
        /// <summary>
        /// An extension method to convert a Revit Curve to a ProtoGeometry Curve.  Note that Bound Revit curves will be returned in trimmed form.
        /// </summary>
        /// <param name="revitCurve"></param>
        /// <returns></returns>
        public static Autodesk.DesignScript.Geometry.Curve ToProtoType(this Autodesk.Revit.DB.Curve revitCurve)
        {
            if (revitCurve == null)
            {
                throw new ArgumentNullException("revitCurve");
            }

            dynamic dyCrv = revitCurve;

            return(RevitToProtoCurve.Convert(dyCrv));
        }
Пример #21
0
        /// <summary>
        /// Creates a new Sketch Plane from a Curve
        /// </summary>
        /// <param name="document">Active Document</param>
        /// <param name="curve">Curve to get plane from</param>
        /// <returns>Plane of the curve</returns>
        public static SketchPlane NewSketchPlaneFromCurve(Document document, Autodesk.Revit.DB.Curve curve)
        {
            XYZ startPoint = curve.GetEndPoint(0);
            XYZ endPoint   = curve.GetEndPoint(1);

            // If Start end Endpoint are the same check further points.
            int i = 2;

            while (startPoint == endPoint && endPoint != null)
            {
                endPoint = curve.GetEndPoint(i);
                i++;
            }



            // Plane to return
            Plane plane;


            // If Z Values are equal the Plane is XY
            if (startPoint.Z == endPoint.Z)
            {
                plane = CreatePlane(document, XYZ.BasisZ, startPoint);
            }
            // If X Values are equal the Plane is YZ
            else if (startPoint.X == endPoint.X)
            {
                plane = CreatePlane(document, XYZ.BasisX, startPoint);
            }
            // If Y Values are equal the Plane is XZ
            else if (startPoint.Y == endPoint.Y)
            {
                plane = CreatePlane(document, XYZ.BasisY, startPoint);
            }
            // Otherwise the Planes Normal Vector is not X,Y or Z.
            // We draw lines from the Origin to each Point and use the Plane this one spans up.
            else
            {
                CurveArray curves = new CurveArray();
                curves.Append(curve);
                curves.Append(Autodesk.Revit.DB.Line.CreateBound(new XYZ(0, 0, 0), startPoint));
                curves.Append(Autodesk.Revit.DB.Line.CreateBound(endPoint, new XYZ(0, 0, 0)));
#if (Revit2015 || Revit2016 || Revit2017)
                plane = document.Application.Create.NewPlane(curves);
#else
                plane = Plane.CreateByThreePoints(startPoint, new XYZ(0, 0, 0), endPoint);
#endif
            }


            // return new Sketchplane
            return(SketchPlane.Create(document, plane));
        }
Пример #22
0
        /// <summary>
        /// Checks whether the curve is vertical or not.
        /// </summary>
        /// <param name="curve"></param>
        /// <returns></returns>
        private bool IsVertical(DB.Curve curve)
        {
            var diffX = Math.Abs(curve.GetEndPoint(0).X - curve.GetEndPoint(1).X);
            var diffY = Math.Abs(curve.GetEndPoint(0).Y - curve.GetEndPoint(1).Y);

            if (diffX < 0.1 && diffY < 0.1)
            {
                return(true);
            }

            return(false);
        }
Пример #23
0
        /// <summary>
        /// Create a new structural member in the specified Revit document
        /// </summary>
        /// <param name="curve">The set-out curve of the member</param>
        /// <param name="symbol">The family symbol of the member to create</param>
        /// <param name="document">The document to add the member to</param>
        /// <param name="distanceUnit">The distance unit the passed-in curve is expressed in</param>
        /// <returns></returns>
        public static FamilyInstance CreateStructuralFraming(FB.Curve curve, FamilySymbol symbol, StructuralType structuralType)
        {
            FamilyInstance instance = CreateFamilyInstance(symbol, structuralType);

            AD.Curve rCrv = ToRevit.Convert(curve);
            if (rCrv != null)
            {
                LocationCurve location = instance.Location as LocationCurve;
                location.Curve = rCrv;
            }
            return(instance);
        }
Пример #24
0
        private List <Rhino.Geometry.Brep> GetWallLayerGeometry(DB.Wall wall)
        {
            // determine wall anchor point to help in sorting layer breps
            DB.Curve wallLocationCurve       = (wall.Location as DB.LocationCurve).Curve;
            DB.XYZ   wallEndPoint            = wallLocationCurve.GetEndPoint(0);
            DB.XYZ   wallOrientation         = wall.Orientation;
            DB.XYZ   anchor                  = wallEndPoint + (wallOrientation * wallLocationCurve.Length);
            Rhino.Geometry.Point3d basePoint = anchor.ToPoint3d();

            return(GetCompoundStructureLayerGeom(wall)
                   .OrderBy(x => Rhino.Geometry.VolumeMassProperties.Compute(x, volume: true, firstMoments: true, secondMoments: false, productMoments: false).Centroid.DistanceTo(basePoint))
                   .ToList());
        }
Пример #25
0
        private void Run()
        {
            List <Autodesk.Revit.DB.Element> doors = DoorSelector.GetDoors(doc, LevelSelector.levelId(doc, level), doorType);

            DoorRenumber renumerator = new DoorRenumber(uidoc, doors, prefix, suffix);

            ISelectionFilter filter = new DoorRenumber.LineSelectionFilter();

            Autodesk.Revit.DB.Reference reference = uidoc.Selection.PickObject(ObjectType.Element, filter, "Select direction curve");

            Autodesk.Revit.DB.Curve curve = (doc.GetElement(reference.ElementId) as Autodesk.Revit.DB.ModelCurve).GeometryCurve;

            renumerator.DoorRenumbering(curve);
        }
Пример #26
0
        public Autodesk.Revit.UI.Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            try
            {
                // get the active document and view
                UIDocument             revitDoc = commandData.Application.ActiveUIDocument;
                Autodesk.Revit.DB.View view     = revitDoc.ActiveView;
                Document  dbDoc             = revitDoc.Document;
                ElementId currentTextTypeId = dbDoc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);

                foreach (ElementId elemId in revitDoc.Selection.GetElementIds())
                {
                    Element elem = dbDoc.GetElement(elemId);
                    if (elem.GetType() == typeof(Autodesk.Revit.DB.Structure.Rebar))
                    {
                        // cast to Rebar and get its first curve
                        Autodesk.Revit.DB.Structure.Rebar rebar = (Autodesk.Revit.DB.Structure.Rebar)elem;
                        Autodesk.Revit.DB.Curve           curve = rebar.GetCenterlineCurves(false, false, false)[0];

                        // calculate necessary arguments
                        Autodesk.Revit.DB.XYZ origin = new XYZ(
                            curve.GetEndPoint(0).X + curve.Length,
                            curve.GetEndPoint(0).Y,
                            curve.GetEndPoint(0).Z);
                        string strText = "This is " + rebar.Category.Name + " : " + rebar.Name;

                        // create the text
                        using (Transaction t = new Transaction(dbDoc))
                        {
                            t.Start("New text note");
                            TextNote.Create(dbDoc, view.Id, origin, strText, currentTextTypeId);
                            t.Commit();
                        }
                        return(Autodesk.Revit.UI.Result.Succeeded);
                    }
                }
                message = "No rebar selected!";
                return(Autodesk.Revit.UI.Result.Failed);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Пример #27
0
        public static Autodesk.Revit.DB.Curve ToRevitType(this Autodesk.DesignScript.Geometry.Curve crv,
                                                          bool performHostUnitConversion = true)
        {
            crv = performHostUnitConversion ? crv.InHostUnits() : crv;

            dynamic dyCrv = crv;

            Autodesk.Revit.DB.Curve converted = ProtoToRevitCurve.Convert(dyCrv);

            if (converted == null)
            {
                throw new Exception("An unexpected failure occurred when attempting to convert the curve");
            }

            return(converted);
        }
        private static void CreateRevitElementInRevit(Autodesk.Revit.DB.Curve geomLine)
        {
            // var OriginShit = geomLine.ComputeDerivatives(0, true);
            //var normal = OriginShit.BasisZ;
            // var origin = OriginShit.Origin;
            // XYZ origin = new XYZ(0, 0, 0);
            // XYZ normal = new XYZ(0, 1, 0);
            var Origin = geomLine.GetEndPoint(0);

            Plane geomPlane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, Origin);
            // Create a sketch plane in current document
            SketchPlane sketch = SketchPlane.Create(Command.uidoc.Document, geomPlane);

            // Create a ModelLine element using the created geometry line and sketch plane
            var line = Command.uidoc.Document.Create.NewModelCurve(geomLine, sketch);
        }
Пример #29
0
        public Autodesk.Revit.UI.Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            try
            {
                // get the active document and view
                UIDocument             revitDoc = commandData.Application.ActiveUIDocument;
                Autodesk.Revit.DB.View view     = revitDoc.Document.ActiveView;
                foreach (Element elem in revitDoc.Selection.Elements)
                {
                    if (elem.GetType() == typeof(Autodesk.Revit.DB.Structure.Rebar))
                    {
                        // cast to Rebar and get its first curve
                        Autodesk.Revit.DB.Structure.Rebar rebar = (Autodesk.Revit.DB.Structure.Rebar)elem;
                        Autodesk.Revit.DB.Curve           curve = rebar.GetCenterlineCurves(false, false, false)[0];

                        // calculate necessary arguments
                        Autodesk.Revit.DB.XYZ origin = new XYZ(
                            curve.GetEndPoint(0).X + curve.Length,
                            curve.GetEndPoint(0).Y,
                            curve.GetEndPoint(0).Z);// draw the text at the right size
                        Autodesk.Revit.DB.XYZ baseVec = new Autodesk.Revit.DB.XYZ(1, 0, 0);
                        Autodesk.Revit.DB.XYZ upVec   = new Autodesk.Revit.DB.XYZ(0, 0, 1);
                        double lineWidth = curve.Length / 50;
                        string strText   = "This is " + rebar.Category.Name + " : " + rebar.Name;

                        // create the text
                        Transaction t = new Transaction(revitDoc.Document);
                        t.Start("Create new textnote");
                        Autodesk.Revit.DB.TextNote text = revitDoc.Document.Create.NewTextNote(view, origin, baseVec, upVec, lineWidth,
                                                                                               Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_LEFT, strText);
                        text.Width = curve.Length; // set the text width
                        t.Commit();
                        return(Autodesk.Revit.UI.Result.Succeeded);
                    }
                }
                message = "No rebar selected!";
                return(Autodesk.Revit.UI.Result.Failed);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Пример #30
0
        /// <summary>
        /// Credits: Grevit
        /// Creates a new Sketch Plane from a Curve
        /// https://github.com/grevit-dev/Grevit/blob/3c7a5cc198e00dfa4cc1e892edba7c7afd1a3f84/Grevit.Revit/Utilities.cs#L402
        /// </summary>
        /// <param name="curve">Curve to get plane from</param>
        /// <returns>Plane of the curve</returns>
        private SketchPlane NewSketchPlaneFromCurve(DB.Curve curve, Document doc)
        {
            XYZ startPoint = curve.GetEndPoint(0);
            XYZ endPoint   = curve.GetEndPoint(1);

            // If Start end Endpoint are the same check further points.
            int i = 2;

            while (startPoint == endPoint && endPoint != null)
            {
                endPoint = curve.GetEndPoint(i);
                i++;
            }

            // Plane to return
            DB.Plane plane;

            // If Z Values are equal the Plane is XY
            if (startPoint.Z == endPoint.Z)
            {
                plane = CreatePlane(XYZ.BasisZ, startPoint);
            }
            // If X Values are equal the Plane is YZ
            else if (startPoint.X == endPoint.X)
            {
                plane = CreatePlane(XYZ.BasisX, startPoint);
            }
            // If Y Values are equal the Plane is XZ
            else if (startPoint.Y == endPoint.Y)
            {
                plane = CreatePlane(XYZ.BasisY, startPoint);
            }
            // Otherwise the Planes Normal Vector is not X,Y or Z.
            // We draw lines from the Origin to each Point and use the Plane this one spans up.
            else
            {
                CurveArray curves = new CurveArray();
                curves.Append(curve);
                curves.Append(DB.Line.CreateBound(new XYZ(0, 0, 0), startPoint));
                curves.Append(DB.Line.CreateBound(endPoint, new XYZ(0, 0, 0)));

                plane = DB.Plane.CreateByThreePoints(startPoint, new XYZ(0, 0, 0), endPoint);
            }

            return(SketchPlane.Create(doc, plane));
        }
Пример #31
0
        private static Curve Flatten3dCurveOnPlane(Curve c, Plane plane)
        {
            if (c is Autodesk.Revit.DB.HermiteSpline)
            {
                var hs = c as Autodesk.Revit.DB.HermiteSpline;
                plane = CurveUtils.GetPlaneFromCurve(c, false);
                var projPoints = new List<XYZ>();
                foreach (var pt in hs.ControlPoints)
                {
                    var proj = pt - (pt - plane.Origin).DotProduct(plane.Normal) * plane.Normal;
                    projPoints.Add(proj);
                }

                return Autodesk.Revit.DB.HermiteSpline.Create(projPoints, false);
            }

            if (c is Autodesk.Revit.DB.NurbSpline)
            {
                var ns = c as Autodesk.Revit.DB.NurbSpline;
                if (plane == null)
                {
                    var bestFitPlane = Autodesk.DesignScript.Geometry.Plane.ByBestFitThroughPoints(
                        ns.CtrlPoints.ToList().ToPoints(false));

                    plane = bestFitPlane.ToPlane(false);
                }

                var projPoints = new List<XYZ>();
                foreach (var pt in ns.CtrlPoints)
                {
                    var proj = pt - (pt - plane.Origin).DotProduct(plane.Normal) * plane.Normal;
                    projPoints.Add(proj);
                }

                return Autodesk.Revit.DB.NurbSpline.Create(projPoints, ns.Weights.Cast<double>().ToList(), ns.Knots.Cast<double>().ToList(), ns.Degree, ns.isClosed, ns.isRational);
            }

            return c;
        }
Пример #32
0
        private static Plane GetPlaneFromCurve(Curve c, bool planarOnly)
        {
            //cases to handle
            //straight line - normal will be inconclusive

            //find the plane of the curve and generate a sketch plane
            double period = c.IsBound ? 0.0 : (c.IsCyclic ? c.Period : 1.0);

            var p0 = c.IsBound ? c.Evaluate(0.0, true) : c.Evaluate(0.0, false);
            var p1 = c.IsBound ? c.Evaluate(0.5, true) : c.Evaluate(0.25 * period, false);
            var p2 = c.IsBound ? c.Evaluate(1.0, true) : c.Evaluate(0.5 * period, false);

            if (c is Line)
            {
                var v1 = p1 - p0;
                var v2 = p2 - p0;
                XYZ norm = null;

                //keep old plane computations
                if (System.Math.Abs(p0.Z - p2.Z) < 0.0001)
                {
                    norm = XYZ.BasisZ;
                }
                else
                {
                    var p3 = new XYZ(p2.X, p2.Y, p0.Z);
                    var v3 = p3 - p0;
                    norm = v1.CrossProduct(v3);
                    if (norm.IsZeroLength())
                    {
                        norm = v2.CrossProduct(XYZ.BasisY);
                    }
                    norm = norm.Normalize();
                }

                return new Plane(norm, p0);

            }

            Autodesk.Revit.DB.CurveLoop cLoop = new Autodesk.Revit.DB.CurveLoop();
            cLoop.Append(c.Clone());
            if (cLoop.HasPlane())
            {
                return cLoop.GetPlane();
            }
            if (planarOnly)
                return null;

            IList<XYZ> points = c.Tessellate();
            List<XYZ> xyzs = new List<XYZ>();
            for (int iPoint = 0; iPoint < points.Count; iPoint++)
                xyzs.Add(points[iPoint]);

            var bestFitPlane =
                Autodesk.DesignScript.Geometry.Plane.ByBestFitThroughPoints(xyzs.ToPoints(false));

            return bestFitPlane.ToPlane(false);
        }
Пример #33
0
 private static Autodesk.Revit.DB.SketchPlane GetSketchPlaneFromCurve(Curve c)
 {
     Plane plane = CurveUtils.GetPlaneFromCurve(c, false);
     return Autodesk.Revit.DB.SketchPlane.Create(Document, plane);
 }
Пример #34
0
        private static ElementId resetSketchPlaneMethod(Autodesk.Revit.DB.CurveElement mc, Curve c, Autodesk.Revit.DB.Plane flattenedOnPlane, out bool needsSketchPlaneReset)
        {
            //do we need to reset?
            needsSketchPlaneReset = false;
            Autodesk.Revit.DB.Plane newPlane = flattenedOnPlane != null ? flattenedOnPlane : GetPlaneFromCurve(c, false);

            Autodesk.Revit.DB.Plane curPlane = mc.SketchPlane.Plane;

            bool resetPlane = false;

            {
                double llSqCur = curPlane.Normal.DotProduct(curPlane.Normal);
                double llSqNew = newPlane.Normal.DotProduct(newPlane.Normal);
                double dotP = newPlane.Normal.DotProduct(curPlane.Normal);
                double dotSqNormalized = (dotP / llSqCur) * (dotP / llSqNew);
                double angleTol = System.Math.PI / 1800.0;
                if (dotSqNormalized < 1.0 - angleTol * angleTol)
                    resetPlane = true;
            }
            Autodesk.Revit.DB.SketchPlane sp = null;

            if (!resetPlane)
            {
                double originDiff = curPlane.Normal.DotProduct(curPlane.Origin - newPlane.Origin);
                double tolerance = 0.000001;
                if (originDiff > tolerance || originDiff < -tolerance)
                {
                    sp = GetSketchPlaneFromCurve(c);
                    mc.SketchPlane = GetSketchPlaneFromCurve(c);
                }
                return (sp == null || mc.SketchPlane.Id == sp.Id) ? ElementId.InvalidElementId : sp.Id;
            }

            //do reset if method is available

            bool foundMethod = false;

            if (hasMethodResetSketchPlane)
            {
                Type CurveElementType = typeof(Autodesk.Revit.DB.CurveElement);
                MethodInfo[] curveElementMethods = CurveElementType.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                System.String nameOfMethodSetCurve = "ResetSketchPlaneAndCurve";
                System.String nameOfMethodSetCurveAlt = "SetSketchPlaneAndCurve";

                foreach (MethodInfo m in curveElementMethods)
                {
                    if (m.Name == nameOfMethodSetCurve || m.Name == nameOfMethodSetCurveAlt)
                    {
                        object[] argsM = new object[2];
                        sp = GetSketchPlaneFromCurve(c);
                        argsM[0] = sp;
                        argsM[1] = null;

                        foundMethod = true;
                        m.Invoke(mc, argsM);
                        break;
                    }
                }
            }
            if (!foundMethod)
            {
                //sp = dynRevitUtils.GetSketchPlaneFromCurve(c);
                hasMethodResetSketchPlane = false;
                needsSketchPlaneReset = true;
                //expect exception, so try to keep old plane?
                //mc.SketchPlane = sp;
                return ElementId.InvalidElementId;
            }

            if (sp != null && mc.SketchPlane.Id != sp.Id)
                return sp.Id;

            return ElementId.InvalidElementId;
        }
Пример #35
0
        private static Plane GetPlaneFromCurve(Curve c, bool planarOnly)
        {
            //cases to handle
            //straight line - normal will be inconclusive

            //find the plane of the curve and generate a sketch plane
            double period = c.IsBound ? 0.0 : (c.IsCyclic ? c.Period : 1.0);

            var p0 = c.IsBound ? c.Evaluate(0.0, true) : c.Evaluate(0.0, false);
            var p1 = c.IsBound ? c.Evaluate(0.5, true) : c.Evaluate(0.25 * period, false);
            var p2 = c.IsBound ? c.Evaluate(1.0, true) : c.Evaluate(0.5 * period, false);

            if (c is Line)
            {
                var v1 = p1 - p0;
                var v2 = p2 - p0;
                XYZ norm = null;

                //keep old plane computations
                if (System.Math.Abs(p0.Z - p2.Z) < 0.0001)
                {
                    norm = XYZ.BasisZ;
                }
                else
                {
                    var p3 = new XYZ(p2.X, p2.Y, p0.Z);
                    var v3 = p3 - p0;
                    norm = v1.CrossProduct(v3);
                    if (norm.IsZeroLength())
                    {
                        norm = v2.CrossProduct(XYZ.BasisY);
                    }
                    norm = norm.Normalize();
                }

                return new Plane(norm, p0);

            }

            Autodesk.Revit.DB.CurveLoop cLoop = new Autodesk.Revit.DB.CurveLoop();
            cLoop.Append(c.Clone());
            if (cLoop.HasPlane())
            {
                return cLoop.GetPlane();
            }
            if (planarOnly)
                return null;

            IList<XYZ> points = c.Tessellate();
            List<XYZ> xyzs = new List<XYZ>();
            for (int iPoint = 0; iPoint < points.Count; iPoint++)
                xyzs.Add(points[iPoint]);

            XYZ meanPt;
            List<XYZ> orderedEigenvectors;
            PrincipalComponentsAnalysis(xyzs, out meanPt, out orderedEigenvectors);
            var normal = orderedEigenvectors[0].CrossProduct(orderedEigenvectors[1]);
            var plane = Document.Application.Create.NewPlane(normal, meanPt);
            return plane;
        }
Пример #36
0
        private static Autodesk.Revit.DB.SketchPlane GetSketchPlaneFromCurve(Curve c)
        {
            Plane plane = GetPlaneFromCurve(c, false);
            Autodesk.Revit.DB.SketchPlane sp = null;
            sp = Document.IsFamilyDocument ?
                Document.FamilyCreate.NewSketchPlane(plane) :
                Document.Create.NewSketchPlane(plane);

            return sp;
        }
Пример #37
0
        private static Curve Flatten3dCurveOnPlane(Curve c, Plane plane)
        {
            XYZ meanPt = null;
            List<XYZ> orderedEigenvectors;
            XYZ normal;

            if (c is Autodesk.Revit.DB.HermiteSpline)
            {
                var hs = c as Autodesk.Revit.DB.HermiteSpline;
                plane = GetPlaneFromCurve(c, false);
                var projPoints = new List<XYZ>();
                foreach (var pt in hs.ControlPoints)
                {
                    var proj = pt - (pt - plane.Origin).DotProduct(plane.Normal) * plane.Normal;
                    projPoints.Add(proj);
                }

                return Autodesk.Revit.DB.HermiteSpline.Create(projPoints, false);
            }

            if (c is Autodesk.Revit.DB.NurbSpline)
            {
                var ns = c as Autodesk.Revit.DB.NurbSpline;
                if (plane == null)
                {
                   PrincipalComponentsAnalysis(ns.CtrlPoints.ToList(), out meanPt, out orderedEigenvectors);
                   normal = orderedEigenvectors[0].CrossProduct(orderedEigenvectors[1]).Normalize();

                   plane = Document.Application.Create.NewPlane(normal, meanPt);
                }

                var projPoints = new List<XYZ>();
                foreach (var pt in ns.CtrlPoints)
                {
                    var proj = pt - (pt - plane.Origin).DotProduct(plane.Normal) * plane.Normal;
                    projPoints.Add(proj);
                }

                return Autodesk.Revit.DB.NurbSpline.Create(projPoints, ns.Weights.Cast<double>().ToList(), ns.Knots.Cast<double>().ToList(), ns.Degree, ns.isClosed, ns.isRational);
            }

            return c;
        }