public XYZ GetViewSectionNormal(Document doc, ElevationMarker marker)
        {
            ViewSection elevViewSection = (ViewSection)doc.GetElement(marker.GetViewId(0));

            double[][] transform = Matrix.transform2matrix(elevViewSection.CropBox.Transform);


            XYZ cbMinT = Matrix.matrix2xyz(Matrix.dot(transform, Matrix.xyz2matrix(elevViewSection.CropBox.Min)));
            XYZ cbMaxT = Matrix.matrix2xyz(Matrix.dot(transform, Matrix.xyz2matrix(elevViewSection.CropBox.Max)));

            XYZ elevViewSectionCoordEndPoint1 = new XYZ(
                cbMinT.X,
                cbMinT.Y,
                cbMaxT.Z);

            XYZ elevViewSectionCoordEndPoint2 = new XYZ(
                cbMinT.X,
                cbMinT.Y,
                cbMinT.Z);

            double[][] inverse = Matrix.invert(transform);
            XYZ        cbEP1   = Matrix.matrix2xyz(Matrix.dot(inverse, Matrix.xyz2matrix(elevViewSectionCoordEndPoint1)));
            XYZ        cbEP2   = Matrix.matrix2xyz(Matrix.dot(inverse, Matrix.xyz2matrix(elevViewSectionCoordEndPoint2)));
            // these points are already in the model coordiante system so no need to translate

            XYZ elevViewSectionNormal = cbEP2.Subtract(cbEP1);

            return(elevViewSectionNormal);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument UIdoc = commandData.Application.ActiveUIDocument;
            Document   doc   = UIdoc.Document;

            this.application = commandData.Application.Application;
            //rewrite method to allow for user selection of walls in model
            List <Wall> wallsToUse = ExtWalls(doc);

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Place Elevations");

                foreach (Wall w in wallsToUse)
                {
                    BoundingBoxXYZ wbb = w.get_BoundingBox(null);
                    using (ElevationMarker marker = PlaceMarker(doc, wbb, w))
                    {
                        RotateMarker(doc, w, marker);
                    }

                    //create elevation view facing wall
                    //set elevation view crop box to that of wall
                    //option to hide everything except for the curtain wall
                    //option to hide elevaion marker in view? maybe put on workset
                }

                tx.Commit();
            }

            return(Result.Succeeded);
        }
        public void SetCropBox(Document doc, ElevationMarker marker, Wall w)
        {
            ViewSection    extElev = (ViewSection)doc.GetElement(marker.GetViewId(0));
            BoundingBoxXYZ eecb    = extElev.CropBox;

            XYZ cbboundsmin = extElev.CropBox.Min;
            XYZ cbboundsmax = extElev.CropBox.Max;

            LocationCurve wallCurve = w.Location as LocationCurve;
            XYZ           wmin      = wallCurve.Curve.GetEndPoint(0);
            XYZ           wallEP2   = wallCurve.Curve.GetEndPoint(1);

            Parameter wallHeight = w.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);
            XYZ       wmax       = new XYZ
                                   (
                wallEP2.X,
                wallEP2.Y,
                wallEP2.Z + wallHeight.AsDouble()
                                   );

            double[][] transform    = Matrix.transform2matrix(eecb.Transform);
            double[][] transformInv = Matrix.invert(transform);

            double[] wMinMatrix  = Matrix.xyz2matrix(wmin);
            double[] wMinTMatrix = Matrix.dot(transform, wMinMatrix);
            XYZ      wMinT       = Matrix.matrix2xyz(wMinTMatrix);

            double[] wMaxMatrix  = Matrix.xyz2matrix(wmax);
            double[] wMaxTMatrix = Matrix.dot(transform, wMaxMatrix);
            XYZ      wMaxT       = Matrix.matrix2xyz(wMaxTMatrix);


            double[] originMatrix  = Matrix.xyz2matrix(eecb.Transform.Origin);
            double[] originTMatrix = Matrix.dot(transform, originMatrix);
            XYZ      originT       = Matrix.matrix2xyz(originTMatrix);

            XYZ wMinTOrdered;
            XYZ wMaxTOrdered;

            Utility.ReorderMinMax(wMinT, wMaxT, out wMinTOrdered, out wMaxTOrdered);

            XYZ wbbboundsmin = new XYZ(
                wMinTOrdered.X - originT.X,
                wMinTOrdered.Y - originT.Y,
                cbboundsmin.Z
                );
            XYZ wbbboundsmax = new XYZ(
                wMaxTOrdered.X - originT.X,
                wMaxTOrdered.Y - originT.Y - 0.01,
                cbboundsmax.Z
                );

            eecb.set_Bounds(0, wbbboundsmin);
            eecb.set_Bounds(1, wbbboundsmax);

            extElev.CropBox        = eecb;
            extElev.CropBoxVisible = false;
        }
        public void RotateMarker(ElevationMarker marker, double angleViewtoWall, XYZ elevMarkerPosition)
        {
            marker.get_BoundingBox(null);

            Line rotationAxis = Line.CreateBound(
                new XYZ(elevMarkerPosition.X, elevMarkerPosition.Y, elevMarkerPosition.Z),
                new XYZ(elevMarkerPosition.X, elevMarkerPosition.Y, elevMarkerPosition.Z + 10)
                );

            marker.Location.Rotate(rotationAxis, angleViewtoWall);
        }
        /// <summary>
        /// Function to create view elevation
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="marker"></param>
        /// <param name="floorPlan"></param>
        /// <param name="i"></param>
        /// <param name="viewTemplate"></param>
        /// <param name="annoCategories"></param>
        /// <returns></returns>
        public static View CreateViewElevation(Document doc, ElevationMarker marker, View floorPlan, int i,
                                               View viewTemplate, List <ElementId> annoCategories)
        {
            // Create view elevation
            View view = marker.CreateElevation(doc, floorPlan.Id, i);

            view.ViewTemplateId = viewTemplate.Id;

            // Hide annotation categories to reduce viewport outline to minimum size
            // This allows labels to align to the base
            view.HideCategoriesTemporary(annoCategories);

            // Regenerate document to pick view scale for title
            doc.Regenerate();

            return(view);
        }
Exemple #6
0
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        UIApplication uiApp = commandData.Application;
        UIDocument    uiDoc = uiApp.ActiveUIDocument;
        Document      doc   = uiDoc.Document;
        Selection     sel   = uiApp.ActiveUIDocument.Selection;

        //pick a point
        XYZ  point = sel.PickPoint("pick a point inside a room");
        Room room  = doc.GetRoomAtPoint(point);
        SpatialElementBoundaryOptions    options    = new SpatialElementBoundaryOptions();
        IList <IList <BoundarySegment> > boundaries = room.GetBoundarySegments(options);



        //create wall section view
        ViewFamilyType vftElevation = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault <ViewFamilyType>(x => ViewFamily.Elevation == x.ViewFamily);
        ViewFamilyType vftSection   = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault <ViewFamilyType>(x => ViewFamily.Section == x.ViewFamily);

        using (Transaction tx = new Transaction(doc)) {
            tx.Start("create wall section view");

            for (int i = 0; i < boundaries.Count; i++)
            {
                for (int j = 0; j < boundaries[i].Count; j++)
                {
                    Wall           wall0   = boundaries[i][j].Element as Wall;
                    BoundingBoxXYZ section = getSectionVewParallelToWall(wall0);

                    ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, vftElevation.Id, point, 96);


                    //ViewPlan viewPlan = ViewPlan.Create(doc, , wall0.LevelId);
                    //viewPlan.CropBox = section;
                    ViewSection.CreateSection(doc, vftSection.Id, section);
                }
            }



            tx.Commit();
        }
        return(Result.Succeeded);
    }
        public void PlaceElevations(Document doc, XYZ center, ViewPlan intElevPlan)
        {
            //current scale set to 1/8"
            ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, FindFamilyTypeId(doc), center, 96);
            Parameter       p      = intElevPlan.get_Parameter(BuiltInParameter.VIEW_PHASE);

            marker.get_Parameter(BuiltInParameter.PHASE_CREATED).Set(p.AsElementId());

            for (int markerindex = 0; markerindex < marker.MaximumViewCount; markerindex++)
            {
                Debug($"Writing marker at {markerindex}");
                if (marker.IsAvailableIndex(markerindex))
                {
                    Debug($"Writing market to plan {intElevPlan.Name}");
                    ViewSection intElev = marker.CreateElevation(doc, intElevPlan.Id, markerindex);
                    intElev.get_Parameter(BuiltInParameter.VIEW_PHASE).Set(p.AsElementId());
                }
            }
        }
        /// <summary>
        /// Places interior elevation makers and inter elevation views for the room
        /// </summary>
        /// <param name="doc">UI Document</param>
        /// <param name="center">coordinate where marker will be placed</param>
        /// <param name="intElevPlan">the plan in which the marker will be visible</param>
        /// <param name="selectedFamilyType">user selected view family type</param>
        /// <param name="scale">user selected scale for interior elevations</param>
        /// <returns>a list of the interior elevations created</returns>
        public List <ViewSection> PlaceElevations(Document doc, XYZ center, ViewPlan intElevPlan, ElementId selectedFamilyType, int scale, out ElevationMarker marker)
        {
            marker = ElevationMarker.CreateElevationMarker(doc, selectedFamilyType, center, scale);
            Parameter p = intElevPlan.get_Parameter(BuiltInParameter.VIEW_PHASE);

            marker.get_Parameter(BuiltInParameter.PHASE_CREATED).Set(p.AsElementId());
            List <ViewSection> intElevList = new List <ViewSection>();

            for (int markerindex = 0; markerindex < marker.MaximumViewCount; markerindex++)
            {
                if (marker.IsAvailableIndex(markerindex))
                {
                    ViewSection intElev = marker.CreateElevation(doc, intElevPlan.Id, markerindex);
                    intElev.get_Parameter(BuiltInParameter.VIEW_PHASE).Set(p.AsElementId());
                    intElevList.Add(intElev);
                }
            }

            return(intElevList);
        }
        public bool RotateMarker(ElevationMarker marker, XYZ markerPoint, double angle)
        {
            bool rotated = false;

            try
            {
                XYZ point1 = markerPoint;
                XYZ point2 = new XYZ(markerPoint.X, markerPoint.Y, markerPoint.Z + 10);

                Line axis = Line.CreateBound(point1, point2);

                ElementTransformUtils.RotateElement(m_doc, marker.Id, axis, angle);
                rotated = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to rotate the elevation marker.\n" + ex.Message, "Elevation Creator: RotateMarker", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

            return(rotated);
        }
Exemple #10
0
        public List <ViewSection> PlaceElevations(Document doc, XYZ center, ViewPlan intElevPlan)
        {
            //add pop up to input scale
            //current scale set to 1/8"
            ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, FindFamilyTypeId(doc), center, 96);
            Parameter       p      = intElevPlan.get_Parameter(BuiltInParameter.VIEW_PHASE);

            marker.get_Parameter(BuiltInParameter.PHASE_CREATED).Set(p.AsElementId());
            List <ViewSection> intElevList = new List <ViewSection>();

            for (int markerindex = 0; markerindex < marker.MaximumViewCount; markerindex++)
            {
                if (marker.IsAvailableIndex(markerindex))
                {
                    ViewSection intElev = marker.CreateElevation(doc, intElevPlan.Id, markerindex);
                    intElev.get_Parameter(BuiltInParameter.VIEW_PHASE).Set(p.AsElementId());
                    intElevList.Add(intElev);
                }
            }

            return(intElevList);
        }
        public ElevationMarker PlaceMarker(Document doc, XYZ elevMarkerPosition, Wall w)
        {
            ViewPlan  plan = DocumentElevPlanViews(doc, w);
            Parameter p    = plan.get_Parameter(BuiltInParameter.VIEW_PHASE);
            //ElementId[] toHide = new ElementId[1];

            //change scale to user input
            ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, FindFamilyTypeId(doc), elevMarkerPosition, 96);

            marker.get_Parameter(BuiltInParameter.PHASE_CREATED).Set(p.AsElementId());
            //toHide[0] = marker.Id;

            //move this back into the if statement when code works

            if (marker.IsAvailableIndex(0))
            {
                ViewSection extElev = marker.CreateElevation(doc, plan.Id, 0);
                extElev.get_Parameter(BuiltInParameter.VIEW_PHASE).Set(p.AsElementId());
            }

            return(marker);
        }
