Example #1
0
        private RoomInfo Getinfo_Room(Document document, Room room)
        {
            if (room != null)

            {
                var info = new RoomInfo();
                info.Room       = room;
                info.RoomName   = room.Name;
                info.RoomLevel  = room.Level.Name;
                info.RoomNumber = room.Number;

                if (room.Location is LocationPoint location)
                {
                    XYZ point = location.Point;
                    info.RoomLocation = point;
                }

                #region GetHeight
                SpatialElementBoundaryOptions sebOptions = new SpatialElementBoundaryOptions
                {
                    SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish
                };
                SpatialElementGeometryCalculator calc    = new SpatialElementGeometryCalculator(document, sebOptions);
                SpatialElementGeometryResults    results = calc.CalculateSpatialElementGeometry(room);
                Solid roomSolid = results.GetGeometry();
                var   getbb     = roomSolid.GetBoundingBox();
                var   maxZ      = getbb.Max.Z;
                var   minZ      = getbb.Min.Z;
                info.RoomHeight = maxZ - minZ;
                #endregion

                IList <IList <BoundarySegment> > segments = room.GetBoundarySegments(new SpatialElementBoundaryOptions());

                if (null != segments)
                {
                    foreach (IList <BoundarySegment> segmentList in segments)
                    {
                        foreach (BoundarySegment boundarySegment in segmentList)
                        {
                            if (boundarySegment.GetCurve() is Line)
                            {
                                info.RoomBoundarySegment.Add(new RoomInfo
                                {
                                    RoomStartPoint = boundarySegment.GetCurve().GetEndPoint(0),
                                    RoomEndPoint   = boundarySegment.GetCurve().GetEndPoint(1)
                                });
                            }
                            if (boundarySegment.GetCurve() is Arc)
                            {
                                TaskDialog.Show("s", boundarySegment.GetCurve().GetType().ToString());
                            }
                        }
                    }
                }

                return(info);
            }

            return(null);
        }
Example #2
0
        /// <summary>
        /// 使用空间计算工具计算房间Solid
        /// </summary>
        /// <param name="room"></param>
        /// <returns></returns>
        /// <remarks>轮廓上没问题,在高度上可能会出错</remarks>
        public static Solid GetRoomSolid(this Room room)
        {
            var bndOpt = new SpatialElementBoundaryOptions();
            SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(room.Document, bndOpt);
            SpatialElementGeometryResults    results    = calculator.CalculateSpatialElementGeometry(room); // compute the room geometry
            Solid roomSolid = results.GetGeometry();                                                        // get the solid representing the room's geometry

            return(roomSolid);
        }
Example #3
0
        public void Draw()
        {
            sortedlocalsTech = sortedlocalsTech.Distinct(new CusComparer()).ToList();
            try
            {
                for (int i = 0; i < sortedlocalsTech.Count(); i += 1)
                {
                    foreach (var item in sortedlocalsTech.ElementAt(i))
                    {
                        var myspace = doc.GetElement(item.Id) as Space;
                        SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(doc);
                        SpatialElementGeometryResults    results    = calculator.CalculateSpatialElementGeometry(myspace); // compute the room geometry
                        Solid roomSolid = results.GetGeometry();
                        results.GetGeometry();

                        XYZ sp = null, ep = null;

                        ElementId levelId  = ElementId.InvalidElementId;
                        Document  document = uidoc.Document;
                        Utils.lazyInstance.GetElementLocation(out sp, myspace);
                        BoundingBoxXYZ bbxyz = myspace.get_BoundingBox(null);

                        bbxyz.Enabled = true;
                        List <XYZ> edges = new List <XYZ>();
                        edges.Add(new XYZ(Math.Round(bbxyz.get_Bounds(0).X, 2), Math.Round(bbxyz.get_Bounds(0).Y, 2), Math.Round(bbxyz.get_Bounds(1).Z, 2)));
                        edges.Add(new XYZ(Math.Round(bbxyz.get_Bounds(1).X, 2), Math.Round(bbxyz.get_Bounds(0).Y, 2), Math.Round(bbxyz.get_Bounds(1).Z, 2)));
                        edges.Add(new XYZ(Math.Round(bbxyz.get_Bounds(0).X, 2), Math.Round(bbxyz.get_Bounds(0).Y, 2), Math.Round(bbxyz.get_Bounds(0).Z, 2)));
                        edges.Add(new XYZ(Math.Round(bbxyz.get_Bounds(1).X, 2), Math.Round(bbxyz.get_Bounds(0).Y, 2), Math.Round(bbxyz.get_Bounds(0).Z, 2)));
                        edges.Add(new XYZ(Math.Round(bbxyz.get_Bounds(0).X, 2), Math.Round(bbxyz.get_Bounds(1).Y, 2), Math.Round(bbxyz.get_Bounds(1).Z, 2)));
                        edges.Add(new XYZ(Math.Round(bbxyz.get_Bounds(1).X, 2), Math.Round(bbxyz.get_Bounds(1).Y, 2), Math.Round(bbxyz.get_Bounds(1).Z, 2)));
                        edges.Add(new XYZ(Math.Round(bbxyz.get_Bounds(0).X, 2), Math.Round(bbxyz.get_Bounds(1).Y, 2), Math.Round(bbxyz.get_Bounds(0).Z, 2)));
                        edges.Add(new XYZ(Math.Round(bbxyz.get_Bounds(1).X, 2), Math.Round(bbxyz.get_Bounds(1).Y, 2), Math.Round(bbxyz.get_Bounds(0).Z, 2)));

                        Utils.lazyInstance.GetLowestAndHighestPolygon(edges, myspace.Level);
                        RevitDataContext.lazyInstance.SpacesInfo.Add(myspace, new Tuple <XYZ,
                                                                                         List <XYZ>,
                                                                                         List <XYZ>,
                                                                                         List <XYZ> >(Utils.lazyInstance.GetCenterOfPolygon(edges),
                                                                                                      edges, new List <XYZ>(Utils.lazyInstance.lowestPolyg), new List <XYZ>(Utils.lazyInstance.highestPolyg)));
                        ep = sp;
                    }
                    Debug.WriteLine("count(): " + RevitDataContext.lazyInstance.SpacesInfo.Count());
                    CreateDucts(i);
                    correspSmallestSpaces.Clear();
                    tiltingSpaces.Clear();
                    currentConnectors.Clear();
                    CorrespIntersec.Clear();
                    RevitDataContext.lazyInstance.SpacesInfo.Clear();
                }
            }
            catch
            {
                TaskDialog.Show("Erreur", "Erreur: Vérifier bien que toutes les gaines ont été correctement assigné. Supprimez tous les espaces non assignés et non clos.");
            }
        }
