示例#1
0
        /// <summary>
        /// Convert a wall to an IfcWallStandardCase
        /// </summary>
        /// <param name="wall"></param>
        /// <param name="context"></param>
        /// <param name="doc"></param>
        /// <returns></returns>
        private static IfcWallStandardCase ToIfcWallStandardCase(this Wall wall, IfcRepresentationContext context, Document doc)
        {
            var sweptArea        = wall.CenterLine.Thicken(wall.Thickness()).ToIfcArbitraryClosedProfileDef(doc);
            var extrudeDirection = Vector3.ZAxis.ToIfcDirection();

            // We don't use the Wall's transform for positioning, because
            // our walls have a transform that lays the wall "flat". Just
            // use a identity transform.
            var position = new Transform().ToIfcAxis2Placement3D(doc);
            var repItem  = new IfcExtrudedAreaSolid(sweptArea, position,
                                                    extrudeDirection, new IfcPositiveLengthMeasure(wall.Height));
            var rep = new IfcShapeRepresentation(context, "Body", "SweptSolid", new List <IfcRepresentationItem> {
                repItem
            });
            var productRep = new IfcProductDefinitionShape(new List <IfcRepresentation> {
                rep
            });
            var id             = IfcGuid.ToIfcGuid(Guid.NewGuid());
            var localPlacement = new Transform().ToIfcLocalPlacement(doc);
            var ifcWall        = new IfcWallStandardCase(new IfcGloballyUniqueId(id),
                                                         null, wall.Name, null, null, localPlacement, productRep, null);

            doc.AddEntity(sweptArea);
            doc.AddEntity(extrudeDirection);
            doc.AddEntity(position);
            doc.AddEntity(repItem);
            doc.AddEntity(rep);
            doc.AddEntity(localPlacement);
            doc.AddEntity(productRep);
            doc.AddEntity(ifcWall);

            return(ifcWall);
        }
        private static IfcSlab ToIfc(this Floor floor, Guid id,
                                     IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var slab = new IfcSlab(IfcGuid.ToIfcGuid(id), null, null, null,
                                   null, localPlacement, shape, null, IfcSlabTypeEnum.FLOOR);

            return(slab);
        }
        private static IfcBeam ToIfc(this Beam beam,
                                     IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var ifcBeam = new IfcBeam(IfcGuid.ToIfcGuid(beam.Id), null,
                                      null, null, null, localPlacement, shape, null, IfcBeamTypeEnum.BEAM);

            return(ifcBeam);
        }
        private static IfcColumn ToIfc(this Column column, Guid id,
                                       IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var ifcColumn = new IfcColumn(IfcGuid.ToIfcGuid(id), null,
                                          null, null, null, localPlacement, shape, null, IfcColumnTypeEnum.COLUMN);

            return(ifcColumn);
        }
        private static IfcPlate ToIfc(this Panel panel, Guid id,
                                      IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var plate = new IfcPlate(IfcGuid.ToIfcGuid(id), null,
                                     null, null, null, localPlacement, shape, null, IfcPlateTypeEnum.NOTDEFINED);

            return(plate);
        }
        private static IfcMember ToIfc(this Brace column, Guid id,
                                       IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var member = new IfcMember(IfcGuid.ToIfcGuid(id), null,
                                       null, null, null, localPlacement, shape, null, IfcMemberTypeEnum.NOTDEFINED);

            return(member);
        }
示例#7
0
        private static IfcPlate ToIfc(this Panel panel,
                                      IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var plate = new IfcPlate(IfcGuid.ToIfcGuid(Guid.NewGuid()), null,
                                     null, null, null, localPlacement, shape, null);

            return(plate);
        }
        private static IfcBuildingElementProxy ToIfc(this Mass mass, Guid id,
                                                     IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var proxy = new IfcBuildingElementProxy(IfcGuid.ToIfcGuid(id), null,
                                                    null, null, null, localPlacement, shape, null, IfcBuildingElementProxyTypeEnum.ELEMENT);

            return(proxy);
        }
示例#9
0
        private static IfcMember ToIfc(this Brace column,
                                       IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var member = new IfcMember(IfcGuid.ToIfcGuid(Guid.NewGuid()), null,
                                       null, null, null, localPlacement, shape, null);

            return(member);
        }
示例#10
0
        private static IfcColumn ToIfc(this Column column,
                                       IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var ifcColumn = new IfcColumn(IfcGuid.ToIfcGuid(Guid.NewGuid()), null,
                                          null, null, null, localPlacement, shape, null);

            return(ifcColumn);
        }
示例#11
0
        private static IfcBeam ToIfc(this Beam beam,
                                     IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var ifcBeam = new IfcBeam(IfcGuid.ToIfcGuid(Guid.NewGuid()), null,
                                      null, null, null, localPlacement, shape, null);

            return(ifcBeam);
        }
示例#12
0
        private static IfcWall ToIfc(this Wall wall,
                                     IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var ifcWall = new IfcWall(IfcGuid.ToIfcGuid(Guid.NewGuid()),
                                      null, wall.Name, null, null, localPlacement, shape, null);

            return(ifcWall);
        }
示例#13
0
        // TODO: There is a lot of duplicate code used to create products.
        // Can we make a generic method like ToIfc<TProduct>()? There are
        // exceptions for which this won't work like IfcSpace.

        private static IfcSpace ToIfc(this Space space,
                                      IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var ifcSpace = new IfcSpace(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, null, null,
                                        null, localPlacement, shape, null, IfcElementCompositionEnum.ELEMENT, IfcInternalOrExternalEnum.NOTDEFINED,
                                        new IfcLengthMeasure(space.Transform.Origin.Z));

            return(ifcSpace);
        }
        private static IfcOpeningElement ToIfc(this Opening opening, Guid id, IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var ifcOpening = new IfcOpeningElement(IfcGuid.ToIfcGuid(id),
                                                   null,
                                                   null,
                                                   null,
                                                   null,
                                                   localPlacement,
                                                   shape,
                                                   null,
                                                   IfcOpeningElementTypeEnum.OPENING);

            return(ifcOpening);
        }
        private static IfcBuildingElementProxy ToIfc(this GeometricElement element, Guid id, IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var proxy = new IfcBuildingElementProxy(IfcGuid.ToIfcGuid(id),
                                                    null,
                                                    element.Name,
                                                    $"A {element.GetType().Name} created in Hypar.",
                                                    $"{element.GetType().FullName}",
                                                    localPlacement,
                                                    shape,
                                                    null,
                                                    IfcBuildingElementProxyTypeEnum.ELEMENT);

            return(proxy);
        }
        private static IfcWall ToIfc(this Wall wall, Guid id,
                                     IfcLocalPlacement localPlacement, IfcProductDefinitionShape shape)
        {
            var ifcWall = new IfcWall(IfcGuid.ToIfcGuid(id),
                                      null,
                                      wall.Name,
                                      null,
                                      null,
                                      localPlacement,
                                      shape,
                                      null,
                                      IfcWallTypeEnum.NOTDEFINED);

            return(ifcWall);
        }
        /// <summary>
        /// Creates a map between revit element ids and their IFC GUIDs inside the given document.
        /// </summary>
        /// <param name="doc">A revit document</param>
        /// <param name="elements">A list of element ids</param>
        /// <returns>The map between IFC GUIDs and revit element ids.</returns>
        public static Dictionary <string, ElementId> GetIfcGuidElementIdMap(this Document doc,
                                                                            IEnumerable <ElementId> elements)
        {
            var map = new Dictionary <string, ElementId>();

            foreach (ElementId element in elements)
            {
                var ifcGuid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, element));
                if (!map.ContainsKey(ifcGuid))
                {
                    map.Add(ifcGuid, element);
                }
            }

            return(map);
        }