Exemple #12
0
        public void setup_elevation_markers(Document doc)
        {
            Transaction trans = new Transaction(doc);
            FilteredElementCollector levels_col
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(ElevationMarker));

            while (levels_col.Count() > 0)
            {
                ElevationMarker m = levels_col.Last() as ElevationMarker;
                using (trans = new Transaction(doc))
                {
                    trans.Start("elevation markers");
                    doc.Delete(m.Id);
                    trans.Commit();
                }
            }

            ViewFamilyType vft = new FilteredElementCollector(doc)
                                 .OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>()
                                 .FirstOrDefault <ViewFamilyType>(a => ViewFamily.Elevation == a.ViewFamily);

            XYZ center = new XYZ(60, 10, 0);
            // FIXME : select the Floor plan/Site view
            View view = doc.ActiveView;

            using (trans = new Transaction(doc))
            {
                trans.Start("elevation views");
                ElevationMarker marker        = ElevationMarker.CreateElevationMarker(doc, vft.Id, center, 50);
                ViewSection     elevationView = marker.CreateElevation(doc, view.Id, 0);
                Parameter       p             = elevationView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR);
                p.Set(300.0);
                trans.Commit();
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument UIdoc = commandData.Application.ActiveUIDocument;
            Document   doc   = UIdoc.Document;

            this.application = commandData.Application.Application;

            Debug("I got here before construct dialog");
            CreateExteriorElevationInput1 wallSelectionForm = new CreateExteriorElevationInput1(UIdoc);

            Debug("I got here before show dialog");
            wallSelectionForm.ShowDialog();
            Debug($"I got here after show dialog {wallSelectionForm.DialogResult}");

            if (wallSelectionForm.DialogResult != true)
            {
                return(Result.Cancelled);
            }

            Selection         userObjectSelection = UIdoc.Selection;
            IList <Reference> userSelection       = userObjectSelection.PickObjects(ObjectType.Element);

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

            foreach (Reference s in userSelection)
            {
                Element el = UIdoc.Document.GetElement(s.ElementId);
                Wall    w  = el as Wall;

                if (w != null)
                {
                    userWallSelection.Add(w);
                }
            }

            if (0 == userWallSelection.Count)
            {
                //no elements selected
                TaskDialog.Show("Revit", "There are no elements selected.");
            }

            //user wall selction
            List <Wall> wallsToUse = userWallSelection;

            Debug($"Received {wallsToUse.Count} walls");

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Place Elevations");

                foreach (Wall w in wallsToUse)
                {
                    BoundingBoxXYZ wbb = w.get_BoundingBox(null);
                    XYZ            elevMarkerPosition = GetElevationMarkerPosition(w);
                    this.Debug("wall Id" + w.Id);

                    this.Debug("wall LevelId" + w.LevelId);

                    using (ElevationMarker marker = PlaceMarker(doc, elevMarkerPosition, w))
                    {
                        XYZ    elevViewSectionNormal = GetViewSectionNormal(doc, marker);
                        double angleViewtoWall       = GetAngleViewtoWall(elevViewSectionNormal, w);

                        RotateMarker(marker, angleViewtoWall, elevMarkerPosition);

                        SetCropBox(doc, marker, w);
                    }

                    //set view filter
                    //option to hide elevaion marker in view? maybe put on workset
                }

                tx.Commit();
            }

            return(Result.Succeeded);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            // Variables to store user input
            List <int>     selectedIntIds;
            Element        titleBlock;
            View           viewTemplate;
            ViewFamilyType viewFamilyType;
            double         sheetDrawingHeight;
            double         sheetDrawingWidth;

            // Prompt window to collect user input
            using (InteriorElevationsWindow customWindow = new InteriorElevationsWindow(commandData))
            {
                customWindow.ShowDialog();
                selectedIntIds = customWindow.IntegerIds;
                titleBlock     = customWindow.SelectedComboItemTitleBlock.Tag as Element;
                viewTemplate   = customWindow.SelectedComboItemViewTemplate.Tag as View;
                viewFamilyType = customWindow.SelectedComboItemViewType.Tag as ViewFamilyType;

                #region Required elements for this tool

                // No required elements loaded
                if (titleBlock == null && viewTemplate == null && viewFamilyType == null)
                {
                    TaskDialog.Show("Warning", "Please load a Elevation, a Title Block and create a View Template");
                    return(Result.Cancelled);
                }
                // No title block and elevation loaded
                else if (titleBlock == null && viewFamilyType == null)
                {
                    TaskDialog.Show("Warning", "Please load a Elevation and a Title Block");
                    return(Result.Cancelled);
                }
                // No title block and view template
                else if (titleBlock == null && viewTemplate == null)
                {
                    TaskDialog.Show("Warning", "Please load a Title Block and create a View Template");
                    return(Result.Cancelled);
                }
                // No elevation and view template
                else if (viewFamilyType == null && viewTemplate == null)
                {
                    TaskDialog.Show("Warning", "Please load an Elevation and create a View Template");
                    return(Result.Cancelled);
                }
                // No elevation
                else if (viewFamilyType == null)
                {
                    TaskDialog.Show("Warning", "Please load an Elevation");
                    return(Result.Cancelled);
                }
                // No title block
                else if (titleBlock == null)
                {
                    TaskDialog.Show("Warning", "Please load a Title Block");
                    return(Result.Cancelled);
                }
                // No view template
                else if (titleBlock == null)
                {
                    TaskDialog.Show("Warning", "Please create a view template");
                    return(Result.Cancelled);
                }
                #endregion

                // Room selected
                else if (selectedIntIds != null)
                {
                    // Select first plan view
                    FilteredElementCollector floorPlansCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views);
                    View floorPlan = floorPlansCollector.Cast <View>().Where(v =>
                                                                             v.ViewType == ViewType.FloorPlan).Where(v => v.IsTemplate == false).FirstOrDefault();

                    if (floorPlan == null)
                    {
                        TaskDialog.Show("Warning", "Please create a floor plan");
                        return(Result.Cancelled);
                    }

                    // Store rooms with elevations created
                    List <string> roomsSucceeded = new List <string>();

                    // Collect rooms
                    foreach (int id in selectedIntIds)
                    {
                        Room room = doc.GetElement(new ElementId(id)) as Room;

                        // Retrieve boundaries
                        IList <IList <BoundarySegment> > boundaries = Helpers.Helpers.SpatialBoundaries(room);

                        // Check boundaries list is not empty
                        if (boundaries != null)
                        {
                            // Retrieve doc annotation categories
                            var annoCategories = Helpers.Helpers.AnnoCatIds(doc);

                            #region Rectangular rooms without interior boundaries
                            if (boundaries[0].Count == 4 && boundaries.Count == 1 && Helpers.Helpers.IsRectangle(boundaries[0]))
                            {
                                // Transaction
                                Transaction t = new Transaction(doc, "Create Single Marker Interior Elevations");
                                t.Start();

                                List <XYZ> points   = Helpers.Helpers.BoundaPoints(boundaries);
                                XYZ        centroid = Helpers.Helpers.Centroid(points);

                                // Create sheet
                                ViewSheet sheet = Helpers.HelpersView.CreateSheet(doc,
                                                                                  titleBlock.Id,
                                                                                  room.Number + "-" + "INTERIOR ELEVATIONS");

                                // Retrieve title block
                                FamilyInstance tBlock = new FilteredElementCollector(doc, sheet.Id)
                                                        .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                                        .FirstElement() as FamilyInstance;

                                // Retrieve title block size
                                double sheetHeight = tBlock.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble();
                                double sheetWidth  = tBlock.get_Parameter(BuiltInParameter.SHEET_WIDTH).AsDouble();

                                // Center of title block
                                XYZ centerTitleBlock = new XYZ(sheetWidth / 2, sheetHeight / 2, 0);

                                // Create elevation marker
                                ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, viewFamilyType.Id, centroid, viewTemplate.Scale);

                                // Place views on sheet
                                var viewports = new List <Viewport>();

                                for (int i = 0; i < 4; i++)
                                {
                                    // Create elevation
                                    View view = Helpers.HelpersView.CreateViewElevation(doc, marker, floorPlan, i, viewTemplate,
                                                                                        annoCategories);
                                    Helpers.HelpersView.CreateViewport(doc, sheet, ref viewports, view);
                                }

                                // Dictionary to store viewport dimensions
                                var viewportDims = Helpers.HelpersView.ViewportDimensions(viewports);

                                // Retrieve overall dimensions
                                List <double> firstRowX = new List <double>();
                                List <double> firstRowY = new List <double>();

                                List <double> secondRowX = new List <double>();
                                List <double> secondRowY = new List <double>();

                                foreach (KeyValuePair <Viewport, double[]> entry in viewportDims)
                                {
                                    Viewport vp           = entry.Key;
                                    string   detailNumber = vp.get_Parameter(BuiltInParameter.VIEWER_DETAIL_NUMBER).AsString();

                                    if (detailNumber == "1" || detailNumber == "2")
                                    {
                                        firstRowX.Add(entry.Value[0]);
                                        firstRowY.Add(entry.Value[1]);
                                    }
                                    else
                                    {
                                        secondRowX.Add(entry.Value[0]);
                                        secondRowY.Add(entry.Value[1]);
                                    }
                                }

                                // Calculate X spacing
                                double spacingViewX = Helpers.Helpers.MillimetersToFeet(30);
                                double overallX     = spacingViewX;

                                if (firstRowX.Sum() > secondRowX.Sum())
                                {
                                    overallX += firstRowX.Sum();
                                }
                                else
                                {
                                    overallX += secondRowX.Sum();
                                }

                                // Calculate Y spacing
                                double spacingViewY = Helpers.Helpers.MillimetersToFeet(30);
                                double overallY     = spacingViewY;

                                if (firstRowY.Sum() > secondRowY.Sum())
                                {
                                    overallY += firstRowY.Sum();
                                }
                                else
                                {
                                    overallY += secondRowY.Sum();
                                }

                                // Closest and furthest X points
                                double centerTitleBlockX = centerTitleBlock.X;
                                double furthestX         = overallX / 2 + centerTitleBlockX;
                                double closestX          = centerTitleBlockX - overallX / 2;

                                // Closest and furthest Y points
                                double centerTitleBlockY = centerTitleBlock.Y;
                                double furthestY         = overallY / 2 + centerTitleBlockY;
                                double closestY          = centerTitleBlockY - overallY / 2;

                                // Points boundary
                                XYZ lowestRight    = new XYZ(furthestX, closestY, 0);
                                XYZ lowestLeft     = new XYZ(closestX, closestY, 0);
                                XYZ heightestLeft  = new XYZ(closestX, furthestY, 0);
                                XYZ heightestRight = new XYZ(furthestX, furthestY, 0);

                                // Move viewports
                                foreach (Viewport vp in viewports)
                                {
                                    Outline vpOut    = vp.GetBoxOutline();
                                    Outline labelOut = vp.GetLabelOutline();

                                    // Viewport dimensions
                                    XYZ maxPoint = vpOut.MaximumPoint;
                                    XYZ minPoint = vpOut.MinimumPoint;

                                    string detailNumber = vp.get_Parameter(BuiltInParameter.VIEWER_DETAIL_NUMBER).AsString();

                                    if (detailNumber == "4")
                                    {
                                        XYZ lowRightPoint = new XYZ(maxPoint.X, minPoint.Y, 0);
                                        XYZ moveVec       = lowestRight - lowRightPoint;

                                        ElementTransformUtils.MoveElement(doc, vp.Id, moveVec);
                                    }
                                    else if (detailNumber == "3")
                                    {
                                        XYZ lowLeftPoint = new XYZ(minPoint.X, minPoint.Y, 0);
                                        XYZ moveVec      = lowestLeft - lowLeftPoint;

                                        ElementTransformUtils.MoveElement(doc, vp.Id, moveVec);
                                    }
                                    else if (detailNumber == "2")
                                    {
                                        XYZ highRightPoint = new XYZ(maxPoint.X, maxPoint.Y, 0);
                                        XYZ moveVec        = heightestRight - highRightPoint;

                                        ElementTransformUtils.MoveElement(doc, vp.Id, moveVec);
                                    }
                                    else if (detailNumber == "1")
                                    {
                                        XYZ highLeftPoint = new XYZ(minPoint.X, maxPoint.Y, 0);
                                        XYZ moveVec       = heightestLeft - highLeftPoint;

                                        ElementTransformUtils.MoveElement(doc, vp.Id, moveVec);
                                    }
                                }

                                // Append room number to success list
                                roomsSucceeded.Add(room.Number);

                                // Commit transaction
                                t.Commit();
                            }
                            #endregion

                            #region Rest of rooms
                            // When room has more or less than 4 sides
                            else
                            {
                                // Offset distanceof the elevation marker
                                double offsetElevation = Helpers.Helpers.MillimetersToFeet(-1000);
                                // Vector Z
                                XYZ zAxis = new XYZ(0, 0, 1);

                                // Transaction to create single elevations
                                Transaction t2 = new Transaction(doc, "Create single elevations");
                                t2.Start();

                                // Create sheet
                                ViewSheet sheet = Helpers.HelpersView.CreateSheet(doc,
                                                                                  titleBlock.Id,
                                                                                  room.Number + "-" + "INTERIOR ELEVATIONS");

                                // Retrieve title block
                                FamilyInstance tBlock = new FilteredElementCollector(doc, sheet.Id)
                                                        .OfCategory(BuiltInCategory.OST_TitleBlocks)
                                                        .FirstElement() as FamilyInstance;

                                // Retrieve title block size
                                double sheetHeight = tBlock.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble();
                                double sheetWidth  = tBlock.get_Parameter(BuiltInParameter.SHEET_WIDTH).AsDouble();

                                // Store viewports on sheet
                                var viewports = new List <Viewport>();

                                // Loop through each boundary
                                foreach (var boundary in boundaries[0])
                                {
                                    Curve originalCurve = boundary.GetCurve();
                                    Curve offsetCurve   = originalCurve.CreateOffset(offsetElevation, zAxis);

                                    // Curve centers
                                    XYZ origCenter   = (originalCurve.GetEndPoint(0) + originalCurve.GetEndPoint(1)) / 2;
                                    XYZ offsetCenter = (offsetCurve.GetEndPoint(0) + offsetCurve.GetEndPoint(1)) / 2;

                                    // Vector marker to center of original boundary
                                    XYZ vec = origCenter - offsetCenter;

                                    // Create elevation marker
                                    ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, viewFamilyType.Id, offsetCenter, viewTemplate.Scale);

                                    // Calculate rotation angle
                                    double angle = Helpers.Helpers.AngleTwoVectors(new XYZ(0, 100, 0), vec);

                                    // Check the component X of the translated vector to new origin is positive
                                    // this means angle to rotate clockwise
                                    if (angle != 0 && vec.X > 0)
                                    {
                                        angle = angle * -1;
                                    }
                                    else if (angle != 0 && origCenter.X < offsetCenter.X && origCenter.X > 0)
                                    {
                                        // Angle remains the same
                                    }
                                    // Check if rotation needs to be 180 degrees
                                    else if (angle == 0 && origCenter.Y < offsetCenter.Y)
                                    {
                                        angle = Math.PI;
                                    }
                                    // Line along z axis
                                    Line zLine = Line.CreateBound(new XYZ(offsetCenter.X, offsetCenter.Y, offsetCenter.Z), new XYZ(offsetCenter.X, offsetCenter.Y, offsetCenter.Z + 10));

                                    // Create Elevation View as marker needs to have at least one elevation to rotate
                                    View view = Helpers.HelpersView.CreateViewElevation(doc, marker, floorPlan, 1, viewTemplate, annoCategories);

                                    // Rotate in increments as Revit API adds 180 degrees to certain positive angles
                                    if (angle > 0)
                                    {
                                        double angleRemainder = angle;
                                        while (angleRemainder > 0)
                                        {
                                            double rotAngle = 0;
                                            if (angleRemainder > 0.6)
                                            {
                                                rotAngle = 0.6;
                                            }
                                            else
                                            {
                                                rotAngle = angleRemainder;
                                            }

                                            ElementTransformUtils.RotateElement(doc, marker.Id, zLine, rotAngle);

                                            angleRemainder -= rotAngle;
                                        }
                                    }
                                    // Rotate normally
                                    else
                                    {
                                        ElementTransformUtils.RotateElement(doc, marker.Id, zLine, angle);
                                    }

                                    // Retrieve crop shape
                                    ViewCropRegionShapeManager cropShapeManag = view.GetCropRegionShapeManager();
                                    IList <CurveLoop>          cropCurves     = cropShapeManag.GetCropShape();

                                    // Retrieve max and min height
                                    double minHeight = 0;
                                    double maxHeight = 0;

                                    foreach (Curve curve in cropCurves[0])
                                    {
                                        XYZ    point  = curve.GetEndPoint(0);
                                        double height = point.Z;

                                        if (height > maxHeight)
                                        {
                                            maxHeight = height;
                                        }
                                        else if (height < minHeight)
                                        {
                                            minHeight = height;
                                        }
                                    }

                                    // Crop region offset
                                    double topOffset = Helpers.Helpers.MillimetersToFeet(25);

                                    // Create curves for crop region
                                    XYZ bottomStartPoint = offsetCurve.GetEndPoint(0);
                                    XYZ bottomEndPoint   = offsetCurve.GetEndPoint(1);

                                    XYZ startBase = new XYZ(bottomStartPoint.X, bottomStartPoint.Y, bottomStartPoint.Z + minHeight);
                                    XYZ endBase   = new XYZ(bottomEndPoint.X, bottomEndPoint.Y, bottomEndPoint.Z + minHeight);

                                    XYZ startTop = new XYZ(bottomStartPoint.X, bottomStartPoint.Y, bottomStartPoint.Z + maxHeight + topOffset);
                                    XYZ endTop   = new XYZ(bottomEndPoint.X, bottomEndPoint.Y, bottomEndPoint.Z + maxHeight + topOffset);

                                    // Create CurveLoop for new crop shape
                                    List <Curve> curvesNewCrop = new List <Curve>();

                                    // Create contiguous lines
                                    Line sideOne  = Line.CreateBound(startBase, startTop);
                                    Line sideTwo  = Line.CreateBound(endTop, endBase);
                                    Line top      = Line.CreateBound(startTop, endTop);
                                    Line baseLine = Line.CreateBound(endBase, startBase);

                                    // Add the curves in order to the CurveLoop list
                                    curvesNewCrop.Add(baseLine);
                                    curvesNewCrop.Add(sideOne);
                                    curvesNewCrop.Add(top);
                                    curvesNewCrop.Add(sideTwo);

                                    // Apply new crop shape
                                    cropShapeManag.SetCropShape(CurveLoop.Create(curvesNewCrop));
                                    // Update document to reflect new crop shape when placing viewports
                                    doc.Regenerate();

                                    // Create viewports
                                    Helpers.HelpersView.CreateViewport(doc, sheet, ref viewports, view);
                                }

                                // Final viewport translation coordinates
                                sheetDrawingHeight = Helpers.Helpers.MillimetersToFeet(customWindow.SheetDrawingHeight);
                                sheetDrawingWidth  = Helpers.Helpers.MillimetersToFeet(customWindow.SheetDrawingWidth);

                                var viewportDims = Helpers.HelpersView.ViewportDimensions(viewports);
                                var coordinates  = Helpers.HelpersView.ViewportRowsColumns(viewportDims, sheetDrawingWidth, sheetDrawingHeight);

                                for (int i = 0; i < viewports.Count; i++)
                                {
                                    ElementTransformUtils.MoveElement(doc, viewports[i].Id, coordinates[i]);
                                }

                                // Append room number to success list
                                roomsSucceeded.Add(room.Number);

                                // Commit transaction
                                t2.Commit();
                            }
                            #endregion
                        }
                    }

                    #region Display results to user
                    // Display results to user
                    if (roomsSucceeded.Count > 0)
                    {
                        string messageSuccess = string.Join("\n", roomsSucceeded.ToArray());
                        TaskDialog.Show("Success", "The following room elevations have been created: " + "\n" + messageSuccess);
                    }
                    else
                    {
                        TaskDialog.Show("Error", "No room elevations have been created");
                    }
                    #endregion
                }
            }

            return(Result.Succeeded);
        }