Example #4
0
        public double CalculateFamilyInstanceBBRadius()
        {
            BoundingBoxXYZ familySolidBB = null;

            using (Transaction tx = new Transaction(m_doc))
            {
                tx.Start("Transaction Temp");

                // Get a bottom face from room solid
                SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(m_doc);
                SpatialElementGeometryResults    results    = calculator.CalculateSpatialElementGeometry(m_room);
                Solid      roomSolid = results.GetGeometry();
                PlanarFace roomFace  = GetBottomPlanarFaceFromSolid(roomSolid);

                // Create family instance temporarily
                FamilyInstance tempInstance = m_doc.Create.NewFamilyInstance(roomFace.Origin, m_familySymbol, m_level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                // Get a boudingbox of family instance
                Options getometryOptions = new Options();
                getometryOptions.IncludeNonVisibleObjects = false;
                getometryOptions.View = m_view;

                GeometryElement geoElem = tempInstance.get_Geometry(getometryOptions);

                foreach (GeometryObject geoObject in geoElem)
                {
                    GeometryInstance geoInst = geoObject as GeometryInstance;

                    foreach (GeometryObject instanceGeoObject in geoInst.GetInstanceGeometry())
                    {
                        if (instanceGeoObject is Solid)
                        {
                            Solid solid = (Solid)instanceGeoObject;

                            familySolidBB = solid.GetBoundingBox();
                        }
                    }
                }

                tx.RollBack();
            }

            // Calculate perimeter of family instance
            XYZ familySolidBBMaxPt = familySolidBB.Max;
            XYZ familySolidBBMinPt = familySolidBB.Min;

            XYZ    minPt = new XYZ(familySolidBBMinPt.X, familySolidBBMinPt.Y, 0.0);
            XYZ    maxPt = new XYZ(familySolidBBMaxPt.X, familySolidBBMaxPt.Y, 0.0);
            double familySolidBBRadius = (minPt.DistanceTo(maxPt)) / 2;

            familySolidBBRadius = Math.Round(familySolidBBRadius, 4, MidpointRounding.AwayFromZero);

            return(familySolidBBRadius);
        }
Example #5
0
        public static void MoveRoomToCentroid(Document doc, List <Room> modelRooms)
        {
            SpatialElementGeometryCalculator geomCalculator = new SpatialElementGeometryCalculator(doc);
            bool NotEnclosedRooms = false;  //declare variable to detect Not Enclosed rooms

            foreach (Room r in modelRooms)
            {
                if (r.Area == 0) //are there not enclosed rooms?
                {
                    NotEnclosedRooms = true;
                    continue;
                }
                if (r.Area > 0) //hadle exception for Not Enclosed rooms when trying to calculate SpatialElementGeometry
                {
                    Location      rLoc            = r.Location;
                    LocationPoint currentLoc      = (LocationPoint)r.Location;
                    XYZ           currentLocPoint = currentLoc.Point;

                    SpatialElementGeometryResults geomResults = geomCalculator.CalculateSpatialElementGeometry(r);
                    Solid roomSolid    = geomResults.GetGeometry();
                    XYZ   roomCentroid = roomSolid.ComputeCentroid();

                    XYZ moveVector = new XYZ(roomCentroid.X - currentLocPoint.X, roomCentroid.Y - currentLocPoint.Y, roomCentroid.Z - currentLocPoint.Z);

                    // don´t move if centroid is outside of a room
                    if (r.IsPointInRoom(roomCentroid))
                    {
                        rLoc.Move(moveVector);
                    }
                }
            }

            if (NotEnclosedRooms == true)   //warn the user about not enclosed rooms
            {
                Form.Form_Main.warningMsgMain = "Warning";
                Form.Form_Main.warningMsgBody = string.Format("There are 'Not Enclosed' rooms in this project.{0}{0}" +
                                                              " This application have ignored them," +
                                                              " but I strongly recommend you to revise them and amend as appropriate."
                                                              , Environment.NewLine);

                using (UI.Info.Form_Warning thisForm = new UI.Info.Form_Warning())
                {
                    thisForm.ShowDialog();
                }
            }
        }
Example #6
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Document      doc   = uiapp.ActiveUIDocument.Document;
            Result        rc;

            try
            {
                SpatialElementBoundaryOptions sebOptions
                    = new SpatialElementBoundaryOptions
                    {
                    SpatialElementBoundaryLocation
                        = SpatialElementBoundaryLocation.Finish
                    };

                IEnumerable <Element> rooms
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(SpatialElement))
                      .Where <Element>(e => (e is Room));

                List <string>  compareWallAndRoom = new List <string>();
                OpeningHandler openingHandler     = new OpeningHandler();

                List <SpatialBoundaryCache> lstSpatialBoundaryCache
                    = new List <SpatialBoundaryCache>();

                foreach (Room room in rooms)
                {
                    if (room == null)
                    {
                        continue;
                    }
                    if (room.Location == null)
                    {
                        continue;
                    }
                    if (room.Area.Equals(0))
                    {
                        continue;
                    }

                    Autodesk.Revit.DB.SpatialElementGeometryCalculator calc =
                        new Autodesk.Revit.DB.SpatialElementGeometryCalculator(
                            doc, sebOptions);

                    SpatialElementGeometryResults results
                        = calc.CalculateSpatialElementGeometry(
                              room);

                    Solid roomSolid = results.GetGeometry();

                    foreach (Face face in results.GetGeometry().Faces)
                    {
                        IList <SpatialElementBoundarySubface> boundaryFaceInfo
                            = results.GetBoundaryFaceInfo(face);

                        foreach (var spatialSubFace in boundaryFaceInfo)
                        {
                            if (spatialSubFace.SubfaceType
                                != SubfaceType.Side)
                            {
                                continue;
                            }

                            SpatialBoundaryCache spatialData
                                = new SpatialBoundaryCache();

                            Wall wall = doc.GetElement(spatialSubFace
                                                       .SpatialBoundaryElement.HostElementId)
                                        as Wall;

                            if (wall == null)
                            {
                                continue;
                            }

                            WallType wallType = doc.GetElement(
                                wall.GetTypeId()) as WallType;

                            if (wallType.Kind == WallKind.Curtain)
                            {
                                // Leave out, as curtain walls are not painted.

                                LogCreator.LogEntry("WallType is CurtainWall");

                                continue;
                            }

                            HostObject hostObject = wall as HostObject;

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

                            double openingArea = 0;

                            foreach (ElementId idInsert in insertsThisHost)
                            {
                                string countOnce = room.Id.ToString()
                                                   + wall.Id.ToString() + idInsert.ToString();

                                if (!compareWallAndRoom.Contains(countOnce))
                                {
                                    Element elemOpening = doc.GetElement(
                                        idInsert) as Element;

                                    openingArea = openingArea
                                                  + openingHandler.GetOpeningArea(
                                        wall, elemOpening, room, roomSolid);

                                    compareWallAndRoom.Add(countOnce);
                                }
                            }

                            // Cache SpatialElementBoundarySubface info.

                            spatialData.roomName   = room.Name;
                            spatialData.idElement  = wall.Id;
                            spatialData.idMaterial = spatialSubFace
                                                     .GetBoundingElementFace().MaterialElementId;
                            spatialData.dblNetArea = Util.sqFootToSquareM(
                                spatialSubFace.GetSubface().Area - openingArea);
                            spatialData.dblOpeningArea = Util.sqFootToSquareM(
                                openingArea);

                            lstSpatialBoundaryCache.Add(spatialData);
                        } // end foreach subface from which room bounding elements are derived
                    }     // end foreach Face
                }         // end foreach Room

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

                List <SpatialBoundaryCache> groupedData
                    = SortByRoom(lstSpatialBoundaryCache);

                foreach (SpatialBoundaryCache sbc in groupedData)
                {
                    t.Add(sbc.roomName
                          + "; all wall types and materials: "
                          + sbc.AreaReport);
                }

                Util.InfoMsg2("Total Net Area in m2 by Room",
                              string.Join(System.Environment.NewLine, t));

                t.Clear();

                groupedData = SortByRoomAndWallType(
                    lstSpatialBoundaryCache);

                foreach (SpatialBoundaryCache sbc in groupedData)
                {
                    Element elemWall = doc.GetElement(
                        sbc.idElement) as Element;

                    t.Add(sbc.roomName + "; " + elemWall.Name
                          + "(" + sbc.idElement.ToString() + "): "
                          + sbc.AreaReport);
                }

                Util.InfoMsg2("Net Area in m2 by Wall Type",
                              string.Join(System.Environment.NewLine, t));

                t.Clear();

                groupedData = SortByRoomAndMaterial(
                    lstSpatialBoundaryCache);

                foreach (SpatialBoundaryCache sbc in groupedData)
                {
                    string materialName
                        = (sbc.idMaterial == ElementId.InvalidElementId)
              ? string.Empty
              : doc.GetElement(sbc.idMaterial).Name;

                    t.Add(sbc.roomName + "; " + materialName + ": "
                          + sbc.AreaReport);
                }

                Util.InfoMsg2(
                    "Net Area in m2 by Outer Layer Material",
                    string.Join(System.Environment.NewLine, t));

                rc = Result.Succeeded;
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Room Boundaries",
                                ex.Message + "\r\n" + ex.StackTrace);

                rc = Result.Failed;
            }
            return(rc);
        }