示例#18
0
        private static IfcBeam ToIfcBeam(this Beam beam, IfcRepresentationContext context, Document doc)
        {
            var sweptArea = beam.ElementType.Profile.Perimeter.ToIfcArbitraryClosedProfileDef(doc);
            var line      = beam.Curve as Line;

            if (line == null)
            {
                throw new Exception("The beam could not be exported to IFC. Only linear beams are currently supported.");
            }

            // We use the Z extrude direction because the direction is
            // relative to the local placement, which is a transform at the
            // beam's end with the Z axis pointing along the direction.

            var extrudeDirection = Vector3.ZAxis.ToIfcDirection();

            var position = new Transform().ToIfcAxis2Placement3D(doc);
            var repItem  = new IfcExtrudedAreaSolid(sweptArea, position,
                                                    extrudeDirection, new IfcPositiveLengthMeasure(beam.Curve.Length()));
            var localPlacement = beam.Curve.TransformAt(0.0).ToIfcLocalPlacement(doc);
            var rep            = new IfcShapeRepresentation(context, "Body", "SweptSolid", new List <IfcRepresentationItem> {
                repItem
            });
            var productRep = new IfcProductDefinitionShape(new List <IfcRepresentation> {
                rep
            });
            var ifcBeam = new IfcBeam(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, null, null, null, localPlacement, productRep, null);

            doc.AddEntity(sweptArea);
            doc.AddEntity(extrudeDirection);
            doc.AddEntity(position);
            doc.AddEntity(repItem);
            doc.AddEntity(rep);
            doc.AddEntity(localPlacement);
            doc.AddEntity(productRep);
            doc.AddEntity(ifcBeam);

            return(ifcBeam);
        }
示例#19
0
        private static IfcOpeningElement ToIfcOpeningElement(this Opening opening, IfcRepresentationContext context, Document doc, IfcObjectPlacement parent)
        {
            // var sweptArea = opening.Profile.Perimeter.ToIfcArbitraryClosedProfileDef(doc);
            // We use the Z extrude direction because the direction is
            // relative to the local placement, which is a transform at the
            // beam's end with the Z axis pointing along the direction.

            // var extrudeDirection = opening.ExtrudeDirection.ToIfcDirection();
            // var position = new Transform().ToIfcAxis2Placement3D(doc);
            // var solid = new IfcExtrudedAreaSolid(sweptArea, position,
            //     extrudeDirection, new IfcPositiveLengthMeasure(opening.ExtrudeDepth));

            var solid          = opening.ToIfcExtrudedAreaSolid(new Transform(), doc);
            var localPlacement = new Transform().ToIfcLocalPlacement(doc, parent);

            var shape = new IfcShapeRepresentation(context, "Body", "SweptSolid", new List <IfcRepresentationItem> {
                solid
            });
            var productRep = new IfcProductDefinitionShape(new List <IfcRepresentation> {
                shape
            });

            var ifcOpening = new IfcOpeningElement(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, null, null, null, localPlacement, productRep, null);

            // doc.AddEntity(sweptArea);
            // doc.AddEntity(extrudeDirection);
            // doc.AddEntity(position);
            // doc.AddEntity(repItem);

            doc.AddEntity(solid);
            doc.AddEntity(localPlacement);
            doc.AddEntity(shape);
            doc.AddEntity(productRep);

            return(ifcOpening);
        }
