/// <summary>
        /// Create a label property, or retrieve from cache.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="propertyName">The name of the property.</param>
        /// <param name="value">The value of the property.</param>
        /// <param name="valueType">The value type of the property.</param>
        /// <returns>The created or cached property handle.</returns>
        public static IFCAnyHandle CreateElectricalCurrentMeasurePropertyFromCache(IFCFile file, string propertyName, double value, PropertyValueType valueType)
        {
            // We have a partial cache here - we will only cache multiples of 15 degrees.
            bool canCache = false;
            double ampsDiv5 = Math.Floor(value / 5.0 + 0.5);
            double integerAmps = ampsDiv5 * 5.0;
            if (MathUtil.IsAlmostEqual(value, integerAmps))
            {
                canCache = true;
                value = integerAmps;
            }

            IFCAnyHandle propertyHandle;
            if (canCache)
            {
                propertyHandle = ExporterCacheManager.PropertyInfoCache.ElectricalCurrentCache.Find(propertyName, value);
                if (propertyHandle != null)
                    return propertyHandle;
            }

            propertyHandle = CreateElectricalCurrentMeasureProperty(file, propertyName, value, valueType);

            if (canCache && !IFCAnyHandleUtil.IsNullOrHasNoValue(propertyHandle))
            {
                ExporterCacheManager.PropertyInfoCache.ElectricalCurrentCache.Add(propertyName, value, propertyHandle);
            }

            return propertyHandle;
        }
        /// <summary>
        /// Creates uniformat classification.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC.</param>
        /// <param name="file">The file.</param>
        /// <param name="element">The element.</param>
        /// <param name="elemHnd">The element handle.</param>
        public static void CreateUniformatClassification(ExporterIFC exporterIFC, IFCFile file, Element element, IFCAnyHandle elemHnd)
        {
            // Create Uniformat classification, if it is not set.
            string uniformatKeyString = "Uniformat";
            string uniformatCode = "";
            if (ParameterUtil.GetStringValueFromElementOrSymbol(element, BuiltInParameter.UNIFORMAT_CODE, false, out uniformatCode) == null)
                ParameterUtil.GetStringValueFromElementOrSymbol(element, "Assembly Code", out uniformatCode);
            string uniformatDescription = "";

            if (!String.IsNullOrWhiteSpace(uniformatCode))
            {
                if (ParameterUtil.GetStringValueFromElementOrSymbol(element, BuiltInParameter.UNIFORMAT_DESCRIPTION, false, out uniformatDescription) == null)
                    ParameterUtil.GetStringValueFromElementOrSymbol(element, "Assembly Description", out uniformatDescription);
            }

            IFCAnyHandle classification;
            if (!ExporterCacheManager.ClassificationCache.ClassificationHandles.TryGetValue(uniformatKeyString, out classification))
            {
                classification = IFCInstanceExporter.CreateClassification(file, "http://www.csiorg.net/uniformat", "1998", null, uniformatKeyString);
                ExporterCacheManager.ClassificationCache.ClassificationHandles.Add(uniformatKeyString, classification);
            }

                InsertClassificationReference(exporterIFC, file, element, elemHnd, uniformatKeyString, uniformatCode, uniformatDescription, "http://www.csiorg.net/uniformat" );

        }
Пример #3
0
        /// <summary>
        /// Creates uniformat classification.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC.</param>
        /// <param name="file">The file.</param>
        /// <param name="element">The element.</param>
        /// <param name="elemHnd">The element handle.</param>
        public static void CreateUniformatClassification(ExporterIFC exporterIFC, IFCFile file, Element element, IFCAnyHandle elemHnd)
        {
            // Create Uniformat classification, if it is set.
            string uniformatCode = "";
            if (ParameterUtil.GetStringValueFromElementOrSymbol(element, BuiltInParameter.UNIFORMAT_CODE, false, out uniformatCode) ||
                ParameterUtil.GetStringValueFromElementOrSymbol(element, "Assembly Code", out uniformatCode))
            {
                string uniformatDescription = "";
                if (!ParameterUtil.GetStringValueFromElementOrSymbol(element, BuiltInParameter.UNIFORMAT_DESCRIPTION, false, out uniformatDescription))
                    ParameterUtil.GetStringValueFromElementOrSymbol(element, "Assembly Description", out uniformatDescription);

                IFCAnyHandle classification;
                if (!ExporterCacheManager.ClassificationCache.TryGetValue("UniFormat", out classification))
                {
                    classification = IFCInstanceExporter.CreateClassification(file, "http://www.csiorg.net/uniformat", "1998", null, "UniFormat");
                    ExporterCacheManager.ClassificationCache.Add("UniFormat", classification);
                }

                IFCAnyHandle classificationReference = IFCInstanceExporter.CreateClassificationReference(file,
                  "http://www.csiorg.net/uniformat", uniformatCode, uniformatDescription, classification);

                HashSet<IFCAnyHandle> relatedObjects = new HashSet<IFCAnyHandle>();
                relatedObjects.Add(elemHnd);

                IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, ExporterIFCUtils.CreateGUID(),
                   exporterIFC.GetOwnerHistoryHandle(), "UniFormatClassification", "", relatedObjects, classificationReference);
            }
        }
        /// <summary>
        /// Creates IfcAxis2Placement3D object.
        /// </summary>
        /// <param name="file">
        /// The IFC file.
        /// </param>
        /// <param name="origin">
        /// The origin.
        /// </param>
        /// <param name="zDirection">
        /// The Z direction.
        /// </param>
        /// <param name="xDirection">
        /// The X direction.
        /// </param>
        /// <returns>
        /// The handle.
        /// </returns>
        public static IFCAnyHandle CreateAxis(IFCFile file, XYZ origin, XYZ zDirection, XYZ xDirection)
        {
            IFCAnyHandle directionOpt = IFCAnyHandle.Create();
            IFCAnyHandle refOpt = IFCAnyHandle.Create();
            IFCAnyHandle location = IFCAnyHandle.Create();

            if (origin != null)
            {
                IList<double> measure = new List<double>();
                measure.Add(origin.X); measure.Add(origin.Y); measure.Add(origin.Z);
                location = CreateCartesianPoint(file, measure);
            }
            else
            {
                location = ExporterIFCUtils.GetGlobal3DOriginHandle();
            }

            bool exportzDirectionAndxDirection = (zDirection != null && xDirection != null && (!MathUtil.IsAlmostEqual(zDirection[2], 1.0) || !MathUtil.IsAlmostEqual(xDirection[0], 1.0)));

            if (exportzDirectionAndxDirection)
            {
                IList<double> axisPts = new List<double>();
                axisPts.Add(zDirection.X); axisPts.Add(zDirection.Y); axisPts.Add(zDirection.Z);
                directionOpt = CreateDirection(file, axisPts);
            }

            if (exportzDirectionAndxDirection)
            {
                IList<double> axisPts = new List<double>();
                axisPts.Add(xDirection.X); axisPts.Add(xDirection.Y); axisPts.Add(xDirection.Z);
                refOpt = CreateDirection(file, axisPts);
            }

            return file.CreateAxis2Placement3D(location, directionOpt, refOpt);
        }
Пример #5
0
 /// <summary>
 /// Create a Frequency measure property from the element's parameter.
 /// </summary>
 /// <param name="file">The IFC file.</param>
 /// <param name="exporterIFC">The ExporterIFC.</param>
 /// <param name="elem">The Element.</param>
 /// <param name="revitParameterName">The name of the parameter.</param>
 /// <param name="ifcPropertyName">The name of the property.</param>
 /// <param name="valueType">The value type of the property.</param>
 /// <returns>The created property handle.</returns>
 public static IFCAnyHandle CreateFrequencyPropertyFromElement(IFCFile file, ExporterIFC exporterIFC, Element elem,
     string revitParameterName, string ifcPropertyName, PropertyValueType valueType)
 {
     double propertyValue;
     if (ParameterUtil.GetDoubleValueFromElement(elem, null, revitParameterName, out propertyValue) != null)
         return CreateFrequencyProperty(file, ifcPropertyName, propertyValue, valueType);
     return null;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="exporterIFC"></param>
        /// <param name="file"></param>
        /// <param name="element"></param>
        /// <param name="elemHnd"></param>
        /// <param name="location"></param>
        public static void CreateClassification(ExporterIFC exporterIFC, IFCFile file, Element element, IFCAnyHandle elemHnd, string location)
        {
            string paramClassificationCode = "";
            string classificationName = null;
            string classificationCode = null;
            string classificationDescription = null;
            // For now the support is fixed to 10 predefined classification code parameter names (to support limitation of schedule key that supports only one category per schedule key and needs one parameter for each)
            int noClassCodeParam = 10;
            string [] classCodeParamName = {"ClassificationCode", "ClassificationCode(2)", "ClassificationCode(3)", "ClassificationCode(4)", "ClassificationCode(5)",
                                           "ClassificationCode(6)", "ClassificationCode(7)", "ClassificationCode(8)", "ClassificationCode(9)", "ClassificationCode(10)"}; 
            int ret = 0;

            for (int n = 0; n < noClassCodeParam; n++)
            {
                // Create A classification, if it is not set.
                if (ParameterUtil.GetStringValueFromElementOrSymbol(element, classCodeParamName[n], out paramClassificationCode))
                {
                    ret = parseClassificationCode(paramClassificationCode, out classificationName, out classificationCode, out classificationDescription);

                    if (string.IsNullOrEmpty(classificationName))
                        classificationName = "Default Classification";

                    IFCAnyHandle classification;
                    if (!ExporterCacheManager.ClassificationCache.TryGetValue(classificationName, out classification))
                    {
                        IFCClassificationMgr savedClassificationFromUI = new IFCClassificationMgr();
                        IFCClassification savedClassification = new IFCClassification();

                        if (savedClassificationFromUI.GetSavedClassificationByName(element.Document, classificationName, out savedClassification))
                        {
                            if (savedClassification.ClassificationEditionDate == null)
                            {
                                IFCAnyHandle editionDate = IFCInstanceExporter.CreateCalendarDate(file, savedClassification.ClassificationEditionDate.Day, savedClassification.ClassificationEditionDate.Month, savedClassification.ClassificationEditionDate.Year);

                                classification = IFCInstanceExporter.CreateClassification(file, savedClassification.ClassificationSource, savedClassification.ClassificationEdition,
                                    editionDate, savedClassification.ClassificationName);
                            }
                            else
                                classification = IFCInstanceExporter.CreateClassification(file, savedClassification.ClassificationSource, savedClassification.ClassificationEdition,
                                    null, savedClassification.ClassificationName);
                        }
                        else
                            classification = IFCInstanceExporter.CreateClassification(file, "", "", null, classificationName);

                        ExporterCacheManager.ClassificationCache.Add(classificationName, classification);
                        if (!String.IsNullOrEmpty(savedClassification.ClassificationLocation))
                            ExporterCacheManager.ClassificationLocationCache.Add(classificationName, savedClassification.ClassificationLocation);
                    }

                    if (String.IsNullOrEmpty(location))
                    {
                        ExporterCacheManager.ClassificationLocationCache.TryGetValue(classificationName, out location);
                    }
                    InsertClassificationReference(exporterIFC, file, element, elemHnd, classificationName, classificationCode, classificationDescription, location);
                }
            }
        }
Пример #7
0
        /// <summary>
        /// Creates a handle representing an IfcActor and assigns it to the file.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="guid">The GUID.</param>
        /// <param name="ownerHistory">The owner history.</param>
        /// <param name="name">The name</param>
        /// <param name="description">The description</param>
        /// <param name="objectType">The object type.</param>
        /// <param name="theActor">The actor.</param>
        /// <returns>The handle.</returns>
        public static IFCAnyHandle CreateActor(IFCFile file, string guid, IFCAnyHandle ownerHistory,
            string name, string description, string objectType, IFCAnyHandle theActor)
        {
            ValidateActor(guid, ownerHistory, name, description, objectType, theActor);

            IFCAnyHandle actorHandle = CreateInstance(file, IFCEntityType.IfcActor);
            SetActor(actorHandle, guid, ownerHistory, name, description, objectType, theActor);
            return actorHandle;
        }
 /// <summary>
 /// Creates handles for the quantities.
 /// </summary>
 /// <param name="file">The IFC file.</param>
 /// <param name="exporterIFC">The ExporterIFC class.</param>
 /// <param name="ifcParams">The extrusion creation data, used to get extra parameter information.</param>
 /// <param name="elementToUse">The base element.</param>
 /// <param name="elemTypeToUse">The base element type.</param>
 /// <returns>A set of quantities handles.</returns>
 public HashSet<IFCAnyHandle> ProcessEntries(IFCFile file, ExporterIFC exporterIFC, IFCExtrusionCreationData ifcParams, Element elementToUse, ElementType elemTypeToUse)
 {
     HashSet<IFCAnyHandle> props = new HashSet<IFCAnyHandle>();
     foreach (QuantityEntry entry in m_Entries)
     {
         IFCAnyHandle propHnd = entry.ProcessEntry(file, exporterIFC, ifcParams, elementToUse, elemTypeToUse);
         if (!IFCAnyHandleUtil.IsNullOrHasNoValue(propHnd))
             props.Add(propHnd);
     }
     return props;
 }
Пример #9
0
        /// <summary>
        /// Creates an IfcActuatorType, and assigns it to the file.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="guid">The GUID.</param>
        /// <param name="ownerHistory">The owner history.</param>
        /// <param name="name">The name.</param>
        /// <param name="description">The description.</param>
        /// <param name="applicableOccurrence">The attribute optionally defines the data type of the occurrence object.</param>
        /// <param name="propertySets">The property set(s) associated with the type.</param>
        /// <param name="representationMaps">The mapped geometries associated with the type.</param>
        /// <param name="elementTag">The tag that represents the entity.</param>
        /// <param name="elementType">The type name.</param>
        /// <param name="predefinedType">The predefined types.</param>
        /// <returns>The handle.</returns>
        public static IFCAnyHandle CreateActuatorType(IFCFile file, string guid, IFCAnyHandle ownerHistory, string name,
            string description, string applicableOccurrence, HashSet<IFCAnyHandle> propertySets,
            IList<IFCAnyHandle> representationMaps, string elementTag, string elementType, IFCActuatorType predefinedType)
        {
            ValidateElementType(guid, ownerHistory, name, description, applicableOccurrence, propertySets,
                representationMaps, elementTag, elementType);

            IFCAnyHandle actuatorType = CreateInstance(file, IFCEntityType.IfcActuatorType);
            IFCAnyHandleUtil.SetAttribute(actuatorType, "PredefinedType", predefinedType);
            SetElementType(actuatorType, guid, ownerHistory, name, description, applicableOccurrence, propertySets,
                representationMaps, elementTag, elementType);
            return actuatorType;
        }
 /// <summary>
 /// Create a label property.
 /// </summary>
 /// <param name="file">The IFC file.</param>
 /// <param name="propertyName">The name of the property.</param>
 /// <param name="value">The value of the property.</param>
 /// <param name="valueType">The value type of the property.</param>
 /// <returns>The created property handle.</returns>
 public static IFCAnyHandle CreateElectricalCurrentMeasureProperty(IFCFile file, string propertyName, double value, PropertyValueType valueType)
 {
     switch (valueType)
     {
         case PropertyValueType.EnumeratedValue:
             {
                 IList<IFCData> valueList = new List<IFCData>();
                 valueList.Add(IFCDataUtil.CreateAsElectricalCurrentMeasure(value));
                 return IFCInstanceExporter.CreatePropertyEnumeratedValue(file, propertyName, null, valueList, null);
             }
         case PropertyValueType.SingleValue:
             return IFCInstanceExporter.CreatePropertySingleValue(file, propertyName, null, IFCDataUtil.CreateAsElectricalCurrentMeasure(value), null);
         default:
             throw new InvalidOperationException("Missing case!");
     }
 }
Пример #11
0
        private static IFCAnyHandle CreateSweptDiskSolid(ExporterIFC exporterIFC, IFCFile file, Curve centerCurve, double radius)
        {
            IList<Curve> curves = new List<Curve>();
            double endParam = 0.0;
            if (centerCurve is Arc || centerCurve is Ellipse)
            {
                if (centerCurve.IsBound)
                    endParam = (centerCurve.get_EndParameter(1) - centerCurve.get_EndParameter(0)) * 180 / Math.PI;
                else
                    endParam = (2 * Math.PI) * 180 / Math.PI;
            }
            else
                endParam = 1.0;
            curves.Add(centerCurve);

            IFCAnyHandle compositeCurve = GeometryUtil.CreateCompositeCurve(exporterIFC, curves);
            return IFCInstanceExporter.CreateSweptDiskSolid(file, compositeCurve, radius, null, 0, endParam);
        }
        /// <summary>
        /// Create a label property.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="propertyName">The name of the property.</param>
        /// <param name="value">The value of the property.</param>
        /// <param name="valueType">The value type of the property.</param>
        /// <returns>The created property handle.</returns>
        public static IFCAnyHandle CreatePositivePlaneAngleMeasureProperty(IFCFile file, string propertyName, double value, PropertyValueType valueType)
        {
            // Ensure it is positive.  Don't throw, but should tell user.
            if (value <= MathUtil.Eps())
                return null;

            switch (valueType)
            {
                case PropertyValueType.EnumeratedValue:
                    {
                        IList<IFCData> valueList = new List<IFCData>();
                        valueList.Add(IFCDataUtil.CreateAsPositivePlaneAngleMeasure(value));
                        return IFCInstanceExporter.CreatePropertyEnumeratedValue(file, propertyName, null, valueList, null);
                    }
                case PropertyValueType.SingleValue:
                    return IFCInstanceExporter.CreatePropertySingleValue(file, propertyName, null, IFCDataUtil.CreateAsPositivePlaneAngleMeasure(value), null);
                default:
                    throw new InvalidOperationException("Missing case!");
            }
        }
Пример #13
0
 protected static IFCAnyHandle CreateCommonProperty(IFCFile file, string propertyName, IFCData valueData, PropertyValueType valueType, string unitTypeKey)
 {
     switch (valueType)
     {
         case PropertyValueType.EnumeratedValue:
             {
                 IList<IFCData> valueList = new List<IFCData>();
                 valueList.Add(valueData);
                 return IFCInstanceExporter.CreatePropertyEnumeratedValue(file, propertyName, null, valueList, null);
             }
         case PropertyValueType.SingleValue:
             {
                 if (unitTypeKey != null)
                     return IFCInstanceExporter.CreatePropertySingleValue(file, propertyName, null, valueData, ExporterCacheManager.UnitsCache[unitTypeKey]);
                 else
                     return IFCInstanceExporter.CreatePropertySingleValue(file, propertyName, null, valueData, null);
             }
         default:
             throw new InvalidOperationException("Missing case!");
     }
 }
Пример #14
0
        /// <summary>
        /// Create a Frequency measure property from the element's or type's parameter.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="exporterIFC">The ExporterIFC.</param>
        /// <param name="elem">The Element.</param>
        /// <param name="revitParameterName">The name of the parameter.</param>
        /// <param name="revitBuiltInParam">The built in parameter to use, if revitParameterName isn't found.</param>
        /// <param name="ifcPropertyName">The name of the property.</param>
        /// <param name="valueType">The value type of the property.</param>
        /// <returns>The created property handle.</returns>
        public static IFCAnyHandle CreateFrequencyPropertyFromElementOrSymbol(IFCFile file, ExporterIFC exporterIFC, Element elem,
            string revitParameterName, BuiltInParameter revitBuiltInParam, string ifcPropertyName, PropertyValueType valueType)
        {
            IFCAnyHandle propHnd = CreateFrequencyPropertyFromElement(file, exporterIFC, elem, revitParameterName, ifcPropertyName, valueType);
            if (!IFCAnyHandleUtil.IsNullOrHasNoValue(propHnd))
                return propHnd;

            if (revitBuiltInParam != BuiltInParameter.INVALID)
            {
                string builtInParamName = LabelUtils.GetLabelFor(revitBuiltInParam);
                propHnd = CreateFrequencyPropertyFromElement(file, exporterIFC, elem, builtInParamName, ifcPropertyName, valueType);
                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(propHnd))
                    return propHnd;
            }

            // For Symbol
            Document document = elem.Document;
            ElementId typeId = elem.GetTypeId();
            Element elemType = document.GetElement(typeId);
            if (elemType != null)
                return CreateFrequencyPropertyFromElementOrSymbol(file, exporterIFC, elemType, revitParameterName, revitBuiltInParam, ifcPropertyName, valueType);
            else
                return null;
        }
Пример #15
0
 /// <summary>
 /// Creates IfcMappedItem object from a transform
 /// </summary>
 /// <param name="file">
 /// The IFC file.
 /// </param>
 /// <param name="repMap">
 /// The handle to be mapped.
 /// </param>
 /// <param name="transform">
 /// The transform.
 /// </param>
 /// <returns>
 /// The handle.
 /// </returns>
 public static IFCAnyHandle CreateMappedItemFromTransform(IFCFile file, IFCAnyHandle repMap, Transform transform)
 {
     IFCAnyHandle axis1 = CreateDirection(file, transform.BasisX);
     IFCAnyHandle axis2 = CreateDirection(file, transform.BasisY);
     IFCAnyHandle axis3 = CreateDirection(file, transform.BasisZ);
     IFCAnyHandle origin = CreateCartesianPoint(file, transform.Origin);
     double scale = 1.0;
     IFCAnyHandle mappingTarget =
        IFCInstanceExporter.CreateCartesianTransformationOperator3D(file, axis1, axis2, origin, scale, axis3);
     return IFCInstanceExporter.CreateMappedItem(file, repMap, mappingTarget);
 }