Exemple #15
0
        /// <summary>
        /// Nhận vào 2 tham số, trả về null khi tạo 4 mặt đứng bằng instance thuộc lớp ElevationMarker
        /// </summary>
        /// <param name="uiDoc"></param>
        /// <param name="myRoom"></param>
        private void createElevationByRoom(UIDocument uiDoc, Room myRoom)
        {
            // Set active document
            Document doc = uiDoc.Document;

            using (Transaction trans = new Transaction(doc, "add elevation"))
            {
                // Start Transaction
                trans.Start();


                // Get parameter of room
                double myLevel = myRoom.Level.Elevation;

                // Get BoundingBoxXYZ of the room.
                BoundingBoxXYZ myRoomBB = myRoom.get_BoundingBox(null);

                XYZ maxPointBB = myRoomBB.Max;
                XYZ minPointBB = myRoomBB.Min;

                //Set Origin View Point as rooms Location Point
                LocationPoint lcPointRoom = myRoom.Location as LocationPoint;
                XYZ           originPoint = lcPointRoom.Point;

                // Get Center Point of room to make reference Point of views
                XYZ OriginPoint2 = new XYZ((maxPointBB.X + minPointBB.X) / 2, (maxPointBB.Y + minPointBB.Y) / 2, originPoint.Z);

                // second parameter in contructor ElevationMarker
                ViewFamilyType vft = new FilteredElementCollector(doc)
                                     .OfClass(typeof(ViewFamilyType))
                                     .Cast <ViewFamilyType>()
                                     .FirstOrDefault <ViewFamilyType>(x =>
                                                                      ViewFamily.Elevation == x.ViewFamily);

                ElementId myEleId = vft.Id;


                // Create 1 ElevationMaker with scale = 1:40, type View = Elevation
                ElevationMarker myELM = ElevationMarker.CreateElevationMarker(doc, myEleId, originPoint, 40);

                // Set max and Min Elevation of View (axis Y of Section Views), offset = 1 feet;

                double minY = myRoom.Level.Elevation - 1;                           // offset - 1
                double maxY = myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 1; //offset + 1

                for (int i = 0; i < 4; i++)

                {
                    ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);


                    string roomsName = myRoom.Name.Substring(0, myRoom.Name.Length - 1 - myRoom.Number.ToString().Length);

                    elevationView.Name = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();

                    elevationView.CropBoxActive = true;

                    elevationView.DisplayStyle = DisplayStyle.Realistic;

                    BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);
                    if (i == 0)
                    {
                        // Case 1: LeftView
                        myCrop.Min            = new XYZ(myRoomBB.Min.Y - 1, minY, myCrop.Min.Z);
                        myCrop.Max            = new XYZ(myRoomBB.Max.Y + 1, maxY, myCrop.Max.Z);
                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;
                    }
                    else if (i == 1)
                    {
                        //Case 2: Above View
                        myCrop.Min = new XYZ(myRoomBB.Min.X - 1, minY, myCrop.Min.Z);
                        myCrop.Max = new XYZ(myRoomBB.Max.X + 1, maxY, myCrop.Max.Z);

                        elevationView.CropBox = myCrop;

                        // Set visual style	for View
                        elevationView.DisplayStyle = DisplayStyle.HLR;
                    }

                    // Case 3, 4 make OriginPoint2 as reference Point
                    else if (i == 2)
                    {
                        //
                        double XMin = -(Math.Abs(maxPointBB.Y - minPointBB.Y) / 2) - 1;
                        double XMax = +(Math.Abs(maxPointBB.Y - minPointBB.Y) / 2) + 1;

                        myCrop.Min = new XYZ(XMin - OriginPoint2.Y, minY, myCrop.Min.Z);
                        myCrop.Max = new XYZ(myCrop.Min.X + myRoomBB.Max.Y - myRoomBB.Min.Y + 2, maxY, myCrop.Max.Z);

                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;
                    }

                    else
                    {
                        myCrop.Min            = new XYZ(myRoomBB.Min.X - 1 - 2 * (OriginPoint2.X), minY, myCrop.Min.Z);
                        myCrop.Max            = new XYZ(myCrop.Min.X + myRoomBB.Max.X - myRoomBB.Min.X + 2, maxY, myCrop.Max.Z);
                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;
                    }
                }
                trans.Commit();
            }
        }
        /// <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();
            }
        }
        private void createElevationByRoom2(Room myRoom)
        {
            // Set active document
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   doc   = uiDoc.Document;

            // List View Section

            List <ViewSection> myListViewSecton = new List <ViewSection>();

            ElevationMarker myELM = null;

            BoundingBoxXYZ myRoomBB = null;

            XYZ minPointBB = null;
            XYZ maxPointBB = null;

            XYZ minPointBb = null;

            XYZ OriginPoint2 = null;

//			XYZ OriginPoint = null;


            using (Transaction trans0 = new Transaction(doc, "Create a new Elevation Marker"))
            {
                trans0.Start();
                // Show parameter of picked room

                BoundingBoxXYZ roomBounding = myRoom.get_BoundingBox(null);

                minPointBb = roomBounding.Min;

                // Get parameter of room
                double myLevel = myRoom.Level.Elevation;
                myRoomBB = myRoom.get_BoundingBox(null);

                maxPointBB = myRoomBB.Max;
                minPointBB = myRoomBB.Min;

                LocationPoint lcPointRoom = myRoom.Location as LocationPoint;

                XYZ originPoint = lcPointRoom.Point;

                OriginPoint2 = new XYZ((maxPointBB.X + minPointBb.X) / 2, (maxPointBB.Y + minPointBb.Y) / 2, originPoint.Z);

                // second parameter in contructor ElevationMarker
                ViewFamilyType vft = new FilteredElementCollector(doc)
                                     .OfClass(typeof(ViewFamilyType))
                                     .Cast <ViewFamilyType>()
                                     .FirstOrDefault <ViewFamilyType>(x =>
                                                                      ViewFamily.Elevation == x.ViewFamily);

                ElementId myEleId = vft.Id;



                // Tao 1 ElevationMaker
                myELM = ElevationMarker.CreateElevationMarker(doc, myEleId, originPoint, 40);



                myRoomBB.Min = new XYZ(myRoomBB.Min.X, myRoomBB.Min.Y, myRoom.Level.Elevation);
                myRoomBB.Max = new XYZ(myRoomBB.Max.X, myRoomBB.Max.Y, myRoom.Level.Elevation + 1);
                trans0.Commit();
            }

//			string roomsName = myRoom.Name.Substring(0, myRoom.Name.Length - 1 - myRoom.Number.ToString().Length);
            string roomsName = myRoom.Name.ToString();

            for (int i = 0; i < 4; i++)

            {
                if (i == 0)
                {
                    using (Transaction trans1 = new Transaction(doc, "create sec 0"))
                    {
                        trans1.Start();

                        ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);
                        elevationView.Name          = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();
                        elevationView.CropBoxActive = true;
                        BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);

                        myCrop.Min            = new XYZ(myRoomBB.Min.Y - 1, myRoom.Level.Elevation - 1, myCrop.Min.Z);
                        myCrop.Max            = new XYZ(myRoomBB.Max.Y + 1, myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 1, myCrop.Max.Z);
                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;

                        trans1.Commit();

                        //add View to List View
                        myListViewSecton.Add(elevationView);
                    }
                }
                else if (i == 1)
                {
                    using (Transaction trans2 = new Transaction(doc, "create sec 1"))
                    {
                        trans2.Start();
                        ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);
                        elevationView.Name          = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();
                        elevationView.CropBoxActive = true;
                        BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);

                        myCrop.Min = new XYZ(myRoomBB.Min.X - 1, myRoom.Level.Elevation - 1, myCrop.Min.Z);
                        myCrop.Max = new XYZ(myRoomBB.Max.X + 1, myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 1, myCrop.Max.Z);

                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;

                        trans2.Commit();

                        //add View to List View
                        myListViewSecton.Add(elevationView);
                    }
                }

                // mai xu li
                else if (i == 2)
                {
                    using (Transaction trans3 = new Transaction(doc, "create sec 2"))
                    {
                        trans3.Start();
                        ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);
                        elevationView.Name          = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();
                        elevationView.CropBoxActive = true;
                        BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);


                        double XMin = -(Math.Abs(maxPointBB.Y - minPointBb.Y) / 2) - 1;
                        double XMax = +(Math.Abs(maxPointBB.Y - minPointBb.Y) / 2) + 1;

                        myCrop.Min = new XYZ(XMin - OriginPoint2.Y, myRoom.Level.Elevation - 1, myCrop.Min.Z);
                        myCrop.Max = new XYZ(myCrop.Min.X + myRoomBB.Max.Y - myRoomBB.Min.Y + 2, myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 1, myCrop.Max.Z);

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;


                        elevationView.CropBox = myCrop;

                        trans3.Commit();

                        //add View to List View
                        myListViewSecton.Add(elevationView);
                    }
                }

                else
                {
                    using (Transaction trans4 = new Transaction(doc, "create sec 3"))
                    {
                        trans4.Start();
                        ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);
                        elevationView.Name          = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();
                        elevationView.CropBoxActive = true;
                        BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);

                        myCrop.Min            = new XYZ(myRoomBB.Min.X - 1 - 2 * (OriginPoint2.X), myRoom.Level.Elevation - 1, myCrop.Min.Z);
                        myCrop.Max            = new XYZ(myCrop.Min.X + myRoomBB.Max.X - myRoomBB.Min.X + 2, myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 1, myCrop.Max.Z);
                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;

                        trans4.Commit();

                        //add View to List View
                        myListViewSecton.Add(elevationView);
                    }
                }
            }