示例#20
0
        /// <summary>
        /// Generate Viewpoint
        /// </summary>
        /// <param name="elemCheck"></param>
        /// <returns></returns>
        public VisualizationInfo generateViewpoint(int elemCheck)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                VisualizationInfo v = new VisualizationInfo();

                XYZ    centerIMP = new XYZ();
                string type      = "";
                double zoomValue = 1;

                if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
                {
                    XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                    XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
                    v.SheetCamera             = new SheetCamera();
                    v.SheetCamera.SheetID     = uidoc.ActiveView.Id.IntegerValue;
                    v.SheetCamera.TopLeft     = new IssueTracker.Classes.BCF2.Point(TL.X, TL.Y, TL.Z);
                    v.SheetCamera.BottomRight = new IssueTracker.Classes.BCF2.Point(BR.X, BR.Y, BR.Z);
                }
                else
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (!view3D.IsPerspective) //IS ORTHO
                    {
                        XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                        XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                        double xO = (TL.X + BR.X) / 2;
                        double yO = (TL.Y + BR.Y) / 2;
                        double zO = (TL.Z + BR.Z) / 2;
                        //converto to METERS
                        centerIMP = new XYZ(xO, yO, zO);
                        double dist       = TL.DistanceTo(BR) / 2; //custom sectet value to get solibri zoom value from Corners of Revit UiView
                        XYZ    diagVector = TL.Subtract(BR);
                        // **** CUSTOM VALUE FOR TEKLA **** //
                        //zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS);
                        // **** CUSTOM VALUE FOR TEKLA **** //
                        double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                        zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                        type      = "OrthogonalCamera";
                    }
                    else // it is a perspective view
                    {
                        centerIMP = uidoc.ActiveView.Origin;
                        type      = "PerspectiveCamera";
                        zoomValue = 45;
                    }
                    ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
                    //ViewOrientation3D t = new ViewOrientation3D(centerIMP, uidoc.ActiveView.UpDirection, uidoc.ActiveView.ViewDirection);
                    XYZ c  = t.EyePosition;
                    XYZ vi = t.ForwardDirection;
                    XYZ up = t.UpDirection;

                    if (type == "OrthogonalCamera")
                    {
                        v.OrthogonalCamera = new OrthogonalCamera();
                        v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.ViewToWorldScale  = zoomValue;
                    }
                    else
                    {
                        v.PerspectiveCamera = new PerspectiveCamera();
                        v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.FieldOfView       = zoomValue;
                    }


                    // handle section box if enabled
                    if (view3D.IsSectionBoxActive)
                    {
                        BoundingBoxXYZ sectionBox = view3D.GetSectionBox();

                        // Note that the section box can be rotated and transformed.
                        // So the min/max corners coordinates relative to the model must be computed via the transform.
                        Transform trf = sectionBox.Transform;

                        XYZ max = sectionBox.Max; //Maximum coordinates (upper-right-front corner of the box before transform is applied).
                        XYZ min = sectionBox.Min; //Minimum coordinates (lower-left-rear corner of the box before transform is applied).

                        // Transform the min and max to model coordinates
                        XYZ maxInModelCoords = trf.OfPoint(max);
                        XYZ minInModelCoords = trf.OfPoint(min);

                        // Convert to project unit
                        DisplayUnitType lengthUnitType = doc.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;
                        maxInModelCoords = new XYZ(UnitUtils.ConvertFromInternalUnits(maxInModelCoords.X, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(maxInModelCoords.Y, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(maxInModelCoords.Z, lengthUnitType));
                        minInModelCoords = new XYZ(UnitUtils.ConvertFromInternalUnits(minInModelCoords.X, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(minInModelCoords.Y, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(minInModelCoords.Z, lengthUnitType));

                        // Convert to shared coordinates
                        maxInModelCoords = ARUP.IssueTracker.Revit.Classes.Utils.ConvertToFromSharedCoordinate(doc, maxInModelCoords, false);
                        minInModelCoords = ARUP.IssueTracker.Revit.Classes.Utils.ConvertToFromSharedCoordinate(doc, minInModelCoords, false);

                        // Add to BCF clipping planes
                        v.ClippingPlanes = BcfAdapter.GetClippingPlanesFromBoundingBox
                                           (
                            maxInModelCoords.X, maxInModelCoords.Y, maxInModelCoords.Z,
                            minInModelCoords.X, minInModelCoords.Y, minInModelCoords.Z
                                           );
                    }
                }


                //COMPONENTS PART
                FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                System.Collections.Generic.ICollection <ElementId> collection = null;

                if (elemCheck == 0)
                {
                    collection = collector.ToElementIds();
                }
                else if (elemCheck == 1)
                {
                    collection = uidoc.Selection.GetElementIds();
                }

                if (null != collection && collection.Any())
                {
                    v.Components = new List <IssueTracker.Classes.BCF2.Component>();
                    foreach (var eId in collection)
                    {
                        Guid   guid    = ExportUtils.GetExportId(doc, eId);
                        string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
                        v.Components.Add(new ARUP.IssueTracker.Classes.BCF2.Component(doc.Application.VersionName, eId.ToString(), ifcguid));
                    }
                }

                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
            return(null);
        }
示例#21
0
        /// <summary>
        /// Write the model to IFC.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="path">The path to the generated IFC STEP file.</param>
        public static void ToIFC(this Model model, string path)
        {
            var ifc = new Document("Elements", "Elements", Environment.UserName,
                                   null, null, null, "Elements", null, null,
                                   null, null, null, null, null, null
                                   );

            var proj = ifc.AllInstancesOfType <IfcProject>().FirstOrDefault();

            // Add a site
            var site          = new IfcSite(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var projAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, proj, new List <IfcObjectDefinition> {
                site
            });

            // Add building and building storey
            var building  = new IfcBuilding(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var storey    = new IfcBuildingStorey(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var aggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, building, new List <IfcObjectDefinition> {
                storey
            });

            // Aggregate the building into the site
            var siteAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, site, new List <IfcObjectDefinition> {
                building
            });

            ifc.AddEntity(site);
            ifc.AddEntity(projAggregate);
            ifc.AddEntity(building);
            ifc.AddEntity(storey);
            ifc.AddEntity(aggregate);
            ifc.AddEntity(siteAggregate);

            var products = new List <IfcProduct>();
            var context  = ifc.AllInstancesOfType <IfcGeometricRepresentationContext>().FirstOrDefault();

            foreach (var e in model.Elements.Values)
            {
                try
                {
                    products.AddRange(e.ToIfcProducts(context, ifc));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"There was an error writing an element of type {e.GetType()} to IFC: " + ex.Message);
                    Console.WriteLine(ex.StackTrace);
                    continue;
                }
            }

            var spatialRel = new IfcRelContainedInSpatialStructure(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, products, storey);

            ifc.AddEntity(spatialRel);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.WriteAllText(path, ifc.ToSTEP(path));
        }
示例#22
0
        //<summary>
        //Generate a VisualizationInfo of the current view
        //</summary>
        //<returns></returns>
        private VisualizationInfo GenerateViewpoint()
        {
            try
            {
                var uidoc = uiapp.ActiveUIDocument;
                var doc   = uidoc.Document;

                var v = new VisualizationInfo();

                //Corners of the active UI view
                var topLeft     = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                var bottomRight = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                //It's a 2D view
                //not supported by BCF, but I store it under a custom
                //fields using 2D coordinates and sheet id
                if (uidoc.ActiveView.ViewType != ViewType.ThreeD)
                {
                    v.SheetCamera = new SheetCamera
                    {
                        SheetID = uidoc.ActiveView.Id.IntegerValue,
                        TopLeft = new Point {
                            X = topLeft.X, Y = topLeft.Y, Z = topLeft.Z
                        },
                        BottomRight = new Point {
                            X = bottomRight.X, Y = bottomRight.Y, Z = bottomRight.Z
                        }
                    };
                }
                //It's a 3d view
                else
                {
                    var    viewCenter = new XYZ();
                    var    view3D     = (View3D)uidoc.ActiveView;
                    double zoomValue  = 1;
                    // it is a orthogonal view
                    if (!view3D.IsPerspective)
                    {
                        double x = (topLeft.X + bottomRight.X) / 2;
                        double y = (topLeft.Y + bottomRight.Y) / 2;
                        double z = (topLeft.Z + bottomRight.Z) / 2;
                        //center of the UI view
                        viewCenter = new XYZ(x, y, z);

                        //vector going from BR to TL
                        XYZ diagVector = topLeft.Subtract(bottomRight);
                        //lenght of the vector
                        double dist = topLeft.DistanceTo(bottomRight) / 2;

                        //ViewToWorldScale value
                        zoomValue = dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)).ToMeters();

                        // **** CUSTOM VALUE FOR TEKLA **** //
                        // calculated sperimentally, not sure why but it works
                        //if (UserSettings.Get("optTekla") == "1")
                        //  zoomValue = zoomValue * 2.5;
                        // **** CUSTOM VALUE FOR TEKLA **** //

                        ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection,
                                                                          uidoc.ActiveView.UpDirection, false);

                        XYZ c  = t.EyePosition;
                        XYZ vi = t.ForwardDirection;
                        XYZ up = t.UpDirection;


                        v.OrthogonalCamera = new OrthogonalCamera
                        {
                            CameraViewPoint =
                            {
                                X = c.X.ToMeters(),
                                Y = c.Y.ToMeters(),
                                Z = c.Z.ToMeters()
                            },
                            CameraUpVector =
                            {
                                X = up.X.ToMeters(),
                                Y = up.Y.ToMeters(),
                                Z = up.Z.ToMeters()
                            },
                            CameraDirection =
                            {
                                X = vi.X.ToMeters() * -1,
                                Y = vi.Y.ToMeters() * -1,
                                Z = vi.Z.ToMeters() * -1
                            },
                            ViewToWorldScale = zoomValue
                        };
                    }
                    // it is a perspective view
                    else
                    {
                        viewCenter = uidoc.ActiveView.Origin;
                        //revit default value
                        zoomValue = 45;

                        ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection,
                                                                          uidoc.ActiveView.UpDirection, false);

                        XYZ c  = t.EyePosition;
                        XYZ vi = t.ForwardDirection;
                        XYZ up = t.UpDirection;

                        v.PerspectiveCamera = new PerspectiveCamera
                        {
                            CameraViewPoint =
                            {
                                X = c.X.ToMeters(),
                                Y = c.Y.ToMeters(),
                                Z = c.Z.ToMeters()
                            },
                            CameraUpVector =
                            {
                                X = up.X.ToMeters(),
                                Y = up.Y.ToMeters(),
                                Z = up.Z.ToMeters()
                            },
                            CameraDirection =
                            {
                                X = vi.X.ToMeters() * -1,
                                Y = vi.Y.ToMeters() * -1,
                                Z = vi.Z.ToMeters() * -1
                            },
                            FieldOfView = zoomValue
                        };
                    }
                }
                //COMPONENTS PART
                string versionName = doc.Application.VersionName;
                v.Components = new List <Component>();

                var visibleElems = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                   .WhereElementIsNotElementType()
                                   .WhereElementIsViewIndependent()
                                   .ToElementIds();
                var hiddenElems = new FilteredElementCollector(doc)
                                  .WhereElementIsNotElementType()
                                  .WhereElementIsViewIndependent()
                                  .Where(x => x.IsHidden(doc.ActiveView) ||
                                         !doc.ActiveView.IsElementVisibleInTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate, x.Id)).ToList();//would need to check how much this is affecting performance

                var selectedElems = uidoc.Selection.GetElementIds();


                //include only hidden elements and selected in the BCF
                if (visibleElems.Count() > hiddenElems.Count())
                {
                    foreach (var elem in hiddenElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem.Id)),
                            Visible           = false,
                            Selected          = false,
                            AuthoringToolId   = elem.Id.IntegerValue.ToString()
                        });
                    }
                    foreach (var elem in selectedElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem)),
                            Visible           = true,
                            Selected          = true,
                            AuthoringToolId   = elem.IntegerValue.ToString()
                        });
                    }
                }
                //include only visigle elements
                //all the others are hidden
                else
                {
                    foreach (var elem in visibleElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem)),
                            Visible           = true,
                            Selected          = selectedElems.Contains(elem),
                            AuthoringToolId   = elem.IntegerValue.ToString()
                        });
                    }
                }
                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error generating viewpoint", "exception: " + ex1);
            }
            return(null);
        }