Example #7
0
        /// <summary>
        /// Test whether each room has a roof to bound it.
        /// </summary>
        /// <param name="message">Error message to be dumped.</param>
        /// <param name="elements">Some elements to return.</param>
        /// <returns></returns>
        private bool FindRoomBoundingRoofs(ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // Get all rooms
            List <Element> rooms = GetRoomsElements();

            if (rooms.Count == 0)
            {
                message = "Unable to identify any rooms, please create room first!";
                return(false);
            }

            // Represents the criteria for boundary elements to be considered bounding roofs
            LogicalOrFilter categoryFilter = new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_Roofs),
                                                                 new ElementCategoryFilter(BuiltInCategory.OST_RoofSoffit));

            // Calculator for room/space geometry.
            SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(m_document);

            // Stores the resulting room->roof relationships
            Dictionary <Element, List <ElementId> > roomsAndRoofs = new Dictionary <Element, List <ElementId> >();

            foreach (Element room in rooms)
            {
                // Get room geometry & boundaries
                SpatialElementGeometryResults results = calculator.CalculateSpatialElementGeometry((SpatialElement)room);

                // Get solid geometry so we can examine each face
                Solid geometry = results.GetGeometry();

                foreach (Face face in geometry.Faces)
                {
                    // Get list of roof boundary subfaces for a given face
                    IList <SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face);
                    foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces)
                    {
                        // Get boundary element
                        LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement;

                        // Only considering local file room bounding elements
                        ElementId localElementId = boundaryElementId.HostElementId;

                        // Evaluate if element meets criteria using PassesFilter()
                        if (localElementId != ElementId.InvalidElementId && categoryFilter.PassesFilter(m_document, localElementId))
                        {
                            // Room already has roofs, add more
                            if (roomsAndRoofs.ContainsKey(room))
                            {
                                List <ElementId> roofs = roomsAndRoofs[room];
                                if (!roofs.Contains(localElementId))
                                {
                                    roofs.Add(localElementId);
                                }
                            }
                            // Room found first roof
                            else
                            {
                                List <ElementId> roofs = new List <ElementId>();
                                roofs.Add(localElementId);
                                roomsAndRoofs.Add(room, roofs);
                            }
                            break;
                        }
                    }
                }
            }

            // Format results
            if (roomsAndRoofs.Count > 0)
            {
                String logs = String.Format("Rooms that have a bounding roof:");
                message += logs + "\t\r\n";
                Trace.WriteLine(logs);
                foreach (KeyValuePair <Element, List <ElementId> > kvp in roomsAndRoofs)
                {
                    // remove this room from all rooms list
                    rooms.Remove(kvp.Key);

                    List <ElementId> roofs = kvp.Value;
                    String           roofsString;

                    // Single roof boundary
                    if (roofs.Count == 1)
                    {
                        Element roof = m_document.GetElement(roofs[0]);
                        roofsString = String.Format("Roof: Id = {0}, Name = {1}", roof.Id.IntegerValue, roof.Name);
                    }
                    // Multiple roofs
                    else
                    {
                        roofsString = "Roofs ids = " + string.Join(", ", Array.ConvertAll <ElementId, string>(roofs.ToArray(), i => i.ToString()));
                    }

                    // Save results
                    logs = String.Format(
                        "  Room: Id = {0}, Name = {1} --> {2}",
                        kvp.Key.Id.IntegerValue, kvp.Key.Name, roofsString);
                    message += logs + "\t\r\n";
                    Trace.WriteLine(logs);
                }
            }

            // Format the rooms that have no bounding roof
            Trace.WriteLine("Geometry relationship checking finished...");
            if (rooms.Count != 0)
            {
                String logs = String.Format("Below rooms don't have bounding roofs:");
                message += logs + "\t\r\n";
                Trace.WriteLine(logs);
                foreach (Element room in rooms)
                {
                    elements.Insert(room);
                    logs = String.Format("  Room Id: {0}, Room Name: {1}",
                                         room.Id.IntegerValue, room.Name);
                    message += logs + "\t\r\n";
                    Trace.WriteLine(logs);
                }
            }

            return(true);
        }
        /// <summary>
        /// Creates IFC room/space/area item, not include boundaries. 
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="spatialElement">The spatial element.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        /// <param name="setter">The PlacementSetter.</param>
        /// <returns>True if created successfully, false otherwise.</returns>
        static bool CreateIFCSpace(ExporterIFC exporterIFC, SpatialElement spatialElement, ProductWrapper productWrapper, 
            PlacementSetter setter, out SpatialElementGeometryResults results)
        {
            results = null;

            IList<CurveLoop> curveLoops = null;
            try
            {
                // Avoid throwing for a spatial element with no location.
                if (spatialElement.Location == null)
                    return false;

                SpatialElementBoundaryOptions options = GetSpatialElementBoundaryOptions(spatialElement);
                curveLoops = ExporterIFCUtils.GetRoomBoundaryAsCurveLoopArray(spatialElement, options, true);
            }
            catch (Autodesk.Revit.Exceptions.InvalidOperationException)
            {
                //Some spatial elements are not placed that have no boundary loops. Don't export them.
                return false;
            }

            Autodesk.Revit.DB.Document document = spatialElement.Document;
            ElementId levelId = spatialElement.LevelId;

            ElementId catId = spatialElement.Category != null ? spatialElement.Category.Id : ElementId.InvalidElementId;

            double dArea = 0.0;
            if (ParameterUtil.GetDoubleValueFromElement(spatialElement, BuiltInParameter.ROOM_AREA, out dArea) != null)
                dArea = UnitUtil.ScaleArea(dArea);

            IFCLevelInfo levelInfo = exporterIFC.GetLevelInfo(levelId);

            string strSpaceNumber = null;
            string strSpaceName = null;
            string strSpaceDesc = null;

            if (ParameterUtil.GetStringValueFromElement(spatialElement, BuiltInParameter.ROOM_NUMBER, out strSpaceNumber) == null)
                strSpaceNumber = null;

            if (ParameterUtil.GetStringValueFromElement(spatialElement, BuiltInParameter.ROOM_NAME, out strSpaceName) == null)
                strSpaceName = null;

            if (ParameterUtil.GetStringValueFromElement(spatialElement, BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS, out strSpaceDesc) == null)
                strSpaceDesc = null;

            string name = strSpaceNumber;
            string longName = strSpaceName;
            string desc = strSpaceDesc;

            IFCFile file = exporterIFC.GetFile();

            IFCAnyHandle localPlacement = setter.LocalPlacement;
            ElementType elemType = document.GetElement(spatialElement.GetTypeId()) as ElementType;
            IFCInternalOrExternal internalOrExternal = CategoryUtil.IsElementExternal(spatialElement) ? IFCInternalOrExternal.External : IFCInternalOrExternal.Internal;

            double scaledRoomHeight = GetScaledHeight(spatialElement, levelId, levelInfo);
            if (scaledRoomHeight <= 0.0)
                return false;

            double bottomOffset;
            ParameterUtil.GetDoubleValueFromElement(spatialElement, BuiltInParameter.ROOM_LOWER_OFFSET, out bottomOffset);

         double elevation = (levelInfo != null) ? levelInfo.Elevation : 0.0;
            XYZ zDir = new XYZ(0, 0, 1);
         XYZ orig = new XYZ(0, 0, elevation + bottomOffset);

            Plane plane = new Plane(zDir, orig); // room calculated as level offset.

            GeometryElement geomElem = null;
            bool isArea = (spatialElement is Area);
            Area spatialElementAsArea = isArea ? (spatialElement as Area) : null;

            if (spatialElement is Autodesk.Revit.DB.Architecture.Room)
            {
                Autodesk.Revit.DB.Architecture.Room room = spatialElement as Autodesk.Revit.DB.Architecture.Room;
                geomElem = room.ClosedShell;
            }
            else if (spatialElement is Autodesk.Revit.DB.Mechanical.Space)
            {
                Autodesk.Revit.DB.Mechanical.Space space = spatialElement as Autodesk.Revit.DB.Mechanical.Space;
                geomElem = space.ClosedShell;
            }
            else if (isArea)
            {
                Options geomOptions = GeometryUtil.GetIFCExportGeometryOptions();
                geomElem = spatialElementAsArea.get_Geometry(geomOptions);
            }

            IFCAnyHandle spaceHnd = null;
            string spatialElementName = null;
            using (IFCExtrusionCreationData extraParams = new IFCExtrusionCreationData())
            {
                extraParams.SetLocalPlacement(localPlacement);
                extraParams.PossibleExtrusionAxes = IFCExtrusionAxes.TryZ;

                using (IFCTransaction transaction2 = new IFCTransaction(file))
                {
                    IFCAnyHandle repHnd = null;
                    if (!ExporterCacheManager.ExportOptionsCache.Use2DRoomBoundaryForRoomVolumeCreation && geomElem != null)
                    {
                        BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true);
                        bodyExporterOptions.TessellationLevel = BodyExporter.GetTessellationLevel();
                        repHnd = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, spatialElement,
                            catId, geomElem, bodyExporterOptions, null, extraParams, false);
                        if (IFCAnyHandleUtil.IsNullOrHasNoValue(repHnd))
                            extraParams.ClearOpenings();
                    }
                    else
                    {
                        IFCAnyHandle shapeRep = ExtrusionExporter.CreateExtrudedSolidFromCurveLoop(exporterIFC, null, curveLoops, plane, zDir, scaledRoomHeight);
                        if (IFCAnyHandleUtil.IsNullOrHasNoValue(shapeRep))
                            return false;
                        IFCAnyHandle styledItemHnd = BodyExporter.CreateSurfaceStyleForRepItem(exporterIFC, document,
                            shapeRep, ElementId.InvalidElementId);

                        HashSet<IFCAnyHandle> bodyItems = new HashSet<IFCAnyHandle>();
                        bodyItems.Add(shapeRep);
                        shapeRep = RepresentationUtil.CreateSweptSolidRep(exporterIFC, spatialElement, catId, exporterIFC.Get3DContextHandle("Body"), bodyItems, null);
                        IList<IFCAnyHandle> shapeReps = new List<IFCAnyHandle>();
                        shapeReps.Add(shapeRep);

                        IFCAnyHandle boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, geomElem, Transform.Identity);
                        if (boundingBoxRep != null)
                            shapeReps.Add(boundingBoxRep);

                        repHnd = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps);
                    }

                    extraParams.ScaledHeight = scaledRoomHeight;
                    extraParams.ScaledArea = dArea;

                    spatialElementName = NamingUtil.GetNameOverride(spatialElement, name);
                    string spatialElementDescription = NamingUtil.GetDescriptionOverride(spatialElement, desc);
                    string spatialElementObjectType = NamingUtil.GetObjectTypeOverride(spatialElement, null);
                    string spatialElementLongName = NamingUtil.GetLongNameOverride(spatialElement, longName);
                    
                    double? spaceElevationWithFlooring = null;
                    double elevationWithFlooring = 0.0;
                    if (ParameterUtil.GetDoubleValueFromElement(spatialElement, null, "IfcElevationWithFlooring", out elevationWithFlooring) != null)
                        spaceElevationWithFlooring = UnitUtil.ScaleLength(elevationWithFlooring);
                    spaceHnd = IFCInstanceExporter.CreateSpace(file, GUIDUtil.CreateGUID(spatialElement),
                                                  ExporterCacheManager.OwnerHistoryHandle,
                                                  spatialElementName, spatialElementDescription, spatialElementObjectType,
                                                  extraParams.GetLocalPlacement(), repHnd, spatialElementLongName, Toolkit.IFCElementComposition.Element,
                                                  internalOrExternal, spaceElevationWithFlooring);

                    transaction2.Commit();
                }

                if (spaceHnd != null)
                {
                    productWrapper.AddSpace(spatialElement, spaceHnd, levelInfo, extraParams, true);
                    if (isArea)
                    {
                        Element areaScheme = spatialElementAsArea.AreaScheme;
                        if (areaScheme != null)
                        {
                            ElementId areaSchemeId = areaScheme.Id;
                            HashSet<IFCAnyHandle> areas = null;
                            if (!ExporterCacheManager.AreaSchemeCache.TryGetValue(areaSchemeId, out areas))
                            {
                                areas = new HashSet<IFCAnyHandle>();
                                ExporterCacheManager.AreaSchemeCache[areaSchemeId] = areas;
                            }
                            areas.Add(spaceHnd);
                        }
                    }
                }
            }

            // Save room handle for later use/relationships
            ExporterCacheManager.SpaceInfoCache.SetSpaceHandle(spatialElement, spaceHnd);

            // Find Ceiling as a Space boundary and keep the relationship in a cache for use later
            bool ret = GetCeilingSpaceBoundary(spatialElement, out results);

         if (!MathUtil.IsAlmostZero(dArea) && !(ExporterCacheManager.ExportOptionsCache.ExportAsCOBIE) &&
                !ExporterCacheManager.ExportOptionsCache.ExportAs2x3CoordinationView2 && !ExporterCacheManager.ExportOptionsCache.ExportBaseQuantities)
            {
                bool isDesignGrossArea = (string.Compare(spatialElementName, "GSA Design Gross Area") > 0);
                PropertyUtil.CreatePreCOBIEGSAQuantities(exporterIFC, spaceHnd, "GSA Space Areas", (isDesignGrossArea ? "GSA Design Gross Area" : "GSA BIM Area"), dArea);
            }

            // Export Classifications for SpatialElement for GSA/COBIE.
         if (ExporterCacheManager.ExportOptionsCache.ExportAsCOBIE)
            {
                ProjectInfo projectInfo = document.ProjectInformation;
                if (projectInfo != null)
                    CreateCOBIESpaceClassifications(exporterIFC, file, spaceHnd, projectInfo, spatialElement);
            }

            return true;
        }
        /// <summary>
        /// Collect relationship information from Ceiling to Room to be used later to determine whether a Ceiling can be contained in a Room
        /// </summary>
        /// <param name="spatialElement">The revit spatial object to process</param>
        /// <param name="results">The results of the CalculateSpatialElementGeometry call, for caching for later use.</param>
        /// <returns>True if it found a ceiling, false otherwise.</returns>
        static private bool GetCeilingSpaceBoundary(SpatialElement spatialElement, out SpatialElementGeometryResults results)
        {
            results = null;
            
            // Areas don't have a 3D rep, so no ceiling space boundaries.
            if (spatialElement is Area)
                return false;

            // Represents the criteria for boundary elements to be considered bounding Ceiling
            LogicalOrFilter categoryFilter = new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_Ceilings),
                                                        new ElementCategoryFilter(BuiltInCategory.OST_Ceilings));

            try
            {
                results = s_SpatialElementGeometryCalculator.CalculateSpatialElementGeometry(spatialElement);
            }
            catch
            {
                return false;
            }
            Solid geometry = results.GetGeometry();

            // Go through the boundary faces to identify whether it is bounded by a Ceiling. If it is Ceiling, add into the Cache
            foreach (Face face in geometry.Faces)
            {
                IList<SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face);
                foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces)
                {
                    // Get boundary element
                    LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement;

                    // Only considering local file room bounding elements
                    ElementId localElementId = boundaryElementId.HostElementId;
                    // Evaluate if element meets criteria using PassesFilter()
                    if (localElementId != ElementId.InvalidElementId && categoryFilter.PassesFilter(spatialElement.Document, localElementId))
                    {
                        if (ExporterCacheManager.CeilingSpaceRelCache.ContainsKey(localElementId))
                        {
                            // The ceiling already exists in the Dictionary, add the Space into list
                            IList<ElementId> roomlist = ExporterCacheManager.CeilingSpaceRelCache[localElementId];
                            roomlist.Add(spatialElement.Id);
                        }
                        else
                        {
                            // The first time this Ceiling Id appears
                            IList<ElementId> roomlist = new List<ElementId>();
                            roomlist.Add(spatialElement.Id);
                            ExporterCacheManager.CeilingSpaceRelCache.Add(localElementId, roomlist);
                        }

                    }
                }
            }

            return true;
        }