//			TaskDialog.Show("abc", "my List view create: " + myListViewSecton.Count().ToString());

            foreach (ViewSection mySec in myListViewSecton)
            {
//				using (Transaction trans11 = new Transaction(doc, "Chang style for cropBox"))
//				{
//					trans11.Start();

                setStyleCropBoxFromView(mySec);

//					trans11.Commit();

//				}
            }
        }
Exemple #18
0
        public static List <List <Revit.Elements.Element> > ElevationInRoom(List <Revit.Elements.Room> Rooms, Revit.Elements.Element FloorPlan, double Offset = 500)
        {
            var doc           = DocumentManager.Instance.CurrentDBDocument;
            var vtype         = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(a => a.ViewFamily == ViewFamily.Elevation);
            var ElevationView = new List <List <Revit.Elements.Element> >();

            TransactionManager.Instance.EnsureInTransaction(doc);
            foreach (var r in Rooms)
            {
                var    list      = new List <Revit.Elements.Element>();
                var    elevViews = new List <Revit.Elements.Element>();
                String rname     = r.InternalElement.LookupParameter("Number").AsString() + "_" + r.InternalElement.LookupParameter("Name").AsString();

                LocationPoint   elevPoint = (Autodesk.Revit.DB.LocationPoint)r.InternalElement.Location;
                XYZ             point     = elevPoint.Point;
                BoundingBoxXYZ  bbox      = r.InternalElement.get_BoundingBox(doc.ActiveView);
                ElevationMarker marker    = Autodesk.Revit.DB.ElevationMarker.CreateElevationMarker(doc, vtype.Id, point, 50);

                BoundingBoxXYZ bcrop    = Utility.crop_box(bbox, Offset / 304.8);
                var            surfaces = bcrop.ToProtoType(true).ToPolySurface().Surfaces().Skip(2).Take(4);

                var westElev = marker.CreateElevation(doc, FloorPlan.InternalElement.Id, 0);
                westElev.Name = rname + " - A";
                var westcrsm  = westElev.GetCropRegionShapeManager();
                var west      = surfaces.ElementAt(0).PerimeterCurves();
                var westcurve = new List <Autodesk.Revit.DB.Curve>();
                foreach (var w in west)
                {
                    westcurve.Add(w.ToRevitType(true));
                }
                CurveLoop wcloop = CurveLoop.Create(westcurve);
                westcrsm.SetCropShape(wcloop);

                var northElev = marker.CreateElevation(doc, FloorPlan.InternalElement.Id, 1);
                northElev.Name = rname + " - B";
                var northcrsm  = northElev.GetCropRegionShapeManager();
                var north      = surfaces.ElementAt(1).PerimeterCurves();
                var northcurve = new List <Autodesk.Revit.DB.Curve>();
                foreach (var w in north)
                {
                    northcurve.Add(w.ToRevitType(true));
                }
                CurveLoop ncloop = CurveLoop.Create(northcurve);
                northcrsm.SetCropShape(ncloop);

                var eastElev = marker.CreateElevation(doc, FloorPlan.InternalElement.Id, 2);
                eastElev.Name = rname + " - C";
                var eastcrsm  = eastElev.GetCropRegionShapeManager();
                var east      = surfaces.ElementAt(2).PerimeterCurves();
                var eastcurve = new List <Autodesk.Revit.DB.Curve>();
                foreach (var w in east)
                {
                    eastcurve.Add(w.ToRevitType(true));
                }
                CurveLoop ecloop = CurveLoop.Create(eastcurve);
                eastcrsm.SetCropShape(ecloop);

                var southElev = marker.CreateElevation(doc, FloorPlan.InternalElement.Id, 3);
                southElev.Name = rname + " - D";
                var southcrsm  = southElev.GetCropRegionShapeManager();
                var south      = surfaces.ElementAt(3).PerimeterCurves();
                var southcurve = new List <Autodesk.Revit.DB.Curve>();
                foreach (var w in south)
                {
                    southcurve.Add(w.ToRevitType(true));
                }
                CurveLoop scloop = CurveLoop.Create(southcurve);
                southcrsm.SetCropShape(scloop);

                list.Add(westElev.ToDSType(true));
                list.Add(northElev.ToDSType(true));
                list.Add(eastElev.ToDSType(true));
                list.Add(southElev.ToDSType(true));

                ElevationView.Add(list);
            }
            TransactionManager.Instance.TransactionTaskDone();
            return(ElevationView);
        }
        public bool CreateElevationByWall()
        {
            bool result = false;

            try
            {
                ElevationMarker marker         = null;
                XYZ             markerLocation = null;
                Dictionary <int, ElevationViewProperties> elevationViews = new Dictionary <int, ElevationViewProperties>();
                ApplyTemplateSettings();

                using (Transaction trans = new Transaction(m_doc, "Elevation Creator"))
                {
                    trans.Start();
                    try
                    {
                        BoundingBoxXYZ bbBox = m_room.get_BoundingBox(null);
                        markerLocation = new XYZ(pickPoint.X, pickPoint.Y, bbBox.Min.Z);
                        if (m_room.Document.IsLinked)
                        {
                            var documents = from doc in linkedDocuments.Values where doc.DocumentTitle == m_room.Document.Title select doc;
                            if (documents.Count() > 0)
                            {
                                LinkedInstanceProperties lip = documents.First();
                                roomLink       = lip;
                                markerLocation = lip.TransformValue.OfPoint(markerLocation);
                            }
                        }

                        marker = ElevationMarker.CreateElevationMarker(m_doc, m_viewFamilyTypeId, markerLocation, toolSettings.CustomScale);
                        trans.Commit();

                        if (null != marker)
                        {
                            string prefix           = toolSettings.PrefixText;
                            string intermediateText = GetRoomParameterValue(m_room, toolSettings.IntermediateText);
                            int    elevationIndex   = GetElevationMarkIndex();
                            string suffix           = GetRoomParameterValue(m_room, toolSettings.SuffixText);

                            int viewCount = marker.MaximumViewCount < suffix.Length ? marker.MaximumViewCount : suffix.Length;

                            double rotationalAngle = 0;
                            Dictionary <int, string> indexLabels = GetMarkerLabel(markerLocation, out rotationalAngle);
                            bool firstView = true;
                            foreach (int index in indexLabels.Keys)
                            {
                                if (index < marker.MaximumViewCount)
                                {
                                    trans.Start();
                                    ViewSection viewElevation = marker.CreateElevation(m_doc, m_viewPlan.Id, index);
                                    viewElevation.Name = GetViewName(prefix, intermediateText, elevationIndex, indexLabels[index], suffix);
                                    if (toolSettings.ViewTemplateId != -1)
                                    {
                                        viewElevation.ViewTemplateId = new ElementId(toolSettings.ViewTemplateId);
                                    }

                                    Parameter param = viewElevation.LookupParameter("Title on Sheet");
                                    if (null != param)
                                    {
                                        param.Set(m_room.Name);
                                    }

                                    trans.Commit();

                                    if (firstView && null != viewElevation)
                                    {
                                        trans.Start();
                                        try
                                        {
                                            bool rotated = RotateMarker(marker, markerLocation, rotationalAngle);
                                            firstView = false;
                                            trans.Commit();
                                        }
                                        catch (Exception ex)
                                        {
                                            trans.RollBack();
                                            MessageBox.Show("Failed to rotate the elevation marker.\n" + ex.Message, "Elevation Creator : RotateMarker", MessageBoxButton.OK, MessageBoxImage.Warning);
                                        }
                                    }

                                    ElevationViewProperties viewProperties = new ElevationViewProperties(viewElevation);
                                    viewProperties.WallId = m_wall.Id.IntegerValue;
                                    if (!elevationViews.ContainsKey(viewProperties.ViewId))
                                    {
                                        elevationViews.Add(viewProperties.ViewId, viewProperties);
                                    }
                                }
                            }

                            if (elevationViews.Count > 0 && !roomProperties.ElevationViews.ContainsKey(marker.Id.IntegerValue))
                            {
                                roomProperties.ElevationViews.Add(marker.Id.IntegerValue, elevationViews);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        trans.RollBack();
                        MessageBox.Show("Failed to create an elevation view.\n" + ex.Message, "Create Elevation View", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return(false);
                    }
                }

                if (null != marker && null != markerLocation)
                {
                    if (ModifyCropBox(roomProperties, marker.Id.IntegerValue))
                    {
                        if (ElevationCreatorDataStorageUtil.StoreRoomElevationProperties(m_doc, roomProperties))
                        {
                            //update extensible storage
                            result = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create an elevation view.\nRoom Name: " + m_room.Name + "\nWall Name: " + m_wall.Name + "\n" + ex.Message, "", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(result);
        }
        private void createElevationByRoom(Room myRoom)
        {
            // Set active document
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   doc   = uiDoc.Document;

            // List View Section

//			List<ViewSection> myListViewSecton = null;

            using (Transaction trans = new Transaction(doc, "add elevation"))
            {
                trans.Start();

                // Show parameter of picked room

                BoundingBoxXYZ roomBounding = myRoom.get_BoundingBox(null);

                XYZ minPointBb = roomBounding.Min;


//				TaskDialog.Show("Min point", Math.Round(minPointBb.X,0).ToString() + "," + Math.Round(minPointBb.Y,0).ToString()+"," + minPointBb.Z.ToString());
//				TaskDialog.Show("Max point", Math.Round(minPointBb.X,0).ToString() + "," + Math.Round(minPointBb.Y,0).ToString()+"," + minPointBb.Z.ToString());

                // Get parameter of room
                double         myLevel  = myRoom.Level.Elevation;
                BoundingBoxXYZ myRoomBB = myRoom.get_BoundingBox(null);

                XYZ maxPointBB = myRoomBB.Max;
                XYZ minPointBB = myRoomBB.Min;



//				TaskDialog.Show("abc","Level: " + myLevel.ToString() + "Min: " + minPointBB.ToString());

                LocationPoint lcPointRoom = myRoom.Location as LocationPoint;

                XYZ originPoint = lcPointRoom.Point;

                XYZ OriginPoint2 = new XYZ((maxPointBB.X + minPointBb.X) / 2, (maxPointBB.Y + minPointBb.Y) / 2, originPoint.Z);

                // second parameter in contructor ElevationMarker
                ViewFamilyType vft = new FilteredElementCollector(doc)
                                     .OfClass(typeof(ViewFamilyType))
                                     .Cast <ViewFamilyType>()
                                     .FirstOrDefault <ViewFamilyType>(x =>
                                                                      ViewFamily.Elevation == x.ViewFamily);

                ElementId myEleId = vft.Id;


                // Tao 1 ElevationMaker
                ElevationMarker myELM = ElevationMarker.CreateElevationMarker(doc, myEleId, originPoint, 40);


                myRoomBB.Min = new XYZ(myRoomBB.Min.X, myRoomBB.Min.Y, myRoom.Level.Elevation);
                myRoomBB.Max = new XYZ(myRoomBB.Max.X, myRoomBB.Max.Y, myRoom.Level.Elevation + 1);

//				TaskDialog.Show("Abc", myRoom.Level.Elevation.ToString());

                for (int i = 0; i < 4; i++)

                {
                    ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);

                    string roomsName = myRoom.Name.Substring(0, myRoom.Name.Length - 1 - myRoom.Number.ToString().Length);

                    elevationView.Name = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();
//					TaskDialog.Show("abc", myELM.Name.ToString());
                    elevationView.CropBoxActive = true;

                    // Set style
//					setStyleCropBoxFromView(elevationView);

                    BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);
                    if (i == 0)
                    {
                        myCrop.Min            = new XYZ(myRoomBB.Min.Y - 1, myRoom.Level.Elevation - 0.5, myCrop.Min.Z);
                        myCrop.Max            = new XYZ(myRoomBB.Max.Y + 1, myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 0.5, myCrop.Max.Z);
                        elevationView.CropBox = myCrop;


//						doc.ActiveView.SetElementOverrides(elevationView.Id,ogs);
                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;
                    }
                    else if (i == 1)
                    {
                        myCrop.Min = new XYZ(myRoomBB.Min.X - 1, myRoom.Level.Elevation - 0.5, myCrop.Min.Z);
                        myCrop.Max = new XYZ(myRoomBB.Max.X + 1, myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 0.5, myCrop.Max.Z);

                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;
                    }

                    // mai xu li
                    else if (i == 2)
                    {
                        double XMin = -(Math.Abs(maxPointBB.Y - minPointBb.Y) / 2) - 1;
                        double XMax = +(Math.Abs(maxPointBB.Y - minPointBb.Y) / 2) + 1;

                        myCrop.Min = new XYZ(XMin - OriginPoint2.Y, myRoom.Level.Elevation - 0.5, myCrop.Min.Z);
                        myCrop.Max = new XYZ(myCrop.Min.X + myRoomBB.Max.Y - myRoomBB.Min.Y + 2, myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 0.5, myCrop.Max.Z);

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;


                        elevationView.CropBox = myCrop;
                    }

                    else
                    {
                        myCrop.Min            = new XYZ(myRoomBB.Min.X - 1 - 2 * (OriginPoint2.X), myRoom.Level.Elevation - 0.5, myCrop.Min.Z);
                        myCrop.Max            = new XYZ(myCrop.Min.X + myRoomBB.Max.X - myRoomBB.Min.X + 2, myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 0.5, myCrop.Max.Z);
                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;
                    }
                }
                trans.Commit();
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            using (Transaction transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "Test"))
            {
                try
                {
                    bool isValidSelect = false;
                    do
                    {
                        Reference reference = commandData.Application.ActiveUIDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, "Please select room.");
                        if (reference == null)
                        {
                            TaskDialog.Show("Error", "It is not object!");
                        }
                        else
                        {
                            Element element      = commandData.Application.ActiveUIDocument.Document.GetElement(reference);
                            Room    selectedRoom = element as Room;

                            if (selectedRoom == null)
                            {
                                TaskDialog.Show("Error", "It is not room!");
                            }
                            else
                            {
                                IList <IList <BoundarySegment> > roomSegments = selectedRoom.GetBoundarySegments(new SpatialElementBoundaryOptions {
                                    SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish
                                });
                                Curve curveRight = null;
                                Curve curveLeft  = null;
                                Curve curveUp    = null;
                                Curve curveDown  = null;
                                transaction.Start();
                                foreach (IList <BoundarySegment> segments in roomSegments)
                                {
                                    foreach (BoundarySegment segment in segments)
                                    {
                                        Line    cu   = segment.GetCurve() as Line;
                                        Element e    = commandData.Application.ActiveUIDocument.Document.GetElement(segment.ElementId);
                                        Wall    wall = e as Wall;
                                        if (cu.Direction.X == -1)
                                        {
                                            if (curveUp != null)
                                            {
                                                curveUp = Line.CreateBound(curveUp.GetEndPoint(0), segment.GetCurve().GetEndPoint(1)) as Curve;
                                            }
                                            else
                                            {
                                                curveUp = segment.GetCurve();
                                            }
                                        }
                                        else if (cu.Direction.X == 1)
                                        {
                                            if (curveDown != null)
                                            {
                                                curveDown = Line.CreateBound(curveDown.GetEndPoint(0), segment.GetCurve().GetEndPoint(1)) as Curve;
                                            }
                                            else
                                            {
                                                curveDown = segment.GetCurve();
                                            }
                                        }
                                        else if (cu.Direction.Y == -1)
                                        {
                                            if (curveLeft != null)
                                            {
                                                curveLeft = Line.CreateBound(curveLeft.GetEndPoint(0), segment.GetCurve().GetEndPoint(1)) as Curve;
                                            }
                                            else
                                            {
                                                curveLeft = segment.GetCurve();
                                            }
                                        }
                                        else if (cu.Direction.Y == 1)
                                        {
                                            if (curveRight != null)
                                            {
                                                curveRight = Line.CreateBound(curveRight.GetEndPoint(0), segment.GetCurve().GetEndPoint(1)) as Curve;
                                            }
                                            else
                                            {
                                                curveRight = segment.GetCurve();
                                            }
                                        }
                                    }
                                }

                                IEnumerable <ViewFamilyType> viewFamilyTypes = from elem in new FilteredElementCollector(commandData.Application.ActiveUIDocument.Document).OfClass(typeof(ViewFamilyType))
                                                                               let type = elem as ViewFamilyType
                                                                                          where type.ViewFamily == ViewFamily.Elevation
                                                                                          select type;

                                ElevationMarker markerUp  = ElevationMarker.CreateElevationMarker(commandData.Application.ActiveUIDocument.Document, viewFamilyTypes.FirstOrDefault().Id, new XYZ(curveUp.GetEndPoint(0).X, curveUp.GetEndPoint(0).Y - 1, curveUp.GetEndPoint(0).Z), 1);
                                ViewSection     sectionUp = markerUp.CreateElevation(commandData.Application.ActiveUIDocument.Document, commandData.Application.ActiveUIDocument.Document.ActiveView.Id, 1);
                                sectionUp.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).Set(3);

                                ElevationMarker markerDown  = ElevationMarker.CreateElevationMarker(commandData.Application.ActiveUIDocument.Document, viewFamilyTypes.FirstOrDefault().Id, new XYZ(curveDown.GetEndPoint(0).X, curveDown.GetEndPoint(0).Y + 1, curveDown.GetEndPoint(0).Z), 1);
                                ViewSection     sectionDown = markerDown.CreateElevation(commandData.Application.ActiveUIDocument.Document, commandData.Application.ActiveUIDocument.Document.ActiveView.Id, 3);
                                sectionDown.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).Set(3);

                                ElevationMarker markerLeft  = ElevationMarker.CreateElevationMarker(commandData.Application.ActiveUIDocument.Document, viewFamilyTypes.FirstOrDefault().Id, new XYZ(curveLeft.GetEndPoint(0).X + 1, curveLeft.GetEndPoint(0).Y, curveLeft.GetEndPoint(0).Z), 1);
                                ViewSection     sectionLeft = markerLeft.CreateElevation(commandData.Application.ActiveUIDocument.Document, commandData.Application.ActiveUIDocument.Document.ActiveView.Id, 0);
                                sectionLeft.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).Set(3);

                                ElevationMarker markerRight  = ElevationMarker.CreateElevationMarker(commandData.Application.ActiveUIDocument.Document, viewFamilyTypes.FirstOrDefault().Id, new XYZ(curveRight.GetEndPoint(0).X - 1, curveRight.GetEndPoint(0).Y, curveRight.GetEndPoint(0).Z), 1);
                                ViewSection     sectionRight = markerRight.CreateElevation(commandData.Application.ActiveUIDocument.Document, commandData.Application.ActiveUIDocument.Document.ActiveView.Id, 2);
                                sectionRight.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).Set(3);
                                transaction.Commit();
                                isValidSelect = true;
                            }
                        }
                    } while (!isValidSelect);
                }
                catch (Exception e)
                {
                    return(Result.Failed);
                }
            }
            return(Result.Succeeded);
        }