Пример #16
0
        /// <summary>
        /// Creates a property from the calculator.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="exporterIFC">The ExporterIFC.</param>
        /// <param name="extrusionCreationData">The IFCExtrusionCreationData.</param>
        /// <param name="element">The element.</param>
        /// <param name="elementType">The element type.</param>
        /// <param name="handle">The handle for which we calculate the property.</param>
        /// <returns>The property handle.</returns>
        IFCAnyHandle CreatePropertyFromCalculator(IFCFile file, ExporterIFC exporterIFC, IFCExtrusionCreationData extrusionCreationData, Element element,
                                                  ElementType elementType, IFCAnyHandle handle, PropertyType propertyType, PropertyValueType valueType, Type propertyEnumerationType, string propertyName)
        {
            IFCAnyHandle propHnd = null;

            if (PropertyCalculator == null)
            {
                return(propHnd);
            }

            if (PropertyCalculator.GetParameterFromSubelementCache(element, handle) ||
                PropertyCalculator.Calculate(exporterIFC, extrusionCreationData, element, elementType))
            {
                switch (propertyType)
                {
                case PropertyType.Label:
                {
                    if (PropertyCalculator.CalculatesMutipleValues)
                    {
                        propHnd = PropertyUtil.CreateLabelProperty(file, propertyName, PropertyCalculator.GetStringValues(), valueType, propertyEnumerationType);
                    }
                    else
                    {
                        bool cacheLabel = PropertyCalculator.CacheStringValues;
                        propHnd = PropertyUtil.CreateLabelPropertyFromCache(file, null, propertyName, PropertyCalculator.GetStringValue(), valueType, cacheLabel, propertyEnumerationType);
                    }
                    break;
                }

                case PropertyType.Text:
                {
                    propHnd = PropertyUtil.CreateTextPropertyFromCache(file, propertyName, PropertyCalculator.GetStringValue(), valueType);
                    break;
                }

                case PropertyType.Identifier:
                {
                    propHnd = PropertyUtil.CreateIdentifierPropertyFromCache(file, propertyName, PropertyCalculator.GetStringValue(), valueType);
                    break;
                }

                case PropertyType.Boolean:
                {
                    propHnd = PropertyUtil.CreateBooleanPropertyFromCache(file, propertyName, PropertyCalculator.GetBooleanValue(), valueType);
                    break;
                }

                case PropertyType.Logical:
                {
                    propHnd = PropertyUtil.CreateLogicalPropertyFromCache(file, propertyName, PropertyCalculator.GetLogicalValue(), valueType);
                    break;
                }

                case PropertyType.Integer:
                {
                    if (PropertyCalculator.CalculatesMultipleParameters)
                    {
                        propHnd = PropertyUtil.CreateIntegerPropertyFromCache(file, propertyName, PropertyCalculator.GetIntValue(propertyName), valueType);
                    }
                    else
                    {
                        propHnd = PropertyUtil.CreateIntegerPropertyFromCache(file, propertyName, PropertyCalculator.GetIntValue(), valueType);
                    }
                    break;
                }

                case PropertyType.Real:
                {
                    propHnd = PropertyUtil.CreateRealPropertyFromCache(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.Length:
                {
                    if (PropertyCalculator.CalculatesMultipleParameters)
                    {
                        propHnd = PropertyUtil.CreateLengthMeasurePropertyFromCache(file, propertyName, PropertyCalculator.GetDoubleValue(propertyName), valueType);
                    }
                    else
                    {
                        propHnd = PropertyUtil.CreateLengthMeasurePropertyFromCache(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    }
                    break;
                }

                case PropertyType.PositiveLength:
                {
                    if (PropertyCalculator.CalculatesMultipleParameters)
                    {
                        propHnd = PropertyUtil.CreatePositiveLengthMeasureProperty(file, propertyName, PropertyCalculator.GetDoubleValue(propertyName), valueType);
                    }
                    else
                    {
                        propHnd = PropertyUtil.CreatePositiveLengthMeasureProperty(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    }
                    break;
                }

                case PropertyType.NormalisedRatio:
                {
                    propHnd = PropertyUtil.CreateNormalisedRatioMeasureProperty(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.PositiveRatio:
                {
                    propHnd = PropertyUtil.CreatePositiveRatioMeasureProperty(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.Ratio:
                {
                    propHnd = PropertyUtil.CreateRatioMeasureProperty(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.PlaneAngle:
                {
                    propHnd = PropertyUtil.CreatePlaneAngleMeasurePropertyFromCache(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.PositivePlaneAngle:
                {
                    propHnd = PositivePlaneAnglePropertyUtil.CreatePositivePlaneAngleMeasurePropertyFromCache(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.Area:
                {
                    propHnd = PropertyUtil.CreateAreaMeasureProperty(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.Count:
                {
                    if (PropertyCalculator.CalculatesMultipleParameters)
                    {
                        propHnd = PropertyUtil.CreateCountMeasureProperty(file, propertyName, PropertyCalculator.GetIntValue(propertyName), valueType);
                    }
                    else
                    {
                        propHnd = PropertyUtil.CreateCountMeasureProperty(file, propertyName, PropertyCalculator.GetIntValue(), valueType);
                    }
                    break;
                }

                case PropertyType.Frequency:
                {
                    propHnd = FrequencyPropertyUtil.CreateFrequencyProperty(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.Power:
                {
                    propHnd = PropertyUtil.CreatePowerPropertyFromCache(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.ThermodynamicTemperature:
                {
                    propHnd = PropertyUtil.CreateThermodynamicTemperaturePropertyFromCache(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.ThermalTransmittance:
                {
                    propHnd = PropertyUtil.CreateThermalTransmittancePropertyFromCache(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.VolumetricFlowRate:
                {
                    propHnd = PropertyUtil.CreateVolumetricFlowRateMeasureProperty(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                case PropertyType.LinearVelocity:
                {
                    propHnd = PropertyUtil.CreateLinearVelocityMeasureProperty(file, propertyName, PropertyCalculator.GetDoubleValue(), valueType);
                    break;
                }

                default:
                    throw new InvalidOperationException();
                }
            }

            return(propHnd);
        }
Пример #17
0
        /// <summary>
        /// Create IfcClassification references from hardwired or custom classification code fields.
        /// </summary>
        /// <param name="exporterIFC">The exporterIFC class.</param>
        /// <param name="file">The IFC file class.</param>
        /// <param name="element">The element to export.</param>
        /// <param name="elemHnd">The corresponding IFC entity handle.</param>
        /// <returns>True if a classification or classification reference is created.</returns>
        public static bool CreateClassification(ExporterIFC exporterIFC, IFCFile file, Element element, IFCAnyHandle elemHnd)
        {
            bool createdClassification = false;

            string         paramClassificationCode         = "";
            string         baseClassificationCodeFieldName = "ClassificationCode";
            IList <string> customClassificationCodeNames   = new List <string>();

            string classificationName        = null;
            string classificationCode        = null;
            string classificationDescription = null;

            int customPass     = 0;
            int standardPass   = 1;
            int numCustomCodes = ExporterCacheManager.ClassificationCache.CustomClassificationCodeNames.Count;

            while (standardPass <= 10)
            {
                // Create a classification, if it is not set.
                string classificationCodeFieldName = null;
                if (customPass < numCustomCodes)
                {
                    classificationCodeFieldName = ExporterCacheManager.ClassificationCache.CustomClassificationCodeNames[customPass];
                    customPass++;

                    if (string.IsNullOrWhiteSpace(classificationCodeFieldName))
                    {
                        continue;
                    }
                }
                else
                {
                    classificationCodeFieldName = baseClassificationCodeFieldName;
                    if (standardPass > 1)
                    {
                        classificationCodeFieldName += "(" + standardPass + ")";
                    }
                    standardPass++;
                }

                if (ParameterUtil.GetStringValueFromElementOrSymbol(element, classificationCodeFieldName, out paramClassificationCode) == null)
                {
                    continue;
                }

                parseClassificationCode(paramClassificationCode, classificationCodeFieldName, out classificationName, out classificationCode, out classificationDescription);

                // If classificationName is empty, there is no classification to export.
                if (String.IsNullOrEmpty(classificationName))
                {
                    continue;
                }

                IFCAnyHandle classification;
                if (!ExporterCacheManager.ClassificationCache.ClassificationHandles.TryGetValue(classificationName, out classification))
                {
                    IFCClassification savedClassification = new IFCClassification();
                    if (ExporterCacheManager.ClassificationCache.ClassificationsByName.TryGetValue(classificationName, out savedClassification))
                    {
                        if (savedClassification.ClassificationEditionDate == null)
                        {
                            IFCAnyHandle editionDate = IFCInstanceExporter.CreateCalendarDate(file, savedClassification.ClassificationEditionDate.Day, savedClassification.ClassificationEditionDate.Month, savedClassification.ClassificationEditionDate.Year);

                            classification = IFCInstanceExporter.CreateClassification(file, savedClassification.ClassificationSource, savedClassification.ClassificationEdition,
                                                                                      editionDate, savedClassification.ClassificationName);
                        }
                        else
                        {
                            classification = IFCInstanceExporter.CreateClassification(file, savedClassification.ClassificationSource, savedClassification.ClassificationEdition,
                                                                                      null, savedClassification.ClassificationName);
                        }

                        if (!String.IsNullOrEmpty(savedClassification.ClassificationLocation))
                        {
                            ExporterCacheManager.ClassificationLocationCache.Add(classificationName, savedClassification.ClassificationLocation);
                        }
                    }
                    else
                    {
                        classification = IFCInstanceExporter.CreateClassification(file, "", "", null, classificationName);
                    }

                    ExporterCacheManager.ClassificationCache.ClassificationHandles.Add(classificationName, classification);
                    createdClassification = true;
                }

                string location = null;
                ExporterCacheManager.ClassificationLocationCache.TryGetValue(classificationName, out location);
                if (!String.IsNullOrEmpty(classificationCode))
                {
                    InsertClassificationReference(exporterIFC, file, elemHnd, classificationName, classificationCode, classificationDescription, location);
                    createdClassification = true;
                }
            }

            return(createdClassification);
        }
Пример #18
0
        /// <summary>
        /// Exports an element as IFC railing.
        /// </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 ExportRailing(ExporterIFC exporterIFC, Element element, GeometryElement geomElem, string ifcEnumType, ProductWrapper productWrapper)
        {
            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcRailing;
            if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
            {
                return;
            }

            ElementType elemType    = element.Document.GetElement(element.GetTypeId()) as ElementType;
            IFCFile     file        = exporterIFC.GetFile();
            Options     geomOptions = GeometryUtil.GetIFCExportGeometryOptions();

            using (IFCTransaction transaction = new IFCTransaction(file))
            {
                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element))
                {
                    using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData())
                    {
                        IFCAnyHandle           localPlacement = setter.LocalPlacement;
                        StairRampContainerInfo stairRampInfo  = null;
                        ElementId hostId     = GetStairOrRampHostId(exporterIFC, element as Railing);
                        Transform inverseTrf = Transform.Identity;
                        if (hostId != ElementId.InvalidElementId)
                        {
                            stairRampInfo = ExporterCacheManager.StairRampContainerInfoCache.GetStairRampContainerInfo(hostId);
                            IFCAnyHandle stairRampLocalPlacement = stairRampInfo.LocalPlacements[0];
                            Transform    relTrf = ExporterIFCUtils.GetRelativeLocalPlacementOffsetTransform(stairRampLocalPlacement, localPlacement);
                            inverseTrf = relTrf.Inverse;

                            IFCAnyHandle railingLocalPlacement = ExporterUtil.CreateLocalPlacement(file, stairRampLocalPlacement,
                                                                                                   inverseTrf.Origin, inverseTrf.BasisZ, inverseTrf.BasisX);
                            localPlacement = railingLocalPlacement;
                        }
                        ecData.SetLocalPlacement(localPlacement);

                        SolidMeshGeometryInfo solidMeshInfo = GeometryUtil.GetSplitSolidMeshGeometry(geomElem);
                        IList <Solid>         solids        = solidMeshInfo.GetSolids();
                        IList <Mesh>          meshes        = solidMeshInfo.GetMeshes();

                        Railing           railingElem   = element as Railing;
                        IList <ElementId> subElementIds = CollectSubElements(railingElem);

                        foreach (ElementId subElementId in subElementIds)
                        {
                            Element subElement = railingElem.Document.GetElement(subElementId);
                            if (subElement != null)
                            {
                                GeometryElement subElementGeom = GeometryUtil.GetOneLevelGeometryElement(subElement.get_Geometry(geomOptions), 0);

                                SolidMeshGeometryInfo subElementSolidMeshInfo = GeometryUtil.GetSplitSolidMeshGeometry(subElementGeom);
                                IList <Solid>         subElementSolids        = subElementSolidMeshInfo.GetSolids();
                                IList <Mesh>          subElementMeshes        = subElementSolidMeshInfo.GetMeshes();
                                foreach (Solid subElementSolid in subElementSolids)
                                {
                                    solids.Add(subElementSolid);
                                }
                                foreach (Mesh subElementMesh in subElementMeshes)
                                {
                                    meshes.Add(subElementMesh);
                                }
                            }
                        }

                        ElementId           catId               = CategoryUtil.GetSafeCategoryId(element);
                        BodyData            bodyData            = null;
                        BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.Medium);
                        //bodyExporterOptions.UseGroupsIfPossible = true;
                        //bodyExporterOptions.UseMappedGeometriesIfPossible = true;

                        if (solids.Count > 0 || meshes.Count > 0)
                        {
                            bodyData = BodyExporter.ExportBody(exporterIFC, element, catId, ElementId.InvalidElementId, solids, meshes, bodyExporterOptions, ecData);
                        }
                        else
                        {
                            IList <GeometryObject> geomlist = new List <GeometryObject>();
                            geomlist.Add(geomElem);
                            bodyData = BodyExporter.ExportBody(exporterIFC, element, catId, ElementId.InvalidElementId, geomlist, bodyExporterOptions, ecData);
                        }

                        IFCAnyHandle bodyRep = bodyData.RepresentationHnd;
                        if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep))
                        {
                            if (ecData != null)
                            {
                                ecData.ClearOpenings();
                            }
                            return;
                        }

                        IList <IFCAnyHandle> representations = new List <IFCAnyHandle>();
                        representations.Add(bodyRep);

                        IList <GeometryObject> geomObjects = new List <GeometryObject>();
                        foreach (Solid solid in solids)
                        {
                            geomObjects.Add(solid);
                        }
                        foreach (Mesh mesh in meshes)
                        {
                            geomObjects.Add(mesh);
                        }

                        Transform boundingBoxTrf = (bodyData.OffsetTransform != null) ? bodyData.OffsetTransform.Inverse : Transform.Identity;
                        boundingBoxTrf = inverseTrf.Multiply(boundingBoxTrf);
                        IFCAnyHandle boundingBoxRep = BoundingBoxExporter.ExportBoundingBox(exporterIFC, geomObjects, boundingBoxTrf);
                        if (boundingBoxRep != null)
                        {
                            representations.Add(boundingBoxRep);
                        }

                        IFCAnyHandle prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, representations);

                        IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle;

                        string instanceGUID = GUIDUtil.CreateGUID(element);

                        //string railingType = IFCValidateEntry.GetValidIFCPredefinedType(element, ifcEnumType);

                        IFCAnyHandle railing = IFCInstanceExporter.CreateRailing(exporterIFC, element, instanceGUID, ownerHistory,
                                                                                 ecData.GetLocalPlacement(), prodRep, ifcEnumType);

                        bool associateToLevel = (hostId == ElementId.InvalidElementId);

                        productWrapper.AddElement(element, railing, setter, ecData, associateToLevel);
                        OpeningUtil.CreateOpeningsIfNecessary(railing, element, ecData, bodyData.OffsetTransform,
                                                              exporterIFC, ecData.GetLocalPlacement(), setter, productWrapper);

                        CategoryUtil.CreateMaterialAssociation(exporterIFC, railing, bodyData.MaterialIds);

                        // Create multi-story duplicates of this railing.
                        if (stairRampInfo != null)
                        {
                            stairRampInfo.AddComponent(0, railing);

                            List <IFCAnyHandle> stairHandles = stairRampInfo.StairOrRampHandles;
                            for (int ii = 1; ii < stairHandles.Count; ii++)
                            {
                                IFCAnyHandle railingLocalPlacement = stairRampInfo.LocalPlacements[ii];
                                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(railingLocalPlacement))
                                {
                                    IFCAnyHandle railingHndCopy = CopyRailingHandle(exporterIFC, element, catId, railingLocalPlacement, railing);
                                    stairRampInfo.AddComponent(ii, railingHndCopy);
                                    productWrapper.AddElement(element, railingHndCopy, (IFCLevelInfo)null, ecData, false);
                                    CategoryUtil.CreateMaterialAssociation(exporterIFC, railingHndCopy, bodyData.MaterialIds);
                                }
                            }

                            ExporterCacheManager.StairRampContainerInfoCache.AddStairRampContainerInfo(hostId, stairRampInfo);
                        }
                    }
                    transaction.Commit();
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Exports an element as an IFC assembly.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="element">The element.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        /// <returns>True if exported successfully, false otherwise.</returns>
        public static bool ExportAssemblyInstanceElement(ExporterIFC exporterIFC, AssemblyInstance element,
                                                         ProductWrapper productWrapper)
        {
            if (element == null)
            {
                return(false);
            }

            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                IFCAnyHandle assemblyInstanceHnd = null;

                string          guid            = GUIDUtil.CreateGUID(element);
                IFCAnyHandle    ownerHistory    = ExporterCacheManager.OwnerHistoryHandle;
                IFCAnyHandle    localPlacement  = null;
                PlacementSetter placementSetter = null;
                IFCLevelInfo    levelInfo       = null;
                bool            relateToLevel   = true;

                string            ifcEnumType;
                IFCExportInfoPair exportAs = ExporterUtil.GetExportType(exporterIFC, element, out ifcEnumType);
                if (exportAs.ExportInstance == IFCEntityType.IfcSystem)
                {
                    string name        = NamingUtil.GetNameOverride(element, NamingUtil.GetIFCName(element));
                    string description = NamingUtil.GetDescriptionOverride(element, null);
                    string objectType  = NamingUtil.GetObjectTypeOverride(element, NamingUtil.GetFamilyAndTypeName(element));
                    assemblyInstanceHnd = IFCInstanceExporter.CreateSystem(file, guid, ownerHistory, name, description, objectType);

                    // Create classification reference when System has classification filed name assigned to it
                    ClassificationUtil.CreateClassification(exporterIFC, file, element, assemblyInstanceHnd);

                    HashSet <IFCAnyHandle> relatedBuildings = new HashSet <IFCAnyHandle>();
                    relatedBuildings.Add(ExporterCacheManager.BuildingHandle);

                    IFCAnyHandle relServicesBuildings = IFCInstanceExporter.CreateRelServicesBuildings(file, GUIDUtil.CreateGUID(),
                                                                                                       ExporterCacheManager.OwnerHistoryHandle, null, null, assemblyInstanceHnd, relatedBuildings);

                    relateToLevel = false; // Already related to the building via IfcRelServicesBuildings.
                }
                else
                {
                    // Check for containment override
                    IFCAnyHandle overrideContainerHnd = null;
                    ElementId    overrideContainerId  = ParameterUtil.OverrideContainmentParameter(exporterIFC, element, out overrideContainerHnd);

                    using (placementSetter = PlacementSetter.Create(exporterIFC, element, null, null, overrideContainerId, overrideContainerHnd))
                    {
                        IFCAnyHandle representation = null;

                        // We have limited support for exporting assemblies as other container types.
                        localPlacement = placementSetter.LocalPlacement;
                        levelInfo      = placementSetter.LevelInfo;

                        switch (exportAs.ExportInstance)
                        {
                        case IFCEntityType.IfcCurtainWall:
                            //case IFCExportType.IfcCurtainWallType:
                            //string cwPredefinedType = IFCValidateEntry.GetValidIFCPredefinedType(element, ifcEnumType, "IfcCurtainWallType");
                            assemblyInstanceHnd = IFCInstanceExporter.CreateCurtainWall(exporterIFC, element, guid,
                                                                                        ownerHistory, localPlacement, representation, ifcEnumType);
                            break;

                        case IFCEntityType.IfcRamp:
                            string rampPredefinedType = RampExporter.GetIFCRampType(ifcEnumType);
                            //rampPredefinedType = IFCValidateEntry.GetValidIFCPredefinedType(element, rampPredefinedType, "IfcRampType");
                            assemblyInstanceHnd = IFCInstanceExporter.CreateRamp(exporterIFC, element, guid,
                                                                                 ownerHistory, localPlacement, representation, rampPredefinedType);
                            break;

                        case IFCEntityType.IfcRoof:
                            //string roofPredefinedType = IFCValidateEntry.GetValidIFCPredefinedType(element, ifcEnumType, "IfcRoofType");
                            assemblyInstanceHnd = IFCInstanceExporter.CreateRoof(exporterIFC, element, guid,
                                                                                 ownerHistory, localPlacement, representation, ifcEnumType);
                            break;

                        case IFCEntityType.IfcStair:
                            string stairPredefinedType = StairsExporter.GetIFCStairType(ifcEnumType);
                            //stairPredefinedType = IFCValidateEntry.GetValidIFCPredefinedType(element, stairPredefinedType, "IfcStairType");
                            assemblyInstanceHnd = IFCInstanceExporter.CreateStair(exporterIFC, element, guid,
                                                                                  ownerHistory, localPlacement, representation, stairPredefinedType);
                            break;

                        case IFCEntityType.IfcWall:
                            //string wallPredefinedType = IFCValidateEntry.GetValidIFCPredefinedType(element, ifcEnumType, "IfcWallType");
                            assemblyInstanceHnd = IFCInstanceExporter.CreateWall(exporterIFC, element, guid,
                                                                                 ownerHistory, localPlacement, representation, ifcEnumType);
                            break;

                        default:
                            string objectType = NamingUtil.GetObjectTypeOverride(element, NamingUtil.GetFamilyAndTypeName(element));
                            IFCElementAssemblyType assemblyPredefinedType = GetPredefinedTypeFromObjectType(objectType);
                            assemblyInstanceHnd = IFCInstanceExporter.CreateElementAssembly(exporterIFC, element, guid,
                                                                                            ownerHistory, localPlacement, representation, IFCAssemblyPlace.NotDefined, assemblyPredefinedType);
                            break;
                        }
                    }
                }

                if (assemblyInstanceHnd == null)
                {
                    return(false);
                }

                // relateToLevel depends on how the AssemblyInstance is being mapped to IFC, above.
                productWrapper.AddElement(element, assemblyInstanceHnd, levelInfo, null, relateToLevel, exportAs);

                ExporterCacheManager.AssemblyInstanceCache.RegisterAssemblyInstance(element.Id, assemblyInstanceHnd);

                tr.Commit();
                return(true);
            }
        }
Пример #20
0
        /// <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, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                        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   = ExporterCacheManager.OwnerHistoryHandle;
                        IFCAnyHandle localPlacement = ecData.GetLocalPlacement();
                        //string predefinedType = GetIFCRoofType(ifcEnumType);
                        string predefinedType = IFCValidateEntry.GetValidIFCPredefinedTypeType(ifcEnumType, "NOTDEFINED", IFCEntityType.IfcRoofType.ToString());

                        IFCAnyHandle roofHnd = IFCInstanceExporter.CreateRoof(exporterIFC, roof, guid, ownerHistory,
                                                                              localPlacement, exportSlab ? null : representation, predefinedType);

                        // Export IfcRoofType
                        IFCExportInfoPair exportInfo = new IFCExportInfoPair(IFCEntityType.IfcRoof, IFCEntityType.IfcRoofType, predefinedType);
                        if (exportInfo.ExportType != IFCEntityType.UnKnown)
                        {
                            string overridePDefType;
                            if (ParameterUtil.GetStringValueFromElementOrSymbol(roof, "IfcExportType", out overridePDefType) == null) // change IFCType to consistent parameter of IfcExportType
                            {
                                if (ParameterUtil.GetStringValueFromElementOrSymbol(roof, "IfcType", out overridePDefType) == null)   // support IFCType for legacy support
                                {
                                    if (string.IsNullOrEmpty(predefinedType))
                                    {
                                        predefinedType = "NOTDEFINED";
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(overridePDefType))
                            {
                                exportInfo.ValidatedPredefinedType = overridePDefType;
                            }
                            else
                            {
                                exportInfo.ValidatedPredefinedType = predefinedType;
                            }

                            IFCAnyHandle typeHnd = ExporterUtil.CreateGenericTypeFromElement(roof, exportInfo, file, ownerHistory, predefinedType, productWrapper);
                            ExporterCacheManager.TypeRelationsCache.Add(typeHnd, roofHnd);
                        }

                        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.CreateMaterialAssociation(exporterIFC, roofHnd, bodyData.MaterialIds);
                        }

                        if (exportSlab)
                        {
                            string       slabGUID = GUIDUtil.CreateSubElementGUID(roof, (int)IFCRoofSubElements.RoofSlabStart);
                            string       slabName = IFCAnyHandleUtil.GetStringAttribute(roofHnd, "Name") + ":1";
                            IFCAnyHandle slabLocalPlacementHnd = ExporterUtil.CopyLocalPlacement(file, localPlacement);

                            IFCAnyHandle slabHnd = IFCInstanceExporter.CreateSlab(exporterIFC, roof, slabGUID, ownerHistory,
                                                                                  slabLocalPlacementHnd, representation, slabRoofPredefinedType);
                            IFCAnyHandleUtil.OverrideNameAttribute(slabHnd, slabName);
                            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.CreateMaterialAssociation(exporterIFC, slabHnd, bodyData.MaterialIds);

                            // Create type
                            IFCExportInfoPair slabRoofExportType = new IFCExportInfoPair();
                            slabRoofExportType.SetValueWithPair(IFCEntityType.IfcSlab);
                            IFCAnyHandle slabRoofTypeHnd = ExporterUtil.CreateGenericTypeFromElement(roof, slabRoofExportType, exporterIFC.GetFile(), ownerHistory, slabRoofPredefinedType, productWrapper);
                            ExporterCacheManager.TypeRelationsCache.Add(slabRoofTypeHnd, slabHnd);
                        }
                    }
                    tr.Commit();
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Base implementation to export IFC site object.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="document">The Revit document.  It may be null if element isn't.</param>
        /// <param name="element">The element.  It may be null if document isn't.</param>
        /// <param name="geometryElement">The geometry element.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        private static void ExportSiteBase(ExporterIFC exporterIFC, Document document, Element element, GeometryElement geometryElement, ProductWrapper 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;
                    bool exportAsFacetation = !ExporterCacheManager.ExportOptionsCache.ExportAsCoordinationView2;
                    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, exportAsFacetation, ref bodyRep, ref boundaryRep);
                            if (representations.Count == 1 && !IFCAnyHandleUtil.IsNullOrHasNoValue(boundaryRep))
                            {
                                // If the first site has no boundaryRep,
                                // we will add the boundaryRep from second site to it.
                                representations.Clear();
                                representations.Add(boundaryRep);
                                IFCAnyHandleUtil.AddProductRepresentations(siteHandle, representations);
                            }
                            appendedToSite = true;
                        }
                    }

                    if (!appendedToSite)
                    {
                        siteRepresentation = RepresentationUtil.CreateSurfaceProductDefinitionShape(exporterIFC, element, geometryElement, true, exportAsFacetation);
                    }
                }

                List <int>      latitude     = new List <int>();
                List <int>      longitude    = new List <int>();
                ProjectLocation projLocation = doc.ActiveProjectLocation;

                IFCAnyHandle relativePlacement = null;
                double       unscaledElevation = 0.0;
                if (projLocation != null)
                {
                    const double scaleToDegrees = 180 / Math.PI;
                    double       latitudeInDeg  = projLocation.SiteLocation.Latitude * scaleToDegrees;
                    double       longitudeInDeg = projLocation.SiteLocation.Longitude * scaleToDegrees;

                    ExporterUtil.GetSafeProjectPositionAngle(doc, out unscaledElevation);

                    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 (!ExporterCacheManager.ExportOptionsCache.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 (!ExporterCacheManager.ExportOptionsCache.ExportAs2x2)
                    {
                        longitude.Add(longFracSec);
                    }

                    Transform siteSharedCoordinatesTrf = projLocation.GetTransform().Inverse;
                    if (!siteSharedCoordinatesTrf.IsIdentity)
                    {
                        double unscaledSiteElevation = ExporterCacheManager.ExportOptionsCache.IncludeSiteElevation ? 0.0 : unscaledElevation;
                        XYZ    orig = UnitUtil.ScaleLength(siteSharedCoordinatesTrf.Origin - new XYZ(0, 0, unscaledSiteElevation));
                        relativePlacement = ExporterUtil.CreateAxis2Placement3D(file, orig, siteSharedCoordinatesTrf.BasisZ, siteSharedCoordinatesTrf.BasisX);
                    }
                }

                // Get elevation for site.
                double elevation = UnitUtil.ScaleLength(unscaledElevation);

                if (IFCAnyHandleUtil.IsNullOrHasNoValue(relativePlacement))
                {
                    relativePlacement = ExporterUtil.CreateAxis2Placement3D(file);
                }

                IFCAnyHandle localPlacement = IFCInstanceExporter.CreateLocalPlacement(file, null, relativePlacement);
                IFCAnyHandle ownerHistory   = exporterIFC.GetOwnerHistoryHandle();
                string       siteObjectType = NamingUtil.CreateIFCObjectName(exporterIFC, element);

                ProjectInfo projectInfo     = doc.ProjectInformation;
                Element     mainSiteElement = (element != null) ? element : projectInfo;

                bool   exportSite          = false;
                string siteGUID            = null;
                string siteName            = null;
                string siteLongName        = null;
                string siteLandTitleNumber = null;
                string siteDescription     = null;

                if (element != null)
                {
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle))
                    {
                        exportSite = true;

                        // We will use the Project Information site name as the primary name, if it exists.
                        siteGUID = GUIDUtil.CreateSiteGUID(doc, element);

                        siteName        = NamingUtil.GetOverrideStringValue(projectInfo, "SiteName", NamingUtil.GetNameOverride(element, NamingUtil.GetIFCName(element)));
                        siteDescription = NamingUtil.GetDescriptionOverride(element, null);
                        siteObjectType  = NamingUtil.GetObjectTypeOverride(element, siteObjectType);

                        // Look in site element for "IfcLongName" or project information for either "IfcLongName" or "SiteLongName".
                        siteLongName = NamingUtil.GetLongNameOverride(projectInfo, NamingUtil.GetLongNameOverride(element, null));
                        if (string.IsNullOrWhiteSpace(siteLongName))
                        {
                            siteLongName = NamingUtil.GetOverrideStringValue(projectInfo, "SiteLongName", null);
                        }

                        // Look in site element for "IfcLandTitleNumber" or project information for "SiteLandTitleNumber".
                        siteLandTitleNumber = NamingUtil.GetOverrideStringValue(element, "IfcLandTitleNumber", null);
                        if (string.IsNullOrWhiteSpace(siteLandTitleNumber))
                        {
                            siteLandTitleNumber = NamingUtil.GetOverrideStringValue(projectInfo, "SiteLandTitleNumber", null);
                        }
                    }
                }
                else
                {
                    exportSite = true;

                    siteGUID            = GUIDUtil.CreateProjectLevelGUID(doc, IFCProjectLevelGUIDType.Site);
                    siteName            = NamingUtil.GetOverrideStringValue(projectInfo, "SiteName", "Default");
                    siteLongName        = NamingUtil.GetLongNameOverride(projectInfo, NamingUtil.GetOverrideStringValue(projectInfo, "SiteLongName", null));
                    siteLandTitleNumber = NamingUtil.GetOverrideStringValue(projectInfo, "SiteLandTitleNumber", null);

                    // don't bother if we have nothing in the site whatsoever.
                    if ((latitude.Count == 0 || longitude.Count == 0) && IFCAnyHandleUtil.IsNullOrHasNoValue(relativePlacement) &&
                        string.IsNullOrWhiteSpace(siteLongName) && string.IsNullOrWhiteSpace(siteLandTitleNumber))
                    {
                        return;
                    }
                }

                if (exportSite)
                {
                    siteHandle = IFCInstanceExporter.CreateSite(file, siteGUID, ownerHistory, siteName, siteDescription, siteObjectType, localPlacement,
                                                                siteRepresentation, siteLongName, Toolkit.IFCElementComposition.Element, latitude, longitude, elevation, siteLandTitleNumber, null);
                    productWrapper.AddSite(mainSiteElement, siteHandle);
                    exporterIFC.SetSite(siteHandle);
                }


                tr.Commit();
            }
        }
Пример #22
0
        /// <summary>
        /// Creates a facetation of a simple swept solid from a list of curve loops.
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="profileName">The profile name.</param>
        /// <param name="profileCurveLoops">The profile curve loops.</param>
        /// <param name="normal">The normal of the plane that the path lies on.</param>
        /// <param name="directrix">The path curve.</param>
        /// <returns>The list of facet handles.</returns>
        public static HashSet <IFCAnyHandle> CreateSimpleSweptSolidAsBRep(ExporterIFC exporterIFC, string profileName, IList <CurveLoop> profileCurveLoops,
                                                                          XYZ normal, Curve directrix)
        {
            // see definition of IfcSurfaceCurveSweptAreaSolid from
            // http://www.buildingsmart-tech.org/ifc/IFC2x4/rc4/html/schema/ifcgeometricmodelresource/lexical/ifcsurfacecurvesweptareasolid.htm

            HashSet <IFCAnyHandle> facetHnds = null;

            if (!CanCreateSimpleSweptSolid(profileCurveLoops, normal, directrix))
            {
                return(facetHnds);
            }

            // An extra requirement, as we can't tessellate an unbound curve.
            if (!directrix.IsBound)
            {
                return(facetHnds);
            }
            double originalStartParam = directrix.GetEndParameter(0);

            Plane axisPlane, profilePlane;

            CreateAxisAndProfileCurvePlanes(directrix, originalStartParam, out axisPlane, out profilePlane);

            IList <CurveLoop> curveLoops = null;

            try
            {
                // Check that curve loops are valid.
                curveLoops = ExporterIFCUtils.ValidateCurveLoops(profileCurveLoops, profilePlane.Normal);
            }
            catch (Exception)
            {
                return(null);
            }

            if (curveLoops == null || curveLoops.Count == 0)
            {
                return(facetHnds);
            }

            // Tessellate the curve loops.  We don't add the last point, as these should all be closed curves.
            IList <IList <XYZ> > tessellatedOutline = new List <IList <XYZ> >();

            foreach (CurveLoop curveLoop in curveLoops)
            {
                List <XYZ> tessellatedCurve = new List <XYZ>();
                foreach (Curve curve in curveLoop)
                {
                    if (curve is Line)
                    {
                        AddScaledPointToList(exporterIFC, tessellatedCurve, curve.GetEndPoint(0));
                    }
                    else
                    {
                        IList <XYZ> curveTessellation = CreateRoughTessellation(exporterIFC, curve);
                        tessellatedCurve.AddRange(curveTessellation);
                    }
                }

                if (tessellatedCurve.Count != 0)
                {
                    tessellatedOutline.Add(tessellatedCurve);
                }
            }

            IFCFile file = exporterIFC.GetFile();

            IList <IList <IList <IFCAnyHandle> > > facetVertexHandles = new List <IList <IList <IFCAnyHandle> > >();

            IList <IList <IFCAnyHandle> > tessellatedOutlineHandles = new List <IList <IFCAnyHandle> >();

            foreach (IList <XYZ> tessellatedOutlinePolygon in tessellatedOutline)
            {
                IList <IFCAnyHandle> tessellatedOutlinePolygonHandles = new List <IFCAnyHandle>();
                foreach (XYZ tessellatedOutlineXYZ in tessellatedOutlinePolygon)
                {
                    tessellatedOutlinePolygonHandles.Add(ExporterUtil.CreateCartesianPoint(file, tessellatedOutlineXYZ));
                }
                tessellatedOutlineHandles.Add(tessellatedOutlinePolygonHandles);
            }
            facetVertexHandles.Add(tessellatedOutlineHandles);

            // Tessellate the Directrix.  This only works for bound Directrix curves. Unfortunately, we get XYZ values, which we will have to convert
            // back to parameter values to get the local transform.
            IList <double> tessellatedDirectrixParameters = CreateRoughParametricTessellation(directrix);

            // Create all of the other outlines by transformng the first tessellated outline to the current transform.
            Transform profilePlaneTrf = Transform.CreateTranslation(ExporterIFCUtils.TransformAndScalePoint(exporterIFC, profilePlane.Origin));

            profilePlaneTrf.BasisX = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, profilePlane.XVec);
            profilePlaneTrf.BasisY = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, profilePlane.YVec);
            profilePlaneTrf.BasisZ = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, profilePlane.Normal);

            // The inverse transform will be applied to generate the delta transform for the profile curves from the start of the directrix
            // to the current location.  This could be optimized in the case of a Line, but current usage is really only for a single arc.
            // If that changes, we should revisit optimization possibilities.
            Transform profilePlaneTrfInverse = profilePlaneTrf.Inverse;

            // Create the delta transforms and the offset tessellated profiles.
            foreach (double parameter in tessellatedDirectrixParameters)
            {
                Transform directrixDirs  = CreateProfileCurveTransform(exporterIFC, directrix, parameter);
                Transform deltaTransform = directrixDirs.Multiply(profilePlaneTrfInverse);

                IList <IList <IFCAnyHandle> > currTessellatedOutline = new List <IList <IFCAnyHandle> >();
                foreach (IList <XYZ> pointLoop in tessellatedOutline)
                {
                    IList <IFCAnyHandle> currTessellatedPoinLoop = new List <IFCAnyHandle>();
                    foreach (XYZ point in pointLoop)
                    {
                        XYZ          transformedPoint       = deltaTransform.OfPoint(point);
                        IFCAnyHandle transformedPointHandle = ExporterUtil.CreateCartesianPoint(file, transformedPoint);
                        currTessellatedPoinLoop.Add(transformedPointHandle);
                    }
                    currTessellatedOutline.Add(currTessellatedPoinLoop);
                }
                facetVertexHandles.Add(currTessellatedOutline);
            }

            // Create the side facets.
            facetHnds = new HashSet <IFCAnyHandle>();

            int numFacets = facetVertexHandles.Count - 1;

            for (int ii = 0; ii < numFacets; ii++)
            {
                IList <IList <IFCAnyHandle> > firstOutline  = facetVertexHandles[ii];
                IList <IList <IFCAnyHandle> > secondOutline = facetVertexHandles[ii + 1];

                int numLoops = firstOutline.Count;
                for (int jj = 0; jj < numLoops; jj++)
                {
                    IList <IFCAnyHandle> firstLoop  = firstOutline[jj];
                    IList <IFCAnyHandle> secondLoop = secondOutline[jj];

                    int numVertices = firstLoop.Count;

                    for (int kk = 0; kk < numVertices; kk++)
                    {
                        IList <IFCAnyHandle> polyLoopHandles = new List <IFCAnyHandle>(4);
                        polyLoopHandles.Add(secondLoop[kk]);
                        polyLoopHandles.Add(secondLoop[(kk + 1) % numVertices]);
                        polyLoopHandles.Add(firstLoop[(kk + 1) % numVertices]);
                        polyLoopHandles.Add(firstLoop[kk]);

                        IFCAnyHandle face = BodyExporter.CreateFaceFromVertexList(file, polyLoopHandles);
                        facetHnds.Add(face);
                    }
                }
            }

            // Create the end facets.
            for (int ii = 0; ii < 2; ii++)
            {
                int faceIndex = (ii == 0) ? 0 : facetVertexHandles.Count - 1;

                int numLoops = facetVertexHandles[faceIndex].Count;
                HashSet <IFCAnyHandle> faceBounds = new HashSet <IFCAnyHandle>();

                for (int jj = 0; jj < numLoops; jj++)
                {
                    IList <IFCAnyHandle> polyLoopHandles = null;
                    if (ii == 0)
                    {
                        polyLoopHandles = facetVertexHandles[faceIndex][jj];
                    }
                    else
                    {
                        int numHandles = facetVertexHandles[faceIndex][jj].Count;
                        polyLoopHandles = new List <IFCAnyHandle>(numHandles);
                        for (int kk = numHandles - 1; kk >= 0; kk--)
                        {
                            polyLoopHandles.Add(facetVertexHandles[faceIndex][jj][kk]);
                        }
                    }

                    IFCAnyHandle polyLoop  = IFCInstanceExporter.CreatePolyLoop(file, polyLoopHandles);
                    IFCAnyHandle faceBound = (jj == 0) ?
                                             IFCInstanceExporter.CreateFaceOuterBound(file, polyLoop, true) :
                                             IFCInstanceExporter.CreateFaceBound(file, polyLoop, true);
                    faceBounds.Add(faceBound);
                }

                IFCAnyHandle face = IFCInstanceExporter.CreateFace(file, faceBounds);
                facetHnds.Add(face);
            }

            return(facetHnds);
        }
Пример #23
0
        /// <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)
        {
            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcPipeSegmentType;
            if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
            {
                return;
            }

            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                // Check for containment override
                IFCAnyHandle overrideContainerHnd = null;
                ElementId    overrideContainerId  = ParameterUtil.OverrideContainmentParameter(exporterIFC, element, out overrideContainerHnd);

                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element, null, null, overrideContainerId, overrideContainerHnd))
                {
                    using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData())
                    {
                        ecData.SetLocalPlacement(setter.LocalPlacement);

                        ElementId categoryId = CategoryUtil.GetSafeCategoryId(element);

                        BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                        IFCAnyHandle        bodyRep             = BodyExporter.ExportBody(exporterIFC, element, categoryId, ElementId.InvalidElementId,
                                                                                          geometryElement, bodyExporterOptions, ecData).RepresentationHnd;
                        if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRep))
                        {
                            if (ecData != null)
                            {
                                ecData.ClearOpenings();
                            }
                            return;
                        }
                        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, null, null, repMapList, IFCPipeSegmentType.Gutter);
                        IFCAnyHandleUtil.OverrideNameAttribute(style, elementTypeName);
                        IFCExportInfoPair exportInfo = new IFCExportInfoPair(IFCEntityType.IfcPipeSegmentType, IFCPipeSegmentType.Gutter.ToString());

                        IFCAnyHandleUtil.SetAttribute(style, "Tag", originalTag);
                        ExporterUtil.SetGlobalId(style, typeGuid);
                        IFCAnyHandleUtil.SetAttribute(style, "ElementType", elementTypeName);

                        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);

                        IFCAnyHandle elemHnd = IFCInstanceExporter.CreateFlowSegment(exporterIFC, element, guid,
                                                                                     ExporterCacheManager.OwnerHistoryHandle, localPlacementToUse, prodRep);

                        bool containedInSpace = (roomId != ElementId.InvalidElementId);
                        productWrapper.AddElement(element, elemHnd, setter.LevelInfo, ecData, !containedInSpace, exportInfo);

                        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();
                }
            }
        }
Пример #24
0
        /// <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 ExportGenericElement(ExporterIFC exporterIFC, Element element,
                                                        GeometryElement geometryElement, ProductWrapper productWrapper, IFCExportInfoPair exportType)
        {
            if (element == null || geometryElement == null)
            {
                return(null);
            }

            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            if (exportType.ExportInstance == IFCEntityType.UnKnown)
            {
                exportType.SetValueWithPair(IFCEntityType.IfcBuildingElementProxy, exportType.ValidatedPredefinedType);
            }
            if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(exportType.ExportInstance))
            {
                return(null);
            }

            // Check for containment override
            IFCAnyHandle overrideContainerHnd = null;
            ElementId    overrideContainerId  = ParameterUtil.OverrideContainmentParameter(exporterIFC, element, out overrideContainerHnd);

            IFCFile      file           = exporterIFC.GetFile();
            IFCAnyHandle instanceHandle = null;

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, element, null, null, overrideContainerId, overrideContainerHnd))
                {
                    using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData())
                    {
                        ecData.SetLocalPlacement(placementSetter.LocalPlacement);

                        ElementId categoryId = CategoryUtil.GetSafeCategoryId(element);

                        BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                        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;
                        IFCAnyHandle localPlacement = ecData.GetLocalPlacement();
                        IFCAnyHandle styleHandle    = null;

                        instanceHandle = FamilyExporterUtil.ExportGenericInstance(exportType, exporterIFC, element, productWrapper, placementSetter, ecData, guid, ownerHistory,
                                                                                  representation, exportType.ValidatedPredefinedType, null);

                        if (exportType.ExportType != IFCEntityType.UnKnown)
                        {
                            if (element is FamilyInstance)
                            {
                                FamilySymbol familySymbol = (element as FamilyInstance).Symbol;
                                if (familySymbol != null)
                                {
                                    HashSet <IFCAnyHandle> propertySetsOpt = new HashSet <IFCAnyHandle>();
                                    IList <IFCAnyHandle>   repMapListOpt   = new List <IFCAnyHandle>();

                                    styleHandle = FamilyExporterUtil.ExportGenericType(exporterIFC, exportType, exportType.ValidatedPredefinedType,
                                                                                       propertySetsOpt, repMapListOpt, element, familySymbol);
                                }
                            }
                            if (IFCAnyHandleUtil.IsNullOrHasNoValue(styleHandle))
                            {
                                styleHandle = ExporterUtil.CreateGenericTypeFromElement(element, exportType, file, ownerHistory, exportType.ValidatedPredefinedType, productWrapper);
                            }
                        }

                        if (!IFCAnyHandleUtil.IsNullOrHasNoValue(instanceHandle))
                        {
                            productWrapper.AddElement(element, instanceHandle, placementSetter.LevelInfo, ecData, true, exportType);
                            if (!IFCAnyHandleUtil.IsNullOrHasNoValue(styleHandle))
                            {
                                ExporterCacheManager.TypeRelationsCache.Add(styleHandle, instanceHandle);
                            }
                        }
                    }
                    tr.Commit();
                }
            }

            return(instanceHandle);
        }
        private void CalculateDoorWindowInformation(ExporterIFC exporterIFC, FamilyInstance famInst,
                                                    ElementId overrideLevelId, Transform trf)
        {
            IFCFile file = exporterIFC.GetFile();

            if (ExportingDoor)
            {
                string doorOperationType = null;

                Element doorType = famInst.Document.GetElement(famInst.GetTypeId());
                if (doorType != null)
                {
                    ParameterUtil.GetStringValueFromElement(doorType, BuiltInParameter.DOOR_OPERATION_TYPE, out doorOperationType);
                }

                DoorOperationTypeString = "NOTDEFINED";
                if (!string.IsNullOrWhiteSpace(doorOperationType))
                {
                    Type enumType = null;
                    if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                    {
                        enumType = typeof(Toolkit.IFC4.IFCDoorStyleOperation);
                    }
                    else
                    {
                        enumType = typeof(Toolkit.IFCDoorStyleOperation);
                    }

                    foreach (Enum ifcDoorStyleOperation in Enum.GetValues(enumType))
                    {
                        string enumAsString = ifcDoorStyleOperation.ToString();
                        if (NamingUtil.IsEqualIgnoringCaseSpacesAndUnderscores(enumAsString, doorOperationType))
                        {
                            DoorOperationTypeString = enumAsString;
                            break;
                        }
                    }
                }

                if (DoorOperationTypeString == "NOTDEFINED")
                {
                    // We are going to try to guess the hinge placement.
                    DoorOperationTypeString = CalculateDoorOperationStyle(famInst);
                }

                if (FlippedX ^ FlippedY)
                {
                    DoorOperationTypeString = ReverseDoorStyleOperation(DoorOperationTypeString);
                }

                if (String.Compare(DoorOperationTypeString, "USERDEFINED", true) == 0)
                {
                    string userDefinedOperationType;
                    ParameterUtil.GetStringValueFromElementOrSymbol(doorType, "UserDefinedOperationType", out userDefinedOperationType);
                    if (!string.IsNullOrEmpty(userDefinedOperationType))
                    {
                        UserDefinedOperationType = userDefinedOperationType;
                    }
                    else
                    {
                        DoorOperationTypeString = "NOTDEFINED";   //re-set to NotDefined if operation type is set to UserDefined but the userDefinedOperationType parameter is empty!
                    }
                }

                // Get override operationtype from parameter Operation
                ParameterUtil.GetStringValueFromElementOrSymbol(doorType, "Operation", out doorOperationType);
                if (!string.IsNullOrEmpty(doorOperationType))
                {
                    if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                    {
                        Toolkit.IFC4.IFCDoorTypeOperation doorOp = Toolkit.IFC4.IFCDoorTypeOperation.NOTDEFINED;
                        if (Enum.TryParse <Toolkit.IFC4.IFCDoorTypeOperation>(doorOperationType, true, out doorOp))
                        {
                            DoorOperationTypeString = doorOp.ToString();
                        }
                    }
                    else
                    {
                        Toolkit.IFCDoorStyleOperation doorOp = Toolkit.IFCDoorStyleOperation.NotDefined;
                        if (Enum.TryParse <Toolkit.IFCDoorStyleOperation>(doorOperationType, true, out doorOp))
                        {
                            DoorOperationTypeString = doorOp.ToString();
                        }
                    }
                }
            }

            if (HasRealWallHost)
            {
                // do hingeside calculation
                Wall wall = HostObject as Wall;
                PosHingeSide = true;

                BoundingBoxXYZ  famBBox     = null;
                Options         options     = GeometryUtil.GetIFCExportGeometryOptions();
                GeometryElement geomElement = famInst.GetOriginalGeometry(options);
                if (geomElement != null)
                {
                    famBBox = geomElement.GetBoundingBox();
                }

                if (famBBox != null)
                {
                    XYZ bboxCtr = trf.OfPoint((famBBox.Min + famBBox.Max) / 2.0);

                    Curve curve = WallExporter.GetWallAxis(wall);

                    XYZ wallZDir = WallExporter.GetWallHeightDirection(wall);

                    // famInst.HostParameter will fail if FamilyPlacementType is WorkPlaneBased, regardless of whether or not the reported host is a Wall.
                    // In this case, just use the start parameter of the curve.
                    bool   hasHostParameter = famInst.Symbol.Family.FamilyPlacementType != FamilyPlacementType.WorkPlaneBased;
                    double param            = hasHostParameter ? famInst.HostParameter : curve.GetEndParameter(0);

                    Transform wallTrf  = curve.ComputeDerivatives(param, false);
                    XYZ       wallOrig = wallTrf.Origin;
                    XYZ       wallXDir = wallTrf.BasisX;
                    XYZ       wallYDir = wallZDir.CrossProduct(wallXDir);

                    double eps = MathUtil.Eps();

                    bboxCtr     -= wallOrig;
                    PosHingeSide = (bboxCtr.DotProduct(wallYDir) > -eps);

                    XYZ famInstYDir = trf.BasisY;
                    FlippedSymbol = (PosHingeSide != (wallYDir.DotProduct(famInstYDir) > -eps));
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Exports an element as an annotation.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="filledRegion">The filled region element.</param>
        /// <param name="geometryElement">The geometry element.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        public static void Export(ExporterIFC exporterIFC, FilledRegion filledRegion,
                                  GeometryElement geometryElement, ProductWrapper productWrapper)
        {
            if (filledRegion == null || geometryElement == 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))
            {
                IList <CurveLoop> boundaries = filledRegion.GetBoundaries();
                if (boundaries.Count == 0)
                {
                    return;
                }

                Plane plane = null;
                try
                {
                    plane = boundaries[0].GetPlane();
                }
                catch
                {
                    return;
                }

                Transform orientTrf           = GeometryUtil.CreateTransformFromPlane(plane);
                XYZ       projectionDirection = plane.Normal;

                IList <IList <CurveLoop> > sortedLoops = ExporterIFCUtils.SortCurveLoops(boundaries);
                if (sortedLoops.Count == 0)
                {
                    return;
                }

                FilledRegionType filledRegionType = filledRegion.Document.GetElement(filledRegion.GetTypeId()) as FilledRegionType;
                Color            color            = filledRegionType != null?CategoryUtil.GetSafeColor(filledRegionType.ForegroundPatternColor) : new Color(0, 0, 0);

                ElementId foregroundPatternId = filledRegionType != null ? filledRegionType.ForegroundPatternId : ElementId.InvalidElementId;
                ElementId categoryId          = CategoryUtil.GetSafeCategoryId(filledRegion);

                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, filledRegion, null, orientTrf))
                {
                    foreach (IList <CurveLoop> curveLoopList in sortedLoops)
                    {
                        IFCAnyHandle           outerCurve  = null;
                        HashSet <IFCAnyHandle> innerCurves = null;
                        for (int ii = 0; ii < curveLoopList.Count; ii++)
                        {
                            IFCAnyHandle ifcCurve = GeometryUtil.CreateIFCCurveFromCurveLoop(exporterIFC, curveLoopList[ii], orientTrf, projectionDirection);
                            if (ii == 0)
                            {
                                outerCurve = ifcCurve;
                            }
                            else
                            {
                                if (innerCurves == null)
                                {
                                    innerCurves = new HashSet <IFCAnyHandle>();
                                }
                                innerCurves.Add(ifcCurve);
                            }
                        }

                        IFCAnyHandle representItem = IFCInstanceExporter.CreateAnnotationFillArea(file, outerCurve, innerCurves);
                        file.CreateStyle(exporterIFC, representItem, color, foregroundPatternId);

                        HashSet <IFCAnyHandle> bodyItems = new HashSet <IFCAnyHandle>();
                        bodyItems.Add(representItem);
                        IFCAnyHandle bodyRepHnd = RepresentationUtil.CreateAnnotationSetRep(exporterIFC, filledRegion, categoryId,
                                                                                            exporterIFC.Get2DContextHandle(), bodyItems);

                        if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRepHnd))
                        {
                            return;
                        }

                        List <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>();
                        shapeReps.Add(bodyRepHnd);

                        IFCAnyHandle productShape = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps);
                        IFCAnyHandle annotation   = IFCInstanceExporter.CreateAnnotation(exporterIFC, filledRegion, GUIDUtil.CreateGUID(), ExporterCacheManager.OwnerHistoryHandle,
                                                                                         setter.LocalPlacement, productShape);

                        productWrapper.AddAnnotation(annotation, setter.LevelInfo, true);
                    }
                }

                transaction.Commit();
            }
        }
