/// <summary> /// Exports an element to IFC footing. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="element"> /// The element. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="ifcEnumType"> /// The string value represents the IFC type. /// </param> /// <param name="productWrapper"> /// The IFCProductWrapper. /// </param> public static void ExportFooting(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, string ifcEnumType, IFCProductWrapper productWrapper) { // export parts or not bool exportParts = PartExporter.CanExportParts(element); if (exportParts && !PartExporter.CanExportElementInPartExport(element, element.Level.Id, false)) return; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, element)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(setter.GetPlacement()); IFCAnyHandle prodRep = null; if (!exportParts) { ElementId catId = CategoryUtil.GetSafeCategoryId(element); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); prodRep = RepresentationUtil.CreateBRepProductDefinitionShape(element.Document.Application, exporterIFC, element, catId, geometryElement, bodyExporterOptions, null, ecData); if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodRep)) { ecData.ClearOpenings(); return; } } string instanceGUID = ExporterIFCUtils.CreateGUID(element); string origInstanceName = exporterIFC.GetName(); string instanceName = NamingUtil.GetNameOverride(element, origInstanceName); string instanceDescription = NamingUtil.GetDescriptionOverride(element, null); string instanceObjectType = NamingUtil.GetObjectTypeOverride(element, exporterIFC.GetFamilyName()); string instanceElemId = NamingUtil.CreateIFCElementId(element); Toolkit.IFCFootingType footingType = GetIFCFootingType(element, ifcEnumType); IFCAnyHandle footing = IFCInstanceExporter.CreateFooting(file, instanceGUID, exporterIFC.GetOwnerHistoryHandle(), instanceName, instanceDescription, instanceObjectType, ecData.GetLocalPlacement(), prodRep, instanceElemId, footingType); if (exportParts) { PartExporter.ExportHostPart(exporterIFC, element, footing, productWrapper, setter, setter.GetPlacement(), null); } productWrapper.AddElement(footing, setter, ecData, LevelUtil.AssociateElementToLevel(element)); OpeningUtil.CreateOpeningsIfNecessary(footing, element, ecData, exporterIFC, ecData.GetLocalPlacement(), setter, productWrapper); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, productWrapper); } } tr.Commit(); } }
/// <summary> /// Exports mullion. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="mullion"> /// The mullion object. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="localPlacement"> /// The local placement handle. /// </param> /// <param name="extraParams"> /// The extrusion creation data. /// </param> /// <param name="setter"> /// The IFCPlacementSetter. /// </param> /// <param name="productWrapper"> /// The IFCProductWrapper. /// </param> public static void Export(ExporterIFC exporterIFC, Mullion mullion, GeometryElement geometryElement, IFCAnyHandle localPlacement, IFCExtrusionCreationData extraParams, IFCPlacementSetter setter, IFCProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); ElementId catId = CategoryUtil.GetSafeCategoryId(mullion); IFCSolidMeshGeometryInfo solidMeshInfo = ExporterIFCUtils.GetSolidMeshGeometry(exporterIFC, geometryElement, Transform.Identity); IList<Solid> solids = solidMeshInfo.GetSolids(); IList<Mesh> polyMeshes = solidMeshInfo.GetMeshes(); bool tryToExportAsExtrusion = true; if (solids.Count != 1 || polyMeshes.Count != 0) tryToExportAsExtrusion = false; IFCAnyHandle shapeRep = BodyExporter.ExportBody(mullion.Document.Application, exporterIFC, catId, solids, polyMeshes, tryToExportAsExtrusion, extraParams); IList<IFCAnyHandle> shapeReps = new List<IFCAnyHandle>(); shapeReps.Add(shapeRep); IFCAnyHandle repHnd = file.CreateProductDefinitionShape(IFCLabel.Create(), IFCLabel.Create(), shapeReps); IFCLabel elemGUID = IFCLabel.CreateGUID(mullion); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); IFCLabel elemObjectType = NamingUtil.CreateIFCObjectName(exporterIFC, mullion); IFCLabel elemId = NamingUtil.CreateIFCElementId(mullion); //IFCLabel elemType = IFCLabel.Create("MULLION"); IFCAnyHandle mullionHnd = file.CreateMember(elemGUID, ownerHistory, elemObjectType, IFCLabel.Create(), elemObjectType, localPlacement, repHnd, elemId); productWrapper.AddElement(mullionHnd, setter, extraParams, true); }
/// <summary> /// Exports mullion. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="mullion"> /// The mullion object. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="localPlacement"> /// The local placement handle. /// </param> /// <param name="extraParams"> /// The extrusion creation data. /// </param> /// <param name="setter"> /// The IFCPlacementSetter. /// </param> /// <param name="productWrapper"> /// The IFCProductWrapper. /// </param> public static void Export(ExporterIFC exporterIFC, Mullion mullion, GeometryElement geometryElement, IFCAnyHandle localPlacement, IFCExtrusionCreationData extraParams, IFCPlacementSetter setter, IFCProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); ElementId catId = CategoryUtil.GetSafeCategoryId(mullion); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); IFCAnyHandle repHnd = RepresentationUtil.CreateBRepProductDefinitionShape(mullion.Document.Application, exporterIFC, mullion, catId, geometryElement, bodyExporterOptions, null, extraParams); if (IFCAnyHandleUtil.IsNullOrHasNoValue(repHnd)) { extraParams.ClearOpenings(); return; } string elemGUID = ExporterIFCUtils.CreateGUID(mullion); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string elemObjectType = NamingUtil.CreateIFCObjectName(exporterIFC, mullion); string elemId = NamingUtil.CreateIFCElementId(mullion); IFCAnyHandle mullionHnd = IFCInstanceExporter.CreateMember(file, elemGUID, ownerHistory, elemObjectType, null, elemObjectType, localPlacement, repHnd, elemId); productWrapper.AddElement(mullionHnd, setter, extraParams, LevelUtil.AssociateElementToLevel(mullion)); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, mullion, productWrapper); }
/// <summary> /// Exports a ceiling to IFC covering. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="ceiling"> /// The ceiling element to be exported. /// </param> /// <param name="geomElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void ExportCeilingElement(ExporterIFC exporterIFC, Ceiling ceiling, GeometryElement geomElement, ProductWrapper productWrapper) { string ifcEnumType = CategoryUtil.GetIFCEnumTypeName(exporterIFC, ceiling); if (String.IsNullOrEmpty(ifcEnumType)) ifcEnumType = "CEILING"; ExportCovering(exporterIFC, ceiling, geomElement, ifcEnumType, productWrapper); }
/// <summary> /// Exports a hosted weep. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="hostedSweep">The hosted sweep element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void Export(ExporterIFC exporterIFC, HostedSweep hostedSweep, GeometryElement geometryElement, ProductWrapper productWrapper) { ElementId catId = CategoryUtil.GetSafeCategoryId(hostedSweep); if (catId == new ElementId(BuiltInCategory.OST_Gutter)) ExportGutter(exporterIFC, hostedSweep, geometryElement, productWrapper); else ProxyElementExporter.Export(exporterIFC, hostedSweep, geometryElement, productWrapper); }
/// <summary> /// Exports a geometry element to boundary representation. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="exportBoundaryRep">True if to export boundary representation.</param> /// <param name="exportAsFacetation">True if to export the geometry as facetation.</param> /// <param name="bodyRep">Body representation.</param> /// <param name="boundaryRep">Boundary representation.</param> /// <returns>True if success, false if fail.</returns> public static bool ExportSurface(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, bool exportBoundaryRep, bool exportAsFacetation, ref IFCAnyHandle bodyRep, ref IFCAnyHandle boundaryRep) { if (geometryElement == null) return false; IFCGeometryInfo ifcGeomInfo = null; Document doc = element.Document; Plane plane = GeometryUtil.CreateDefaultPlane(); XYZ projDir = new XYZ(0, 0, 1); double eps = UnitUtil.ScaleLength(doc.Application.VertexTolerance); ifcGeomInfo = IFCGeometryInfo.CreateFaceGeometryInfo(exporterIFC, plane, projDir, eps, exportBoundaryRep); ExporterIFCUtils.CollectGeometryInfo(exporterIFC, ifcGeomInfo, geometryElement, XYZ.Zero, true); IFCFile file = exporterIFC.GetFile(); HashSet<IFCAnyHandle> faceSets = new HashSet<IFCAnyHandle>(); IList<ICollection<IFCAnyHandle>> faceList = ifcGeomInfo.GetFaces(); foreach (ICollection<IFCAnyHandle> faces in faceList) { // no faces, don't complain. if (faces.Count == 0) continue; HashSet<IFCAnyHandle> faceSet = new HashSet<IFCAnyHandle>(faces); faceSets.Add(IFCInstanceExporter.CreateConnectedFaceSet(file, faceSet)); } if (faceSets.Count == 0) return false; IFCAnyHandle surface = IFCInstanceExporter.CreateFaceBasedSurfaceModel(file, faceSets); BodyExporter.CreateSurfaceStyleForRepItem(exporterIFC, doc, surface, BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, element)); ISet<IFCAnyHandle> surfaceItems = new HashSet<IFCAnyHandle>(); surfaceItems.Add(surface); ElementId catId = CategoryUtil.GetSafeCategoryId(element); bodyRep = RepresentationUtil.CreateSurfaceRep(exporterIFC, element, catId, exporterIFC.Get3DContextHandle("Body"), surfaceItems, exportAsFacetation, bodyRep); if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep)) return false; ICollection<IFCAnyHandle> boundaryRepresentations = ifcGeomInfo.GetRepresentations(); if (exportBoundaryRep && boundaryRepresentations.Count > 0) { HashSet<IFCAnyHandle> boundaryRepresentationSet = new HashSet<IFCAnyHandle>(); boundaryRepresentationSet.UnionWith(boundaryRepresentations); boundaryRep = RepresentationUtil.CreateBoundaryRep(exporterIFC, element, catId, exporterIFC.Get3DContextHandle("FootPrint"), boundaryRepresentationSet, boundaryRep); } return true; }
/// <summary> /// Exports a floor to IFC slab. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="floor"> /// The floor element. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void Export(ExporterIFC exporterIFC, HostObject floor, GeometryElement geometryElement, ProductWrapper productWrapper) { string ifcEnumType = CategoryUtil.GetIFCEnumTypeName(exporterIFC, floor); // export parts or not bool exportParts = PartExporter.CanExportParts(floor); if (exportParts && !PartExporter.CanExportElementInPartExport(floor, floor.Level.Id, false)) return; ExportFloor(exporterIFC, floor, geometryElement, ifcEnumType, productWrapper, exportParts); }
/// <summary> /// Exports an element as a covering of type insulation. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <returns>True if exported successfully, false otherwise.</returns> public static bool ExportDuctLining(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { if (element == null || geometryElement == null) return false; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, element)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(placementSetter.LocalPlacement); ElementId categoryId = CategoryUtil.GetSafeCategoryId(element); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); IFCAnyHandle representation = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, element, categoryId, geometryElement, bodyExporterOptions, null, ecData, true); if (IFCAnyHandleUtil.IsNullOrHasNoValue(representation)) { ecData.ClearOpenings(); return false; } string guid = GUIDUtil.CreateGUID(element); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string revitObjectType = exporterIFC.GetFamilyName(); string name = NamingUtil.GetNameOverride(element, revitObjectType); string description = NamingUtil.GetDescriptionOverride(element, null); string objectType = NamingUtil.GetObjectTypeOverride(element, revitObjectType); IFCAnyHandle localPlacement = ecData.GetLocalPlacement(); string elementTag = NamingUtil.GetTagOverride(element, NamingUtil.CreateIFCElementId(element)); IFCAnyHandle ductLining = IFCInstanceExporter.CreateCovering(file, guid, ownerHistory, name, description, objectType, localPlacement, representation, elementTag, "Wrapping"); ExporterCacheManager.ElementToHandleCache.Register(element.Id, ductLining); productWrapper.AddElement(element, ductLining, placementSetter.LevelInfo, ecData, true); ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, element); CategoryUtil.CreateMaterialAssociation(exporterIFC, ductLining, matId); } } tr.Commit(); return true; } }
/// <summary> /// Exports a wall swepp. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="wallSweep">The WallSwepp.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void Export(ExporterIFC exporterIFC, WallSweep wallSweep, GeometryElement geometryElement, ProductWrapper productWrapper) { WallSweepInfo wallSweepInfo = wallSweep.GetWallSweepInfo(); //Reveals are exported as openings with wall exporter. if (wallSweepInfo.WallSweepType == WallSweepType.Reveal) return; if (!ProxyElementExporter.Export(exporterIFC, wallSweep, geometryElement, productWrapper)) return; HostObjectExporter.ExportHostObjectMaterials(exporterIFC, wallSweep, productWrapper.GetAnElement(), geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis2); }
/// <summary> /// Exports an element as a covering of type insulation. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <returns>True if exported successfully, false otherwise.</returns> public static bool ExportDuctLining(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { if (element == null || geometryElement == null) return false; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (IFCPlacementSetter placementSetter = IFCPlacementSetter.Create(exporterIFC, element)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(placementSetter.GetPlacement()); ElementId categoryId = CategoryUtil.GetSafeCategoryId(element); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); IFCAnyHandle representation = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, element, categoryId, geometryElement, bodyExporterOptions, null, ecData); if (IFCAnyHandleUtil.IsNullOrHasNoValue(representation)) { ecData.ClearOpenings(); return false; } string guid = GUIDUtil.CreateGUID(element); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string revitObjectType = exporterIFC.GetFamilyName(); string name = NamingUtil.GetNameOverride(element, revitObjectType); string description = NamingUtil.GetDescriptionOverride(element, null); string objectType = NamingUtil.GetObjectTypeOverride(element, revitObjectType); IFCAnyHandle localPlacement = ecData.GetLocalPlacement(); string elementTag = NamingUtil.GetTagOverride(element, NamingUtil.CreateIFCElementId(element)); IFCAnyHandle ductLining = IFCInstanceExporter.CreateCovering(file, guid, ownerHistory, name, description, objectType, localPlacement, representation, elementTag, IFCCoveringType.Wrapping); productWrapper.AddElement(ductLining, placementSetter.GetLevelInfo(), ecData, LevelUtil.AssociateElementToLevel(element)); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, productWrapper); } } tr.Commit(); return true; } }
/// <summary> /// Exports mullion. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="mullion"> /// The mullion object. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="localPlacement"> /// The local placement handle. /// </param> /// <param name="setter"> /// The IFCPlacementSetter. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void Export(ExporterIFC exporterIFC, Mullion mullion, GeometryElement geometryElement, IFCAnyHandle localPlacement, IFCPlacementSetter setter, ProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); using (IFCPlacementSetter mullionSetter = IFCPlacementSetter.Create(exporterIFC, mullion, null, null, ExporterUtil.GetBaseLevelIdForElement(mullion))) { using (IFCExtrusionCreationData extraParams = new IFCExtrusionCreationData()) { IFCAnyHandle mullionPlacement = mullionSetter.GetPlacement(); Transform relTrf = ExporterIFCUtils.GetRelativeLocalPlacementOffsetTransform(localPlacement, mullionPlacement); Transform inverseTrf = relTrf.Inverse; IFCAnyHandle mullionRelativePlacement = ExporterUtil.CreateAxis2Placement3D(file, inverseTrf.Origin, inverseTrf.BasisZ, inverseTrf.BasisX); IFCAnyHandle mullionLocalPlacement = IFCInstanceExporter.CreateLocalPlacement(file, localPlacement, mullionRelativePlacement); extraParams.SetLocalPlacement(mullionLocalPlacement); ElementId catId = CategoryUtil.GetSafeCategoryId(mullion); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); IFCAnyHandle repHnd = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, mullion, catId, geometryElement, bodyExporterOptions, null, extraParams, true); if (IFCAnyHandleUtil.IsNullOrHasNoValue(repHnd)) { extraParams.ClearOpenings(); return; } string elemGUID = GUIDUtil.CreateGUID(mullion); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string elemObjectType = NamingUtil.CreateIFCObjectName(exporterIFC, mullion); string name = NamingUtil.GetNameOverride(mullion, elemObjectType); string description = NamingUtil.GetDescriptionOverride(mullion, null); string objectType = NamingUtil.GetObjectTypeOverride(mullion, elemObjectType); string elemTag = NamingUtil.GetTagOverride(mullion, NamingUtil.CreateIFCElementId(mullion)); IFCAnyHandle mullionHnd = IFCInstanceExporter.CreateMember(file, elemGUID, ownerHistory, name, description, objectType, mullionLocalPlacement, repHnd, elemTag); ExporterCacheManager.HandleToElementCache.Register(mullionHnd, mullion.Id); productWrapper.AddElement(mullion, mullionHnd, mullionSetter, extraParams, false); ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, mullion); CategoryUtil.CreateMaterialAssociation(exporterIFC, mullionHnd, matId); } } }
/// <summary> /// Exports an element as building element proxy. /// </summary> /// <remarks> /// This function is called from the Export function, but can also be called directly if you do not /// want CreateInternalPropertySets to be called. /// </remarks> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <returns>The handle if created, null otherwise.</returns> public static IFCAnyHandle ExportBuildingElementProxy(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { if (element == null || geometryElement == null) return null; IFCFile file = exporterIFC.GetFile(); IFCAnyHandle buildingElementProxy = null; using (IFCTransaction tr = new IFCTransaction(file)) { using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, element)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(placementSetter.LocalPlacement); ElementId categoryId = CategoryUtil.GetSafeCategoryId(element); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); IFCAnyHandle representation = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, element, categoryId, geometryElement, bodyExporterOptions, null, ecData, true); if (IFCAnyHandleUtil.IsNullOrHasNoValue(representation)) { ecData.ClearOpenings(); return null; } string guid = GUIDUtil.CreateGUID(element); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; string revitObjectType = exporterIFC.GetFamilyName(); string name = NamingUtil.GetNameOverride(element, revitObjectType); string description = NamingUtil.GetDescriptionOverride(element, null); string objectType = NamingUtil.GetObjectTypeOverride(element, revitObjectType); IFCAnyHandle localPlacement = ecData.GetLocalPlacement(); string elementTag = NamingUtil.GetTagOverride(element, NamingUtil.CreateIFCElementId(element)); buildingElementProxy = IFCInstanceExporter.CreateBuildingElementProxy(file, guid, ownerHistory, name, description, objectType, localPlacement, representation, elementTag, null); productWrapper.AddElement(element, buildingElementProxy, placementSetter.LevelInfo, ecData, true); } tr.Commit(); } } return buildingElementProxy; }
/// <summary> /// Helper Function: parse the geometry element by geometry type. /// Geometry informaion can easily go into depth. Here we look at the top level. /// See RevitCommands in the SDK sample for complete implementation. /// </summary> public static string GeometryElementToString(GeometryElement geomElem) { string str = string.Empty; foreach (GeometryObject geomObj in geomElem) { if (geomObj is Solid) { // ex. wall Solid solid = (Solid)geomObj; //str += GeometrySolidToString(solid); str += "Solid" + "\n"; } else if (geomObj is GeometryInstance) { // ex. door/window str += " -- Geometry.Instance -- " + "\n"; GeometryInstance geomInstance = (GeometryInstance)geomObj; GeometryElement geoElem = geomInstance.SymbolGeometry; str += GeometryElementToString(geoElem); } else if (geomObj is Curve) { Curve curv = (Curve)geomObj; //str += GeometryCurveToString(curv); str += "Curve" + "\n"; } else if (geomObj is Mesh) { Mesh mesh = (Mesh)geomObj; //str += GeometryMeshToString(mesh); str += "Mesh" + "\n"; } else { str += " *** unkown geometry type" + geomObj.GetType().ToString(); } } return str; }
/// <summary> /// Exports an element as IFC covering. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="element"> /// The element to be exported. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void ExportCovering(ExporterIFC exporterIFC, Element element, GeometryElement geomElem, string ifcEnumType, ProductWrapper productWrapper) { bool exportParts = PartExporter.CanExportParts(element); if (exportParts && !PartExporter.CanExportElementInPartExport(element, element.Level.Id, false)) return; ElementType elemType = element.Document.GetElement(element.GetTypeId()) as ElementType; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction transaction = new IFCTransaction(file)) { using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, element)) { IFCAnyHandle prodRep = exportParts ? null : RepresentationUtil.CreateSurfaceProductDefinitionShape(exporterIFC, element, geomElem, false, false); string instanceGUID = GUIDUtil.CreateGUID(element); string instanceName = NamingUtil.GetIFCName(element); string instanceDescription = NamingUtil.GetDescriptionOverride(element, null); string instanceObjectType = NamingUtil.GetObjectTypeOverride(element, exporterIFC.GetFamilyName()); string instanceElemId = NamingUtil.CreateIFCElementId(element); Toolkit.IFCCoveringType coveringType = GetIFCCoveringType(element, ifcEnumType); IFCAnyHandle covering = IFCInstanceExporter.CreateCovering(file, instanceGUID, exporterIFC.GetOwnerHistoryHandle(), instanceName, instanceDescription, instanceObjectType, setter.GetPlacement(), prodRep, instanceElemId, coveringType); if (exportParts) { PartExporter.ExportHostPart(exporterIFC, element, covering, productWrapper, setter, setter.GetPlacement(), null); } productWrapper.AddElement(covering, setter, null, LevelUtil.AssociateElementToLevel(element)); Ceiling ceiling = element as Ceiling; if (ceiling != null && !exportParts) { HostObjectExporter.ExportHostObjectMaterials(exporterIFC, ceiling, covering, geomElem, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3); } if (ExporterCacheManager.ExportOptionsCache.PropertySetOptions.ExportIFCCommon) ExporterIFCUtils.CreateCoveringPropertySet(exporterIFC, element, productWrapper.ToNative()); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, productWrapper); } transaction.Commit(); } }
/// <summary> /// Exports an element as building element proxy. /// </summary> /// <remarks> /// This function is called from the Export function, but can also be called directly if you do not /// want CreateInternalPropertySets to be called. /// </remarks> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The IFCProductWrapper.</param> /// <returns>True if exported successfully, false otherwise.</returns> public static bool ExportBuildingElementProxy(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, IFCProductWrapper productWrapper) { if (element == null || geometryElement == null) return false; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (IFCPlacementSetter placementSetter = IFCPlacementSetter.Create(exporterIFC, element)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(placementSetter.GetPlacement()); ElementId categoryId = CategoryUtil.GetSafeCategoryId(element); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); IFCAnyHandle representation = RepresentationUtil.CreateBRepProductDefinitionShape(element.Document.Application, exporterIFC, element, categoryId, geometryElement, bodyExporterOptions, null, ecData); if (IFCAnyHandleUtil.IsNullOrHasNoValue(representation)) { ecData.ClearOpenings(); return false; } string guid = ExporterIFCUtils.CreateGUID(element); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string objectType = exporterIFC.GetFamilyName(); IFCAnyHandle localPlacement = ecData.GetLocalPlacement(); string elementTag = NamingUtil.CreateIFCElementId(element); IFCAnyHandle buildingElementProxy = IFCInstanceExporter.CreateBuildingElementProxy(file, guid, ownerHistory, objectType, null, objectType, localPlacement, representation, elementTag, Toolkit.IFCElementComposition.Element); productWrapper.AddElement(buildingElementProxy, placementSetter.GetLevelInfo(), ecData, LevelUtil.AssociateElementToLevel(element)); } tr.Commit(); return true; } } }
/// <summary> /// Exports mullion. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="mullion"> /// The mullion object. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="localPlacement"> /// The local placement handle. /// </param> /// <param name="extraParams"> /// The extrusion creation data. /// </param> /// <param name="setter"> /// The IFCPlacementSetter. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void Export(ExporterIFC exporterIFC, Mullion mullion, GeometryElement geometryElement, IFCAnyHandle localPlacement, IFCExtrusionCreationData extraParams, IFCPlacementSetter setter, ProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); using (IFCPlacementSetter mullionSetter = IFCPlacementSetter.Create(exporterIFC, mullion)) { IFCAnyHandle mullionPlacement = mullionSetter.GetPlacement(); Transform relTrf = ExporterIFCUtils.GetRelativeLocalPlacementOffsetTransform(localPlacement, mullionPlacement); Transform inverseTrf = relTrf.Inverse; IFCAnyHandle mullionRelativePlacement = ExporterUtil.CreateAxis2Placement3D(file, inverseTrf.Origin, inverseTrf.BasisZ, inverseTrf.BasisX); IFCAnyHandle mullionLocalPlacement = IFCInstanceExporter.CreateLocalPlacement(file, localPlacement, mullionRelativePlacement); extraParams.SetLocalPlacement(mullionLocalPlacement); ElementId catId = CategoryUtil.GetSafeCategoryId(mullion); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); IFCAnyHandle repHnd = RepresentationUtil.CreateBRepProductDefinitionShape(mullion.Document.Application, exporterIFC, mullion, catId, geometryElement, bodyExporterOptions, null, extraParams); if (IFCAnyHandleUtil.IsNullOrHasNoValue(repHnd)) { extraParams.ClearOpenings(); return; } string elemGUID = GUIDUtil.CreateGUID(mullion); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string elemObjectType = NamingUtil.CreateIFCObjectName(exporterIFC, mullion); string elemId = NamingUtil.CreateIFCElementId(mullion); IFCAnyHandle mullionHnd = IFCInstanceExporter.CreateMember(file, elemGUID, ownerHistory, elemObjectType, null, elemObjectType, mullionLocalPlacement, repHnd, elemId); productWrapper.AddElement(mullionHnd, mullionSetter, extraParams, false); ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, mullion); CategoryUtil.CreateMaterialAssociation(mullion.Document, exporterIFC, mullionHnd, matId); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, mullion, productWrapper); } }
/// <summary> /// Exports an element as building element proxy. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <returns>True if exported successfully, false otherwise.</returns> public static bool Export(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { bool exported = false; if (element == null || geometryElement == null) return exported; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { exported = ExportBuildingElementProxy(exporterIFC, element, geometryElement, productWrapper); if (exported) { PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, productWrapper); tr.Commit(); } } return exported; }
/// <summary> /// Exports a staircase to IfcStair. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The stairs element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void Export(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { string ifcEnumType = CategoryUtil.GetIFCEnumTypeName(exporterIFC, element); IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { if (element is Stairs) { Stairs stair = element as Stairs; int numFlights = stair.NumberOfStories; if (numFlights > 0) { ExportStairsAsContainer(exporterIFC, ifcEnumType, stair, geometryElement, numFlights, productWrapper); if (IFCAnyHandleUtil.IsNullOrHasNoValue(productWrapper.GetAnElement())) ExportStairAsSingleGeometry(exporterIFC, ifcEnumType, element, geometryElement, numFlights, productWrapper); } } else if (IsLegacyStairs(element)) { ExportLegacyStairOrRampAsContainer(exporterIFC, ifcEnumType, element, geometryElement, true, productWrapper); if (IFCAnyHandleUtil.IsNullOrHasNoValue(productWrapper.GetAnElement())) { double defaultHeight = GetDefaultHeightForLegacyStair(exporterIFC.LinearScale); int numFlights = GetNumFlightsForLegacyStair(exporterIFC, element, defaultHeight); if (numFlights > 0) ExportStairAsSingleGeometry(exporterIFC, ifcEnumType, element, geometryElement, numFlights, productWrapper); } } else { ExportStairAsSingleGeometry(exporterIFC, ifcEnumType, element, geometryElement, 1, productWrapper); } PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, productWrapper); tr.Commit(); } }
/// <summary> /// Creates the bounding box representation corresponding to a particular geometry. /// </summary> /// <param name="exporterIFC">The exporterIFC.</param> /// <param name="geomElement">The geometry of the element.</param> /// <param name="trf">An extra transform to apply, generally used for families.</param> /// <returns>The handle to the bounding box representation, or null if not valid or not exported.</returns> public static IFCAnyHandle ExportBoundingBox(ExporterIFC exporterIFC, GeometryElement geomElement, Transform trf) { if (!ExporterCacheManager.ExportOptionsCache.ExportBoundingBox) return null; if (geomElement == null) return null; SolidMeshGeometryInfo solidMeshCapsule = GeometryUtil.GetSolidMeshGeometry(geomElement, Transform.Identity); IList<Solid> solids = solidMeshCapsule.GetSolids(); IList<Mesh> meshes = solidMeshCapsule.GetMeshes(); IList<Face> faces = new List<Face>(); return ExportBoundingBoxFromGeometry(exporterIFC, solids, meshes, faces, trf); }
/// <summary> /// Exports curtain object as container. /// </summary> /// <param name="allSubElements"> /// Collection of elements contained in the host curtain element. /// </param> /// <param name="wallElement"> /// The curtain wall element. /// </param> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void ExportCurtainObjectCommonAsContainer(ICollection <ElementId> allSubElements, Element wallElement, ExporterIFC exporterIFC, ProductWrapper origWrapper, PlacementSetter currSetter) { if (wallElement == null) { return; } string overrideCADLayer = null; if (ParameterUtil.GetStringValueFromElementOrSymbol(wallElement, "IFCCadLayer", out overrideCADLayer) == null || string.IsNullOrWhiteSpace(overrideCADLayer)) { if ((ParameterUtil.GetStringValueFromElementOrSymbol(wallElement, "IfcPresentationLayer", out overrideCADLayer) == null) || string.IsNullOrWhiteSpace(overrideCADLayer)) { overrideCADLayer = ExporterStateManager.GetCurrentCADLayerOverride(); } } using (ExporterStateManager.CADLayerOverrideSetter layerSetter = new ExporterStateManager.CADLayerOverrideSetter(overrideCADLayer)) { HashSet <ElementId> alreadyVisited = new HashSet <ElementId>(); // just in case. Options geomOptions = GeometryUtil.GetIFCExportGeometryOptions(); { foreach (ElementId subElemId in allSubElements) { using (ProductWrapper productWrapper = ProductWrapper.Create(origWrapper)) { Element subElem = wallElement.Document.GetElement(subElemId); if (subElem == null) { continue; } if (alreadyVisited.Contains(subElem.Id)) { continue; } alreadyVisited.Add(subElem.Id); // Respect element visibility settings. if (!ElementFilteringUtil.CanExportElement(exporterIFC, subElem, false) || !ElementFilteringUtil.IsElementVisible(subElem)) { continue; } GeometryElement geomElem = subElem.get_Geometry(geomOptions); if (geomElem == null) { continue; } try { if (subElem is FamilyInstance) { string ifcEnumType; IFCExportInfoPair exportType = ExporterUtil.GetExportType(exporterIFC, subElem, out ifcEnumType); if (subElem is Mullion) { if (ExporterCacheManager.ExportOptionsCache.ExportAs2x2) { ProxyElementExporter.Export(exporterIFC, subElem, geomElem, productWrapper, exportType); } else { IFCAnyHandle currLocalPlacement = currSetter.LocalPlacement; if (exportType.ExportInstance == IFCEntityType.IfcCurtainWall) { // By default, panels and mullions are set to the same category as their parent. In this case, // ask to get the exportType from the category id, since we don't want to inherit the parent class. ifcEnumType = "MULLION"; exportType.SetValueWithPair(IFCEntityType.IfcMemberType, ifcEnumType); } FamilyInstanceExporter.ExportFamilyInstanceAsMappedItem(exporterIFC, subElem as Mullion, exportType, exportType.ValidatedPredefinedType, productWrapper, ElementId.InvalidElementId, null, currLocalPlacement); } } else { FamilyInstance subFamInst = subElem as FamilyInstance; if (exportType.ExportInstance == IFCEntityType.IfcCurtainWall) { // By default, panels and mullions are set to the same category as their parent. In this case, // ask to get the exportType from the category id, since we don't want to inherit the parent class. ElementId catId = CategoryUtil.GetSafeCategoryId(subElem); exportType = ElementFilteringUtil.GetExportTypeFromCategoryId(catId, out ifcEnumType); } if (ExporterCacheManager.ExportOptionsCache.ExportAs2x2) { if ((exportType.ExportInstance == IFCEntityType.UnKnown) || (exportType.ExportInstance == IFCEntityType.IfcPlate) || (exportType.ExportInstance == IFCEntityType.IfcMember)) { exportType.SetValueWithPair(IFCEntityType.IfcBuildingElementProxy, ifcEnumType); } } else { if (exportType.ExportInstance == IFCEntityType.UnKnown) { ifcEnumType = "CURTAIN_PANEL"; exportType.SetValueWithPair(IFCEntityType.IfcPlateType, ifcEnumType); } } IFCAnyHandle currLocalPlacement = currSetter.LocalPlacement; using (IFCExtrusionCreationData extraParams = new IFCExtrusionCreationData()) { FamilyInstanceExporter.ExportFamilyInstanceAsMappedItem(exporterIFC, subFamInst, exportType, ifcEnumType, productWrapper, ElementId.InvalidElementId, null, currLocalPlacement); } } } else if (subElem is CurtainGridLine) { ProxyElementExporter.Export(exporterIFC, subElem, geomElem, productWrapper); } else if (subElem is Wall) { WallExporter.ExportWall(exporterIFC, null, subElem, null, geomElem, productWrapper); } } catch (Exception ex) { if (ExporterUtil.IsFatalException(wallElement.Document, ex)) { throw ex; } continue; } } } } } }
/// <summary> /// Exports a generic element as an IfcSlab.</summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="floor">The floor element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="ifcEnumType">The string value represents the IFC type.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <returns>True if the floor is exported successfully, false otherwise.</returns> public static void ExportGenericSlab(ExporterIFC exporterIFC, Element slabElement, GeometryElement geometryElement, string ifcEnumType, ProductWrapper productWrapper) { if (geometryElement == null) { return; } IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (IFCTransformSetter transformSetter = IFCTransformSetter.Create()) { using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, slabElement)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { bool exportParts = PartExporter.CanExportParts(slabElement); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; IFCAnyHandle localPlacement = placementSetter.LocalPlacement; IFCAnyHandle prodDefHnd = null; bool isBRepSlabHnd = false; if (!exportParts) { ecData.SetLocalPlacement(localPlacement); ElementId catId = CategoryUtil.GetSafeCategoryId(slabElement); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.Medium); BodyData bodyData; prodDefHnd = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, slabElement, catId, geometryElement, bodyExporterOptions, null, ecData, out bodyData); if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodDefHnd)) { ecData.ClearOpenings(); return; } isBRepSlabHnd = (bodyData.ShapeRepresentationType == ShapeRepresentationType.Brep || bodyData.ShapeRepresentationType == ShapeRepresentationType.Tessellation); } // Create the slab from either the extrusion or the BRep information. string ifcGUID = GUIDUtil.CreateGUID(slabElement); string entityType = IFCValidateEntry.GetValidIFCType <IFCSlabType>(slabElement, ifcEnumType, "FLOOR"); IFCAnyHandle slabHnd = IFCInstanceExporter.CreateSlab(exporterIFC, slabElement, ifcGUID, ownerHistory, localPlacement, exportParts ? null : prodDefHnd, entityType); if (IFCAnyHandleUtil.IsNullOrHasNoValue(slabHnd)) { return; } if (exportParts) { PartExporter.ExportHostPart(exporterIFC, slabElement, slabHnd, productWrapper, placementSetter, localPlacement, null); } productWrapper.AddElement(slabElement, slabHnd, placementSetter, ecData, true); if (!exportParts) { IFCExportInfoPair exportInfo = new IFCExportInfoPair(IFCEntityType.IfcSlab, IFCEntityType.IfcSlabType, entityType); IFCAnyHandle typeHnd = ExporterUtil.CreateGenericTypeFromElement(slabElement, exportInfo, file, ownerHistory, entityType, productWrapper); ExporterCacheManager.TypeRelationsCache.Add(typeHnd, slabHnd); if (slabElement is HostObject) { HostObject hostObject = slabElement as HostObject; HostObjectExporter.ExportHostObjectMaterials(exporterIFC, hostObject, slabHnd, geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, isBRepSlabHnd, typeHnd); } else if (slabElement is FamilyInstance) { ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, slabElement); //Document doc = slabElement.Document; if (typeHnd != null) { CategoryUtil.CreateMaterialAssociation(exporterIFC, typeHnd, matId); } else { CategoryUtil.CreateMaterialAssociation(exporterIFC, slabHnd, matId); } } OpeningUtil.CreateOpeningsIfNecessary(slabHnd, slabElement, ecData, null, exporterIFC, ecData.GetLocalPlacement(), placementSetter, productWrapper); } } } tr.Commit(); return; } } }
/// <summary> /// Return a reference to the topmost face of the given element. /// </summary> private Reference FindTopMostReference(Element e) { Reference ret = null; Document doc = e.Document; #region Revit 2012 #if _2012 using (SubTransaction t = new SubTransaction(doc)) { t.Start(); // Create temporary 3D view //View3D view3D = doc.Create.NewView3D( // 2012 // viewDirection ); // 2012 ViewFamilyType vft = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .FirstOrDefault <ViewFamilyType>(x => ViewFamily.ThreeDimensional == x.ViewFamily); Debug.Assert(null != vft, "expected to find a valid 3D view family type"); View3D view = View3D.CreateIsometric(doc, vft.Id); // 2013 XYZ eyePosition = XYZ.BasisZ; XYZ upDirection = XYZ.BasisY; XYZ forwardDirection = -XYZ.BasisZ; view.SetOrientation(new ViewOrientation3D( eyePosition, upDirection, forwardDirection)); XYZ viewDirection = -XYZ.BasisZ; BoundingBoxXYZ bb = e.get_BoundingBox(view); XYZ max = bb.Max; XYZ minAtMaxElevation = Create.NewXYZ( bb.Min.X, bb.Min.Y, max.Z); XYZ centerOfTopOfBox = 0.5 * (minAtMaxElevation + max); centerOfTopOfBox += 10 * XYZ.BasisZ; // Cast a ray through the model // to find the topmost surface #if DEBUG //ReferenceArray references // = doc.FindReferencesByDirection( // centerOfTopOfBox, viewDirection, view3D ); // 2011 IList <ReferenceWithContext> references = doc.FindReferencesWithContextByDirection( centerOfTopOfBox, viewDirection, view); // 2012 double closest = double.PositiveInfinity; //foreach( Reference r in references ) //{ // // 'Autodesk.Revit.DB.Reference.Element' is // // obsolete: Property will be removed. Use // // Document.GetElement(Reference) instead. // //Element re = r.Element; // 2011 // Element re = doc.GetElement( r ); // 2012 // if( re.Id.IntegerValue == e.Id.IntegerValue // && r.ProximityParameter < closest ) // { // ret = r; // closest = r.ProximityParameter; // } //} foreach (ReferenceWithContext r in references) { Element re = doc.GetElement( r.GetReference()); // 2012 if (re.Id.IntegerValue == e.Id.IntegerValue && r.Proximity < closest) { ret = r.GetReference(); closest = r.Proximity; } } string stable_reference = null == ret ? null : ret.ConvertToStableRepresentation(doc); #endif // DEBUG ReferenceIntersector ri = new ReferenceIntersector( e.Id, FindReferenceTarget.Element, view); ReferenceWithContext r2 = ri.FindNearest( centerOfTopOfBox, viewDirection); if (null == r2) { Debug.Print("ReferenceIntersector.FindNearest returned null!"); } else { ret = r2.GetReference(); Debug.Assert(stable_reference.Equals(ret .ConvertToStableRepresentation(doc)), "expected same reference from " + "FindReferencesWithContextByDirection and " + "ReferenceIntersector"); } t.RollBack(); } #endif // _2012 #endregion // Revit 2012 Options opt = doc.Application.Create .NewGeometryOptions(); opt.ComputeReferences = true; GeometryElement geo = e.get_Geometry(opt); foreach (GeometryObject obj in geo) { GeometryInstance inst = obj as GeometryInstance; if (null != inst) { geo = inst.GetSymbolGeometry(); break; } } Solid solid = geo.OfType <Solid>() .First <Solid>(sol => null != sol); double z = double.MinValue; foreach (Face f in solid.Faces) { BoundingBoxUV b = f.GetBoundingBox(); UV p = b.Min; UV q = b.Max; UV midparam = p + 0.5 * (q - p); XYZ midpoint = f.Evaluate(midparam); XYZ normal = f.ComputeNormal(midparam); if (Util.PointsUpwards(normal)) { if (midpoint.Z > z) { z = midpoint.Z; ret = f.Reference; } } } return(ret); }
/// <summary> /// Creates a SweptSolid, Brep, SolidModel or SurfaceModel product definition shape representation, based on the geometry and IFC version. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="categoryId">The category id.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="bodyExporterOptions">The body exporter options.</param> /// <param name="extraReps">Extra representations (e.g. Axis, Boundary). May be null.</param> /// <param name="extrusionCreationData">The extrusion creation data.</param> /// <param name="bodyData">The body data.</param> /// <returns>The handle.</returns> public static IFCAnyHandle CreateAppropriateProductDefinitionShape(ExporterIFC exporterIFC, Element element, ElementId categoryId, GeometryElement geometryElement, BodyExporterOptions bodyExporterOptions, IList <IFCAnyHandle> extraReps, IFCExtrusionCreationData extrusionCreationData, out BodyData bodyData) { bodyData = null; SolidMeshGeometryInfo info = null; IList <GeometryObject> geometryList = new List <GeometryObject>(); if (!ExporterCacheManager.ExportOptionsCache.ExportAs2x2) { info = GeometryUtil.GetSplitSolidMeshGeometry(geometryElement, Transform.Identity); IList <Mesh> meshes = info.GetMeshes(); if (meshes.Count == 0) { IList <Solid> solidList = info.GetSolids(); foreach (Solid solid in solidList) { geometryList.Add(solid); } } } if (geometryList.Count == 0) { geometryList.Add(geometryElement); } else { bodyExporterOptions.TryToExportAsExtrusion = true; } bodyData = BodyExporter.ExportBody(exporterIFC, element, categoryId, ElementId.InvalidElementId, geometryList, bodyExporterOptions, extrusionCreationData); IFCAnyHandle bodyRep = bodyData.RepresentationHnd; List <IFCAnyHandle> bodyReps = new List <IFCAnyHandle>(); if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep)) { if (extrusionCreationData != null) { extrusionCreationData.ClearOpenings(); } } else { bodyReps.Add(bodyRep); } if (extraReps != null) { foreach (IFCAnyHandle hnd in extraReps) { bodyReps.Add(hnd); } } Transform boundingBoxTrf = (bodyData.OffsetTransform != null) ? bodyData.OffsetTransform.Inverse : Transform.Identity; IFCAnyHandle boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, geometryElement, boundingBoxTrf); if (boundingBoxRep != null) { bodyReps.Add(boundingBoxRep); } if (bodyReps.Count == 0) { return(null); } return(IFCInstanceExporter.CreateProductDefinitionShape(exporterIFC.GetFile(), null, null, bodyReps)); }
public void QTO_2_PlaceHoldersFromDWFMarkups( Document doc, string activityId) { View activeView = doc.ActiveView; if (!(activeView is ViewSheet)) { TaskDialog.Show("QTO", "The current view must be a Sheet View with DWF markups"); return; } ViewSheet vs = activeView as ViewSheet; Viewport vp = doc.GetElement( vs.GetAllViewports().First()) as Viewport; View plan = doc.GetElement(vp.ViewId) as View; int scale = vp.Parameters.Cast <Parameter>() .First(x => x.Id.IntegerValue.Equals( (int)BuiltInParameter.VIEW_SCALE)) .AsInteger(); IEnumerable <Element> dwfMarkups = new FilteredElementCollector(doc) .OfClass(typeof(ImportInstance)) .WhereElementIsNotElementType() .Where(x => x.Name.StartsWith("Markup") && x.OwnerViewId.IntegerValue.Equals( activeView.Id.IntegerValue)); using (TransactionGroup tg = new TransactionGroup(doc)) { tg.Start("DWF markups placeholders"); using (Transaction t = new Transaction(doc)) { t.Start("DWF Transfer"); plan.Parameters.Cast <Parameter>() .First(x => x.Id.IntegerValue.Equals( (int)BuiltInParameter.VIEWER_CROP_REGION)) .Set(1); XYZ VC = (plan.CropBox.Min + plan.CropBox.Max) / 2; XYZ BC = vp.GetBoxCenter(); t.RollBack(); foreach (Element e in dwfMarkups) { GeometryElement GeoElem = e.get_Geometry(new Options()); GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First(); GeometryElement gei = gi.GetSymbolGeometry(); IList <GeometryObject> gos = new List <GeometryObject>(); if (gei.Cast <GeometryObject>().Count(x => x is Arc) > 0) { continue; } foreach (GeometryObject go in gei) { XYZ med = new XYZ(); if (go is PolyLine) { PolyLine pl = go as PolyLine; XYZ min = new XYZ(pl.GetCoordinates().Min(p => p.X), pl.GetCoordinates().Min(p => p.Y), pl.GetCoordinates().Min(p => p.Z)); XYZ max = new XYZ(pl.GetCoordinates().Max(p => p.X), pl.GetCoordinates().Max(p => p.Y), pl.GetCoordinates().Max(p => p.Z)); med = (min + max) / 2; } med = med - BC; // Convert DWF sheet coordinates into model coordinates XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0); } } t.Start("DWF Transfer"); foreach (Element e in dwfMarkups) { GeometryElement GeoElem = e.get_Geometry(new Options()); GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First(); GeometryElement gei = gi.GetSymbolGeometry(); IList <GeometryObject> gos = new List <GeometryObject>(); if (gei.Cast <GeometryObject>().Count(x => x is Arc) == 0) { continue; } foreach (GeometryObject go in gei) { if (go is Arc) { Curve c = go as Curve; XYZ med = c.Evaluate(0.5, true); med = med - BC; XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0); // Warning CS0618: // Autodesk.Revit.Creation.ItemFactoryBase.NewTextNote( // View, XYZ, XYZ, XYZ, double, TextAlignFlags, string) // is obsolete: // This method is deprecated in Revit 2016. // Please use one of the TextNote.Create methods instead. //doc.Create.NewTextNote( plan, // a, // XYZ.BasisX, // XYZ.BasisY, // MMtoFeet( 5 ), // TextAlignFlags.TEF_ALIGN_CENTER, // activityId ); ElementId textTypeId = new FilteredElementCollector(doc) .OfClass(typeof(TextNoteType)) .FirstElementId(); TextNote.Create(doc, plan.Id, a, activityId, textTypeId); } } t.Commit(); } } tg.Assimilate(); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; double scale = 304.8; #region TEST ////cut line endpoints //XYZ v1 = new XYZ(0, 2000, 0)/scale; //XYZ v2 = new XYZ(6018, 2000, 0) / scale; ////rhino cut line endpoints // rg.Point3d rv0 = new rg.Point3d(0, 2000, 0); // rg.Point3d rv1 = new rg.Point3d(6018, 2000, 0); //rg.Point3d rv2 = new rg.Point3d(0, 2000, 1); ////rhino cut plane //rg.Plane cutPlane = new rg.Plane(rv0, rv1, rv2); ////wip points //rg.Point3d rv3 = new rg.Point3d(857, 203, 4597); //rg.Point3d rv4 = new rg.Point3d(857, 6221, 4597); //rg.Point3d rv5 = new rg.Point3d(9818, 6221, 4597); // //wip plane // rg.Plane rhinoPlane = new rg.Plane(rv3, rv4, rv5); // rg.Line intLine; // var result = rg.Intersect.Intersection.PlanePlane(cutPlane, rhinoPlane, out intLine); // using (Transaction t = new Transaction(doc, "Project Line")) // { // t.Start(); // SketchPlane sp = SketchPlane.Create(doc, RhinoToRevitPlane(cutPlane)); // doc.Create.NewModelCurve(RhinoToRevitLine(intLine), sp); // t.Commit(); // } // TaskDialog.Show("r", "Done"); #endregion #region Revit // SELECT THE LINE TO PROJECT AND CONSTRUCT THE PLANE TO INTERSECT THE MESH Reference lineToProject = uidoc.Selection.PickObject(ObjectType.Element, "Select cut Line"); Element lineElement = doc.GetElement(lineToProject); CurveElement curveLine = lineElement as CurveElement; LocationCurve lineLocation = lineElement.Location as LocationCurve; Line line = lineLocation.Curve as Line; rg.Line rhinoCutLine = new rg.Line(RevitToRhinoPoint(line.GetEndPoint(0)), RevitToRhinoPoint(line.GetEndPoint(1))); XYZ perpDir = line.Direction.CrossProduct(XYZ.BasisZ).Normalize(); Plane cutPlane = Plane.CreateByNormalAndOrigin(perpDir, line.GetEndPoint(0)); // GET THE MESH GEOMETRY Reference meshRef = uidoc.Selection.PickObject(ObjectType.Element, "Select Mesh"); Element e = doc.GetElement(meshRef); Options opt = new Options(); opt.ComputeReferences = true; opt.IncludeNonVisibleObjects = false; opt.View = doc.ActiveView; GeometryElement geomElem = e.get_Geometry(opt); Mesh geomMesh = null; foreach (GeometryObject geomObj in geomElem) { GeometryInstance gi = geomObj as GeometryInstance; if (gi != null) { foreach (GeometryObject element in gi.GetInstanceGeometry()) { geomMesh = element as Mesh; } } else { geomMesh = geomObj as Mesh; } } int counter = 0; using (Transaction t = new Transaction(doc, "Project Line")) { t.Start(); SketchPlane sp = SketchPlane.Create(doc, cutPlane); XYZ spOrigin = sp.GetPlane().Origin; Debug.Write($"Sketch plane origin: {spOrigin}\n"); XYZ spNormal = sp.GetPlane().Normal; Debug.Write($"Sketch plane normal: {spNormal}\n"); Line spX = Line.CreateBound(spOrigin, spOrigin + XYZ.BasisZ * 100); Debug.Write($"line start: {spX.GetEndParameter(0)}\n"); Debug.Write($"line end: {spX.GetEndParameter(1)}\n"); ModelCurve mc = doc.Create.NewModelCurve(spX, sp); Debug.Write($"mc: {mc.Id}\n"); List <XYZ> intersectionPoints = new List <XYZ>(); for (int i = 0; i < geomMesh.NumTriangles; i++) { MeshTriangle triangle = geomMesh.get_Triangle(i); XYZ vertex1 = triangle.get_Vertex(0); XYZ vertex2 = triangle.get_Vertex(1); XYZ vertex3 = triangle.get_Vertex(2); rg.Point3d rhinoVertex1 = RevitToRhinoPoint(vertex1); rg.Point3d rhinoVertex2 = RevitToRhinoPoint(vertex2); rg.Point3d rhinoVertex3 = RevitToRhinoPoint(vertex3); List <rg.Line> rhinoEdges = new List <rg.Line> { new rg.Line(rhinoVertex1, rhinoVertex2), new rg.Line(rhinoVertex1, rhinoVertex2), new rg.Line(rhinoVertex1, rhinoVertex2) }; XYZ[] pts = new XYZ[2]; int ptscount = 0; foreach (rg.Line edge in rhinoEdges) { double a = 0; double b = 0; bool result = rg.Intersect.Intersection.LineLine(edge, rhinoCutLine, out a, out b); if (result) { intersectionPoints.Add(RhinoToRevitPoint(edge.PointAt(a))); pts[ptscount] = RhinoToRevitPoint(edge.PointAt(a)); ptscount = 1; counter++; } } if (pts[0] != null) { try { Line temp = Line.CreateBound(pts[0], pts[0] + XYZ.BasisZ * 100); //Line li = Line.CreateBound(pts[0], new XYZ(pts[0].X, pts[0].Y, pts[0].Z +100)); doc.Create.NewModelCurve(temp, sp); } catch { } } } t.Commit(); } TaskDialog.Show("Intersections found", counter.ToString()); #endregion return(Result.Succeeded); }
public static Dictionary <double, int[]> IntersectionPoint(Document doc, Reference refBeam, IList <Reference> refLines) { Element ele = doc.GetElement(refBeam.ElementId); Face webFace = null; Options geomOptions = pickOptions(doc); GeometryElement beamGeom = ele.get_Geometry(geomOptions); Transform instTransform = null; Dictionary <int, Face> areas = new Dictionary <int, Face>(); foreach (GeometryObject obj in beamGeom) { Solid geomSolid = obj as Solid; if (null != geomSolid) { foreach (Face geomFace in geomSolid.Faces) { try { areas.Add((int)geomFace.Area, geomFace); } catch { } } } else { Helpers.GetSymbolGeometry(obj, areas, out instTransform); } } int total = areas.Keys.Count; int maxArea = areas.Keys.Max(); webFace = areas[maxArea]; XYZ location = null; XYZ beamDirection = null; Helpers.BeamStartUVPoint(ele, webFace, out location, out beamDirection); XYZ faceOrigin = null; // the element does not have available solid geometries. Need to use its geometry instance first and transform the point to the project coordinates. if (beamGeom.Count() == 1) { XYZ transformedPoint = instTransform.OfPoint(location); //LocationCurve lc = ele.Location as LocationCurve; //XYZ direction = lc.Curve.GetEndPoint(0) - lc.Curve.GetEndPoint(1); faceOrigin = new XYZ(transformedPoint.X, transformedPoint.Y, 0); } else { faceOrigin = new XYZ(location.X, location.Y, 0); } LocationCurve beamLine = ele.Location as LocationCurve; Line bl = beamLine.Curve as Line; XYZ origin = bl.GetEndPoint(0); /* * XYZ originProjected = new XYZ (origin.X, origin.Y, 0); */ List <double> distances = new List <double>(); Dictionary <double, int[]> penoDistAndSize = new Dictionary <double, int[]>(); foreach (Reference r in refLines) { Element refLine = doc.GetElement(r.ElementId); LocationCurve lineCrv = refLine.Location as LocationCurve; Line l = lineCrv.Curve as Line; try { //XYZ intersectionPoint = Intersection(bl, l); XYZ intersectionPoint = GetIntersection(bl, l); XYZ intersectionPointProjected = new XYZ(intersectionPoint.X, intersectionPoint.Y, 0); double d = intersectionPointProjected.DistanceTo(faceOrigin); distances.Add(d * 304.8); int penoWidth = Int16.Parse(GetLinestyle(doc, r)[0]); int penoDepth = Int16.Parse(GetLinestyle(doc, r)[1]); penoDistAndSize.Add(d * 304.8, new int[] { penoWidth, penoDepth }); } catch { //do nothing } } return(penoDistAndSize); }//close method
}//close method //public static Dictionary<double, int[]> IntersectionLinePlane(Document doc, Reference refBeam, IList<Reference> refRefPlane) public static List <Tuple <double, int[], ReferencePlane> > IntersectionLinePlane(Document doc, Reference refBeam, IList <Reference> refRefPlane) { Element ele = doc.GetElement(refBeam.ElementId); Face webFace = null; Options geomOptions = pickOptions(doc); GeometryElement beamGeom = ele.get_Geometry(geomOptions); Transform instTransform = null; Dictionary <int, Face> areas = new Dictionary <int, Face>(); foreach (GeometryObject obj in beamGeom) { Solid geomSolid = obj as Solid; if (null != geomSolid) { Debug.WriteLine("Geom Solid not null"); foreach (Face geomFace in geomSolid.Faces) { if (!areas.ContainsKey((int)geomFace.Area)) { areas.Add((int)geomFace.Area, geomFace); } } } else { Helpers.GetSymbolGeometry(obj, areas, out instTransform); Debug.WriteLine("Geom Solid null. Get symbol geometry"); } } int total = areas.Keys.Count; int maxArea = areas.Keys.Max(); webFace = areas[maxArea]; XYZ location = null; XYZ beamDirection = null; Helpers.BeamStartUVPoint(ele, webFace, out location, out beamDirection); XYZ faceOrigin = null; // the element does not have available solid geometries. Need to use its geometry instance first and transform the point to the project coordinates. if (beamGeom.Count() == 1) { Debug.WriteLine("the element does not have available solid geometries"); XYZ transformedPoint = instTransform.OfPoint(location); //LocationCurve lc = ele.Location as LocationCurve; //XYZ direction = lc.Curve.GetEndPoint(0) - lc.Curve.GetEndPoint(1); faceOrigin = new XYZ(transformedPoint.X, transformedPoint.Y, 0); } else { faceOrigin = new XYZ(location.X, location.Y, 0); Debug.WriteLine($"Face origin: {faceOrigin.X},{faceOrigin.Y},0"); } LocationCurve beamLine = ele.Location as LocationCurve; Line bl = beamLine.Curve as Line; Line projectedBl = Line.CreateBound(new XYZ(bl.GetEndPoint(0).X, bl.GetEndPoint(0).Y, 0), new XYZ(bl.GetEndPoint(1).X, bl.GetEndPoint(1).Y, 0)); XYZ origin = bl.GetEndPoint(0); /* * XYZ originProjected = new XYZ (origin.X, origin.Y, 0); */ List <double> distances = new List <double>(); // Dictionary<double, int[]> penoDistAndSize = new Dictionary<double, int[]>(); List <Tuple <double, int[], ReferencePlane> > penoDistAndSize = new List <Tuple <double, int[], ReferencePlane> >(); foreach (Reference r in refRefPlane) { ReferencePlane refPlane = doc.GetElement(r.ElementId) as ReferencePlane; //projected to z=0 Line refPlaneProjectedLine = Line.CreateBound(new XYZ(refPlane.BubbleEnd.X, refPlane.BubbleEnd.Y, 0), new XYZ(refPlane.FreeEnd.X, refPlane.FreeEnd.Y, 0)); XYZ intersectionPoint = null; try { //XYZ intersectionPoint = Intersection(bl, l); intersectionPoint = GetIntersection(projectedBl, refPlaneProjectedLine); double d = intersectionPoint.DistanceTo(faceOrigin); distances.Add(d * 304.8); int penoWidth = Int16.Parse(GetReferencePlaneSubCategory(doc, refPlane)[0]); int penoDepth = Int16.Parse(GetReferencePlaneSubCategory(doc, refPlane)[1]); //penoDistAndSize.Add(d * 304.8, new int[] { penoWidth, penoDepth }); DICTIONARY! penoDistAndSize.Add(new Tuple <double, int[], ReferencePlane> (d * 304.8, new int[] { penoWidth, penoDepth }, refPlane)); } catch { if (intersectionPoint == null) { //TaskDialog.Show("Error", "Intersection point not found"); } else { TaskDialog.Show("Error", "Reference Plane subcategory error"); } } } return(penoDistAndSize); }//close method
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; List <Element> a = new List <Element>(); if (!Util.GetSelectedElementsOrAll(a, uidoc, typeof(FamilyInstance))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some family instances." : "No family instances found."; return(Result.Failed); } FamilyInstance inst = a[0] as FamilyInstance; // Here are two ways to traverse the nested instance geometry. // The first way can get the right position, but can't get the right structure. // The second way can get the right structure, but can't get the right position. // What I want is the right structure and right position. // First way: // In the current project project1.rvt, I can get myFamily3 instance via API, // the class is Autodesk.Revit.Elements.FamilyInstance. // Then i try to get its geometry: Options opt = app.Application.Create.NewGeometryOptions(); GeometryElement geoElement = inst.get_Geometry(opt); //GeometryObjectArray a1 = geoElement.Objects; // 2012 //int n = a1.Size; // 2012 int n = geoElement.Count <GeometryObject>(); // 2013 Debug.Print( "Family instance geometry has {0} geometry object{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); int i = 0; //foreach( GeometryObject o1 in a1 ) // 2012 foreach (GeometryObject o1 in geoElement) // 2013 { GeometryInstance geoInstance = o1 as GeometryInstance; if (null != geoInstance) { // geometry includes one instance, so get its geometry: GeometryElement symbolGeo = geoInstance.SymbolGeometry; //GeometryObjectArray a2 = symbolGeo.Objects; // 2012 //foreach( GeometryObject o2 in a2 ) // 2012 // the symbol geometry contains five solids. // how can I find out which solid belongs to which column? // how to relate the solid to the family instance? foreach (GeometryObject o2 in symbolGeo) { Solid s = o2 as Solid; if (null != s && 0 < s.Edges.Size) { List <XYZ> vertices = new List <XYZ>(); GetVertices(vertices, s); n = vertices.Count; Debug.Print("Solid {0} has {1} vertices{2} {3}", i++, n, Util.DotOrColon(n), Util.PointArrayString(vertices)); } } } } // In the Revit 2009 API, we can use // FamilyInstance.Symbol.Family.Components // to obtain the nested family instances // within the top level family instance. // In the Revit 2010 API, this property has been // removed, since we can iterate through the elements // of a family just like any other document; // cf. What's New in the RevitAPI.chm: #if REQUIRES_REVIT_2009_API ElementSet components = inst.Symbol.Family.Components; n = components.Size; #endif // REQUIRES_REVIT_2009_API Document fdoc = doc.EditFamily(inst.Symbol.Family); #if REQUIRES_REVIT_2010_API List <Element> components = new List <Element>(); fdoc.get_Elements(typeof(FamilyInstance), components); n = components.Count; #endif // REQUIRES_REVIT_2010_API FilteredElementCollector collector = new FilteredElementCollector(fdoc); collector.OfClass(typeof(FamilyInstance)); IList <Element> components = collector.ToElements(); Debug.Print( "Family instance symbol family has {0} component{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); foreach (Element e in components) { // there are 3 FamilyInstance: Column, myFamily1, myFamily2 // then we can loop myFamily1, myFamily2 also. // then get all the Column geometry // But all the Column's position is the same, // because the geometry is defined by the Symbol. // Not the actually position in project1.rvt LocationPoint lp = e.Location as LocationPoint; Debug.Print("{0} at {1}", Util.ElementDescription(e), Util.PointString(lp.Point)); } return(Result.Failed); }
public void Execute(UIApplication uiapp) { try { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; using (Transaction tx = new Transaction(doc)) { tx.Start("EE06_PlaceFamily"); FamilySymbol myFamilySymbol_Platform = myMethod_CheckExistanceOfFamily(doc, myString_Family_Platform, myString_Type_Platform); if (myFamilySymbol_Platform == null) { return; } FamilySymbol myFamilySymbol_Chair = null; if (myBool_AlsoPlaceAChair) { myFamilySymbol_Chair = myMethod_CheckExistanceOfFamily(doc, myString_Family_Chair, myString_Type_Chair); if (myFamilySymbol_Chair == null) { return; } } Reference pickedRef = null; try { pickedRef = uiapp.ActiveUIDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.PointOnElement, "Please select a Face"); } #region catch and finally catch (Exception ex) { } finally { } #endregion if (pickedRef == null) { return; } FamilyInstance myFamilyInstance_New = doc.Create.NewFamilyInstance(XYZ.Zero, myFamilySymbol_Platform, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); doc.Regenerate(); IList <ElementId> placePointIds_1338 = AdaptiveComponentInstanceUtils.GetInstancePointElementRefIds(myFamilyInstance_New); ReferencePoint myReferencePoint_Centre = doc.GetElement(placePointIds_1338.First()) as ReferencePoint; UV point_in_3d_UV = pickedRef.UVPoint; PointOnFace myPointOnFace = uidoc.Application.Application.Create.NewPointOnFace(pickedRef, point_in_3d_UV); myReferencePoint_Centre.SetPointElementReference(myPointOnFace); doc.Regenerate(); myReferencePoint_Centre.get_Parameter(BuiltInParameter.POINT_ELEMENT_DRIVEN).Set(0); ElementTransformUtils.MoveElement(doc, myReferencePoint_Centre.Id, myReferencePoint_Centre.GetCoordinateSystem().OfPoint(new XYZ(0, 0, 0.1)) - myReferencePoint_Centre.Position); if (myFamilySymbol_Chair != null) { GeometryElement myGeomeryElement = myFamilyInstance_New.get_Geometry(new Options() { ComputeReferences = true }); GeometryInstance myGeometryInstance = myGeomeryElement.First() as GeometryInstance; GeometryElement myGeomeryElementSymbol = myGeometryInstance.GetSymbolGeometry(); GeometryObject myGeometryObject = myGeomeryElementSymbol.Where(x => (x as Solid) != null).First(); PlanarFace myPlanarFace = ((Solid)myGeometryObject).Faces.get_Item(0) as PlanarFace; doc.Create.NewFamilyInstance(myPlanarFace, myReferencePoint_Centre.Position, myReferencePoint_Centre.GetCoordinateSystem().OfVector(new XYZ(1, 0, 0)), myFamilySymbol_Chair); } tx.Commit(); uidoc.Selection.SetElementIds(new List <ElementId>() { myReferencePoint_Centre.Id }); myWindow1.mySelectMethod(myIntUPDown); myIntUPDown.Value = myFamilyInstance_New.Id.IntegerValue; } myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisZ, false); myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisX, false); myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisY, true); } #region catch and finally catch (Exception ex) { _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE06_PlaceFamily" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true); } finally { } #endregion }
/// <summary> /// Exports a beam to IFC beam if it has an axis representation and only one Solid as its geometry, ideally as an extrusion, potentially with clippings and openings. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element to be exported.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <param name="dontExport">An output value that says that the element shouldn't be exported at all.</param> /// <returns>The created handle.</returns> /// <remarks>In the original implementation, the ExportBeam function would export each beam as its own individual geometry (that is, not use representation maps). /// For non-standard beams, this could result in massive IFC files. Now, we use the ExportBeamAsStandardElement function and limit its scope, and instead /// resort to the standard FamilyInstanceExporter.ExportFamilyInstanceAsMappedItem for more complicated objects categorized as beams. This has the following pros and cons: /// Pro: possiblity for massively reduced file sizes for files containing repeated complex beam families /// Con: some beams that may have had an "Axis" representation before will no longer have them, although this possibility is minimized. /// Con: some beams that have 1 Solid and an axis, but that Solid will be heavily faceted, won't be helped by this improvement. /// It is intended that we phase out this routine entirely and instead teach ExportFamilyInstanceAsMappedItem how to sometimes export the Axis representation for beams.</remarks> public static IFCAnyHandle ExportBeamAsStandardElement(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper, out bool dontExport) { dontExport = true; IList <GeometryObject> geomObjects = BeamGeometryToExport(exporterIFC, element, geometryElement, out dontExport); if (dontExport) { return(null); } IFCAnyHandle beam = null; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction transaction = new IFCTransaction(file)) { BeamAxisInfo axisInfo = GetBeamAxisTransform(element); bool canExportAxis = (axisInfo != null); Curve curve = canExportAxis ? axisInfo.Axis : null; XYZ beamDirection = canExportAxis ? axisInfo.AxisDirection : null; Transform orientTrf = canExportAxis ? axisInfo.LCSAsTransform : null; using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element, null, orientTrf)) { IFCAnyHandle localPlacement = setter.LocalPlacement; using (IFCExtrusionCreationData extrusionCreationData = new IFCExtrusionCreationData()) { extrusionCreationData.SetLocalPlacement(localPlacement); if (canExportAxis && (orientTrf.BasisX != null)) { extrusionCreationData.CustomAxis = beamDirection; extrusionCreationData.PossibleExtrusionAxes = IFCExtrusionAxes.TryCustom; } else { extrusionCreationData.PossibleExtrusionAxes = IFCExtrusionAxes.TryXY; } ElementId catId = CategoryUtil.GetSafeCategoryId(element); // There may be an offset to make the local coordinate system // be near the origin. This offset will be used to move the axis to the new LCS. Transform offsetTransform = null; // The list of materials in the solids or meshes. ICollection <ElementId> materialIds = null; // The representation handle generated from one of the methods below. BeamBodyAsExtrusionInfo extrusionInfo = CreateBeamGeometryAsExtrusion(exporterIFC, element, catId, geomObjects, axisInfo); if (extrusionInfo != null && extrusionInfo.DontExport) { dontExport = true; return(null); } IFCAnyHandle repHnd = (extrusionInfo != null) ? extrusionInfo.RepresentationHandle : null; if (!IFCAnyHandleUtil.IsNullOrHasNoValue(repHnd)) { materialIds = extrusionInfo.Materials; extrusionCreationData.Slope = extrusionInfo.Slope; } else { // Here is where we limit the scope of how complex a case we will still try to export as a standard element. // This is explicitly added so that many curved beams that can be represented by a reasonable facetation because of the // SweptSolidExporter can still have an Axis representation. BodyData bodyData = null; BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow); if (geomObjects != null && geomObjects.Count == 1 && geomObjects[0] is Solid) { bodyData = BodyExporter.ExportBody(exporterIFC, element, catId, ElementId.InvalidElementId, geomObjects[0], bodyExporterOptions, extrusionCreationData); repHnd = bodyData.RepresentationHnd; materialIds = bodyData.MaterialIds; offsetTransform = bodyData.OffsetTransform; } } if (IFCAnyHandleUtil.IsNullOrHasNoValue(repHnd)) { extrusionCreationData.ClearOpenings(); return(null); } IList <IFCAnyHandle> representations = new List <IFCAnyHandle>(); IFCAnyHandle axisRep = CreateBeamAxis(exporterIFC, element, catId, axisInfo, offsetTransform); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(axisRep)) { representations.Add(axisRep); } representations.Add(repHnd); Transform boundingBoxTrf = (offsetTransform == null) ? Transform.Identity : offsetTransform.Inverse; IFCAnyHandle boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, geometryElement, boundingBoxTrf); if (boundingBoxRep != null) { representations.Add(boundingBoxRep); } IFCAnyHandle prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, representations); string instanceGUID = GUIDUtil.CreateGUID(element); string instanceName = NamingUtil.GetNameOverride(element, NamingUtil.GetIFCName(element)); string instanceDescription = NamingUtil.GetDescriptionOverride(element, null); string instanceObjectType = NamingUtil.GetObjectTypeOverride(element, NamingUtil.CreateIFCObjectName(exporterIFC, element)); string instanceTag = NamingUtil.GetTagOverride(element, NamingUtil.CreateIFCElementId(element)); string preDefinedType = "BEAM"; // Default predefined type for Beam preDefinedType = IFCValidateEntry.GetValidIFCType(element, preDefinedType); beam = IFCInstanceExporter.CreateBeam(file, instanceGUID, ExporterCacheManager.OwnerHistoryHandle, instanceName, instanceDescription, instanceObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, instanceTag, preDefinedType); productWrapper.AddElement(element, beam, setter, extrusionCreationData, true); OpeningUtil.CreateOpeningsIfNecessary(beam, element, extrusionCreationData, offsetTransform, exporterIFC, extrusionCreationData.GetLocalPlacement(), setter, productWrapper); FamilyTypeInfo typeInfo = new FamilyTypeInfo(); typeInfo.ScaledDepth = extrusionCreationData.ScaledLength; typeInfo.ScaledArea = extrusionCreationData.ScaledArea; typeInfo.ScaledInnerPerimeter = extrusionCreationData.ScaledInnerPerimeter; typeInfo.ScaledOuterPerimeter = extrusionCreationData.ScaledOuterPerimeter; PropertyUtil.CreateBeamColumnBaseQuantities(exporterIFC, beam, element, typeInfo, null); if (materialIds.Count != 0) { CategoryUtil.CreateMaterialAssociations(exporterIFC, beam, materialIds); } // Register the beam's IFC handle for later use by truss and beam system export. ExporterCacheManager.ElementToHandleCache.Register(element.Id, beam); } } transaction.Commit(); return(beam); } }
/// <summary> /// Exports a gutter element. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void ExportGutter(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(setter.LocalPlacement); ElementId categoryId = CategoryUtil.GetSafeCategoryId(element); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(); IFCAnyHandle bodyRep = BodyExporter.ExportBody(exporterIFC, element, categoryId, ElementId.InvalidElementId, geometryElement, bodyExporterOptions, ecData).RepresentationHnd; if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep)) { if (ecData != null) { ecData.ClearOpenings(); } return; } IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string originalTag = NamingUtil.CreateIFCElementId(element); // In Revit, we don't have a corresponding type, so we create one for every gutter. IFCAnyHandle origin = ExporterUtil.CreateAxis2Placement3D(file); IFCAnyHandle repMap3dHnd = IFCInstanceExporter.CreateRepresentationMap(file, origin, bodyRep); List <IFCAnyHandle> repMapList = new List <IFCAnyHandle>(); repMapList.Add(repMap3dHnd); string elementTypeName = NamingUtil.CreateIFCObjectName(exporterIFC, element); string typeGuid = GUIDUtil.CreateSubElementGUID(element, (int)IFCHostedSweepSubElements.PipeSegmentType); IFCAnyHandle style = IFCInstanceExporter.CreatePipeSegmentType(file, typeGuid, ownerHistory, elementTypeName, null, null, null, repMapList, originalTag, elementTypeName, IFCPipeSegmentType.Gutter); List <IFCAnyHandle> representationMaps = GeometryUtil.GetRepresentationMaps(style); IFCAnyHandle mappedItem = ExporterUtil.CreateDefaultMappedItem(file, representationMaps[0]); ISet <IFCAnyHandle> representations = new HashSet <IFCAnyHandle>(); representations.Add(mappedItem); IFCAnyHandle bodyMappedItemRep = RepresentationUtil.CreateBodyMappedItemRep(exporterIFC, element, categoryId, exporterIFC.Get3DContextHandle("Body"), representations); if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyMappedItemRep)) { return; } List <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>(); shapeReps.Add(bodyMappedItemRep); IFCAnyHandle boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, geometryElement, Transform.Identity); if (boundingBoxRep != null) { shapeReps.Add(boundingBoxRep); } IFCAnyHandle prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps); IFCAnyHandle localPlacementToUse; ElementId roomId = setter.UpdateRoomRelativeCoordinates(element, out localPlacementToUse); if (roomId == ElementId.InvalidElementId) { localPlacementToUse = ecData.GetLocalPlacement(); } string guid = GUIDUtil.CreateGUID(element); string name = NamingUtil.GetNameOverride(element, NamingUtil.GetIFCName(element)); string description = NamingUtil.GetDescriptionOverride(element, null); string objectType = NamingUtil.GetObjectTypeOverride(element, elementTypeName); string tag = NamingUtil.GetTagOverride(element, originalTag); IFCAnyHandle elemHnd = IFCInstanceExporter.CreateFlowSegment(file, guid, ownerHistory, name, description, objectType, localPlacementToUse, prodRep, tag); bool containedInSpace = (roomId != ElementId.InvalidElementId); productWrapper.AddElement(element, elemHnd, setter.LevelInfo, ecData, !containedInSpace); if (containedInSpace) { ExporterCacheManager.SpaceInfoCache.RelateToSpace(roomId, elemHnd); } // Associate segment with type. ExporterCacheManager.TypeRelationsCache.Add(style, elemHnd); OpeningUtil.CreateOpeningsIfNecessary(elemHnd, element, ecData, null, exporterIFC, localPlacementToUse, setter, productWrapper); } tr.Commit(); } } }
/// <summary> /// Exports a geometry element to boundary representation. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="exportBoundaryRep">True if to export boundary representation.</param> /// <param name="exportAsFacetation">True if to export the geometry as facetation.</param> /// <param name="bodyRep">Body representation.</param> /// <param name="boundaryRep">Boundary representation.</param> /// <returns>True if success, false if fail.</returns> public static bool ExportSurface(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, bool exportBoundaryRep, bool exportAsFacetation, ref IFCAnyHandle bodyRep, ref IFCAnyHandle boundaryRep) { if (geometryElement == null) { return(false); } IFCGeometryInfo ifcGeomInfo = null; Plane plane = GeometryUtil.CreateDefaultPlane(); XYZ projDir = new XYZ(0, 0, 1); double eps = element.Document.Application.VertexTolerance * exporterIFC.LinearScale; ifcGeomInfo = IFCGeometryInfo.CreateFaceGeometryInfo(exporterIFC, plane, projDir, eps, exportBoundaryRep); ExporterIFCUtils.CollectGeometryInfo(exporterIFC, ifcGeomInfo, geometryElement, XYZ.Zero, true); IFCFile file = exporterIFC.GetFile(); HashSet <IFCAnyHandle> faceSets = new HashSet <IFCAnyHandle>(); IList <ICollection <IFCAnyHandle> > faceList = ifcGeomInfo.GetFaces(); foreach (ICollection <IFCAnyHandle> faces in faceList) { // no faces, don't complain. if (faces.Count == 0) { continue; } HashSet <IFCAnyHandle> faceSet = new HashSet <IFCAnyHandle>(faces); faceSets.Add(IFCInstanceExporter.CreateConnectedFaceSet(file, faceSet)); } if (faceSets.Count == 0) { return(false); } IFCAnyHandle surface = IFCInstanceExporter.CreateFaceBasedSurfaceModel(file, faceSets); IList <IFCAnyHandle> surfaceItems = new List <IFCAnyHandle>(); surfaceItems.Add(surface); ElementId catId = CategoryUtil.GetSafeCategoryId(element); bodyRep = RepresentationUtil.CreateSurfaceRep(exporterIFC, element, catId, exporterIFC.Get3DContextHandle("Body"), surfaceItems, exportAsFacetation, bodyRep); if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep)) { return(false); } ICollection <IFCAnyHandle> boudaryRepresentations = ifcGeomInfo.GetRepresentations(); if (exportBoundaryRep && boudaryRepresentations.Count > 1) { boundaryRep = RepresentationUtil.CreateBoundaryRep(exporterIFC, element, catId, exporterIFC.Get3DContextHandle("Body"), boudaryRepresentations, boundaryRep); } return(true); }
/// <summary> /// Exports a floor to IFC slab. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="floor"> /// The floor element. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="ifcEnumType"> /// The string value represents the IFC type. /// </param> /// <param name="productWrapper"> /// The IFCProductWrapper. /// </param> /// <returns> /// True if the floor is exported successfully, false otherwise. /// </returns> public static void ExportFloor(ExporterIFC exporterIFC, Floor floor, GeometryElement geometryElement, IFCProductWrapper productWrapper) { if (geometryElement == null) return; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (IFCTransformSetter transformSetter = IFCTransformSetter.Create()) { using (IFCPlacementSetter placementSetter = IFCPlacementSetter.Create(exporterIFC, floor)) { IFCAnyHandle localPlacement = placementSetter.GetPlacement(); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string ifcEnumType = CategoryUtil.GetIFCEnumTypeName(exporterIFC, floor); double scale = exporterIFC.LinearScale; ElementId catId = CategoryUtil.GetSafeCategoryId(floor); IList<IFCAnyHandle> reps = new List<IFCAnyHandle>(); IList<IList<CurveLoop>> extrusionLoops = new List<IList<CurveLoop>>(); IList<IFCExtrusionCreationData> loopExtraParams = new List<IFCExtrusionCreationData>(); Plane floorPlane = GeometryUtil.CreateDefaultPlane(); IList<IFCAnyHandle> localPlacements = new List<IFCAnyHandle>(); bool exportedAsExtrusion = ExporterIFCUtils.ExportSlabAsExtrusion(exporterIFC, floor, geometryElement, transformSetter, localPlacement, out localPlacements, out reps, out extrusionLoops, out loopExtraParams, floorPlane); // We will use the ExtrusionAnalyzer when it is ready. // XYZ extrusionDirection = { 0, 0, -1 }; // XYZ modelOrigin = { 0, 0, 0 }; // XYZ floorOrigin = floor.GetVerticalProjectionPoint(modelOrigin, FloorFace.Top); // XYZ floorDir = floor.GetNormalAtVerticalProjectionPoint(floorOrigin, FloorFace.Top); // Plane floorPlane(floorDir, floorOrigin); // ExtrusionAnalyzer floorExtrusion = // ExtrusionAnalyzer.Create(geometryElement, floorPlane, extrusionDirection); if (!exportedAsExtrusion) { IFCAnyHandle bodyRep = null; IList<GeometryObject> geomObjects = new List<GeometryObject>(); geomObjects.Add(geometryElement); bodyRep = BodyExporter.ExportBody(floor.Document.Application, exporterIFC, catId, geomObjects, true, null); if (bodyRep == null || !bodyRep.HasValue) { tr.Commit(); return; } IFCAnyHandle prodDefHnd = file.CreateProductDefinitionShape(bodyRep); if (!prodDefHnd.HasValue) return; reps.Add(prodDefHnd); } // Create the slab from either the extrusion or the BRep information. IFCLabel ifcGUID = IFCLabel.CreateGUID(floor); IList<IFCAnyHandle> slabHnds = new List<IFCAnyHandle>(); int numReps = reps.Count; for (int ii = 0; ii < numReps; ii++) { IFCLabel ifcName = NamingUtil.GetNameOverride(floor, NamingUtil.CreateIFCName(exporterIFC, ii == 0 ? -1 : ii + 1)); IFCLabel ifcDescription = NamingUtil.GetDescriptionOverride(floor, IFCLabel.Create()); IFCLabel ifcObjectType = NamingUtil.GetObjectTypeOverride(floor, exporterIFC.GetFamilyNameFromExportState()); IFCLabel ifcElemId = NamingUtil.CreateIFCElementId(floor); IFCLabel currentGUID = (ii == 0) ? ifcGUID : IFCLabel.CreateGUID(); IFCAnyHandle localPlacementHnd = exportedAsExtrusion ? localPlacements[ii] : localPlacement; IFCAnyHandle slabHnd = file.CreateSlab(currentGUID, ownerHistory, ifcName, ifcDescription, ifcObjectType, localPlacementHnd, ifcElemId, ifcEnumType, reps[ii]); if (!slabHnd.HasValue) return; slabHnds.Add(slabHnd); } for (int ii = 0; ii < numReps; ii++) { IFCExtrusionCreationData loopExtraParam = ii < loopExtraParams.Count ? loopExtraParams[ii] : null; productWrapper.AddElement(slabHnds[ii], placementSetter, loopExtraParam, true); } if (exportedAsExtrusion) ExporterIFCUtils.ExportExtrudedSlabOpenings(exporterIFC, floor, placementSetter, localPlacements[0], slabHnds, extrusionLoops, floorPlane, productWrapper); ExporterIFCUtils.CreateGenericElementPropertySet(exporterIFC, floor, productWrapper); ExporterIFCUtils.ExportHostObject(exporterIFC, floor, geometryElement, productWrapper); } } tr.Commit(); } }
/// <summary> /// Get geometry of family instances and show them in Revit views /// </summary> public void GetInstanceGeometry() { FilteredElementCollector instanceCollector = new FilteredElementCollector(RevitDoc); instanceCollector.OfClass(typeof(FamilyInstance)); // create views by different names ElementId View3DId = new ElementId(-1); IList <Element> elems = new FilteredElementCollector(RevitDoc).OfClass(typeof(ViewFamilyType)).ToElements(); foreach (Element e in elems) { ViewFamilyType v = e as ViewFamilyType; if (v != null && v.ViewFamily == ViewFamily.ThreeDimensional) { View3DId = e.Id; break; } } //View instanceView = RevitDoc.Create.NewView3D(new XYZ(1, 1, -1)); View3D instanceView = View3D.CreateIsometric(RevitDoc, View3DId); ViewOrientation3D instanceViewOrientation3D = new ViewOrientation3D(new XYZ(-30.8272352809007, -2.44391067967133, 18.1013736367246), new XYZ(0.577350269189626, 0.577350269189626, -0.577350269189626), new XYZ(0.408248290463863, 0.408248290463863, 0.816496580927726)); instanceView.SetOrientation(instanceViewOrientation3D); instanceView.SaveOrientation(); instanceView.Name = "InstanceGeometry"; //View originalView = RevitDoc.Create.NewView3D(new XYZ(0, 1, -1)); View3D originalView = View3D.CreateIsometric(RevitDoc, View3DId); ViewOrientation3D originalViewOrientation3D = new ViewOrientation3D(new XYZ(-19.0249866627872, -5.09536632799455, 20.7528292850478), new XYZ(0, 0.707106781186547, -0.707106781186547), new XYZ(0, 0.707106781186548, 0.707106781186548)); originalView.SetOrientation(originalViewOrientation3D); originalView.SaveOrientation(); originalView.Name = "OriginalGeometry"; //View transView = RevitDoc.Create.NewView3D(new XYZ(-1, 1, -1)); View3D transView = View3D.CreateIsometric(RevitDoc, View3DId); //ViewOrientation3D transViewOrientation3D = new ViewOrientation3D(new XYZ(-7.22273804467383, -2.44391067967133, 18.1013736367246), new XYZ(-0.577350269189626, 0.577350269189626, -0.577350269189626), new XYZ(-0.408248290463863, 0.408248290463863, 0.816496580927726)); ViewOrientation3D transViewOrientation3D = new ViewOrientation3D(new XYZ(-19.0249866627872, -5.09536632799455, 20.7528292850478), new XYZ(0, 0.707106781186547, -0.707106781186547), new XYZ(0, 0.707106781186548, 0.707106781186548)); transView.SetOrientation(transViewOrientation3D); transView.SaveOrientation(); transView.Name = "TransformedGeometry"; foreach (FamilyInstance instance in instanceCollector) { GeometryElement instanceGeo = instance.get_Geometry(m_options); GeometryElement computedGeo = instance.GetOriginalGeometry(m_options); GeometryElement transformGeo = computedGeo.GetTransformed(instance.GetTransform()); // show family instance geometry //foreach (GeometryObject obj in instanceGeo.Objects) IEnumerator <GeometryObject> Objects = instanceGeo.GetEnumerator(); while (Objects.MoveNext()) { GeometryObject obj = Objects.Current; if (obj is Solid) { Solid solid = obj as Solid; PaintSolid(solid, instanceView); } } // show geometry that is original geometry //foreach (GeometryObject obj in computedGeo.Objects) IEnumerator <GeometryObject> Objects1 = computedGeo.GetEnumerator(); while (Objects1.MoveNext()) { GeometryObject obj = Objects1.Current; if (obj is Solid) { Solid solid = obj as Solid; PaintSolid(solid, originalView); } } // show geometry that was transformed //foreach (GeometryObject obj in transformGeo.Objects) IEnumerator <GeometryObject> Objects2 = transformGeo.GetEnumerator(); while (Objects2.MoveNext()) { GeometryObject obj = Objects2.Current; if (obj is Solid) { Solid solid = obj as Solid; PaintSolid(solid, transView); } } } // remove original instances to view point results. RevitDoc.Delete(instanceCollector.ToElementIds()); }
/// <summary> /// Exports curtain object as one Brep. /// </summary> /// <param name="allSubElements"> /// Collection of elements contained in the host curtain element. /// </param> /// <param name="wallElement"> /// The curtain wall element. /// </param> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="setter"> /// The PlacementSetter object. /// </param> /// <param name="localPlacement"> /// The local placement handle. /// </param> /// <returns> /// The handle. /// </returns> public static IFCAnyHandle ExportCurtainObjectCommonAsOneBRep(ICollection <ElementId> allSubElements, Element wallElement, ExporterIFC exporterIFC, PlacementSetter setter, IFCAnyHandle localPlacement) { IFCAnyHandle prodDefRep = null; Document document = wallElement.Document; double eps = UnitUtil.ScaleLength(document.Application.VertexTolerance); IFCFile file = exporterIFC.GetFile(); IFCAnyHandle contextOfItems = exporterIFC.Get3DContextHandle("Body"); IFCGeometryInfo info = IFCGeometryInfo.CreateFaceGeometryInfo(eps); ISet <IFCAnyHandle> bodyItems = new HashSet <IFCAnyHandle>(); // Want to make sure we don't accidentally add a mullion or curtain line more than once. HashSet <ElementId> alreadyVisited = new HashSet <ElementId>(); bool useFallbackBREP = true; Options geomOptions = GeometryUtil.GetIFCExportGeometryOptions(); foreach (ElementId subElemId in allSubElements) { Element subElem = wallElement.Document.GetElement(subElemId); GeometryElement geomElem = subElem.get_Geometry(geomOptions); if (geomElem == null) { continue; } if (alreadyVisited.Contains(subElem.Id)) { continue; } alreadyVisited.Add(subElem.Id); // Export tessellated geometry when IFC4 Reference View is selected if (ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView || ExporterCacheManager.ExportOptionsCache.ExportAs4General) { BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(false, ExportOptionsCache.ExportTessellationLevel.ExtraLow); IList <IFCAnyHandle> triFaceSet = BodyExporter.ExportBodyAsTessellatedFaceSet(exporterIFC, subElem, bodyExporterOptions, geomElem); if (triFaceSet != null && triFaceSet.Count > 0) { foreach (IFCAnyHandle triFaceSetItem in triFaceSet) { bodyItems.Add(triFaceSetItem); } useFallbackBREP = false; // no need to do Brep since it is successful } } // Export AdvancedFace before use fallback BREP else if (ExporterCacheManager.ExportOptionsCache.ExportAs4DesignTransferView) { BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(false, ExportOptionsCache.ExportTessellationLevel.ExtraLow); IFCAnyHandle advancedBRep = BodyExporter.ExportBodyAsAdvancedBrep(exporterIFC, subElem, bodyExporterOptions, geomElem); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(advancedBRep)) { bodyItems.Add(advancedBRep); useFallbackBREP = false; // no need to do Brep since it is successful } } if (useFallbackBREP) { ExporterIFCUtils.CollectGeometryInfo(exporterIFC, info, geomElem, XYZ.Zero, false); HashSet <IFCAnyHandle> faces = new HashSet <IFCAnyHandle>(info.GetSurfaces()); IFCAnyHandle outer = IFCInstanceExporter.CreateClosedShell(file, faces); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(outer)) { bodyItems.Add(RepresentationUtil.CreateFacetedBRep(exporterIFC, document, outer, ElementId.InvalidElementId)); } } } if (bodyItems.Count == 0) { return(prodDefRep); } ElementId catId = CategoryUtil.GetSafeCategoryId(wallElement); IFCAnyHandle shapeRep; // Use tessellated geometry in Reference View if ((ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView || ExporterCacheManager.ExportOptionsCache.ExportAs4General) && !useFallbackBREP) { shapeRep = RepresentationUtil.CreateTessellatedRep(exporterIFC, wallElement, catId, contextOfItems, bodyItems, null); } else if (ExporterCacheManager.ExportOptionsCache.ExportAs4DesignTransferView && !useFallbackBREP) { shapeRep = RepresentationUtil.CreateAdvancedBRepRep(exporterIFC, wallElement, catId, contextOfItems, bodyItems, null); } else { shapeRep = RepresentationUtil.CreateBRepRep(exporterIFC, wallElement, catId, contextOfItems, bodyItems); } if (IFCAnyHandleUtil.IsNullOrHasNoValue(shapeRep)) { return(prodDefRep); } IList <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>(); shapeReps.Add(shapeRep); IFCAnyHandle boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, wallElement.get_Geometry(geomOptions), Transform.Identity); if (boundingBoxRep != null) { shapeReps.Add(boundingBoxRep); } prodDefRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps); return(prodDefRep); }
/// <summary> /// Exports a ramp to IfcRamp, without decomposing into separate runs and landings. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="ifcEnumType">The ramp type.</param> /// <param name="ramp">The ramp element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="numFlights">The number of flights for a multistory ramp.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void ExportRamp(ExporterIFC exporterIFC, string ifcEnumType, Element ramp, GeometryElement geometryElement, int numFlights, ProductWrapper productWrapper) { if (ramp == null || geometryElement == null) { return; } IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, ramp)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(placementSetter.LocalPlacement); ecData.ReuseLocalPlacement = false; GeometryElement rampGeom = GeometryUtil.GetOneLevelGeometryElement(geometryElement, numFlights); BodyData bodyData; ElementId categoryId = CategoryUtil.GetSafeCategoryId(ramp); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(); IFCAnyHandle representation = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, ramp, categoryId, rampGeom, bodyExporterOptions, null, ecData, out bodyData); if (IFCAnyHandleUtil.IsNullOrHasNoValue(representation)) { ecData.ClearOpenings(); return; } string containedRampGuid = GUIDUtil.CreateSubElementGUID(ramp, (int)IFCRampSubElements.ContainedRamp); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string rampName = NamingUtil.GetNameOverride(ramp, NamingUtil.GetIFCName(ramp)); string rampDescription = NamingUtil.GetDescriptionOverride(ramp, null); string rampObjectType = NamingUtil.GetObjectTypeOverride(ramp, NamingUtil.CreateIFCObjectName(exporterIFC, ramp)); IFCAnyHandle containedRampLocalPlacement = ExporterUtil.CreateLocalPlacement(file, ecData.GetLocalPlacement(), null); string elementTag = NamingUtil.GetTagOverride(ramp, NamingUtil.CreateIFCElementId(ramp)); string rampType = GetIFCRampType(ifcEnumType); List <IFCAnyHandle> components = new List <IFCAnyHandle>(); IList <IFCExtrusionCreationData> componentExtrusionData = new List <IFCExtrusionCreationData>(); IFCAnyHandle containedRampHnd = IFCInstanceExporter.CreateRamp(file, containedRampGuid, ownerHistory, rampName, rampDescription, rampObjectType, containedRampLocalPlacement, representation, elementTag, rampType); components.Add(containedRampHnd); componentExtrusionData.Add(ecData); //productWrapper.AddElement(containedRampHnd, placementSetter.LevelInfo, ecData, false); CategoryUtil.CreateMaterialAssociations(exporterIFC, containedRampHnd, bodyData.MaterialIds); string guid = GUIDUtil.CreateGUID(ramp); IFCAnyHandle localPlacement = ecData.GetLocalPlacement(); IFCAnyHandle rampHnd = IFCInstanceExporter.CreateRamp(file, guid, ownerHistory, rampName, rampDescription, rampObjectType, localPlacement, null, elementTag, rampType); productWrapper.AddElement(ramp, rampHnd, placementSetter.LevelInfo, ecData, true); StairRampContainerInfo stairRampInfo = new StairRampContainerInfo(rampHnd, components, localPlacement); ExporterCacheManager.StairRampContainerInfoCache.AddStairRampContainerInfo(ramp.Id, stairRampInfo); ExportMultistoryRamp(exporterIFC, ramp, numFlights, rampHnd, components, componentExtrusionData, placementSetter, productWrapper); } tr.Commit(); } } }
public FindIntersection( FamilyInstance jbox, UIDocument uiDoc) { XYZ jboxPoint = (jbox.Location as LocationPoint).Point; FilteredElementCollector filteredCloserConduits = new FilteredElementCollector(uiDoc.Document); List <Element> listOfCloserConduit = filteredCloserConduits .OfClass(typeof(Conduit)) .ToList() .Where(x => ((x as Conduit).Location as LocationCurve).Curve .GetEndPoint(0).DistanceTo(jboxPoint) < 30 || ((x as Conduit).Location as LocationCurve).Curve .GetEndPoint(1).DistanceTo(jboxPoint) < 30) .ToList(); // getting the location of the box and all conduit around. Options opt = new Options(); opt.View = uiDoc.ActiveView; GeometryElement geoEle = jbox.get_Geometry(opt); // getting the geometry of the element to // access the geometry of the instance. foreach (GeometryObject geomObje1 in geoEle) { GeometryElement geoInstance = (geomObje1 as GeometryInstance).GetInstanceGeometry(); // the geometry of the family instance can be // accessed by this method that returns a // GeometryElement type. so we must get the // GeometryObject again to access the Face of // the family instance. if (geoInstance != null) { foreach (GeometryObject geomObje2 in geoInstance) { Solid geoSolid = geomObje2 as Solid; if (geoSolid != null) { foreach (Face face in geoSolid.Faces) { foreach (Element cond in listOfCloserConduit) { Conduit con = cond as Conduit; Curve conCurve = (con.Location as LocationCurve).Curve; SetComparisonResult set = face.Intersect(conCurve); if (set.ToString() == "Overlap") { //getting the conduit the intersect the box. GetListOfConduits.Add(con); } } } } } } } }
/// <summary> /// Export the dummy wall to host an orphan part. It usually happens in the cases of associated parts are higher than split sub-wall. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The wall element.</param> /// <param name="geometryElement">The geometry of wall.</param> /// <param name="origWrapper">The IFCProductWrapper.</param> /// <param name="overrideLevelId">The ElementId that will crate the dummy wall.</param> /// <param name="range">The IFCRange corresponding to the dummy wall.</param> /// <returns>The handle of dummy wall.</returns> public static IFCAnyHandle ExportDummyWall(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, IFCProductWrapper origWrapper, ElementId overrideLevelId, IFCRange range) { using (IFCProductWrapper localWrapper = IFCProductWrapper.Create(origWrapper)) { ElementId catId = CategoryUtil.GetSafeCategoryId(element); Wall wallElement = element as Wall; if (wallElement == null) return null; if (wallElement != null && IsWallCompletelyClipped(wallElement, exporterIFC, range)) return null; // get global values. Document doc = element.Document; double scale = exporterIFC.LinearScale; IFCFile file = exporterIFC.GetFile(); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); bool validRange = (range != null && !MathUtil.IsAlmostZero(range.Start - range.End)); bool exportParts = PartExporter.CanExportParts(wallElement); if (exportParts && !PartExporter.CanExportElementInPartExport(wallElement, validRange ? overrideLevelId : wallElement.Level.Id, validRange)) return null; string objectType = NamingUtil.CreateIFCObjectName(exporterIFC, element); IFCAnyHandle wallHnd = null; string elemGUID = (validRange) ? ExporterIFCUtils.CreateGUID() : ExporterIFCUtils.CreateGUID(element); string elemName = NamingUtil.GetNameOverride(element, exporterIFC.GetName()); string elemDesc = NamingUtil.GetDescriptionOverride(element, null); string elemObjectType = NamingUtil.GetObjectTypeOverride(element, objectType); string elemId = NamingUtil.CreateIFCElementId(element); Transform orientationTrf = Transform.Identity; using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, element, null, orientationTrf, overrideLevelId)) { IFCAnyHandle localPlacement = setter.GetPlacement(); wallHnd = IFCInstanceExporter.CreateWall(file, elemGUID, ownerHistory, elemName, elemDesc, elemObjectType, localPlacement, null, elemId); if (exportParts) PartExporter.ExportHostPart(exporterIFC, wallElement, wallHnd, localWrapper, setter, localPlacement, overrideLevelId); IFCExtrusionCreationData extraParams = new IFCExtrusionCreationData(); extraParams.PossibleExtrusionAxes = IFCExtrusionAxes.TryZ; // only allow vertical extrusions! extraParams.AreInnerRegionsOpenings = true; localWrapper.AddElement(wallHnd, setter, extraParams, true); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, localWrapper); ElementId wallLevelId = (validRange) ? setter.LevelId : ElementId.InvalidElementId; exporterIFC.RegisterSpaceBoundingElementHandle(wallHnd, element.Id, wallLevelId); } return wallHnd; } }
/// <summary> /// Exports an element as an IfcReinforcingMesh. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <returns>True if exported successfully, false otherwise.</returns> public static bool ExportFabricSheet(ExporterIFC exporterIFC, FabricSheet sheet, GeometryElement geometryElement, ProductWrapper productWrapper) { if (sheet == null || geometryElement == null) { return(false); } // Check the intended IFC entity or type name is in the exclude list specified in the UI Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcReinforcingMesh; if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum)) { return(false); } Document doc = sheet.Document; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { // Check for containment override IFCAnyHandle overrideContainerHnd = null; ElementId overrideContainerId = ParameterUtil.OverrideContainmentParameter(exporterIFC, sheet, out overrideContainerHnd); using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, sheet, null, null, overrideContainerId, overrideContainerHnd)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(placementSetter.LocalPlacement); ElementId categoryId = CategoryUtil.GetSafeCategoryId(sheet); ElementId materialId = ElementId.InvalidElementId; ParameterUtil.GetElementIdValueFromElementOrSymbol(sheet, BuiltInParameter.MATERIAL_ID_PARAM, out materialId); string guid = GUIDUtil.CreateGUID(sheet); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; string revitObjectType = NamingUtil.GetFamilyAndTypeName(sheet); IFCAnyHandle localPlacement = ecData.GetLocalPlacement(); string steelGrade = NamingUtil.GetOverrideStringValue(sheet, "SteelGrade", null); double?meshLength = sheet.CutOverallLength; double?meshWidth = sheet.CutOverallWidth; Element fabricSheetTypeElem = doc.GetElement(sheet.GetTypeId()); FabricSheetType fabricSheetType = (fabricSheetTypeElem == null) ? null : (fabricSheetTypeElem as FabricSheetType); double longitudinalBarNominalDiameter = 0.0; double transverseBarNominalDiameter = 0.0; double longitudinalBarCrossSectionArea = 0.0; double transverseBarCrossSectionArea = 0.0; double longitudinalBarSpacing = 0.0; double transverseBarSpacing = 0.0; if (fabricSheetType != null) { Element majorFabricWireTypeElem = doc.GetElement(fabricSheetType.MajorDirectionWireType); FabricWireType majorFabricWireType = (majorFabricWireTypeElem == null) ? null : (majorFabricWireTypeElem as FabricWireType); if (majorFabricWireType != null) { longitudinalBarNominalDiameter = UnitUtil.ScaleLength(majorFabricWireType.WireDiameter); double localRadius = longitudinalBarNominalDiameter / 2.0; longitudinalBarCrossSectionArea = localRadius * localRadius * Math.PI; } Element minorFabricWireTypeElem = doc.GetElement(fabricSheetType.MinorDirectionWireType); FabricWireType minorFabricWireType = (minorFabricWireTypeElem == null) ? null : (minorFabricWireTypeElem as FabricWireType); if (minorFabricWireType != null) { transverseBarNominalDiameter = UnitUtil.ScaleLength(minorFabricWireType.WireDiameter); double localRadius = transverseBarNominalDiameter / 2.0; transverseBarCrossSectionArea = localRadius * localRadius * Math.PI; } longitudinalBarSpacing = UnitUtil.ScaleLength(fabricSheetType.MajorSpacing); transverseBarSpacing = UnitUtil.ScaleLength(fabricSheetType.MinorSpacing); } ISet <IFCAnyHandle> bodyItems = new HashSet <IFCAnyHandle>(); IList <Curve> wireCenterlines = sheet.GetWireCenterlines(WireDistributionDirection.Major); foreach (Curve wireCenterline in wireCenterlines) { IFCAnyHandle bodyItem = GeometryUtil.CreateSweptDiskSolid(exporterIFC, file, wireCenterline, longitudinalBarNominalDiameter, null); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(bodyItem)) { bodyItems.Add(bodyItem); } } wireCenterlines = sheet.GetWireCenterlines(WireDistributionDirection.Minor); foreach (Curve wireCenterline in wireCenterlines) { IFCAnyHandle bodyItem = GeometryUtil.CreateSweptDiskSolid(exporterIFC, file, wireCenterline, transverseBarNominalDiameter, null); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(bodyItem)) { bodyItems.Add(bodyItem); } } IFCAnyHandle shapeRep = (bodyItems.Count > 0) ? RepresentationUtil.CreateAdvancedSweptSolidRep(exporterIFC, sheet, categoryId, exporterIFC.Get3DContextHandle("Body"), bodyItems, null) : null; IList <IFCAnyHandle> shapeReps = null; if (shapeRep != null) { shapeReps = new List <IFCAnyHandle>(); shapeReps.Add(shapeRep); } IFCAnyHandle prodRep = (shapeReps != null) ? IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps) : null; IFCAnyHandle fabricSheet = IFCInstanceExporter.CreateReinforcingMesh(exporterIFC, sheet, guid, ownerHistory, localPlacement, prodRep, steelGrade, meshLength, meshWidth, longitudinalBarNominalDiameter, transverseBarNominalDiameter, longitudinalBarCrossSectionArea, transverseBarCrossSectionArea, longitudinalBarSpacing, transverseBarSpacing); ElementId fabricAreaId = sheet.FabricAreaOwnerId; if (fabricAreaId != ElementId.InvalidElementId) { HashSet <IFCAnyHandle> fabricSheets = null; if (!ExporterCacheManager.FabricAreaHandleCache.TryGetValue(fabricAreaId, out fabricSheets)) { fabricSheets = new HashSet <IFCAnyHandle>(); ExporterCacheManager.FabricAreaHandleCache[fabricAreaId] = fabricSheets; } fabricSheets.Add(fabricSheet); } productWrapper.AddElement(sheet, fabricSheet, placementSetter.LevelInfo, ecData, true); CategoryUtil.CreateMaterialAssociation(exporterIFC, fabricSheet, materialId); } } tr.Commit(); return(true); } }
/// <summary> /// Exports a curve element to IFC curve annotation. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="curveElement"> /// The curve element to be exported. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void ExportCurveElement(ExporterIFC exporterIFC, CurveElement curveElement, GeometryElement geometryElement, ProductWrapper productWrapper) { if (geometryElement == null || !ShouldCurveElementBeExported(curveElement)) { return; } SketchPlane sketchPlane = curveElement.SketchPlane; if (sketchPlane == null) { return; } // Check the intended IFC entity or type name is in the exclude list specified in the UI Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcAnnotation; if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum)) { return; } IFCFile file = exporterIFC.GetFile(); using (IFCTransaction transaction = new IFCTransaction(file)) { // Check for containment override IFCAnyHandle overrideContainerHnd = null; ElementId overrideContainerId = ParameterUtil.OverrideContainmentParameter(exporterIFC, curveElement, out overrideContainerHnd); using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, curveElement, null, null, overrideContainerId, overrideContainerHnd)) { IFCAnyHandle localPlacement = setter.LocalPlacement; IFCAnyHandle axisPlacement = GeometryUtil.GetRelativePlacementFromLocalPlacement(localPlacement); Plane planeSK = sketchPlane.GetPlane(); XYZ projDir = planeSK.Normal; XYZ origin = planeSK.Origin; bool useOffsetTrf = false; if (projDir.IsAlmostEqualTo(XYZ.BasisZ)) { XYZ offset = XYZ.BasisZ * setter.Offset; origin -= offset; } else { useOffsetTrf = true; } Transform curveLCS = GeometryUtil.CreateTransformFromPlane(planeSK); curveLCS.Origin = origin; IList <IFCAnyHandle> curves = null; if (ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView) { Transform trf = null; if (useOffsetTrf) { XYZ offsetOrig = -XYZ.BasisZ * setter.Offset; trf = Transform.CreateTranslation(offsetOrig); } curves = new List <IFCAnyHandle>(); //Curve curve = (geometryElement as GeometryObject) as Curve; List <Curve> curvesFromGeomElem = GeometryUtil.GetCurvesFromGeometryElement(geometryElement); foreach (Curve curve in curvesFromGeomElem) { IFCAnyHandle curveHnd; try { curveHnd = GeometryUtil.CreatePolyCurveFromCurve(exporterIFC, curve, trf); } catch { curveHnd = GeometryUtil.OutdatedCreatePolyCurveFromCurve(exporterIFC, curve, trf); } if (!IFCAnyHandleUtil.IsNullOrHasNoValue(curveHnd)) { curves.Add(curveHnd); } } } else { IFCGeometryInfo info = IFCGeometryInfo.CreateCurveGeometryInfo(exporterIFC, curveLCS, projDir, false); if (useOffsetTrf) { XYZ offsetOrig = -XYZ.BasisZ * setter.Offset; Transform trf = Transform.CreateTranslation(offsetOrig); ExporterIFCUtils.CollectGeometryInfo(exporterIFC, info, geometryElement, XYZ.Zero, false, trf); } else { ExporterIFCUtils.CollectGeometryInfo(exporterIFC, info, geometryElement, XYZ.Zero, false); } curves = info.GetCurves(); } if (curves.Count != 1) { throw new Exception("IFC: expected 1 curve when export curve element."); } HashSet <IFCAnyHandle> curveSet = new HashSet <IFCAnyHandle>(curves); IFCAnyHandle repItemHnd = IFCInstanceExporter.CreateGeometricCurveSet(file, curveSet); IFCAnyHandle curveStyle = file.CreateStyle(exporterIFC, repItemHnd); CurveAnnotationCache annotationCache = ExporterCacheManager.CurveAnnotationCache; IFCAnyHandle curveAnno = annotationCache.GetAnnotation(sketchPlane.Id, curveStyle); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(curveAnno)) { AddCurvesToAnnotation(curveAnno, curves); } else { curveAnno = CreateCurveAnnotation(exporterIFC, curveElement, curveElement.Category.Id, sketchPlane.Id, curveLCS, curveStyle, setter, localPlacement, repItemHnd); productWrapper.AddAnnotation(curveAnno, setter.LevelInfo, true); annotationCache.AddAnnotation(sketchPlane.Id, curveStyle, curveAnno); } } transaction.Commit(); } }
/// <summary> /// Sample file is at /// C:\a\j\adn\case\bsd\1242980\attach\mullion.rvt /// </summary> public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = app.ActiveUIDocument.Document; Selection sel = uidoc.Selection; Options options = app.Application.Create.NewGeometryOptions(); string s, msg = string.Empty; int n; foreach (ElementId id in sel.GetElementIds()) { Mullion mullion = doc.GetElement(id) as Mullion; if (null != mullion) { //Location location = mullion.AsFamilyInstance.Location; // seems to be uninitialised // 2011 Location location = mullion.Location; // 2012 LocationPoint lp = mullion.Location as LocationPoint; Debug.Assert(null != lp, "expected a valid mullion location point"); Debug.Assert(null != mullion.LocationCurve, // 2012 "in Revit 2012, the mullion also has a valid location curve"); // 2012 GeometryElement geoElem = mullion.get_Geometry(options); //GeometryObjectArray objects = geoElem.Objects; // 2012 //n = objects.Size; // 2012 n = geoElem.Count <GeometryObject>(); // 2013 s = string.Format( "Mullion <{0} {1}> at {2} rotation" + " {3} has {4} geo object{5}:", mullion.Name, mullion.Id.IntegerValue, Util.PointString(lp.Point), Util.RealString(lp.Rotation), n, Util.PluralSuffix(n)); if (0 < msg.Length) { msg += "\n\n"; } msg += s; //foreach( GeometryObject obj in objects ) // 2012 foreach (GeometryObject obj in geoElem) // 2013 { GeometryInstance inst = obj as GeometryInstance; Transform t = inst.Transform; s = " Transform " + Util.TransformString(t); msg += "\n" + s; GeometryElement elem2 = inst.SymbolGeometry; //foreach( GeometryObject obj2 in elem2.Objects ) // 2012 foreach (GeometryObject obj2 in elem2) // 2013 { Solid solid = obj2 as Solid; if (null != solid) { FaceArray faces = solid.Faces; n = faces.Size; s = string.Format( " {0} face{1}, face point > WCS point:", n, Util.PluralSuffix(n)); msg += "\n" + s; foreach (Face face in solid.Faces) { s = string.Empty; Mesh mesh = face.Triangulate(); foreach (XYZ p in mesh.Vertices) { s += (0 == s.Length) ? " " : ", "; s += string.Format("{0} > {1}", Util.PointString(p), Util.PointString(t.OfPoint(p))); } msg += "\n" + s; } } } } } } if (0 == msg.Length) { msg = "Please select some mullions."; } Util.InfoMsg(msg); return(Result.Failed); }
/// <summary> /// Exports topography surface as IFC site object. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="topSurface"> /// The TopographySurface object. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The IFCProductWrapper. /// </param> public static void ExportTopographySurface(ExporterIFC exporterIFC, TopographySurface topSurface, GeometryElement geometryElement, IFCProductWrapper productWrapper) { ExportSiteBase(exporterIFC, null, topSurface, geometryElement, productWrapper); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, topSurface, productWrapper); }
public static void SlopedWallTest( ExternalCommandData revit) { Document massDoc = revit.Application.Application.NewFamilyDocument( @"C:\ProgramData\Autodesk\RAC 2012\Family Templates\English_I\Conceptual Mass\Mass.rft"); Transaction transaction = new Transaction(massDoc); transaction.SetName("TEST"); transaction.Start(); ExternalCommandData cdata = revit; Autodesk.Revit.ApplicationServices.Application app = revit.Application.Application; app = revit.Application.Application; // Create one profile ReferenceArray ref_ar = new ReferenceArray(); Autodesk.Revit.DB.XYZ ptA = new XYZ(0, 0, 0); XYZ ptB = new XYZ(0, 30, 0); ModelCurve modelcurve = MakeLine(revit.Application, ptA, ptB, massDoc); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new XYZ(0, 30, 0); ptB = new XYZ(2, 30, 0); modelcurve = MakeLine(revit.Application, ptA, ptB, massDoc); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new XYZ(2, 30, 0); ptB = new XYZ(2, 0, 0); modelcurve = MakeLine(revit.Application, ptA, ptB, massDoc); ref_ar.Append(modelcurve.GeometryCurve.Reference); ptA = new XYZ(2, 0, 0); ptB = new XYZ(0, 0, 0); modelcurve = MakeLine(revit.Application, ptA, ptB, massDoc); ref_ar.Append(modelcurve.GeometryCurve.Reference); // The extrusion form direction XYZ direction = new XYZ(-6, 0, 50); Form form = massDoc.FamilyCreate.NewExtrusionForm(true, ref_ar, direction); transaction.Commit(); if (File.Exists(@"C:\TestFamily.rfa")) { File.Delete(@"C:\TestFamily.rfa"); } massDoc.SaveAs(@"C:\TestFamily.rfa"); if (!revit.Application.ActiveUIDocument.Document.LoadFamily(@"C:\TestFamily.rfa")) { throw new Exception("DID NOT LOAD FAMILY"); } Family family = null; foreach (Element el in new FilteredElementCollector( revit.Application.ActiveUIDocument.Document).WhereElementIsNotElementType().ToElements()) { if (el is Family) { if (((Family)el).Name.ToUpper().Trim().StartsWith("TEST")) { family = (Family)el; } } } FamilySymbol fs = null; foreach (FamilySymbol sym in family.Symbols) { fs = sym; } // Create a family instance. revit.Application.ActiveUIDocument.Document.Create.NewFamilyInstance( new XYZ(0, 0, 0), fs, revit.Application.ActiveUIDocument.Document.ActiveView.Level, StructuralType.NonStructural); WallType wallType = null; foreach (WallType wt in revit.Application.ActiveUIDocument.Document.WallTypes) { if (FaceWall.IsWallTypeValidForFaceWall(revit.Application.ActiveUIDocument.Document, wt.Id)) { wallType = wt; break; } } foreach (Element el in new FilteredElementCollector( revit.Application.ActiveUIDocument.Document).WhereElementIsNotElementType().ToElements()) { if (el is FamilyInstance) { if (((FamilyInstance)el).Symbol.Family.Name.ToUpper().StartsWith("TEST")) { Options options = revit.Application.Application.Create.NewGeometryOptions(); options.ComputeReferences = true; options.View = revit.Application.ActiveUIDocument.Document.ActiveView; GeometryElement geoel = el.get_Geometry(options); // Attempt to create a slopped wall from the geometry. for (int i = 0; i < geoel.Objects.Size; i++) { if (geoel.Objects.get_Item(i) is Solid) { Solid solid = (Solid)geoel.Objects.get_Item(i); for (int j = 0; j < solid.Faces.Size; j++) { try { if (solid.Faces.get_Item(i).Reference != null) { FaceWall.Create(revit.Application.ActiveUIDocument.Document, wallType.Id, WallLocationLine.CoreCenterline, solid.Faces.get_Item(i).Reference); } } catch (System.Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } } } } } } } }
/// <summary> /// Exports a family instance to corresponding IFC object. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="familyInstance"> /// The family instance to be exported. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void ExportFamilyInstanceElement(ExporterIFC exporterIFC, FamilyInstance familyInstance, GeometryElement geometryElement, ProductWrapper productWrapper) { // Don't export family if it is invisible, or has a null geometry. if (familyInstance.Invisible || geometryElement == null) return; // Don't export mullions and panels if they have a host and their host is not a mass // as they will be exported with the host (curtain wall/roof). if (familyInstance.Category.Id == new ElementId(BuiltInCategory.OST_CurtainWallMullions) || familyInstance.Category.Id == new ElementId(BuiltInCategory.OST_CurtainWallPanels)) { Element host = familyInstance.Host; if (host != null && host.Category.Id != new ElementId(BuiltInCategory.OST_Mass)) return; } FamilySymbol familySymbol = familyInstance.Symbol; Family family = familySymbol.Family; if (family == null) return; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { string ifcEnumType; IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, familyInstance, out ifcEnumType); if (exportType == IFCExportType.DontExport) return; if (ExportFamilyInstanceAsStandardElement(exporterIFC, familyInstance, geometryElement, exportType, ifcEnumType, productWrapper)) { tr.Commit(); return; } // If we are exporting a column, we may need to split it into parts by level. Create a list of ranges. IList<ElementId> levels = new List<ElementId>(); IList<IFCRange> ranges = new List<IFCRange>(); // We will not split walls and columns if the assemblyId is set, as we would like to keep the original wall // associated with the assembly, on the level of the assembly. bool splitColumn = (exportType == IFCExportType.ExportColumnType) && (ExporterCacheManager.ExportOptionsCache.WallAndColumnSplitting) && (familyInstance.AssemblyInstanceId == ElementId.InvalidElementId); if (splitColumn) { LevelUtil.CreateSplitLevelRangesForElement(exporterIFC, exportType, familyInstance, out levels, out ranges); } int numPartsToExport = ranges.Count; if (numPartsToExport == 0) { ExportFamilyInstanceAsMappedItem(exporterIFC, familyInstance, exportType, ifcEnumType, productWrapper, ElementId.InvalidElementId, null, null); } else { for (int ii = 0; ii < numPartsToExport; ii++) { ExportFamilyInstanceAsMappedItem(exporterIFC, familyInstance, exportType, ifcEnumType, productWrapper, levels[ii], ranges[ii], null); } if (ExporterCacheManager.DummyHostCache.HasRegistered(familyInstance.Id)) { List<KeyValuePair<ElementId, IFCRange>> levelRangeList = ExporterCacheManager.DummyHostCache.Find(familyInstance.Id); foreach (KeyValuePair<ElementId, IFCRange> levelRange in levelRangeList) { ExportFamilyInstanceAsMappedItem(exporterIFC, familyInstance, exportType, ifcEnumType, productWrapper, levelRange.Key, levelRange.Value, null); } } } tr.Commit(); } }
/// <summary> /// Exports a gutter element. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void ExportGutter(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { ecData.SetLocalPlacement(setter.LocalPlacement); ElementId categoryId = CategoryUtil.GetSafeCategoryId(element); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(); IFCAnyHandle bodyRep = BodyExporter.ExportBody(exporterIFC, element, categoryId, ElementId.InvalidElementId, geometryElement, bodyExporterOptions, ecData).RepresentationHnd; if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep)) { if (ecData != null) ecData.ClearOpenings(); return; } IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string originalTag = NamingUtil.CreateIFCElementId(element); // In Revit, we don't have a corresponding type, so we create one for every gutter. IFCAnyHandle origin = ExporterUtil.CreateAxis2Placement3D(file); IFCAnyHandle repMap3dHnd = IFCInstanceExporter.CreateRepresentationMap(file, origin, bodyRep); List<IFCAnyHandle> repMapList = new List<IFCAnyHandle>(); repMapList.Add(repMap3dHnd); string elementTypeName = NamingUtil.CreateIFCObjectName(exporterIFC, element); string typeGuid = GUIDUtil.CreateSubElementGUID(element, (int) IFCHostedSweepSubElements.PipeSegmentType); IFCAnyHandle style = IFCInstanceExporter.CreatePipeSegmentType(file, typeGuid, ownerHistory, elementTypeName, null, null, null, repMapList, originalTag, elementTypeName, IFCPipeSegmentType.Gutter); List<IFCAnyHandle> representationMaps = GeometryUtil.GetRepresentationMaps(style); IFCAnyHandle mappedItem = ExporterUtil.CreateDefaultMappedItem(file, representationMaps[0]); ISet<IFCAnyHandle> representations = new HashSet<IFCAnyHandle>(); representations.Add(mappedItem); IFCAnyHandle bodyMappedItemRep = RepresentationUtil.CreateBodyMappedItemRep(exporterIFC, element, categoryId, exporterIFC.Get3DContextHandle("Body"), representations); if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyMappedItemRep)) return; List<IFCAnyHandle> shapeReps = new List<IFCAnyHandle>(); shapeReps.Add(bodyMappedItemRep); IFCAnyHandle boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, geometryElement, Transform.Identity); if (boundingBoxRep != null) shapeReps.Add(boundingBoxRep); IFCAnyHandle prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps); IFCAnyHandle localPlacementToUse; ElementId roomId = setter.UpdateRoomRelativeCoordinates(element, out localPlacementToUse); if (roomId == ElementId.InvalidElementId) localPlacementToUse = ecData.GetLocalPlacement(); string guid = GUIDUtil.CreateGUID(element); string name = NamingUtil.GetNameOverride(element, NamingUtil.GetIFCName(element)); string description = NamingUtil.GetDescriptionOverride(element, null); string objectType = NamingUtil.GetObjectTypeOverride(element, elementTypeName); string tag = NamingUtil.GetTagOverride(element, originalTag); IFCAnyHandle elemHnd = IFCInstanceExporter.CreateFlowSegment(file, guid, ownerHistory, name, description, objectType, localPlacementToUse, prodRep, tag); bool containedInSpace = (roomId != ElementId.InvalidElementId); productWrapper.AddElement(element, elemHnd, setter.LevelInfo, ecData, !containedInSpace); if (containedInSpace) ExporterCacheManager.SpaceInfoCache.RelateToSpace(roomId, elemHnd); // Associate segment with type. ExporterCacheManager.TypeRelationsCache.Add(style, elemHnd); OpeningUtil.CreateOpeningsIfNecessary(elemHnd, element, ecData, null, exporterIFC, localPlacementToUse, setter, productWrapper); } tr.Commit(); } } }
/// <summary> /// Exports a CeilingAndFloor element to IFC. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="floor">The floor element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void ExportCeilingAndFloorElement(ExporterIFC exporterIFC, CeilingAndFloor floorElement, GeometryElement geometryElement, ProductWrapper productWrapper) { if (geometryElement == null) { return; } // export parts or not bool exportParts = PartExporter.CanExportParts(floorElement); if (exportParts && !PartExporter.CanExportElementInPartExport(floorElement, floorElement.LevelId, false)) { return; } IFCFile file = exporterIFC.GetFile(); string ifcEnumType; IFCExportInfoPair exportType = ExporterUtil.GetExportType(exporterIFC, floorElement, out ifcEnumType); IFCAnyHandle type = null; // Check the intended IFC entity or type name is in the exclude list specified in the UI Common.Enums.IFCEntityType elementClassTypeEnum; if (Enum.TryParse <Common.Enums.IFCEntityType>(exportType.ToString(), out elementClassTypeEnum)) { if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum)) { return; } } string predefinedType = null; using (IFCTransaction tr = new IFCTransaction(file)) { bool canExportAsContainerOrWithExtrusionAnalyzer = (!exportParts && (floorElement is Floor)); if (canExportAsContainerOrWithExtrusionAnalyzer) { // Try to export the Floor slab as a container. If that succeeds, we are done. // If we do export the floor as a container, it will take care of the local placement and transform there, so we need to leave // this out of the IFCTransformSetter and PlacementSetter scopes below, or else we'll get double transforms. IFCAnyHandle floorHnd = RoofExporter.ExportRoofOrFloorAsContainer(exporterIFC, ifcEnumType, floorElement, geometryElement, productWrapper); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(floorHnd)) { tr.Commit(); return; } } IList <IFCAnyHandle> slabHnds = new List <IFCAnyHandle>(); IList <IFCAnyHandle> brepSlabHnds = new List <IFCAnyHandle>(); IList <IFCAnyHandle> nonBrepSlabHnds = new List <IFCAnyHandle>(); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; using (IFCTransformSetter transformSetter = IFCTransformSetter.Create()) { using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, floorElement)) { IFCAnyHandle localPlacement = placementSetter.LocalPlacement; // The routine ExportExtrudedSlabOpenings is called if exportedAsInternalExtrusion is true, and it requires having a valid level association. // Disable calling ExportSlabAsExtrusion if we can't handle potential openings. bool canExportAsInternalExtrusion = placementSetter.LevelInfo != null; bool exportedAsInternalExtrusion = false; ElementId catId = CategoryUtil.GetSafeCategoryId(floorElement); IList <IFCAnyHandle> prodReps = new List <IFCAnyHandle>(); IList <ShapeRepresentationType> repTypes = new List <ShapeRepresentationType>(); IList <IList <CurveLoop> > extrusionLoops = new List <IList <CurveLoop> >(); IList <IFCExtrusionCreationData> loopExtraParams = new List <IFCExtrusionCreationData>(); Plane floorPlane = GeometryUtil.CreateDefaultPlane(); IList <IFCAnyHandle> localPlacements = new List <IFCAnyHandle>(); if (canExportAsContainerOrWithExtrusionAnalyzer) { Floor floor = floorElement as Floor; // Next, try to use the ExtrusionAnalyzer for the limited cases it handles - 1 solid, no openings, end clippings only. // Also limited to cases with line and arc boundaries. // SolidMeshGeometryInfo solidMeshInfo = GeometryUtil.GetSplitSolidMeshGeometry(geometryElement); IList <Solid> solids = solidMeshInfo.GetSolids(); IList <Mesh> meshes = solidMeshInfo.GetMeshes(); if (solids.Count == 1 && meshes.Count == 0) { bool completelyClipped; // floorExtrusionDirection is set to (0, 0, -1) because extrusionAnalyzerFloorPlane is computed from the top face of the floor XYZ floorExtrusionDirection = new XYZ(0, 0, -1); XYZ modelOrigin = XYZ.Zero; XYZ floorOrigin = floor.GetVerticalProjectionPoint(modelOrigin, FloorFace.Top); if (floorOrigin == null) { // GetVerticalProjectionPoint may return null if FloorFace.Top is an edited face that doesn't // go through the Revit model origin. We'll try the midpoint of the bounding box instead. BoundingBoxXYZ boundingBox = floorElement.get_BoundingBox(null); modelOrigin = (boundingBox.Min + boundingBox.Max) / 2.0; floorOrigin = floor.GetVerticalProjectionPoint(modelOrigin, FloorFace.Top); } if (floorOrigin != null) { XYZ floorDir = floor.GetNormalAtVerticalProjectionPoint(floorOrigin, FloorFace.Top); Plane extrusionAnalyzerFloorBasePlane = GeometryUtil.CreatePlaneByNormalAtOrigin(floorDir); GenerateAdditionalInfo additionalInfo = ExporterCacheManager.ExportOptionsCache.ExportAs4 ? GenerateAdditionalInfo.GenerateFootprint : GenerateAdditionalInfo.None; HandleAndData floorAndProperties = ExtrusionExporter.CreateExtrusionWithClippingAndProperties(exporterIFC, floorElement, catId, solids[0], extrusionAnalyzerFloorBasePlane, floorOrigin, floorExtrusionDirection, null, out completelyClipped, addInfo: additionalInfo); if (completelyClipped) { return; } if (floorAndProperties.Handle != null) { IList <IFCAnyHandle> representations = new List <IFCAnyHandle>(); representations.Add(floorAndProperties.Handle); // Footprint representation will only be exported in export to IFC4 if (((additionalInfo & GenerateAdditionalInfo.GenerateFootprint) != 0) && (floorAndProperties.FootprintInfo != null)) { if (!(IFCAnyHandleUtil.IsNullOrHasNoValue(floorAndProperties.FootprintInfo.FootPrintHandle))) { representations.Add(floorAndProperties.FootprintInfo.FootPrintHandle); } } IFCAnyHandle prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, representations); prodReps.Add(prodRep); repTypes.Add(ShapeRepresentationType.SweptSolid); if (floorAndProperties.Data != null) { loopExtraParams.Add(floorAndProperties.Data); } } } } } // Use internal routine as backup that handles openings. if (prodReps.Count == 0 && canExportAsInternalExtrusion && !ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView) { //IList<IFCAnyHandle> prodRepsTmp = new List<IFCAnyHandle>(); exportedAsInternalExtrusion = ExporterIFCUtils.ExportSlabAsExtrusion(exporterIFC, floorElement, geometryElement, transformSetter, localPlacement, out localPlacements, out prodReps, out extrusionLoops, out loopExtraParams, floorPlane); for (int ii = 0; ii < prodReps.Count; ii++) { // all are extrusions repTypes.Add(ShapeRepresentationType.SweptSolid); // Footprint representation will only be exported in export to IFC4 if (ExporterCacheManager.ExportOptionsCache.ExportAs4) { if (extrusionLoops.Count > ii) { if (extrusionLoops[ii].Count > 0) { // Get the extrusion footprint using the first Curveloop. Transform needs to be obtained from the returned local placement Transform lcs = ExporterIFCUtils.GetUnscaledTransform(exporterIFC, localPlacements[ii]); IFCAnyHandle footprintGeomRepItem = GeometryUtil.CreateIFCCurveFromCurveLoop(exporterIFC, extrusionLoops[ii][0], lcs, floorPlane.Normal); IFCAnyHandle contextOfItemsFootprint = exporterIFC.Get3DContextHandle("FootPrint"); ISet <IFCAnyHandle> repItem = new HashSet <IFCAnyHandle>(); repItem.Add(footprintGeomRepItem); IFCAnyHandle footprintShapeRepresentation = RepresentationUtil.CreateBaseShapeRepresentation(exporterIFC, contextOfItemsFootprint, "FootPrint", "Curve2D", repItem); //representations.Add(footprintShapeRepresentation); IList <IFCAnyHandle> reps = new List <IFCAnyHandle>(); reps.Add(footprintShapeRepresentation); IFCAnyHandleUtil.AddRepresentations(prodReps[ii], reps); } } } } } if (prodReps.Count == 0) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { // Brep representation using tesellation after ExportSlabAsExtrusion does not return prodReps BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.Medium); BodyData bodyData; IFCAnyHandle prodDefHnd = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, floorElement, catId, geometryElement, bodyExporterOptions, null, ecData, out bodyData); if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodDefHnd)) { ecData.ClearOpenings(); return; } prodReps.Add(prodDefHnd); repTypes.Add(bodyData.ShapeRepresentationType); } } // Create the slab from either the extrusion or the BRep information. string ifcGUID = GUIDUtil.CreateGUID(floorElement); int numReps = exportParts ? 1 : prodReps.Count; switch (exportType.ExportInstance) { case IFCEntityType.IfcFooting: if (ExporterCacheManager.ExportOptionsCache.ExportAs4) { predefinedType = IFCValidateEntry.GetValidIFCType <Revit.IFC.Export.Toolkit.IFC4.IFCFootingType>(floorElement, ifcEnumType, null); } else { predefinedType = IFCValidateEntry.GetValidIFCType <IFCFootingType>(floorElement, ifcEnumType, null); } break; case IFCEntityType.IfcCovering: predefinedType = IFCValidateEntry.GetValidIFCType <IFCCoveringType>(floorElement, ifcEnumType, "FLOORING"); break; case IFCEntityType.IfcRamp: if (ExporterCacheManager.ExportOptionsCache.ExportAs4) { predefinedType = IFCValidateEntry.GetValidIFCType <Revit.IFC.Export.Toolkit.IFC4.IFCRampType>(floorElement, ifcEnumType, null); } else { predefinedType = IFCValidateEntry.GetValidIFCType <IFCRampType>(floorElement, ifcEnumType, null); } break; default: bool isBaseSlab = false; AnalyticalModel analyticalModel = floorElement.GetAnalyticalModel(); if (analyticalModel != null) { AnalyzeAs slabFoundationType = analyticalModel.GetAnalyzeAs(); isBaseSlab = (slabFoundationType == AnalyzeAs.SlabOnGrade) || (slabFoundationType == AnalyzeAs.Mat); } predefinedType = IFCValidateEntry.GetValidIFCType <IFCSlabType>(floorElement, ifcEnumType, isBaseSlab ? "BASESLAB" : "FLOOR"); break; } for (int ii = 0; ii < numReps; ii++) { string ifcName = NamingUtil.GetNameOverride(floorElement, NamingUtil.GetIFCNamePlusIndex(floorElement, ii == 0 ? -1 : ii + 1)); string currentGUID = (ii == 0) ? ifcGUID : GUIDUtil.CreateGUID(); IFCAnyHandle localPlacementHnd = exportedAsInternalExtrusion ? localPlacements[ii] : localPlacement; IFCAnyHandle slabHnd = null; slabHnd = IFCInstanceExporter.CreateGenericIFCEntity(exportType, exporterIFC, floorElement, currentGUID, ownerHistory, localPlacementHnd, exportParts ? null : prodReps[ii]); if (!string.IsNullOrEmpty(ifcName)) { IFCAnyHandleUtil.SetAttribute(slabHnd, "Name", ifcName); } if (!string.IsNullOrEmpty(predefinedType)) { IFCAnyHandleUtil.SetAttribute(slabHnd, "PredefinedType", predefinedType, true); } if (IFCAnyHandleUtil.IsNullOrHasNoValue(slabHnd)) { return; } IFCAnyHandleUtil.SetAttribute(slabHnd, "Name", ifcName); if (exportParts) { PartExporter.ExportHostPart(exporterIFC, floorElement, slabHnd, productWrapper, placementSetter, localPlacementHnd, null); } slabHnds.Add(slabHnd); if (!exportParts) { if (repTypes[ii] == ShapeRepresentationType.Brep || repTypes[ii] == ShapeRepresentationType.Tessellation) { brepSlabHnds.Add(slabHnd); } else { nonBrepSlabHnds.Add(slabHnd); } } } for (int ii = 0; ii < numReps; ii++) { IFCExtrusionCreationData loopExtraParam = ii < loopExtraParams.Count ? loopExtraParams[ii] : null; productWrapper.AddElement(floorElement, slabHnds[ii], placementSetter, loopExtraParam, true); type = ExporterUtil.CreateGenericTypeFromElement(floorElement, exportType, file, ownerHistory, predefinedType, productWrapper); ExporterCacheManager.TypeRelationsCache.Add(type, slabHnds[ii]); } // This call to the native function appears to create Brep opening also when appropriate. But the creation of the IFC instances is not // controllable from the managed code. Therefore in some cases BRep geometry for Opening will still be exported even in the Reference View if (exportedAsInternalExtrusion) { ExporterIFCUtils.ExportExtrudedSlabOpenings(exporterIFC, floorElement, placementSetter.LevelInfo, localPlacements[0], slabHnds, extrusionLoops, floorPlane, productWrapper.ToNative()); } } if (!exportParts) { if (nonBrepSlabHnds.Count > 0) { HostObjectExporter.ExportHostObjectMaterials(exporterIFC, floorElement, nonBrepSlabHnds, geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, false, type); } if (brepSlabHnds.Count > 0) { HostObjectExporter.ExportHostObjectMaterials(exporterIFC, floorElement, brepSlabHnds, geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, true, type); } } } tr.Commit(); return; } }
/// <summary> /// Exports an element as building element proxy. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <returns>True if exported successfully, false otherwise.</returns> public static bool Export(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { bool exported = false; if (element == null || geometryElement == null) return exported; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { exported = (ExportBuildingElementProxy(exporterIFC, element, geometryElement, productWrapper) != null); if (exported) tr.Commit(); } return exported; }
/// <summary> /// Export the individual part (IfcBuildingElementPart). /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="partElement">The part element to export.</param> /// <param name="geometryElement">The geometry of part.</param> /// <param name="productWrapper">The ProductWrapper object.</param> public static void ExportPart(ExporterIFC exporterIFC, Element partElement, ProductWrapper productWrapper, PlacementSetter placementSetter, IFCAnyHandle originalPlacement, IFCRange range, IFCExtrusionAxes ifcExtrusionAxes, Element hostElement, ElementId overrideLevelId, bool asBuildingElement) { if (!ElementFilteringUtil.IsElementVisible(partElement)) { return; } Part part = partElement as Part; if (part == null) { return; } PlacementSetter standalonePlacementSetter = null; bool standaloneExport = hostElement == null && !asBuildingElement; ElementId partExportLevel = null; if (standaloneExport || asBuildingElement) { partExportLevel = partElement.LevelId; } else { if (part.OriginalCategoryId != hostElement.Category.Id) { return; } partExportLevel = hostElement.LevelId; } if (overrideLevelId != null) { partExportLevel = overrideLevelId; } if (ExporterCacheManager.PartExportedCache.HasExported(partElement.Id, partExportLevel)) { return; } Options options = GeometryUtil.GetIFCExportGeometryOptions(); View ownerView = partElement.Document.GetElement(partElement.OwnerViewId) as View; if (ownerView != null) { options.View = ownerView; } GeometryElement geometryElement = partElement.get_Geometry(options); if (geometryElement == null) { return; } try { IFCFile file = exporterIFC.GetFile(); using (IFCTransaction transaction = new IFCTransaction(file)) { IFCAnyHandle partPlacement = null; if (standaloneExport || asBuildingElement) { Transform orientationTrf = Transform.Identity; standalonePlacementSetter = PlacementSetter.Create(exporterIFC, partElement, null, orientationTrf, partExportLevel); partPlacement = standalonePlacementSetter.LocalPlacement; } else { partPlacement = ExporterUtil.CreateLocalPlacement(file, originalPlacement, null); } bool validRange = (range != null && !MathUtil.IsAlmostZero(range.Start - range.End)); SolidMeshGeometryInfo solidMeshInfo; if (validRange) { solidMeshInfo = GeometryUtil.GetSplitClippedSolidMeshGeometry(geometryElement, range); if (solidMeshInfo.GetSolids().Count == 0 && solidMeshInfo.GetMeshes().Count == 0) { return; } } else { solidMeshInfo = GeometryUtil.GetSplitSolidMeshGeometry(geometryElement); } using (IFCExtrusionCreationData extrusionCreationData = new IFCExtrusionCreationData()) { extrusionCreationData.SetLocalPlacement(partPlacement); extrusionCreationData.ReuseLocalPlacement = false; extrusionCreationData.PossibleExtrusionAxes = ifcExtrusionAxes; IList <Solid> solids = solidMeshInfo.GetSolids(); IList <Mesh> meshes = solidMeshInfo.GetMeshes(); ElementId catId = CategoryUtil.GetSafeCategoryId(partElement); ElementId hostCatId = CategoryUtil.GetSafeCategoryId(hostElement); BodyData bodyData = null; BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); if (solids.Count > 0 || meshes.Count > 0) { bodyData = BodyExporter.ExportBody(exporterIFC, partElement, catId, ElementId.InvalidElementId, solids, meshes, bodyExporterOptions, extrusionCreationData); } else { IList <GeometryObject> geomlist = new List <GeometryObject>(); geomlist.Add(geometryElement); bodyData = BodyExporter.ExportBody(exporterIFC, partElement, catId, ElementId.InvalidElementId, geomlist, bodyExporterOptions, extrusionCreationData); } IFCAnyHandle bodyRep = bodyData.RepresentationHnd; if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep)) { extrusionCreationData.ClearOpenings(); return; } IList <IFCAnyHandle> representations = new List <IFCAnyHandle>(); representations.Add(bodyRep); IFCAnyHandle boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, geometryElement, Transform.Identity); if (boundingBoxRep != null) { representations.Add(boundingBoxRep); } IFCAnyHandle prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, representations); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string partGUID = GUIDUtil.CreateGUID(partElement); string partName = NamingUtil.GetNameOverride(partElement, NamingUtil.GetIFCName(partElement)); string partDescription = NamingUtil.GetDescriptionOverride(partElement, null); string partObjectType = NamingUtil.GetObjectTypeOverride(partElement, NamingUtil.CreateIFCObjectName(exporterIFC, partElement)); string partTag = NamingUtil.GetTagOverride(partElement, NamingUtil.CreateIFCElementId(partElement)); IFCAnyHandle ifcPart = null; if (!asBuildingElement) { ifcPart = IFCInstanceExporter.CreateBuildingElementPart(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag); } else { string ifcEnumType = null; IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, hostElement, out ifcEnumType); string defaultValue = null; // This replicates old functionality before IFC4 addition, where the default for slab was "FLOOR". // Really the export layer table should be fixed for this case. if (string.IsNullOrWhiteSpace(ifcEnumType) && hostCatId == new ElementId(BuiltInCategory.OST_Floors)) { ifcEnumType = "FLOOR"; } ifcEnumType = IFCValidateEntry.GetValidIFCType(hostElement, ifcEnumType, defaultValue); switch (exportType) { case IFCExportType.IfcColumnType: ifcPart = IFCInstanceExporter.CreateColumn(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag, ifcEnumType); break; case IFCExportType.IfcCovering: ifcPart = IFCInstanceExporter.CreateCovering(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag, ifcEnumType); break; case IFCExportType.IfcFooting: ifcPart = IFCInstanceExporter.CreateFooting(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag, ifcEnumType); break; case IFCExportType.IfcPile: ifcPart = IFCInstanceExporter.CreatePile(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag, ifcEnumType, null); break; case IFCExportType.IfcRoof: ifcPart = IFCInstanceExporter.CreateRoof(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag, ifcEnumType); break; case IFCExportType.IfcSlab: ifcPart = IFCInstanceExporter.CreateSlab(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag, ifcEnumType); break; case IFCExportType.IfcWall: ifcPart = IFCInstanceExporter.CreateWall(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag, ifcEnumType); break; default: ifcPart = IFCInstanceExporter.CreateBuildingElementProxy(file, partGUID, ownerHistory, partName, partDescription, partObjectType, extrusionCreationData.GetLocalPlacement(), prodRep, partTag, null); break; } } bool containedInLevel = (standaloneExport || asBuildingElement); PlacementSetter whichPlacementSetter = containedInLevel ? standalonePlacementSetter : placementSetter; productWrapper.AddElement(partElement, ifcPart, whichPlacementSetter, extrusionCreationData, containedInLevel); //Add the exported part to exported cache. TraceExportedParts(partElement, partExportLevel, standaloneExport || asBuildingElement ? ElementId.InvalidElementId : hostElement.Id); CategoryUtil.CreateMaterialAssociations(exporterIFC, ifcPart, bodyData.MaterialIds); transaction.Commit(); } } } finally { if (standalonePlacementSetter != null) { standalonePlacementSetter.Dispose(); } } }
/// <summary> /// Exports a MEP family instance. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="element"> /// The element. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The IFCProductWrapper. /// </param> public static void Export(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, IFCProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { string ifcEnumType; IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, element, out ifcEnumType); using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, element)) { IFCAnyHandle localPlacementToUse = setter.GetPlacement(); using (IFCExtrusionCreationData extraParams = new IFCExtrusionCreationData()) { ElementId catId = CategoryUtil.GetSafeCategoryId(element); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); IFCAnyHandle productRepresentation = RepresentationUtil.CreateBRepProductDefinitionShape(element.Document.Application, exporterIFC, element, catId, geometryElement, bodyExporterOptions, null, extraParams); if (IFCAnyHandleUtil.IsNullOrHasNoValue(productRepresentation)) { extraParams.ClearOpenings(); return; } IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); ElementId typeId = element.GetTypeId(); ElementType type = element.Document.GetElement(typeId) as ElementType; FamilyTypeInfo currentTypeInfo = ExporterCacheManager.TypeObjectsCache.Find(typeId, false); bool found = currentTypeInfo.IsValid(); if (!found) { string typeGUID = ExporterIFCUtils.CreateGUID(type); string origTypeName = exporterIFC.GetName(); string typeName = NamingUtil.GetNameOverride(type, origTypeName); string typeObjectType = NamingUtil.CreateIFCObjectName(exporterIFC, type); string applicableOccurance = NamingUtil.GetObjectTypeOverride(type, typeObjectType); string typeDescription = NamingUtil.GetDescriptionOverride(type, null); string typeElemId = NamingUtil.CreateIFCElementId(type); HashSet<IFCAnyHandle> propertySetsOpt = new HashSet<IFCAnyHandle>(); IList<IFCAnyHandle> repMapListOpt = new List<IFCAnyHandle>(); IFCAnyHandle styleHandle = FamilyExporterUtil.ExportGenericType(file, exportType, ifcEnumType, typeGUID, ownerHistory, typeName, typeDescription, applicableOccurance, propertySetsOpt, repMapListOpt, typeElemId, typeName, element, type); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(styleHandle)) { currentTypeInfo.Style = styleHandle; ExporterCacheManager.TypeObjectsCache.Register(typeId, false, currentTypeInfo); } } string instanceGUID = ExporterIFCUtils.CreateGUID(element); string origInstanceName = exporterIFC.GetName(); string instanceName = NamingUtil.GetNameOverride(element, origInstanceName); string objectType = NamingUtil.CreateIFCObjectName(exporterIFC, element); string instanceObjectType = NamingUtil.GetObjectTypeOverride(element, objectType); string instanceDescription = NamingUtil.GetDescriptionOverride(element, null); string instanceElemId = NamingUtil.CreateIFCElementId(element); bool roomRelated = !FamilyExporterUtil.IsDistributionFlowElementSubType(exportType); ElementId roomId = ElementId.InvalidElementId; if (roomRelated) { roomId = setter.UpdateRoomRelativeCoordinates(element, out localPlacementToUse); } IFCAnyHandle instanceHandle = null; if (FamilyExporterUtil.IsFurnishingElementSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateFurnishingElement(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsDistributionFlowElementSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateDistributionFlowElement(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsEnergyConversionDeviceSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateEnergyConversionDevice(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsFlowFittingSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateFlowFitting(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsFlowMovingDeviceSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateFlowMovingDevice(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsFlowSegmentSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateFlowSegment(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsFlowStorageDeviceSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateFlowStorageDevice(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsFlowTerminalSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateFlowTerminal(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsFlowTreatmentDeviceSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateFlowTreatmentDevice(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } else if (FamilyExporterUtil.IsFlowControllerSubType(exportType)) { instanceHandle = IFCInstanceExporter.CreateFlowController(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacementToUse, productRepresentation, instanceElemId); } if (IFCAnyHandleUtil.IsNullOrHasNoValue(instanceHandle)) return; if (roomId != ElementId.InvalidElementId) { exporterIFC.RelateSpatialElement(roomId, instanceHandle); productWrapper.AddElement(instanceHandle, setter, extraParams, false); } else { productWrapper.AddElement(instanceHandle, setter, extraParams, LevelUtil.AssociateElementToLevel(element)); } OpeningUtil.CreateOpeningsIfNecessary(instanceHandle, element, extraParams, exporterIFC, localPlacementToUse, setter, productWrapper); if (currentTypeInfo.IsValid()) ExporterCacheManager.TypeRelationsCache.Add(currentTypeInfo.Style, instanceHandle); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, productWrapper); ExporterCacheManager.MEPCache.Register(element, instanceHandle); tr.Commit(); } } } }
/// <summary> /// Exports a roof as a container of multiple roof slabs. Returns the handle, if successful. /// </summary> /// <param name="exporterIFC">The exporter.</param> /// <param name="ifcEnumType">The roof type.</param> /// <param name="element">The roof element.</param> /// <param name="geometry">The geometry of the element.</param> /// <param name="productWrapper">The product wrapper.</param> /// <returns>The roof handle.</returns> public static IFCAnyHandle ExportRoofAsContainer(ExporterIFC exporterIFC, string ifcEnumType, Element element, GeometryElement geometry, ProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); if (!(element is ExtrusionRoof) && !(element is FootPrintRoof)) { return(null); } using (IFCTransaction transaction = new IFCTransaction(file)) { using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element)) { IFCAnyHandle localPlacement = setter.LocalPlacement; RoofComponents roofComponents = null; try { roofComponents = ExporterIFCUtils.GetRoofComponents(exporterIFC, element as RoofBase); } catch { return(null); } if (roofComponents == null) { return(null); } try { using (IFCExtrusionCreationData extrusionCreationData = new IFCExtrusionCreationData()) { IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); extrusionCreationData.SetLocalPlacement(localPlacement); extrusionCreationData.ReuseLocalPlacement = true; using (TransformSetter trfSetter = TransformSetter.Create()) { IList <GeometryObject> geometryList = new List <GeometryObject>(); geometryList.Add(geometry); trfSetter.InitializeFromBoundingBox(exporterIFC, geometryList, extrusionCreationData); IFCAnyHandle prodRepHnd = null; string elementGUID = GUIDUtil.CreateGUID(element); string elementName = NamingUtil.GetIFCName(element); string elementDescription = NamingUtil.GetDescriptionOverride(element, null); string elementObjectType = NamingUtil.GetObjectTypeOverride(element, exporterIFC.GetFamilyName()); string elementId = NamingUtil.CreateIFCElementId(element); string roofType = IFCValidateEntry.GetValidIFCType(element, ifcEnumType); IFCAnyHandle roofHandle = IFCInstanceExporter.CreateRoof(file, elementGUID, ownerHistory, elementName, elementDescription, elementObjectType, localPlacement, prodRepHnd, elementId, roofType); IList <IFCAnyHandle> elementHandles = new List <IFCAnyHandle>(); elementHandles.Add(roofHandle); //only thing supported right now. XYZ extrusionDir = new XYZ(0, 0, 1); ElementId catId = CategoryUtil.GetSafeCategoryId(element); IList <CurveLoop> roofCurveloops = roofComponents.GetCurveLoops(); IList <XYZ> planeDirs = roofComponents.GetPlaneDirections(); IList <XYZ> planeOrigins = roofComponents.GetPlaneOrigins(); IList <Face> loopFaces = roofComponents.GetLoopFaces(); double scaledDepth = roofComponents.ScaledDepth; IList <double> areas = roofComponents.GetAreasOfCurveLoops(); IList <IFCAnyHandle> slabHandles = new List <IFCAnyHandle>(); using (IFCExtrusionCreationData slabExtrusionCreationData = new IFCExtrusionCreationData()) { slabExtrusionCreationData.SetLocalPlacement(extrusionCreationData.GetLocalPlacement()); slabExtrusionCreationData.ReuseLocalPlacement = false; slabExtrusionCreationData.ForceOffset = true; for (int numLoop = 0; numLoop < roofCurveloops.Count; numLoop++) { trfSetter.InitializeFromBoundingBox(exporterIFC, geometryList, slabExtrusionCreationData); Plane plane = new Plane(planeDirs[numLoop], planeOrigins[numLoop]); IList <CurveLoop> curveLoops = new List <CurveLoop>(); curveLoops.Add(roofCurveloops[numLoop]); double slope = Math.Abs(planeDirs[numLoop].Z); double scaledExtrusionDepth = scaledDepth * slope; IFCAnyHandle shapeRep = ExtrusionExporter.CreateExtrudedSolidFromCurveLoop(exporterIFC, null, curveLoops, plane, extrusionDir, scaledExtrusionDepth); if (IFCAnyHandleUtil.IsNullOrHasNoValue(shapeRep)) { return(null); } ElementId matId = HostObjectExporter.GetFirstLayerMaterialId(element as HostObject); BodyExporter.CreateSurfaceStyleForRepItem(exporterIFC, element.Document, shapeRep, matId); HashSet <IFCAnyHandle> bodyItems = new HashSet <IFCAnyHandle>(); bodyItems.Add(shapeRep); shapeRep = RepresentationUtil.CreateSweptSolidRep(exporterIFC, element, catId, exporterIFC.Get3DContextHandle("Body"), bodyItems, null); IList <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>(); shapeReps.Add(shapeRep); IFCAnyHandle repHnd = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps); // Allow support for up to 256 named IfcSlab components, as defined in IFCSubElementEnums.cs. string slabGUID = (numLoop < 256) ? GUIDUtil.CreateSubElementGUID(element, (int)IFCRoofSubElements.RoofSlabStart + numLoop) : GUIDUtil.CreateGUID(); IFCAnyHandle slabPlacement = ExporterUtil.CreateLocalPlacement(file, slabExtrusionCreationData.GetLocalPlacement(), null); IFCAnyHandle slabHnd = IFCInstanceExporter.CreateSlab(file, slabGUID, ownerHistory, elementName, elementDescription, elementObjectType, slabPlacement, repHnd, elementId, "ROOF"); //slab quantities slabExtrusionCreationData.ScaledLength = scaledExtrusionDepth; slabExtrusionCreationData.ScaledArea = UnitUtil.ScaleArea(areas[numLoop]); slabExtrusionCreationData.ScaledOuterPerimeter = UnitUtil.ScaleLength(curveLoops[0].GetExactLength()); slabExtrusionCreationData.Slope = UnitUtil.ScaleAngle(Math.Acos(Math.Abs(planeDirs[numLoop].Z))); productWrapper.AddElement(null, slabHnd, setter, slabExtrusionCreationData, false); elementHandles.Add(slabHnd); slabHandles.Add(slabHnd); } } productWrapper.AddElement(element, roofHandle, setter, extrusionCreationData, true); ExporterUtil.RelateObjects(exporterIFC, null, roofHandle, slabHandles); OpeningUtil.AddOpeningsToElement(exporterIFC, elementHandles, roofCurveloops, element, null, roofComponents.ScaledDepth, null, setter, localPlacement, productWrapper); transaction.Commit(); return(roofHandle); } } } finally { exporterIFC.ClearFaceWithElementHandleMap(); } } } }
/// <summary> /// Base implementation to export IFC site object. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="document"> /// The Revit document. /// </param> /// <param name="element"> /// The element. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The IFCProductWrapper. /// </param> private static void ExportSiteBase(ExporterIFC exporterIFC, Document document, Element element, GeometryElement geometryElement, IFCProductWrapper productWrapper) { IFCAnyHandle siteHandle = exporterIFC.GetSite(); int numSiteElements = (!IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle) ? 1 : 0); if (element == null && (numSiteElements != 0)) return; Document doc = document; if (doc == null) { if (element != null) doc = element.Document; else throw new ArgumentException("Both document and element are null."); } IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { IFCAnyHandle siteRepresentation = null; if (element != null) { // It would be possible that they actually represent several different sites with different buildings, // but until we have a concept of a building in Revit, we have to assume 0-1 sites, 1 building. bool appendedToSite = false; if (!IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle)) { IList<IFCAnyHandle> representations = IFCAnyHandleUtil.GetProductRepresentations(siteHandle); if (representations.Count > 0) { IFCAnyHandle bodyRep = representations[0]; IFCAnyHandle boundaryRep = null; if (representations.Count > 1) boundaryRep = representations[1]; siteRepresentation = RepresentationUtil.CreateSurfaceProductDefinitionShape(exporterIFC, element, geometryElement, true, true, ref bodyRep, ref boundaryRep); appendedToSite = true; } } if (!appendedToSite) { siteRepresentation = RepresentationUtil.CreateSurfaceProductDefinitionShape(exporterIFC, element, geometryElement, true, true); } } List<int> latitude = new List<int>(); List<int> longitude = new List<int>(); ProjectLocation projLocation = doc.ActiveProjectLocation; IFCAnyHandle relativePlacement = null; double elevation = 0.0; if (projLocation != null) { double latitudeInDeg = projLocation.SiteLocation.Latitude * 180 / Math.PI; double longitudeInDeg = projLocation.SiteLocation.Longitude * 180 / Math.PI; int latDeg = ((int)latitudeInDeg); latitudeInDeg -= latDeg; latitudeInDeg *= 60; int latMin = ((int)latitudeInDeg); latitudeInDeg -= latMin; latitudeInDeg *= 60; int latSec = ((int)latitudeInDeg); latitudeInDeg -= latSec; latitudeInDeg *= 1000000; int latFracSec = ((int)latitudeInDeg); latitude.Add(latDeg); latitude.Add(latMin); latitude.Add(latSec); if (!exporterIFC.ExportAs2x2) latitude.Add(latFracSec); int longDeg = ((int)longitudeInDeg); longitudeInDeg -= longDeg; longitudeInDeg *= 60; int longMin = ((int)longitudeInDeg); longitudeInDeg -= longMin; longitudeInDeg *= 60; int longSec = ((int)longitudeInDeg); longitudeInDeg -= longSec; longitudeInDeg *= 1000000; int longFracSec = ((int)longitudeInDeg); longitude.Add(longDeg); longitude.Add(longMin); longitude.Add(longSec); if (!exporterIFC.ExportAs2x2) longitude.Add(longFracSec); Transform siteSharedCoordinatesTrf = projLocation.GetTransform().Inverse; if (!siteSharedCoordinatesTrf.IsIdentity) { XYZ orig = siteSharedCoordinatesTrf.Origin; orig = orig.Multiply(exporterIFC.LinearScale); relativePlacement = ExporterUtil.CreateAxis2Placement3D(file, orig, siteSharedCoordinatesTrf.BasisZ, siteSharedCoordinatesTrf.BasisX); } } // Get elevation for site. elevation = -LevelUtil.GetReferenceHeightForRelativeElevation(doc) * exporterIFC.LinearScale; if (IFCAnyHandleUtil.IsNullOrHasNoValue(relativePlacement)) relativePlacement = ExporterUtil.CreateAxis2Placement3D(file); IFCAnyHandle localPlacement = IFCInstanceExporter.CreateLocalPlacement(file, null, relativePlacement); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string objectType = NamingUtil.CreateIFCObjectName(exporterIFC, element); if (element != null) { if (IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle)) { string instanceGUID = ExporterIFCUtils.CreateGUID(element); string origInstanceName = exporterIFC.GetName(); string instanceName = NamingUtil.GetNameOverride(element, origInstanceName); string instanceDescription = NamingUtil.GetDescriptionOverride(element, null); string instanceObjectType = NamingUtil.GetObjectTypeOverride(element, objectType); string instanceElemId = NamingUtil.CreateIFCElementId(element); siteHandle = IFCInstanceExporter.CreateSite(file, instanceGUID, ownerHistory, instanceName, instanceDescription, instanceObjectType, localPlacement, siteRepresentation, null, Toolkit.IFCElementComposition.Element, latitude, longitude, elevation, null, null); } } else { // don't bother if we have nothing in the site whatsoever. if ((latitude.Count == 0 || longitude.Count == 0) && IFCAnyHandleUtil.IsNullOrHasNoValue(relativePlacement)) return; string defaultSiteName = "Default"; siteHandle = IFCInstanceExporter.CreateSite(file, ExporterIFCUtils.CreateProjectLevelGUID(doc, IFCProjectLevelGUIDType.Site), ownerHistory, defaultSiteName, null, objectType, localPlacement, null, null, Toolkit.IFCElementComposition.Element, latitude, longitude, elevation, null, null); } productWrapper.AddSite(siteHandle); exporterIFC.SetSite(siteHandle); tr.Commit(); } }
/// <summary> /// Export the roof to IfcRoof containing its parts. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The roof element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void ExportRoofAsParts(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, ProductWrapper productWrapper) { IFCFile file = exporterIFC.GetFile(); using (IFCTransaction transaction = new IFCTransaction(file)) { using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element)) { IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); IFCAnyHandle localPlacement = setter.LocalPlacement; IFCAnyHandle prodRepHnd = null; string elementGUID = GUIDUtil.CreateGUID(element); string elementName = NamingUtil.GetNameOverride(element, NamingUtil.GetIFCName(element)); string elementDescription = NamingUtil.GetDescriptionOverride(element, null); string elementObjectType = NamingUtil.GetObjectTypeOverride(element, exporterIFC.GetFamilyName()); string elementTag = NamingUtil.GetTagOverride(element, NamingUtil.CreateIFCElementId(element)); //need to convert the string to enum string ifcEnumType = ExporterUtil.GetIFCTypeFromExportTable(exporterIFC, element); ifcEnumType = IFCValidateEntry.GetValidIFCType(element, ifcEnumType); IFCAnyHandle roofHandle = IFCInstanceExporter.CreateRoof(file, elementGUID, ownerHistory, elementName, elementDescription, elementObjectType, localPlacement, prodRepHnd, elementTag, ifcEnumType); // Export the parts PartExporter.ExportHostPart(exporterIFC, element, roofHandle, productWrapper, setter, localPlacement, null); productWrapper.AddElement(element, roofHandle, setter, null, true); transaction.Commit(); } } }
/// <summary> /// Exports a family instance as standard element. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element to be exported.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="familyType">The export type.</param> /// <param name="ifcEnumTypeString">The string value represents the IFC type.</param> /// <param name="productWrapper">The ProductWrapper.</param> /// <returns>True if the family instance was exported, false otherwise.</returns> static bool ExportFamilyInstanceAsStandardElement(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement, IFCExportType familyType, string ifcEnumTypeString, ProductWrapper productWrapper) { switch (familyType) { // These entities don't get exported as a mapped instance. As such, we export them using // the standard methods. // standard building elements case IFCExportType.ExportBeam: BeamExporter.ExportBeam(exporterIFC, element, geometryElement, productWrapper); return true; case IFCExportType.ExportFooting: FootingExporter.ExportFooting(exporterIFC, element, geometryElement, ifcEnumTypeString, productWrapper); return true; case IFCExportType.ExportCovering: CeilingExporter.ExportCovering(exporterIFC, element, geometryElement, ifcEnumTypeString, productWrapper); return true; case IFCExportType.ExportPile: PileExporter.ExportPile(exporterIFC, element, geometryElement, ifcEnumTypeString, productWrapper); return true; case IFCExportType.ExportRamp: RampExporter.ExportRamp(exporterIFC, ifcEnumTypeString, element, geometryElement, 1, productWrapper); return true; case IFCExportType.ExportRailing: if (ExporterCacheManager.RailingCache.Contains(element.Id)) { // Don't export this object if it is part of a parent railing. if (!ExporterCacheManager.RailingSubElementCache.Contains(element.Id)) RailingExporter.ExportRailing(exporterIFC, element, geometryElement, ifcEnumTypeString, productWrapper); } else { ExporterCacheManager.RailingCache.Add(element.Id); } return true; case IFCExportType.ExportRoof: RoofExporter.ExportRoof(exporterIFC, ifcEnumTypeString, element, geometryElement, productWrapper); return true; case IFCExportType.ExportSlab: FloorExporter.ExportFloor(exporterIFC, element, geometryElement, ifcEnumTypeString, productWrapper, false); return true; case IFCExportType.ExportStair: StairsExporter.ExportStairAsSingleGeometry(exporterIFC, ifcEnumTypeString, element, geometryElement, 1, productWrapper); return true; case IFCExportType.ExportWall: WallExporter.ExportWall(exporterIFC, element, geometryElement, productWrapper); return true; default: return false; } }
/// <summary> /// Exports a roof to IfcRoof. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="ifcEnumType">The roof type.</param> /// <param name="roof">The roof element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void ExportRoof(ExporterIFC exporterIFC, string ifcEnumType, Element roof, GeometryElement geometryElement, ProductWrapper productWrapper) { if (roof == null || geometryElement == null) { return; } IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, roof)) { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { // If the roof is an in-place family, we will allow any arbitrary orientation. While this may result in some // in-place "cubes" exporting with the wrong direction, it is unlikely that an in-place family would be // used for this reason in the first place. ecData.PossibleExtrusionAxes = (roof is FamilyInstance) ? IFCExtrusionAxes.TryXYZ : IFCExtrusionAxes.TryZ; ecData.AreInnerRegionsOpenings = true; ecData.SetLocalPlacement(placementSetter.LocalPlacement); ElementId categoryId = CategoryUtil.GetSafeCategoryId(roof); BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true); BodyData bodyData; IFCAnyHandle representation = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, roof, categoryId, geometryElement, bodyExporterOptions, null, ecData, out bodyData); if (IFCAnyHandleUtil.IsNullOrHasNoValue(representation)) { ecData.ClearOpenings(); return; } bool exportSlab = ecData.ScaledLength > MathUtil.Eps(); string guid = GUIDUtil.CreateGUID(roof); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); string roofName = NamingUtil.GetNameOverride(roof, NamingUtil.GetIFCName(roof)); string roofDescription = NamingUtil.GetDescriptionOverride(roof, null); string roofObjectType = NamingUtil.GetObjectTypeOverride(roof, NamingUtil.CreateIFCObjectName(exporterIFC, roof)); IFCAnyHandle localPlacement = ecData.GetLocalPlacement(); string elementTag = NamingUtil.GetTagOverride(roof, NamingUtil.CreateIFCElementId(roof)); string roofType = GetIFCRoofType(ifcEnumType); roofType = IFCValidateEntry.GetValidIFCType(roof, ifcEnumType); IFCAnyHandle roofHnd = IFCInstanceExporter.CreateRoof(file, guid, ownerHistory, roofName, roofDescription, roofObjectType, localPlacement, exportSlab ? null : representation, elementTag, roofType); productWrapper.AddElement(roof, roofHnd, placementSetter.LevelInfo, ecData, true); // will export its host object materials later if it is a roof if (!(roof is RoofBase)) { CategoryUtil.CreateMaterialAssociations(exporterIFC, roofHnd, bodyData.MaterialIds); } if (exportSlab) { string slabGUID = GUIDUtil.CreateSubElementGUID(roof, (int)IFCRoofSubElements.RoofSlabStart); string slabName = roofName + ":1"; IFCAnyHandle slabLocalPlacementHnd = ExporterUtil.CopyLocalPlacement(file, localPlacement); IFCAnyHandle slabHnd = IFCInstanceExporter.CreateSlab(file, slabGUID, ownerHistory, slabName, roofDescription, roofObjectType, slabLocalPlacementHnd, representation, elementTag, "ROOF"); Transform offsetTransform = (bodyData != null) ? bodyData.OffsetTransform : Transform.Identity; OpeningUtil.CreateOpeningsIfNecessary(slabHnd, roof, ecData, offsetTransform, exporterIFC, slabLocalPlacementHnd, placementSetter, productWrapper); ExporterUtil.RelateObject(exporterIFC, roofHnd, slabHnd); productWrapper.AddElement(null, slabHnd, placementSetter.LevelInfo, ecData, false); CategoryUtil.CreateMaterialAssociations(exporterIFC, slabHnd, bodyData.MaterialIds); } } tr.Commit(); } } }
/// <summary> /// Exports a curve element to IFC curve annotation. /// </summary> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="curveElement"> /// The curve element to be exported. /// </param> /// <param name="geometryElement"> /// The geometry element. /// </param> /// <param name="productWrapper"> /// The ProductWrapper. /// </param> public static void ExportCurveElement(ExporterIFC exporterIFC, CurveElement curveElement, GeometryElement geometryElement, ProductWrapper productWrapper) { if (geometryElement == null || !ShouldCurveElementBeExported(curveElement)) return; SketchPlane sketchPlane = curveElement.SketchPlane; if (sketchPlane == null) return; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction transaction = new IFCTransaction(file)) { using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, curveElement)) { IFCAnyHandle localPlacement = setter.LocalPlacement; IFCAnyHandle axisPlacement = GeometryUtil.GetRelativePlacementFromLocalPlacement(localPlacement); Plane planeSK = sketchPlane.GetPlane(); XYZ projDir = planeSK.Normal; XYZ origin = planeSK.Origin; bool useOffsetTrf = false; if (projDir.IsAlmostEqualTo(XYZ.BasisZ)) { XYZ offset = XYZ.BasisZ * setter.Offset; origin -= offset; } else useOffsetTrf = true; Plane plane = new Plane(planeSK.XVec, planeSK.YVec, origin); IFCGeometryInfo info = IFCGeometryInfo.CreateCurveGeometryInfo(exporterIFC, plane, projDir, false); if (useOffsetTrf) { XYZ offsetOrig = -XYZ.BasisZ * setter.Offset; Transform trf = Transform.CreateTranslation(offsetOrig); ExporterIFCUtils.CollectGeometryInfo(exporterIFC, info, geometryElement, XYZ.Zero, false, trf); } else { ExporterIFCUtils.CollectGeometryInfo(exporterIFC, info, geometryElement, XYZ.Zero, false); } IList<IFCAnyHandle> curves = info.GetCurves(); if (curves.Count != 1) { throw new Exception("IFC: expected 1 curve when export curve element."); } HashSet<IFCAnyHandle> curveSet = new HashSet<IFCAnyHandle>(curves); IFCAnyHandle repItemHnd = IFCInstanceExporter.CreateGeometricCurveSet(file, curveSet); IFCAnyHandle curveStyle = file.CreateStyle(exporterIFC, repItemHnd); CurveAnnotationCache annotationCache = ExporterCacheManager.CurveAnnotationCache; IFCAnyHandle curveAnno = annotationCache.GetAnnotation(sketchPlane.Id, curveStyle); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(curveAnno)) { AddCurvesToAnnotation(curveAnno, curves); } else { curveAnno = CreateCurveAnnotation(exporterIFC, curveElement, curveElement.Category.Id, sketchPlane.Id, plane, curveStyle, setter, localPlacement, repItemHnd); productWrapper.AddAnnotation(curveAnno, setter.LevelInfo, true); annotationCache.AddAnnotation(sketchPlane.Id, curveStyle, curveAnno); } } transaction.Commit(); } }
/// <summary> /// Exports a Rebar Coupler, /// </summary> /// <param name="exporterIFC">The exporter.</param> /// <param name="coupler">The RebarCoupler element.</param> /// <param name="productWrapper">The product wrapper.</param> public static void ExportCoupler(ExporterIFC exporterIFC, RebarCoupler coupler, ProductWrapper productWrapper) { if (coupler == null) { return; } FamilySymbol familySymbol = ExporterCacheManager.Document.GetElement(coupler.GetTypeId()) as FamilySymbol; if (familySymbol == null) { return; } // Check the intended IFC entity or type name is in the exclude list specified in the UI Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcMechanicalFastener; if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum)) { return; } ElementId categoryId = CategoryUtil.GetSafeCategoryId(coupler); IFCFile file = exporterIFC.GetFile(); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; Options options = GeometryUtil.GetIFCExportGeometryOptions();; string ifcEnumType; IFCExportInfoPair exportType = ExporterUtil.GetProductExportType(exporterIFC, coupler, out ifcEnumType); using (IFCTransaction tr = new IFCTransaction(file)) { FamilyTypeInfo currentTypeInfo = ExporterCacheManager.FamilySymbolToTypeInfoCache.Find(coupler.GetTypeId(), false, exportType); bool found = currentTypeInfo.IsValid(); if (!found) { string typeObjectType = NamingUtil.CreateIFCObjectName(exporterIFC, familySymbol); HashSet <IFCAnyHandle> propertySetsOpt = new HashSet <IFCAnyHandle>(); GeometryElement exportGeometry = familySymbol.get_Geometry(options); BodyData bodyData = null; BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow); bodyData = BodyExporter.ExportBody(exporterIFC, coupler, categoryId, ElementId.InvalidElementId, exportGeometry, bodyExporterOptions, null); List <IFCAnyHandle> repMap = new List <IFCAnyHandle>(); IFCAnyHandle origin = ExporterUtil.CreateAxis2Placement3D(file);; repMap.Add(IFCInstanceExporter.CreateRepresentationMap(file, origin, bodyData.RepresentationHnd)); IFCAnyHandle styleHandle = FamilyExporterUtil.ExportGenericType(exporterIFC, exportType, ifcEnumType, propertySetsOpt, repMap, coupler, familySymbol); productWrapper.RegisterHandleWithElementType(familySymbol, exportType, styleHandle, propertySetsOpt); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(styleHandle)) { currentTypeInfo.Style = styleHandle; ExporterCacheManager.FamilySymbolToTypeInfoCache.Register(coupler.GetTypeId(), false, exportType, currentTypeInfo); } } int nCouplerQuantity = coupler.GetCouplerQuantity(); if (nCouplerQuantity <= 0) { return; } ISet <IFCAnyHandle> createdRebarCouplerHandles = new HashSet <IFCAnyHandle>(); string origInstanceName = NamingUtil.GetNameOverride(coupler, NamingUtil.GetIFCName(coupler)); for (int idx = 0; idx < nCouplerQuantity; idx++) { string instanceGUID = GUIDUtil.CreateSubElementGUID(coupler, idx); IFCAnyHandle style = currentTypeInfo.Style; if (IFCAnyHandleUtil.IsNullOrHasNoValue(style)) { return; } IList <IFCAnyHandle> repMapList = GeometryUtil.GetRepresentationMaps(style); if (repMapList == null) { return; } if (repMapList.Count == 0) { return; } IList <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>(); IFCAnyHandle contextOfItems3d = exporterIFC.Get3DContextHandle("Body"); ISet <IFCAnyHandle> representations = new HashSet <IFCAnyHandle>(); representations.Add(ExporterUtil.CreateDefaultMappedItem(file, repMapList[0], XYZ.Zero)); IFCAnyHandle shapeRep = RepresentationUtil.CreateBodyMappedItemRep(exporterIFC, coupler, categoryId, contextOfItems3d, representations); shapeReps.Add(shapeRep); IFCAnyHandle productRepresentation = IFCInstanceExporter.CreateProductDefinitionShape(exporterIFC.GetFile(), null, null, shapeReps); Transform trf = coupler.GetCouplerPositionTransform(idx); using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, coupler, trf, null)) { IFCAnyHandle instanceHandle = null; IFCExportInfoPair exportMechFastener = new IFCExportInfoPair(IFCEntityType.IfcMechanicalFastener, ifcEnumType); instanceHandle = IFCInstanceExporter.CreateGenericIFCEntity(exportMechFastener, exporterIFC, coupler, instanceGUID, ownerHistory, setter.LocalPlacement, productRepresentation); string instanceName = NamingUtil.GetNameOverride(instanceHandle, coupler, origInstanceName + ": " + idx); IFCAnyHandleUtil.OverrideNameAttribute(instanceHandle, instanceName); if (ExporterCacheManager.ExportOptionsCache.ExportAs4) { // In IFC4 NominalDiameter and NominalLength attributes have been deprecated. PredefinedType attribute was added. IFCAnyHandleUtil.SetAttribute(instanceHandle, "PredefinedType", Revit.IFC.Export.Toolkit.IFC4.IFCMechanicalFastenerType.USERDEFINED); } else { IFCAnyHandleUtil.SetAttribute(instanceHandle, "NominalDiameter", familySymbol.get_Parameter(BuiltInParameter.COUPLER_WIDTH).AsDouble()); IFCAnyHandleUtil.SetAttribute(instanceHandle, "NominalLength", familySymbol.get_Parameter(BuiltInParameter.COUPLER_LENGTH).AsDouble()); } createdRebarCouplerHandles.Add(instanceHandle); productWrapper.AddElement(coupler, instanceHandle, setter, null, true, exportType); } } string couplerGUID = GUIDUtil.CreateGUID(coupler); if (nCouplerQuantity > 1) { // Create a group to hold all of the created IFC entities, if the coupler aren't already in an assembly. // We want to avoid nested groups of groups of couplers. if (coupler.AssemblyInstanceId == ElementId.InvalidElementId) { string revitObjectType = NamingUtil.GetFamilyAndTypeName(coupler); string name = NamingUtil.GetNameOverride(coupler, revitObjectType); string description = NamingUtil.GetDescriptionOverride(coupler, null); string objectType = NamingUtil.GetObjectTypeOverride(coupler, revitObjectType); IFCAnyHandle rebarGroup = IFCInstanceExporter.CreateGroup(file, couplerGUID, ownerHistory, name, description, objectType); productWrapper.AddElement(coupler, rebarGroup, exportType); IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, createdRebarCouplerHandles, null, rebarGroup); } } else { // We will update the GUID of the one created element to be the element GUID. // This will allow the IfcGUID parameter to be use/set if appropriate. ExporterUtil.SetGlobalId(createdRebarCouplerHandles.ElementAt(0), couplerGUID); } tr.Commit(); } }
/// <summary> /// Export the standalone parts: /// - The parts made from originals in Links /// - The Orphan parts: the linked file where the original host element comes from is unloaded. /// - The Zombie parts: the original host element is deleted from the linked file. /// </summary> /// <remarks> /// This is a temporary workaround to export the parts made from linked elements. It should be refined when linked are supported (LinkedInstance at least.) /// There are some limitations: /// The linked element will not export as host, including the relative elements: e.g. windows, doors, openings. /// The host part cannot export if visibility is set by linked view and has 'Show Original'. /// The standalone part will skip export if Base Level is set 'Non Associated'. /// The linked part export cannot be split even if its category is wall or column and 'Split wall or column by story' is checked. /// </remarks> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="partElement">The standalone part to export.</param> /// <param name="geometryElement">The goemetry of the part.</param> /// <param name="productWrapper">The ProductWrapper object.</param> public static void ExportStandalonePart(ExporterIFC exporterIFC, Element partElement, GeometryElement geometryElement, ProductWrapper productWrapper) { Part part = partElement as Part; if (!ExporterCacheManager.ExportOptionsCache.ExportParts || part == null || geometryElement == null) { return; } foreach (LinkElementId linkElementId in part.GetSourceElementIds()) { if (linkElementId.HostElementId != ElementId.InvalidElementId) { // Has host element, so should export with host element. return; } if (linkElementId.LinkedElementId != ElementId.InvalidElementId) { if (part.LevelId == ElementId.InvalidElementId) { // skip the parts have NO Base Level. continue; } IFCExtrusionAxes ifcExtrusionAxes = GetDefaultExtrusionAxesForPart(part); PartExporter.ExportPart(exporterIFC, partElement, productWrapper, null, null, null, ifcExtrusionAxes, null, null, false); } } }
private void WriteElementGeometry(int elementId) { FilteredElementCollector viewCollector = new FilteredElementCollector(m_doc); viewCollector.OfClass(typeof(ViewPlan)); Func <ViewPlan, bool> isLevel1FloorPlan = v => !v.IsTemplate && v.Name == "Level 1" && v.ViewType == ViewType.FloorPlan; m_targetView = viewCollector.Cast <ViewPlan>().First <ViewPlan>(isLevel1FloorPlan); Transaction createCurve = new Transaction(m_doc, "Create reference curves"); createCurve.Start(); const double xReferenceLocation = 30; Line vLine = Line.CreateBound(new XYZ(xReferenceLocation, 0, 0), new XYZ(xReferenceLocation, 20, 0)); m_vLine = m_doc.Create.NewDetailCurve(m_targetView, vLine); const double yReferenceLocation = -10; Line hLine = Line.CreateBound(new XYZ(0, yReferenceLocation, 0), new XYZ(20, yReferenceLocation, 0)); m_hLine = m_doc.Create.NewDetailCurve(m_targetView, hLine); createCurve.Commit(); Element e = m_doc.GetElement(new ElementId(elementId)); Options options = new Options(); options.ComputeReferences = true; options.IncludeNonVisibleObjects = true; options.View = m_targetView; GeometryElement geomElem = e.get_Geometry(options); foreach (GeometryObject geomObj in geomElem) { if (geomObj is Solid) { WriteSolid((Solid)geomObj); } else if (geomObj is GeometryInstance) { TraverseGeometryInstance((GeometryInstance)geomObj); } else { m_writer.WriteLine("Something else - " + geomObj.GetType().Name); } } foreach (Curve curve in m_referencePlaneReferences) { // Try to get the geometry object from reference Reference curveReference = curve.Reference; GeometryObject geomObj = e.GetGeometryObjectFromReference(curveReference); if (geomObj != null) { m_writer.WriteLine("Curve reference leads to: " + geomObj.GetType().Name); } } // Dimension to reference curves foreach (Curve curve in m_referencePlaneReferences) { DetailCurve targetLine = m_vLine; Line line = (Line)curve; XYZ lineStartPoint = line.GetEndPoint(0); XYZ lineEndPoint = line.GetEndPoint(1); XYZ direction = lineEndPoint - lineStartPoint; Line dimensionLine = null; if (Math.Abs(direction.Y) < 0.0001) { targetLine = m_hLine; XYZ dimensionLineStart = new XYZ(lineStartPoint.X + 5, lineStartPoint.Y, 0); XYZ dimensionLineEnd = new XYZ(dimensionLineStart.X, dimensionLineStart.Y + 10, 0); dimensionLine = Line.CreateBound(dimensionLineStart, dimensionLineEnd); } else { targetLine = m_vLine; XYZ dimensionLineStart = new XYZ(lineStartPoint.X, lineStartPoint.Y + 5, 0); XYZ dimensionLineEnd = new XYZ(dimensionLineStart.X + 10, dimensionLineStart.Y, 0); dimensionLine = Line.CreateBound(dimensionLineStart, dimensionLineEnd); } ReferenceArray references = new ReferenceArray(); references.Append(curve.Reference); references.Append(targetLine.GeometryCurve.Reference); Transaction t = new Transaction(m_doc, "Create dimension"); t.Start(); m_doc.Create.NewDimension(m_targetView, dimensionLine, references); t.Commit(); } }
/// <summary> /// This method takes the solidsList and clips all of its solids between the given range. /// </summary> /// <param name="elem"> /// The Element from which we obtain our BoundingBoxXYZ. /// </param> /// <param name="geomElem"> /// The top-level GeometryElement from which to gather X and Y coordinates for the intersecting solid. /// </param> /// <param name="range"> /// The IFCRange whose Z values we use to create an intersecting solid to clip the solids in this class's internal solidsList. /// If range boundaries are equal, method returns, performing no clippings. /// </param> public void ClipSolidsList(GeometryElement geomElem, IFCRange range) { if (geomElem == null) { throw new ArgumentNullException("geomElemToUse"); } if (MathUtil.IsAlmostEqual(range.Start, range.End) || solidsList.Count == 0) { return; } double bottomZ; double boundDifference; if (range.Start < range.End) { bottomZ = range.Start; boundDifference = range.End - range.Start; } else { bottomZ = range.End; boundDifference = range.Start - range.End; } // create a new solid using the X and Y of the bounding box on the top level GeometryElement and the Z of the IFCRange BoundingBoxXYZ elemBoundingBox = geomElem.GetBoundingBox(); XYZ pointA = new XYZ(elemBoundingBox.Min.X, elemBoundingBox.Min.Y, bottomZ); XYZ pointB = new XYZ(elemBoundingBox.Max.X, elemBoundingBox.Min.Y, bottomZ); XYZ pointC = new XYZ(elemBoundingBox.Max.X, elemBoundingBox.Max.Y, bottomZ); XYZ pointD = new XYZ(elemBoundingBox.Min.X, elemBoundingBox.Max.Y, bottomZ); List<Curve> perimeter = new List<Curve>(); perimeter.Add(Line.CreateBound(pointA, pointB)); perimeter.Add(Line.CreateBound(pointB, pointC)); perimeter.Add(Line.CreateBound(pointC, pointD)); perimeter.Add(Line.CreateBound(pointD, pointA)); List<CurveLoop> boxPerimeterList = new List<CurveLoop>(); boxPerimeterList.Add(CurveLoop.Create(perimeter)); Solid intersectionSolid = GeometryCreationUtilities.CreateExtrusionGeometry(boxPerimeterList, XYZ.BasisZ, boundDifference); // cycle through the elements in solidsList and intersect them against intersectionSolid to create a new list List<Solid> clippedSolidsList = new List<Solid>(); Solid currSolid; foreach (Solid solid in solidsList) { try { // ExecuteBooleanOperation can throw if it fails. In this case, just ignore the clipping. currSolid = BooleanOperationsUtils.ExecuteBooleanOperation(solid, intersectionSolid, BooleanOperationsType.Intersect); if (currSolid != null && currSolid.Volume != 0) { clippedSolidsList.Add(currSolid); } } catch { } } solidsList = clippedSolidsList; }
/// <summary> /// Export the parts as independent building elements. /// </summary> /// <remarks> /// The function works with AlternateIFCUI and it requires two conditions: /// 1. Allows export parts: 'current view only' is checked and 'show parts' is selected. /// 2. Allows export parts independent: 'Export parts as building elements' is checked in alternate UI dialog. /// </remarks> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="partElement">The standalone part to export.</param> /// <param name="geometryElement">The goemetry of the part.</param> /// <param name="productWrapper">The ProductWrapper object.</param> public static void ExportPartAsBuildingElement(ExporterIFC exporterIFC, Element partElement, GeometryElement geometryElement, ProductWrapper productWrapper) { Part part = partElement as Part; if (!ExporterCacheManager.ExportOptionsCache.ExportParts || part == null || geometryElement == null) { return; } bool isWall = part.OriginalCategoryId == new ElementId(BuiltInCategory.OST_Walls); bool isColumn = part.OriginalCategoryId == new ElementId(BuiltInCategory.OST_Columns); bool isWallOrColumn = isWall || isColumn; IFCExtrusionAxes ifcExtrusionAxes = GetDefaultExtrusionAxesForPart(part); Element hostElement = null; ElementId overrideLevelId = null; // Find the host element of the part. hostElement = FindRootParent(part, part.OriginalCategoryId); // If part's level is not associated, try to get the host's level with the same category. if (hostElement != null) { overrideLevelId = hostElement.LevelId; } // Split parts with original category is wall or column and the option wall or column is split by level is checked, and then export; // otherwise, export separate parts normally. if (isWallOrColumn && ExporterCacheManager.ExportOptionsCache.WallAndColumnSplitting) { IList <ElementId> levels = new List <ElementId>(); IList <IFCRange> ranges = new List <IFCRange>(); IFCExportType exportType = isWall ? IFCExportType.IfcWall : IFCExportType.IfcColumnType; LevelUtil.CreateSplitLevelRangesForElement(exporterIFC, exportType, part, out levels, out ranges); if (ranges.Count == 0) { PartExporter.ExportPart(exporterIFC, partElement, productWrapper, null, null, null, ifcExtrusionAxes, hostElement, overrideLevelId, true); } else { for (int ii = 0; ii < ranges.Count; ii++) { PartExporter.ExportPart(exporterIFC, partElement, productWrapper, null, null, ranges[ii], ifcExtrusionAxes, hostElement, levels[ii], true); } } } else { PartExporter.ExportPart(exporterIFC, partElement, productWrapper, null, null, null, ifcExtrusionAxes, hostElement, overrideLevelId, true); } }