Example #1
0
        public static IEnumerable <XYZ> OffsetPoints(List <XYZ> pts, double offset, XYZ normal)
        {
            CurveLoop curveLoop  = CreateCurveLoop(pts);
            CurveLoop curveLoop2 = CurveLoop.CreateViaOffset(curveLoop, offset, normal);

            return(curveLoop2.Select <Curve, XYZ>(c => c.GetEndPoint(0)));
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // get UIdocument
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            //get document
            Document doc = uidoc.Document;

            //get level
            Level level = new FilteredElementCollector(doc)
                          .OfCategory(BuiltInCategory.OST_Levels)
                          .WhereElementIsNotElementType()
                          .Cast <Level>()
                          .First(x => x.Name == "Ground Floor");

            // create points
            XYZ p1 = new XYZ(-10, -10, 0);
            XYZ p2 = new XYZ(10, -10, 0);
            XYZ p3 = new XYZ(15, 0, 0);
            XYZ p4 = new XYZ(10, 10, 0);
            XYZ p5 = new XYZ(-10, 10, 0);

            // create curves
            List <Curve> curves = new List <Curve>();
            Line         l1     = Line.CreateBound(p1, p2);
            Arc          l2     = Arc.Create(p2, p4, p3);
            Line         l3     = Line.CreateBound(p4, p5);
            Line         l4     = Line.CreateBound(p5, p1);

            curves.Add(l1);
            curves.Add(l2);
            curves.Add(l3);
            curves.Add(l4);

            //create curve loop
            CurveLoop  crvLoop   = CurveLoop.Create(curves);
            double     offset    = UnitUtils.ConvertToInternalUnits(135, DisplayUnitType.DUT_MILLIMETERS);
            CurveLoop  offsetcrv = CurveLoop.CreateViaOffset(crvLoop, offset, new XYZ(0, 0, 1));
            CurveArray cArray    = new CurveArray();

            foreach (Curve c in offsetcrv)
            {
                cArray.Append(c);
            }
            try
            {
                using (Transaction trans = new Transaction(doc, "Place Family"))
                {
                    trans.Start();
                    doc.Create.NewFloor(cArray, false);
                    trans.Commit();
                }

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
        /// <summary>
        /// 调整viewPlan的尺寸并贴合选中房间
        /// change a viewPlan to fix the selected room
        /// </summary>
        /// <param name="view"></param>
        /// <param name="tran"></param>
        /// <param name="viewOffseet"></param>
        public void ChangeViewFitRoom(ViewPlan view, Transaction tran, double viewOffseet)
        {
            if (view == null)
            {
                TaskDialog.Show("viewIsNull", "Can't find the type of View.");
                return;
            }

            //获得并设定房间的边界设定,并获取其边界集
            DocSet.uidoc.ActiveView = view;
            SpatialElementBoundaryOptions opt = new SpatialElementBoundaryOptions();

            opt.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Center;//房间边界设定,能变更获取的边界位置
            IList <IList <BoundarySegment> > segments = DocSet.selRoom.GetBoundarySegments(opt);

            if (segments == null)
            {
                TaskDialog.Show("segementsIsNull", "can't get the BoundarySegment of room");
                return;
            }


            ViewCropRegionShapeManager vcrShanpMgr = view.GetCropRegionShapeManager();

            CurveLoop loop = new CurveLoop();

            foreach (IList <BoundarySegment> segmentList in segments)
            {
                foreach (BoundarySegment segment in segmentList)
                {
                    Curve curve = segment.GetCurve();
                    loop.Append(curve);
                }


                bool cropValid = vcrShanpMgr.IsCropRegionShapeValid(loop);
                if (cropValid)
                {
                    //默认矩形
                    //TaskDialog.Show("cropValid", "the crop is shape Valid");
                    tran.Start("change the view crop region");
                    vcrShanpMgr.SetCropShape(loop);
                    tran.Commit();
                    tran.Start("Remove Crop Region Shape");
                    vcrShanpMgr.RemoveCropRegionShape();
                    tran.Commit();
                    //TaskDialog.Show("ChangeView", "ChangeViewdone");
                    break;
                }
            }

            tran.Start("loop offset");
            //TaskDialog.Show("!!!", "changeloop!");
            loop = CurveLoop.CreateViaOffset(vcrShanpMgr.GetCropShape().First(), -1 * viewOffseet / 300, new XYZ(0, 0, 1));
            vcrShanpMgr.SetCropShape(loop);
            tran.Commit();

            DocSet.uidoc.ActiveView = view;
        }
Example #4
0
        /// <summary>
        ///  1 过滤器筛选元素 2 通过区域锁定元素 3 使用clipper进行裁剪
        /// </summary>
        public void RegionCalcution(Document doc, CurveArray controlRegionBaseWall)
        {
            #region 获取目标region内的元素
            ElementCategoryFilter detailGroupFilter = new ElementCategoryFilter(BuiltInCategory.OST_IOSDetailGroups);
            //ElementCategoryFilter modelGroupFilter = new ElementCategoryFilter(BuiltInCategory.OST_IOSModelGroups);
            ElementCategoryFilter detailComponentsFilter = new ElementCategoryFilter(BuiltInCategory.OST_DetailComponents);
            ElementCategoryFilter linesFilter            = new ElementCategoryFilter(BuiltInCategory.OST_Lines);
            ElementCategoryFilter genericModel           = new ElementCategoryFilter(BuiltInCategory.OST_GenericModel);
            LogicalOrFilter       logicalOrFilter        = new LogicalOrFilter(new List <ElementFilter>()
            {
                detailGroupFilter, detailComponentsFilter, linesFilter, genericModel
            });

            List <Element> allTarEles = (new FilteredElementCollector(doc, doc.ActiveView.Id)).WherePasses(logicalOrFilter).WhereElementIsNotElementType().ToElements().ToList();
            List <Element> selEles    = _Methods.GetTarlElesByRegion(doc, controlRegionBaseWall, allTarEles);
            #endregion

            #region 筛选 地库_地库外墙线圈中的目标元素 障碍物 主次道路中线 处理地库_地库外墙线退距 默认800mm

            #region 基于各属性进行目标元素抓取
            CurveArray roadCurves     = new CurveArray();
            CurveArray mainRoadCurves = RegionConditionGrab(doc, selEles, out roadCurves);

            #endregion

            CurveLoop baseWallLoop = new CurveLoop();
            bool      isLoop       = _Methods.IsCurveLoop(controlRegionBaseWall, out baseWallLoop);

            CurveArrArray baseWallCurveArrArray = new CurveArrArray();
            XYZ           normal             = new XYZ(0, 0, 1);
            double        offsetDistance     = 0;
            bool          isCounterclockwise = baseWallLoop.IsCounterclockwise(normal);//curveloop内外偏移的依据
            if (isCounterclockwise)
            {
                offsetDistance = -CMD.basementWall_offset_distance;
            }
            else if (!isCounterclockwise)
            {
                offsetDistance = CMD.basementWall_offset_distance;
            }

            CurveLoop  curveLoop      = CurveLoop.CreateViaOffset(baseWallLoop, offsetDistance, normal);
            CurveArray _controlRegion = _Methods.CurveLoopToCurveArray(curveLoop);
            baseWallCurveArrArray.Append(_controlRegion);
            #endregion

            #region clipper最后图形处理 得到各个可停车区域region
            Paths basementWallPath = clipper_methods.Paths_xyzToPaths(_Methods.GetUniqueXYZFromCurves(baseWallCurveArrArray));
            Paths roadRegion       = HandleMainRoadSpace(mainRoadCurves, roadCurves, CMD.Wd_main, CMD.Wd);
            Paths canPlacedRegion  = clipper_methods.RegionCropctDifference(basementWallPath, roadRegion);//得到可停车区域
            this.parkingRegionsPoints = clipper_methods.PathsToPaths_xyz(canPlacedRegion);

            List <List <Line> > listLines = _Methods.GetListClosedtLineFromListPoints(this.parkingRegionsPoints);
            this.parkingCurveArrArray = _Methods.ListLinesToCurveArrArray(listLines);
            #endregion
        }
Example #5
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;

            //Get document file Link
            //var link = new FilteredElementCollector(doc).OfType<RevitLinkInstance>().FirstOrDefault(l => l.Name == "test.rvt");
            //var linkdoc = link.GetLinkDocument();

            var foundations = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFoundation)
                              .WhereElementIsNotElementType()
                              .ToElements();

            foreach (var foundation in foundations)
            {
                //var otp = new Options();
                //otp.DetailLevel = ViewDetailLevel.Fine;
                //var geoElement = foundation.get_Geometry(otp);
                //var instance = geoElement.Cast<GeometryObject>().OfType<GeometryInstance>().Select(i => i.GetInstanceGeometry()).ToList();
                //var solids = geoElement.Cast<GeometryObject>().Concat(instance).OfType<Solid>().Where(s => s.Volume > 0 && s.Faces.Size > 0).ToList();

                var solids     = GetTargetSolids(foundation);
                var solid      = solids.OrderByDescending(s => s.Volume).FirstOrDefault();
                var botFace    = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1);
                var topFace    = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == 1);
                var offsetFace = CurveLoop.CreateViaOffset(topFace.GetEdgesAsCurveLoops().FirstOrDefault(), 5, topFace.FaceNormal);

                var fdoc = commandData.Application.Application.NewFamilyDocument(@"C:\ProgramData\Autodesk\RVT 2020\Family Templates\English\Metric Generic Model.rft");
                using (Transaction tran = new Transaction(fdoc, "new Blend"))
                {
                    tran.Start();
                    var plan        = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, botFace.Origin);
                    var sketchPlane = SketchPlane.Create(fdoc, plan);
                    var top         = ConvertLoopToArray(offsetFace);
                    var baseface    = ConvertLoopToArray(botFace.GetEdgesAsCurveLoops().FirstOrDefault());
                    var blend       = fdoc.FamilyCreate.NewBlend(true, top, baseface, sketchPlane);
                    blend.LookupParameter("Second End").Set(Math.Abs(blend.LookupParameter("Second End").AsDouble()));
                    //CreateBlend(fdoc, null);
                    tran.Commit();
                }
                fdoc.SaveAs($"{Path.GetTempPath()}{foundation.Id.ToString()}-{Guid.NewGuid().ToString()}.rfa");
                Family family = fdoc.LoadFamily(doc);
                fdoc.Close();
                using (Transaction tran = new Transaction(doc, "new void"))
                {
                    tran.Start();
                    //offsetFace.ToList().ForEach(f => doc.Create.NewModelCurve(f, SketchPlane.Create(doc, Plane.CreateByThreePoints(f.GetEndPoint(0), f.GetEndPoint(1), new XYZ(0, 0, 1)))));
                    //botFace.GetEdgesAsCurveLoops().FirstOrDefault().ToList().ForEach(f => doc.Create.NewModelCurve(f, SketchPlane.Create(doc, Plane.CreateByThreePoints(f.GetEndPoint(0), f.GetEndPoint(1), new XYZ(0, 0, 1)))));
                    var symbol = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
                    symbol.Activate();
                    doc.Create.NewFamilyInstance(XYZ.Zero, symbol, Autodesk.Revit.DB.Structure.StructuralType.Footing);
                    tran.Commit();
                }
            }
            return(Result.Succeeded);
        }
Example #6
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            XYZ p1 = new XYZ(-10, 10, 0);
            XYZ p2 = new XYZ(10, 10, 0);
            XYZ p3 = new XYZ(15, 0, 0);
            XYZ p4 = new XYZ(10, -10, 0);
            XYZ p5 = new XYZ(-10, -10, 0);

            List <Curve> curves = new List <Curve>()
            {
                Line.CreateBound(p1, p2),
                Arc.Create(p2, p4, p3),
                Line.CreateBound(p4, p5),
                Line.CreateBound(p5, p1)
            };

            Level level = new FilteredElementCollector(doc)
                          .OfCategory(BuiltInCategory.OST_Levels)
                          .WhereElementIsNotElementType()
                          .Cast <Level>()
                          .First(x => x.Name == "Level 1");
            CurveLoop  curveLoops = CurveLoop.Create(curves);
            double     offset     = UnitUtils.ConvertToInternalUnits(-10, DisplayUnitType.DUT_CENTIMETERS);
            CurveLoop  offsetsrv  = CurveLoop.CreateViaOffset(curveLoops, offset, new XYZ(0, 0, 1));
            CurveArray curveArray = new CurveArray();

            foreach (var c in offsetsrv)
            {
                curveArray.Append(c);
            }
            using (Transaction trans = new Transaction(doc, "Create Wall"))
            {
                trans.Start();
                foreach (Curve curve in curves)
                {
                    Wall.Create(doc, curve, level.Id, true);
                }

                doc.Create.NewFloor(curveArray, true);
                trans.Commit();
            }
            return(Result.Succeeded);
        }
Example #7
0
        protected override void Process(IFCAnyHandle ifcCurve)
        {
            base.Process(ifcCurve);

            IFCAnyHandle basisCurve = IFCImportHandleUtil.GetRequiredInstanceAttribute(ifcCurve, "BasisCurve", false);

            if (basisCurve == null)
            {
                return;
            }

            IFCAnyHandle dir = IFCImportHandleUtil.GetRequiredInstanceAttribute(ifcCurve, "RefDirection", false);

            bool   found    = false;
            double distance = IFCImportHandleUtil.GetRequiredScaledLengthAttribute(ifcCurve, "Distance", out found);

            if (!found)
            {
                distance = 0.0;
            }

            IFCCurve ifcBasisCurve = IFCCurve.ProcessIFCCurve(basisCurve);
            XYZ      dirXYZ        = (dir == null) ? ifcBasisCurve.GetNormal() : IFCPoint.ProcessNormalizedIFCDirection(dir);

            try
            {
                if (ifcBasisCurve.Curve != null)
                {
                    SetCurve(ifcBasisCurve.Curve.CreateOffset(distance, XYZ.BasisZ));
                }
                else
                {
                    CurveLoop baseCurveLoop = ifcBasisCurve.GetTheCurveLoop();
                    if (baseCurveLoop != null)
                    {
                        SetCurveLoop(CurveLoop.CreateViaOffset(baseCurveLoop, distance, XYZ.BasisZ));
                    }
                }
            }
            catch
            {
                Importer.TheLog.LogError(ifcCurve.StepId, "Couldn't create offset curve.", false);
            }
        }