Пример #27
0
 /// <summary>
 /// Creates a copy of local placement object.
 /// </summary>
 /// <param name="file">
 /// The IFC file.
 /// </param>
 /// <param name="originalPlacement">
 /// The original placement object to be copied.
 /// </param>
 /// <returns>
 /// The handle.
 /// </returns>
 public static IFCAnyHandle CopyLocalPlacement(IFCFile file, IFCAnyHandle originalPlacement)
 {
     IFCAnyHandle placementRelToOpt = GeometryUtil.GetPlacementRelToFromLocalPlacement(originalPlacement);
     IFCAnyHandle relativePlacement = GeometryUtil.GetRelativePlacementFromLocalPlacement(originalPlacement);
     return IFCInstanceExporter.CreateLocalPlacement(file, placementRelToOpt, relativePlacement);
 }
Пример #28
0
        /// <summary>
        /// Get the handles of Grid Axes.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="sameDirectionAxes">The grid axes in the same direction of one level.</param>
        /// <param name="representations">The representation of grid axis.</param>
        /// <returns>The list of handles of grid axes.</returns>
        private static List <IFCAnyHandle> CreateIFCGridAxisAndRepresentations(ExporterIFC exporterIFC, ProductWrapper productWrapper, IList <Grid> sameDirectionAxes,
                                                                               IList <IFCAnyHandle> representations, GridRepresentationData gridRepresentationData)
        {
            if (sameDirectionAxes.Count == 0)
            {
                return(null);
            }

            IDictionary <ElementId, List <IFCAnyHandle> > gridAxisMap = new Dictionary <ElementId, List <IFCAnyHandle> >();
            IDictionary <ElementId, List <IFCAnyHandle> > gridRepMap  = new Dictionary <ElementId, List <IFCAnyHandle> >();

            IFCFile ifcFile  = exporterIFC.GetFile();
            Grid    baseGrid = sameDirectionAxes[0];

            Transform lcs = Transform.Identity;

            List <IFCAnyHandle> ifcGridAxes = new List <IFCAnyHandle>();

            foreach (Grid grid in sameDirectionAxes)
            {
                // Because the IfcGrid is a collection of Revit Grids, any one of them can override the IFC CAD Layer.
                // We will take the first name, and not do too much checking.
                if (string.IsNullOrWhiteSpace(gridRepresentationData.m_IFCCADLayer))
                {
                    ParameterUtil.GetStringValueFromElementOrSymbol(grid, "IFCCadLayer", out gridRepresentationData.m_IFCCADLayer);
                }

                // Get the handle of curve.
                XYZ             projectionDirection = lcs.BasisZ;
                IFCGeometryInfo info = IFCGeometryInfo.CreateCurveGeometryInfo(exporterIFC, lcs, projectionDirection, false);
                ExporterIFCUtils.CollectGeometryInfo(exporterIFC, info, grid.Curve, XYZ.Zero, false);
                IList <IFCAnyHandle> curves = info.GetCurves();
                if (curves.Count != 1)
                {
                    throw new Exception("IFC: expected 1 curve when export curve element.");
                }

                IFCAnyHandle axisCurve = curves[0];

                bool sameSense = true;
                if (baseGrid.Curve is Line)
                {
                    Line baseLine = baseGrid.Curve as Line;
                    Line axisLine = grid.Curve as Line;
                    sameSense = (axisLine.Direction.IsAlmostEqualTo(baseLine.Direction));
                }

                IFCAnyHandle ifcGridAxis = IFCInstanceExporter.CreateGridAxis(ifcFile, grid.Name, axisCurve, sameSense);
                ifcGridAxes.Add(ifcGridAxis);

                HashSet <IFCAnyHandle> AxisCurves = new HashSet <IFCAnyHandle>();
                AxisCurves.Add(axisCurve);

                IFCAnyHandle repItemHnd = IFCInstanceExporter.CreateGeometricCurveSet(ifcFile, AxisCurves);

                // get the weight and color from the GridType to create the curve style.
                GridType gridType = grid.Document.GetElement(grid.GetTypeId()) as GridType;

                IFCData curveWidth = null;
                if (ExporterCacheManager.ExportOptionsCache.ExportAnnotations)
                {
                    int    outWidth;
                    double width =
                        (ParameterUtil.GetIntValueFromElement(gridType, BuiltInParameter.GRID_END_SEGMENT_WEIGHT, out outWidth) != null) ? outWidth : 1;
                    curveWidth = IFCDataUtil.CreateAsPositiveLengthMeasure(width);
                }

                int outColor;
                int color =
                    (ParameterUtil.GetIntValueFromElement(gridType, BuiltInParameter.GRID_END_SEGMENT_COLOR, out outColor) != null) ? outColor : 0;
                double blueVal  = 0.0;
                double greenVal = 0.0;
                double redVal   = 0.0;
                GeometryUtil.GetRGBFromIntValue(color, out blueVal, out greenVal, out redVal);
                IFCAnyHandle colorHnd = IFCInstanceExporter.CreateColourRgb(ifcFile, null, redVal, greenVal, blueVal);

                BodyExporter.CreateCurveStyleForRepItem(exporterIFC, repItemHnd, curveWidth, colorHnd);

                HashSet <IFCAnyHandle> curveSet = new HashSet <IFCAnyHandle>();
                curveSet.Add(repItemHnd);

                gridRepresentationData.m_Grids.Add(grid);
                gridRepresentationData.m_curveSets.Add(curveSet);
            }

            return(ifcGridAxes);
        }