示例#23
0
        /// <summary>
        /// Write the model to IFC.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="path">The path to the generated IFC STEP file.</param>
        public static void ToIFC(this Model model, string path)
        {
            var ifc = new Document("Elements", "Elements", Environment.UserName,
                                   null, null, null, "Elements", null, null,
                                   null, null, null, null, null, null
                                   );

            var proj = ifc.AllInstancesOfType <IfcProject>().FirstOrDefault();

            // Add a site
            var site = new IfcSite(IfcGuid.ToIfcGuid(Guid.NewGuid()),
                                   null,
                                   "Hypar Site",
                                   "The default site generated by Hypar",
                                   null,
                                   null,
                                   null,
                                   null,
                                   IfcElementCompositionEnum.ELEMENT,
                                   new IfcCompoundPlaneAngleMeasure(new List <int> {
                0, 0, 0
            }),
                                   new IfcCompoundPlaneAngleMeasure(new List <int> {
                0, 0, 0
            }),
                                   0,
                                   null,
                                   null);
            var projAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), proj, new List <IfcObjectDefinition> {
                site
            });

            // Add building and building storey
            var building = new IfcBuilding(IfcGuid.ToIfcGuid(Guid.NewGuid()),
                                           null,
                                           "Default Building",
                                           "The default building generated by Hypar.",
                                           null,
                                           null,
                                           null,
                                           null,
                                           IfcElementCompositionEnum.ELEMENT,
                                           0,
                                           0,
                                           null);
            var storey = new IfcBuildingStorey(IfcGuid.ToIfcGuid(Guid.NewGuid()),
                                               null,
                                               "Default Storey",
                                               "The default storey generated by Hypar",
                                               null,
                                               null,
                                               null,
                                               null,
                                               IfcElementCompositionEnum.ELEMENT,
                                               0);
            var aggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), building, new List <IfcObjectDefinition> {
                storey
            });

            // Aggregate the building into the site
            var siteAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), site, new List <IfcObjectDefinition> {
                building
            });

            ifc.AddEntity(site);
            ifc.AddEntity(projAggregate);
            ifc.AddEntity(building);
            ifc.AddEntity(storey);
            ifc.AddEntity(aggregate);
            ifc.AddEntity(siteAggregate);

            var products = new List <IfcProduct>();
            var context  = ifc.AllInstancesOfType <IfcGeometricRepresentationContext>().FirstOrDefault();

            // IfcRelAssociatesMaterial
            // IfcMaterialDefinitionRepresentation
            // https://forums.buildingsmart.org/t/where-and-how-will-my-colors-be-saved-in-ifc/1806/12
            var styleAssignments = new Dictionary <Guid, List <IfcStyleAssignmentSelect> >();

            var white = Colors.White.ToIfcColourRgb();

            ifc.AddEntity(white);

            // TODO: Fix color support in all applications.
            // https://forums.buildingsmart.org/t/why-is-it-so-difficult-to-get-colors-to-show-up/2312/12
            foreach (var m in model.AllElementsOfType <Material>())
            {
                var material = new IfcMaterial(m.Name, null, "Hypar");
                ifc.AddEntity(material);

                var color = m.Color.ToIfcColourRgb();
                ifc.AddEntity(color);

                var transparency = new IfcNormalisedRatioMeasure(1.0 - m.Color.Alpha);

                var shading = new IfcSurfaceStyleShading(color, transparency);
                ifc.AddEntity(shading);

                var styles = new List <IfcSurfaceStyleElementSelect> {
                    new IfcSurfaceStyleElementSelect(shading),
                };
                var surfaceStyle = new IfcSurfaceStyle(material.Name, IfcSurfaceSide.BOTH, styles);
                ifc.AddEntity(surfaceStyle);

                var styleAssign = new IfcStyleAssignmentSelect(surfaceStyle);
                var assignments = new List <IfcStyleAssignmentSelect>()
                {
                    styleAssign
                };
                styleAssignments.Add(m.Id, assignments);
            }


            foreach (var e in model.Elements.Values.Where(e =>
            {
                var t = e.GetType();
                return(((e is GeometricElement &&
                         !((GeometricElement)e).IsElementDefinition) || e is ElementInstance) &&
                       t != typeof(ModelCurve) &&
                       t != typeof(ModelPoints) &&
                       t != typeof(AnalysisMesh));
            }))
            {
                try
                {
                    products.AddRange(e.ToIfcProducts(context, ifc, styleAssignments));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"There was an error writing an element of type {e.GetType()} to IFC: " + ex.Message);
                    Console.WriteLine(ex.StackTrace);
                    continue;
                }
            }

            var spatialRel = new IfcRelContainedInSpatialStructure(IfcGuid.ToIfcGuid(Guid.NewGuid()), products, storey);

            ifc.AddEntity(spatialRel);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.WriteAllText(path, ifc.ToSTEP(path));
        }
        /// <summary>
        /// Generate Viewpoint
        /// </summary>
        /// <param name="elemCheck"></param>
        /// <returns></returns>
        private VisualizationInfo generateViewpoint(int elemCheck)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                VisualizationInfo v = new VisualizationInfo();

                XYZ    centerIMP = new XYZ();
                string type      = "";
                double zoomValue = 1;

                if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
                {
                    XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                    XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
                    v.SheetCamera             = new SheetCamera();
                    v.SheetCamera.SheetID     = uidoc.ActiveView.Id.IntegerValue;
                    v.SheetCamera.TopLeft     = new IssueTracker.Data.Point(TL.X, TL.Y, TL.Z);
                    v.SheetCamera.BottomRight = new IssueTracker.Data.Point(BR.X, BR.Y, BR.Z);
                }
                else
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (!view3D.IsPerspective) //IS ORTHO
                    {
                        XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                        XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                        double xO = (TL.X + BR.X) / 2;
                        double yO = (TL.Y + BR.Y) / 2;
                        double zO = (TL.Z + BR.Z) / 2;
                        //converto to METERS
                        centerIMP = new XYZ(xO, yO, zO);
                        double dist            = TL.DistanceTo(BR) / 2; //custom value to get solibri zoom value from Corners of Revit UiView
                        XYZ    diagVector      = TL.Subtract(BR);
                        double customZoomValue = (ProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                        zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                        type      = "OrthogonalCamera";
                    }
                    else // it is a perspective view
                    {
                        centerIMP = uidoc.ActiveView.Origin;
                        type      = "PerspectiveCamera";
                        zoomValue = 45;
                    }
                    ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
                    XYZ c  = t.EyePosition;
                    XYZ vi = t.ForwardDirection;
                    XYZ up = t.UpDirection;

                    if (type == "OrthogonalCamera")
                    {
                        v.OrthogonalCamera = new OrthogonalCamera();
                        v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.ViewToWorldScale  = zoomValue;
                    }
                    else
                    {
                        v.PerspectiveCamera = new PerspectiveCamera();
                        v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.FieldOfView       = zoomValue;
                    }
                }


                //COMPONENTS PART
                FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                System.Collections.Generic.ICollection <ElementId> collection = null;

                if (elemCheck == 0)
                {
                    collection = collector.ToElementIds();
                }
                else if (elemCheck == 1)
                {
                    collection = uidoc.Selection.GetElementIds();
                }

                if (null != collection && collection.Any())
                {
                    v.Components = new IssueTracker.Data.Component[collection.Count];
                    for (var i = 0; i < collection.Count; i++)
                    {
                        Guid   guid    = ExportUtils.GetExportId(doc, collection.ElementAt(i));
                        string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
                        ;
                        v.Components[i] = new Case.IssueTracker.Data.Component(doc.Application.VersionName, collection.ElementAt(i).ToString(), ifcguid);
                    }
                }

                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
            return(null);
        }