Example #8
0
        public List <XYZ> CreateObjectPlacementPointList()
        {
            // Get room finish boundary curve loop
            CurveLoop roomFinishBoundary = GetRoomFinishBoundarySolid();

            // Create a new boundary curve loop with setting offset distance from wall to inner area
            CurveLoop internalOffsetRoomFinishBoundary = CurveLoop.CreateViaOffset(roomFinishBoundary, -m_minimumDistanceFromObjectToWall, XYZ.BasisZ);

            // Create a solid from roomFinishBoundary and internalOffsetRoomFinishBoundary
            IList <CurveLoop> internalRoomBoundaryCurveLoopList = new List <CurveLoop>();

            internalRoomBoundaryCurveLoopList.Add(internalOffsetRoomFinishBoundary);

            Solid internalRoomBoundarySolid = GeometryCreationUtilities.CreateExtrusionGeometry(internalRoomBoundaryCurveLoopList, XYZ.BasisZ, 1.0);

            // Get a bottom face of the solid
            Face internalRoomBoundaryFace = GetBottomPlanarFaceFromSolid(internalRoomBoundarySolid);

            // Get outlines of door boundingbox
            List <Outline> doorsOutlineList = GetDoorsOutlineList();

            // Get outlines of columns
            List <Outline> coulumnsOutlineList = GetColumnsOutlineList();

            // get outlines of walls
            List <Outline> wallsOutlineList = GetWallsOutlineList();

            // Create UV points on a room boundary face
            List <UV> uvPoints = CreateUVPointsOnRoomBoundaryFace(internalRoomBoundaryFace);

            // Get XYZ points on a room boundary face
            List <XYZ> pointsInsideRoom = new List <XYZ>();

            foreach (UV uvPoint in uvPoints)
            {
                pointsInsideRoom.Add(internalRoomBoundaryFace.Evaluate(uvPoint));
            }

            // Remove points where family instance intersects with doors and columns
            List <XYZ> objectPlacementPointList = RemoveObjectIntersectionPoints(pointsInsideRoom, doorsOutlineList, coulumnsOutlineList, wallsOutlineList);

            return(objectPlacementPointList);
        }
Example #9
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            XYZ p1 = new XYZ(0, 0, 0) / 304.8;
            XYZ p2 = new XYZ(1000, 0, 0) / 304.8;
            XYZ p3 = new XYZ(1000, 1000, 0) / 304.8;

            IList <CurveLoop> ppp = new List <CurveLoop>();

            CurveLoop lp    = new CurveLoop();
            Line      line  = Line.CreateBound(p1, p2);
            Line      line1 = Line.CreateBound(p2, p3);
            Line      line2 = Line.CreateBound(p3, p1);

            lp.Append(line);
            lp.Append(line1);
            lp.Append(line2);

            CurveLoop pp = CurveLoop.CreateViaOffset(lp, 500 / 304.8, XYZ.BasisZ);

            ppp.Add(lp);
            ppp.Add(pp);

            CeilingType ct = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Ceilings)
                             .OfClass(typeof(CeilingType)).FirstElement() as CeilingType;

            using (Transaction trans = new Transaction(doc, "fe"))
            {
                trans.Start("fo");
                Ceiling createcl = Ceiling.Create(doc, ppp, ct.Id, doc.ActiveView.GenLevel.Id);
                trans.Commit();
            }


            return(Result.Succeeded);
        }
        protected override void Process(IFCAnyHandle ifcCurve)
        {
            base.Process(ifcCurve);

            IFCAnyHandle basisCurve = IFCImportHandleUtil.GetRequiredInstanceAttribute(ifcCurve, "BasisCurve", false);

            if (basisCurve == null)
            {
                return;
            }

            bool   found    = false;
            double distance = IFCImportHandleUtil.GetRequiredScaledLengthAttribute(ifcCurve, "Distance", out found);

            if (!found)
            {
                distance = 0.0;
            }

            try
            {
                IFCCurve ifcBasisCurve = IFCCurve.ProcessIFCCurve(basisCurve);
                if (ifcBasisCurve.Curve != null)
                {
                    Curve = ifcBasisCurve.Curve.CreateOffset(distance, XYZ.BasisZ);
                }
                else if (ifcBasisCurve.CurveLoop != null)
                {
                    CurveLoop = CurveLoop.CreateViaOffset(ifcBasisCurve.CurveLoop, distance, XYZ.BasisZ);
                }
            }
            catch
            {
                Importer.TheLog.LogError(ifcCurve.StepId, "Couldn't create offset curve.", false);
            }
        }
