Ejemplo n.º 1
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document         doc    = commandData.Application.ActiveUIDocument.Document;
            Selection        sel    = commandData.Application.ActiveUIDocument.Selection;
            List <ElementId> selids = sel.GetElementIds().ToList();

            if (selids.Count == 0)
            {
                message = "Выберите элементы";
                return(Result.Failed);
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Отсоединение элементов");
                foreach (ElementId selId in selids)
                {
                    Element          elem = doc.GetElement(selId);
                    List <ElementId> ids  = JoinGeometryUtils.GetJoinedElements(doc, elem).ToList();

                    foreach (ElementId id in ids)
                    {
                        Element elem2 = doc.GetElement(id);
                        JoinGeometryUtils.UnjoinGeometry(doc, elem, elem2);
                    }
                    doc.Regenerate();
                }
                t.Commit();
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Get UIdocument
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            //Get Document
            Document doc = uidoc.Document;

            try
            {
                //Get elements of Category
                var eles = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns)
                           .WhereElementIsNotElementType()
                           .ToElements();

                using (var tran = new Transaction(doc, "Calculator Formwork Area for Element"))
                {
                    tran.Start();
                    foreach (var ele in eles)
                    {
                        //Get BoundingBox from Element
                        BoundingBoxXYZ boundingBox = ele.get_BoundingBox(null);
                        //Get Outline
                        Outline outline = new Outline(boundingBox.Min, boundingBox.Max);
                        BoundingBoxIntersectsFilter filter = new BoundingBoxIntersectsFilter(outline);
                        //BoundingBoxIntersectsFilter invertFilter = new BoundingBoxIntersectsFilter(outline,true);

                        var eleIntersect = new FilteredElementCollector(doc)
                                           .WhereElementIsNotElementType()
                                           .WherePasses(filter)
                                           .ToElements();

                        foreach (var item in eleIntersect)
                        {
                            var joined = JoinGeometryUtils.AreElementsJoined(doc, ele, item);
                            if (joined == true)
                            {
                                JoinGeometryUtils.UnjoinGeometry(doc, ele, item);
                                //JoinGeometryUtils.JoinGeometry(doc, ele, item);
                                //JoinGeometryUtils.SwitchJoinOrder(doc, ele, item);
                            }
                            JoinGeometryUtils.JoinGeometry(doc, ele, item);
                            //JoinGeometryUtils.SwitchJoinOrder(doc, ele, item);
                        }
                    }
                    tran.Commit();
                }
                return(Result.Succeeded);
            }
            catch (Exception exception)
            {
                message = exception.Message;
                return(Result.Failed);
            }
        }
Ejemplo n.º 3
0
        public static void joinGeoByTwoCategories(Document doc, BuiltInCategory firstCategory, BuiltInCategory secondCategory)
        {
            FilteredElementCollector coll = new FilteredElementCollector(doc);
            // 篩選條件牆的篩選器
            ElementCategoryFilter filterFirstCategory   = new ElementCategoryFilter(firstCategory);
            IList <Element>       FirstCategoryElements = coll.WherePasses(filterFirstCategory)
                                                          .WhereElementIsNotElementType().ToElements();

            //因為元件接合要做寫入改動,因此要將它放入交易
            //針對所有元件作自動接合
            foreach (Element firstElement in FirstCategoryElements)
            {
                BoundingBoxXYZ bbx = firstElement.get_BoundingBox(null);
                //從第一元件取得「邊界長方體」(包覆元件邊界的長方體,如果元件本身是長方體,就會完全包覆)
                //OutLine是一條線,此處等於直接拿包覆長方體的對角線來定義它
                Outline outline = new Outline(bbx.Min, bbx.Max);//Min及Max各是一個點,都能存取XYZ座標
                BoundingBoxIntersectsFilter filterIntersection = new BoundingBoxIntersectsFilter(outline);
                //這個過濾器會取得「所有和這個BoundingBox相交的BoundingBox,並且傳回其所代表之元件」
                ElementCategoryFilter filterSecondCategory = new ElementCategoryFilter(secondCategory);
                //然後在相交元件當中,我只想先處理第一類別與第二類別的相交,所以需要再一個篩選器
                LogicalAndFilter andfilter = new LogicalAndFilter(filterIntersection, filterSecondCategory); //用交集篩選器將它們組合起來

                IList <Element> adjacents = new FilteredElementCollector(doc).WherePasses(andfilter).
                                            WhereElementIsNotElementType().ToElements();
                //以上一行選取所有和第一元件相鄰,而且屬於第二類別的元件,把整個doc放進Collector後再濾出通過篩選器的元件
                foreach (Element secondElement in adjacents)
                {
                    //MessageBox.Show(secondElement.Id + "\n" + secondElement.Category.Name); //debug
                    Transaction trans = new Transaction(doc);
                    try
                    {
                        trans.Start("join");                                                               //開始交易(接合)
                        if (JoinGeometryUtils.AreElementsJoined(doc, firstElement, secondElement) == true) //如果兩個元件已接合
                        {
                            JoinGeometryUtils.UnjoinGeometry(doc, firstElement, secondElement);            //先解除接合,因為我假設它不是我要的結果
                        }
                        //以上那個動作有點近似我們在Revit裡頭除了「接合」、「取消接合」以外,也可以「改變接合順序」
                        JoinGeometryUtils.JoinGeometry(doc, firstElement, secondElement); //再重新接合,但原本就處於未接合的元件也會被接合
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.ToString());
                    }
                    finally //這裡刻意讓finally陳述句登場,只是強調無論如何都要做交易的commit
                    {
                        trans.Commit();
                    }
                } //end inner foreach
            }     //end outer foreach
        }         //end fun
Ejemplo n.º 4
0
        public void UnjoinAll()
        {
            var doc = this.elements.First().Document;

            foreach (var p in this.joinMap)
            {
                var e1  = doc.GetElement(p.Key);
                var ids = p.Value;
                foreach (var id in ids)
                {
                    var e2 = doc.GetElement(id);
                    JoinGeometryUtils.UnjoinGeometry(doc, e1, e2);
                }
            }
        }