Пример #29
0
 /// <summary>
 /// Creates a new local placement object.
 /// </summary>
 /// <param name="file">The IFC file.</param>
 /// <param name="placementRelTo">The placement object.</param>
 /// <param name="location">The relative placement origin.</param>
 /// <param name="axis">The relative placement Z value.</param>
 /// <param name="refDirection">The relative placement X value.</param>
 /// <returns></returns>
 public static IFCAnyHandle CreateLocalPlacement(IFCFile file, IFCAnyHandle placementRelTo, XYZ location, XYZ axis, XYZ refDirection)
 {
     IFCAnyHandle relativePlacement = ExporterUtil.CreateAxis2Placement3D(file, location, axis, refDirection);
     return IFCInstanceExporter.CreateLocalPlacement(file, placementRelTo, relativePlacement);
 }
Пример #30
0
        /// <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.LevelId, false))
            {
                return;
            }

            // 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>("IfcCovering", out elementClassTypeEnum))
            {
                if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
                {
                    return;
                }
            }

            ElementType elemType = element.Document.GetElement(element.GetTypeId()) as ElementType;
            IFCFile     file     = exporterIFC.GetFile();

            using (IFCTransaction transaction = new IFCTransaction(file))
            {
                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element))
                {
                    using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData())
                    {
                        ElementId categoryId = CategoryUtil.GetSafeCategoryId(element);

                        IFCAnyHandle prodRep = null;
                        if (!exportParts)
                        {
                            ecData.SetLocalPlacement(setter.LocalPlacement);
                            ecData.PossibleExtrusionAxes = IFCExtrusionAxes.TryZ;

                            BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                            prodRep = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, element,
                                                                                                 categoryId, geomElem, bodyExporterOptions, null, ecData, true);
                            if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodRep))
                            {
                                ecData.ClearOpenings();
                                return;
                            }
                        }

                        // We will use the category of the element to set a default value for the covering.
                        string defaultCoveringEnumType = null;

                        if (categoryId == new ElementId(BuiltInCategory.OST_Ceilings))
                        {
                            defaultCoveringEnumType = "CEILING";
                        }
                        else if (categoryId == new ElementId(BuiltInCategory.OST_Floors))
                        {
                            defaultCoveringEnumType = "FLOORING";
                        }
                        else if (categoryId == new ElementId(BuiltInCategory.OST_Roofs))
                        {
                            defaultCoveringEnumType = "ROOFING";
                        }

                        string instanceGUID        = GUIDUtil.CreateGUID(element);
                        string instanceName        = NamingUtil.GetNameOverride(element, NamingUtil.GetIFCName(element));
                        string instanceDescription = NamingUtil.GetDescriptionOverride(element, null);
                        string instanceObjectType  = NamingUtil.GetObjectTypeOverride(element, exporterIFC.GetFamilyName());
                        string instanceTag         = NamingUtil.GetTagOverride(element, NamingUtil.CreateIFCElementId(element));
                        string coveringType        = IFCValidateEntry.GetValidIFCType(element, ifcEnumType, defaultCoveringEnumType);

                        IFCAnyHandle covering = IFCInstanceExporter.CreateCovering(file, instanceGUID, ExporterCacheManager.OwnerHistoryHandle,
                                                                                   instanceName, instanceDescription, instanceObjectType, setter.LocalPlacement, prodRep, instanceTag, coveringType);

                        if (exportParts)
                        {
                            PartExporter.ExportHostPart(exporterIFC, element, covering, productWrapper, setter, setter.LocalPlacement, null);
                        }

                        bool         containInSpace      = false;
                        IFCAnyHandle localPlacementToUse = setter.LocalPlacement;

                        // Ceiling containment in Space is generally required and not specific to any view
                        if (ExporterCacheManager.CeilingSpaceRelCache.ContainsKey(element.Id))
                        {
                            IList <ElementId> roomlist = ExporterCacheManager.CeilingSpaceRelCache[element.Id];

                            // Process Ceiling to be contained in a Space only when it is exactly bounding one Space
                            if (roomlist.Count == 1)
                            {
                                productWrapper.AddElement(element, covering, setter, null, false);

                                // Modify the Ceiling placement to be relative to the Space that it bounds
                                IFCAnyHandle roomPlacement     = IFCAnyHandleUtil.GetObjectPlacement(ExporterCacheManager.SpaceInfoCache.FindSpaceHandle(roomlist[0]));
                                Transform    relTrf            = ExporterIFCUtils.GetRelativeLocalPlacementOffsetTransform(roomPlacement, localPlacementToUse);
                                Transform    inverseTrf        = relTrf.Inverse;
                                IFCAnyHandle relLocalPlacement = ExporterUtil.CreateAxis2Placement3D(file, inverseTrf.Origin, inverseTrf.BasisZ, inverseTrf.BasisX);
                                IFCAnyHandleUtil.SetAttribute(localPlacementToUse, "PlacementRelTo", roomPlacement);
                                GeometryUtil.SetRelativePlacement(localPlacementToUse, relLocalPlacement);

                                ExporterCacheManager.SpaceInfoCache.RelateToSpace(roomlist[0], covering);
                                containInSpace = true;
                            }
                        }

                        // if not contained in Space, assign it to default containment in Level
                        if (!containInSpace)
                        {
                            productWrapper.AddElement(element, covering, setter, null, true);
                        }

                        if (!exportParts)
                        {
                            Ceiling ceiling = element as Ceiling;
                            if (ceiling != null)
                            {
                                HostObjectExporter.ExportHostObjectMaterials(exporterIFC, ceiling, covering,
                                                                             geomElem, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, null);
                            }
                            else
                            {
                                ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geomElem, exporterIFC, element);
                                CategoryUtil.CreateMaterialAssociation(exporterIFC, covering, matId);
                            }
                        }

                        OpeningUtil.CreateOpeningsIfNecessary(covering, element, ecData, null,
                                                              exporterIFC, ecData.GetLocalPlacement(), setter, productWrapper);
                    }
                }
                transaction.Commit();
            }
        }