Exemple #22
0
        /// <summary>
        /// Nhận vào 2 tham số, trả về null khi tạo 4 mặt đứng bằng instance thuộc lớp ElevationMarker
        /// </summary>
        /// <param name="uiDoc"></param>
        /// <param name="myRoom"></param>
        private void createElevationByRoom(UIDocument uiDoc, Room myRoom)
        {
            // Set active document
            Document doc = uiDoc.Document;

            List <ViewSection> myListViewSecton = new List <ViewSection>();

            ElevationMarker myELM = null;

            BoundingBoxXYZ myRoomBB = null;

            XYZ minPointBB = null;
            XYZ maxPointBB = null;

            XYZ minPointBb = null;

            XYZ OriginPoint2 = null;

            double minY = myRoom.Level.Elevation - 1;                           // offset - 1
            double maxY = myRoom.UpperLimit.Elevation + myRoom.LimitOffset + 1; //offset + 1

            using (Transaction trans0 = new Transaction(doc, "add elevation"))
            {
                // Start Transaction
                trans0.Start();

                // Get parameter of room
                double myLevel = myRoom.Level.Elevation;

                // Get BoundingBoxXYZ of the room.
                myRoomBB = myRoom.get_BoundingBox(null);

                maxPointBB = myRoomBB.Max;
                minPointBB = myRoomBB.Min;

                //Set Origin View Point as rooms Location Point
                LocationPoint lcPointRoom = myRoom.Location as LocationPoint;
                XYZ           originPoint = lcPointRoom.Point;

                // Get Center Point of room to make reference Point of views
                OriginPoint2 = new XYZ((maxPointBB.X + minPointBB.X) / 2, (maxPointBB.Y + minPointBB.Y) / 2, originPoint.Z);

                // second parameter in contructor ElevationMarker
                ViewFamilyType vft = new FilteredElementCollector(doc)
                                     .OfClass(typeof(ViewFamilyType))
                                     .Cast <ViewFamilyType>()
                                     .FirstOrDefault <ViewFamilyType>(x =>
                                                                      ViewFamily.Elevation == x.ViewFamily);

                ElementId myEleId = vft.Id;


                // Create 1 ElevationMaker with scale = 1:40, type View = Elevation
                myELM = ElevationMarker.CreateElevationMarker(doc, myEleId, originPoint, 40);

                // Set max and Min Elevation of View (axis Y of Section Views), offset = 1 feet;


                // Commit 1
                trans0.Commit();
            }

            string roomsName = myRoom.Name.ToString();

            for (int i = 0; i < 4; i++)

            {
                #region section0

                if (i == 0)
                {
                    using (Transaction trans1 = new Transaction(doc, "create sec 0"))
                    {
                        trans1.Start();


                        ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);


                        //string roomsName = myRoom.Name.Substring(0, myRoom.Name.Length - 1 - myRoom.Number.ToString().Length);

                        elevationView.Name = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();

                        elevationView.CropBoxActive = true;

                        elevationView.DisplayStyle = DisplayStyle.Realistic;

                        BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);


                        // Case 1: LeftView
                        myCrop.Min            = new XYZ(myRoomBB.Min.Y - 1, minY, myCrop.Min.Z);
                        myCrop.Max            = new XYZ(myRoomBB.Max.Y + 1, maxY, myCrop.Max.Z);
                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;

                        trans1.Commit();
                        //add View to List View
                        myListViewSecton.Add(elevationView);
                    }
                }

                #endregion


                #region section1
                else if (i == 1)
                {
                    using (Transaction trans2 = new Transaction(doc, "create sec 1"))
                    {
                        trans2.Start();

                        ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);


                        //string roomsName = myRoom.Name.Substring(0, myRoom.Name.Length - 1 - myRoom.Number.ToString().Length);

                        elevationView.Name = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();

                        elevationView.CropBoxActive = true;

                        elevationView.DisplayStyle = DisplayStyle.Realistic;

                        BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);

                        //Case 2: Above View
                        myCrop.Min = new XYZ(myRoomBB.Min.X - 1, minY, myCrop.Min.Z);
                        myCrop.Max = new XYZ(myRoomBB.Max.X + 1, maxY, myCrop.Max.Z);

                        elevationView.CropBox = myCrop;

                        // Set visual style	for View
                        elevationView.DisplayStyle = DisplayStyle.HLR;

                        trans2.Commit();
                        //add View to List View
                        myListViewSecton.Add(elevationView);
                    }
                }

                #endregion


                #region section2
                else if (i == 2)
                {
                    using (Transaction trans3 = new Transaction(doc, "create sec 2"))
                    {
                        trans3.Start();


                        ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);


                        //string roomsName = myRoom.Name.Substring(0, myRoom.Name.Length - 1 - myRoom.Number.ToString().Length);

                        elevationView.Name = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();

                        elevationView.CropBoxActive = true;

                        elevationView.DisplayStyle = DisplayStyle.Realistic;

                        BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);


                        //
                        double XMin = -(Math.Abs(maxPointBB.Y - minPointBB.Y) / 2) - 1;
                        double XMax = +(Math.Abs(maxPointBB.Y - minPointBB.Y) / 2) + 1;

                        myCrop.Min = new XYZ(XMin - OriginPoint2.Y, minY, myCrop.Min.Z);
                        myCrop.Max = new XYZ(myCrop.Min.X + myRoomBB.Max.Y - myRoomBB.Min.Y + 2, maxY, myCrop.Max.Z);

                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;

                        trans3.Commit();


                        //add View to List View
                        myListViewSecton.Add(elevationView);
                    }
                }

                #endregion


                #region section3


                else
                {
                    using (Transaction trans4 = new Transaction(doc, "create sec 3"))
                    {
                        trans4.Start();

                        ViewSection elevationView = myELM.CreateElevation(doc, doc.ActiveView.Id, i);


                        //string roomsName = myRoom.Name.Substring(0, myRoom.Name.Length - 1 - myRoom.Number.ToString().Length);

                        elevationView.Name = roomsName.ToUpper() + ", Section ".ToUpper() + i.ToString().ToUpper();

                        elevationView.CropBoxActive = true;

                        elevationView.DisplayStyle = DisplayStyle.Realistic;

                        BoundingBoxXYZ myCrop = elevationView.get_BoundingBox(null);



                        myCrop.Min            = new XYZ(myRoomBB.Min.X - 1 - 2 * (OriginPoint2.X), minY, myCrop.Min.Z);
                        myCrop.Max            = new XYZ(myCrop.Min.X + myRoomBB.Max.X - myRoomBB.Min.X + 2, maxY, myCrop.Max.Z);
                        elevationView.CropBox = myCrop;

                        // Set visual style
                        elevationView.DisplayStyle = DisplayStyle.HLR;

                        trans4.Commit();

                        //add View to List View
                        myListViewSecton.Add(elevationView);
                    }
                }
                #endregion
            }

            #region change setting graphic
            foreach (ViewSection mySec in myListViewSecton)
            {
                setStyleCropBoxFromView(uiDoc, mySec);
            }
            #endregion
        }
        public ElevationMarker PlaceMarker(Document doc, BoundingBoxXYZ wallbb, Wall w)
        {
            XYZ       wallbbmin = wallbb.Min;
            XYZ       wallbbmax = wallbb.Max;
            ViewPlan  plan      = DocumentElevPlanViews(doc);
            Parameter p         = plan.get_Parameter(BuiltInParameter.VIEW_PHASE);
            //Debug("p equals " + p.AsElementId() + " phase called " + p.AsValueString());
            ////Element planPhase = doc.GetElement(p.AsElementId());
            ////Debug("planPhase equals " + planPhase);

            //List<Room> allRooms = RoomHelpers.GetAllRooms(doc);
            //foreach(Room room in allRooms)
            //{
            //    //Parameter roomPhase = room.get_Parameter(BuiltInParameter.VIEW_PHASE);
            //    //Debug("Room Phase View Phase " + room.Name + " - " + roomPhase + " (" + roomPhase.AsValueString() + ")");

            //    Parameter roomPhase2 = room.get_Parameter(BuiltInParameter.PHASE_CREATED);
            //    Debug("Room Phase Phase Created " + room.Name + " - " + roomPhase2.AsElementId().ToString() + " (" + roomPhase2.AsValueString() + ")");

            //    Parameter roomPhase3 = room.get_Parameter(BuiltInParameter.ROOM_PHASE);
            //    Debug("Room Phase Room Phase " + room.Name + " - " + roomPhase3.AsElementId().ToString() + " (" + roomPhase3.AsValueString() + ")");

            //    //ElementId roomPhase1 = room.CreatedPhaseId;
            //    //Debug("Room Phase 1 " + room.Name + " - " + roomPhase1 + " (" + roomPhase1.ToString() + ")");
            //}

            //Debug("Wallbb min " + wallbbmin);
            //Debug("Wallbb max " + wallbbmax);
            //Debug("Plan phase Id " + p.AsElementId().ToString());
            ////Debug("Plan phase Name " + planPhase.Name);

            XYZ wallCenter = new XYZ(
                (wallbbmax.X + wallbbmin.X) / 2,
                (wallbbmax.Y + wallbbmin.Y) / 2,
                wallbbmin.Z
                );

            List <Room> phasedRooms = RoomHelpers.GetPhasedRooms(doc, p.AsElementId());
            //Debug("Phase of wall " + w.CreatedPhaseId.ToString());
            //Debug("Phase of wall name " + w.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString());

            XYZ wallCenterYTranslatedPositive = new XYZ(
                wallCenter.X,
                wallCenter.Y + 10,
                wallCenter.Z
                );

            XYZ wallCenterYTranslatedNegative = new XYZ(
                wallCenter.X,
                wallCenter.Y - 10,
                wallCenter.Z
                );

            XYZ wallCenterXTranslatedPositive = new XYZ(
                wallCenter.X + 10,
                wallCenter.Y,
                wallCenter.Z
                );

            XYZ wallCenterXTranslatedNegative = new XYZ(
                wallCenter.X - 10,
                wallCenter.Y,
                wallCenter.Z
                );

            //Debug("wall center " + wallCenter);

            //Debug("wallCenterYTranslatedPositive " + wallCenterYTranslatedPositive);
            //Debug("wallCenterYTranslatedNegative " + wallCenterYTranslatedNegative);
            //Debug("wallCenterXTranslatedPositive " + wallCenterXTranslatedPositive);
            //Debug("wallCenterXTranslatedNegative " + wallCenterXTranslatedNegative);

            XYZ markerLocation = wallCenter;

            Debug("markerLocation before the loops " + markerLocation);
            Debug("length of list phasedrooms " + phasedRooms.Count);

            if ((wallbbmax.X - wallbbmin.X) > (wallbbmax.Y - wallbbmin.Y))
            {
                foreach (Room r in phasedRooms)
                {
                    if (r.IsPointInRoom(wallCenterYTranslatedPositive))
                    {
                        Debug("room name " + r.Name);
                        Debug("is Y positive in room " + r.IsPointInRoom(wallCenterYTranslatedPositive));

                        markerLocation = wallCenterYTranslatedNegative;
                        break;
                    }
                    else if (r.IsPointInRoom(wallCenterYTranslatedNegative))
                    {
                        Debug("room name " + r.Name);
                        Debug("is Y negative in room " + r.IsPointInRoom(wallCenterYTranslatedNegative));
                        markerLocation = wallCenterYTranslatedPositive;
                        break;
                    }
                }
                Debug("is Y check done");
            }
            else
            {
                foreach (Room r in phasedRooms)
                {
                    if (r.IsPointInRoom(wallCenterXTranslatedPositive))
                    {
                        Debug("room name " + r.Name);
                        Debug("is X positive in room " + r.IsPointInRoom(wallCenterXTranslatedPositive));
                        markerLocation = wallCenterXTranslatedNegative;
                        break;
                    }
                    else if (r.IsPointInRoom(wallCenterXTranslatedNegative))
                    {
                        Debug("room name " + r.Name);
                        Debug("is X negative in room " + r.IsPointInRoom(wallCenterXTranslatedNegative));
                        markerLocation = wallCenterXTranslatedPositive;
                        break;
                    }
                }
                Debug("is X check done");
            }

            Debug("selected marker location after loops " + markerLocation);

            //change scale to user input
            ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, FindFamilyTypeId(doc), markerLocation, 96);

            marker.get_Parameter(BuiltInParameter.PHASE_CREATED).Set(p.AsElementId());


            if (marker.IsAvailableIndex(0))
            {
                ViewSection extElev = marker.CreateElevation(doc, plan.Id, 0);

                extElev.get_Parameter(BuiltInParameter.VIEW_PHASE).Set(p.AsElementId());
            }

            return(marker);
        }
        public static void PurgeGarbage(Document currentDoc)
        {
            List <ElementId> MarkersToDelete   = new List <ElementId>();
            List <ElementId> TemplatesToDelete = new List <ElementId>();
            List <ElementId> FiltersToDelete   = new List <ElementId>();

            FilteredElementCollector viewCollector = new FilteredElementCollector(currentDoc);

            List <ElementId> Views   = viewCollector.OfCategory(BuiltInCategory.OST_Views).ToElementIds().ToList();
            List <Element>   Markers = viewCollector.OfClass(typeof(ElevationMarker)).ToList();

            FilteredElementCollector filtCollector = new FilteredElementCollector(currentDoc);
            List <ElementId>         filters       = filtCollector.OfClass(typeof(FilterElement)).ToElementIds().ToList();

            for (int i = 0; i < Markers.Count(); i++)
            {
                ElevationMarker marker = Markers[i] as ElevationMarker;
                if (marker.CurrentViewCount == 0)
                {
                    MarkersToDelete.Add(marker.Id);
                }
            }

            List <ElementId> templates     = new List <ElementId>();
            List <ElementId> usedtemplates = new List <ElementId>();
            List <ElementId> usedfilters   = new List <ElementId>();

            for (int i = 0; i < Views.Count(); i++)
            {
                View view = currentDoc.GetElement(Views[i]) as View;
                if (view.IsTemplate)
                {
                    templates.Add(Views[i]);
                }
                else
                {
                    usedtemplates.Add(view.ViewTemplateId);
                }
            }
            for (int i = 0; i < templates.Count(); i++)
            {
                if (!usedtemplates.Contains(templates[i]))
                {
                    TemplatesToDelete.Add(templates[i]);
                }
            }

            for (int i = 0; i < Views.Count(); i++)
            {
                if (!TemplatesToDelete.Contains(Views[i]))
                {
                    View             v          = currentDoc.GetElement(Views[i]) as View;
                    List <ElementId> filterlist = v.GetFilters().ToList();
                    for (int j = 0; j < filterlist.Count(); j++)
                    {
                        if (!usedfilters.Contains(filterlist[j]))
                        {
                            usedfilters.Add(filterlist[j]);
                        }
                    }
                }
            }

            for (int i = 0; i < filters.Count(); i++)
            {
                if (!usedfilters.Contains(filters[i]))
                {
                    FiltersToDelete.Add(filters[i]);
                }
            }

            using (Transaction trans = new Transaction(currentDoc, "Purge Elements"))
            {
                trans.Start();
                foreach (ElementId MID in MarkersToDelete)
                {
                    currentDoc.Delete(MID);
                }
                foreach (ElementId TID in TemplatesToDelete)
                {
                    currentDoc.Delete(TID);
                }
                foreach (ElementId FID in FiltersToDelete)
                {
                    currentDoc.Delete(FID);
                }
                trans.Commit();
            }

            TaskDialog.Show("Document Cleanup", "Deleted\r\n" +
                            FiltersToDelete.Count() + " Filters\r\n" +
                            TemplatesToDelete.Count() + " View Templates\r\n" +
                            MarkersToDelete.Count() + "Unused Elevation Markers");
        }