Example #11
0
        /// <summary>
        /// Improved implementation by Alexander Ignatovich
        /// supporting curved wall with curved window,
        /// second attempt, published April 10, 2015:
        /// </summary>
        public Result Execute3(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;

            Autodesk.Revit.Creation.Application creapp
                = app.Create;

            Autodesk.Revit.Creation.Document credoc
                = doc.Create;

            Reference r = uidoc.Selection.PickObject(
                ObjectType.Element, "Select a wall");

            Element e = uidoc.Document.GetElement(r);

            Creator creator = new Creator(doc);

            Wall wall = e as Wall;

            if (wall == null)
            {
                return(Result.Cancelled);
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Wall Profile");

                // Get the external wall face for the profile
                // a little bit simpler than in the last realization

                Reference sideFaceReference
                    = HostObjectUtils.GetSideFaces(
                          wall, ShellLayerType.Exterior)
                      .First();

                Face face = wall.GetGeometryObjectFromReference(
                    sideFaceReference) as Face;

                // The normal of the wall external face.

                XYZ normal = wall.Orientation;

                // Offset curve copies for visibility.

                Transform offset = Transform.CreateTranslation(
                    5 * normal);

                // If the curve loop direction is counter-
                // clockwise, change its color to RED.

                Color colorRed = new Color(255, 0, 0);

                // Get edge loops as curve loops.

                IList <CurveLoop> curveLoops
                    = face.GetEdgesAsCurveLoops();

                foreach (var curveLoop in curveLoops)
                {
                    CurveArray curves = creapp.NewCurveArray();

                    foreach (Curve curve in curveLoop)
                    {
                        curves.Append(curve.CreateTransformed(
                                          offset));
                    }

                    var isCounterClockwize = curveLoop
                                             .IsCounterclockwise(normal);

                    // Create model lines for an curve loop if it is made

                    if (((LocationCurve)wall.Location).Curve
                        is Line)
                    {
                        //Plane plane = creapp.NewPlane( curves ); // 2016
                        Plane plane = CurveLoop.CreateViaOffset(
                            curveLoop, 5 * normal.GetLength(),
                            normal.Normalize()).GetPlane(); // 2017

                        SketchPlane sketchPlane
                            = SketchPlane.Create(doc, plane);

                        ModelCurveArray curveElements = credoc
                                                        .NewModelCurveArray(curves, sketchPlane);

                        if (isCounterClockwize)
                        {
                            SetModelCurvesColor(curveElements,
                                                view, colorRed);
                        }
                    }
                    else
                    {
                        foreach (var curve in curves.Cast <Curve>())
                        {
                            var curveElements = creator.CreateModelCurves(curve);
                            if (isCounterClockwize)
                            {
                                SetModelCurvesColor(curveElements, view, colorRed);
                            }
                        }
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
Example #12
0
        private Result SlopeSelectedBuildingPad(UIDocument targetUIdoc, ref string message, double maxPointDistInFeet, double targetAngleInRadians)
        {
            Document  doc = targetUIdoc.Document;
            Selection sel = targetUIdoc.Selection;

            View3D current3dView = doc.ActiveView as View3D;

            if (current3dView == null)
            {
                message = Properties.Messages.SlopeGradingFromPads_Not3DView;
                return(Result.Failed);
            }

            BuildingPad selectedBuildingPad = doc.GetElement(sel.PickObject(ObjectType.Element, new PadSelectionFilter(), Properties.Messages.SlopeGradingFromPads_SelectPad)) as BuildingPad;

            //Check if the Pad is associate with a Surface (never seen one doesnt, but anyways)
            ElementId topoElementID = selectedBuildingPad.HostId;

            if (topoElementID.Equals(ElementId.InvalidElementId))
            {
                message = Properties.Messages.SlopeGradingFromPads_NoTopoAssociate;
                return(Result.Failed);
            }

            TopographySurface currentTopo = doc.GetElement(topoElementID) as TopographySurface;

            if (currentTopo == null)
            {
                message = Properties.Messages.SlopeGradingFromPads_NoTopoAssociate;;
                return(Result.Failed);
            }

            IList <CurveLoop> PadBoundaryLoops = new List <CurveLoop>();
            CurveLoop         outerLoop        = null;

            IList <Reference> TopFacesReferences = HostObjectUtils.GetTopFaces(selectedBuildingPad);

            if (TopFacesReferences.Count > 1)
            {
                message = Properties.Messages.SlopeGradingFromPads_PadsWithMoreThanOneUpperFace;
                return(Result.Failed);
            }

            XYZ plannarDirection = XYZ.BasisZ;
            XYZ plannarOrigin    = XYZ.Zero;

            // interate on the only face
            foreach (Reference currentFaceRef in TopFacesReferences)
            {
                GeometryObject currentFaceObj = selectedBuildingPad.GetGeometryObjectFromReference(currentFaceRef);
                if (currentFaceObj is PlanarFace)
                {
                    PlanarFace currentPlanarFace = currentFaceObj as PlanarFace;
                    plannarDirection = currentPlanarFace.FaceNormal;
                    plannarOrigin    = currentPlanarFace.Origin;
                    PadBoundaryLoops = currentPlanarFace.GetEdgesAsCurveLoops();
                }
                else
                {
                    message = Properties.Messages.SlopeGradingFromPads_UpperFaceNotPlanar;
                    return(Result.Failed);
                }
            }

            //Sort the curves so the outer loop comes first
            IList <IList <CurveLoop> > curveLoopLoop = ExporterIFCUtils.SortCurveLoops(PadBoundaryLoops);

            if (curveLoopLoop.Count > 0)
            {
                IList <CurveLoop> firstList = curveLoopLoop.First();
                if (firstList.Count > 0)
                {
                    outerLoop = firstList.First();
                }
            }

            if (outerLoop == null)
            {
                message = Properties.Messages.SlopeGradingFromPads_OuterLoopIssue;
                return(Result.Failed);
            }

            //This will be the list of elements that the ReferenceIntersector will shoot the rays
            //If we try to shoot the rays only in the toposurface and the it has subregions, the reference
            //intersection will not recognize these regions, so its necessary to shoot rays to the surface and its subregions
            IList <ElementId> currentSubRegionsAndSurface = currentTopo.GetHostedSubRegionIds();

            currentSubRegionsAndSurface.Add(topoElementID);

            //Search for the max distance from the Pad to the topography
            //Doesnt matter if it is upwards or downwards, but we will check that, since the ray has to go to one direction
            //This is to estabilish what the distance will be using to create the slope to the right amount
            ReferenceIntersector topoRefIntersec = new ReferenceIntersector(currentSubRegionsAndSurface, FindReferenceTarget.Mesh, current3dView);

            double maxDist = double.NegativeInfinity;

            foreach (Curve currentCurve in outerLoop)
            {
                int    numberOfInteractions = 0;
                double increaseAmount       = 0;
                double currentParameter     = 0;
                EstabilishInteractionPoints(currentCurve, maxPointDistInFeet, out numberOfInteractions, out increaseAmount);

                for (int i = 0; i < numberOfInteractions; i++)
                {
                    if (i == 0)
                    {
                        currentParameter = 0;
                    }
                    else
                    {
                        currentParameter += increaseAmount;
                    }

                    XYZ currentPointToEvaluate = currentCurve.Evaluate(currentParameter, true);

                    ReferenceWithContext currentRefContext = topoRefIntersec.FindNearest(currentPointToEvaluate, XYZ.BasisZ);
                    if (currentRefContext == null)
                    {
                        currentRefContext = topoRefIntersec.FindNearest(currentPointToEvaluate, XYZ.BasisZ.Negate());
                    }

                    if (currentRefContext == null)
                    {
                        continue;
                    }

                    double currentDist = currentRefContext.Proximity;
                    if (currentDist > maxDist)
                    {
                        maxDist = currentDist;
                    }
                }
            }

            // if we haven't changed the maxdist yet, something went wrong
            if (maxDist == double.NegativeInfinity)
            {
                message = Properties.Messages.SlopeGradingFromPads_NoTopoAssociate;
                return(Result.Failed);
            }

            //Estabilish the offset from the pad
            double offsetDist = maxDist / Math.Tan(targetAngleInRadians);

            using (TopographyEditScope topoEditGroup = new TopographyEditScope(doc, Properties.Messages.SlopeGradingFromPads_Transaction))
            {
                topoEditGroup.Start(topoElementID);
                using (Transaction t = new Transaction(doc, Properties.Messages.SlopeGradingFromPads_Transaction))
                {
                    t.Start();

                    CurveLoop offsetLoop = null;

                    try
                    {
                        offsetLoop = CurveLoop.CreateViaOffset(outerLoop, offsetDist, plannarDirection);
                    }
                    catch
                    {
                        message += Properties.Messages.SlopeGradingFromPads_OuterOffsetLoopIssue;
                        return(Result.Failed);
                    }

                    #region DebugCurve Loop

                    //Plane p = new Plane(plannarDirection, plannarOrigin);
                    //SketchPlane sktP = SketchPlane.Create(doc, p);
                    //foreach (Curve currentOffsetCurve in offsetLoop)
                    //{
                    //    doc.Create.NewModelCurve(currentOffsetCurve, sktP);
                    //}

                    #endregion


                    foreach (Curve currentOffsetCurve in offsetLoop)
                    {
                        int    numberOfInteractions = 0;
                        double increaseAmount       = 0;
                        double currentParameter     = 0;

                        EstabilishInteractionPoints(currentOffsetCurve, maxPointDistInFeet, out numberOfInteractions, out increaseAmount);

                        for (int i = 0; i < numberOfInteractions; i++)
                        {
                            if (i == 0)
                            {
                                currentParameter = 0;
                            }
                            else
                            {
                                currentParameter += increaseAmount;
                            }

                            XYZ currentPointOffset = currentOffsetCurve.Evaluate(currentParameter, true);

                            ReferenceWithContext currentRefContext = topoRefIntersec.FindNearest(currentPointOffset, XYZ.BasisZ);
                            if (currentRefContext == null)
                            {
                                currentRefContext = topoRefIntersec.FindNearest(currentPointOffset, XYZ.BasisZ.Negate());
                            }
                            //if we couldn't find points upwards and downwards, the topo is near the border, so we cant add points
                            if (currentRefContext == null)
                            {
                                continue;
                            }

                            Reference currentReference  = currentRefContext.GetReference();
                            XYZ       currentPointToAdd = currentReference.GlobalPoint;

                            if (currentTopo.ContainsPoint(currentPointToAdd))
                            {
                                continue;
                            }

                            IList <XYZ> ListPointToAdd = new List <XYZ>();
                            ListPointToAdd.Add(currentPointToAdd);

                            currentTopo.AddPoints(ListPointToAdd);
                        }
                    }

                    foreach (Curve currentCurve in outerLoop)
                    {
                        int    numberOfInteractions = 0;
                        double increaseAmount       = 0;
                        double currentParameter     = 0;
                        EstabilishInteractionPoints(currentCurve, maxPointDistInFeet, out numberOfInteractions, out increaseAmount);

                        for (int i = 0; i < numberOfInteractions; i++)
                        {
                            if (i == 0)
                            {
                                currentParameter = 0;
                            }
                            else
                            {
                                currentParameter += increaseAmount;
                            }

                            XYZ currentPointToAdd = currentCurve.Evaluate(currentParameter, true);

                            if (currentTopo.ContainsPoint(currentPointToAdd))
                            {
                                continue;
                            }

                            IList <XYZ> ListPointToAdd = new List <XYZ>();
                            ListPointToAdd.Add(currentPointToAdd);

                            currentTopo.AddPoints(ListPointToAdd);
                        }
                    }
                    t.Commit();
                }
                topoEditGroup.Commit(new TopographyFailurePreprocessor());

                return(Result.Succeeded);
            }
        }
        /// <summary>
        /// 在房间X的中心创建四个方向的立面
        /// Create four Elevations on the center of the "X" of the selRoom
        /// </summary>
        /// <param name="elevationOffset"></param>
        /// <param name="FloorThickness"></param>
        public void CreateElevations(double elevationOffset, double FloorThickness)
        {
            int i = 0;//循环用

            //获取立面的familytype     Get the familyType of Elevation
            FilteredElementCollector collector = new FilteredElementCollector(DocSet.doc);

            collector.OfClass(typeof(ViewFamilyType));

            var viewFamilyTypes = from elem in collector
                                  let type = elem as ViewFamilyType
                                             where type.ViewFamily == ViewFamily.Elevation
                                             select type;

            ElementId viewTypeId;

            if (viewFamilyTypes.Count() > 0)
            {
                viewTypeId = viewFamilyTypes.First().Id;
            }
            else
            {
                return;
            }


            using (Transaction tran = new Transaction(DocSet.doc))
            {
                //房间的"X"的交点
                LocationPoint pt = DocSet.selRoom.Location as LocationPoint;

                tran.Start("newElvation");
                ElevationMarker marker = ElevationMarker.CreateElevationMarker(DocSet.doc, viewTypeId, pt.Point, 50);
                for (; i < 4; i++)
                {
                    ViewSection sv = marker.CreateElevation(DocSet.doc, DocSet.doc.ActiveView.Id, i);

                    //设定立面的 远剪裁偏移
                    sv.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).SetValueString("10000");

                    //设定每个立面的名称
                    XYZ    normal        = null;//法向量
                    string elevationName = "ELE -";
                    switch (i)
                    {
                    case 0:
                        elevationName += " West " + _SoANumber;
                        normal         = new XYZ(-1, 0, 0);
                        sv.get_Parameter(BuiltInParameter.VIEW_DESCRIPTION).Set("ELEVATION WEST");
                        break;

                    case 1:
                        elevationName += " North" + _SoANumber;
                        normal         = new XYZ(0, 1, 0);
                        sv.get_Parameter(BuiltInParameter.VIEW_DESCRIPTION).Set("ELEVATION NORTH");
                        break;

                    case 2:
                        elevationName += " East" + _SoANumber;
                        normal         = new XYZ(1, 0, 0);
                        sv.get_Parameter(BuiltInParameter.VIEW_DESCRIPTION).Set("ELEVATION EAST");
                        break;

                    case 3:
                        elevationName += " South" + _SoANumber;
                        normal         = new XYZ(0, -1, 0);
                        sv.get_Parameter(BuiltInParameter.VIEW_DESCRIPTION).Set("ELEVATION SOUTH");
                        break;
                    }
                    sv.ViewName = elevationName;

                    //不能删 必须先保存修改才能获取上面的元素
                    tran.Commit();
                    tran.Start("change elevation crop shape");

                    //小指型房间专用修改
                    if (cbSpRoom.IsChecked == true)
                    {
                        if (i == 1 || i == 2)
                        {
                            normal = -normal;
                        }
                        spRoomElevationChange(sv, elevationOffset, normal, FloorThickness);
                    }
                    else
                    {
                        //修改立面底边的高度
                        XYZ pt1 = null;
                        XYZ pt2 = null;
                        XYZ pt3 = null;
                        XYZ pt4 = null;
                        sv.CropBoxActive = true;
                        ViewCropRegionShapeManager vcrShanpMgr = sv.GetCropRegionShapeManager();
                        CurveLoop         loop     = vcrShanpMgr.GetCropShape().First();
                        CurveLoopIterator iterator = loop.GetCurveLoopIterator();

                        //分辨点的位置
                        while (iterator.MoveNext())
                        {
                            Curve curve = iterator.Current;
                            XYZ   pt0   = curve.GetEndPoint(0);
                            if (-1 < pt0.Z - pt.Point.Z && pt0.Z - pt.Point.Z < 1)
                            {
                                if (pt1 == null)
                                {
                                    pt1 = pt0;
                                }
                                else
                                {
                                    pt2 = pt0;
                                }
                            }

                            else
                            {
                                if (pt3 == null)
                                {
                                    pt3 = pt0;
                                }
                                else
                                {
                                    pt4 = pt0;
                                }
                            }
                        }

                        //重新生成一个边界框
                        //TaskDialog.Show("1", pt1.ToString() + "\n" + pt2.ToString() + "\n" + pt3.ToString() + "\n" + pt4.ToString());
                        pt1 = new XYZ(pt1.X, pt1.Y, pt1.Z + FloorThickness / 300);
                        pt2 = new XYZ(pt2.X, pt2.Y, pt1.Z);

                        Line lineBottom = Line.CreateBound(pt1, pt2);
                        Line lineRight  = Line.CreateBound(pt2, pt4);
                        Line lineTop    = Line.CreateBound(pt4, pt3);
                        Line lineLeft   = Line.CreateBound(pt3, pt1);

                        CurveLoop profile = new CurveLoop();
                        profile.Append(lineBottom);
                        profile.Append(lineRight);
                        profile.Append(lineTop);
                        profile.Append(lineLeft);

                        profile = CurveLoop.CreateViaOffset(profile, elevationOffset / 300, -normal);
                        vcrShanpMgr.SetCropShape(profile);
                    }
                }

                tran.Commit();
            }
        }
Example #14
0
        private void createLiningConcreteAsFloor2(Document doc, ElementId myFoundtionId, string nameFamily, double offsetValue)

        {
            Element myFoundation = doc.GetElement(myFoundtionId) as Element;

            //Get level from elemet
            Level myLevel = doc.GetElement(myFoundation.LevelId) as Level;

            //Get geometry from element
            GeometryElement geometryElement = myFoundation.get_Geometry(new Options());

            //Get list Of face (with normal vector = xyz(0,0,-1);

            List <Face> myListBottomFace = new List <Face>();

            using (Transaction myTrans = new Transaction(doc, "fil face of foundation"))
            {
                myTrans.Start();
                UV myPoint = new UV(0, 0);

                foreach (GeometryObject geometryObject in geometryElement)
                {
                    if (geometryObject is Solid)
                    {
                        Solid solid     = geometryObject as Solid;
                        XYZ   myNormVec = new XYZ();
                        foreach (Face myFace in solid.Faces)
                        {
                            myNormVec = myFace.ComputeNormal(myPoint);

                            // If normal vector of face has Z value == -1 add to list
                            if (Math.Round(myNormVec.Z, 1) == -1.0)
                            {
                                myListBottomFace.Add(myFace);
                            }
                        }
                    }
                }
                myTrans.Commit();
            }

            // Now We has a list of face (with normal vector = (0,0,-1)

            //Save floor to a list

            List <Floor> myListLining = new List <Floor>();


            using (Transaction trans = new Transaction(doc, "abc"))
            {
                trans.Start();
                foreach (Face myPickedFace in myListBottomFace)
                {
                    //Get Nomarl vector
                    XYZ myNorVecFace = myPickedFace.ComputeNormal(new UV(0, 0));
                    List <CurveLoop> myListCurvefromFace = myPickedFace.GetEdgesAsCurveLoops() as List <CurveLoop>;


                    CurveArray myBoundaFloor = new CurveArray();

                    foreach (CurveLoop myCurLoop in myListCurvefromFace)
                    {
                        if (myFoundation.Category.Name != "Structural Framing")
                        {
                            // Offset For Slab
                            CurveLoop curOffset = CurveLoop.CreateViaOffset(myCurLoop, offsetValue, myNorVecFace);
                            //TaskDialog.Show("abc", "xyz: " +curOffset.GetPlane().Normal.ToString());

                            foreach (Curve myCur in curOffset)
                            {
                                myBoundaFloor.Append(myCur);
                            }
                        }

                        else
                        {
                            List <double> myOffsetDist = getOffsetDis(myCurLoop, offsetValue);


                            CurveLoop curOffset = CurveLoop.CreateViaOffset(myCurLoop, myOffsetDist, myNorVecFace);
                            //TaskDialog.Show("abc", "xyz: " +curOffset.GetPlane().Normal.ToString());

                            foreach (Curve myCur in curOffset)
                            {
                                myBoundaFloor.Append(myCur);
                            }
                        }
                    }

                    FloorType floorType
                        = new FilteredElementCollector(doc)
                          .OfClass(typeof(FloorType))
                          .OfCategory(BuiltInCategory.OST_Floors)
                          .First <Element>(f => f.Name.Equals(nameFamily)) as FloorType;

                    //Floor myLining =  doc.Create.NewFoundationSlab(myBoundaFloor, floorType, myLevel, true, new XYZ(0,0,1));

                    //Floor myLining =  doc.Create.NewFloor(myBoundaFloor, floorType, myLevel, true, new XYZ(0,0,1));

                    Floor myLining = doc.Create.NewFloor(myBoundaFloor, floorType, myLevel, true, new XYZ(0, 0, 1));

                    myListLining.Add(myLining);
                }
                trans.Commit();
            }

            // Switch Joint
            if (myListLining.Count() < 1)
            {
                return;
            }
            else
            {
                foreach (Floor myLining in myListLining)
                {
                    switchJoinOrder(doc, myLining);
                }
            }
        }
Example #15
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            FinishForm MainForm = new FinishForm(doc);

            MainForm.disFElements("New");
            MainForm.ShowDialog();

            double FT = 0.3048;


            Phase     lastPhase = MainForm.retPhase;
            ElementId idPhase   = lastPhase.Id;
            //Выбираем элементы в Ревите
            ICollection <ElementId> selectedElements = uidoc.Selection.GetElementIds();
            List <Room>             selectedRooms    = selectedElements.Select(x => doc.GetElement(x) as Room).ToList();

            //Находим граничные элементы помещения
            //SpatialElementBoundaryOptions options = new SpatialElementBoundaryOptions();

            List <IList <IList <BoundarySegment> > > roomBounds = selectedRooms.Select(x => x.GetBoundarySegments(new SpatialElementBoundaryOptions())).ToList();

            //foreach (var r in selectedRooms)
            //{
            //    roomBounds.Add(r.GetBoundarySegments(options));
            //}

            //Получаем элементы границ и несоединенные кривые
            List <Element> roomElems = new List <Element>();
            List <List <List <Curve> > > disjoinedCurves = new List <List <List <Curve> > >();

            foreach (IList <IList <BoundarySegment> > rb in roomBounds)
            {
                List <List <Curve> > tempCrvList = new List <List <Curve> >();
                foreach (var closedCrv in rb)
                {
                    List <Curve> tempCCCrvList = new List <Curve>();
                    foreach (var elem in closedCrv)
                    {
                        tempCCCrvList.Add(elem.GetCurve());
                        if (doc.GetElement(elem.ElementId) == null)//Если элемент косячный
                        {
                            roomElems.Add(null);
                        }
                        else
                        {
                            roomElems.Add(doc.GetElement(elem.ElementId));
                        }
                    }
                    tempCrvList.Add(tempCCCrvList);
                }
                disjoinedCurves.Add(tempCrvList);
            }

            //Соединяем кривые в полилинии
            List <List <CurveLoop> > joinedCurvesUnfl = new List <List <CurveLoop> >();

            foreach (var d in disjoinedCurves)
            {
                List <CurveLoop> tempList = d.Select(x => CurveLoop.Create(x)).ToList();
                joinedCurvesUnfl.Add(tempList);
            }

            //Check the sense of polycurve
            foreach (var j in joinedCurvesUnfl)
            {
                foreach (CurveLoop crv in j)
                {
                    if (crv.GetPlane().Normal.Z < 0)
                    {
                        crv.Flip();
                    }
                }
            }
            List <string> getRoomNumbers = new List <string>();

            List <List <Room> > repeatedRoomsUnfl = new List <List <Room> >();
            int count = 0;

            foreach (var j in joinedCurvesUnfl)
            {
                List <Room> tempList = new List <Room>();

                foreach (CurveLoop crv in j)
                {
                    tempList.Add(selectedRooms.ElementAt(count));
                }
                repeatedRoomsUnfl.Add(tempList);
                count += 1;
            }

            List <Room> repeatedRoomsFl = GenericList <Room> .Flatten(repeatedRoomsUnfl);

            List <CurveLoop> joinedCurvesFl = GenericList <CurveLoop> .Flatten(joinedCurvesUnfl);

            List <string>  wHeights     = new List <string>();
            List <Element> wTypes       = new List <Element>();
            List <Element> allWallTypes = new FilteredElementCollector(doc).OfClass(typeof(WallType)).ToList();

            //GlobalParameter OTD_Main;
            //using (Transaction tryGlobal = new Transaction(doc, "defineGlobal"))
            //{
            //    tryGlobal.Start();

            //    if (GlobalParametersManager.FindByName(doc, "ОТД_Основная") != ElementId.InvalidElementId)
            //    {
            //        OTD_Main = doc.GetElement(GlobalParametersManager.FindByName(doc, "ОТД_Основная")) as GlobalParameter;
            //    }
            //    else
            //    {
            //        OTD_Main = GlobalParameter.Create(doc, "ОТД_Основная", ParameterType.Text);

            //    }

            //    tryGlobal.Commit();
            //}
            string s_OTD_Main = MainForm.wTypeBoxes[0];

            //string s_OTD_Main = ((StringParameterValue)OTD_Main.GetValue()).Value;
            //wTypes.Add(MainForm.wTypeBoxes)
            foreach (Element wt in allWallTypes)
            {
                if (wt.Name == s_OTD_Main)
                {
                    wTypes.Add(wt);
                }
            }
            //foreach (Room r in repeatedRoomsFl)
            //{
            //    //wHeights.Add(r.getP(s_OTD_Main));
            //    //allWallTypes.Where(x => x.Name == r.getP("setFFF")).ToList();
            //    foreach (Element wt in allWallTypes)
            //    {
            //        if (wt.Name==r.getP(s_OTD_Main))
            //        {
            //            wTypes.Add(wt);
            //        }
            //    }
            //}

            //Level of each room
            List <Level> levels = repeatedRoomsFl.Select(x => x.Level).ToList();

            //Create offset curve
            List <CurveLoop> offsetedCurves = new List <CurveLoop>();
            DisplayUnitType  docLengthUnit  = doc.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;

            count = 0;
            foreach (CurveLoop j in joinedCurvesFl)
            {
                double valueWith = wTypes[0].get_Parameter(BuiltInParameter.WALL_ATTR_WIDTH_PARAM).AsDouble();
                //double value = UnitUtils.Convert(valueWith, DisplayUnitType.DUT_DECIMAL_FEET, docLengthUnit);
                double    value = valueWith / FT;
                CurveLoop gg    = CurveLoop.CreateViaOffset(j, (valueWith * (0.5)), j.GetPlane().Normal);

                if (repeatedRoomsFl[count].IsPointInRoom(gg.GetCurveLoopIterator().Current.GetEndPoint(0)) == true)
                {
                    offsetedCurves.Add(gg);
                }
                else
                {
                    //offsetedCurves.Add(gg);
                    try
                    {
                        offsetedCurves.Add(CurveLoop.CreateViaOffset(j, (valueWith * (-0.5)), j.GetPlane().Normal));
                    }
                    catch (Exception)
                    {
                    }
                }
                count += 1;
            }

            List <List <Curve> > explodedCurves = new List <List <Curve> >();

            foreach (CurveLoop oc in offsetedCurves)
            {
                List <Curve> tempList = new List <Curve>();
                foreach (Curve i in oc)
                {
                    tempList.Add(i);
                }

                explodedCurves.Add(tempList);
            }

            List <Wall> walls = new List <Wall>();

            using (Transaction tr = new Transaction(doc, "PerimetralWall"))
            {
                tr.Start();
                count = 0;
                foreach (List <Curve> group in explodedCurves)
                {
                    foreach (Curve crv in group)
                    {
                        Wall w = Wall.Create(doc, crv, wTypes[0].Id, levels[count].Id, 2 / FT, 0, false, false);
                        walls.Add(w);
                    }

                    count += 1;
                }
                count = 0;
                foreach (Wall w in walls)
                {
                    w.get_Parameter(BuiltInParameter.WALL_ATTR_ROOM_BOUNDING).Set(0);
                    w.get_Parameter(BuiltInParameter.WALL_KEY_REF_PARAM).Set(2);
                    w.DemolishedPhaseId = lastPhase.Id;
                    //w.setP("Помещение", repeatedRoomsFl[count].Number);
                    count += 1;
                }
                count = 0;

                /*
                 * foreach (Element r in roomElems)
                 * {
                 *  try
                 *  {
                 *      JoinGeometryUtils.JoinGeometry(doc, walls[count], r);
                 *  }
                 *  catch (Exception)
                 *  {
                 *
                 *
                 *  }
                 *  count += 1;
                 * }
                 */

                tr.Commit();
            }
            return(Result.Succeeded);
        }
Example #16
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication  uiapp                  = commandData.Application;
            UIDocument     uidoc                  = uiapp.ActiveUIDocument;
            Application    app                    = uiapp.Application;
            Document       doc                    = uidoc.Document;
            IList <double> wallthicknessList      = new List <double>();
            XYZ            normal                 = new XYZ(0, 0, 1);
            SpatialElementBoundaryOptions seb_opt = new SpatialElementBoundaryOptions();
            FilteredElementCollector      levels  = new FilteredElementCollector(doc).OfClass(typeof(Level));

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Create cropped views for each room");
                string date_iso = DateTime.Now.ToString("yyyy-MM-dd");
                foreach (Level level in levels)
                {
                    wallthicknessList.Clear();
                    Debug.Print(level.Name);
                    ElementId          id_view = level.FindAssociatedPlanViewId();
                    ViewPlan           view    = doc.GetElement(id_view) as ViewPlan;
                    IEnumerable <Room> rooms   = new FilteredElementCollector(doc, id_view).OfClass(typeof(SpatialElement)).Where <Element>(e => e is Room).Cast <Room>();
                    foreach (Room room in rooms)
                    {
                        wallthicknessList.Clear();
                        string view_name = string.Format("{0}_cropped_to_room_{1}_date_{2}", view.Name, room.Name, date_iso);
                        id_view = view.Duplicate(ViewDuplicateOption.AsDependent);
                        View view_cropped = doc.GetElement(id_view) as View;
                        view_cropped.Name = view_name;
                        IList <IList <BoundarySegment> > sloops = room.GetBoundarySegments(seb_opt);
                        if (null == sloops) // the room may not be bound
                        {
                            continue;
                        }
                        CurveLoop loop = null;
                        foreach (IList <BoundarySegment> sloop in sloops)
                        {
                            loop = new CurveLoop();
                            foreach (BoundarySegment s in sloop)
                            {
                                loop.Append(s.GetCurve());
                                ElementType type = doc.GetElement(s.ElementId) as ElementType;
                                Element     elem = doc.GetElement(s.ElementId);
                                if (elem is Wall)
                                {
                                    Wall wall = elem as Wall;
                                    wallthicknessList.Add(wall.Width);
                                }
                                else
                                {
                                    //Room separator
                                    //Any other exceptions to walls need including??
                                    wallthicknessList.Add(0);
                                }
                            }
                            // Skip out after first sloop - ignore
                            // rooms with holes and disjunct parts
                            break;
                        }

                        CurveLoop loop2   = CurveLoop.CreateViaOffset(loop, wallthicknessList, normal);
                        CurveLoop newloop = new CurveLoop();
                        foreach (Curve curve in loop2)
                        {
                            List <XYZ> points = curve.Tessellate().ToList();
                            for (int ip = 0; ip < points.Count - 1; ip++)
                            {
                                Line l = Line.CreateBound(points[ip], points[ip + 1]);
                                newloop.Append(l);
                            }
                        }
                        ViewCropRegionShapeManager vcrs_mgr = view_cropped.GetCropRegionShapeManager();
                        bool valid = vcrs_mgr.IsCropRegionShapeValid(newloop);
                        if (valid)
                        {
                            view_cropped.CropBoxVisible = true;
                            view_cropped.CropBoxActive  = true;
                            vcrs_mgr.SetCropShape(newloop);
                        }
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
Example #17
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication  uiapp                  = commandData.Application;
            UIDocument     uidoc                  = uiapp.ActiveUIDocument;
            Application    app                    = uiapp.Application;
            Document       doc                    = uidoc.Document;
            IList <double> wallthicknessList      = new List <double>();
            XYZ            normal                 = new XYZ(0, 0, 1);
            string         previous               = null;
            double         previousWidth          = 0;
            SpatialElementBoundaryOptions seb_opt = new SpatialElementBoundaryOptions();
            FilteredElementCollector      levels  = new FilteredElementCollector(doc).OfClass(typeof(Level));

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Create cropped views for each room");
                string date_iso = DateTime.Now.ToString("yyyy-MM-dd");
                foreach (Level level in levels)
                {
                    Debug.Print(level.Name);
                    ElementId          id_view = level.FindAssociatedPlanViewId();
                    ViewPlan           view    = doc.GetElement(id_view) as ViewPlan;
                    IEnumerable <Room> rooms   = new FilteredElementCollector(doc, id_view).OfClass(typeof(SpatialElement)).Where <Element>(e => e is Room).Cast <Room>();
                    foreach (Room room in rooms)
                    {
                        wallthicknessList.Clear();
                        string view_name = string.Format("{0}_cropped_to_room_{1}_date_{2}", view.Name, room.Name, date_iso);
                        id_view = view.Duplicate(ViewDuplicateOption.AsDependent);
                        View view_cropped = doc.GetElement(id_view) as View;
                        view_cropped.Name = view_name;
                        IList <IList <BoundarySegment> > sloops = room.GetBoundarySegments(seb_opt);
                        if (null == sloops)  // the room may not be bound
                        {
                            continue;
                        }
                        CurveLoop loop = null;
                        foreach (IList <BoundarySegment> sloop in sloops)
                        {
                            loop = new CurveLoop();
                            foreach (BoundarySegment s in sloop)
                            {
                                loop.Append(s.GetCurve());
                                ElementType type = doc.GetElement(s.ElementId) as ElementType;
                                Element     elem = doc.GetElement(s.ElementId);
                                //Error when wall width varies across length
                                //if (elem is Wall)
                                //{
                                //    Wall wall = elem as Wall;
                                //    wallthicknessList.Add(wall.Width*1.1);
                                //}
                                //else
                                //{
                                //    //Room separator
                                //    //Any other exceptions to walls need including??
                                //    wallthicknessList.Add(0);
                                //}
                                if (elem != null)//The elem == null is due to room separators. Are there going to be any others?
                                {
                                    if (firstPass)
                                    {
                                        if ((BuiltInCategory)elem.Category.Id.IntegerValue == BuiltInCategory.OST_Walls)
                                        {
                                            Wall wall = elem as Wall;
                                            //Is there a better way of identifying Orientation (predominantly horizontal or Vertical) What if walls at 45 deg?
                                            if (Math.Abs(Math.Round(wall.Orientation.Y, 0)) == 1)
                                            {
                                                previous = "Y";
                                            }
                                            else
                                            {
                                                previous = "X";
                                            }
                                            firstPass = false;
                                            wallthicknessList.Add(wall.Width + 0.1);
                                            previousWidth = wall.Width + 0.1;
                                        }
                                        //Are there any other situations need taking account off?
                                        else if ((BuiltInCategory)elem.Category.Id.IntegerValue == BuiltInCategory.OST_RoomSeparationLines)
                                        {
                                            //Room separator
                                            Autodesk.Revit.DB.Options         opt      = new Options();
                                            Autodesk.Revit.DB.GeometryElement geomElem = elem.get_Geometry(opt);
                                            foreach (GeometryObject geomObj in geomElem)
                                            {
                                                Line line = geomObj as Line;
                                                //Is there a better way of identifying Orientation (predominantly horizontal or Vertical) What if walls at 45 deg?
                                                if (0 - line.GetEndPoint(1).X - line.GetEndPoint(0).X > 0 - line.GetEndPoint(1).Y - line.GetEndPoint(0).Y)
                                                {
                                                    previous = "Y";
                                                }
                                                else
                                                {
                                                    previous = "X";
                                                }
                                                firstPass = false;
                                                wallthicknessList.Add(0.1);
                                                previousWidth = 0.1;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if ((BuiltInCategory)elem.Category.Id.IntegerValue == BuiltInCategory.OST_Walls)
                                        {
                                            Wall wall = elem as Wall;
                                            if (Math.Abs(Math.Round(wall.Orientation.Y, 0)) == 1 && previous == "Y")
                                            {
                                                if (wall.Width > previousWidth)
                                                {
                                                    //This would appear to avoid the Cannot properly trim error
                                                    //How to allow for more than two wall thickness changes within the same length?
                                                    //How to not require this and just offset wall widths?
                                                    wallthicknessList[wallthicknessList.Count - 1] = wall.Width + 0.1;
                                                }
                                                wallthicknessList.Add(wall.Width + 0.1);
                                                previousWidth = wall.Width + 0.1;
                                                previous      = "Y";
                                            }
                                            else if (Math.Abs(Math.Round(wall.Orientation.X, 0)) == 1 && previous == "X")
                                            {
                                                if (wall.Width > previousWidth)
                                                {
                                                    //This would appear to avoid the Cannot properly trim error
                                                    //How to allow for more than two wall thickness changes within the same length?
                                                    //How to not require this and just offset wall widths?
                                                    wallthicknessList[wallthicknessList.Count - 1] = wall.Width + 0.1;
                                                }
                                                wallthicknessList.Add(wall.Width + 0.1);
                                                previousWidth = wall.Width + 0.1;
                                                previous      = "X";
                                            }
                                            else
                                            {
                                                if (Math.Abs(Math.Round(wall.Orientation.Y, 0)) == 1)
                                                {
                                                    previous = "Y";
                                                }
                                                else if (Math.Abs(Math.Round(wall.Orientation.X, 0)) == 1)
                                                {
                                                    previous = "X";
                                                }
                                                wallthicknessList.Add(wall.Width + 0.1);
                                                previousWidth = wall.Width + 0.1;
                                            }
                                        }
                                        else if ((BuiltInCategory)elem.Category.Id.IntegerValue == BuiltInCategory.OST_RoomSeparationLines)//Any other situations need taking account of?
                                        {
                                            //Room separator
                                            Autodesk.Revit.DB.Options         opt      = new Options();
                                            Autodesk.Revit.DB.GeometryElement geomElem = elem.get_Geometry(opt);
                                            foreach (GeometryObject geomObj in geomElem)
                                            {
                                                Line line = geomObj as Line;
                                                //Is there a better way of identifying Orientation (predominantly horizontal or Vertical) What if walls at 45 deg?
                                                if (0 - line.GetEndPoint(1).X - line.GetEndPoint(0).X > 0 - line.GetEndPoint(1).Y - line.GetEndPoint(0).Y)
                                                {
                                                    previous = "Y";
                                                }
                                                else
                                                {
                                                    previous = "X";
                                                }
                                                wallthicknessList.Add(previousWidth);
                                                //Error "cannot trim"
                                                //wallthicknessList.Add(0.1);
                                                previousWidth = 0.1;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    wallthicknessList.Add(-0.1);
                                }
                            }
                            // Skip out after first sloop - ignore
                            // rooms with holes and disjunct parts
                            break;
                        }

                        CurveLoop loop2   = CurveLoop.CreateViaOffset(loop, wallthicknessList, normal);
                        CurveLoop newloop = new CurveLoop();
                        foreach (Curve curve in loop2)
                        {
                            List <XYZ> points = curve.Tessellate().ToList();
                            for (int ip = 0; ip < points.Count - 1; ip++)
                            {
                                Line l = Line.CreateBound(points[ip], points[ip + 1]);
                                newloop.Append(l);
                            }
                        }
                        ViewCropRegionShapeManager vcrs_mgr = view_cropped.GetCropRegionShapeManager();
                        bool valid = vcrs_mgr.IsCropRegionShapeValid(newloop);
                        if (valid)
                        {
                            view_cropped.CropBoxVisible = true;
                            view_cropped.CropBoxActive  = true;
                            vcrs_mgr.SetCropShape(newloop);
                        }
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
        /// <summary>
        /// The method that allows the user to select walls and creates the floor.
        /// </summary>
        public void SelectWallsAndCreateFloor()
        {
            // Initialize the wall selection filter
            WallSelectionFilter wallSelectionFilter = new WallSelectionFilter();

            // Select the Walls
            IList <Reference> references = RevitBase.UIDocument.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, wallSelectionFilter);

            if (references != null && references.Count > 0)
            {
                // Initialize the original curves list
                List <Curve> originalWallCurves = new List <Curve>();

                // Initialize the List of original offset distances
                List <double> originalOffsets = new List <double>();

                // Initialize the list of levels ids
                List <ElementId> levelsIds = new List <ElementId>();

                foreach (var r in references)
                {
                    // Get the wall element
                    Wall wall = RevitBase.Document.GetElement(r) as Wall;

                    if (wall != null)
                    {
                        // Add the required offset to the list by dividing the wall width by 2
                        originalOffsets.Add(wall.Width / 2.0);

                        // Add the wall curve to the original curves list
                        originalWallCurves.Add((wall.Location as LocationCurve).Curve);

                        // Add wall level id to the levels ids list
                        levelsIds.Add(wall.LevelId);
                    }
                }

                if (levelsIds.All(lvl => lvl == levelsIds[0]))
                {
                    // Get the contiguous curves with offsets tuple.
                    var contiguousCurvesWithOffsetsTuple = CurveHelper.GetContiguousCurvesWithOffsets(originalWallCurves, originalOffsets);

                    // Get the contiguous curves.
                    List <Curve> contiguousCurves = contiguousCurvesWithOffsetsTuple.curves;

                    // Get the contiguous curves.
                    List <double> contiguousOffsets = contiguousCurvesWithOffsetsTuple.offsets;

                    // Create a curve loop offset to the contiguous curves.
                    CurveLoop floorCurves = CurveLoop.CreateViaOffset(CurveLoop.Create(contiguousCurves), contiguousOffsets, new XYZ(0.0, 0.0, 1.0));

                    // Initialize the curve array
                    CurveArray curveArray = new CurveArray();

                    // Append the floor curves in the curve array
                    foreach (var c in floorCurves)
                    {
                        curveArray.Append(c);
                    }

                    // Get the walls level
                    Level level = RevitBase.Document.GetElement(levelsIds[0]) as Level;

                    using (Transaction transaction = new Transaction(RevitBase.Document, "Create floor from Walls"))
                    {
                        transaction.Start();

                        try
                        {
                            //if (SelectedFloorType == null) SelectedFloorType = FloorTypes.First();

                            // Create the floor
                            RevitBase.Document.Create.NewFloor(curveArray, SelectedFloorType, level, false);

                            // Commit the transaction
                            transaction.Commit();
                        }
                        catch (Exception e)
                        {
                            // Asssign the error message to the message parameter
                            RevitBase.Message = e.Message;

                            // Roll back model changes
                            transaction.RollBack();

                            // Assign result to be failed
                            RevitBase.Result = Result.Failed;
                        }
                    }
                }
                else
                {
                    // Assign result to be failed
                    RevitBase.Result = Result.Failed;
                }
            }
            else
            {
                // Assign result to be failed
                RevitBase.Result = Result.Failed;
            }

            // Return result
        }
Example #19
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;

            //Get document file Link
            //var link = new FilteredElementCollector(doc).OfType<RevitLinkInstance>().FirstOrDefault(l => l.Name == "test.rvt");
            //var linkdoc = link.GetLinkDocument();
            var vm     = new DiggingHoleViewModel();
            var window = new DiggingHole(vm);

            window.ShowDialog();


            if (window.DialogResult == true)
            {
                var topoffset   = UnitUtils.ConvertToInternalUnits(double.Parse(vm.TopOffset), DisplayUnitType.DUT_MILLIMETERS);
                var botoffset   = UnitUtils.ConvertToInternalUnits(double.Parse(vm.BotOffset), DisplayUnitType.DUT_MILLIMETERS);
                var filter      = new FoundationFilter();
                var foundations = uidoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, filter)
                                  .Select(r => doc.GetElement(r.ElementId))
                                  .ToList();

                var results = new List <Element>();

                foreach (var foundation in foundations)
                {
                    //var otp = new Options();
                    //otp.DetailLevel = ViewDetailLevel.Fine;
                    //var geoElement = foundation.get_Geometry(otp);
                    //var instance = geoElement.Cast<GeometryObject>().OfType<GeometryInstance>().Select(i => i.GetInstanceGeometry()).ToList();
                    //var solids = geoElement.Cast<GeometryObject>().Concat(instance).OfType<Solid>().Where(s => s.Volume > 0 && s.Faces.Size > 0).ToList();

                    var solids        = foundation.GetSolids();
                    var solid         = solids.OrderByDescending(s => s.Volume).FirstOrDefault();
                    var botFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1);
                    var topFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == 1);
                    var offsettopFace = CurveLoop.CreateViaOffset(topFace.GetEdgesAsCurveLoops().FirstOrDefault(), topoffset, topFace.FaceNormal);

                    var offsetbotFace = CurveLoop.CreateViaOffset(botFace.GetEdgesAsCurveLoops().FirstOrDefault(), botoffset, botFace.FaceNormal);
                    offsetbotFace.Transform(Transform.CreateTranslation(new XYZ(0, 0, UnitUtils.ConvertToInternalUnits(-100, DisplayUnitType.DUT_MILLIMETERS))));
                    var fdoc = commandData.Application.Application.NewFamilyDocument(@"C:\ProgramData\Autodesk\RVT 2020\Family Templates\English\Metric Generic Model.rft");
                    using (Transaction tran = new Transaction(fdoc, "new Blend"))
                    {
                        tran.Start();
                        var plan        = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, botFace.Origin);
                        var sketchPlane = SketchPlane.Create(fdoc, plan);
                        var top         = ConvertLoopToArray(offsettopFace);
                        var baseface    = ConvertLoopToArray(offsetbotFace);
                        var blend       = fdoc.FamilyCreate.NewBlend(true, top, baseface, sketchPlane);
                        blend.LookupParameter("Second End").Set(Math.Abs(blend.LookupParameter("Second End").AsDouble()));
                        //CreateBlend(fdoc, null);
                        tran.Commit();
                    }
                    fdoc.SaveAs($"{Path.GetTempPath()}{foundation.Id.ToString()}-{Guid.NewGuid().ToString()}.rfa");
                    Family family = fdoc.LoadFamily(doc);
                    fdoc.Close();
                    using (Transaction tran = new Transaction(doc, "new void"))
                    {
                        tran.Start();
                        //offsetFace.ToList().ForEach(f => doc.Create.NewModelCurve(f, SketchPlane.Create(doc, Plane.CreateByThreePoints(f.GetEndPoint(0), f.GetEndPoint(1), new XYZ(0, 0, 1)))));
                        //botFace.GetEdgesAsCurveLoops().FirstOrDefault().ToList().ForEach(f => doc.Create.NewModelCurve(f, SketchPlane.Create(doc, Plane.CreateByThreePoints(f.GetEndPoint(0), f.GetEndPoint(1), new XYZ(0, 0, 1)))));
                        var symbol = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
                        symbol.Activate();
                        var ele = doc.Create.NewFamilyInstance(XYZ.Zero, symbol, Autodesk.Revit.DB.Structure.StructuralType.Footing);
                        results.Add(ele);
                        tran.Commit();
                    }
                }
                foreach (var ele in results)
                {
                    var boundingBox = ele.get_BoundingBox(null);

                    var solids = ele.GetSolids();

                    var outline  = new Outline(boundingBox.Min, boundingBox.Max);
                    var bbfilter = new BoundingBoxIntersectsFilter(outline);

                    var collectors = new FilteredElementCollector(doc, results.Select(e => e.Id).ToList())
                                     .WhereElementIsNotElementType()
                                     .WherePasses(bbfilter)
                                     .ToElements();

                    var solid  = ele.GetSolids().FirstOrDefault();
                    var firstZ = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1).Origin.Z;

                    foreach (var item in collectors)
                    {
                        var secondSolid = item.GetSolids().FirstOrDefault();
                        var secondZ     = secondSolid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1).Origin.Z;
                        if (Math.Round(firstZ, 2) == Math.Round(secondZ, 2))
                        {
                            solid = BooleanOperationsUtils.ExecuteBooleanOperation(solid, item.GetSolids().FirstOrDefault(), BooleanOperationsType.Union);
                        }
                    }
                    var botFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1);
                    var topFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == 1);
                    var offsettopFace = CurveLoop.CreateViaOffset(topFace.GetEdgesAsCurveLoops().FirstOrDefault(), 0, topFace.FaceNormal);
                    var offsetbotFace = CurveLoop.CreateViaOffset(topFace.GetEdgesAsCurveLoops().FirstOrDefault(), -topoffset + botoffset, topFace.FaceNormal);
                    offsetbotFace.Transform(Transform.CreateTranslation(new XYZ(0, 0, -topFace.Origin.Z + botFace.Origin.Z)));
                    var fdoc = commandData.Application.Application.NewFamilyDocument(@"C:\ProgramData\Autodesk\RVT 2020\Family Templates\English\Metric Generic Model.rft");
                    using (Transaction tran = new Transaction(fdoc, "new Blend"))
                    {
                        tran.Start();
                        var plan        = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, botFace.Origin);
                        var sketchPlane = SketchPlane.Create(fdoc, plan);
                        var top         = ConvertLoopToArray(offsettopFace);
                        var baseface    = ConvertLoopToArray(offsetbotFace);
                        var blend       = fdoc.FamilyCreate.NewBlend(true, top, baseface, sketchPlane);
                        blend.LookupParameter("Second End").Set(Math.Abs(blend.LookupParameter("Second End").AsDouble()));
                        //CreateBlend(fdoc, null);
                        tran.Commit();
                    }
                    fdoc.SaveAs($"{Path.GetTempPath()}{ele.Id.ToString()}-{Guid.NewGuid().ToString()}.rfa");
                    Family family = fdoc.LoadFamily(doc);
                    fdoc.Close();
                    using (Transaction tran = new Transaction(doc, "new void"))
                    {
                        tran.Start();
                        //offsetFace.ToList().ForEach(f => doc.Create.NewModelCurve(f, SketchPlane.Create(doc, Plane.CreateByThreePoints(f.GetEndPoint(0), f.GetEndPoint(1), new XYZ(0, 0, 1)))));
                        //botFace.GetEdgesAsCurveLoops().FirstOrDefault().ToList().ForEach(f => doc.Create.NewModelCurve(f, SketchPlane.Create(doc, Plane.CreateByThreePoints(f.GetEndPoint(0), f.GetEndPoint(1), new XYZ(0, 0, 1)))));
                        var symbol = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
                        symbol.Activate();
                        doc.Create.NewFamilyInstance(XYZ.Zero, symbol, Autodesk.Revit.DB.Structure.StructuralType.Footing);
                        tran.Commit();
                    }
                }
            }
            return(Result.Succeeded);
        }