示例#25
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument uidoc      = app.ActiveUIDocument;
                Document   doc        = uidoc.Document;
                var        uniqueView = UserSettings.GetBool("alwaysNewView");

                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = v.OrthogonalCamera.ViewToWorldScale.ToFeet();
                    var cameraDirection = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraDirection);
                    var cameraUpVector  = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraUpVector);
                    var cameraViewPoint = RevitUtils.GetRevitXYZ(v.OrthogonalCamera.CameraViewPoint);
                    var orient3D        = RevitUtils.ConvertBasePoint(doc, cameraViewPoint, cameraDirection, cameraUpVector, true);

                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        var activeView3D = doc.ActiveView as View3D;
                        if (!activeView3D.IsPerspective)
                        {
                            orthoView = activeView3D;
                        }
                    }
                    if (orthoView == null)
                    {
                        //try to use an existing 3D view
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        if (viewcollector3D.Any(o => o.Name == "{3D}" || o.Name == "BCFortho"))
                        {
                            orthoView = viewcollector3D.First(o => o.Name == "{3D}" || o.Name == "BCFortho");
                        }
                    }
                    using (var trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new 3d ortho view

                            if (orthoView == null || uniqueView)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = (uniqueView) ? "BCFortho" + DateTime.Now.ToString("yyyyMMddTHHmmss") : "BCFortho";
                            }
                            else
                            {
                                //reusing an existing view, I net to reset the visibility
                                //placed this here because if set afterwards it doesn't work
                                orthoView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            }
                            orthoView.SetOrientation(orient3D);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = zoom / 2.5;
                    // **** CUSTOM VALUE FOR TEKLA **** //

                    double x = zoom;
                    //if(MySettings.Get("optTekla")=="1")
                    //    x = zoom / 2.5;

                    //set UI view position and zoom
                    XYZ m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                //perspective
                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    //not used since the fov cannot be changed in Revit
                    var zoom = v.PerspectiveCamera.FieldOfView;
                    //FOV - not used
                    //double z1 = 18 / Math.Tan(zoom / 2 * Math.PI / 180);
                    //double z = 18 / Math.Tan(25 / 2 * Math.PI / 180);
                    //double factor = z1 - z;

                    var cameraDirection = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraDirection);
                    var cameraUpVector  = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraUpVector);
                    var cameraViewPoint = RevitUtils.GetRevitXYZ(v.PerspectiveCamera.CameraViewPoint);
                    var orient3D        = RevitUtils.ConvertBasePoint(doc, cameraViewPoint, cameraDirection, cameraUpVector, true);



                    View3D perspView = null;
                    //try to use an existing 3D view
                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    if (viewcollector3D.Any(o => o.Name == "BCFpersp"))
                    {
                        perspView = viewcollector3D.First(o => o.Name == "BCFpersp");
                    }

                    using (var trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView || uniqueView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = (uniqueView) ? "BCFpersp" + DateTime.Now.ToString("yyyyMMddTHHmmss") : "BCFpersp";
                            }
                            else
                            {
                                //reusing an existing view, I net to reset the visibility
                                //placed this here because if set afterwards it doesn't work
                                perspView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            }

                            perspView.SetOrientation(orient3D);

                            // turn off the far clip plane
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                //sheet
                else if (v.SheetCamera != null)
                {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("View " + v.SheetCamera.SheetName + " with Id=" + v.SheetCamera.SheetID + " not found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.RefreshActiveView();

                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y, v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y, v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                //no view included
                else
                {
                    return;
                }

                if (v.Components == null)
                {
                    return;
                }


                var elementsToSelect = new List <ElementId>();
                var elementsToHide   = new List <ElementId>();
                var elementsToShow   = new List <ElementId>();

                var visibleElems = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                   .WhereElementIsNotElementType()
                                   .WhereElementIsViewIndependent()
                                   .ToElementIds()
                                   .Where(e => doc.GetElement(e).CanBeHidden(doc.ActiveView)); //might affect performance, but it's necessary


                bool canSetVisibility = (v.Components.Visibility != null &&
                                         v.Components.Visibility.DefaultVisibilitySpecified &&
                                         v.Components.Visibility.Exceptions.Any())
                ;
                bool canSetSelection = (v.Components.Selection != null && v.Components.Selection.Any());



                //loop elements
                foreach (var e in visibleElems)
                {
                    var guid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, e));

                    if (canSetVisibility)
                    {
                        if (v.Components.Visibility.DefaultVisibility)
                        {
                            if (v.Components.Visibility.Exceptions.Any(x => x.IfcGuid == guid))
                            {
                                elementsToHide.Add(e);
                            }
                        }
                        else
                        {
                            if (v.Components.Visibility.Exceptions.Any(x => x.IfcGuid == guid))
                            {
                                elementsToShow.Add(e);
                            }
                        }
                    }

                    if (canSetSelection)
                    {
                        if (v.Components.Selection.Any(x => x.IfcGuid == guid))
                        {
                            elementsToSelect.Add(e);
                        }
                    }
                }



                using (var trans = new Transaction(uidoc.Document))
                {
                    if (trans.Start("Apply BCF visibility and selection") == TransactionStatus.Started)
                    {
                        if (elementsToHide.Any())
                        {
                            doc.ActiveView.HideElementsTemporary(elementsToHide);
                        }
                        //there are no items to hide, therefore hide everything and just show the visible ones
                        else if (elementsToShow.Any())
                        {
                            doc.ActiveView.IsolateElementsTemporary(elementsToShow);
                        }

                        if (elementsToSelect.Any())
                        {
                            uidoc.Selection.SetElementIds(elementsToSelect);
                        }
                    }
                    trans.Commit();
                }


                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