Пример #31
0
        /// <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);
                        IFCExportInfoPair exportInfo = new IFCExportInfoPair(IFCEntityType.IfcReinforcingMesh);

                        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, exportInfo);

                        CategoryUtil.CreateMaterialAssociation(exporterIFC, fabricSheet, materialId);
                    }
                }
                tr.Commit();
                return(true);
            }
        }
Пример #32
0
        /// <summary>
        ///  Exports a roof or floor 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 or floor element.</param>
        /// <param name="geometry">The geometry of the element.</param>
        /// <param name="productWrapper">The product wrapper.</param>
        /// <returns>The roof handle.</returns>
        /// <remarks>For floors, if there is only one component, return null, as we do not want to create a container.</remarks>
        public static IFCAnyHandle ExportRoofOrFloorAsContainer(ExporterIFC exporterIFC, string ifcEnumType, Element element, GeometryElement geometry, ProductWrapper productWrapper)
        {
            IFCFile file = exporterIFC.GetFile();

            // We support ExtrusionRoofs, FootPrintRoofs, and Floors only.
            bool elementIsRoof  = (element is ExtrusionRoof) || (element is FootPrintRoof);
            bool elementIsFloor = (element is Floor);

            if (!elementIsRoof && !elementIsFloor)
            {
                return(null);
            }

            Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcRoof;
            if (elementIsFloor)
            {
                elementClassTypeEnum = Common.Enums.IFCEntityType.IfcSlab;
            }

            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
            {
                return(null);
            }

            using (IFCTransaction transaction = new IFCTransaction(file))
            {
                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, element))
                {
                    IFCAnyHandle localPlacement = setter.LocalPlacement;
                    IList <HostObjectSubcomponentInfo> hostObjectSubcomponents = null;
                    try
                    {
                        hostObjectSubcomponents = ExporterIFCUtils.ComputeSubcomponents(element as HostObject);
                    }
                    catch
                    {
                        return(null);
                    }

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

                    int numSubcomponents = hostObjectSubcomponents.Count;
                    if (numSubcomponents == 0 || (elementIsFloor && numSubcomponents == 1))
                    {
                        return(null);
                    }

                    try
                    {
                        using (IFCExtrusionCreationData extrusionCreationData = new IFCExtrusionCreationData())
                        {
                            IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle;
                            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 hostObjectType = IFCValidateEntry.GetValidIFCPredefinedType(element, ifcEnumType);

                                IFCAnyHandle hostObjectHandle = null;
                                if (elementIsRoof)
                                {
                                    hostObjectHandle = IFCInstanceExporter.CreateRoof(exporterIFC, element, elementGUID, ownerHistory,
                                                                                      localPlacement, prodRepHnd, ifcEnumType);
                                }
                                else
                                {
                                    hostObjectHandle = IFCInstanceExporter.CreateSlab(exporterIFC, element, elementGUID, ownerHistory,
                                                                                      localPlacement, prodRepHnd, ifcEnumType);
                                }

                                if (IFCAnyHandleUtil.IsNullOrHasNoValue(hostObjectHandle))
                                {
                                    return(null);
                                }

                                IList <IFCAnyHandle> elementHandles = new List <IFCAnyHandle>();
                                elementHandles.Add(hostObjectHandle);

                                // If element is floor, then the profile curve loop of hostObjectSubComponent is computed from the top face of the floor
                                // else if element is roof, then the profile curve loop is taken from the bottom face of the roof instead
                                XYZ extrusionDir = elementIsFloor ? new XYZ(0, 0, -1) : new XYZ(0, 0, 1);

                                ElementId catId = CategoryUtil.GetSafeCategoryId(element);

                                IList <IFCAnyHandle> slabHandles = new List <IFCAnyHandle>();

                                IList <CurveLoop> hostObjectOpeningLoops = new List <CurveLoop>();
                                double            maximumScaledDepth     = 0.0;

                                using (IFCExtrusionCreationData slabExtrusionCreationData = new IFCExtrusionCreationData())
                                {
                                    slabExtrusionCreationData.SetLocalPlacement(extrusionCreationData.GetLocalPlacement());
                                    slabExtrusionCreationData.ReuseLocalPlacement = false;
                                    slabExtrusionCreationData.ForceOffset         = true;

                                    int    loopNum         = 0;
                                    int    subElementStart = elementIsRoof ? (int)IFCRoofSubElements.RoofSlabStart : (int)IFCSlabSubElements.SubSlabStart;
                                    string subSlabType     = elementIsRoof ? "ROOF" : ifcEnumType;

                                    foreach (HostObjectSubcomponentInfo hostObjectSubcomponent in hostObjectSubcomponents)
                                    {
                                        trfSetter.InitializeFromBoundingBox(exporterIFC, geometryList, slabExtrusionCreationData);
                                        Plane     plane = hostObjectSubcomponent.GetPlane();
                                        Transform lcs   = GeometryUtil.CreateTransformFromPlane(plane);

                                        IList <CurveLoop> curveLoops = new List <CurveLoop>();

                                        CurveLoop slabCurveLoop = hostObjectSubcomponent.GetCurveLoop();
                                        curveLoops.Add(slabCurveLoop);
                                        double slope = Math.Abs(plane.Normal.Z);

                                        double       scaledDepth          = UnitUtil.ScaleLength(hostObjectSubcomponent.Depth);
                                        double       scaledExtrusionDepth = scaledDepth * slope;
                                        IFCAnyHandle shapeRep             = ExtrusionExporter.CreateExtrudedSolidFromCurveLoop(exporterIFC, null, curveLoops, lcs, extrusionDir, scaledExtrusionDepth, false);
                                        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 = (loopNum < 256) ? GUIDUtil.CreateSubElementGUID(element, subElementStart + loopNum) : GUIDUtil.CreateGUID();

                                        IFCAnyHandle slabPlacement = ExporterUtil.CreateLocalPlacement(file, slabExtrusionCreationData.GetLocalPlacement(), null);
                                        IFCAnyHandle slabHnd       = IFCInstanceExporter.CreateSlab(exporterIFC, element, slabGUID, ownerHistory,
                                                                                                    slabPlacement, repHnd, subSlabType);

                                        //slab quantities
                                        slabExtrusionCreationData.ScaledLength         = scaledExtrusionDepth;
                                        slabExtrusionCreationData.ScaledArea           = UnitUtil.ScaleArea(UnitUtil.ScaleArea(hostObjectSubcomponent.AreaOfCurveLoop));
                                        slabExtrusionCreationData.ScaledOuterPerimeter = UnitUtil.ScaleLength(curveLoops[0].GetExactLength());
                                        slabExtrusionCreationData.Slope = UnitUtil.ScaleAngle(MathUtil.SafeAcos(Math.Abs(slope)));

                                        productWrapper.AddElement(null, slabHnd, setter, slabExtrusionCreationData, false);
                                        elementHandles.Add(slabHnd);
                                        slabHandles.Add(slabHnd);

                                        hostObjectOpeningLoops.Add(slabCurveLoop);
                                        maximumScaledDepth = Math.Max(maximumScaledDepth, scaledDepth);
                                        loopNum++;
                                    }
                                }

                                productWrapper.AddElement(element, hostObjectHandle, setter, extrusionCreationData, true);

                                ExporterUtil.RelateObjects(exporterIFC, null, hostObjectHandle, slabHandles);

                                OpeningUtil.AddOpeningsToElement(exporterIFC, elementHandles, hostObjectOpeningLoops, element, null, maximumScaledDepth,
                                                                 null, setter, localPlacement, productWrapper);

                                transaction.Commit();
                                return(hostObjectHandle);
                            }
                        }
                    }
                    finally
                    {
                        exporterIFC.ClearFaceWithElementHandleMap();
                    }
                }
            }
        }
Пример #33
0
        /// <summary>
        /// Export one IFCGrid in one level.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="levelId">The level ID.</param>
        /// <param name="sameDirectionAxesU">The U axes of grids.</param>
        /// <param name="sameDirectionAxesV">The V axes of grids.</param>
        /// <param name="sameDirectionAxesW">The W axes of grids.</param>
        public static void ExportGrid(ExporterIFC exporterIFC, ElementId levelId, List <Grid> sameDirectionAxesU, List <Grid> sameDirectionAxesV, List <Grid> sameDirectionAxesW)
        {
            List <IFCAnyHandle> axesU           = null;
            List <IFCAnyHandle> axesV           = null;
            List <IFCAnyHandle> axesW           = null;
            List <IFCAnyHandle> representations = new List <IFCAnyHandle>();

            using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true))
            {
                IFCFile ifcFile = exporterIFC.GetFile();
                using (IFCTransaction transaction = new IFCTransaction(ifcFile))
                {
                    GridRepresentationData gridRepresentationData = new GridRepresentationData();

                    axesU = CreateIFCGridAxisAndRepresentations(exporterIFC, productWrapper, sameDirectionAxesU, representations, gridRepresentationData);
                    axesV = CreateIFCGridAxisAndRepresentations(exporterIFC, productWrapper, sameDirectionAxesV, representations, gridRepresentationData);
                    if (sameDirectionAxesW != null)
                    {
                        axesW = CreateIFCGridAxisAndRepresentations(exporterIFC, productWrapper, sameDirectionAxesW, representations, gridRepresentationData);
                    }

                    IFCAnyHandle contextOfItemsFootPrint = exporterIFC.Get3DContextHandle("FootPrint");
                    string       identifierOpt           = "FootPrint";
                    string       representationTypeOpt   = "GeometricCurveSet";

                    int numGridsToExport = gridRepresentationData.m_Grids.Count;
                    if (numGridsToExport == 0)
                    {
                        return;
                    }

                    bool useIFCCADLayer = !string.IsNullOrWhiteSpace(gridRepresentationData.m_IFCCADLayer);

                    IFCAnyHandle shapeRepresentation = null;

                    HashSet <IFCAnyHandle> allCurves = new HashSet <IFCAnyHandle>();
                    for (int ii = 0; ii < numGridsToExport; ii++)
                    {
                        allCurves.UnionWith(gridRepresentationData.m_curveSets[ii]);
                    }

                    if (useIFCCADLayer)
                    {
                        shapeRepresentation = RepresentationUtil.CreateShapeRepresentation(exporterIFC, contextOfItemsFootPrint,
                                                                                           identifierOpt, representationTypeOpt, allCurves, gridRepresentationData.m_IFCCADLayer);
                    }
                    else
                    {
                        ElementId catId = CategoryUtil.GetSafeCategoryId(gridRepresentationData.m_Grids[0]);
                        shapeRepresentation = RepresentationUtil.CreateShapeRepresentation(exporterIFC, gridRepresentationData.m_Grids[0], catId,
                                                                                           contextOfItemsFootPrint, identifierOpt, representationTypeOpt, allCurves);
                    }
                    representations.Add(shapeRepresentation);

                    IFCAnyHandle productRep = IFCInstanceExporter.CreateProductDefinitionShape(ifcFile, null, null, representations);

                    // We will associate the grid with its level, unless there are no levels in the file, in which case we'll associate it with the building.
                    IFCLevelInfo levelInfo    = ExporterCacheManager.LevelInfoCache.GetLevelInfo(exporterIFC, levelId);
                    bool         useLevelInfo = (levelInfo != null);

                    string gridGUID = GUIDUtil.CreateGUID();

                    // Get the first grid's override name, if cannot find it, use null.
                    string       gridName             = GetGridName(sameDirectionAxesU, sameDirectionAxesV, sameDirectionAxesW);
                    IFCAnyHandle ownerHistory         = ExporterCacheManager.OwnerHistoryHandle;
                    IFCAnyHandle gridLevelHandle      = useLevelInfo ? levelInfo.GetBuildingStorey() : ExporterCacheManager.BuildingHandle;
                    IFCAnyHandle levelObjectPlacement = IFCAnyHandleUtil.GetObjectPlacement(gridLevelHandle);
                    double       elev               = useLevelInfo ? levelInfo.Elevation : 0.0;
                    double       elevation          = UnitUtil.ScaleLength(elev);
                    XYZ          orig               = new XYZ(0.0, 0.0, elevation);
                    IFCAnyHandle copyLevelPlacement = ExporterUtil.CopyLocalPlacement(ifcFile, levelObjectPlacement);
                    IFCAnyHandle ifcGrid            = IFCInstanceExporter.CreateGrid(exporterIFC, gridGUID, ownerHistory, gridName, copyLevelPlacement, productRep, axesU, axesV, axesW);

                    productWrapper.AddElement(null, ifcGrid, levelInfo, null, true);

                    transaction.Commit();
                }
            }
        }
Пример #34
0
        /// <summary>
        /// Exports a generic family instance as IFC instance.
        /// </summary>
        /// <param name="type">The export type.</param>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="familyInstance">The element.</param>
        /// <param name="wrapper">The ProductWrapper.</param>
        /// <param name="setter">The PlacementSetter.</param>
        /// <param name="extraParams">The extrusion creation data.</param>
        /// <param name="instanceGUID">The guid.</param>
        /// <param name="ownerHistory">The owner history handle.</param>
        /// <param name="instanceName">The name.</param>
        /// <param name="instanceDescription">The description.</param>
        /// <param name="instanceObjectType">The object type.</param>
        /// <param name="productRepresentation">The representation handle.</param>
        /// <param name="instanceTag">The tag for the entity, usually based on the element id.</param>
        /// <param name="ifcEnumType">The predefined type/shape type, if any, for the object.</param>
        /// <param name="overrideLocalPlacement">The local placement to use instead of the one in the placement setter, if appropriate.</param>
        /// <returns>The handle.</returns>
        public static IFCAnyHandle ExportGenericInstance(IFCExportInfoPair type,
                                                         ExporterIFC exporterIFC, Element familyInstance,
                                                         ProductWrapper wrapper, PlacementSetter setter, IFCExtrusionCreationData extraParams,
                                                         string instanceGUID, IFCAnyHandle ownerHistory, IFCAnyHandle productRepresentation,
                                                         string ifcEnumType, IFCAnyHandle overrideLocalPlacement)
        {
            IFCFile  file = exporterIFC.GetFile();
            Document doc  = familyInstance.Document;

            bool isRoomRelated      = IsRoomRelated(type);
            bool isChildInContainer = familyInstance.AssemblyInstanceId != ElementId.InvalidElementId;

            IFCAnyHandle localPlacementToUse = setter.LocalPlacement;
            ElementId    roomId = ElementId.InvalidElementId;

            if (isRoomRelated)
            {
                roomId = setter.UpdateRoomRelativeCoordinates(familyInstance, out localPlacementToUse);
            }

            //should remove the create method where there is no use of this handle for API methods
            //some places uses the return value of ExportGenericInstance as input parameter for API methods
            IFCAnyHandle instanceHandle = null;

            switch (type.ExportInstance)
            {
            case IFCEntityType.IfcBeam:
            {
                string preDefinedType = string.IsNullOrWhiteSpace(type.ValidatedPredefinedType) ? "BEAM" : type.ValidatedPredefinedType;
                instanceHandle = IFCInstanceExporter.CreateBeam(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                localPlacementToUse, productRepresentation, preDefinedType);
                break;
            }

            case IFCEntityType.IfcColumn:
            {
                string preDefinedType = string.IsNullOrWhiteSpace(type.ValidatedPredefinedType) ? "COLUMN" : type.ValidatedPredefinedType;
                instanceHandle = IFCInstanceExporter.CreateColumn(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                  localPlacementToUse, productRepresentation, preDefinedType);
                break;
            }

            case IFCEntityType.IfcCurtainWall:
            {
                instanceHandle = IFCInstanceExporter.CreateCurtainWall(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                       localPlacementToUse, productRepresentation, type.ValidatedPredefinedType);
                break;
            }

            case IFCEntityType.IfcMember:
            {
                string preDefinedType = string.IsNullOrWhiteSpace(type.ValidatedPredefinedType) ? "BRACE" : type.ValidatedPredefinedType;
                instanceHandle = IFCInstanceExporter.CreateMember(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                  localPlacementToUse, productRepresentation, preDefinedType);

                // Register the members's IFC handle for later use by truss export.
                ExporterCacheManager.ElementToHandleCache.Register(familyInstance.Id, instanceHandle);
                break;
            }

            case IFCEntityType.IfcPlate:
            {
                IFCAnyHandle localPlacement = localPlacementToUse;
                if (overrideLocalPlacement != null)
                {
                    isChildInContainer = true;
                    localPlacement     = overrideLocalPlacement;
                }

                string preDefinedType = string.IsNullOrWhiteSpace(type.ValidatedPredefinedType) ? "NOTDEFINED" : type.ValidatedPredefinedType;
                instanceHandle = IFCInstanceExporter.CreatePlate(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                 localPlacement, productRepresentation, preDefinedType);
                break;
            }

            case IFCEntityType.IfcMechanicalFastener:
            {
                double?nominalDiameter = null;
                double?nominalLength   = null;

                double nominalDiameterVal, nominalLengthVal;
                if (ParameterUtil.GetDoubleValueFromElementOrSymbol(familyInstance, "NominalDiameter", out nominalDiameterVal) != null)
                {
                    nominalDiameter = UnitUtil.ScaleLength(nominalDiameterVal);
                }
                if (ParameterUtil.GetDoubleValueFromElementOrSymbol(familyInstance, "NominalLength", out nominalLengthVal) != null)
                {
                    nominalLength = UnitUtil.ScaleLength(nominalLengthVal);
                }

                string preDefinedType = string.IsNullOrWhiteSpace(type.ValidatedPredefinedType) ? "NOTDEFINED" : type.ValidatedPredefinedType;

                instanceHandle = IFCInstanceExporter.CreateMechanicalFastener(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                              localPlacementToUse, productRepresentation, nominalDiameter, nominalLength, preDefinedType);
                break;
            }

            case IFCEntityType.IfcRailing:
            {
                //string strEnumType;
                //IFCExportInfoPair exportAs = ExporterUtil.GetExportType(exporterIFC, familyInstance, out strEnumType);
                //if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                //{
                //   instanceHandle = IFCInstanceExporter.CreateRailing(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                //       localPlacementToUse, productRepresentation, GetPreDefinedType<Toolkit.IFC4.IFCRailingType>(familyInstance, strEnumType).ToString());
                //}
                //else
                //{
                //   instanceHandle = IFCInstanceExporter.CreateRailing(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                //       localPlacementToUse, productRepresentation, GetPreDefinedType<Toolkit.IFCRailingType>(familyInstance, strEnumType).ToString());
                //}
                string preDefinedType = string.IsNullOrWhiteSpace(type.ValidatedPredefinedType) ? "NOTDEFINED" : type.ValidatedPredefinedType;
                instanceHandle = IFCInstanceExporter.CreateRailing(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                   localPlacementToUse, productRepresentation, preDefinedType);
                break;
            }

            case IFCEntityType.IfcSpace:
            {
                IFCInternalOrExternal internalOrExternal = CategoryUtil.IsElementExternal(familyInstance) ? IFCInternalOrExternal.External : IFCInternalOrExternal.Internal;

                instanceHandle = IFCInstanceExporter.CreateSpace(exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                 localPlacementToUse, productRepresentation, IFCElementComposition.Element, internalOrExternal);
                break;
            }

            default:
            {
                // !!! These entities are deprecated in IFC4 and will be made abstract in the next version.
                //     It is still kept as it is because if we generate an IfcBuildingElementProxy, teh connectivity will be lost
                if (ExporterCacheManager.ExportOptionsCache.ExportAs4 &&
                    (type.ExportInstance == IFCEntityType.IfcDistributionElement ||
                     type.ExportInstance == IFCEntityType.IfcEnergyConversionDevice ||
                     type.ExportInstance == IFCEntityType.IfcFlowController ||
                     type.ExportInstance == IFCEntityType.IfcFlowFitting ||
                     type.ExportInstance == IFCEntityType.IfcFlowMovingDevice ||
                     type.ExportInstance == IFCEntityType.IfcFlowSegment ||
                     type.ExportInstance == IFCEntityType.IfcFlowStorageDevice ||
                     type.ExportInstance == IFCEntityType.IfcFlowTerminal ||
                     type.ExportInstance == IFCEntityType.IfcFlowTreatmentDevice))
                {
                    instanceHandle = IFCInstanceExporter.CreateGenericIFCEntity(type, exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                                localPlacementToUse, productRepresentation);
                }
                else
                {
                    if (type.ExportInstance != IFCEntityType.UnKnown)
                    {
                        instanceHandle = IFCInstanceExporter.CreateGenericIFCEntity(type, exporterIFC, familyInstance, instanceGUID, ownerHistory,
                                                                                    localPlacementToUse, productRepresentation);
                    }
                }
                break;
            }
            }

            if (!IFCAnyHandleUtil.IsNullOrHasNoValue(instanceHandle))
            {
                bool containedInSpace = (roomId != ElementId.InvalidElementId);
                bool associateToLevel = containedInSpace ? false : !isChildInContainer;
                wrapper.AddElement(familyInstance, instanceHandle, setter, extraParams, associateToLevel);
                if (containedInSpace)
                {
                    ExporterCacheManager.SpaceInfoCache.RelateToSpace(roomId, instanceHandle);
                }
            }
            return(instanceHandle);
        }