Example #10
0
        public static Dictionary <ElementId, double> MaterialsAreas(this SpatialElement spatialElement, double minArea = 0, SpatialElementGeometryCalculator spatialElementGeometryCalculator = null)
        {
            if (spatialElement == null)
            {
                return(null);
            }

            if (double.IsNaN(spatialElement.Area) || spatialElement.Area < minArea)
            {
                return(null);
            }

            if (spatialElementGeometryCalculator == null)
            {
                SpatialElementBoundaryOptions spatialElementBoundaryOptions = new SpatialElementBoundaryOptions()
                {
                    SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish,
                    StoreFreeBoundaryFaces         = false
                };

                spatialElementGeometryCalculator = new SpatialElementGeometryCalculator(spatialElement.Document, spatialElementBoundaryOptions);
            }

            SpatialElementGeometryResults spatialElementGeometryResults = spatialElementGeometryCalculator.CalculateSpatialElementGeometry(spatialElement);

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

            Solid solid = spatialElementGeometryResults.GetGeometry();

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

            Dictionary <ElementId, double> result = new Dictionary <ElementId, double>();

            foreach (Face face in solid.Faces)
            {
                if (face.Area < minArea)
                {
                    continue;
                }

                foreach (SpatialElementBoundarySubface spatialElementBoundarySubface in spatialElementGeometryResults.GetBoundaryFaceInfo(face))
                {
                    Face face_SpatialElement = spatialElementBoundarySubface.GetSpatialElementFace();
                    if (face_SpatialElement == null)
                    {
                        continue;
                    }

                    if (face_SpatialElement.Area < minArea)
                    {
                        continue;
                    }

                    Face face_BoundingElement = spatialElementBoundarySubface.GetBoundingElementFace();
                    if (face_BoundingElement == null)
                    {
                        continue;
                    }

                    ElementId elementId = face_BoundingElement.MaterialElementId;
                    if (elementId != null && elementId != Autodesk.Revit.DB.ElementId.InvalidElementId)
                    {
                        if (result.ContainsKey(elementId))
                        {
                            result[elementId] += face_SpatialElement.Area;
                        }
                        else
                        {
                            result[elementId] = face_SpatialElement.Area;
                        }
                    }
                }
            }

            return(result);
        }