示例#26
0
        private void Open3DView(VisualizationInfo v)
        {
            try
            {
                //    {
                //
                Tuple <Point3D, Vector3D, Vector3D, ViewpointProjection, double> tuple = GetViewCoordinates(v);

                if (tuple == null)
                {
                    MessageBox.Show("Viewpoint not formatted correctly.", "Viewpoint Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                Document oDoc = Autodesk.Navisworks.Api.Application.ActiveDocument;

                // get current viewpoint
                // Viewpoint oCurVP = oDoc.vi.CurrentViewpoint.ToViewpoint;
                // get copy viewpoint
                Viewpoint oCopyVP = new Viewpoint();



                oCopyVP.AlignDirection(tuple.Item3);
                oCopyVP.AlignUp(tuple.Item2);
                oCopyVP.Projection = tuple.Item4;



                // **** CUSTOM VALUE FOR TEKLA **** //
                // otherwise = 1
                // **** CUSTOM VALUE FOR TEKLA **** //
                const double TEKLA = 1.25;

                double x = tuple.Item5 / TEKLA;


                if (oCopyVP.Projection == ViewpointProjection.Orthographic)
                {
                    oCopyVP.Position      = tuple.Item1;
                    oCopyVP.FocalDistance = 1;
                    //top center point of view
                    Point3D xyzTL = oCopyVP.Position.Add(tuple.Item2.Multiply(x));
                    oCopyVP.SetExtentsAtFocalDistance(1, xyzTL.DistanceTo(oCopyVP.Position));
                }
                else
                {
                    //double angle = tuple.Item5 * Math.PI / 180;
                    // MessageBox.Show(tuple.Item5.ToString() + "  " +(Math.Tan(angle / 2)*2).ToString());
                    oCopyVP.FocalDistance = tuple.Item5;
                    //oCopyVP.SetExtentsAtFocalDistance(Math.Tan(angle / 2) * 2, Math.Tan(angle / 2) * 2 / oCopyVP.AspectRatio);
                    oCopyVP.Position = tuple.Item1;
                }

                oDoc.CurrentViewpoint.CopyFrom(oCopyVP);

                if (v.Components != null && v.Components.Any())
                {
                    // ModelItemCollection selected = new ModelItemCollection();
                    List <ModelItem> attachedElems = new List <ModelItem>();

                    List <ModelItem> elems = oDoc.Models.First.RootItem.DescendantsAndSelf.ToList <ModelItem>();


                    foreach (var item in elems.Where(o => o.InstanceGuid != Guid.Empty))
                    {
                        string ifcguid = IfcGuid.ToIfcGuid(item.InstanceGuid).ToString();
                        if (v.Components.Any(o => o.IfcGuid == ifcguid))
                        {
                            attachedElems.Add(item);
                        }
                    }
                    if (attachedElems.Any())//avoid to hide everything if no elements matches
                    {
                        if (MySettings.Get("selattachedelems") == "0")
                        {
                            List <ModelItem> elemsVisible = new List <ModelItem>();
                            foreach (var item in attachedElems)
                            {
                                elemsVisible.AddRange(item.AncestorsAndSelf);
                            }
                            foreach (var item in elemsVisible)
                            {
                                elems.Remove(item);
                            }

                            oDoc.Models.ResetAllHidden();
                            oDoc.Models.SetHidden(elems, true);
                        }

                        else
                        {
                            oDoc.CurrentSelection.Clear();
                            oDoc.CurrentSelection.AddRange(attachedElems);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            //setVisibility(v);
        }
示例#27
0
        /// <summary>
        /// Write the model to IFC.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="path">The path to the generated IFC STEP file.</param>
        public static void ToIFC(this Model model, string path)
        {
            var ifc = new Document("elements", "elements", Environment.UserName,
                                   null, null, null, "elements", null, null,
                                   null, null, null, null, null, null
                                   );

            var proj = ifc.AllInstancesOfType <IfcProject>().FirstOrDefault();

            // Add a site
            var site          = new IfcSite(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var projAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, proj, new List <IfcObjectDefinition> {
                site
            });

            // Add building and building storey
            var building  = new IfcBuilding(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var storey    = new IfcBuildingStorey(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var aggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, building, new List <IfcObjectDefinition> {
                storey
            });

            // Aggregate the building into the site
            var siteAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, site, new List <IfcObjectDefinition> {
                building
            });

            ifc.AddEntity(site);
            ifc.AddEntity(projAggregate);
            ifc.AddEntity(building);
            ifc.AddEntity(storey);
            ifc.AddEntity(aggregate);
            ifc.AddEntity(siteAggregate);

            // Materials
            // foreach(var m in model.Materials.Values)
            // {
            //     var ifcMaterial = new IfcMaterial(m.Name);
            //     ifc.AddEntity(ifcMaterial);
            // }

            var products = new List <IfcProduct>();
            var context  = ifc.AllInstancesOfType <IfcGeometricRepresentationContext>().FirstOrDefault();

            foreach (var e in model.Elements.Values)
            {
                try
                {
                    if (e is Wall)
                    {
                        var w       = (Wall)e;
                        var ifcWall = w.ToIfcWallStandardCase(context, ifc);
                        products.Add(ifcWall);
                    }

                    if (e is Beam)
                    {
                        var b       = (Beam)e;
                        var ifcBeam = b.ToIfcBeam(context, ifc);
                        products.Add(ifcBeam);
                    }
                }
                catch
                {
                    continue;
                }
            }

            var spatialRel = new IfcRelContainedInSpatialStructure(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, products, storey);

            ifc.AddEntity(spatialRel);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.WriteAllText(path, ifc.ToSTEP(path));
        }
示例#28
0
        public static void Open(Document doc, VisualizationInfo v)
        {
            try
            {
                NavisUtils.GetGunits(doc);
                Viewpoint viewpoint = new Viewpoint();

                //orthogonal
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null ||
                        v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var zoom            = v.OrthogonalCamera.ViewToWorldScale.ToInternal();
                    var cameraDirection = NavisUtils.GetNavisVector(v.OrthogonalCamera.CameraDirection);
                    var cameraUpVector  = NavisUtils.GetNavisVector(v.OrthogonalCamera.CameraUpVector);
                    var cameraViewPoint = NavisUtils.GetNavisXYZ(v.OrthogonalCamera.CameraViewPoint);

                    viewpoint.Position = cameraViewPoint;
                    viewpoint.AlignUp(cameraUpVector);
                    viewpoint.AlignDirection(cameraDirection);
                    viewpoint.Projection    = ViewpointProjection.Orthographic;
                    viewpoint.FocalDistance = 1;

                    //TODO
                    //for better zooming from revit should use > zoom * 1.25
                    //for better zooming from tekla should use > zoom / 1.25
                    //still not sure why
                    Point3D xyzTL = cameraViewPoint.Add(cameraUpVector.Multiply(zoom));
                    var     dist  = xyzTL.DistanceTo(cameraViewPoint);
                    viewpoint.SetExtentsAtFocalDistance(1, dist);
                }
                //perspective
                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null ||
                        v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var zoom            = v.PerspectiveCamera.FieldOfView;
                    var cameraDirection = NavisUtils.GetNavisVector(v.PerspectiveCamera.CameraDirection);
                    var cameraUpVector  = NavisUtils.GetNavisVector(v.PerspectiveCamera.CameraUpVector);
                    var cameraViewPoint = NavisUtils.GetNavisXYZ(v.PerspectiveCamera.CameraViewPoint);

                    viewpoint.Position = cameraViewPoint;
                    viewpoint.AlignUp(cameraUpVector);
                    viewpoint.AlignDirection(cameraDirection);
                    viewpoint.Projection    = ViewpointProjection.Perspective;
                    viewpoint.FocalDistance = zoom;
                }

                doc.CurrentViewpoint.CopyFrom(viewpoint);


                //show/hide elements
                //todo: needs improvement
                //todo: add settings
                if (v.Components != null)
                {
                    List <ModelItem> attachedElems = new List <ModelItem>();
                    List <ModelItem> elems         = doc.Models.First.RootItem.DescendantsAndSelf.ToList <ModelItem>();


                    foreach (var item in elems.Where(o => o.InstanceGuid != Guid.Empty))
                    {
                        string ifcguid = IfcGuid.ToIfcGuid(item.InstanceGuid).ToString();
                        //if (v.Components.Any(o => o.IfcGuid == ifcguid))
                        attachedElems.Add(item);
                    }
                    if (attachedElems.Any()) //avoid to hide everything if no elements matches
                    {
                        if (UserSettings.Get("selattachedelems") == "0")
                        {
                            List <ModelItem> elemsVisible = new List <ModelItem>();
                            foreach (var item in attachedElems)
                            {
                                elemsVisible.AddRange(item.AncestorsAndSelf);
                            }
                            foreach (var item in elemsVisible)
                            {
                                elems.Remove(item);
                            }

                            doc.Models.ResetAllHidden();
                            doc.Models.SetHidden(elems, true);
                        }
                        else
                        {
                            doc.CurrentSelection.Clear();
                            doc.CurrentSelection.AddRange(attachedElems);
                        }
                    }
                }
            }

            catch (System.Exception ex1)
            {
                MessageBox.Show("exception: " + ex1, "Error opening view");
            }
        }
示例#29
0
        public Model(IDictionary <Guid, BaseIfc> storage, string name, string description, IfcAddress address, IfcPerson user, IfcOrganization owner)
        {
            this.storage = storage;

            this.storage.Add(address.Id, address);
            this.storage.Add(user.Id, user);
            this.storage.Add(owner.Id, owner);

            // Create an organization for app creation.
            var appOrg = new IfcOrganization(APPNAME);

            this.storage.Add(appOrg.Id, appOrg);

            // Create an authoring application.
            var v   = owner.GetType().Assembly.GetName().Version.ToString();
            var app = new IfcApplication(appOrg, v, APPNAME, APPNAME);

            this.storage.Add(app.Id, app);

            // Create an person and history for the owner history.
            var personAndOrg = new IfcPersonAndOrganization(user, owner);

            this.storage.Add(personAndOrg.Id, personAndOrg);

            // Create an owner history for the project.
            var history = new IfcOwnerHistory(personAndOrg, app, UnixNow());

            this.storage.Add(history.Id, history);

            var lu = new IfcSIUnit(null, IfcUnitEnum.LENGTHUNIT, IfcSIUnitName.METRE);

            this.storage.Add(lu.Id, lu);
            var lengthUnit = new IfcUnit(lu);

            var au = new IfcSIUnit(null, IfcUnitEnum.AREAUNIT, IfcSIUnitName.SQUARE_METRE);

            this.storage.Add(au.Id, au);
            var areaUnit = new IfcUnit(au);

            var vu = new IfcSIUnit(null, IfcUnitEnum.VOLUMEUNIT, IfcSIUnitName.CUBIC_METRE);

            this.storage.Add(vu.Id, vu);
            var volumeUnit = new IfcUnit(vu);

            var sau = new IfcSIUnit(null, IfcUnitEnum.SOLIDANGLEUNIT, IfcSIUnitName.STERADIAN);

            this.storage.Add(sau.Id, sau);
            var solidAngleUnit = new IfcUnit(sau);

            var mu = new IfcSIUnit(null, IfcUnitEnum.MASSUNIT, IfcSIUnitName.GRAM);

            this.storage.Add(mu.Id, mu);
            var massUnit = new IfcUnit(mu);

            var tu = new IfcSIUnit(null, IfcUnitEnum.TIMEUNIT, IfcSIUnitName.SECOND);

            this.storage.Add(tu.Id, tu);
            var timeUnit = new IfcUnit(tu);

            var thu = new IfcSIUnit(null, IfcUnitEnum.THERMODYNAMICTEMPERATUREUNIT, IfcSIUnitName.DEGREE_CELSIUS);

            this.storage.Add(thu.Id, thu);
            var thermUnit = new IfcUnit(thu);

            var lmu = new IfcSIUnit(null, IfcUnitEnum.LUMINOUSINTENSITYUNIT, IfcSIUnitName.LUMEN);

            this.storage.Add(lmu.Id, lmu);
            var lumUnit = new IfcUnit(lmu);

            var pau = new IfcSIUnit(null, IfcUnitEnum.PLANEANGLEUNIT, IfcSIUnitName.RADIAN);

            this.storage.Add(pau.Id, pau);
            var planeAngleUnit = new IfcUnit(pau);

            var measure = new IfcMeasureWithUnit(new IfcValue(new IfcMeasureValue(new IfcPlaneAngleMeasure(1.745e-2))), planeAngleUnit);

            this.storage.Add(measure.Id, measure);

            var dimExp = new IfcDimensionalExponents(0, 0, 0, 0, 0, 0, 0);

            this.storage.Add(dimExp.Id, dimExp);

            var du = new IfcConversionBasedUnit(dimExp, IfcUnitEnum.PLANEANGLEUNIT, "DEGREE", measure);

            this.storage.Add(du.Id, du);
            var degree = new IfcUnit(du);

            var units = new List <IfcUnit> {
                lengthUnit, areaUnit, volumeUnit, solidAngleUnit, massUnit, timeUnit, thermUnit, lumUnit, planeAngleUnit, degree
            };
            var unitAss = new IfcUnitAssignment(units);

            this.storage.Add(unitAss.Id, unitAss);

            // Create the project.
            var proj = new IfcProject(IfcGuid.ToIfcGuid(Guid.NewGuid()), history, name, description, null, null, null, null, unitAss);

            this.storage.Add(proj.Id, proj);
        }
        internal static List <IfcProduct> ToIfcProducts(this Element e,
                                                        IfcRepresentationContext context,
                                                        Document doc,
                                                        Dictionary <Guid, List <IfcStyleAssignmentSelect> > styleAssignments)
        {
            var products = new List <IfcProduct>();

            IfcProductDefinitionShape shape      = null;
            GeometricElement          geoElement = null;
            Transform trans = null;
            Guid      id    = default(Guid);

            if (e is ElementInstance)
            {
                // If we're using an element instance, get the transform
                // and the id and use those to uniquely position and
                // identify the element.
                var instance = (ElementInstance)e;
                geoElement = instance.BaseDefinition;
                id         = instance.Id;
                trans      = instance.Transform;
            }
            else if (e is GeometricElement)
            {
                // If we've go a geometric element, use its properties as-is.
                geoElement = (GeometricElement)e;
                id         = geoElement.Id;
                trans      = geoElement.Transform;
            }

            geoElement.UpdateRepresentations();

            var localPlacement = trans.ToIfcLocalPlacement(doc);

            doc.AddEntity(localPlacement);

            var geoms = new List <IfcRepresentationItem>();

            if (geoElement is MeshElement)
            {
                var meshEl  = (MeshElement)geoElement;
                var lengths = meshEl.Mesh.Vertices.Select(v => v.Position.ToArray().Select(vi => new IfcLengthMeasure(vi)).ToList()).ToList();
                var pts     = new IfcCartesianPointList3D(lengths);
                doc.AddEntity(pts);
                var indices = meshEl.Mesh.Triangles.Select(t => t.Vertices.Select(vx => new IfcPositiveInteger(vx.Index + 1)).ToList()).ToList();
                var idxs    = new List <List <IfcPositiveInteger> >(indices);
                var geom    = new IfcTriangulatedFaceSet(pts, indices);
                geom.Closed = false;
                doc.AddEntity(geom);
                geoms.Add(geom);
                shape = ToIfcProductDefinitionShape(geoms, "Tessellation", context, doc);
            }
            else
            {
                foreach (var op in geoElement.Representation.SolidOperations)
                {
                    if (op is Sweep)
                    {
                        var sweep = (Sweep)op;

                        // Neither of these entities, which are part of the
                        // IFC4 specification, and which would allow a sweep
                        // along a curve, are supported by many applications
                        // which are supposedly IFC4 compliant (Revit). For
                        // Those applications where these entities appear,
                        // the rotation of the profile is often wrong or
                        // inconsistent.
                        // geom = sweep.ToIfcSurfaceCurveSweptAreaSolid(doc);
                        // geom = sweep.ToIfcFixedReferenceSweptAreaSolid(geoElement.Transform, doc);

                        // Instead, we'll divide the curve and create a set of
                        // linear extrusions instead.
                        Polyline pline;
                        if (sweep.Curve is Line)
                        {
                            pline = sweep.Curve.ToPolyline(1);
                        }
                        else
                        {
                            pline = sweep.Curve.ToPolyline();
                        }
                        foreach (var segment in pline.Segments())
                        {
                            var position         = segment.TransformAt(0.0).ToIfcAxis2Placement3D(doc);
                            var extrudeDepth     = segment.Length();
                            var extrudeProfile   = sweep.Profile.Perimeter.ToIfcArbitraryClosedProfileDef(doc);
                            var extrudeDirection = Vector3.ZAxis.Negate().ToIfcDirection();
                            var geom             = new IfcExtrudedAreaSolid(extrudeProfile, position,
                                                                            extrudeDirection, new IfcPositiveLengthMeasure(extrudeDepth));

                            doc.AddEntity(extrudeProfile);
                            doc.AddEntity(extrudeDirection);
                            doc.AddEntity(position);
                            doc.AddEntity(geom);
                            geoms.Add(geom);
                        }
                    }
                    else if (op is Extrude)
                    {
                        var extrude = (Extrude)op;
                        var geom    = extrude.ToIfcExtrudedAreaSolid(doc);
                        doc.AddEntity(geom);
                        geoms.Add(geom);
                    }
                    else if (op is Lamina)
                    {
                        var lamina = (Lamina)op;
                        var geom   = lamina.ToIfcShellBasedSurfaceModel(doc);
                        doc.AddEntity(geom);
                        geoms.Add(geom);
                    }
                    else
                    {
                        throw new Exception("Only IExtrude, ISweepAlongCurve, and ILamina representations are currently supported.");
                    }
                }
                shape = ToIfcProductDefinitionShape(geoms, "SolidModel", context, doc);
            }
            doc.AddEntity(shape);


            // Can we use IfcMappedItem?
            // https://forums.buildingsmart.org/t/can-tessellation-typed-representation-hold-items-from-another-group/1621
            // var rep = new IfcShapeRepresentation(context, "Body", "Solids", geoms);
            // doc.AddEntity(rep);
            // var axisPt = Vector3.Origin.ToIfcCartesianPoint();
            // doc.AddEntity(axisPt);
            // var axis = new IfcAxis2Placement2D(axisPt);
            // doc.AddEntity(axis);
            // var repMap = new IfcRepresentationMap(new IfcAxis2Placement(axis), rep);
            // doc.AddEntity(repMap);
            // var x = trans.XAxis.ToIfcDirection();
            // var y = trans.YAxis.ToIfcDirection();
            // var z = trans.ZAxis.ToIfcDirection();
            // var origin = trans.Origin.ToIfcCartesianPoint();
            // var cart = new IfcCartesianTransformationOperator3D(x, y, origin, trans.XAxis.Length(), z);
            // doc.AddEntity(x);
            // doc.AddEntity(y);
            // doc.AddEntity(z);
            // doc.AddEntity(origin);
            // doc.AddEntity(cart);
            // var mappedItem = new IfcMappedItem(repMap, cart);
            // doc.AddEntity(mappedItem);
            // var shapeRep= new IfcShapeRepresentation(context, new List<IfcRepresentationItem>(){mappedItem});
            // doc.AddEntity(shapeRep);
            // shape = new IfcProductDefinitionShape(new List<IfcRepresentation>(){shapeRep});
            // doc.AddEntity(shape);

            var product = ConvertElementToIfcProduct(id, geoElement, localPlacement, shape);

            products.Add(product);
            doc.AddEntity(product);

            var ifcOpenings = doc.AllEntities.Where(ent => ent.GetType() == typeof(IfcOpeningElement)).Cast <IfcOpeningElement>();

            // If the element has openings, make opening relationships in
            // the IfcElement.
            if (e is IHasOpenings)
            {
                var openings = (IHasOpenings)e;
                if (openings.Openings.Count > 0)
                {
                    foreach (var o in openings.Openings)
                    {
                        var element = (IfcElement)product;
                        // TODO: Find the opening that we've already created that relates here
                        var opening = ifcOpenings.First(ifcO => ifcO.GlobalId == IfcGuid.ToIfcGuid(o.Id));
                        var voidRel = new IfcRelVoidsElement(IfcGuid.ToIfcGuid(Guid.NewGuid()), element, opening);
                        element.HasOpenings.Add(voidRel);
                        doc.AddEntity(voidRel);
                    }
                }
            }

            foreach (var geom in geoms)
            {
                var styledItem = new IfcStyledItem(geom, styleAssignments[geoElement.Material.Id], null);
                doc.AddEntity(styledItem);
            }

            return(products);
        }