/// <summary>
        /// move one element, which may be a wall or a family instance
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="elem"></param>
        /// <param name="translationVector"></param>
        /// <returns></returns>
        private string moveElement(Document doc, Element elem, XYZ translationVector)
        {
            StringBuilder sb = new StringBuilder(); //record the translation information
            //declare two Location objects, as they are multual exclusive, one of them will be null finally
            LocationPoint ptLocation   = null;
            LocationCurve lineLocation = null;

            //the visible element will be either a wall or a familyinstance, these two condition are also mutual exclusive
            FamilyInstance fm = elem as FamilyInstance;

            if (fm != null)
            {
                ptLocation   = fm.Location as LocationPoint;
                lineLocation = fm.Location as LocationCurve;
            }

            Wall wall = elem as Wall;

            if (wall != null)
            {
                lineLocation = wall.Location as LocationCurve;
            }

            if (ptLocation != null)
            {
                XYZ oldPlace = ptLocation.Point;
                //move an element, we provide two method, either of them works
                //ElementTransformUtils.MoveElement(doc, elem.Id, translationVector);
                ptLocation.Move(translationVector);
                //record the final coordinate
                XYZ newPlace = ptLocation.Point;
                //return the info as a string
                sb.AppendLine("the coordinate before translation:");
                sb.AppendLine(oldPlace.ToString());
                sb.AppendLine("the coordinate after translation:");
                sb.AppendLine(newPlace.ToString());
            }
            else //(lineLocation != null)
            {
                lineLocation.Move(translationVector);
                Line line      = lineLocation.Curve as Line;
                XYZ  oldPlace1 = line.GetEndPoint(0);
                XYZ  oldPlace2 = line.GetEndPoint(1);
                //move an element, we provide two method, either of them works
                //ElementTransformUtils.MoveElement(doc, elem.Id, translationVector);
                lineLocation.Move(translationVector);
                //record the final coordinate
                XYZ newPlace1 = line.GetEndPoint(0);
                XYZ newPlace2 = line.GetEndPoint(1);
                //return the info as a string
                sb.AppendLine("the coordinate of start point before translation:");
                sb.AppendLine(oldPlace1.ToString());
                sb.AppendLine("the coordinate of start point before translation:");
                sb.AppendLine(oldPlace2.ToString());
                sb.AppendLine("the coordinate of end point before translation:");
                sb.AppendLine(newPlace1.ToString());
                sb.AppendLine("the coordinate of end point before translation:");
                sb.AppendLine(newPlace2.ToString());
            }
            return(sb.ToString());
        }