Ejemplo n.º 5
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp      = commandData.Application;
            UIDocument    uidoc      = uiapp.ActiveUIDocument;
            Application   app        = uiapp.Application;
            Document      doc        = uidoc.Document;
            View          activeView = doc.ActiveView;


            IList <Reference> selectedElements = uidoc.Selection.PickObjects(ObjectType.Element, "Select Elements to be joined");

            int count = 0;

            using (Transaction t = new Transaction(doc, "Unjoin all"))
            {
                t.Start();

                foreach (Reference eleRef in selectedElements)
                {
                    try
                    {
                        ICollection <ElementId> elementJoined = JoinGeometryUtils.GetJoinedElements(doc, doc.GetElement(eleRef));

                        foreach (ElementId eid in elementJoined)
                        {
                            JoinGeometryUtils.UnjoinGeometry(doc, doc.GetElement(eleRef), doc.GetElement(eid));
                        }

                        count += 1;
                    }
                    catch (Exception ex)
                    {
                        TaskDialog.Show("Error", ex.Message);
                    }
                }


                t.Commit();
            }


            TaskDialog.Show("Result", String.Format("{0} have been unjoined", count));

            return(Result.Succeeded);
        }
Ejemplo n.º 6
0
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        UIApplication           application = commandData.get_Application();
        Document                document    = application.get_ActiveUIDocument().get_Document();
        Selection               selection   = application.get_ActiveUIDocument().get_Selection();
        ICollection <ElementId> elementIds  = selection.GetElementIds();

        if (elementIds.Count != 0)
        {
            List <Element> list = Method.GeometryFilter(document, elementIds);
            int            num  = 0;
            if (list.Count > 1)
            {
                Combinations <Element> combinations = new Combinations <Element>(list, 2, GenerateOption.WithoutRepetition);
                Transaction            val          = new Transaction(document);
                val.Start("UnjoinElement");
                FailureHandlingOptions failureHandlingOptions = val.GetFailureHandlingOptions();
                MyFailuresPreProcessor myFailuresPreProcessor = new MyFailuresPreProcessor();
                failureHandlingOptions.SetFailuresPreprocessor(myFailuresPreProcessor);
                val.SetFailureHandlingOptions(failureHandlingOptions);
                foreach (List <Element> item in combinations)
                {
                    if (JoinGeometryUtils.AreElementsJoined(document, item[0], item[1]))
                    {
                        try
                        {
                            JoinGeometryUtils.UnjoinGeometry(document, item[0], item[1]);
                            num++;
                        }
                        catch
                        {
                        }
                    }
                }
                MessageBox.Show(num.ToString() + " Pairs Elements Successfully Unjoin.", "ElementMerger");
                val.Commit();
            }
            else if (list.Count == 1)
            {
                TaskDialog.Show("ElementMerger", "Only One Element Selected");
            }
        }
        else
        {
            TaskDialog.Show("ElementMerger", "None Element Selected");
        }
        return(0);
    }