Example #11
0
        public static List <Panel> Panels(this SpatialElement spatialElement, SpatialElementGeometryCalculator spatialElementGeometryCalculator, Core.Revit.ConvertSettings convertSettings)
        {
            if (spatialElement == null || spatialElementGeometryCalculator == null)
            {
                return(null);
            }

            SpatialElementGeometryResults spatialElementGeometryResults = spatialElementGeometryCalculator.CalculateSpatialElementGeometry(spatialElement);

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

            Solid solid = spatialElementGeometryResults.GetGeometry();

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

            List <Tuple <Face, LinkElementId, SubfaceType> > tuples = new List <Tuple <Face, LinkElementId, SubfaceType> >();

            foreach (Face face in solid.Faces)
            {
                IList <SpatialElementBoundarySubface> spatialElementBoundarySubfaces = spatialElementGeometryResults.GetBoundaryFaceInfo(face);
                if (spatialElementBoundarySubfaces == null || spatialElementBoundarySubfaces.Count == 0)
                {
                    tuples.Add(new Tuple <Face, LinkElementId, SubfaceType>(face, null, SubfaceType.Side));
                    continue;
                }

                foreach (SpatialElementBoundarySubface spatialElementBoundarySubface in spatialElementBoundarySubfaces)
                {
                    if (spatialElementBoundarySubface == null)
                    {
                        continue;
                    }

                    Face face_Subface = spatialElementBoundarySubface.GetSubface();
                    //Face face_Subface = spatialElementBoundarySubface.GetSpatialElementFace();
                    LinkElementId linkElementId = spatialElementBoundarySubface.SpatialBoundaryElement;

                    tuples.Add(new Tuple <Face, LinkElementId, SubfaceType>(face_Subface, linkElementId, spatialElementBoundarySubface.SubfaceType));
                }
            }

            List <Panel> result = new List <Panel>();

            foreach (Tuple <Face, LinkElementId, SubfaceType> tuple in tuples)
            {
                List <Geometry.Spatial.Face3D> face3Ds = Geometry.Revit.Convert.ToSAM(tuple.Item1);
                if (face3Ds == null || face3Ds.Count == 0)
                {
                    continue;
                }

                foreach (Geometry.Spatial.Face3D face3D in face3Ds)
                {
                    PanelType    panelType    = PanelType.Undefined;
                    Construction construction = null;
                    Panel        panel        = null;

                    if (tuple.Item2 != null)
                    {
                        Element element = Core.Revit.Query.Element(spatialElement.Document, tuple.Item2);
                        if (element != null)
                        {
                            HostObject hostObject = element as HostObject;
                            if (hostObject != null)
                            {
                                List <Panel> panels = hostObject.ToSAM(convertSettings);
                                if (panels != null && panels.Count > 0)
                                {
                                    panel = panels[0];
                                }

                                if (panel != null)
                                {
                                    construction = panel.Construction;
                                    panelType    = Analytical.Query.PanelType(construction?.Name);

                                    if (panelType == PanelType.Undefined)
                                    {
                                        panelType = panel.PanelType;
                                    }
                                }

                                if (panelType == PanelType.Undefined)
                                {
                                    panelType = Query.PanelType(hostObject);
                                }

                                if (construction == null)
                                {
                                    ElementId elementId_Type = hostObject.GetTypeId();
                                    if (elementId_Type != null && elementId_Type != ElementId.InvalidElementId)
                                    {
                                        construction = ((HostObjAttributes)hostObject.Document.GetElement(elementId_Type)).ToSAM(convertSettings);
                                    }
                                }
                            }
                        }
                    }

                    if (panelType == PanelType.Undefined)
                    {
                        panelType = Analytical.Query.PanelType(face3D.GetPlane()?.Normal);
                    }

                    if (panelType == PanelType.Undefined)
                    {
                        switch (tuple.Item3)
                        {
                        case SubfaceType.Bottom:
                            panelType = PanelType.Floor;
                            break;

                        case SubfaceType.Top:
                            panelType = PanelType.Roof;
                            break;

                        case SubfaceType.Side:
                            panelType = PanelType.Wall;
                            break;
                        }
                    }

                    if (construction == null)
                    {
                        construction = Analytical.Query.DefaultConstruction(panelType); //Default Construction
                    }
                    if (panel == null)
                    {
                        panel = Analytical.Create.Panel(construction, panelType, face3D);
                    }
                    else
                    {
                        panel = Analytical.Create.Panel(panel.Guid, panel, face3D);
                    }

                    result.Add(panel);
                }
            }

            return(result);
        }
        // defines the Main Method with 1 argument: ActiveUIDoc
        public void SetRoomFinishingParameters(UIDocument ActiveUIDoc)
        {
            //Active document in Revit application
            Document doc = ActiveUIDoc.Document;

            //Get collection of Rooms in indicated level
            IEnumerable <Element> collector = FindRooms(ActiveUIDoc);

            //List of RoomData
            List <RoomData> roomDataList = new List <RoomData>();

            foreach (Room r in collector)
            {
                #region Retrieving of Room Data
                //List of RoomBoudingElements
                List <Element> roomBoundingElems = new List <Element>();

                // Calculate a room's geometry and find its boundary faces
                SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(doc);
                SpatialElementGeometryResults    results    = calculator.CalculateSpatialElementGeometry(r); // compute the room geometry
                Solid roomSolid = results.GetGeometry();                                                     // get the solid representing the room's geometry

                // Go through the boundary faces to add this element to the list of roomBoundingElems
                foreach (Face face in roomSolid.Faces)
                {
                    IList <SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face);
                    foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces)
                    {
                        // Get boundary element
                        LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement;

                        // Only considering local file room bounding elements
                        ElementId localElementId = boundaryElementId.HostElementId;
                        Element   elem           = doc.GetElement(localElementId);

                        //Add Room Bounding Element to list
                        roomBoundingElems.Add(elem);
                    }
                }

                //List of all Element Types of the Room Bounding Elements
                List <Element> elemsType = new List <Element>();

                foreach (Element elem in roomBoundingElems)
                {
                    ElementId id       = elem.GetTypeId();
                    Element   elemType = doc.GetElement(id);
                    elemsType.Add(elemType);
                }

                //List of all unique Element Types of the Room Bounding Elements
                List <Element> elemsTypeDist = elemsType.Distinct(new ElemTypeIdEqualityComparer()).ToList();

                //List of all unique Element Types of the Room Bounding Elements with the Floors Assembly Code indicated
                IEnumerable <Element> finishingFloorsElemsTypes = GetFinishingElemsTypes(elemsTypeDist, finishingFloorsAssemblyCode);
                //Dictionary with Key values and Keynote Texts
                Dictionary <string, string> finishingFloorsKeynote = GetKeynote(finishingFloorsElemsTypes, ActiveUIDoc); //Dictionary<string, string>

                //List of all unique Element Types of the Room Bounding Elements with the Floors Assembly Code indicated
                IEnumerable <Element> finishingWallsElemsTypes = GetFinishingElemsTypes(elemsTypeDist, finishingWallsAssemblyCode);
                //Dictionary with Key values and Keynote Texts
                Dictionary <string, string> finishingWallsKeynote = GetKeynote(finishingWallsElemsTypes, ActiveUIDoc);

                //List of all unique Element Types of the Room Bounding Elements with the Floors Assembly Code indicated
                IEnumerable <Element> ceilingsElemsTypes = GetFinishingElemsTypes(elemsTypeDist, ceilingsAssemblyCode);
                //Dictionary with Key values and Keynote Texts
                Dictionary <string, string> ceilingsKeynote = GetKeynote(ceilingsElemsTypes, ActiveUIDoc);

                #endregion // Retrieving of Room Data

                //new RoomData class per room
                var RD = new RoomData
                {
                    room            = r,
                    elems           = roomBoundingElems,
                    finishingFloors = finishingFloorsKeynote,
                    finishingWalls  = finishingWallsKeynote,
                    ceilings        = ceilingsKeynote,
                };

                //Adds Room Data to Room Data List
                roomDataList.Add(RD);
            }

            //Fills Parameters
            FillParameters(roomDataList, doc);
        }