Exemple #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");
            }
        }
        public bool CreateElevationByList()
        {
            bool result = false;

            try
            {
                ElevationMarker marker         = null;
                XYZ             markerLocation = null;


                ApplyTemplateSettings();

                using (Transaction trans = new Transaction(m_doc, "Create Elevation Marker"))
                {
                    trans.Start();
                    try
                    {
                        BoundingBoxXYZ bbBox = m_room.get_BoundingBox(null);
                        markerLocation = new XYZ((bbBox.Max.X + bbBox.Min.X) / 2, (bbBox.Max.Y + bbBox.Min.Y) / 2, bbBox.Min.Z);

                        //LocationPoint locationPoint = m_room.Location as LocationPoint;
                        //markerLocation = locationPoint.Point;
                        if (m_room.Document.IsLinked)
                        {
                            var documents = from doc in linkedDocuments.Values where doc.DocumentTitle == m_room.Document.Title select doc;
                            if (documents.Any())
                            {
                                LinkedInstanceProperties lip = documents.First();
                                roomLink       = lip;
                                markerLocation = lip.TransformValue.OfPoint(markerLocation);
                            }
                        }

                        marker = ElevationMarker.CreateElevationMarker(m_doc, m_viewFamilyTypeId, markerLocation, toolSettings.CustomScale);
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.RollBack();
                        LogMessageBuilder.AddLogMessage(roomProperties.RoomNumber + " - " + roomProperties.RoomName + " : failed to create an elevation marker.");
                        LogMessageBuilder.AddLogMessage(ex.Message);
                        //MessageBox.Show("Failed to create an elevation marker.\n" + ex.Message, "Elevation Creator: Create Elevation Marker", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }

                if (null != marker)
                {
                    using (Transaction trans = new Transaction(m_doc, "Create Elevation Views"))
                    {
                        trans.Start();
                        try
                        {
                            string prefix           = toolSettings.PrefixText;
                            string intermediateText = GetRoomParameterValue(m_room, toolSettings.IntermediateText);
                            int    elevationIndex   = GetElevationMarkIndex();
                            string suffix           = GetRoomParameterValue(m_room, toolSettings.SuffixText);

                            int viewCount = marker.MaximumViewCount < 4 ? marker.MaximumViewCount : 4;

                            Dictionary <int, Dictionary <int, ElevationViewProperties> > elevationDictionary = new Dictionary <int, Dictionary <int, ElevationViewProperties> >();
                            Dictionary <int, ElevationViewProperties> elevationViews = new Dictionary <int, ElevationViewProperties>();

                            for (int i = 0; i < viewCount; i++)
                            {
                                string indexText = "";
                                if (i == 0 && toolSettings.DIsSelected)
                                {
                                    indexText = "D";
                                }
                                else if (i == 1 && toolSettings.AIsSelected)
                                {
                                    indexText = "A";
                                }
                                else if (i == 2 && toolSettings.BIsSelected)
                                {
                                    indexText = "B";
                                }
                                else if (i == 3 && toolSettings.CIsSelected)
                                {
                                    indexText = "C";
                                }
                                else
                                {
                                    continue;
                                }

                                ViewSection viewElevation = marker.CreateElevation(m_doc, m_viewPlan.Id, i);
                                viewElevation.Name = GetViewName(prefix, intermediateText, elevationIndex, indexText, suffix);
                                if (toolSettings.ViewTemplateId != -1)
                                {
                                    viewElevation.ViewTemplateId = new ElementId(toolSettings.ViewTemplateId);
                                }

                                Parameter param = viewElevation.LookupParameter("Title on Sheet");

                                if (null != param)
                                {
                                    param.Set(m_room.Name);
                                }

                                ElevationViewProperties viewProperties = new ElevationViewProperties(viewElevation);
                                if (!elevationViews.ContainsKey(viewProperties.ViewId))
                                {
                                    elevationViews.Add(viewProperties.ViewId, viewProperties);
                                }
                            }

                            if (elevationViews.Count > 0 && !roomProperties.ElevationViews.ContainsKey(marker.Id.IntegerValue))
                            {
                                roomProperties.KeyMarkId = marker.Id.IntegerValue;
                                roomProperties.ElevationViews.Add(marker.Id.IntegerValue, elevationViews);
                            }

                            trans.Commit();
                        }
                        catch (Exception ex)
                        {
                            trans.RollBack();
                            LogMessageBuilder.AddLogMessage(roomProperties.RoomNumber + " - " + roomProperties.RoomName + " : failed to create elevation views.");
                            LogMessageBuilder.AddLogMessage(ex.Message);
                            //MessageBox.Show("Failed to create elevation views.\n" + ex.Message, "Elevation Creator: Create Elevation Views", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                }

                if (null != marker && null != markerLocation)
                {
                    if (ModifyCropBox(roomProperties, marker.Id.IntegerValue))
                    {
                        if (ElevationCreatorDataStorageUtil.StoreRoomElevationProperties(m_doc, roomProperties))
                        {
                            //update extensible storage
                            result = true;
                        }
                    }
                }
                result = true;
            }
            catch (Exception ex)
            {
                LogMessageBuilder.AddLogMessage(roomProperties.RoomNumber + " - " + roomProperties.RoomName + " : failed to create elevations by room lists.\n" + ex.Message);
                //MessageBox.Show("Failed to create elevation by room lists.\n"+ex.Message, "Elevation Creator: CreateElevationByList", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(result);
        }
        public void RotateMarker(Document doc, Wall w, ElevationMarker marker)
        {
            XYZ wallNormal = w.Orientation;

            //rotate maker to be parallel to wall
        }
Exemple #28
0
        public static int countFail = 0;                            // number of elements failed

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Application   app   = uiapp.Application;
            Document      doc   = commandData.Application.ActiveUIDocument.Document;

            // add event handler for when the app does not find the ArpUtilies.dll assembly
            //AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            #region check if it is family document
            if (doc.IsFamilyDocument)
            {
                using (UI.Form_Info3 thisForm = new UI.Form_Info3())
                {
                    thisForm.ShowDialog();
                    return(Result.Cancelled);
                }
            }
            #endregion

            #region warn the user if he wants to proceed
            using (UI.Warning.Form_Warning thisForm = new UI.Warning.Form_Warning())
            {
                thisForm.ShowDialog();
                if (thisForm.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    return(Result.Cancelled);
                }
            }
            #endregion

            #region remove elevation tags
            using (TransactionGroup tg = new TransactionGroup(doc, "Remove Elevation Tags"))
            {
                tg.Start();
                count = 0; // reset the counter for when the app is run more than once
                foreach (Element e in new FilteredElementCollector(doc)
                         .OfClass(typeof(ElevationMarker))
                         .WhereElementIsNotElementType()
                         .ToElements())
                {
                    ElevationMarker em = e as ElevationMarker;

                    // only proceed with empty elevation marks
                    if (em.HasElevations() == false)
                    {
                        string elevType = doc.GetElement(e.GetTypeId()).Name;
                        //string itemInfo = "ID: " + "\t" + e.Id + "     Elevation Type: " + elevType;
                        //string itemFail = "ID: " + "\t" + e.Id + "     Elevation Type: " + elevType;
                        string itemInfo = string.Format("Elevation Type: {0} (ID: {1})", elevType, e.Id);
                        string itemFail = string.Format("Elevation Type: {0} (ID: {1})", elevType, e.Id);
                        try
                        {
                            // delete item
                            using (Transaction t = new Transaction(doc, "Remove Single Elevation Tag"))
                            {
                                t.Start();
                                doc.Delete(e.Id);
                                t.Commit();
                            }
                            // collect info
                            info.Add(itemInfo);
                            count += 1;
                        }
                        catch (Exception)
                        {
                            infoFail.Add(itemFail);
                            countFail += 1;
                        }
                    }
                }
                tg.Assimilate();
            }
            #endregion

            // if count = 0 show Not Found form
            if (count == 0)
            {
                using (UI.Info.Form_Info1 thisForm = new UI.Info.Form_Info1())
                {
                    thisForm.ShowDialog();
                }
            }

            // show Results Form
            if (count != 0)
            {
                using (UI.Info.Form_Results thisForm = new UI.Info.Form_Results())
                {
                    thisForm.ShowDialog();
                }
            }

            #region get analytics
            //try
            //{
            //    Utilities.GetAnalyticsCSV(doc, app);
            //}
            //catch (Exception)
            //{
            //}
            #endregion

            return(Result.Succeeded);
        }
        public static void GenViews(ViewFamilyType vft, View av, Room r)
        {
            Document currentDoc = r.Document;

            foreach (ElementId vtd in ViewsToDelete(r))
            {
                if (currentDoc.GetElement(vtd).IsValidObject)
                {
                    currentDoc.Delete(vtd);
                }
            }

            BoundingBoxXYZ bbse = r.get_BoundingBox(null);
            double         yMin = bbse.Min.Z;
            double         yMax = bbse.Max.Z;

            BoundaryData BData = new BoundaryData(r);

            if (null != BData.Edges())
            {
                foreach (KeyValuePair <Line, XYZ> kvp in BData.Edges())
                {
                    XYZ start  = kvp.Key.GetEndPoint(0);
                    XYZ end    = kvp.Key.GetEndPoint(1);
                    XYZ vector = end - start;
                    XYZ midpt  = start + (0.5 * vector);

                    double xsize  = kvp.Key.Length;
                    double height = yMax - yMin;

                    double minx = midpt.X - (xsize / 2) - offset;
                    double maxx = midpt.X + (xsize / 2) + offset;
                    double miny = yMin - offset;
                    double maxy = yMax + offset;
                    double minz = midpt.Z - offset / 2;
                    double maxz = midpt.Z + offset / 2;

                    XYZ minbound = new XYZ(minx, miny, minz);
                    XYZ maxbound = new XYZ(maxx, maxy, maxz);

                    BoundingBoxXYZ sectionBox = new BoundingBoxXYZ();
                    sectionBox.Min = minbound;
                    sectionBox.Max = maxbound;

                    ElevationMarker em = ElevationMarker.CreateElevationMarker(currentDoc, vft.Id, midpt, 48);
                    ViewSection     vs = em.CreateElevation(currentDoc, av.Id, 1);
                    vs.CropBox = sectionBox;

                    XYZ    baseangle = XYZ.BasisY;
                    double rotation  = kvp.Value.AngleTo(baseangle);
                    if (kvp.Value.X > 0)
                    {
                        rotation *= -1;
                    }

                    string dir = Direction(rotation);

                    Line axisline = Line.CreateBound(midpt, new XYZ(midpt.X, midpt.Y, midpt.Z + 1));
                    em.Location.Rotate(axisline, rotation);

                    em.Location.Move(-kvp.Value * offset);

                    int  j         = 1;
                    bool iscreated = false;
                    while (iscreated == false)
                    {
                        string viewname = r.Name + " - " + dir + " " + j;
                        FilteredElementCollector vfilter = new FilteredElementCollector(currentDoc).OfClass(typeof(View));
                        View testname = vfilter.FirstOrDefault <Element>(a => a.Name.Equals(viewname)) as View;
                        if (testname == null)
                        {
                            vs.Name   = viewname;
                            iscreated = true;
                        }
                        else
                        {
                            j++;
                        }
                    }
                }
            }
        }