Ejemplo n.º 7
0
        public Result Execute(ExternalCommandData commandData,
                              ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // code
            try
            {
                FilteredElementCollector collectorBeam = new FilteredElementCollector(doc);
                List <Element>           listBeams     = collectorBeam.OfCategory(BuiltInCategory.OST_StructuralFraming)
                                                         .WhereElementIsNotElementType().ToElements().ToList();

                FilteredElementCollector collectorDeck = new FilteredElementCollector(doc);
                List <Element>           listDecks     = collectorDeck.OfCategory(BuiltInCategory.OST_Floors)
                                                         .WhereElementIsNotElementType().ToElements().ToList();

                Transaction tran = new Transaction(doc);
                tran.Start("UnJoin beam to deck");
                int count = 0;
                foreach (Element deck in listDecks)
                {
                    foreach (Element beam in listBeams)
                    {
                        try
                        {
                            JoinGeometryUtils.UnjoinGeometry(doc, beam, deck);
                            count++;
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                tran.Commit();
                MessageBox.Show($"Auto unjoin {count} pairs of beam deck done!");
            }
            catch (Exception ex)
            {
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 8
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;

            var eles = new FilteredElementCollector(doc).OfCategory((BuiltInCategory.OST_StructuralColumns))
                       .WhereElementIsNotElementType()
                       .ToElements();

            using (var tran = new Transaction(doc, "Join Floor and Column"))
            {
                tran.Start();
                foreach (var ele in eles)
                {
                    var boundingBox = ele.get_BoundingBox(null);
                    var outline     = new Outline(boundingBox.Min, boundingBox.Max);
                    var filter      = new BoundingBoxIntersectsFilter(outline);

                    var collectors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                     .WhereElementIsNotElementType()
                                     .WherePasses(filter)
                                     .ToElements();

                    foreach (var item in collectors)
                    {
                        //Options options = new Options();
                        //options.ComputeReferences = true;
                        //options.DetailLevel = ViewDetailLevel.Fine;
                        //GeometryElement geoElement = item.get_Geometry(options);

                        bool joined = JoinGeometryUtils.AreElementsJoined(doc, ele, item);
                        if (joined == true)
                        {
                            JoinGeometryUtils.UnjoinGeometry(doc, ele, item);
                        }
                        JoinGeometryUtils.JoinGeometry(doc, ele, item);
                        //JoinGeometryUtils.SwitchJoinOrder(doc, ele, item);
                    }
                }
                tran.Commit();
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 9
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            _uiapp = commandData.Application;
            _uidoc = _uiapp.ActiveUIDocument;
            _doc   = _uidoc.Document;

            try
            {
                List <FamilyInstance> bn_pvList =
                    (from FamilyInstance beam in new FilteredElementCollector(_doc)
                     .OfCategory(BuiltInCategory.OST_StructuralFraming)
                     .OfClass(typeof(FamilyInstance))
                     .Cast <FamilyInstance>()
                     where beam.Name.Contains("BN") || beam.Name.Contains("TAL")
                     select beam)
                    .ToList();


                TaskDialog.Show("Revit", $"{bn_pvList.Count()} BN/Talon");
                using (Transaction tx = new Transaction(_doc))
                {
                    tx.Start("Unjoin");
                    foreach (FamilyInstance bn in bn_pvList)
                    {
                        IList <ElementId> eleList = JoinGeometryUtils.GetJoinedElements(_doc, bn).ToList();

                        foreach (ElementId id in eleList)
                        {
                            Element ele = _doc.GetElement(id);
                            JoinGeometryUtils.UnjoinGeometry(_doc, bn, ele);
                        }
                    }
                    tx.Commit();
                }

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Ejemplo n.º 10
0
        static void UnjoinElements(Document doc, Element selectedElem)
        {
            ICollection <ElementId> joinedElements =
                JoinGeometryUtils.GetJoinedElements(doc, selectedElem);

            if (joinedElements != null &&
                joinedElements.Count > 0)
            {
                using (Transaction t = new Transaction(doc, "Unjoin Elements"))
                {
                    t.Start();
                    foreach (ElementId id in joinedElements)
                    {
                        JoinGeometryUtils.UnjoinGeometry
                            (doc, selectedElem, doc.GetElement(id));
                    }
                    t.Commit();
                }
            }

            m_selectedElem      = selectedElem;
            m_selectedElemSolid = RvtGeometryUtils.GetSolid(m_selectedElem);
        }
Ejemplo n.º 11
0
        public static void FixInstanceFaceProblem(Element _host)
        {
            var doc     = _host.Document;
            var anyWall = new FilteredElementCollector(doc)
                          .WhereElementIsNotElementType()
                          .OfClass(typeof(Wall))
                          .FirstOrDefault(x => ((Wall)x).WallType.Kind == WallKind.Basic &&
                                          x.SameDesignOption(_host));

            if (anyWall == null)
            {
                return;
            }
            else if (JoinGeometryUtils.AreElementsJoined(doc, _host, anyWall) == false)
            {
                try
                {
                    JoinGeometryUtils.JoinGeometry(doc, anyWall, _host);
                    JoinGeometryUtils.UnjoinGeometry(doc, anyWall, _host);
                }
                catch { }
            }
        }
Ejemplo n.º 12
0
        /***************************************************/
        /****              Private Methods              ****/
        /***************************************************/

        private static Dictionary <PlanarSurface, List <PlanarSurface> > PanelSurfaces_HostDocument(this HostObject hostObject, IEnumerable <ElementId> insertsToIgnore = null, RevitSettings settings = null)
        {
            List <Autodesk.Revit.DB.Plane> planes = hostObject.IPanelPlanes();

            if (planes.Count == 0)
            {
                return(null);
            }

            Document doc = hostObject.Document;
            Dictionary <PlanarSurface, List <PlanarSurface> > result = new Dictionary <PlanarSurface, List <PlanarSurface> >();

            IList <ElementId> inserts = hostObject.FindInserts(true, true, true, true);

            if (insertsToIgnore != null)
            {
                inserts = inserts.Where(x => insertsToIgnore.All(y => x.IntegerValue != y.IntegerValue)).ToList();
            }

            Transaction            t = new Transaction(doc);
            FailureHandlingOptions failureHandlingOptions = t.GetFailureHandlingOptions().SetClearAfterRollback(true);

            t.Start("Temp Delete Inserts And Unjoin Geometry");

            try
            {
                foreach (ElementId id in JoinGeometryUtils.GetJoinedElements(doc, hostObject))
                {
                    JoinGeometryUtils.UnjoinGeometry(doc, hostObject, doc.GetElement(id));
                }

                if (hostObject is Wall)
                {
                    WallUtils.DisallowWallJoinAtEnd((Wall)hostObject, 0);
                    WallUtils.DisallowWallJoinAtEnd((Wall)hostObject, 1);
                }

                if (insertsToIgnore != null)
                {
                    doc.Delete(insertsToIgnore.ToList());
                }

                doc.Regenerate();

                List <Solid> solidsWithOpenings = hostObject.Solids(new Options());
                List <Solid> fullSolids;

                if (inserts.Count != 0)
                {
                    solidsWithOpenings = solidsWithOpenings.Select(x => SolidUtils.Clone(x)).ToList();

                    doc.Delete(inserts);
                    doc.Regenerate();

                    fullSolids = hostObject.Solids(new Options());
                }
                else
                {
                    fullSolids = solidsWithOpenings;
                }

                fullSolids = fullSolids.SelectMany(x => SolidUtils.SplitVolumes(x)).ToList();
                if (hostObject is Wall)
                {
                    fullSolids.ForEach(x => BooleanOperationsUtils.CutWithHalfSpaceModifyingOriginalSolid(x, planes[0]));
                    Autodesk.Revit.DB.Plane flippedPlane = Autodesk.Revit.DB.Plane.CreateByNormalAndOrigin(-planes[0].Normal, planes[0].Origin + planes[0].Normal * 1e-3);
                    fullSolids.ForEach(x => BooleanOperationsUtils.CutWithHalfSpaceModifyingOriginalSolid(x, flippedPlane));
                    fullSolids = fullSolids.SelectMany(x => SolidUtils.SplitVolumes(x)).ToList();
                    planes[0]  = Autodesk.Revit.DB.Plane.CreateByNormalAndOrigin(-planes[0].Normal, planes[0].Origin);
                }


                foreach (Autodesk.Revit.DB.Plane plane in planes)
                {
                    foreach (Solid s in fullSolids)
                    {
                        List <CurveLoop> loops = new List <CurveLoop>();
                        foreach (Autodesk.Revit.DB.Face f in s.Faces)
                        {
                            PlanarFace pf = f as PlanarFace;
                            if (pf == null)
                            {
                                continue;
                            }

                            if (Math.Abs(1 - pf.FaceNormal.DotProduct(plane.Normal)) <= settings.DistanceTolerance && Math.Abs((pf.Origin - plane.Origin).DotProduct(plane.Normal)) <= settings.AngleTolerance)
                            {
                                loops.AddRange(pf.GetEdgesAsCurveLoops());
                            }
                        }

                        CurveLoop            outline  = loops.FirstOrDefault(x => x.IsCounterclockwise(plane.Normal));
                        PlanarSurface        surface  = new PlanarSurface(outline.FromRevit(), null);
                        List <PlanarSurface> openings = new List <PlanarSurface>();
                        foreach (CurveLoop loop in loops.Where(x => x != outline))
                        {
                            openings.Add(new PlanarSurface(loop.FromRevit(), null));
                        }

                        if (inserts.Count != 0)
                        {
                            List <Solid> openingVolumes = new List <Solid>();
                            foreach (Solid s2 in solidsWithOpenings)
                            {
                                openingVolumes.Add(BooleanOperationsUtils.ExecuteBooleanOperation(s, s2, BooleanOperationsType.Difference));
                            }

                            foreach (Solid s2 in openingVolumes)
                            {
                                foreach (Autodesk.Revit.DB.Face f in s2.Faces)
                                {
                                    PlanarFace pf = f as PlanarFace;
                                    if (pf == null)
                                    {
                                        continue;
                                    }

                                    if (Math.Abs(1 - pf.FaceNormal.DotProduct(plane.Normal)) <= settings.DistanceTolerance && Math.Abs((pf.Origin - plane.Origin).DotProduct(plane.Normal)) <= settings.AngleTolerance)
                                    {
                                        foreach (CurveLoop cl in pf.GetEdgesAsCurveLoops())
                                        {
                                            openings.Add(new PlanarSurface(cl.FromRevit(), null));
                                        }
                                    }
                                }
                            }
                        }

                        result.Add(surface, openings);
                    }
                }
            }
            catch
            {
                BH.Engine.Reflection.Compute.RecordError(String.Format("Geometrical processing of a Revit element failed due to an internal Revit error. Converted panel might be missing one or more of its surfaces. Revit ElementId: {0}", hostObject.Id));
            }

            t.RollBack(failureHandlingOptions);

            return(result);
        }
Ejemplo n.º 13
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   = uidoc.Selection;

            var acview = doc.ActiveView;

            var floorTypes = doc.TCollector <FloorType>().ToList();

            var selectorUI = FloorTypeSelector.Instance;

            selectorUI.floortypeBox.ItemsSource       = floorTypes;
            selectorUI.floortypeBox.DisplayMemberPath = "Name";
            selectorUI.floortypeBox.SelectedIndex     = 0;
            selectorUI.ShowDialog();

            var targetFloortype = selectorUI.floortypeBox.SelectedItem as FloorType; //目标楼板类型

            var beamrefs = default(IList <Reference>);

            try
            {
                beamrefs = sel.PickObjects(ObjectType.Element,
                                           doc.GetSelectionFilter(m => m.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralFraming),
                                           "选择生成板的梁");
            }
            catch (Exception e)
            {
                MessageBox.Show("用户取消了命令!");
                return(Result.Cancelled);
            }

            var beams = beamrefs.Select(m => m.GetElement(doc));

            //var ele = sel.PickObject(ObjectType.Element).GetElement(doc);
            //var solid = ele.get_Geometry(new Options()).GetSolidOfGeometryObject().First();
            //var trans = Transform.Identity;
            //trans.Origin = new XYZ(-10, 0, 0);
            //doc.Invoke(m =>
            //{
            //    var newsolid = SolidUtils.CreateTransformed(solid, trans);
            //    var directshape = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));

            //    directshape.AppendShape(new List<GeometryObject>() {newsolid});
            //}, "test");
            //doc.Create.NewFloor()


            Transaction temtran = new Transaction(doc, "temtran");

            temtran.Start();
            foreach (Element beam in beams)
            {
                var joinedelements = JoinGeometryUtils.GetJoinedElements(doc, beam);

                if (joinedelements.Count > 0)
                {
                    foreach (var id in joinedelements)
                    {
                        var temele   = id.GetElement(doc);
                        var isjoined = JoinGeometryUtils.AreElementsJoined(doc, beam, temele);
                        if (isjoined)
                        {
                            JoinGeometryUtils.UnjoinGeometry(doc, beam, temele);
                        }
                    }
                }
            }
            temtran.RollBack();

            var solidss = new List <GeometryObject>();//beams.Select(m => m.Getsolids());

            foreach (var element in beams)
            {
                solidss.AddRange(element.Getsolids());
            }

            var joinedsolid = MergeSolids(solidss.Cast <Solid>().ToList());

            //var upfaces = beams.Select(m => m.get_Geometry(new Options() { DetailLevel = ViewDetailLevel.Fine }).Getupfaces().First());
            //MessageBox.Show(upfaces.Count().ToString());

            //var solids = upfaces.Select(m =>
            //    GeometryCreationUtilities.CreateExtrusionGeometry(m.GetEdgesAsCurveLoops(), XYZ.BasisZ, 10)).ToList();

            //MessageBox.Show("solids count" + solids.Count().ToString());
            //var targetsolid = MergeSolids(solids);

            //List<GeometryObject> geoobjs = solids.Cast<GeometryObject>().ToList();

            var upfaces = joinedsolid.Getupfaces();

            var edgeArrays = upfaces.First().EdgeLoops.Cast <EdgeArray>().ToList();

            //var curvearrays = curveloops.Select();

            var curveloops = upfaces.First().GetEdgesAsCurveLoops();

            var orderedcurveloops = curveloops.OrderBy(m => m.GetExactLength()).ToList();

            orderedcurveloops.RemoveAt(orderedcurveloops.Count - 1);
            curveloops = orderedcurveloops;

            var curvearrays = curveloops.Select(m => m.ToCurveArray());

            doc.Invoke(m =>
            {
                foreach (var curvearray in curvearrays)
                {
                    doc.Create.NewFloor(curvearray, false);
                    //doc.Create.NewFloor(curvearray, false); //可指定楼板类型来创建
                }
            }, "一键楼板");

            //doc.Invoke(m =>
            //{
            //    var directshape = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));
            //    //directshape.AppendShape(new List<GeometryObject>(){targetsolid});
            //    //directshape.AppendShape(solidss);
            //    directshape.AppendShape(new List<GeometryObject>() { joinedsolid });
            //}, "temsolid");

            return(Result.Succeeded);
        }
Ejemplo n.º 14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            Selection  sel   = uidoc.Selection;

            try
            {
                //IList<Level> projectLevelList = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(Level))
                //    .Cast<Level>().OrderBy(l => l.Elevation).ToList();

                IList <LevelInfo> projectLevelList = Utils.GetInformation.GetAllLevelsInfo(doc);

                ElementsJoinUIAdvanced currentUI = new ElementsJoinUIAdvanced(projectLevelList);
                currentUI.ShowDialog();

                if (currentUI.DialogResult == false)
                {
                    return(Result.Cancelled);
                }

                string firstCatName = (currentUI.comboFirstCategory.SelectedItem as ComboBoxItem).Content.ToString();
                string seconCatName = (currentUI.comboSecondCategory.SelectedItem as ComboBoxItem).Content.ToString();

                BuiltInCategory firstCat  = checkCategory(currentUI.comboFirstCategory.SelectedIndex);
                BuiltInCategory secondCat = checkCategory(currentUI.comboSecondCategory.SelectedIndex);

                if (firstCat == BuiltInCategory.INVALID || secondCat == BuiltInCategory.INVALID)
                {
                    return(Result.Cancelled);
                }

                Level lowerLevel = null;
                Level upperLevel = null;

                Element lowerLevelElement = null;
                Element upperLevelElement = null;

                if (currentUI.selectedLowerLevel != 0 && currentUI.selectedLowerLevel != -1)
                {
                    lowerLevelElement = doc.GetElement(new ElementId(currentUI.selectedLowerLevel));
                }

                if (currentUI.selectedUpperLevel != 0 && currentUI.selectedUpperLevel != -1)
                {
                    upperLevelElement = doc.GetElement(new ElementId(currentUI.selectedUpperLevel));
                }

                if (lowerLevelElement != null)
                {
                    lowerLevel = lowerLevelElement as Level;
                }

                if (upperLevelElement != null)
                {
                    upperLevel = GetNextLevel(upperLevelElement as Level);
                }


                IList <Element>   ElementsToJoin    = GetElementsOnLevels(doc, firstCat, lowerLevel, upperLevel);
                IList <ElementId> elementsIdsToJoin = new List <ElementId>();

                foreach (Element currentElement in ElementsToJoin)
                {
                    elementsIdsToJoin.Add(currentElement.Id);
                }

                IList <Element> elementsIntersecting = new List <Element>();

                using (Transaction t = new Transaction(doc, Properties.Messages.ElementJoin_JoinTransaction))
                {
                    t.Start();

                    FailureHandlingOptions joinFailOp = t.GetFailureHandlingOptions();
                    joinFailOp.SetFailuresPreprocessor(new JoinFailurAdvHandler());
                    t.SetFailureHandlingOptions(joinFailOp);

                    IList <Element>   elementsIToBeJoin   = GetElementsOnLevels(doc, secondCat, lowerLevel, upperLevel);
                    IList <ElementId> elementsIdsToBeJoin = new List <ElementId>();

                    foreach (Element currentElement in elementsIToBeJoin)
                    {
                        elementsIdsToBeJoin.Add(currentElement.Id);
                    }

                    foreach (Element currentElementToJoin in ElementsToJoin)
                    {
                        BoundingBoxXYZ bBox = currentElementToJoin.get_BoundingBox(null);
                        bBox.Enabled = true;
                        Outline outlineToJoin = new Outline(bBox.Min, bBox.Max);

                        BoundingBoxIntersectsFilter bbIntersects = new BoundingBoxIntersectsFilter(outlineToJoin, Utils.ConvertM.cmToFeet(0.5));

                        elementsIntersecting = new FilteredElementCollector(doc, elementsIdsToBeJoin).OfCategory(secondCat).WherePasses(bbIntersects).ToElements();

                        ElementIntersectsElementFilter intersectFilter = new ElementIntersectsElementFilter(currentElementToJoin);

                        foreach (Element currentElementToBeJoined in elementsIntersecting)
                        {
                            if (currentUI.join)
                            {
                                if (currentElementToJoin.Id == currentElementToBeJoined.Id)
                                {
                                    continue;
                                }

                                if (currentElementToJoin.Category.Id != currentElementToBeJoined.Category.Id)
                                {
                                    if (!intersectFilter.PassesFilter(currentElementToBeJoined))
                                    {
                                        continue;
                                    }
                                }



                                if (!JoinGeometryUtils.AreElementsJoined(doc, currentElementToJoin, currentElementToBeJoined))
                                {
                                    try
                                    {
                                        JoinGeometryUtils.JoinGeometry(doc, currentElementToJoin, currentElementToBeJoined);
                                    }
                                    catch (Exception e)
                                    {
                                        System.Diagnostics.Debug.Print(e.Message);
                                    }
                                }
                            }
                            else
                            {
                                if (JoinGeometryUtils.AreElementsJoined(doc, currentElementToJoin, currentElementToBeJoined))
                                {
                                    try
                                    {
                                        JoinGeometryUtils.UnjoinGeometry(doc, currentElementToJoin, currentElementToBeJoined);
                                    }
                                    catch (Exception e)
                                    {
                                        System.Diagnostics.Debug.Print(e.Message);
                                    }
                                }
                            }
                        }
                    }
                    t.Commit();
                }
            }
            catch (Exception excep)
            {
                ExceptionManager eManager = new ExceptionManager(excep);
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 15
0
        public static Result Do(UIApplication uiapp, Dictionary <ElementId, double> level)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            List <XYZ>   points      = new List <XYZ>();
            List <Curve> SplitCurves = new List <Curve>();

            List <double> _elevations = RevitModel.LevelElevation.GetElevations(doc);

            foreach (ElementId e1 in GlobalVariables.SplitObjects)
            {
                Curve c1 = Elements.GetCurve(doc, level, e1);

                if (null != c1)
                {
                    SplitCurves.Add(c1);

                    foreach (ElementId e2 in GlobalVariables.CutObjects)
                    {
                        Curve c2 = Elements.GetCurve(doc, level, e2);

                        if (null != c2)
                        {
                            XYZ intersection = GetIntersection(c1, c2);

                            if (intersection != null && !PointAlreadyInList.Check(points, intersection))
                            {
                                points.Add(intersection);
                            }
                        }
                    }
                }
            }

            using (TransactionGroup transgroup = new TransactionGroup(doc, "Intersect Geometry"))
            {
                try
                {
                    if (transgroup.Start() != TransactionStatus.Started)
                    {
                        return(Result.Failed);
                    }

                    foreach (ElementId e1 in GlobalVariables.SplitObjects)
                    {
                        Curve          c         = Elements.GetCurve(doc, level, e1);
                        FamilyInstance f         = Elements.GetFamilyInstance(doc, level, e1);
                        List <Curve>   newCurves = ElementSplitter.Do(c, points);

                        ICollection <ElementId> newElements = null;

                        for (int i = 0; i < newCurves.Count; i++)
                        {
                            if (i != 0)     // First Element different - just change endpoint
                                            // All other make copy first
                            {
                                using (Transaction trans = new Transaction(doc, "Copy element."))
                                {
                                    try
                                    {
                                        if (trans.Start() != TransactionStatus.Started)
                                        {
                                            return(Result.Failed);
                                        }

                                        XYZ transform = newCurves[i].GetEndPoint(0) - c.GetEndPoint(0);
                                        newElements = Elements.Transform(doc, e1, transform);

                                        if (TransactionStatus.Committed != trans.Commit())
                                        {
                                            trans.RollBack();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.ToString());
                                        trans.RollBack();
                                    }
                                }

                                foreach (ElementId id in newElements)
                                {
                                    // Change Curve
                                    using (Transaction trans = new Transaction(doc, "Transform element."))
                                    {
                                        try
                                        {
                                            if (trans.Start() != TransactionStatus.Started)
                                            {
                                                return(Result.Failed);
                                            }

                                            FamilyInstance newf = Elements.GetFamilyInstance(doc, level, id);
                                            Elements.ChangeEndPoint(doc, newCurves[i], newf, level, _elevations);

                                            FailureHandlingOptions options = trans.GetFailureHandlingOptions();
                                            options.SetFailuresPreprocessor(new WarningSwallower());

                                            if (TransactionStatus.Committed != trans.Commit(options))
                                            {
                                                trans.RollBack();
                                            }
                                        }
                                        catch
                                        {
                                            trans.RollBack();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                using (Transaction trans = new Transaction(doc, "Transform element."))
                                {
                                    try
                                    {
                                        if (trans.Start() != TransactionStatus.Started)
                                        {
                                            return(Result.Failed);
                                        }

                                        foreach (ElementId eId in JoinGeometryUtils.GetJoinedElements(doc, f))
                                        {
                                            JoinGeometryUtils.UnjoinGeometry(doc, doc.GetElement(e1), doc.GetElement(eId));
                                        }

                                        FailureHandlingOptions options = trans.GetFailureHandlingOptions();
                                        options.SetFailuresPreprocessor(new WarningSwallower());

                                        if (TransactionStatus.Committed != trans.Commit(options))
                                        {
                                            trans.RollBack();
                                        }
                                    }
                                    catch
                                    {
                                        trans.RollBack();
                                    }
                                }
                                using (Transaction trans = new Transaction(doc, "Transform element."))
                                {
                                    try
                                    {
                                        if (trans.Start() != TransactionStatus.Started)
                                        {
                                            return(Result.Failed);
                                        }

                                        LocationCurve orig_location = f.Location as LocationCurve;
                                        double        orig_len      = orig_location.Curve.Length;

                                        double up_len = newCurves[i].Length;

                                        Elements.ChangeEndPoint(doc, newCurves[i], f, level, _elevations);

                                        LocationCurve after_location = f.Location as LocationCurve;
                                        double        after_len      = after_location.Curve.Length;
                                        doc.Regenerate();

                                        LocationCurve regen_location = f.Location as LocationCurve;
                                        double        regen_len      = regen_location.Curve.Length;

                                        uidoc.RefreshActiveView();

                                        FailureHandlingOptions options = trans.GetFailureHandlingOptions();
                                        options.SetFailuresPreprocessor(new WarningSwallower());
                                        options.SetClearAfterRollback(true);

                                        if (TransactionStatus.Committed != trans.Commit(options))
                                        {
                                            trans.RollBack();
                                            return(Result.Failed);
                                        }
                                    }
                                    catch
                                    {
                                        trans.RollBack();
                                        return(Result.Failed);
                                    }
                                }
                            }
                        }
                    }
                    if (transgroup.Assimilate() == TransactionStatus.Committed)
                    {
                        return(Result.Succeeded);
                    }
                    else
                    {
                        return(Result.Failed);
                    }
                }
                catch
                {
                    transgroup.RollBack();
                    return(Result.Failed);
                }
            }
        }
Ejemplo n.º 16
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document  doc = commandData.Application.ActiveUIDocument.Document;
            Selection sel = commandData.Application.ActiveUIDocument.Selection;

            if (sel.GetElementIds().Count != 1)
            {
                message = "Выберите одну стену";
                return(Result.Failed);
            }

            Wall wall = doc.GetElement(sel.GetElementIds().First()) as Wall;

            if (wall == null)
            {
                message = "Выберите стену";
                return(Result.Failed);
            }

            List <FamilyInstance> holesInWall = new FilteredElementCollector(doc)
                                                .OfCategory(BuiltInCategory.OST_GenericModel)
                                                .OfClass(typeof(FamilyInstance))
                                                .Cast <FamilyInstance>()
                                                .Where(i => i.Symbol.FamilyName.StartsWith("231"))
                                                .Where(i => JoinGeometryUtils.AreElementsJoined(doc, wall, i))
                                                .ToList();

            List <FamilyInstance> doorsInWall = new FilteredElementCollector(doc)
                                                .OfCategory(BuiltInCategory.OST_Windows)
                                                .OfClass(typeof(FamilyInstance))
                                                .Cast <FamilyInstance>()
                                                .Where(i => i.Symbol.FamilyName.StartsWith("231"))
                                                .Where(i => i.Host.Id == wall.Id)
                                                .ToList();


            using (Transaction t = new Transaction(doc))
            {
                t.Start("Отсоединяю отверстия");

                //Отсоединяю отверстия
                foreach (FamilyInstance hole in holesInWall)
                {
                    JoinGeometryUtils.UnjoinGeometry(doc, wall, hole);
                }

                doc.Regenerate();


                if (doorsInWall.Count > 0) //есть дверь или проем в стене, меняю её размеры
                {
                    FamilyInstance door = doorsInWall.First();
                    //меняю размер двери
                    Parameter widthParam = door.LookupParameter("Рзм.Ширина");
                    double    width      = widthParam.AsDouble();
                    double    width2     = width + 0.01;
                    widthParam.Set(width2);

                    doc.Regenerate();
                    widthParam.Set(width);
                }
                else //нет двери, значит меняю высоту стены
                {
                    Parameter offsetParam = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
                    double    baseOffset  = offsetParam.AsDouble();
                    double    baseOffset2 = baseOffset - 0.01;

                    offsetParam.Set(baseOffset2);
                    doc.Regenerate();
                    offsetParam.Set(baseOffset);
                }
                doc.Regenerate();

                //присоединяю отверстия обратно
                foreach (FamilyInstance hole in holesInWall)
                {
                    JoinGeometryUtils.JoinGeometry(doc, hole, wall);
                }

                t.Commit();
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 17
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                Document doc = commandData.Application.ActiveUIDocument.Document;
                List <FailureMessage> messages = doc.GetWarnings().ToList();
                Dictionary <int, List <ElementId> > elemsDictToUnjoin = new Dictionary <int, List <ElementId> >();
                int indexUnjoin = 0;
                foreach (FailureMessage mess in messages)
                {
                    String description = mess.GetDescriptionText();
                    if (description.Contains("Выделенные элементы объединены, но они не пересекаются"))
                    {
                        indexUnjoin++;
                        List <ElementId> failingElems = mess.GetFailingElements().ToList();
                        elemsDictToUnjoin.Add(indexUnjoin, failingElems);
                    }
                }
                int    max    = elemsDictToUnjoin.Keys.Count();
                string format = "{0} из " + max.ToString() + " элементов обработано";
                using (Progress_Single pb = new Progress_Single("Отсоединение элементов", format, max))
                {
                    using (Transaction t = new Transaction(doc))
                    {
                        t.Start("Отсоединение элементов");
                        int counterUnj      = 0;
                        int faultCounterUnj = 0;
                        Print("Начинаю отсоединение элементов. Может занять продолжительное время ↑", KPLN_Loader.Preferences.MessageType.Header);
                        foreach (int key in elemsDictToUnjoin.Keys)
                        {
                            pb.Increment();
                            List <ElementId> unjElems = elemsDictToUnjoin[key];
                            Element          elem1    = doc.GetElement(unjElems[0]);
                            Element          elem2    = doc.GetElement(unjElems[1]);
                            if (JoinGeometryUtils.AreElementsJoined(doc, elem1, elem2))
                            {
                                try
                                {
                                    JoinGeometryUtils.UnjoinGeometry(doc, elem1, elem2);
                                    doc.Regenerate();
                                }
                                catch (Exception e)
                                {
                                    PrintError(e);
                                }

                                if (JoinGeometryUtils.AreElementsJoined(doc, elem1, elem2))
                                {
                                    Print(string.Format("Не удалось отсоединить элементы: {0} id:{1} и {2} id:{3}",
                                                        elem1.Name,
                                                        elem1.Id.IntegerValue,
                                                        elem2.Name,
                                                        elem2.Id.IntegerValue
                                                        ),
                                          KPLN_Loader.Preferences.MessageType.System_Regular);
                                    faultCounterUnj++;
                                }
                                else
                                {
                                    counterUnj++;
                                }
                            }
                        }

                        Print(string.Format("Обработано конфликтов: {0}", counterUnj),
                              KPLN_Loader.Preferences.MessageType.System_OK);
                        Print(string.Format("Не удалось обработать конфликтов: {0}", faultCounterUnj),
                              KPLN_Loader.Preferences.MessageType.System_OK);

                        t.Commit();
                    }
                }
                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                PrintError(e, "Произошла ошибка во время запуска скрипта");
                return(Result.Failed);
            }
        }
Ejemplo n.º 18
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;

            var categories = Enum.GetNames(typeof(BuiltInCategory));
            var viewmodel  = new AutoJoinDialogViewModel(categories.OrderBy(s => s).ToArray());
            var window     = new AutoJoinDialog(viewmodel);

            window.ShowDialog();

            if (window.DialogResult == true)
            {
                Enum.TryParse(viewmodel.Category1, out BuiltInCategory category1);
                Enum.TryParse(viewmodel.Category2, out BuiltInCategory category2);

                var eles = new FilteredElementCollector(doc).OfCategory(category1)
                           .WhereElementIsNotElementType()
                           .ToElements();

                using (var tran = new Transaction(doc, "Join Floor and Column"))
                {
                    tran.Start();
                    foreach (var ele in eles)
                    {
                        var boundingBox = ele.get_BoundingBox(null);
                        var outline     = new Outline(boundingBox.Min, boundingBox.Max);
                        var filter      = new BoundingBoxIntersectsFilter(outline);

                        var collectors = new FilteredElementCollector(doc).OfCategory(category2)
                                         .WhereElementIsNotElementType()
                                         .WherePasses(filter)
                                         .ToElements();

                        foreach (var item in collectors)
                        {
                            //Options options = new Options();
                            //options.ComputeReferences = true;
                            //options.DetailLevel = ViewDetailLevel.Fine;
                            //GeometryElement geoElement = item.get_Geometry(options);

                            bool joined = JoinGeometryUtils.AreElementsJoined(doc, ele, item);
                            if (joined == true)
                            {
                                JoinGeometryUtils.UnjoinGeometry(doc, ele, item);
                                JoinGeometryUtils.JoinGeometry(doc, ele, item);
                            }
                            else
                            {
                                JoinGeometryUtils.JoinGeometry(doc, ele, item);
                            }
                            //JoinGeometryUtils.SwitchJoinOrder(doc, ele, item);
                        }
                    }
                    tran.Commit();
                }
            }


            return(Result.Succeeded);
        }
        private void Button1_Click(object sender, EventArgs e)
        {
            //Code here
            string comboA = comboBox1.SelectedItem.ToString();
            string comboB = comboBox2.SelectedItem.ToString();

            if (comboA == comboB)
            {
                MessageBox.Show("Please select diffirent combo above");
                return;
            }
            bool checkJoin       = radioButton1.Checked;
            bool checkUnJoin     = radioButton2.Checked;
            bool checkSwitchJoin = radioButton3.Checked;

            // Get data for combo A,B
            List <Element> listA = new List <Element>();
            List <Element> listB = new List <Element>();

            FilteredElementCollector collectorA = new FilteredElementCollector(doc);

            switch (comboA)
            {
            case "Beam":
                listA = collectorA.OfCategory(BuiltInCategory.OST_StructuralFraming)
                        .WhereElementIsNotElementType().ToElements().ToList();
                break;

            case "Column":
                listA = collectorA.OfCategory(BuiltInCategory.OST_StructuralColumns)
                        .WhereElementIsNotElementType().ToElements().ToList();
                break;

            case "Deck":
                listA = collectorA.OfCategory(BuiltInCategory.OST_Floors)
                        .WhereElementIsNotElementType().ToElements().ToList();
                break;
            }
            FilteredElementCollector collectorB = new FilteredElementCollector(doc);

            switch (comboB)
            {
            case "Beam":
                listB = collectorB.OfCategory(BuiltInCategory.OST_StructuralFraming)
                        .WhereElementIsNotElementType().ToElements().ToList();
                break;

            case "Column":
                listB = collectorB.OfCategory(BuiltInCategory.OST_StructuralColumns)
                        .WhereElementIsNotElementType().ToElements().ToList();
                break;

            case "Deck":
                listB = collectorB.OfCategory(BuiltInCategory.OST_Floors)
                        .WhereElementIsNotElementType().ToElements().ToList();
                break;
            }

            if (checkJoin)
            {
                Transaction tran = new Transaction(doc);
                tran.Start($"Auto Join {comboA} to {comboB}");
                int count = 0;
                foreach (Element a in listA)
                {
                    foreach (Element b in listB)
                    {
                        try
                        {
                            JoinGeometryUtils.JoinGeometry(doc, a, b);
                            count++;
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                tran.Commit();
                MessageBox.Show($"Auto join {count} pairs of {comboA} {comboB} done!");
            }
            else if (checkUnJoin)
            {
                Transaction tran = new Transaction(doc);
                tran.Start($"Auto UnJoin {comboA} to {comboB}");
                int count = 0;
                foreach (Element a in listA)
                {
                    foreach (Element b in listB)
                    {
                        try
                        {
                            JoinGeometryUtils.UnjoinGeometry(doc, a, b);
                            count++;
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                tran.Commit();
                MessageBox.Show($"Auto Unjoin {count} pairs of {comboA} {comboB} done!");
            }
            else if (checkSwitchJoin)
            {
                Transaction tran = new Transaction(doc);
                tran.Start("Switch Beam PRT Column");
                int count = 0;
                foreach (Element a in listA)
                {
                    foreach (Element b in listB)
                    {
                        if (JoinGeometryUtils.AreElementsJoined(doc, a, b))
                        {
                            if (!JoinGeometryUtils.IsCuttingElementInJoin(doc, a, b))
                            {
                                JoinGeometryUtils.SwitchJoinOrder(doc, a, b);
                                count++;
                            }
                            else
                            {
                                JoinGeometryUtils.SwitchJoinOrder(doc, b, a);
                                count++;
                            }
                        }
                    }
                }

                tran.Commit();
                MessageBox.Show($"Auto switch {count} pairs of {comboA} {comboB} done!");
            }
            else
            {
                MessageBox.Show("Please select mode before run.");
            }
        }
Ejemplo n.º 20
0
        private void JoinOrUnJoinElements(bool join)
        {
            if (uidoc != null)
            {
                if (joinSelectUI.currentFirstElementList != null && joinSelectUI.currentSecondElementList != null)
                {
                    bool secondElementsWasEmpty = false;
                    // if we the second elements were not selected, use the first list
                    if (joinSelectUI.currentFirstElementList.Count == 0)
                    {
                        return;
                    }

                    if (joinSelectUI.currentSecondElementList.Count == 0)
                    {
                        secondElementsWasEmpty = true;
                        joinSelectUI.currentSecondElementList = joinSelectUI.currentFirstElementList.ToList();
                    }

                    string transactionName = join ? Properties.Messages.ElementJoinSelect_JoinTransaction : Properties.Messages.ElementJoinSelect_UnJoinTransaction;

                    using (Transaction t = new Transaction(uidoc.Document, transactionName))
                    {
                        t.Start();

                        FailureHandlingOptions joinFailOp = t.GetFailureHandlingOptions();
                        joinFailOp.SetFailuresPreprocessor(new JoinFailurAdvHandler());
                        t.SetFailureHandlingOptions(joinFailOp);

                        foreach (Element currentElementToJoin in joinSelectUI.currentFirstElementList)
                        {
                            BoundingBoxXYZ bBox = currentElementToJoin.get_BoundingBox(null);
                            bBox.Enabled = true;
                            Outline outLine = new Outline(bBox.Min, bBox.Max);

                            BoundingBoxIntersectsFilter    bbIntersects    = new BoundingBoxIntersectsFilter(outLine, Utils.ConvertM.cmToFeet(3));
                            ElementIntersectsElementFilter intersectFilter = new ElementIntersectsElementFilter(currentElementToJoin);

                            foreach (Element currentElementToBeJoined in joinSelectUI.currentSecondElementList)
                            {
                                if (join)
                                {
                                    if (currentElementToJoin.Id == currentElementToBeJoined.Id)
                                    {
                                        continue;
                                    }

                                    if (!bbIntersects.PassesFilter(currentElementToBeJoined))
                                    {
                                        continue;
                                    }

                                    if (currentElementToJoin.Category.Id != currentElementToBeJoined.Category.Id)
                                    {
                                        if (!intersectFilter.PassesFilter(currentElementToBeJoined))
                                        {
                                            continue;
                                        }
                                    }

                                    if (!JoinGeometryUtils.AreElementsJoined(uidoc.Document, currentElementToJoin, currentElementToBeJoined))
                                    {
                                        try
                                        {
                                            JoinGeometryUtils.JoinGeometry(uidoc.Document, currentElementToJoin, currentElementToBeJoined);
                                        }
                                        catch (Exception e)
                                        {
                                            System.Diagnostics.Debug.Print(e.Message);
                                        }
                                    }
                                }
                                else
                                {
                                    if (JoinGeometryUtils.AreElementsJoined(uidoc.Document, currentElementToJoin, currentElementToBeJoined))
                                    {
                                        try
                                        {
                                            JoinGeometryUtils.UnjoinGeometry(uidoc.Document, currentElementToJoin, currentElementToBeJoined);
                                        }
                                        catch (Exception e)
                                        {
                                            System.Diagnostics.Debug.Print(e.Message);
                                        }
                                    }
                                }
                            }
                        }

                        if (secondElementsWasEmpty)
                        {
                            joinSelectUI.currentSecondElementList = new List <Element>();
                        }

                        t.Commit();
                    }
                }
            }
        }
Ejemplo n.º 21
0
        //---//
        private void button1_Click(object sender, EventArgs e)
        {
            //code here
            string chooseA = comboBoxA.SelectedItem.ToString();
            string chooseB = comboBoxB.SelectedItem.ToString();

            List <Element> listA = GetElementByKey(chooseA);
            List <Element> listB = GetElementByKey(chooseB);

            //Code

            if (AutoJoin.Checked)
            {
                //join
                try
                {
                    Transaction tran = new Transaction(doc);
                    tran.Start($"Join {chooseA} to {chooseB}");
                    int count = 0;
                    foreach (Element a in listA)
                    {
                        foreach (Element b in listB)
                        {
                            try
                            {
                                JoinGeometryUtils.JoinGeometry(doc, a, b);
                                count++;
                            }
                            catch (Exception exx)
                            {
                            }
                        }
                    }
                    tran.Commit();
                    MessageBox.Show($"Auto Join {count} pairs of {chooseA} {chooseB} done!");
                }
                catch (Exception ex)
                {
                }
            }
            else if (AutoUnJoin.Checked)
            {
                //Unjoin
                try
                {
                    Transaction tran = new Transaction(doc);
                    tran.Start($"UnJoin {chooseA} to {chooseB}");
                    int count = 0;
                    foreach (Element a in listA)
                    {
                        foreach (Element b in listB)
                        {
                            try
                            {
                                JoinGeometryUtils.UnjoinGeometry(doc, a, b);
                                count++;
                            }
                            catch (Exception exx)
                            {
                            }
                        }
                    }
                    tran.Commit();
                    MessageBox.Show($"Auto UnJoin {count} pairs of {chooseA} {chooseB} done!");
                }
                catch (Exception ex)
                {
                }
            }
            else if (SwitchJoin.Checked)
            {
                // Switch join
                try
                {
                    Transaction tran = new Transaction(doc);
                    tran.Start($"Switch {chooseA} PRT {chooseB}");
                    int count = 0;
                    foreach (Element a in listA)
                    {
                        foreach (Element b in listB)
                        {
                            if (JoinGeometryUtils.AreElementsJoined(doc, a, b))
                            {
                                if (!JoinGeometryUtils.IsCuttingElementInJoin(doc, b, a))
                                {
                                    JoinGeometryUtils.SwitchJoinOrder(doc, b, a);
                                    count++;
                                }
                            }
                        }
                    }
                    tran.Commit();
                    MessageBox.Show($"Auto switchjoin {count} pairs of {chooseA} {chooseB} done!");
                }
                catch (Exception ex)
                {
                }
            }
            else
            {
                MessageBox.Show("Please choose one option!");
            }
            Close();
        }