Example #13
0
        public static Result ExecuteCalculations(ExternalCommandData commandData)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            List <string> roomNames     = new List <string>();
            List <string> areaType      = new List <string>();
            List <string> areaValue     = new List <string>();
            List <string> levelNames    = new List <string>();
            List <string> areaValueCalc = new List <string>();

            using (Transaction t = new Transaction(doc, "Turn on volume calculation"))
            {
                t.Start();
                AreaVolumeSettings settings = AreaVolumeSettings.GetAreaVolumeSettings(doc);
                settings.ComputeVolumes = true;
                t.Commit();
            }

            // setup spacial properties
            SpatialElementBoundaryOptions sebOptions = new SpatialElementBoundaryOptions();



            // get all rooms
            FilteredElementCollector room_collector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType();
            IList <ElementId>        room_eids      = room_collector.ToElementIds() as IList <ElementId>;

            foreach (ElementId eid in room_eids)
            {
                Room room = doc.GetElement(eid) as Room;
                {
                    // grab room spacial calculations
                    sebOptions.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Center;
                    SpatialElementGeometryCalculator centerCalc = new SpatialElementGeometryCalculator(doc, sebOptions);
                    SpatialElementGeometryResults    center     = centerCalc.CalculateSpatialElementGeometry(room);

                    sebOptions.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish;
                    SpatialElementGeometryCalculator finishCalc = new SpatialElementGeometryCalculator(doc, sebOptions);
                    SpatialElementGeometryResults    finish     = finishCalc.CalculateSpatialElementGeometry(room);

                    // get room properties
                    roomNames.Add(room.Name);
                    areaType.Add("Center");
                    levelNames.Add(room.Level.Name);
                    areaValue.Add(center.GetGeometry().SurfaceArea.ToString());

                    TaskDialog.Show("Revit", room.Name + room.Level.Name + center.GetGeometry().SurfaceArea.ToString());


                    roomNames.Add(room.Name);
                    areaType.Add("Finish");
                    levelNames.Add(room.Level.Name);
                    areaValue.Add(finish.GetGeometry().SurfaceArea.ToString());

                    TaskDialog.Show("Revit", room.Name + room.Level.Name + finish.GetGeometry().SurfaceArea.ToString());
                }
            }



            return(Result.Succeeded);
        }