Beispiel #2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

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

            foreach (RevitLinkInstance instance in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType().ToElements().Cast <RevitLinkInstance>())
            {
                try
                {
                    List <Room> rooms = new FilteredElementCollector(instance.GetLinkDocument()).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_Rooms).Cast <Room>().ToList();

                    if (rooms.Count != 0)
                    {
                        string RVT_link = instance.GetLinkDocument().PathName;
                        liste.Add(RVT_link);
                    }
                }
                catch
                {
                }
            }

            if (liste.Count == 0)
            {
                TaskDialog td = new TaskDialog("Avertissement");
                td.Title       = "Avertissement";
                td.MainIcon    = TaskDialogIcon.TaskDialogIconWarning;
                td.MainContent = "Aucun lien Revit contenant des pièces n'est chargé dans le projet actif.";
                td.Show();
                return(Result.Cancelled);
            }

            Space_Creator form = new Space_Creator(doc);

            if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return(Result.Cancelled);
            }

            if (DialogResult.OK == form.ShowDialog())
            {
                List <Level> levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements().Cast <Level>().ToList();

                using (Transaction t = new Transaction(doc, "Créer des espaces à partir des pièces"))
                {
                    t.Start();
                    string filename = form.GetSelectedRVTlink();
                    //var viewFamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast<ViewFamilyType>().FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);
                    //View3D view3D = View3D.CreateIsometric(doc, viewFamilyType.Id);
                    //view3D.Name = "__TEST A EFFACER";
                    //string room_param = "FICHE";
                    //string space_param = "INGP_FICHE";
                    int           unplaced_rooms         = 0;
                    int           unclosed_rooms         = 0;
                    int           redundant_rooms        = 0;
                    int           created_spaces         = 0;
                    List <string> unclosed_rooms_levels  = new List <string>();
                    List <string> redundant_rooms_levels = new List <string>();

                    List <Level> MEP_levels = new List <Level>();
                    MEP_levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements().Cast <Level>().ToList();

                    foreach (RevitLinkInstance instance in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType().ToElements().Cast <RevitLinkInstance>())
                    {
                        Document linkDoc = instance.GetLinkDocument();

                        if (linkDoc != null && Path.GetFileName(linkDoc.PathName) == filename)
                        {
                            List <string> rooms = new List <string>();
                            foreach (Space s in new FilteredElementCollector(doc).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_MEPSpaces).Cast <Space>())
                            {
                                Parameter room_name   = s.get_Parameter(BuiltInParameter.SPACE_ASSOC_ROOM_NAME);
                                Parameter room_number = s.get_Parameter(BuiltInParameter.SPACE_ASSOC_ROOM_NUMBER);
                                rooms.Add(room_name.AsString() + " " + room_number.AsString());
                            }

                            Transform tr = instance.GetTotalTransform();

                            foreach (Room room in new FilteredElementCollector(linkDoc).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_Rooms).Cast <Room>())
                            {
                                if (DistinguishRoom(room) == RoomState.Placed || DistinguishRoom(room) == RoomState.NotEnclosed || DistinguishRoom(room) == RoomState.Redundant)
                                {
                                    Parameter room_name   = room.get_Parameter(BuiltInParameter.ROOM_NAME);
                                    Parameter room_number = room.get_Parameter(BuiltInParameter.ROOM_NUMBER);
                                    //Parameter room_level = room.LookupParameter("Niveau");
                                    LocationPoint point = room.Location as LocationPoint;
                                    XYZ           pt    = new XYZ(point.Point.X, point.Point.Y, point.Point.Z);
                                    pt = tr.OfPoint(pt);

                                    Level level = GetNearestLevel(pt, levels);
                                    Phase phase = doc.GetElement(doc.ActiveView.get_Parameter(BuiltInParameter.VIEW_PHASE).AsElementId()) as Phase;

                                    if (!rooms.Contains(room_name.AsString() + " " + room_number.AsString()))
                                    {
                                        Space space = doc.Create.NewSpace(level, phase, new UV(pt.X, pt.Y));
                                        created_spaces += 1;

                                        if (form.roomData() == true)
                                        {
                                            space.Name   = room.get_Parameter(BuiltInParameter.ROOM_NAME).AsString();
                                            space.Number = room.Number;
                                        }
                                        //space.LookupParameter(space_param).Set(room.LookupParameter(room_param).AsString());
                                        space.BaseOffset = room.BaseOffset;

                                        if (form.spaceGeometry() == true)
                                        {
                                            Parameter limitOffset = space.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET);
                                            if (room.LimitOffset > 0)
                                            {
                                                limitOffset.Set(room.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET).AsDouble());
                                            }
                                            if (space.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble() != room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble())
                                            {
                                                limitOffset.Set(room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble() + room.get_Parameter(BuiltInParameter.ROOM_LOWER_OFFSET).AsDouble());
                                            }
                                        }

                                        if (form.spaceGeometry() == false)
                                        {
                                            Parameter     limitOffset = space.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET);
                                            List <double> distances   = GetDistancesToFloors(doc, doc.ActiveView as View3D, room);
                                            try
                                            {
                                                if (distances[0] < room.BaseOffset)
                                                {
                                                    if (distances[1] < room.BaseOffset)
                                                    {
                                                        //limitOffset.Set(Math.Round(distances[2], 2));
                                                        limitOffset.Set(distances[2]);
                                                    }
                                                    else
                                                    {
                                                        //limitOffset.Set(Math.Round(distances[1], 2));
                                                        limitOffset.Set(distances[1]);
                                                    }
                                                }
                                                else
                                                {
                                                    //limitOffset.Set(Math.Round(distances.First(), 2));
                                                    limitOffset.Set(distances.First());
                                                }

                                                for (int i = 0; i < 10; i++)
                                                {
                                                    if (space.UnboundedHeight < UnitUtils.ConvertToInternalUnits(1.5, DisplayUnitType.DUT_METERS))
                                                    {
                                                        limitOffset.Set(Math.Round(distances[i], 5));
                                                        //limitOffset.Set(distances[i]);
                                                        if (space.UnboundedHeight > UnitUtils.ConvertToInternalUnits(1.5, DisplayUnitType.DUT_METERS))
                                                        {
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            catch
                                            {
                                                if (room.LimitOffset > 0)
                                                {
                                                    limitOffset.Set(room.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET).AsDouble());
                                                }
                                                if (space.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble() != room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble())
                                                {
                                                    limitOffset.Set(room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble() + room.get_Parameter(BuiltInParameter.ROOM_LOWER_OFFSET).AsDouble());
                                                }
                                            }
                                        }

                                        if (DistinguishRoom(room) == RoomState.Redundant)
                                        {
                                            LocationPoint pt2  = space.Location as LocationPoint;
                                            XYZ           xyz  = new XYZ(0.001, 0, 0);
                                            XYZ           xyz2 = new XYZ(0.001, 0, 0);
                                            pt2.Move(xyz);
                                            pt2.Move(-xyz);
                                        }
                                    }
                                }
                                if (DistinguishRoom(room) == RoomState.NotPlaced)
                                {
                                    unplaced_rooms += 1;
                                }

                                if (DistinguishRoom(room) == RoomState.NotEnclosed)
                                {
                                    unclosed_rooms += 1;
                                    if (!unclosed_rooms_levels.Contains(room.Level.Name))
                                    {
                                        unclosed_rooms_levels.Add(room.Level.Name);
                                    }
                                }
                                if (DistinguishRoom(room) == RoomState.Redundant)
                                {
                                    redundant_rooms += 1;
                                    if (!redundant_rooms_levels.Contains(room.Level.Name))
                                    {
                                        redundant_rooms_levels.Add(room.Level.Name);
                                    }
                                }
                            }
                        }
                    }

                    TaskDialog td = new TaskDialog("Confirmation");
                    td.AllowCancellation = true;
                    td.TitleAutoPrefix   = true;


                    if (created_spaces > 0)
                    {
                        td.Title           = "Confirmation";
                        td.MainInstruction = created_spaces.ToString() + " espaces vont être crées.";

                        if (unclosed_rooms == 0 && redundant_rooms == 0)
                        {
                            td.MainContent = "Confirmer la création ?";
                        }
                        if (unclosed_rooms > 0 && redundant_rooms > 0)
                        {
                            td.MainContent = "dont espaces non fermés : " + unclosed_rooms.ToString() + " (" + string.Join("; ", unclosed_rooms_levels) + ")"
                                             + Environment.NewLine + "dont espaces superflus : " + redundant_rooms.ToString() + " (" + string.Join("; ", redundant_rooms_levels) + ")"
                                             + Environment.NewLine + "Confirmer la création ?";
                        }
                        if (unclosed_rooms > 0 && redundant_rooms == 0)
                        {
                            td.MainContent = "dont espaces non fermés : " + unclosed_rooms.ToString() + " (" + string.Join("; ", unclosed_rooms_levels) + ")"
                                             + Environment.NewLine + "Confirmer la création ?";
                        }
                        if (unclosed_rooms == 0 && redundant_rooms > 0)
                        {
                            td.MainContent = "dont espaces superflus : " + redundant_rooms.ToString() + " (" + string.Join("; ", redundant_rooms_levels) + ")"
                                             + Environment.NewLine + "Confirmer la création ?";
                        }

                        td.CommonButtons = TaskDialogCommonButtons.Cancel | TaskDialogCommonButtons.Ok;
                        TaskDialogResult result = td.Show();
                        if (result == TaskDialogResult.Ok)
                        {
                            t.Commit();
                        }
                        return(Result.Succeeded);
                    }
                }
                return(Result.Succeeded);
            }
            return(Result.Succeeded);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            // Call WPF for user input
            using (DuplicateSheetsWPF customWindow = new DuplicateSheetsWPF(commandData))
            {
                // Revit application as window's owner
                System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(customWindow);
                helper.Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

                customWindow.ShowDialog();

                // Retrieve all user input
                List <int> sheetIds              = customWindow.sheetIds;
                var        titleBlockComboBox    = customWindow.SelectedComboItemTitleBlock;
                var        copyViews             = customWindow.copyViews;
                var        optDuplicate          = customWindow.optDuplicate;
                var        optDuplicateDetailing = customWindow.optDuplicateDetailing;
                var        optDuplicateDependant = customWindow.optDuplicateDependant;
                var        viewPrefix            = customWindow.viewPrefix;
                var        viewSuffix            = customWindow.viewSuffix;
                var        sheetPrefix           = customWindow.sheetPrefix;
                var        sheetSuffix           = customWindow.sheetSuffix;

                // Establish duplicate options at top to avoid reassignment inside loop
                var viewDuplicateOption = ViewDuplicateOption.Duplicate;
                if (optDuplicateDetailing == true)
                {
                    viewDuplicateOption = ViewDuplicateOption.WithDetailing;
                }
                else if (optDuplicateDependant == true)
                {
                    viewDuplicateOption = ViewDuplicateOption.AsDependent;
                }

                // Group transacation
                TransactionGroup tg = new TransactionGroup(doc, "Duplicate sheets");
                tg.Start();

                // List to store sheets duplicated
                var viewSheetSuccess = new List <string>();

                // Duplicate all selected sheets
                foreach (var sId in sheetIds)
                {
                    // Retrieve sheet and sheet Id
                    ElementId sheetId = new ElementId(sId);
                    ViewSheet vSheet  = doc.GetElement(sheetId) as ViewSheet;

                    // Retrieve title block according to user input
                    FamilyInstance titleblock = null;
                    if (titleBlockComboBox.Content as string != "Current Title Block")
                    {
                        titleblock = titleBlockComboBox.Tag as FamilyInstance;
                    }
                    else
                    {
                        // Retrieve titleblock from current sheet
                        titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance))
                                     .OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>()
                                     .First(q => q.OwnerViewId == vSheet.Id);
                    }
                    // Guard against no loaded titleblocks in project or in sheet
                    if (titleblock == null)
                    {
                        titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance))
                                     .OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>()
                                     .First();
                    }

                    // Retrieve elements on sheet
                    var elementsInViewId = new FilteredElementCollector(doc, sheetId).ToElementIds();
                    // Retrieve viewports in view
                    FilteredElementCollector viewPorts = new FilteredElementCollector(doc, sheetId).OfClass(typeof(Viewport));
                    // Retrieve schedules in view
                    FilteredElementCollector schedules = new FilteredElementCollector(doc).OwnedByView(sheetId)
                                                         .OfClass(typeof(ScheduleSheetInstance));
                    // Retrieve viewSchedules
                    FilteredElementCollector viewSchedules = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule));

                    // Store copied elements and annotation elements
                    var copiedElementIds     = new List <ElementId>();
                    var annotationElementsId = new List <ElementId>();

                    using (Transaction t = new Transaction(doc, "Duplicate Sheet"))
                    {
                        // Start transaction to duplicate sheet
                        t.Start();

                        // Duplicate sheet
                        ViewSheet newsheet = ViewSheet.Create(doc, titleblock.GetTypeId());
                        newsheet.SheetNumber = sheetPrefix + vSheet.SheetNumber + sheetSuffix;
                        newsheet.Name        = vSheet.Name;

                        // Get origin of the titleblock
                        XYZ originTitle = titleblock.GetTransform().Origin;
                        // Check titleblock position
                        Element       copyTitleBlock = new FilteredElementCollector(doc).OwnedByView(newsheet.Id).OfCategory(BuiltInCategory.OST_TitleBlocks).FirstElement();
                        LocationPoint titleLoc       = copyTitleBlock.Location as LocationPoint;
                        XYZ           titleLocPoint  = titleLoc.Point;
                        // Check if title block is in the same position as original
                        if (titleLocPoint.DistanceTo(originTitle) != 0)
                        {
                            // Move it in case it is not
                            titleLoc.Move(originTitle);
                        }

                        // Check if user selected copy views
                        if (copyViews)
                        {
                            // Retrieve all views placed on sheet except schedules
                            foreach (ElementId eId in vSheet.GetAllPlacedViews())
                            {
                                View origView = doc.GetElement(eId) as View;
                                View newView  = null;

                                // Legends
                                if (origView.ViewType == ViewType.Legend)
                                {
                                    newView = origView;
                                }
                                // Rest of view types
                                else
                                {
                                    if (origView.CanViewBeDuplicated(viewDuplicateOption))
                                    {
                                        ElementId newViewId = origView.Duplicate(viewDuplicateOption);
                                        newView      = doc.GetElement(newViewId) as View;
                                        newView.Name = viewPrefix + origView.Name + viewSuffix;
                                    }
                                }

                                // Loop through viewports
                                foreach (Viewport vp in viewPorts)
                                {
                                    if (vp.SheetId == vSheet.Id && vp.ViewId == origView.Id)
                                    {
                                        // Retrieve centerpoint of original viewport
                                        XYZ center = vp.GetBoxCenter();
                                        // Create viewport in the original spot
                                        Viewport newVp = Viewport.Create(doc, newsheet.Id, newView.Id, center);
                                    }
                                    // Add element in copied list
                                    copiedElementIds.Add(vp.Id);
                                }
                                // Add element in copied list
                                copiedElementIds.Add(eId);
                            }

                            // Retrieve and copy schedules
                            foreach (ScheduleSheetInstance sch in schedules)
                            {
                                // Check schedule is not a revision inside titleblock
                                if (!sch.IsTitleblockRevisionSchedule)
                                {
                                    foreach (ViewSchedule vsc in viewSchedules)
                                    {
                                        if (sch.ScheduleId == vsc.Id)
                                        {
                                            // Retrieve center of schedule
                                            XYZ schCenter = sch.Point;
                                            // Create schedule in the same position
                                            ScheduleSheetInstance newSch = ScheduleSheetInstance.Create(doc, newsheet.Id, vsc.Id, schCenter);
                                        }
                                        copiedElementIds.Add(vsc.Id);
                                    }
                                }
                            }

                            // Duplicate annotation elements
                            foreach (ElementId eId in elementsInViewId)
                            {
                                if (!copiedElementIds.Contains(eId))
                                {
                                    annotationElementsId.Add(eId);
                                }
                            }

                            // Copy annotation elements
                            ElementTransformUtils.CopyElements(vSheet, annotationElementsId, newsheet, null, null);
                        }

                        viewSheetSuccess.Add(newsheet.SheetNumber + " - " + newsheet.Name);

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

                // Commit group transaction
                tg.Assimilate();

                // Display result message to user
                if (viewSheetSuccess.Count > 0)
                {
                    TaskDialog.Show("Success", "The following sheets have been duplicated: \n" + string.Join("\n", viewSheetSuccess));
                }

                return(Result.Succeeded);
            }
        }