Пример #35
0
        /// <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);

            IFCFile      file = exporterIFC.GetFile();
            IFCAnyHandle surface;
            ICollection <IFCAnyHandle> boundaryRepresentations = new List <IFCAnyHandle>();

            ISet <IFCAnyHandle> surfaceItems = new HashSet <IFCAnyHandle>();

            // Use tessellated geometry for surface in IFC Reference View
            if (ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView || ExporterCacheManager.ExportOptionsCache.ExportAs4General)
            {
                BodyExporterOptions  options = new BodyExporterOptions(false, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                IList <IFCAnyHandle> items   = BodyExporter.ExportBodyAsTessellatedFaceSet(exporterIFC, element, options, geometryElement);
                if (items == null || items.Count == 0)
                {
                    return(false);
                }

                foreach (IFCAnyHandle item in items)
                {
                    surfaceItems.Add(item);
                }
            }
            else
            {
                ifcGeomInfo = IFCGeometryInfo.CreateFaceGeometryInfo(exporterIFC, plane, projDir, eps, exportBoundaryRep);

                ExporterIFCUtils.CollectGeometryInfo(exporterIFC, ifcGeomInfo, geometryElement, XYZ.Zero, true);

                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);
                }

                surface = IFCInstanceExporter.CreateFaceBasedSurfaceModel(file, faceSets);

                // Collect Footprint data
                boundaryRepresentations = ifcGeomInfo.GetRepresentations();

                if (IFCAnyHandleUtil.IsNullOrHasNoValue(surface))
                {
                    return(false);
                }

                // This is currently never a void.
                BodyExporter.CreateSurfaceStyleForRepItem(exporterIFC, doc, false, surface,
                                                          BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, element));

                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);
            }

            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);
        }
Пример #36
0
        /// <summary>
        /// Create an IfcCreateCurveBoundedPlane given a polygonal outer boundary and 0 or more polygonal inner boundaries.
        /// </summary>
        /// <param name="file">The IFCFile.</param>
        /// <param name="newOuterLoopPoints">The list of points representating the outer boundary of the plane.</param>
        /// <param name="innerLoopPoints">The list of inner boundaries of the plane.  This list can be null.</param>
        /// <returns>The IfcCreateCurveBoundedPlane.</returns>
        public static IFCAnyHandle CreateCurveBoundedPlane(IFCFile file, IList<XYZ> newOuterLoopPoints, IList<IList<XYZ>> innerLoopPoints)
        {
            if (newOuterLoopPoints == null)
                return null;

            // We need at least 3 distinct points for the outer polygon.
            int outerSz = newOuterLoopPoints.Count;
            if (outerSz < 3)
                return null;

            // We allow the polygon to duplicate the first and last points, or not.  If the last point is duplicated, we will generally ignore it.
            bool firstIsLast = newOuterLoopPoints[0].IsAlmostEqualTo(newOuterLoopPoints[outerSz - 1]);
            if (firstIsLast && (outerSz == 3))
                return null;

            // Calculate the X direction of the plane using the first point and the next point that generates a valid direction.
            XYZ firstDir = null;
            int ii = 1;
            for (; ii < outerSz; ii++)
            {
                firstDir = (newOuterLoopPoints[ii] - newOuterLoopPoints[0]).Normalize();
                if (firstDir != null)
                    break;
            }
            if (firstDir == null)
                return null;

            // Calculate the Y direction of the plane using the first point and the next point that generates a valid direction that isn't
            // parallel to the first direction.
            XYZ secondDir = null;
            for (ii++; ii < outerSz; ii++)
            {
                secondDir = (newOuterLoopPoints[ii] - newOuterLoopPoints[0]).Normalize();
                if (secondDir == null)
                    continue;

                if (MathUtil.IsAlmostEqual(Math.Abs(firstDir.DotProduct(secondDir)), 1.0))
                    continue;

                break;
            }
            if (secondDir == null)
                return null;

            // Generate the normal of the plane, ensure it is valid.
            XYZ norm = firstDir.CrossProduct(secondDir);
            if (norm == null || norm.IsZeroLength())
                return null;

            norm = norm.Normalize();
            if (norm == null)
                return null;

            // The original secondDir was almost certainly not orthogonal to firstDir; generate an orthogonal direction.
            secondDir = norm.CrossProduct(firstDir);
            Plane projPlane = new Plane(firstDir, secondDir, newOuterLoopPoints[0]);

            if (firstIsLast)
                outerSz--;

            // Create the UV points before we create handles, to avoid deleting handles on failure.
            IList<UV> projVecData = new List<UV>();
            for (ii = 0; ii < outerSz; ii++)
            {
                UV uv = GeometryUtil.ProjectPointToPlane(projPlane, newOuterLoopPoints[ii]);
                if (uv == null)
                    return null;
                projVecData.Add(uv);
            }

            // Generate handles for outer bound.
            IList<IFCAnyHandle> polyLinePts = CreateCartesianPointList(file, projVecData);

            IFCAnyHandle outerBound = IFCInstanceExporter.CreatePolyline(file, polyLinePts);

            IFCAnyHandle origHnd = CreateCartesianPoint(file, newOuterLoopPoints[0]);
            IFCAnyHandle refHnd = CreateDirection(file, firstDir);
            IFCAnyHandle dirHnd = CreateDirection(file, norm);

            IFCAnyHandle positionHnd = IFCInstanceExporter.CreateAxis2Placement3D(file, origHnd, dirHnd, refHnd);
            IFCAnyHandle basisPlane = IFCInstanceExporter.CreatePlane(file, positionHnd);

            // We only assign innerBounds if we create any.  We expect innerBounds to be null if there aren't any created.
            ISet<IFCAnyHandle> innerBounds = null;
            if (innerLoopPoints != null)
            {
                int innerSz = innerLoopPoints.Count;
                for (ii = 0; ii < innerSz; ii++)
                {
                    IList<XYZ> currInnerLoopVecData = innerLoopPoints[ii];
                    int loopSz = currInnerLoopVecData.Count;

                    projVecData.Clear();
                    firstIsLast = currInnerLoopVecData[0].IsAlmostEqualTo(currInnerLoopVecData[outerSz - 1]);
                    
                    // Be lenient on what we find.
                    bool continueOnFailure = ((loopSz < 2) || (firstIsLast && (loopSz == 3)));
                    for (int jj = 0; jj < loopSz && !continueOnFailure; jj++)
                    {
                        UV uv = GeometryUtil.ProjectPointToPlane(projPlane, currInnerLoopVecData[jj]);
                        if (uv == null)
                            continueOnFailure = true;
                        else
                            projVecData.Add(uv);
                    }

                    // We allow for bad inners - we just ignore them.
                    if (continueOnFailure)
                        continue;

                    polyLinePts = CreateCartesianPointList(file, projVecData);
                    IFCAnyHandle polyLine = IFCInstanceExporter.CreatePolyline(file, polyLinePts);

                    if (innerBounds == null)
                        innerBounds = new HashSet<IFCAnyHandle>();
                    innerBounds.Add(polyLine);
                }
            }

            return IFCInstanceExporter.CreateCurveBoundedPlane(file, basisPlane, outerBound, innerBounds);
        }
Пример #37
0
        void commonInit(ExporterIFC exporterIFC, Element elem, Transform familyTrf, Transform orientationTrf, ElementId overrideLevelId)
        {
            m_ExporterIFC = exporterIFC;

            overrideLevelId = overrideLevelId != null ? overrideLevelId : ElementId.InvalidElementId;

            Document  doc        = elem.Document;
            Element   hostElem   = elem;
            ElementId elemId     = elem.Id;
            ElementId newLevelId = overrideLevelId;

            bool useOverrideOrigin = false;
            XYZ  overrideOrigin    = XYZ.Zero;

            IDictionary <ElementId, IFCLevelInfo> levelInfos = exporterIFC.GetLevelInfos();

            if (overrideLevelId == ElementId.InvalidElementId)
            {
                if (familyTrf == null)
                {
                    // Override for CurveElems -- base level calculation on origin of sketch Plane.
                    if (elem is CurveElement)
                    {
                        SketchPlane sketchPlane = (elem as CurveElement).SketchPlane;
                        if (sketchPlane != null)
                        {
                            useOverrideOrigin = true;
                            overrideOrigin    = sketchPlane.GetPlane().Origin;
                        }
                    }
                    else
                    {
                        ElementId hostElemId = ElementId.InvalidElementId;
                        // a bit of a hack.  If we have a railing, we want it to have the same level base as its host Stair (because of
                        // the way the stairs place railings and stair flights together).
                        if (elem is Railing)
                        {
                            hostElemId = (elem as Railing).HostId;
                        }
                        else if (elem.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Assemblies)
                        {
                            hostElemId = elem.AssemblyInstanceId;
                        }

                        if (hostElemId != ElementId.InvalidElementId)
                        {
                            hostElem = doc.GetElement(hostElemId);
                        }

                        newLevelId = hostElem != null ? hostElem.LevelId : ElementId.InvalidElementId;

                        if (newLevelId == ElementId.InvalidElementId)
                        {
                            ExporterIFCUtils.GetLevelIdByHeight(exporterIFC, hostElem);
                        }
                    }
                }

                // todo: store.
                double    bottomHeight  = double.MaxValue;
                ElementId bottomLevelId = ElementId.InvalidElementId;
                if ((newLevelId == ElementId.InvalidElementId) || orientationTrf != null)
                {
                    // if we have a trf, it might geometrically push the instance to a new level.  Check that case.
                    // actually, we should ALWAYS check the bbox vs the settings
                    newLevelId = ElementId.InvalidElementId;
                    XYZ  originToUse   = XYZ.Zero;
                    bool originIsValid = useOverrideOrigin;

                    if (useOverrideOrigin)
                    {
                        originToUse = overrideOrigin;
                    }
                    else
                    {
                        BoundingBoxXYZ bbox = elem.get_BoundingBox(null);
                        if (bbox != null)
                        {
                            originToUse   = bbox.Min;
                            originIsValid = true;
                        }
                        else if (hostElem.Id != elemId)
                        {
                            bbox = hostElem.get_BoundingBox(null);
                            if (bbox != null)
                            {
                                originToUse   = bbox.Min;
                                originIsValid = true;
                            }
                        }
                    }


                    // The original heuristic here was that the origin determined the level containment based on exact location:
                    // if the Z of the origin was higher than the current level but lower than the next level, it was contained
                    // on that level.
                    // However, in some places (e.g. Germany), the containment is thought to start just below the level, because floors
                    // are placed before the level, not above.  So we have made a small modification so that anything within
                    // 10cm of the 'next' level is on that level.

                    double leveExtension = 10.0 / (12.0 * 2.54);
                    foreach (KeyValuePair <ElementId, IFCLevelInfo> levelInfoPair in levelInfos)
                    {
                        // the cache contains levels from all the exported documents
                        // if the export is performed for a linked document, filter the levels that are not from this document
                        if (ExporterCacheManager.ExportOptionsCache.ExportingLink)
                        {
                            Element levelElem = doc.GetElement(levelInfoPair.Key);
                            if (levelElem == null || !(levelElem is Level))
                            {
                                continue;
                            }
                        }

                        IFCLevelInfo levelInfo   = levelInfoPair.Value;
                        double       startHeight = levelInfo.Elevation - leveExtension;
                        double       height      = levelInfo.DistanceToNextLevel;
                        bool         useHeight   = !MathUtil.IsAlmostZero(height);
                        double       endHeight   = startHeight + height;

                        if (originIsValid && ((originToUse[2] > (startHeight - MathUtil.Eps())) && (!useHeight || originToUse[2] < (endHeight - MathUtil.Eps()))))
                        {
                            newLevelId = levelInfoPair.Key;
                        }

                        if (startHeight < (bottomHeight + MathUtil.Eps()))
                        {
                            bottomLevelId = levelInfoPair.Key;
                            bottomHeight  = startHeight;
                        }
                    }
                }

                if (newLevelId == ElementId.InvalidElementId)
                {
                    newLevelId = bottomLevelId;
                }
            }

            m_LevelInfo = exporterIFC.GetLevelInfo(newLevelId);
            if (m_LevelInfo == null)
            {
                foreach (KeyValuePair <ElementId, IFCLevelInfo> levelInfoPair in levelInfos)
                {
                    // the cache contains levels from all the exported documents
                    // if the export is performed for a linked document, filter the levels that are not from this document
                    if (ExporterCacheManager.ExportOptionsCache.ExportingLink)
                    {
                        Element levelElem = doc.GetElement(levelInfoPair.Key);
                        if (levelElem == null || !(levelElem is Level))
                        {
                            continue;
                        }
                    }
                    m_LevelInfo = levelInfoPair.Value;
                    break;
                }
                //m_LevelInfo = levelInfos.Values.First<IFCLevelInfo>();
            }

            double       elevation      = m_LevelInfo.Elevation;
            IFCAnyHandle levelPlacement = m_LevelInfo.GetLocalPlacement();

            IFCFile file = exporterIFC.GetFile();

            Transform trf = Transform.Identity;

            if (familyTrf != null)
            {
                XYZ origin, xDir, yDir, zDir;

                xDir = familyTrf.BasisX; yDir = familyTrf.BasisY; zDir = familyTrf.BasisZ;

                Transform origOffsetTrf  = Transform.Identity;
                XYZ       negLevelOrigin = new XYZ(0, 0, -elevation);
                origOffsetTrf.Origin = negLevelOrigin;

                Transform newTrf = origOffsetTrf * familyTrf;

                origin = newTrf.Origin;

                trf.BasisX = xDir; trf.BasisY = yDir; trf.BasisZ = zDir;
                trf        = trf.Inverse;

                origin           = UnitUtil.ScaleLength(origin);
                m_LocalPlacement = ExporterUtil.CreateLocalPlacement(file, levelPlacement, origin, zDir, xDir);
            }
            else if (orientationTrf != null)
            {
                XYZ origin, xDir, yDir, zDir;

                xDir = orientationTrf.BasisX; yDir = orientationTrf.BasisY; zDir = orientationTrf.BasisZ; origin = orientationTrf.Origin;

                XYZ levelOrigin = new XYZ(0, 0, elevation);
                origin = origin - levelOrigin;

                trf.BasisX = xDir; trf.BasisY = yDir; trf.BasisZ = zDir; trf.Origin = origin;
                trf        = trf.Inverse;

                origin           = UnitUtil.ScaleLength(origin);
                m_LocalPlacement = ExporterUtil.CreateLocalPlacement(file, levelPlacement, origin, zDir, xDir);
            }
            else
            {
                m_LocalPlacement = ExporterUtil.CreateLocalPlacement(file, levelPlacement, null, null, null);
            }

            Transform origOffsetTrf2  = Transform.Identity;
            XYZ       negLevelOrigin2 = new XYZ(0, 0, -elevation);

            origOffsetTrf2.Origin = negLevelOrigin2;
            Transform newTrf2 = trf * origOffsetTrf2;

            m_ExporterIFC.PushTransform(newTrf2);
            m_Offset  = elevation;
            m_LevelId = newLevelId;
        }
Пример #38
0
 /// <summary>
 /// Creates IfcDirection object.
 /// </summary>
 /// <param name="file">
 /// The IFC file.
 /// </param>
 /// <param name="direction">
 /// The direction.
 /// </param>
 /// <returns>
 /// The handle.
 /// </returns>
 public static IFCAnyHandle CreateDirection(IFCFile file, XYZ direction)
 {
     IList<double> measure = new List<double>();
     measure.Add(direction.X);
     measure.Add(direction.Y);
     measure.Add(direction.Z);
     return CreateDirection(file, measure);
 }
Пример #39
0
        /// <summary>
        /// Gets material handle from material id or creates one if there is none.
        /// </summary>
        /// <param name="document">
        /// The Revit document.
        /// </param>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="materialId">
        /// The material id.
        /// </param>
        /// <returns>
        /// The handle.
        /// </returns>
        public static IFCAnyHandle GetOrCreateMaterialHandle(Document document, ExporterIFC exporterIFC, ElementId materialId)
        {
            IFCAnyHandle materialNameHandle = null;

            materialNameHandle = ExporterCacheManager.MaterialHandleCache.Find(materialId);
            if (IFCAnyHandleUtil.IsNullOrHasNoValue(materialNameHandle))
            {
                string materialName = " <Unnamed>";
                if (materialId != ElementId.InvalidElementId)
                {
                    Material material = document.GetElement(materialId) as Material;
                    if (material != null)
                    {
                        materialName = material.Name;
                    }
                }
                materialNameHandle = IFCInstanceExporter.CreateMaterial(exporterIFC.GetFile(), materialName);
                ExporterCacheManager.MaterialHandleCache.Register(materialId, materialNameHandle);

                // associate Material with SurfaceStyle if necessary.
                IFCFile file = exporterIFC.GetFile();
                if (materialId != ElementId.InvalidElementId && !ExporterCacheManager.ExportOptionsCache.ExportAs2x2 && materialNameHandle.HasValue)
                {
                    HashSet <IFCAnyHandle> matRepHandles = IFCAnyHandleUtil.GetHasRepresentation(materialNameHandle);
                    if (matRepHandles.Count == 0)
                    {
                        Material matElem = document.GetElement(materialId) as Material;

                        ElementId fillPatternId       = (matElem != null) ? matElem.GetCutPatternId() : ElementId.InvalidElementId;
                        Autodesk.Revit.DB.Color color = (matElem != null) ? matElem.GetCutPatternColor() : new Color(0, 0, 0);

                        double planScale = 100.0;

                        HashSet <IFCAnyHandle> styles = new HashSet <IFCAnyHandle>();

                        bool hasFill = false;

                        IFCAnyHandle styledRepItem = null;
                        IFCAnyHandle matStyleHnd   = CategoryUtil.GetOrCreateMaterialStyle(document, exporterIFC, materialId);
                        if (!IFCAnyHandleUtil.IsNullOrHasNoValue(matStyleHnd))
                        {
                            styles.Add(matStyleHnd);

                            if (fillPatternId != ElementId.InvalidElementId && !ExporterCacheManager.ExportOptionsCache.ExportAs2x3CoordinationView2)
                            {
                                IFCAnyHandle cutStyleHnd = exporterIFC.GetOrCreateFillPattern(fillPatternId, color, planScale);
                                if (cutStyleHnd.HasValue)
                                {
                                    styles.Add(cutStyleHnd);
                                    hasFill = true;
                                }
                            }

                            IFCAnyHandle presStyleHnd = IFCInstanceExporter.CreatePresentationStyleAssignment(file, styles);

                            HashSet <IFCAnyHandle> presStyleSet = new HashSet <IFCAnyHandle>();
                            presStyleSet.Add(presStyleHnd);

                            IFCAnyHandle styledItemHnd = IFCInstanceExporter.CreateStyledItem(file, styledRepItem, presStyleSet, null);

                            IFCAnyHandle contextOfItems = exporterIFC.Get3DContextHandle("");

                            string repId   = "Style";
                            string repType = (hasFill) ? "Material and Cut Pattern" : "Material";
                            HashSet <IFCAnyHandle> repItems = new HashSet <IFCAnyHandle>();
                            repItems.Add(styledItemHnd);

                            IFCAnyHandle styleRepHnd = IFCInstanceExporter.CreateStyledRepresentation(file, contextOfItems, repId, repType, repItems);

                            List <IFCAnyHandle> repList = new List <IFCAnyHandle>();
                            repList.Add(styleRepHnd);

                            IFCAnyHandle matDefRepHnd = IFCInstanceExporter.CreateMaterialDefinitionRepresentation(file, null, null, repList, materialNameHandle);
                        }
                    }
                }
            }
            return(materialNameHandle);
        }
Пример #40
0
        /// <summary>
        /// Creates IfcCartesianPoint object.
        /// </summary>
        /// <param name="file">
        /// The IFC file.
        /// </param>
        /// <param name="measure">
        /// The list of doubles to create the Cartesian point.
        /// </param>
        /// <returns>
        /// The handle.
        /// </returns>
        public static IFCAnyHandle CreateCartesianPoint(IFCFile file, IList<double> measure)
        {
            IList<double> cleanMeasure = new List<double>();
            foreach (double value in measure)
            {
                double ceilMeasure = Math.Ceiling(value);
                double floorMeasure = Math.Floor(value);

                if (MathUtil.IsAlmostEqual(value, ceilMeasure))
                    cleanMeasure.Add(ceilMeasure);
                else if (MathUtil.IsAlmostEqual(value, floorMeasure))
                    cleanMeasure.Add(floorMeasure);
                else
                    cleanMeasure.Add(value);
            }

            if (MathUtil.IsAlmostZero(cleanMeasure[0]) && MathUtil.IsAlmostZero(cleanMeasure[1]))
            {
                if (measure.Count == 2)
                {
                    return ExporterIFCUtils.GetGlobal2DOriginHandle();
                }
                if (measure.Count == 3 && MathUtil.IsAlmostZero(cleanMeasure[2]))
                {
                    return ExporterIFCUtils.GetGlobal3DOriginHandle();
                }

            }

            IFCAnyHandle pointHandle = IFCInstanceExporter.CreateCartesianPoint(file, cleanMeasure);

            return pointHandle;
        }
Пример #41
0
 /// <summary>
 /// Creates an IfcAxis2Placement3D object.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="location">The origin.</param>
 /// <returns>The handle.</returns>
 public static IFCAnyHandle CreateAxis2Placement3D(IFCFile file, XYZ location)
 {
     return CreateAxis2Placement3D(file, location, null, null);
 }
Пример #42
0
        /// <summary>
        /// Creates IfcMappedItem object from an origin.
        /// </summary>
        /// <param name="file">
        /// The IFC file.
        /// </param>
        /// <param name="repMap">
        /// The handle to be mapped.
        /// </param>
        /// <param name="orig">
        /// The orig for mapping transformation.
        /// </param>
        /// <returns>
        /// The handle.
        /// </returns>
        public static IFCAnyHandle CreateDefaultMappedItem(IFCFile file, IFCAnyHandle repMap, XYZ orig)
        {
            if (MathUtil.IsAlmostZero(orig.X) && MathUtil.IsAlmostZero(orig.Y) && MathUtil.IsAlmostZero(orig.Z))
                return CreateDefaultMappedItem(file, repMap);

            IFCAnyHandle origin = CreateCartesianPoint(file, orig);
            double scale = 1.0;
            IFCAnyHandle mappingTarget =
               IFCInstanceExporter.CreateCartesianTransformationOperator3D(file, null, null, origin, scale, null);
            return IFCInstanceExporter.CreateMappedItem(file, repMap, mappingTarget);
        }