Example #14
0
        private void CreateDucts(int jndex)
        {
            if (sortedlocalsTech.ElementAt(jndex).ElementAt(0).Name.Contains("GT24"))
            {
                Debug.WriteLine("TEST GAINE 24");
            }
            Debug.WriteLine(jndex);
            ElementId levelId = ElementId.InvalidElementId;

            tiltingSpaces.Clear();
            GetBestPath();
            GetTiltingSpace();
            GetBestPosition();
            currentConn = null;

            for (int i = 0; i < sortedlocalsTech.ElementAt(jndex).Count();)
            {
                if (sortedlocalsTech.ElementAt(jndex).Count() == 1)
                {
                    Debug.WriteLine("i: " + i);
                    break;
                }

                Element e     = doc.GetElement(sortedlocalsTech.ElementAt(jndex).ElementAt(i).Id);
                var     space = doc.GetElement(sortedlocalsTech.ElementAt(jndex).ElementAt(i).Id) as Space;

                try
                {
                    if (i >= RevitDataContext.lazyInstance.SpacesInfo.Count())
                    {
                        break;
                    }
                    SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(doc);
                    SpatialElementGeometryResults    results    = calculator.CalculateSpatialElementGeometry(space); // compute the room geometry
                    Solid       roomSolid = results.GetGeometry();
                    List <Face> lf        = new List <Face>();
                    List <XYZ>  Edges     = new List <XYZ>();
                    List <XYZ>  temp      = new List <XYZ>();
                    foreach (Face face in roomSolid.Faces)
                    {
                        foreach (EdgeArray item in face.EdgeLoops)
                        {
                            List <XYZ> lc = JtBoundingBoxXyzExtensionMethods.GetPolygon(item);
                            foreach (var subitem in lc)
                            {
                                temp.Add(subitem);
                            }
                        }
                    }
                    XYZ tempXYZ = null;
                    #region delete identical points, Distinct() linq not that smart
                    foreach (var item in temp)
                    {
                        if (tempXYZ == null)
                        {
                            tempXYZ = item;
                            Edges.Add(item);
                        }
                        else
                        {
                            bool isPresent = false;
                            foreach (var item2 in Edges)
                            {
                                if (item.X == item2.X &&
                                    item.Y == item2.Y &&
                                    item.Z == item2.Z)
                                {
                                    isPresent = true;
                                }
                            }
                            if (isPresent == false)
                            {
                                Edges.Add(item);
                            }
                        }
                    }
                    #endregion

                    Level currentLevel = null;
                    //Get the duct Type
                    FilteredElementCollector collector1 = new FilteredElementCollector(doc);
                    collector1.OfClass(typeof(DuctType));
                    DuctType ductType = null;
                    foreach (Element elem in collector1)
                    {
                        /**
                         * Raccord avec té et coude droit
                         *  Raccord par té avec coude segmenté
                         *  Raccord par piquage et coude segmenté
                         *  Raccord par té et coude droit
                         *  Raccord par piquage et coude droit
                         *  Raccord avec té et coude segmenté
                         *  Raccord par piquage et coude à rayon
                         *  Raccord par piquage et coude segmenté
                         *  Raccord par piquage et coude droit
                         *  Raccord par piquage et coude lisse
                         *  Raccord avec té et coude lisse
                         *  Synoptique de désenfumage
                         *  Raccord par piquage et coude droit chanfreiné
                         *  Raccord avec té et coude à rayon
                         **/
                        if (elem.Name == "Raccord avec té et coude lisse" ||
                            elem.Name == "Connection with tee and smooth elbow")    // gerer english
                        {
                            ductType = elem as DuctType;
                        }
                    }
                    FilteredElementCollector collector2 = new FilteredElementCollector(doc);
                    collector2.OfClass(typeof(MechanicalSystemType)).OfCategory(BuiltInCategory.OST_DuctSystem);
                    MechanicalSystemType mechType = null;
                    foreach (Element e1 in collector2)
                    {
                        /**
                         *  Désenfumage air neuf
                         *  Conduit de Fumée
                         *  Soufflage
                         *  Reprise
                         *  Extraction
                         *  VMC
                         *  Desenfumage Extraction
                         *  Air Neuf
                         *  Rejet
                         *  Desenfumage Air Neuf
                         *  Soufflage Recylage
                         *  Reprise Recyclage
                         *  Soufflage VC
                         *  Soufflage CTA
                         *  ..
                         **/
                        if (e1.Name == "VMC" || e1.Name == "CMV")  // gerer english
                        {
                            mechType = e1 as MechanicalSystemType;
                        }
                    }

                    /**
                     *  Get next space
                     **/


                    bool GetMe = false;
                    int  at    = 0;
                    foreach (var key in RevitDataContext.lazyInstance.SpacesInfo.Keys)
                    {
                        if (key.Number == space.Number)
                        {
                            GetMe = true;
                        }
                        if (GetMe == true)
                        {
                            if (at != 0)
                            {
                                at -= 1;
                            }
                            break;
                        }
                        at += 1;
                    }

                    currentLevel = e.Document.GetElement(e.LevelId) as Level;
                    XYZ startingPoint = null;
                    XYZ endingPoint   = null;

                    /**
                     *  Get the starting point shifted depending on next space location
                     * */

                    Utils.lazyInstance.GetLowestAndHighestPolygon(RevitDataContext.lazyInstance.SpacesInfo.ElementAt(i).Value.Item2, space.Level);
                    List <XYZ> test1 = new List <XYZ>();
                    List <XYZ> test2 = new List <XYZ>();
                    test1 = Utils.lazyInstance.lowestPolyg;
                    test2 = Utils.lazyInstance.highestPolyg;
                    if (test1.Count() != 0 && test2.Count() != 0)
                    {
                        startingPoint = Utils.lazyInstance.GetCenterOfPolygon(test1);
                        endingPoint   = Utils.lazyInstance.GetCenterOfPolygon(test2);
                    }

                    Utils.lazyInstance.GetLowestAndHighestPolygon(RevitDataContext.lazyInstance.SpacesInfo.ElementAt(correspSmallestSpaces[i]).Value.Item2,
                                                                  RevitDataContext.lazyInstance.SpacesInfo.ElementAt(correspSmallestSpaces[i]).Key.Level);
                    List <XYZ> test5 = new List <XYZ>();
                    List <XYZ> test6 = new List <XYZ>();
                    test5 = Utils.lazyInstance.lowestPolyg;
                    test6 = Utils.lazyInstance.highestPolyg;
                    XYZ SendingPoint = Utils.lazyInstance.GetCenterOfPolygon(test6);
                    startingPoint = Utils.lazyInstance.GetCenterOfPolygon(test5);
                    Duct      duct      = null;
                    Connector ductStart = null;
                    Connector ductEnd   = null;
                    Utils.lazyInstance.GetLowestAndHighestPolygon(RevitDataContext.lazyInstance.SpacesInfo.ElementAt(i).Value.Item2,
                                                                  RevitDataContext.lazyInstance.SpacesInfo.ElementAt(i).Key.Level);
                    List <XYZ> test3 = new List <XYZ>();
                    List <XYZ> test4 = new List <XYZ>();
                    test3       = Utils.lazyInstance.lowestPolyg;
                    test4       = Utils.lazyInstance.highestPolyg;
                    endingPoint = new XYZ(SendingPoint.X, SendingPoint.Y, Utils.lazyInstance.GetCenterOfPolygon(test4).Z);

                    if (tiltingSpaces.Contains(correspSmallestSpaces[i]) && i != RevitDataContext.lazyInstance.SpacesInfo.Count() - 1)
                    {
                        XYZ nSt = new XYZ(startingPoint.X - 0.1, startingPoint.Y, startingPoint.Z - 0.8);
                        startingPoint = nSt;
                    }
                    Debug.WriteLine("i: " + i);
                    if (!tiltingSpaces.Contains(i) || i == 0 || i == tiltingSpaces.LastOrDefault())
                    {
                        if (currentConn != null)
                        {
                            XYZ nStart1 = currentConnOrigin;
                            endingPoint = nStart1;
                        }
                        using (Transaction tr = new Transaction(doc))
                        {
                            tr.Start("Create New Duct");
                            {
                                if (currentConn == null)
                                {
                                    duct = Duct.Create(doc, mechType.Id, ductType.Id, RevitDataContext.lazyInstance.SpacesInfo.ElementAt(i).Key.LevelId, startingPoint, endingPoint);
                                }
                                else
                                {
                                    duct = Duct.Create(doc, ductType.Id, RevitDataContext.lazyInstance.SpacesInfo.ElementAt(i).Key.LevelId, currentConn, startingPoint);
                                    Debug.WriteLine("currentConn.Origin: " + currentConn.Origin);
                                    Debug.WriteLine("startingPoint Origin: " + startingPoint);
                                }


                                Parameter parameter = duct.get_Parameter(BuiltInParameter.RBS_CURVE_DIAMETER_PARAM);
                                parameter.Set(diameter);
                                List <Connector> lC = new List <Connector>();
                                foreach (Connector conn in duct.ConnectorManager.Connectors)
                                {
                                    if (conn.ConnectorType == ConnectorType.End)
                                    {
                                        lC.Add(conn);
                                    }
                                }

                                if (lC.ElementAt(0).Origin.Z > lC.ElementAt(1).Origin.Z)
                                {
                                    ductStart = lC.ElementAt(1);
                                    ductEnd   = lC.ElementAt(0);
                                }
                                else
                                {
                                    ductStart = lC.ElementAt(0);
                                    ductEnd   = lC.ElementAt(1);
                                }
                                if (currentConn == null)
                                {
                                    currentConnectors.Add("start" + i, ductStart);
                                    currentConnectors.Add("end" + i, ductEnd);
                                }
                                else
                                {
                                    currentConnectors.Add("start" + i, currentConn);
                                    currentConnectors.Add("end" + i, ductEnd);
                                    doc.Create.NewElbowFitting(ductStart, currentConn);
                                }
                                Debug.WriteLine("Passed, ductStart.Origin : " + ductStart.Origin);
                                tr.Commit();
                                currentConn = ductEnd;
                            }
                        }
                    }

                    // is getting tilted
                    if (tiltingSpaces.Contains(correspSmallestSpaces[i]) &&
                        i != RevitDataContext.lazyInstance.SpacesInfo.Count() - 1 &&
                        correspSmallestSpaces[i] != RevitDataContext.lazyInstance.SpacesInfo.Count() - 1)
                    {
                        Utils.lazyInstance.GetLowestAndHighestPolygon(RevitDataContext.lazyInstance.SpacesInfo.ElementAt(correspSmallestSpaces[i + 1]).Value.Item2,
                                                                      RevitDataContext.lazyInstance.SpacesInfo.ElementAt(correspSmallestSpaces[i + 1]).Key.Level);
                        List <XYZ> test7 = new List <XYZ>();
                        test7 = Utils.lazyInstance.lowestPolyg;
                        var tempZ = startingPoint.Z;
                        endingPoint = new XYZ(Utils.lazyInstance.GetCenterOfPolygon(test7).X, Utils.lazyInstance.GetCenterOfPolygon(test7).Y, tempZ);

                        if (currentConn != null)
                        {
                            Utils.lazyInstance.GetLowestAndHighestPolygon(RevitDataContext.lazyInstance.SpacesInfo.ElementAt(correspSmallestSpaces[correspSmallestSpaces[i] + 1]).Value.Item2,
                                                                          RevitDataContext.lazyInstance.SpacesInfo.ElementAt(correspSmallestSpaces[i + 1]).Key.Level);
                            List <XYZ> test77 = new List <XYZ>();
                            test77 = Utils.lazyInstance.lowestPolyg;
                            var tempZZ = startingPoint.Z;
                            endingPoint = new XYZ(Utils.lazyInstance.GetCenterOfPolygon(test77).X, Utils.lazyInstance.GetCenterOfPolygon(test77).Y, tempZ);
                        }

                        using (Transaction tr2 = new Transaction(doc))
                        {
                            tr2.Start("Create New Tilting Duct");
                            {
                                duct = Duct.Create(doc, mechType.Id, ductType.Id, RevitDataContext.lazyInstance.SpacesInfo.ElementAt(i).Key.LevelId, startingPoint, endingPoint);
                                Debug.WriteLine("startingPoint Origin: " + startingPoint);
                                Debug.WriteLine("endingPoint.Origin: " + endingPoint);

                                Parameter parameter = duct.get_Parameter(BuiltInParameter.RBS_CURVE_DIAMETER_PARAM);
                                parameter.Set(diameter);
                                List <Connector> lC = new List <Connector>();
                                foreach (Connector conn in duct.ConnectorManager.Connectors)
                                {
                                    if (conn.ConnectorType == ConnectorType.End)
                                    {
                                        lC.Add(conn);
                                    }
                                }
                                int tempi = i + 1;
                                if (i != 0)
                                {
                                    tempi = correspSmallestSpaces[correspSmallestSpaces[i] + 1];
                                }
                                // getting the right start and end duct
                                Utils.lazyInstance.GetLowestAndHighestPolygon(RevitDataContext.lazyInstance.SpacesInfo.ElementAt(tempi).Value.Item2,
                                                                              RevitDataContext.lazyInstance.SpacesInfo.ElementAt(tempi).Key.Level);

                                List <XYZ> test8 = new List <XYZ>();
                                test8     = Utils.lazyInstance.lowestPolyg;
                                lC        = Utils.lazyInstance.GetClosestConnector(lC, Utils.lazyInstance.GetCenterOfPolygon(test8));
                                ductStart = lC.ElementAt(0);
                                ductEnd   = lC.ElementAt(1);

                                currentConnOrigin = ductStart.Origin;
                                test11            = ductEnd.Origin;
                                Debug.WriteLine("Start of tilting is :" + ductStart.Origin);
                                Debug.WriteLine("end of tilting is :" + ductEnd.Origin);
                                currentConn = ductStart;
                                doc.Create.NewElbowFitting(ductEnd, currentConnectors.ElementAt(currentConnectors.Count() - 1).Value);
                                currentConnectors.Add("startTilted" + i, ductStart);
                                currentConnectors.Add("endTilted" + i, ductEnd);
                            }
                            tr2.Commit();
                        }
                    }
                    i = correspSmallestSpaces[i] + 1;
                    currentElement = e;
                }
                catch (Exception ex)
                {
                    break;
                }
            }
        }