Example #20
0
        public WallsMPWRequest(UIApplication uiApp, String text)
        {
            MainUI      uiForm = BARevitTools.Application.thisApp.newMainUi;
            RVTDocument doc    = uiApp.ActiveUIDocument.Document;
            //Collect all the levels
            FilteredElementCollector levelsCollector = new FilteredElementCollector(doc);
            ICollection <Element>    existingLevels  = levelsCollector.OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements();
            //Collect the wall types
            FilteredElementCollector wallTypesCollector = new FilteredElementCollector(doc);
            ICollection <Element>    existingWallTypes  = wallTypesCollector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType().ToElements();

            List <Line>    wallLines        = new List <Line>();
            List <Wall>    newWalls         = new List <Wall>();
            List <Element> selectedElements = new List <Element>();
            //Get the wall type name from the MainUI combobox
            string   selectedWallTypeName = uiForm.wallsMPWComboBoxWall.Text.ToString();
            WallType wallTypeInput        = null;
            double   wallHeightInput      = 0;

            //Ensure the active view is a plan view
            if (doc.ActiveView.GetType().ToString() != "Autodesk.Revit.DB.ViewPlan")
            {
                MessageBox.Show("Please run from a plan view");
            }
            else
            {
                try
                {
                    //Get the height of the walls to create from the MainUI, converted to a Double value in decimal feet
                    wallHeightInput = (Convert.ToDouble(uiForm.wallsMPWNumericUpDownWallHeightFt.Value + (uiForm.wallsMPWNumericUpDownWallHeightIn.Value / 12)));
                }
                catch
                {
                    //If the wall height input is invalid, let the user know
                    throw new System.ArgumentException("Invalid wall height");
                }

                double offsetDistance = 0;
                try
                {
                    //To get the distance to offset the wall, get the wall type's thickness, then divide it in half because walls are placed along the centerline
                    foreach (WallType wallType in existingWallTypes)
                    {
                        if (wallType.Name == selectedWallTypeName)
                        {
                            wallTypeInput  = wallType;
                            offsetDistance = (wallTypeInput.Width) / 2;
                            break;
                        }
                    }
                }
                catch
                {
                    new System.ArgumentException("No wall type was selected");
                }

                //Get the active view and its associated level
                ViewPlan activeView = doc.ActiveView as ViewPlan;
                Level    levelInput = activeView.GenLevel;

                //If the user selected a wall type, the level was obtained from the view, and the wall height is valid, continue
                if (wallTypeInput != null && levelInput != null && wallHeightInput != 0)
                {
                    //Invoke selection of the rooms and get them from either the rooms or room tags selected
                    List <Room> selectedRoomElements = RVTOperations.SelectRoomElements(uiApp);

                    //Cycle through the room elements
                    foreach (Room roomElem in selectedRoomElements)
                    {
                        try
                        {
                            //Get the location of the room as a point
                            Location      roomLocation = roomElem.Location;
                            LocationPoint rlp          = roomLocation as LocationPoint;

                            //Get the room geometry
                            Options geomOptions = new Options();
                            geomOptions.IncludeNonVisibleObjects = true;
                            GeometryElement geomElements = roomElem.get_Geometry(geomOptions);
                            foreach (GeometryObject geomObject in geomElements)
                            {
                                if (geomObject.GetType().ToString() == "Autodesk.Revit.DB.Solid")
                                {
                                    //Grab the solid form of the room geometry
                                    Solid     roomSolid      = geomObject as Solid;
                                    FaceArray roomSolidFaces = roomSolid.Faces;
                                    foreach (PlanarFace roomSolidFace in roomSolidFaces)
                                    {
                                        //Get the bottom face of the room which is the face that has a -Z vector
                                        XYZ faceNormal = roomSolidFace.FaceNormal;
                                        if (faceNormal.Z == -1)
                                        {
                                            //Get the CurveLoops for the bottom face
                                            IList <CurveLoop> faceCurveLoops = roomSolidFace.GetEdgesAsCurveLoops();
                                            foreach (CurveLoop curveLoop in faceCurveLoops)
                                            {
                                                //Offset the CurveLoop by the half thickness of the wall
                                                CurveLoop offsetCurveLoops = CurveLoop.CreateViaOffset(curveLoop, offsetDistance, XYZ.BasisZ);
                                                foreach (Line line in offsetCurveLoops)
                                                {
                                                    //Collect the lines to draw walls along
                                                    wallLines.Add(line);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch { continue; }
                    }

                    //Start a transaction
                    using (Transaction t1 = new Transaction(doc, "MakeWalls"))
                    {
                        t1.Start();
                        foreach (Line wallLine in wallLines)
                        {
                            //Draw a line along each of the lines and add them to a list of walls created
                            Wall newWall = Wall.Create(doc, wallLine, wallTypeInput.Id, levelInput.Id, wallHeightInput, 0, true, false);
                            newWalls.Add(newWall);
                        }
                        t1.Commit();
                    }

                    //Start a new transaction to join the walls to adjacent walls
                    using (Transaction t2 = new Transaction(doc, "JoinWalls"))
                    {
                        t2.Start();
                        foreach (Wall newWall in newWalls)
                        {
                            //Collect the walls in the project
                            FilteredElementCollector existingWallsCollector = new FilteredElementCollector(doc, doc.ActiveView.Id);
                            existingWallsCollector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements();
                            //Get the bounding box of each wall
                            BoundingBoxXYZ wallBBox = newWall.get_BoundingBox(doc.ActiveView);
                            //Get the outline of the bounding box using the minimum and maximum points
                            Outline wallBBoxOutline = new Outline(wallBBox.Min, wallBBox.Max);
                            //Generate a new BoundingBoxIntersectsFilter to find the other bounding boxes that intersect the outline
                            BoundingBoxIntersectsFilter bBoxFilter = new BoundingBoxIntersectsFilter(wallBBoxOutline);
                            //Get all walls that pass the filter (they intersect the evaluated new wall's outline)
                            existingWallsCollector.WherePasses(bBoxFilter);
                            foreach (Wall existingWall in existingWallsCollector)
                            {
                                try
                                {
                                    //Try to joing the new wall to the existing walls so they are cut by the hosted elements
                                    JoinGeometryUtils.JoinGeometry(doc, newWall, existingWall);
                                }
                                catch { continue; }
                            }
                        }
                        t2.Commit();
                    }
                }
                else if (levelInput == null)
                {
                    //Let the user know if the level could not be obtained
                    MessageBox.Show("No level set");
                }
                else if (wallTypeInput == null)
                {
                    //Let the user know if they didn't select a wall type
                    MessageBox.Show("No wall type set");
                }
                else if (wallHeightInput <= 0)
                {
                    //Let the user know if they specified a 0 or negative wall height
                    MessageBox.Show("Wall height must be set to greater than 0'");
                }
                else
                {
                    //If for some reason the script fails, report that one of the following settings could not be used. This is highly unlikely though
                    MessageBox.Show(String.Format("One of the following settings could not be used: Wall Type = '{0}'; " +
                                                  "Level = '{1}'; " +
                                                  "Wall Height = '{2}'",
                                                  ((Wall)doc.GetElement(wallTypeInput.Id)).WallType.Name.ToString(),
                                                  ((Level)doc.GetElement(levelInput.Id)).Name.ToString(),
                                                  (wallHeightInput / 12d).ToString()));
                }
            }
        }
Example #21
0
        CurveLoop GetOuterLoopOfRoomFromCreateViaOffset(
            View view,
            IList <IList <BoundarySegment> > sloops)
        {
            Document doc = view.Document;

            CurveLoop      loop = null;
            IList <double> wallthicknessList = new List <double>();

            foreach (IList <BoundarySegment> sloop in sloops)
            {
                loop = new CurveLoop();

                foreach (BoundarySegment s in sloop)
                {
                    loop.Append(s.GetCurve());

                    ElementType type = doc.GetElement(
                        s.ElementId) as ElementType;

                    Element e = doc.GetElement(s.ElementId);

                    double thickness = (e is Wall)
            ? (e as Wall).Width
            : 0; // Room separator; any other exceptions need including??

                    wallthicknessList.Add(thickness
                                          * _wall_width_factor);
                }
                // Skip out after first sloop - ignore
                // rooms with holes and disjunct parts
                break;
            }

            int    n       = loop.Count();
            string slength = string.Join(",",
                                         loop.Select <Curve, string>(
                                             c => c.Length.ToString("#.##")));

            int    m          = wallthicknessList.Count();
            string sthickness = string.Join(",",
                                            wallthicknessList.Select <double, string>(
                                                d => d.ToString("#.##")));

            Debug.Print(
                "{0} curves with lengths {1} and {2} thicknesses {3}",
                n, slength, m, sthickness);

            CreateModelCurves(view, loop);

            bool flip_normal = true;

            XYZ normal = flip_normal ? -XYZ.BasisZ : XYZ.BasisZ;

            CurveLoop room_outer_loop = CurveLoop.CreateViaOffset(
                loop, wallthicknessList, normal);

            CreateModelCurves(view, room_outer_loop);

            //CurveLoop newloop = new CurveLoop();

            //foreach( Curve curve in loop2 )
            //{

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

            //  for( int ip = 0; ip < points.Count - 1; ip++ )
            //  {
            //    Line l = Line.CreateBound(
            //      points[ ip ], points[ ip + 1 ] );

            //    newloop.Append( l );
            //  }
            //}

            return(room_outer_loop);
        }
Example #22
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // get uI document
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            //Get dokument
            Document doc = uidoc.Document;
            // Create levels
            Level level = new FilteredElementCollector(doc)
                          .OfCategory(BuiltInCategory.OST_Levels)
                          .WhereElementIsNotElementType()
                          .Cast <Level>()
                          .First(x => x.Name == "Level 1");
            double cF = 1 / 0.3028;
            XYZ    p1 = new XYZ(0 * cF, 0 * cF, 0 * cF);
            XYZ    p2 = new XYZ(13.135 * cF, 0 * cF, 0 * cF);
            XYZ    p3 = new XYZ(13.135 * cF, 9.135 * cF, 0 * cF);
            XYZ    p4 = new XYZ(0 * cF, 9.135 * cF, 0 * cF);
            Line   l1 = Line.CreateBound(p1, p2);
            Line   l2 = Line.CreateBound(p2, p3);
            Line   l3 = Line.CreateBound(p3, p4);
            Line   l4 = Line.CreateBound(p4, p1);

            List <Curve> curves = new List <Curve>();

            curves.Add(l1);
            curves.Add(l2);
            curves.Add(l3);
            curves.Add(l4);

            // // making a curve in a loop
            CurveLoop crvloop = CurveLoop.Create(curves);
            ////double off = UnitUtils.ConvertFromInternalUnits(120, DisplayUnitType.DUT_MILLIMETERS);
            // // giving the offset
            CurveLoop offcr = CurveLoop.CreateViaOffset(crvloop, 0.1 * cF, new XYZ(0, 0, 1));

            //// creating a curve array object required for method
            CurveArray curArr = new CurveArray();

            foreach (Curve c in offcr)
            {
                //// To put the curves to Currve array
                // //Append adds data to a StringBuilder

                curArr.Append(c);
            }

            try
            {
                using (Transaction trans = new Transaction(doc, "Bungalow"))
                {
                    trans.Start();

                    // for foundation

                    doc.Create.NewFloor(curArr, false);


                    trans.Commit();
                }


                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Example #23
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Microsoft.Office.Interop.Excel.Application xlApp      = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook    xlWorkbook = xlApp.Workbooks.Open(@"D:\WerkStudent\Updated\General_WithOpening");

            Microsoft.Office.Interop.Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[3];
            Microsoft.Office.Interop.Excel.Range     xlRange     = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            //Get UI document
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            //Get document
            Document doc = uidoc.Document;

            string level = (String)xlRange.Cells[3, "A"].Value2;
            //Create levels
            Level levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels)
                           .WhereElementIsNotElementType().Cast <Level>().First(x => x.Name == level);

            string ty1 = (String)xlRange.Cells[2, "A"].Value2;

            var FloorType = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Floors)
                            .WhereElementIsElementType().Cast <FloorType>().First(x => x.Name == ty1);

            //string ty2 = (String)xlRange.Cells[2, "B"].Value2;
            ////var opening =sourceFloor.Document.Create.NewOpening(destFloor,openingCurveArray,true);
            //var Opening = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_FloorOpening)
            //    .WhereElementIsElementType().Cast<Opening>();



            double p01x = xlRange.Cells[4, "B"].value2;
            double p01y = xlRange.Cells[4, "C"].value2;
            double p01z = xlRange.Cells[4, "D"].value2;

            double p02x = xlRange.Cells[5, "B"].value2;
            double p02y = xlRange.Cells[5, "C"].value2;
            double p02z = xlRange.Cells[5, "D"].value2;

            double p03x = xlRange.Cells[6, "B"].value2;
            double p03y = xlRange.Cells[6, "C"].value2;
            double p03z = xlRange.Cells[6, "D"].value2;

            double p04x = xlRange.Cells[7, "B"].value2;
            double p04y = xlRange.Cells[7, "C"].value2;
            double p04z = xlRange.Cells[7, "D"].value2;

            double cF  = 1 / 0.3048;
            XYZ    p01 = new XYZ(p01x * cF, p01y * cF, p01z * cF);
            XYZ    p02 = new XYZ(p02x * cF, p02y * cF, p02z * cF);
            XYZ    p03 = new XYZ(p03x * cF, p03y * cF, p03z * cF);
            XYZ    p04 = new XYZ(p04x * cF, p04y * cF, p04z * cF);


            double p11x = xlRange.Cells[9, "B"].value2;
            double p11y = xlRange.Cells[9, "C"].value2;
            double p11z = xlRange.Cells[9, "D"].value2;

            double p12x = xlRange.Cells[10, "B"].value2;
            double p12y = xlRange.Cells[10, "C"].value2;
            double p12z = xlRange.Cells[10, "D"].value2;

            double p13x = xlRange.Cells[11, "B"].value2;
            double p13y = xlRange.Cells[11, "C"].value2;
            double p13z = xlRange.Cells[11, "D"].value2;

            double p14x = xlRange.Cells[12, "B"].value2;
            double p14y = xlRange.Cells[12, "C"].value2;
            double p14z = xlRange.Cells[12, "D"].value2;


            XYZ p11 = new XYZ(p11x * cF, p11y * cF, p11z * cF);
            XYZ p12 = new XYZ(p12x * cF, p12y * cF, p12z * cF);
            XYZ p13 = new XYZ(p13x * cF, p13y * cF, p13z * cF);
            XYZ p14 = new XYZ(p14x * cF, p14y * cF, p14z * cF);

            double pf1x = xlRange.Cells[14, "B"].value2;
            double pf1y = xlRange.Cells[14, "C"].value2;
            double pf1z = xlRange.Cells[14, "D"].value2;

            double pf2x = xlRange.Cells[15, "B"].value2;
            double pf2y = xlRange.Cells[15, "C"].value2;
            double pf2z = xlRange.Cells[15, "D"].value2;

            double pf3x = xlRange.Cells[16, "B"].value2;
            double pf3y = xlRange.Cells[16, "C"].value2;
            double pf3z = xlRange.Cells[16, "D"].value2;

            double pf4x = xlRange.Cells[17, "B"].value2;
            double pf4y = xlRange.Cells[17, "C"].value2;
            double pf4z = xlRange.Cells[17, "D"].value2;


            XYZ pf1 = new XYZ(pf1x * cF, pf1y * cF, pf1z * cF);
            XYZ pf2 = new XYZ(pf2x * cF, pf2y * cF, pf2z * cF);
            XYZ pf3 = new XYZ(pf3x * cF, pf3y * cF, pf3z * cF);
            XYZ pf4 = new XYZ(pf4x * cF, pf4y * cF, pf4z * cF);

            Line l01 = Line.CreateBound(p01, p02);
            Line l02 = Line.CreateBound(p02, p03);
            Line l03 = Line.CreateBound(p03, p04);
            Line l04 = Line.CreateBound(p04, p01);

            Line l11 = Line.CreateBound(p11, p12);
            Line l12 = Line.CreateBound(p12, p13);
            Line l13 = Line.CreateBound(p13, p14);
            Line l14 = Line.CreateBound(p14, p11);

            Line lf1 = Line.CreateBound(pf1, pf2);
            Line lf2 = Line.CreateBound(pf2, pf3);
            Line lf3 = Line.CreateBound(pf3, pf4);
            Line lf4 = Line.CreateBound(pf4, pf1);

            List <Curve> curves = new List <Curve>();

            curves.Add(l01);
            curves.Add(l02);
            curves.Add(l03);
            curves.Add(l04);

            List <Curve> curves1 = new List <Curve>();

            curves1.Add(l11);
            curves1.Add(l12);
            curves1.Add(l13);
            curves1.Add(l14);

            List <Curve> curvesf = new List <Curve>();

            curvesf.Add(lf1);
            curvesf.Add(lf2);
            curvesf.Add(lf3);
            curvesf.Add(lf4);

            // Making a curve in a loop
            CurveLoop crvloop  = CurveLoop.Create(curves);
            CurveLoop crvloop1 = CurveLoop.Create(curves1);
            CurveLoop crvloopf = CurveLoop.Create(curvesf);

            CurveLoop offcr  = CurveLoop.CreateViaOffset(crvloop, 0.1 * cF, new XYZ(0, 0, 1));
            CurveLoop offcr1 = CurveLoop.CreateViaOffset(crvloop1, 0.1 * cF, new XYZ(0, 0, 1));
            CurveLoop offcrf = CurveLoop.CreateViaOffset(crvloopf, 0.1 * cF, new XYZ(0, 0, 1));

            // Creating a curve array object required for method
            CurveArray curArr            = new CurveArray();
            CurveArray curArr1           = new CurveArray();
            CurveArray openingCurveArray = new CurveArray();


            foreach (Curve c in offcr)
            {
                //Put the curves to curve array

                curArr.Append(c);
            }
            foreach (Curve c in offcr1)
            {
                //Put the curves to curve array

                curArr1.Append(c);
            }
            foreach (Curve c in offcrf)
            {
                //Put the curves to curve array

                openingCurveArray.Append(c);
            }

            try
            {
                using (Transaction trans = new Transaction(doc, "Bungalow/Flair110/Flair152RE"))
                {
                    trans.Start();


                    doc.Create.NewFloor(curArr, FloorType, levels, false);
                    //  doc.Create.NewFloor(curArr1, FloorType, levels, false);

                    //////Floor flaw =  doc.Create.NewFloor(curArr,false);
                    //Floor fl = doc.Create.NewFloor(curArr1, FloorType, levels, false);

                    //doc.Create.NewOpening(fl, curArr1, false);


                    //XYZ openingEdges1 = pf1;
                    //XYZ openingEdges2 = pf2;
                    //XYZ openingEdges3 = pf3;
                    //XYZ openingEdges4 = pf4;

                    //var openingEdges = {openingEdges1, openingEdges2, openingEdges3, openingEdges4};

                    //var openingCurveArray = openingEdges;
                    var opening = doc.Create.NewFloor(curArr, FloorType, levels, false);

                    doc.Create.NewOpening(opening, openingCurveArray, true);


                    trans.Commit();
                }
                return(Result.Succeeded);
            }

            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Initialize the result.
            Result result = Result.Succeeded;

            // Get the active ui document.
            UIDocument uIDocument = commandData.Application.ActiveUIDocument;

            // Get the document.
            Document document = uIDocument.Document;

            // Initialize the wall selection filter.
            WallSelectionFilter wallSelectionFilter = new WallSelectionFilter();

            // Prompt the user to select the walls.
            IList <Reference> references = uIDocument.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, wallSelectionFilter);

            if (references != null && references.Count > 0)
            {
                // Initialize the original curves list.
                List <Curve> originalWallCurves = new List <Curve>();

                // Initialize the List of original offset distances.
                List <double> originalOffsets = new List <double>();

                // Initialize the list of levels ids.
                List <ElementId> levelsIds = new List <ElementId>();

                foreach (var r in references)
                {
                    // Get the wall element.
                    Wall wall = document.GetElement(r) as Wall;

                    if (wall != null)
                    {
                        // Add the required offset to the list by dividing the wall width by 2.
                        originalOffsets.Add(wall.Width / 2.0);

                        // Add the wall curve to the original curves list.
                        originalWallCurves.Add((wall.Location as LocationCurve).Curve);

                        // Add wall level id to the levels ids list.
                        levelsIds.Add(wall.LevelId);
                    }
                }

                if (levelsIds.All(lvl => lvl == levelsIds[0]))
                {
                    // Get the contiguous curves with offsets tuple.
                    var contiguousCurvesWithOffsetsTuple = CurveHelper.GetContiguousCurvesWithOffsets(originalWallCurves, originalOffsets);

                    // Get the contiguous curves.
                    List <Curve> contiguousCurves = contiguousCurvesWithOffsetsTuple.curves;

                    // Get the contiguous curves.
                    List <double> contiguousOffsets = contiguousCurvesWithOffsetsTuple.offsets;

                    // Create a curve loop offset to the contiguous curves.
                    CurveLoop floorCurves = CurveLoop.CreateViaOffset(CurveLoop.Create(contiguousCurves), contiguousOffsets, new XYZ(0.0, 0.0, 1.0));

                    // Initialize the curve array.
                    CurveArray curveArray = new CurveArray();

                    // Append the floor curves in the curve array.
                    foreach (var c in floorCurves)
                    {
                        curveArray.Append(c);
                    }

                    // Get the walls level.
                    Level level = document.GetElement(levelsIds[0]) as Level;

                    // Name the floor type.
                    string floorTypeName = "Generic 300mm";

                    // Collect the floor type to be used.
                    FloorType floorType = new FilteredElementCollector(document)
                                          .OfClass(typeof(FloorType))
                                          .First <Element>(
                        e => e.Name.Equals(floorTypeName)) as FloorType;

                    using (Transaction transaction = new Transaction(document, "Create floor from Walls"))
                    {
                        // Start the transaction.
                        transaction.Start();

                        try
                        {
                            // Create the floor.
                            document.Create.NewFloor(curveArray, floorType, level, false);

                            // Commit the transaction and model changes.
                            transaction.Commit();
                        }
                        catch (Exception e)
                        {
                            // Asssign the error message to the message parameter.
                            message = e.Message;

                            // Roll back model changes.
                            transaction.RollBack();

                            // Assign result to be failed.
                            result = Result.Failed;
                        }
                    }
                }
                else
                {
                    // Assign result to be failed.
                    result = Result.Failed;
                }
            }
            else
            {
                // Assign result to be failed.
                result = Result.Failed;
            }

            // Return result.
            return(result);
        }
Example #25
0
        public ViewsCEPRRequest(UIApplication uiApp, String text)
        {
            MainUI     uiForm = BARevitTools.Application.thisApp.newMainUi;
            UIDocument uidoc  = uiApp.ActiveUIDocument;

            //Collect the ViewTypes in the project
            FilteredElementCollector viewTypesCollector = new FilteredElementCollector(uidoc.Document);
            ICollection <Element>    viewTypes          = viewTypesCollector.OfClass(typeof(ViewFamilyType)).ToElements();
            ElementId viewTypeId = null;

            //Cycle through the ViewType elements to find the one with a type name equal to the one selected in the MainUI's combobox
            foreach (ViewFamilyType viewType in viewTypes)
            {
                if (viewType.get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_NAME).AsString() == uiForm.viewsCEPRElevationComboBox.Text)
                {
                    viewTypeId = viewType.Id;
                }
            }

            //If the ViewType was found, and the active view is a plan view, continue
            if (viewTypeId != null && uidoc.ActiveView.GetType().ToString() == "Autodesk.Revit.DB.ViewPlan")
            {
                //Invoke a room selection
                List <Room> selectedRoomElements = RVTOperations.SelectRoomElements(uiApp);

                //If the user selected rooms, continue
                if (selectedRoomElements != null)
                {
                    try
                    {
                        //Cycle through each selected room
                        foreach (Room room in selectedRoomElements)
                        {
                            //First, get the room number for use in generating the elevation view names
                            string roomNumber = room.Number;
                            string roomName   = room.get_Parameter(BuiltInParameter.ROOM_NAME).AsString().ToUpper();
                            //Get the geometry of the room
                            Options geomOptions = new Options();
                            geomOptions.IncludeNonVisibleObjects = true;
                            GeometryElement geomElements = room.get_Geometry(geomOptions);
                            //Get the location point of the room as a point for where to place the elevation marker
                            LocationPoint roomLocation = room.Location as LocationPoint;
                            XYZ           point        = roomLocation.Point;

                            //Start a transaction
                            Transaction t1 = new Transaction(uidoc.Document, "Create Elevations Per Room");
                            t1.Start();
                            try
                            {
                                //Make a new ElevationMarker that uses the ViewType earlier, the location point of the room, and has a view scale of 1/8"
                                ElevationMarker newMarker = ElevationMarker.CreateElevationMarker(uidoc.Document, viewTypeId, point, 96);
                                //Start making views going around the elevation marker where the indexes start on the west side and go clockwise
                                ViewSection view0 = newMarker.CreateElevation(uidoc.Document, uidoc.ActiveView.Id, 0);
                                //Set the view name equal to the room number + room name + plus orientation
                                view0.Name          = roomNumber + " " + roomName + " WEST";
                                view0.CropBoxActive = true;
                                //Repeat for the other view directions at their appropriate index
                                ViewSection view1 = newMarker.CreateElevation(uidoc.Document, uidoc.ActiveView.Id, 1);
                                view1.Name          = roomNumber + " " + roomName + " NORTH";
                                view1.CropBoxActive = true;
                                ViewSection view2 = newMarker.CreateElevation(uidoc.Document, uidoc.ActiveView.Id, 2);
                                view2.Name          = roomNumber + " " + roomName + " EAST";
                                view2.CropBoxActive = true;
                                ViewSection view3 = newMarker.CreateElevation(uidoc.Document, uidoc.ActiveView.Id, 3);
                                view3.Name          = roomNumber + " " + roomName + " SOUTH";
                                view3.CropBoxActive = true;

                                //Make a Solid object for assignment
                                Solid roomSolid = null;
                                //The following section is dedicated to cropping the elevation views to the cross-section of the room geometry
                                if (uiForm.viewsCEPRCropCheckBox.Checked == true)
                                {
                                    //Cycle through the geometry elements associated with the room geometry until the solid is found
                                    foreach (GeometryObject geom in geomElements)
                                    {
                                        if (geom.GetType().ToString() == "Autodesk.Revit.DB.Solid")
                                        {
                                            roomSolid = geom as Solid;
                                            break;
                                        }
                                    }

                                    //Generate 4 planes at the room point that will correspond to each elevation view's cross section of the room geometry
                                    // Each plane's normal vector is in the direction their view is facing
                                    Plane westPlane  = Plane.CreateByNormalAndOrigin(new XYZ(-1, 0, 0), point); //-X vector for West
                                    Plane northPlane = Plane.CreateByNormalAndOrigin(new XYZ(0, 1, 0), point);  //+Y vector for North
                                    Plane eastPlane  = Plane.CreateByNormalAndOrigin(new XYZ(1, 0, 0), point);  //+X vector for East
                                    Plane southPlane = Plane.CreateByNormalAndOrigin(new XYZ(0, -1, 0), point); //-Y vector for South

                                    //Use the room section's perimeter as the crop boundary if the first index of the MainUI combobox is selected
                                    if (uiForm.viewsCEPRCropMethodComboBox.SelectedIndex == 0)
                                    {
                                        try
                                        {
                                            //Generate some CurveLoop lists for use later
                                            IList <CurveLoop> westCurveLoopsFitted  = null;
                                            IList <CurveLoop> northCurveLoopsFitted = null;
                                            IList <CurveLoop> southCurveLoopsFitted = null;
                                            IList <CurveLoop> eastCurveLoopsFitted  = null;

                                            //Slice the room solid with the westPlane object made earlier. This will result in a solid boolean result to the west of the plane because the positive side of the plane faces west
                                            Solid westBooleanSolid = BooleanOperationsUtils.CutWithHalfSpace(roomSolid, westPlane);
                                            //Grab the faces of the solid that resulted from the boolean
                                            FaceArray westBoolSolidFaces = westBooleanSolid.Faces;
                                            //Cycle through each face and get the normal vector
                                            foreach (PlanarFace westFace in westBoolSolidFaces)
                                            {
                                                //For the west elevation face to use as the crop boundary, we need the face that has a vector going east, or the +X vector
                                                XYZ westFaceNormal = westFace.FaceNormal;
                                                if (westFaceNormal.X == 1)
                                                {
                                                    //Get the edges as a CurveLoops once the face is found, then jump out of the loop thorugh the faces
                                                    westCurveLoopsFitted = westFace.GetEdgesAsCurveLoops();
                                                    break;
                                                }
                                            }

                                            //Repeat for the north elevation
                                            Solid     northBooleanSolid   = BooleanOperationsUtils.CutWithHalfSpace(roomSolid, northPlane);
                                            FaceArray northBoolSolidFaces = northBooleanSolid.Faces;
                                            foreach (PlanarFace northFace in northBoolSolidFaces)
                                            {
                                                XYZ northFaceNormal = northFace.FaceNormal;
                                                if (northFaceNormal.Y == -1)
                                                {
                                                    northCurveLoopsFitted = northFace.GetEdgesAsCurveLoops();
                                                    break;
                                                }
                                            }

                                            //Repeat for the east elevation
                                            Solid     eastBooleanSolid   = BooleanOperationsUtils.CutWithHalfSpace(roomSolid, eastPlane);
                                            FaceArray eastBoolSolidFaces = eastBooleanSolid.Faces;
                                            foreach (PlanarFace eastFace in eastBoolSolidFaces)
                                            {
                                                XYZ eastFaceNormal = eastFace.FaceNormal;
                                                if (eastFaceNormal.X == -1)
                                                {
                                                    eastCurveLoopsFitted = eastFace.GetEdgesAsCurveLoops();
                                                    break;
                                                }
                                            }

                                            //Repeat for the south elevation
                                            Solid     southBooleanSolid   = BooleanOperationsUtils.CutWithHalfSpace(roomSolid, southPlane);
                                            FaceArray southBoolSolidFaces = southBooleanSolid.Faces;
                                            foreach (PlanarFace southFace in southBoolSolidFaces)
                                            {
                                                XYZ southFaceNormal = southFace.FaceNormal;
                                                if (southFaceNormal.Y == 1)
                                                {
                                                    southCurveLoopsFitted = southFace.GetEdgesAsCurveLoops();
                                                    break;
                                                }
                                            }

                                            //To get the CurveLoop fitted 0.5" offset to the boundary of the face retrieved, create a CurveLoop via an offset
                                            //Now, the original curve loop was drawn on a plane with a +X axis vector normal, so the offset must be made in the positive X axis plane as well
                                            CurveLoop offsetWestCurveLoopFitted = CurveLoop.CreateViaOffset(westCurveLoopsFitted[0], (0.5d / 12), XYZ.BasisX);
                                            ViewCropRegionShapeManager westCropRegionShapeManager = view0.GetCropRegionShapeManager();
                                            westCropRegionShapeManager.SetCropShape(offsetWestCurveLoopFitted);

                                            //Repeat for the north CurveLoop
                                            //Note that because the plane has a -Y vector, the offset needs to be negative too
                                            CurveLoop offsetNorthCurveLoopFitted = CurveLoop.CreateViaOffset(northCurveLoopsFitted[0], -(0.5d / 12), XYZ.BasisY);;
                                            ViewCropRegionShapeManager northCropRegionShapeManager = view1.GetCropRegionShapeManager();
                                            northCropRegionShapeManager.SetCropShape(offsetNorthCurveLoopFitted);

                                            //Repeat for the east CurveLoop
                                            CurveLoop offsetEastCurveLoopFitted = CurveLoop.CreateViaOffset(eastCurveLoopsFitted[0], -(0.5d / 12), XYZ.BasisX);;
                                            ViewCropRegionShapeManager eastCropRegionShapeManager = view2.GetCropRegionShapeManager();
                                            eastCropRegionShapeManager.SetCropShape(offsetEastCurveLoopFitted);

                                            //Repeat for the south CurveLoop
                                            CurveLoop offsetSouthCurveLoopFitted = CurveLoop.CreateViaOffset(southCurveLoopsFitted[0], (0.5d / 12), XYZ.BasisY);;
                                            ViewCropRegionShapeManager southCropRegionShapeManager = view3.GetCropRegionShapeManager();
                                            southCropRegionShapeManager.SetCropShape(offsetSouthCurveLoopFitted);
                                        }
                                        catch (Exception e)
                                        {
                                            MessageBox.Show(e.ToString());
                                        }
                                    }

                                    //Use the room section's rectangular extents as the crop boundary if the second index was selected for the MainUI combobox
                                    if (uiForm.viewsCEPRCropMethodComboBox.SelectedIndex == 1)
                                    {
                                        try
                                        {
                                            //Create some CurveLoop lists to use later
                                            IList <CurveLoop> westCurveLoopsRectangular  = null;
                                            IList <CurveLoop> northCurveLoopsRectangular = null;
                                            IList <CurveLoop> southCurveLoopsRectangular = null;
                                            IList <CurveLoop> eastCurveLoopsRectangular  = null;

                                            //To get a rectangular cross section of a non-rectangular room cross section, we need to generate a bounding box for the room, then make a solid from the bounding box
                                            //Get the bounding box of the room
                                            BoundingBoxXYZ roomBBox = roomSolid.GetBoundingBox();
                                            //Use the minimum and maximum points of the bounding box to get the 4 points along the bottom of the bounding box
                                            XYZ pt0 = new XYZ(roomBBox.Min.X, roomBBox.Min.Y, roomBBox.Min.Z);
                                            XYZ pt1 = new XYZ(roomBBox.Max.X, roomBBox.Min.Y, roomBBox.Min.Z);
                                            XYZ pt2 = new XYZ(roomBBox.Max.X, roomBBox.Max.Y, roomBBox.Min.Z);
                                            XYZ pt3 = new XYZ(roomBBox.Min.X, roomBBox.Max.Y, roomBBox.Min.Z);
                                            //Generate perimeter lines for the bottom of the bounding box points
                                            Line edge0 = Line.CreateBound(pt0, pt1);
                                            Line edge1 = Line.CreateBound(pt1, pt2);
                                            Line edge2 = Line.CreateBound(pt2, pt3);
                                            Line edge3 = Line.CreateBound(pt3, pt0);
                                            //Make a list of curves out of the edges
                                            List <Curve> edges = new List <Curve>();
                                            edges.Add(edge0);
                                            edges.Add(edge1);
                                            edges.Add(edge2);
                                            edges.Add(edge3);
                                            //Use the curves to make a CurveLoop list
                                            List <CurveLoop> loops = new List <CurveLoop>();
                                            loops.Add(CurveLoop.Create(edges));
                                            //Generate a solid from an extrusion that uses the CurveLoops extruded upward a height equal to the the height of the bounding box
                                            Solid initialSolidBBox = GeometryCreationUtilities.CreateExtrusionGeometry(loops, XYZ.BasisZ, (roomBBox.Max.Z - roomBBox.Min.Z));
                                            //Create a transformed solid box from the previously created box moved to where the room bounding box is located
                                            Solid roomSolidBBox = SolidUtils.CreateTransformed(initialSolidBBox, roomBBox.Transform);

                                            //Cut the solid box with the west plane created earlier and get the faces
                                            Solid     westBooleanSolidBBox   = BooleanOperationsUtils.CutWithHalfSpace(roomSolidBBox, westPlane);
                                            FaceArray westBoolSolidFacesBBox = westBooleanSolidBBox.Faces;
                                            foreach (PlanarFace westFace in westBoolSolidFacesBBox)
                                            {
                                                //As with the earlier code for a fitted crop, get the face with a positive X normal
                                                XYZ westFaceNormal = westFace.FaceNormal;
                                                if (westFaceNormal.X == 1)
                                                {
                                                    //Obtain the edges of the face
                                                    westCurveLoopsRectangular = westFace.GetEdgesAsCurveLoops();
                                                    break;
                                                }
                                            }

                                            //Repeat for the north face
                                            Solid     northBooleanSolidBBox   = BooleanOperationsUtils.CutWithHalfSpace(roomSolidBBox, northPlane);
                                            FaceArray northBoolSolidFacesBBox = northBooleanSolidBBox.Faces;
                                            foreach (PlanarFace northFace in northBoolSolidFacesBBox)
                                            {
                                                XYZ northFaceNormal = northFace.FaceNormal;
                                                if (northFaceNormal.Y == -1)
                                                {
                                                    northCurveLoopsRectangular = northFace.GetEdgesAsCurveLoops();
                                                    break;
                                                }
                                            }

                                            //Repeat for the east face
                                            Solid     eastBooleanSolidBBox   = BooleanOperationsUtils.CutWithHalfSpace(roomSolidBBox, eastPlane);
                                            FaceArray eastBoolSolidFacesBBox = eastBooleanSolidBBox.Faces;
                                            foreach (PlanarFace eastFace in eastBoolSolidFacesBBox)
                                            {
                                                XYZ eastFaceNormal = eastFace.FaceNormal;
                                                if (eastFaceNormal.X == -1)
                                                {
                                                    eastCurveLoopsRectangular = eastFace.GetEdgesAsCurveLoops();
                                                    break;
                                                }
                                            }

                                            //Repeat for the south face
                                            Solid     southBooleanSolidBBox   = BooleanOperationsUtils.CutWithHalfSpace(roomSolidBBox, southPlane);
                                            FaceArray southBoolSolidFacesBBox = southBooleanSolidBBox.Faces;
                                            foreach (PlanarFace southFace in southBoolSolidFacesBBox)
                                            {
                                                XYZ southFaceNormal = southFace.FaceNormal;
                                                if (southFaceNormal.Y == 1)
                                                {
                                                    southCurveLoopsRectangular = southFace.GetEdgesAsCurveLoops();
                                                    break;
                                                }
                                            }

                                            //As before, get the offset curve from the original curve, but offset by 1'
                                            CurveLoop offsetWestCurveLoopRectangular = CurveLoop.CreateViaOffset(westCurveLoopsRectangular[0], 1, XYZ.BasisX);
                                            ViewCropRegionShapeManager westCropRegionShapeManager = view0.GetCropRegionShapeManager();
                                            westCropRegionShapeManager.SetCropShape(offsetWestCurveLoopRectangular);

                                            //As with the fitted offset curve, the offset for a curve in a plane with a negative vector must also be negative
                                            CurveLoop offsetNorthCurveLoopRectangular = CurveLoop.CreateViaOffset(northCurveLoopsRectangular[0], -1, XYZ.BasisY);
                                            ViewCropRegionShapeManager northCropRegionShapeManager = view1.GetCropRegionShapeManager();
                                            northCropRegionShapeManager.SetCropShape(offsetNorthCurveLoopRectangular);

                                            CurveLoop offsetEastCurveLoopRectangular = CurveLoop.CreateViaOffset(eastCurveLoopsRectangular[0], -1, XYZ.BasisX);
                                            ViewCropRegionShapeManager eastCropRegionShapeManager = view2.GetCropRegionShapeManager();
                                            eastCropRegionShapeManager.SetCropShape(offsetEastCurveLoopRectangular);

                                            CurveLoop offsetSouthCurveLoopRectangular = CurveLoop.CreateViaOffset(southCurveLoopsRectangular[0], 1, XYZ.BasisY);
                                            ViewCropRegionShapeManager southCropRegionShapeManager = view3.GetCropRegionShapeManager();
                                            southCropRegionShapeManager.SetCropShape(offsetSouthCurveLoopRectangular);
                                        }
                                        catch (Exception e)
                                        {
                                            MessageBox.Show(e.ToString());
                                        }
                                    }

                                    //If the user opted to override the crop boundary of the elevations, continue as follows
                                    if (uiForm.viewsCEPROverrideCheckBox.Checked == true)
                                    {
                                        //Make a new OverrideGraphicsSetting to use in the boundary override
                                        OverrideGraphicSettings orgs = new OverrideGraphicSettings();
                                        //Use the solid line pattern
                                        orgs.SetProjectionLinePatternId(LinePatternElement.GetSolidPatternId());
                                        //Set the line weight to the properties value
                                        orgs.SetProjectionLineWeight(Properties.Settings.Default.RevitOverrideInteriorCropWeight);

                                        //Grab all of the viewers, which are the viewport windows, and cycle through them
                                        var viewers = new FilteredElementCollector(uidoc.Document).OfCategory(BuiltInCategory.OST_Viewers);
                                        foreach (Element viewer in viewers)
                                        {
                                            //Get the parameters for the viewer
                                            ParameterSet parameters = viewer.Parameters;
                                            foreach (Parameter parameter in parameters)
                                            {
                                                //Get the View Name parameter
                                                if (parameter.Definition.Name.ToString() == "View Name")
                                                {
                                                    string viewName = parameter.AsString();
                                                    //If the view's view name is the same as the west elvation, continue
                                                    if (viewName == view0.Name)
                                                    {
                                                        //Set the view's override setting using the viewer and the OverrideGraphicsSettings
                                                        Autodesk.Revit.DB.View viewtouse = view0 as Autodesk.Revit.DB.View;
                                                        viewtouse.SetElementOverrides(viewer.Id, orgs);
                                                    }
                                                    //Continue to evaluate for the other view names
                                                    else if (viewName == view1.Name)
                                                    {
                                                        Autodesk.Revit.DB.View viewtouse = view1 as Autodesk.Revit.DB.View;
                                                        viewtouse.SetElementOverrides(viewer.Id, orgs);
                                                    }
                                                    else if (viewName == view2.Name)
                                                    {
                                                        Autodesk.Revit.DB.View viewtouse = view2 as Autodesk.Revit.DB.View;
                                                        viewtouse.SetElementOverrides(viewer.Id, orgs);
                                                    }
                                                    else if (viewName == view3.Name)
                                                    {
                                                        Autodesk.Revit.DB.View viewtouse = view3 as Autodesk.Revit.DB.View;
                                                        viewtouse.SetElementOverrides(viewer.Id, orgs);
                                                    }
                                                    else
                                                    {
                                                        //If the view's name is not one of the create elevation views, skip it
                                                        continue;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                t1.Commit();
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(e.ToString());
                                t1.RollBack();
                            }
                            t1.Dispose();
                        }
                    }
                    catch
                    {
                        //If the user did not select any room tags or room elements, then report that
                        MessageBox.Show("No rooms were selected");
                    }
                }
            }
            else if (uidoc.ActiveView.GetType().ToString() != "Autodesk.Revit.DB.ViewPlan")
            {
                //If the user tried to run this outside a plan view, report it
                MessageBox.Show("Please run from a plan view");
            }
            else
            {
                //If the user did not select an elevation type, report it
                MessageBox.Show("No elevation type selected");
            }
        }
Example #26
0
        Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uiDoc.Document;

            TaskDialog.Show("选择", "请选择柱");
            Selection se = uiDoc.Selection;
            FaceArray faces;

            if (se == null)
            {
                TaskDialog.Show("选择", "未进行选择");
                return(Result.Failed);
            }
            else
            {
                Reference re  = se.PickObject(ObjectType.Element);
                Element   col = doc.GetElement(re);
                faces = GetFaceArray(col);
            }
            Face bottomFace = null;

            if (faces != null)
            {
                //取得底面
                foreach (Face face in faces)
                {
                    if (face.ComputeNormal(new UV()).Z == -1)//判断法向量 z=1
                    {
                        if (bottomFace == null)
                        {
                            bottomFace = face;
                        }
                        else
                        {
                            if (bottomFace.EdgeLoops.get_Item(0).get_Item(0).AsCurve().GetEndPoint(0).Z > face.EdgeLoops.get_Item(0).get_Item(0).AsCurve().GetEndPoint(0).Z)
                            {
                                bottomFace = face;
                            }
                        }
                    }
                }
            }
            IList <CurveLoop> bottomEdgesCurveLoop = bottomFace.GetEdgesAsCurveLoops();
            //底面点集合
            List <XYZ> bottumPoint = new List <XYZ>();
            //底面CurveLoop
            CurveLoop bottumCurveLoop = bottomEdgesCurveLoop[0];
            //通过偏移得到模板线
            CurveLoop formWorkCurveLoop = CurveLoop.CreateViaOffset(bottumCurveLoop, 0.0590551, new XYZ(0, 0, -1));

            using (Transaction transaction = new Transaction(doc, "start"))
            {
                transaction.Start();
                foreach (Curve curve in formWorkCurveLoop)
                {
                    Wall wall = Wall.Create(doc, curve, new ElementId(311), true);
                }
                transaction.Commit();
            }


            ///下面这些是通过获得点来计算模板轮廓的算法尸体

            //foreach (Curve curve in bottumCurveLoop)
            //{
            //    bottumPoint.Add(curve.GetEndPoint(0));
            //}
            //double cX = 0, cY = 0, cZ = 0;
            //foreach(XYZ xYZ in bottumPoint)
            //{
            //    cX += xYZ.X;
            //    cY += xYZ.Y;
            //    cZ += xYZ.Z;
            //}
            //EdgeArray bottomEdges = bottomFace.EdgeLoops.get_Item(0);
            //double cX = 0, cY = 0, cZ = 0;
            //if (bottomEdges.Size == 4)
            //{
            //    foreach(Edge edge in bottomEdges)
            //    {
            //        cX = cX + edge.AsCurve().GetEndPoint(0).X;
            //        cY = cY + edge.AsCurve().GetEndPoint(0).Y;
            //        cZ = cZ + edge.AsCurve().GetEndPoint(0).Z;
            //        cX = cX + edge.AsCurve().GetEndPoint(1).X;
            //        cY = cY + edge.AsCurve().GetEndPoint(1).Y;
            //        cZ = cZ + edge.AsCurve().GetEndPoint(1).Z;
            //    }

            //}
            //XYZ centerPoint = new XYZ(cX / 4, cY / 4, cZ / 4);
            ///上面这些是通过获得点来计算模板轮廓的算法尸体

            return(Result.Succeeded);
        }