Пример #43
0
        /// <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 ProductWrapper.
        /// </param>
        public static void ExportFooting(ExporterIFC exporterIFC, Element element, GeometryElement geometryElement,
                                         string ifcEnumType, ProductWrapper productWrapper)
        {
            // export parts or not
            bool exportParts = PartExporter.CanExportParts(element);

            if (exportParts && !PartExporter.CanExportElementInPartExport(element, element.LevelId, false))
            {
                return;
            }

            // 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>("IfcFooting", out elementClassTypeEnum))
            {
                if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
                {
                    return;
                }
            }

            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);

                        IFCAnyHandle prodRep = null;
                        ElementId    matId   = ElementId.InvalidElementId;
                        if (!exportParts)
                        {
                            ElementId catId = CategoryUtil.GetSafeCategoryId(element);


                            matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, element);
                            BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                            prodRep = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC,
                                                                                                 element, catId, geometryElement, bodyExporterOptions, null, ecData, true);
                            if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodRep))
                            {
                                ecData.ClearOpenings();
                                return;
                            }
                        }

                        string instanceGUID = GUIDUtil.CreateGUID(element);

                        string footingType = GetIFCFootingType(ifcEnumType); // need to keep it for legacy support when original data follows slightly diff naming
                        footingType = IFCValidateEntry.GetValidIFCType(element, footingType);

                        IFCAnyHandle footing = IFCInstanceExporter.CreateFooting(exporterIFC, element, instanceGUID, ExporterCacheManager.OwnerHistoryHandle,
                                                                                 ecData.GetLocalPlacement(), prodRep, footingType);

                        if (exportParts)
                        {
                            PartExporter.ExportHostPart(exporterIFC, element, footing, productWrapper, setter, setter.LocalPlacement, null);
                        }
                        else
                        {
                            if (matId != ElementId.InvalidElementId)
                            {
                                CategoryUtil.CreateMaterialAssociation(exporterIFC, footing, matId);
                            }
                        }

                        productWrapper.AddElement(element, footing, setter, ecData, true);

                        OpeningUtil.CreateOpeningsIfNecessary(footing, element, ecData, null,
                                                              exporterIFC, ecData.GetLocalPlacement(), setter, productWrapper);
                    }
                }

                tr.Commit();
            }
        }
Пример #44
0
        // This function is static to make sure that no properties are used directly from the entry.
        private static IFCAnyHandle CreatePropertyFromElementOrSymbolBase(IFCFile file, ExporterIFC exporterIFC, Element element,
                                                                          string revitParamNameToUse, string ifcPropertyName, BuiltInParameter builtInParameter,
                                                                          PropertyType propertyType, PropertyValueType valueType, Type propertyEnumerationType)
        {
            IFCAnyHandle propHnd = null;

            switch (propertyType)
            {
            case PropertyType.Text:
            {
                propHnd = PropertyUtil.CreateTextPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType, propertyEnumerationType);
                break;
            }

            case PropertyType.Label:
            {
                propHnd = PropertyUtil.CreateLabelPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType, propertyEnumerationType);
                break;
            }

            case PropertyType.Identifier:
            {
                propHnd = PropertyUtil.CreateIdentifierPropertyFromElementOrSymbol(file, element, revitParamNameToUse, builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Boolean:
            {
                propHnd = PropertyUtil.CreateBooleanPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Logical:
            {
                propHnd = PropertyUtil.CreateLogicalPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Integer:
            {
                propHnd = PropertyUtil.CreateIntegerPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Real:
            {
                propHnd = PropertyUtil.CreateRealPropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Length:
            {
                propHnd = PropertyUtil.CreateLengthMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                      builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.PositiveLength:
            {
                propHnd = PropertyUtil.CreatePositiveLengthMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                              builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.NormalisedRatio:
            {
                propHnd = PropertyUtil.CreateNormalisedRatioPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                        ifcPropertyName, valueType);
                break;
            }

            case PropertyType.PositiveRatio:
            {
                propHnd = PropertyUtil.CreatePositiveRatioPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                      ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Ratio:
            {
                propHnd = PropertyUtil.CreateRatioPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, ifcPropertyName,
                                                                              valueType);
                break;
            }

            case PropertyType.PlaneAngle:
            {
                propHnd = PropertyUtil.CreatePlaneAngleMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName,
                                                                                          valueType);
                break;
            }

            case PropertyType.PositivePlaneAngle:
            {
                propHnd = PositivePlaneAnglePropertyUtil.CreatePositivePlaneAngleMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName,
                                                                                                                    valueType);
                break;
            }

            case PropertyType.Area:
            {
                propHnd = PropertyUtil.CreateAreaMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                    builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Volume:
            {
                propHnd = PropertyUtil.CreateVolumeMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                      builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Count:
            {
                propHnd = PropertyUtil.CreateCountMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                     builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Frequency:
            {
                propHnd = FrequencyPropertyUtil.CreateFrequencyPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                           ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ElectricalCurrent:
            {
                propHnd = ElectricalCurrentPropertyUtil.CreateElectricalCurrentMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ElectricalVoltage:
            {
                propHnd = ElectricalVoltagePropertyUtil.CreateElectricalVoltageMeasurePropertyFromElementOrSymbol(file, element, revitParamNameToUse, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.LuminousFlux:
            {
                propHnd = PropertyUtil.CreateLuminousFluxMeasurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                            builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Force:
            {
                propHnd = FrequencyPropertyUtil.CreateForcePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                       ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Pressure:
            {
                propHnd = FrequencyPropertyUtil.CreatePressurePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                          ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ColorTemperature:
            {
                propHnd = PropertyUtil.CreateColorTemperaturePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                         ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Currency:
            {
                propHnd = PropertyUtil.CreateCurrencyPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                 ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ElectricalEfficacy:
            {
                propHnd = PropertyUtil.CreateElectricalEfficacyPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                           ifcPropertyName, valueType);
                break;
            }

            case PropertyType.LuminousIntensity:
            {
                propHnd = PropertyUtil.CreateLuminousIntensityPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                          ifcPropertyName, valueType);
                break;
            }

            case PropertyType.MassDensity:
            {
                propHnd = PropertyUtil.CreateMassDensityPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                    ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Illuminance:
            {
                propHnd = PropertyUtil.CreateIlluminancePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                                    ifcPropertyName, valueType);
                break;
            }

            case PropertyType.Power:
            {
                propHnd = PropertyUtil.CreatePowerPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse, builtInParameter,
                                                                              ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ThermodynamicTemperature:
            {
                propHnd = PropertyUtil.CreateThermodynamicTemperaturePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                                 builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ThermalTransmittance:
            {
                propHnd = PropertyUtil.CreateThermalTransmittancePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                             builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.VolumetricFlowRate:
            {
                propHnd = PropertyUtil.CreateVolumetricFlowRatePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                           builtInParameter, ifcPropertyName, valueType);
                break;
            }

            case PropertyType.ClassificationReference:
            {
                propHnd = PropertyUtil.CreateClassificationReferencePropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                                builtInParameter, ifcPropertyName);
                break;
            }

            case PropertyType.LinearVelocity:
            {
                propHnd = PropertyUtil.CreateLinearVelocityPropertyFromElementOrSymbol(file, exporterIFC, element, revitParamNameToUse,
                                                                                       ifcPropertyName, valueType);
                break;
            }

            default:
                throw new InvalidOperationException();
            }

            return(propHnd);
        }
Пример #45
0
        /// <summary>
        /// Creates IfcDirection object.
        /// </summary>
        /// <param name="file">
        /// The IFC file.
        /// </param>
        /// <param name="realList">
        /// The list of doubles to create the direction.
        /// </param>
        /// <returns>
        /// The handle.
        /// </returns>
        public static IFCAnyHandle CreateDirection(IFCFile file, IList<double> realList)
        {
            IList<double> cleanList = new List<double>();

            foreach (double measure in realList)
            {
                double ceilMeasure = Math.Ceiling(measure);
                double floorMeasure = Math.Floor(measure);

                if (MathUtil.IsAlmostEqual(measure, ceilMeasure))
                    cleanList.Add(ceilMeasure);
                else if (MathUtil.IsAlmostEqual(measure, floorMeasure))
                    cleanList.Add(floorMeasure);
                else
                    cleanList.Add(measure);
            }

            int sz = realList.Count;

            if (sz == 3)
            {
                for (int ii = 0; ii < 3; ii++)
                {
                    if (MathUtil.IsAlmostEqual(cleanList[ii], 1.0))
                    {
                        if (!MathUtil.IsAlmostZero(cleanList[(ii + 1) % 3]) || !MathUtil.IsAlmostZero(cleanList[(ii + 2) % 3]))
                            break;
                        return ExporterIFCUtils.GetGlobal3DDirectionHandles(true)[ii];
                    }
                    else if (MathUtil.IsAlmostEqual(cleanList[ii], -1.0))
                    {
                        if (!MathUtil.IsAlmostZero(cleanList[(ii + 1) % 3]) || !MathUtil.IsAlmostZero(cleanList[(ii + 2) % 3]))
                            break;
                        return ExporterIFCUtils.GetGlobal3DDirectionHandles(false)[ii];
                    }
                }
            }
            else if (sz == 2)
            {
                for (int ii = 0; ii < 2; ii++)
                {
                    if (MathUtil.IsAlmostEqual(cleanList[ii], 1.0))
                    {
                        if (!MathUtil.IsAlmostZero(cleanList[1 - ii]))
                            break;
                        return ExporterIFCUtils.GetGlobal2DDirectionHandles(true)[ii];
                    }
                    else if (MathUtil.IsAlmostEqual(cleanList[ii], -1.0))
                    {
                        if (!MathUtil.IsAlmostZero(cleanList[1 - ii]))
                            break;
                        return ExporterIFCUtils.GetGlobal2DDirectionHandles(false)[ii];
                    }
                }
            }

            IFCAnyHandle directionHandle = IFCInstanceExporter.CreateDirection(file, cleanList);
            return directionHandle;
        }
Пример #46
0
        /// <summary>
        /// Process to create element quantity.
        /// </summary>
        /// <param name="file">
        /// The IFC file.
        /// </param>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="extrusionCreationData">
        /// The IFCExtrusionCreationData.
        /// </param>
        /// <param name="element">
        /// The element of which this property is created for.
        /// </param>
        /// <param name="elementType">
        /// The element type of which this quantity is created for.
        /// </param>
        /// <returns>
        /// Then created quantity handle.
        /// </returns>
        public IFCAnyHandle ProcessEntry(IFCFile file, ExporterIFC exporterIFC,
                                         IFCExtrusionCreationData extrusionCreationData, Element element, ElementType elementType)
        {
            bool useProperty = (!String.IsNullOrEmpty(RevitParameterName)) || (RevitBuiltInParameter != BuiltInParameter.INVALID);

            bool   success = false;
            double val     = 0;

            if (useProperty)
            {
                success = (ParameterUtil.GetDoubleValueFromElementOrSymbol(element, RevitParameterName, out val) != null);
                if (!success && RevitBuiltInParameter != BuiltInParameter.INVALID)
                {
                    success = (ParameterUtil.GetDoubleValueFromElementOrSymbol(element, RevitBuiltInParameter, out val) != null);
                }

                if (success) // factor in the scale factor for all the parameters depending of the data type to get the correct value
                {
                    switch (m_QuantityType)
                    {
                    case QuantityType.PositiveLength:
                        val = UnitUtil.ScaleLength(val);
                        break;

                    case QuantityType.Area:
                        val = UnitUtil.ScaleArea(val);
                        break;

                    case QuantityType.Volume:
                        val = UnitUtil.ScaleVolume(val);
                        break;

                    default:
                        break;
                    }
                }
            }

            if (PropertyCalculator != null && !success)
            {
                success = PropertyCalculator.Calculate(exporterIFC, extrusionCreationData, element, elementType);
                if (success)
                {
                    val = PropertyCalculator.GetDoubleValue();
                }
            }

            IFCAnyHandle quantityHnd = null;

            if (success)
            {
                switch (QuantityType)
                {
                case QuantityType.PositiveLength:
                    quantityHnd = IFCInstanceExporter.CreateQuantityLength(file, PropertyName, MethodOfMeasurement, null, val);
                    break;

                case QuantityType.Area:
                    quantityHnd = IFCInstanceExporter.CreateQuantityArea(file, PropertyName, MethodOfMeasurement, null, val);
                    break;

                case QuantityType.Volume:
                    quantityHnd = IFCInstanceExporter.CreateQuantityVolume(file, PropertyName, MethodOfMeasurement, null, val);
                    break;

                default:
                    throw new InvalidOperationException("Missing case!");
                }
            }

            return(quantityHnd);
        }
Пример #47
0
        /// <summary>
        /// Creates IfcCartesianPoint object from a 3D point.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="point">The point</param>
        /// <returns>The IfcCartesianPoint handle.</returns>
        public static IFCAnyHandle CreateCartesianPoint(IFCFile file, XYZ point)
        {
            if (point == null)
                throw new ArgumentNullException("point");

            List<double> points = new List<double>();
            points.Add(point.X);
            points.Add(point.Y);
            points.Add(point.Z);

            return CreateCartesianPoint(file, points);
        }
Пример #48
0
        /// <summary>
        /// Exports a Rebar to IFC ReinforcingBar.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="rebarItem">The rebar to be exported.  This might be an element or a sub-element.</param>
        /// <param name="rebarElement">The element that contains the rebar to be exported.  This may be the same as rebarItem.</param>
        /// <param name="itemIndex">If greater than 0, the index of the first rebar in the rebarItem in the rebarElement, used for naming and GUID creation.</param>
        /// <param name="productWrapper">The ProductWrapper object.</param>
        /// <returns>The set of handles created, to add to the ProductWrapper in the calling function.</returns>
        private static ISet <DelayedProductWrapper> ExportRebar(ExporterIFC exporterIFC, object rebarItem, Element rebarElement, int itemIndex, ProductWrapper productWrapper)
        {
            // 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>("IfcReinforcingBar", out elementClassTypeEnum))
            {
                if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
                {
                    return(null);
                }
            }

            IFCFile file = exporterIFC.GetFile();
            HashSet <DelayedProductWrapper> createdRebars = new HashSet <DelayedProductWrapper>();

            int rebarQuantity = GetRebarQuantity(rebarItem);

            if (rebarQuantity == 0)
            {
                return(null);
            }

            using (IFCTransaction transaction = new IFCTransaction(file))
            {
                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, rebarElement))
                {
                    bool         cannotExportRebar = false;
                    IFCAnyHandle rebarHandle       = ExportRebarAsProxyElementInView(exporterIFC, rebarElement, productWrapper, out cannotExportRebar);
                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(rebarHandle) || cannotExportRebar)
                    {
                        if (!cannotExportRebar)
                        {
                            transaction.Commit();
                        }
                        return(null); // Rebar doesn't create a group.
                    }

                    IFCAnyHandle prodRep = null;

                    double totalBarLengthUnscale = GetRebarTotalLength(rebarItem);
                    double volumeUnscale         = GetRebarVolume(rebarItem);
                    double totalBarLength        = UnitUtil.ScaleLength(totalBarLengthUnscale);

                    if (MathUtil.IsAlmostZero(totalBarLength))
                    {
                        return(null);
                    }

                    ElementId materialId = ElementId.InvalidElementId;
                    ParameterUtil.GetElementIdValueFromElementOrSymbol(rebarElement, BuiltInParameter.MATERIAL_ID_PARAM, out materialId);

                    double diameter = GetBarDiameter(rebarItem);
                    double radius   = diameter / 2.0;
                    double longitudinalBarNominalDiameter  = diameter;
                    double longitudinalBarCrossSectionArea = UnitUtil.ScaleArea(volumeUnscale / totalBarLengthUnscale);

                    int numberOfBarPositions = GetNumberOfBarPositions(rebarItem);

                    string steelGrade = NamingUtil.GetOverrideStringValue(rebarElement, "SteelGrade", null);

                    // Allow use of IFC2x3 or IFC4 naming.
                    string predefinedType = NamingUtil.GetOverrideStringValue(rebarElement, "BarRole", null);
                    if (string.IsNullOrWhiteSpace(predefinedType))
                    {
                        predefinedType = NamingUtil.GetOverrideStringValue(rebarElement, "PredefinedType", null);
                    }
                    IFCReinforcingBarRole role = GetReinforcingBarRole(predefinedType);

                    string origRebarName = NamingUtil.GetNameOverride(rebarElement, NamingUtil.GetIFCName(rebarElement));

                    const int maxBarGUIDS = IFCReinforcingBarSubElements.BarEnd - IFCReinforcingBarSubElements.BarStart + 1;
                    ElementId categoryId  = CategoryUtil.GetSafeCategoryId(rebarElement);

                    IFCAnyHandle originalPlacement = setter.LocalPlacement;

                    // Potential issue : totalBarLength has a rounded value but individual lengths (from centerlines) do not have rounded values.
                    // Also dividing a rounded totalBarLength does not result in barLength rounded by the same round value.
                    double        barLength  = totalBarLength / rebarQuantity;
                    IList <Curve> baseCurves = GetRebarCenterlineCurves(rebarItem, true, false, false);

                    ElementId    barLengthParamId   = new ElementId(BuiltInParameter.REBAR_ELEM_LENGTH);
                    ParameterSet rebarElementParams = rebarElement.Parameters;
                    for (int ii = 0; ii < numberOfBarPositions; ii++)
                    {
                        if (!DoesBarExistAtPosition(rebarItem, ii))
                        {
                            continue;
                        }

                        Rebar rebar = rebarElement as Rebar;
                        if ((rebar != null) && (rebar.DistributionType == DistributionType.VaryingLength || rebar.IsRebarFreeForm()))
                        {
                            baseCurves = GetRebarCenterlineCurves(rebar, true, false, false, MultiplanarOption.IncludeOnlyPlanarCurves, ii);
                            DoubleParameterValue barLengthParamVal = rebar.GetParameterValueAtIndex(barLengthParamId, ii) as DoubleParameterValue;
                            if (barLengthParamVal != null)
                            {
                                barLength = barLengthParamVal.Value;
                            }
                        }

                        int indexForNamingAndGUID = (itemIndex > 0) ? ii + itemIndex : ii + 1;

                        string rebarName = NamingUtil.GetNameOverride(rebarElement, origRebarName + ": " + indexForNamingAndGUID);

                        Transform barTrf = GetBarPositionTransform(rebarItem, ii);

                        IList <Curve> curves   = new List <Curve>();
                        double        endParam = 0.0;
                        foreach (Curve baseCurve in baseCurves)
                        {
                            if (baseCurve is Arc || baseCurve is Ellipse)
                            {
                                if (baseCurve.IsBound)
                                {
                                    endParam += UnitUtil.ScaleAngle(baseCurve.GetEndParameter(1) - baseCurve.GetEndParameter(0));
                                }
                                else
                                {
                                    endParam += UnitUtil.ScaleAngle(2 * Math.PI);
                                }
                            }
                            else
                            {
                                endParam += 1.0;
                            }
                            curves.Add(baseCurve.CreateTransformed(barTrf));
                        }

                        IFCAnyHandle           compositeCurve = GeometryUtil.CreateCompositeCurve(exporterIFC, curves);
                        IFCAnyHandle           sweptDiskSolid = IFCInstanceExporter.CreateSweptDiskSolid(file, compositeCurve, radius, null, 0, endParam);
                        HashSet <IFCAnyHandle> bodyItems      = new HashSet <IFCAnyHandle>();
                        bodyItems.Add(sweptDiskSolid);

                        IFCAnyHandle         shapeRep  = RepresentationUtil.CreateAdvancedSweptSolidRep(exporterIFC, rebarElement, categoryId, exporterIFC.Get3DContextHandle("Body"), bodyItems, null);
                        IList <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>();
                        shapeReps.Add(shapeRep);
                        prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps);

                        IFCAnyHandle copyLevelPlacement = (ii == 0) ? originalPlacement : ExporterUtil.CopyLocalPlacement(file, originalPlacement);

                        string rebarGUID = (indexForNamingAndGUID < maxBarGUIDS) ?
                                           GUIDUtil.CreateSubElementGUID(rebarElement, indexForNamingAndGUID + (int)IFCReinforcingBarSubElements.BarStart - 1) :
                                           GUIDUtil.CreateGUID();
                        IFCAnyHandle elemHnd = IFCInstanceExporter.CreateReinforcingBar(exporterIFC, rebarElement, rebarGUID, ExporterCacheManager.OwnerHistoryHandle,
                                                                                        copyLevelPlacement, prodRep, steelGrade, longitudinalBarNominalDiameter, longitudinalBarCrossSectionArea, barLength, role, null);
                        IFCAnyHandleUtil.SetAttribute(elemHnd, "Name", rebarName);

                        // We will not add the element ot the productWrapper here, but instead in the function that calls
                        // ExportRebar.  The reason for this is that we don't currently know if the handles such be associated
                        // to the level or not, depending on whether they will or won't be grouped.
                        createdRebars.Add(new DelayedProductWrapper(rebarElement, elemHnd, setter.LevelInfo));

                        CacheSubelementParameterValues(rebarElement, rebarElementParams, ii, elemHnd);

                        ExporterCacheManager.HandleToElementCache.Register(elemHnd, rebarElement.Id);
                        CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, materialId);
                    }
                }
                transaction.Commit();
            }
            return(createdRebars);
        }
Пример #49
0
        /// <summary>
        /// Creates an IfcAxis2Placement3D object.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="location">The origin. If null, it will use the global origin handle.</param>
        /// <param name="axis">The Z direction.</param>
        /// <param name="refDirection">The X direction.</param>
        /// <returns>the handle.</returns>
        public static IFCAnyHandle CreateAxis2Placement3D(IFCFile file, XYZ location, XYZ axis, XYZ refDirection)
        {
            IFCAnyHandle locationHandle = null;
            if (location != null)
            {
                List<double> measure = new List<double>();
                measure.Add(location.X);
                measure.Add(location.Y);
                measure.Add(location.Z);
                locationHandle = CreateCartesianPoint(file, measure);
            }
            else
            {
                locationHandle = ExporterIFCUtils.GetGlobal3DOriginHandle();
            }


            bool exportDirAndRef = (axis != null && refDirection != null &&
                (!MathUtil.IsAlmostEqual(axis[2], 1.0) || !MathUtil.IsAlmostEqual(refDirection[0], 1.0)));

            if ((axis != null) ^ (refDirection != null))
            {
                exportDirAndRef = false;
            }

            IFCAnyHandle axisHandle = null;
            if (exportDirAndRef)
            {
                List<double> measure = new List<double>();
                measure.Add(axis.X);
                measure.Add(axis.Y);
                measure.Add(axis.Z);
                axisHandle = CreateDirection(file, measure);
            }

            IFCAnyHandle refDirectionHandle = null;
            if (exportDirAndRef)
            {
                List<double> measure = new List<double>();
                measure.Add(refDirection.X);
                measure.Add(refDirection.Y);
                measure.Add(refDirection.Z);
                refDirectionHandle = CreateDirection(file, measure);
            }

            return IFCInstanceExporter.CreateAxis2Placement3D(file, locationHandle, axisHandle, refDirectionHandle);
        }
Пример #50
0
        /// <summary>
        /// Exports a Rebar, AreaReinforcement or PathReinforcement to IFC ReinforcingBar.
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="element">The element.</param>
        /// <param name="productWrapper">The product wrapper.</param>
        public static void Export(ExporterIFC exporterIFC, Element element, ProductWrapper productWrapper)
        {
            ISet <DelayedProductWrapper> createdRebars = new HashSet <DelayedProductWrapper>();

            if (element is Rebar)
            {
                createdRebars = ExportRebar(exporterIFC, element, productWrapper);
            }
            else if (element is AreaReinforcement)
            {
                AreaReinforcement areaReinforcement = element as AreaReinforcement;
                IList <ElementId> rebarIds          = areaReinforcement.GetRebarInSystemIds();

                Document doc = areaReinforcement.Document;
                foreach (ElementId id in rebarIds)
                {
                    Element rebarInSystem = doc.GetElement(id);
                    ISet <DelayedProductWrapper> newlyCreatedRebars = ExportRebar(exporterIFC, rebarInSystem, productWrapper);
                    if (newlyCreatedRebars != null)
                    {
                        createdRebars.UnionWith(newlyCreatedRebars);
                    }
                }
            }
            else if (element is PathReinforcement)
            {
                PathReinforcement pathReinforcement = element as PathReinforcement;
                IList <ElementId> rebarIds          = pathReinforcement.GetRebarInSystemIds();

                Document doc = pathReinforcement.Document;
                foreach (ElementId id in rebarIds)
                {
                    Element rebarInSystem = doc.GetElement(id);
                    ISet <DelayedProductWrapper> newlyCreatedRebars = ExportRebar(exporterIFC, rebarInSystem, productWrapper);
                    if (newlyCreatedRebars != null)
                    {
                        createdRebars.UnionWith(newlyCreatedRebars);
                    }
                }
            }
            else if (element is RebarContainer)
            {
                int            itemIndex      = 1;
                RebarContainer rebarContainer = element as RebarContainer;
                foreach (RebarContainerItem rebarContainerItem in rebarContainer)
                {
                    ISet <DelayedProductWrapper> newlyCreatedRebars = ExportRebar(exporterIFC, rebarContainerItem, rebarContainer, itemIndex, productWrapper);
                    if (newlyCreatedRebars != null)
                    {
                        itemIndex += createdRebars.Count;
                        createdRebars.UnionWith(newlyCreatedRebars);
                    }
                }
            }

            if (createdRebars != null && createdRebars.Count != 0)
            {
                string guid = GUIDUtil.CreateGUID(element);

                // Create a group to hold all of the created IFC entities, if the rebars aren't already in an assembly or a group.
                // We want to avoid nested groups of groups of rebars.
                bool relateToLevel     = true;
                bool groupRebarHandles = (createdRebars.Count != 1);
                foreach (DelayedProductWrapper delayedProductWrapper in createdRebars)
                {
                    if (ElementIsContainedInAssembly(delayedProductWrapper.RebarElement))
                    {
                        groupRebarHandles = false;
                        relateToLevel     = false;
                        break;
                    }
                }

                ISet <IFCAnyHandle> createdRebarHandles = new HashSet <IFCAnyHandle>();
                foreach (DelayedProductWrapper delayedProductWrapper in createdRebars)
                {
                    IFCAnyHandle currentRebarHandle = delayedProductWrapper.ElementHandle;
                    productWrapper.AddElement(delayedProductWrapper.RebarElement, currentRebarHandle, delayedProductWrapper.LevelInfo, null, relateToLevel);
                    createdRebarHandles.Add(currentRebarHandle);
                }

                if (createdRebars.Count > 1)
                {
                    if (groupRebarHandles)
                    {
                        // 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>("IfcGroup", out elementClassTypeEnum))
                        {
                            if (!ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
                            {
                                IFCFile file = exporterIFC.GetFile();
                                using (IFCTransaction tr = new IFCTransaction(file))
                                {
                                    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 rebarGroup = IFCInstanceExporter.CreateGroup(file, guid,
                                                                                              ownerHistory, name, description, objectType);

                                    productWrapper.AddElement(element, rebarGroup);

                                    IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory,
                                                                                null, null, createdRebarHandles, null, rebarGroup);

                                    tr.Commit();
                                }
                            }
                        }
                    }
                }
                else
                {
                    // We will update the GUID of the one created IfcReinforcingElement to be the element GUID.
                    // This will allow the IfcGUID parameter to be use/set if appropriate.
                    ExporterUtil.SetGlobalId(createdRebarHandles.ElementAt(0), guid);
                }
            }
        }
Пример #51
0
 /// <summary>
 /// Creates a default IfcAxis2Placement3D object.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <returns>The handle.</returns>
 public static IFCAnyHandle CreateAxis2Placement3D(IFCFile file)
 {
     return CreateAxis2Placement3D(file, null);
 }
Пример #52
0
        /// <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);
            }

            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcCovering;
            if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
            {
                return(false);
            }

            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                // Check for containment override
                IFCAnyHandle overrideContainer   = null;
                ElementId    overrideContainerId = ParameterUtil.OverrideContainmentParameter(exporterIFC, element, out overrideContainer);

                using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, element, null, null, overrideContainerId, overrideContainer))
                {
                    using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData())
                    {
                        ecData.SetLocalPlacement(placementSetter.LocalPlacement);

                        ElementId categoryId = CategoryUtil.GetSafeCategoryId(element);

                        BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                        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   = ExporterCacheManager.OwnerHistoryHandle;
                        IFCAnyHandle localPlacement = ecData.GetLocalPlacement();

                        string       ifcType    = "Wrapping";
                        IFCAnyHandle ductLining = IFCInstanceExporter.CreateCovering(exporterIFC, element, guid,
                                                                                     ownerHistory, localPlacement, representation, ifcType);
                        ExporterCacheManager.ElementToHandleCache.Register(element.Id, ductLining);
                        IFCExportInfoPair exportInfo = new IFCExportInfoPair(IFCEntityType.IfcCovering, ifcType);

                        productWrapper.AddElement(element, ductLining, placementSetter.LevelInfo, ecData, true, exportInfo);

                        ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, element);
                        CategoryUtil.CreateMaterialAssociation(exporterIFC, ductLining, matId);
                    }
                }
                tr.Commit();
                return(true);
            }
        }
Пример #53
0
 /// <summary>
 /// Creates IfcMappedItem object at (0,0,0).
 /// </summary>
 /// <param name="file">
 /// The IFC file.
 /// </param>
 /// <param name="repMap">
 /// The handle to be mapped.
 /// </param>
 /// <param name="orig">
 /// The orig for mapping transformation.
 /// </param>
 /// <returns>
 /// The handle.
 /// </returns>
 public static IFCAnyHandle CreateDefaultMappedItem(IFCFile file, IFCAnyHandle repMap)
 {
     IFCAnyHandle transformHnd = ExporterCacheManager.GetDefaultCartesianTransformationOperator3D(file);
     return IFCInstanceExporter.CreateMappedItem(file, repMap, transformHnd);
 }
Пример #54
0
        /// <summary>
        /// Creates IfcPresentationStyleAssignment for text element type.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="textElemType">
        /// The text note element type.
        /// </param>
        /// <param name="cache">
        /// The cache of IfcPresentationStyleAssignment.
        /// </param>
        static void CreatePresentationStyleAssignmentForTextElementType(ExporterIFC exporterIFC, TextElementType textElemType, PresentationStyleAssignmentCache cache)
        {
            IFCFile file = exporterIFC.GetFile();

            string fontName;

            if (ParameterUtil.GetStringValueFromElement(textElemType, BuiltInParameter.TEXT_FONT, out fontName) == null)
            {
                fontName = null;
            }

            double fontSize;

            if (ParameterUtil.GetDoubleValueFromElement(textElemType, BuiltInParameter.TEXT_SIZE, out fontSize) == null)
            {
                fontSize = -1.0;
            }

            double viewScale = 100.0; // currently hardwired.

            fontSize = UnitUtil.ScaleLength(fontSize * viewScale);

            string ifcPreDefinedItemName = "Text Font";

            IList <string> fontNameList = new List <string>();

            fontNameList.Add(fontName);

            IFCAnyHandle textSyleFontModelHnd = IFCInstanceExporter.CreateTextStyleFontModel(file, ifcPreDefinedItemName, fontNameList, null, null, null, IFCDataUtil.CreateAsPositiveLengthMeasure(fontSize));

            int color;

            ParameterUtil.GetIntValueFromElement(textElemType, BuiltInParameter.LINE_COLOR, out color);

            double blueVal  = ((double)((color & 0xff0000) >> 16)) / 255.0;
            double greenVal = ((double)((color & 0xff00) >> 8)) / 255.0;
            double redVal   = ((double)(color & 0xff)) / 255.0;

            IFCAnyHandle colorHnd     = IFCInstanceExporter.CreateColourRgb(file, null, redVal, greenVal, blueVal);
            IFCAnyHandle fontColorHnd = IFCInstanceExporter.CreateTextStyleForDefinedFont(file, colorHnd, null);

            string       ifcAttrName  = textElemType.Name;
            IFCAnyHandle textStyleHnd = IFCInstanceExporter.CreateTextStyle(file, textElemType.Name, fontColorHnd, null, textSyleFontModelHnd);

            if (IFCAnyHandleUtil.IsNullOrHasNoValue(textStyleHnd))
            {
                return;
            }

            HashSet <IFCAnyHandle> presStyleSet = new HashSet <IFCAnyHandle>();

            presStyleSet.Add(textStyleHnd);

            IFCAnyHandle presStyleHnd = IFCInstanceExporter.CreatePresentationStyleAssignment(file, presStyleSet);

            if (IFCAnyHandleUtil.IsNullOrHasNoValue(presStyleHnd))
            {
                return;
            }

            cache.Register(textElemType.Id, presStyleHnd);
        }
Пример #55
0
        /// <summary>
        /// Creates an IfcPolyLine from a list of UV points.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="polylinePts">This list of UV values.</param>
        /// <returns>An IfcPolyline handle.</returns>
        public static IFCAnyHandle CreatePolyline(IFCFile file, IList<UV> polylinePts)
        {
            int numPoints = polylinePts.Count;
            if (numPoints < 2)
                return null;

            bool closed = MathUtil.IsAlmostEqual(polylinePts[0], polylinePts[numPoints - 1]);
            if (closed)
            {
                if (numPoints == 2)
                    return null;
                numPoints--;
            }

            IList<IFCAnyHandle> points = new List<IFCAnyHandle>();
            for (int ii = 0; ii < numPoints; ii++)
            {
                points.Add(CreateCartesianPoint(file, polylinePts[ii]));
            }
            if (closed)
                points.Add(points[0]);

            return IFCInstanceExporter.CreatePolyline(file, points);
        }
Пример #56
0
        /// <summary>
        /// Exports text note elements.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="textNote">
        /// The text note element.
        /// </param>
        /// <param name="productWrapper">
        /// The IFCProductWrapper.
        /// </param>
        public static void Export(ExporterIFC exporterIFC, TextNote textNote, IFCProductWrapper productWrapper)
        {
            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                string textString = textNote.Text;
                if (String.IsNullOrEmpty(textString))
                {
                    throw new Exception("TextNote does not have test string.");
                }

                ElementId symId = textNote.GetTypeId();
                if (symId == ElementId.InvalidElementId)
                {
                    throw new Exception("TextNote does not have valid type id.");
                }

                PresentationStyleAssignmentCache cache = ExporterCacheManager.PresentationStyleAssignmentCache;
                IFCAnyHandle presHnd = cache.Find(symId);
                if (IFCAnyHandleUtil.IsNullOrHasNoValue(presHnd))
                {
                    TextElementType textElemType = textNote.Symbol;
                    CreatePresentationStyleAssignmentForTextElementType(exporterIFC, textElemType, cache);
                    presHnd = cache.Find(symId);
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(presHnd))
                    {
                        throw new Exception("Failed to create presentation style assignment for TextElementType.");
                    }
                }

                HashSet <IFCAnyHandle> presHndSet = new HashSet <IFCAnyHandle>();
                presHndSet.Add(presHnd);

                using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, textNote))
                {
                    double       linScale  = exporterIFC.LinearScale;
                    const double planScale = 100.0;  // currently hardwired.

                    XYZ orig = textNote.Coord;
                    orig = orig.Multiply(linScale);
                    XYZ yDir = textNote.UpDirection;
                    XYZ xDir = textNote.BaseDirection;
                    XYZ zDir = xDir.CrossProduct(yDir);

                    double sizeX = textNote.LineWidth * linScale * planScale;
                    double sizeY = textNote.Height * linScale * planScale;

                    // When we display text on screen, we "flip" it if the xDir is negative with relation to
                    // the X-axis.  So if it is, we'll flip x and y.
                    bool flipOrig = false;
                    if (xDir.X < 0)
                    {
                        xDir     = xDir.Multiply(-1.0);
                        yDir     = yDir.Multiply(-1.0);
                        flipOrig = true;
                    }

                    // xFactor, yFactor only used if flipOrig.
                    double xFactor = 0.0, yFactor = 0.0;
                    string boxAlignment = ConvertTextNoteAlignToBoxAlign(textNote, out xFactor, out yFactor);

                    // modify the origin to match the alignment.  In Revit, the origin is at the top-left (unless flipped,
                    // then bottom-right).
                    if (flipOrig)
                    {
                        orig = orig.Add(xDir.Multiply(sizeX * xFactor));
                        orig = orig.Add(yDir.Multiply(sizeY * yFactor));
                    }

                    IFCAnyHandle origin = ExporterUtil.CreateAxis(file, orig, zDir, xDir);

                    IFCAnyHandle extent         = IFCInstanceExporter.CreatePlanarExtent(file, sizeX, sizeY);
                    IFCAnyHandle repItemHnd     = IFCInstanceExporter.CreateTextLiteralWithExtent(file, textString, origin, Toolkit.IFCTextPath.Left, extent, boxAlignment);
                    IFCAnyHandle annoTextOccHnd = IFCInstanceExporter.CreateStyledItem(file, repItemHnd, presHndSet, null);

                    ElementId catId = textNote.Category != null ? textNote.Category.Id : ElementId.InvalidElementId;
                    HashSet <IFCAnyHandle> bodyItems = new HashSet <IFCAnyHandle>();
                    bodyItems.Add(repItemHnd);
                    IFCAnyHandle bodyRepHnd = RepresentationUtil.CreateAnnotationSetRep(exporterIFC, textNote, catId, exporterIFC.Get2DContextHandle(), bodyItems);

                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(bodyRepHnd))
                    {
                        throw new Exception("Failed to create shape representation.");
                    }

                    IList <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>();
                    shapeReps.Add(bodyRepHnd);

                    IFCAnyHandle prodShapeHnd = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps);
                    IFCAnyHandle annoHnd      = IFCInstanceExporter.CreateAnnotation(file, ExporterIFCUtils.CreateGUID(), exporterIFC.GetOwnerHistoryHandle(),
                                                                                     null, null, null, setter.GetPlacement(), prodShapeHnd);

                    productWrapper.AddAnnotation(annoHnd, setter.GetLevelInfo(), true);
                }

                tr.Commit();
            }
        }
Пример #57
0
 /// <summary>
 /// Creates a new local placement object.
 /// </summary>
 /// <param name="file">The IFC file.</param>
 /// <param name="placementRelTo">The placement object.</param>
 /// <param name="relativePlacement">The relative placement. Null to create a identity relative placement.</param>
 /// <returns></returns>
 public static IFCAnyHandle CreateLocalPlacement(IFCFile file, IFCAnyHandle placementRelTo, IFCAnyHandle relativePlacement)
 {
     if (relativePlacement == null)
     {
         relativePlacement = ExporterUtil.CreateAxis2Placement3D(file);
     }
     return IFCInstanceExporter.CreateLocalPlacement(file, placementRelTo, relativePlacement);
 }
        /// <summary>
        /// Create an electrical voltage measure property from the element's or type's parameter.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="elem">The Element.</param>
        /// <param name="revitParameterName">The name of the parameter.</param>
        /// <param name="ifcPropertyName">The name of the property.</param>
        /// <param name="valueType">The value type of the property.</param>
        /// <returns>The created property handle.</returns>
        public static IFCAnyHandle CreateElectricalVoltageMeasurePropertyFromElementOrSymbol(IFCFile file, Element elem, string revitParameterName, string ifcPropertyName, PropertyValueType valueType)
        {
            double propertyValue;

            if (ParameterUtil.GetDoubleValueFromElement(elem, null, revitParameterName, out propertyValue) != null)
            {
                propertyValue = UnitUtil.ScaleElectricalVoltage(propertyValue);
                return(CreateElectricalVoltageMeasurePropertyFromCache(file, ifcPropertyName, propertyValue, valueType));
            }
            // For Symbol
            Document  document = elem.Document;
            ElementId typeId   = elem.GetTypeId();
            Element   elemType = document.GetElement(typeId);

            if (elemType != null)
            {
                return(CreateElectricalVoltageMeasurePropertyFromElementOrSymbol(file, elemType, revitParameterName, ifcPropertyName, valueType));
            }
            else
            {
                return(null);
            }
        }
Пример #59
0
        /// <summary>
        /// Process to create element quantity.
        /// </summary>
        /// <param name="file">
        /// The IFC file.
        /// </param>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="extrusionCreationData">
        /// The IFCExtrusionCreationData.
        /// </param>
        /// <param name="element">
        /// The element of which this property is created for.
        /// </param>
        /// <param name="elementType">
        /// The element type of which this quantity is created for.
        /// </param>
        /// <returns>
        /// Then created quantity handle.
        /// </returns>
        public IFCAnyHandle ProcessEntry(IFCFile file, ExporterIFC exporterIFC,
            IFCExtrusionCreationData extrusionCreationData, Element element, ElementType elementType)
        {
            bool useProperty = (!String.IsNullOrEmpty(RevitParameterName)) || (RevitBuiltInParameter != BuiltInParameter.INVALID);

            bool success = false;
            double val = 0;
            if (useProperty)
            {
                success = ParameterUtil.GetDoubleValueFromElementOrSymbol(element, RevitParameterName, out val);
                if (!success && RevitBuiltInParameter != BuiltInParameter.INVALID)
                    success = ParameterUtil.GetDoubleValueFromElementOrSymbol(element, RevitBuiltInParameter, out val);
            }

            if (PropertyCalculator != null && !success)
            {
                success = PropertyCalculator.Calculate(exporterIFC, extrusionCreationData, element, elementType);
                if (success)
                    val = PropertyCalculator.GetDoubleValue();
            }

            IFCAnyHandle quantityHnd = null;
            if (success)
            {
                switch (QuantityType)
                {
                    case QuantityType.PositiveLength:
                        quantityHnd = IFCInstanceExporter.CreateQuantityLength(file, PropertyName, MethodOfMeasurement, null, val);
                        break;
                    case QuantityType.Area:
                        quantityHnd = IFCInstanceExporter.CreateQuantityArea(file, PropertyName, MethodOfMeasurement, null, val);
                        break;
                    case QuantityType.Volume:
                        quantityHnd = IFCInstanceExporter.CreateQuantityVolume(file, PropertyName, MethodOfMeasurement, null, val);
                        break;
                    default:
                        throw new InvalidOperationException("Missing case!");
                }
            }

            return quantityHnd;
        }
        /// <summary>
        /// Create a label property.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="propertyName">The name of the property.</param>
        /// <param name="value">The value of the property.</param>
        /// <param name="valueType">The value type of the property.</param>
        /// <returns>The created property handle.</returns>
        public static IFCAnyHandle CreateElectricalVoltageMeasureProperty(IFCFile file, string propertyName, double value, PropertyValueType valueType)
        {
            IFCData electricalVoltageData = IFCDataUtil.CreateAsElectricalVoltageMeasure(value);

            return(CreateCommonProperty(file, propertyName, electricalVoltageData, valueType, null));
        }