Esempio n. 1
0
        /***************************************************/

        public static HostObjAttributes ToRevitElementType(this oM.Physical.Constructions.IConstruction construction, Document document, IEnumerable <BuiltInCategory> categories = null, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null)
        {
            if (construction == null || document == null)
            {
                return(null);
            }

            HostObjAttributes elementType = refObjects.GetValue <HostObjAttributes>(document, construction.BHoM_Guid);

            if (elementType != null)
            {
                return(elementType);
            }

            settings = settings.DefaultIfNull();

            elementType = construction.ElementType(document, categories, settings) as HostObjAttributes;
            if (elementType == null)
            {
                return(null);
            }

            // Copy parameters from BHoM object to Revit element
            elementType.CopyParameters(construction, settings);

            refObjects.AddOrReplace(construction, elementType);
            return(elementType);
        }
        protected override void TrySolveInstance(IGH_DataAccess dataAccess)
        {
            Document document = RhinoInside.Revit.Revit.ActiveDBDocument;

            if (document == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            Panel panel = null;

            if (!dataAccess.GetData(0, ref panel))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            Geometry.Spatial.Vector3D normal = panel.Normal;

            PanelType panelType = panel.PanelType;

            if (panelType == PanelType.Air || panelType == PanelType.Undefined)
            {
                dataAccess.SetData(0, new GooPanel(new Panel(panel)));
                dataAccess.SetData(1, Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false)));
                return;
            }

            PanelType panelType_Normal = Analytical.Revit.Query.PanelType(normal);

            if (panelType_Normal == PanelType.Undefined || panelType.PanelGroup() == panelType_Normal.PanelGroup())
            {
                dataAccess.SetData(0, new GooPanel(new Panel(panel)));
                dataAccess.SetData(1, Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false)));
                return;
            }

            if (panelType.PanelGroup() == PanelGroup.Floor || panelType.PanelGroup() == PanelGroup.Roof)
            {
                double value = normal.Unit.DotProduct(Geometry.Spatial.Vector3D.WorldY);
                if (Math.Abs(value) <= Core.Revit.Tolerance.Tilt)
                {
                    dataAccess.SetData(0, new GooPanel(new Panel(panel)));
                    dataAccess.SetData(1, Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false)));
                    return;
                }
            }

            HostObjAttributes hostObjAttributes = Analytical.Revit.Modify.DuplicateByType(document, panelType_Normal, panel.Construction) as HostObjAttributes;

            if (hostObjAttributes == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, string.Format("Skipped - Could not duplicate construction for {0} panel (Guid: {1}).", panel.Name, panel.Guid));
                return;
            }

            dataAccess.SetData(0, new Panel(panel, panelType_Normal));
            dataAccess.SetData(1, hostObjAttributes);
        }
Esempio n. 3
0
        public static PanelType PanelType(this HostObjAttributes hostObjAttributes)
        {
            if (hostObjAttributes == null)
            {
                return(Analytical.PanelType.Undefined);
            }

            string parameterName_Type = Core.Revit.Query.Name(ActiveSetting.Setting, typeof(Construction), typeof(HostObjAttributes), ConstructionParameter.DefaultPanelType);

            if (!string.IsNullOrWhiteSpace(parameterName_Type))
            {
                IEnumerable <Parameter> parameters = hostObjAttributes.GetParameters(parameterName_Type);
                if (parameters != null && parameters.Count() > 0)
                {
                    foreach (Parameter parameter in parameters)
                    {
                        if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.String)
                        {
                            string text = parameter.AsString();
                            if (!string.IsNullOrWhiteSpace(text))
                            {
                                PanelType result = Analytical.Query.PanelType(text, false);
                                if (result != Analytical.PanelType.Undefined)
                                {
                                    return(result);
                                }
                            }
                        }
                    }
                }
            }

            return(Analytical.Query.PanelType(hostObjAttributes.Name, true));
        }
Esempio n. 4
0
        /// <summary>
        /// Gets the material Id of the first layer of the host object.
        /// </summary>
        /// <param name="hostObject">The host object.</param>
        /// <returns>The material id.</returns>
        public static ElementId GetFirstLayerMaterialId(HostObject hostObject)
        {
            ElementId         typeElemId  = hostObject.GetTypeId();
            HostObjAttributes hostObjAttr = hostObject.Document.GetElement(typeElemId) as HostObjAttributes;

            if (hostObjAttr == null)
            {
                return(ElementId.InvalidElementId);
            }

            CompoundStructure cs = hostObjAttr.GetCompoundStructure();

            if (cs != null)
            {
                ElementId matId = cs.LayerCount > 0 ? cs.GetMaterialId(0) : ElementId.InvalidElementId;
                if (matId != ElementId.InvalidElementId)
                {
                    return(matId);
                }
                else
                {
                    return(CategoryUtil.GetBaseMaterialIdForElement(hostObject));
                };
            }

            return(ElementId.InvalidElementId);
        }
Esempio n. 5
0
        private static HashSet <ElementId> GetUsedMaterialIds(Autodesk.Revit.DB.Element type)
        {
            HostObjAttributes   hostObj         = type as HostObjAttributes;
            HashSet <ElementId> usedMaterialIds = new HashSet <ElementId>();

            if (hostObj != null)
            {
                var compundStructure = hostObj.GetCompoundStructure();
                if (compundStructure != null)
                {
                    int layerCount = compundStructure.LayerCount;
                    for (int j = 0; j < layerCount; j++)
                    {
                        usedMaterialIds.Add(compundStructure.GetMaterialId(j));
                    }
                }
            }
            List <ElementId> elementMaterialIds = type.GetMaterialIds(false).ToList();

            if (elementMaterialIds.Any())
            {
                usedMaterialIds.UnionWith(elementMaterialIds);
            }

            return(usedMaterialIds);
        }
Esempio n. 6
0
        Stream(ArrayList data, HostObjAttributes hostAtt)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(HostObjAttributes)));

            data.Add(new Snoop.Data.Object("Compound Structure", hostAtt.GetCompoundStructure()));

            ContFootingType contFootingType = hostAtt as ContFootingType;

            if (contFootingType != null)
            {
                Stream(data, contFootingType);
                return;
            }

            CurtainSystemType curSysType = hostAtt as CurtainSystemType;

            if (curSysType != null)
            {
                Stream(data, curSysType);
                return;
            }

            FloorType floorType = hostAtt as FloorType;

            if (floorType != null)
            {
                Stream(data, floorType);
                return;
            }

            HostedSweepType hostSweepType = hostAtt as HostedSweepType;

            if (hostSweepType != null)
            {
                Stream(data, hostSweepType);
                return;
            }

            RoofType roofType = hostAtt as RoofType;

            if (roofType != null)
            {
                Stream(data, roofType);
                return;
            }

            WallType wallType = hostAtt as WallType;

            if (wallType != null)
            {
                Stream(data, wallType);
                return;
            }
        }
Esempio n. 7
0
        public static HostPartitionType ToSAM_HostPartitionType(this HostObjAttributes hostObjAttributes, ConvertSettings convertSettings)
        {
            if (hostObjAttributes == null)
            {
                return(null);
            }

            HostPartitionType result = convertSettings?.GetObject <HostPartitionType>(hostObjAttributes.Id);

            if (result != null)
            {
                return(result);
            }

            string name = hostObjAttributes.Name;

            List <MaterialLayer> materialLayers = Architectural.Revit.Create.MaterialLayers(hostObjAttributes.Document, hostObjAttributes.GetCompoundStructure());

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

            if (hostObjAttributes is Autodesk.Revit.DB.WallType)
            {
                result = new WallType(name);
            }
            else if (hostObjAttributes is Autodesk.Revit.DB.RoofType)
            {
                result = new RoofType(name);
            }
            else if (hostObjAttributes is Autodesk.Revit.DB.FloorType)
            {
                result = new FloorType(name);
            }

            CompoundStructure compoundStructure = hostObjAttributes.GetCompoundStructure();

            if (compoundStructure != null)
            {
                compoundStructure.GetLayers();
            }

            if (result != null)
            {
                result.UpdateParameterSets(hostObjAttributes);
                convertSettings?.Add(hostObjAttributes.Id, result);
            }

            return(result);
        }
Esempio n. 8
0
        public static Construction ToSAM(this HostObjAttributes hostObjAttributes, Core.Revit.ConvertSettings convertSettings)
        {
            if (hostObjAttributes == null)
            {
                return(null);
            }

            Construction result = convertSettings?.GetObject <Construction>(hostObjAttributes.Id);

            if (result != null)
            {
                return(result);
            }

            string    name      = hostObjAttributes.Name;
            PanelType panelType = hostObjAttributes.PanelType();

            if (panelType == PanelType.Undefined)
            {
                panelType = Query.PanelType((BuiltInCategory)hostObjAttributes.Category.Id.IntegerValue);
            }

            Construction construction = Analytical.Query.DefaultConstruction(panelType);

            if (construction != null && (name.Equals(construction.Name) || name.Equals(construction.UniqueName())))
            {
                result = new Construction(construction);
            }
            else
            {
                result = new Construction(hostObjAttributes.Name);
            }

            result.UpdateParameterSets(hostObjAttributes, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));

            //result.Add(Core.Revit.Query.ParameterSet(hostObjAttributes));

            convertSettings?.Add(hostObjAttributes.Id, result);

            if (panelType != PanelType.Undefined)
            {
                result.SetValue(ConstructionParameter.DefaultPanelType, panelType.Text());
            }
            else
            {
                result.SetValue(ConstructionParameter.DefaultPanelType, null);
            }

            return(result);
        }
Esempio n. 9
0
        /***************************************************/
        /****               Public Methods              ****/
        /***************************************************/

        public static oM.Physical.Elements.Wall WallFromRevit(this Wall wall, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            if (wall == null)
            {
                return(null);
            }

            settings = settings.DefaultIfNull();

            oM.Physical.Elements.Wall bHoMWall = refObjects.GetValue <oM.Physical.Elements.Wall>(wall.Id);
            if (bHoMWall != null)
            {
                return(bHoMWall);
            }

            if (wall.StackedWallOwnerId != null && wall.StackedWallOwnerId != ElementId.InvalidElementId)
            {
                return(null);
            }

            if (wall.CurtainGrid != null)
            {
                bHoMWall = wall.WallFromRevit_Curtain(settings, refObjects);
            }
            else
            {
                bHoMWall = wall.WallFromRevit_Solid(settings, refObjects);
            }

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

            HostObjAttributes hostObjAttributes = wall.Document.GetElement(wall.GetTypeId()) as HostObjAttributes;
            string            materialGrade     = wall.MaterialGrade(settings);

            oM.Physical.Constructions.Construction construction = hostObjAttributes.ConstructionFromRevit(materialGrade, settings, refObjects);
            bHoMWall.Construction = construction;

            bHoMWall.Name = wall.FamilyTypeFullName();

            //Set identifiers, parameters & custom data
            bHoMWall.SetIdentifiers(wall);
            bHoMWall.CopyParameters(wall, settings.ParameterSettings);
            bHoMWall.SetProperties(wall, settings.ParameterSettings);

            refObjects.AddOrReplace(wall.Id, bHoMWall);
            return(bHoMWall);
        }
Esempio n. 10
0
        /***************************************************/

        public static IBHoMObject FromRevit(this HostObjAttributes hostObjAttributes, Discipline discipline, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            switch (discipline)
            {
            case Discipline.Structural:
                return(hostObjAttributes.SurfacePropertyFromRevit(null, settings, refObjects) as IBHoMObject);

            case Discipline.Architecture:
            case Discipline.Physical:
            case Discipline.Environmental:
                return(hostObjAttributes.ConstructionFromRevit(null, settings, refObjects));

            default:
                return(null);
            }
        }
Esempio n. 11
0
        /***************************************************/
        /****               Public Methods              ****/
        /***************************************************/

        public static oM.Physical.Elements.Roof RoofFromRevit(this RoofBase roof, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            if (roof == null)
            {
                return(null);
            }

            settings = settings.DefaultIfNull();

            oM.Physical.Elements.Roof bHoMRoof = refObjects.GetValue <oM.Physical.Elements.Roof>(roof.Id);
            if (bHoMRoof != null)
            {
                return(bHoMRoof);
            }

            List <CurtainGrid> curtainGrids = roof.ICurtainGrids();

            if (curtainGrids.Count != 0)
            {
                bHoMRoof = roof.CurtainRoofFromRevit(settings, refObjects);
            }
            else
            {
                bHoMRoof = roof.SolidRoofFromRevit(settings, refObjects);
            }

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

            HostObjAttributes hostObjAttributes = roof.Document.GetElement(roof.GetTypeId()) as HostObjAttributes;
            string            materialGrade     = roof.MaterialGrade(settings);

            oM.Physical.Constructions.Construction construction = hostObjAttributes.ConstructionFromRevit(materialGrade, settings, refObjects);
            bHoMRoof.Construction = construction;

            bHoMRoof.Name = roof.FamilyTypeFullName();

            //Set identifiers, parameters & custom data
            bHoMRoof.SetIdentifiers(roof);
            bHoMRoof.CopyParameters(roof, settings.ParameterSettings);
            bHoMRoof.SetProperties(roof, settings.ParameterSettings);

            refObjects.AddOrReplace(roof.Id, bHoMRoof);
            return(bHoMRoof);
        }
Esempio n. 12
0
        /***************************************************/

        public static bool SetType(this HostObject element, ISurface bHoMObject, RevitSettings settings)
        {
            Document          doc         = element.Document;
            HostObjAttributes hostObjAttr = bHoMObject.Construction.ToRevitElementType(doc, bHoMObject.BuiltInCategories(doc), settings);

            if (hostObjAttr == null)
            {
                hostObjAttr = bHoMObject.IElementType(doc, settings) as HostObjAttributes;
            }

            if (hostObjAttr != null && hostObjAttr.Id.IntegerValue != element.GetTypeId().IntegerValue)
            {
                return(element.SetParameter(BuiltInParameter.ELEM_TYPE_PARAM, hostObjAttr.Id));
            }

            return(false);
        }
Esempio n. 13
0
        /***************************************************/
        /****               Public Methods              ****/
        /***************************************************/

        public static oM.Physical.Constructions.Construction ConstructionFromRevit(this HostObjAttributes hostObjAttributes, string materialGrade = null, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            settings = settings.DefaultIfNull();

            string refId = hostObjAttributes.Id.ReferenceIdentifier(materialGrade);

            oM.Physical.Constructions.Construction construction = refObjects.GetValue <oM.Physical.Constructions.Construction>(refId);
            if (construction != null)
            {
                return(construction);
            }

            List <BH.oM.Physical.Constructions.Layer> layers = new List <oM.Physical.Constructions.Layer>();
            CompoundStructure compoundStructure = hostObjAttributes.GetCompoundStructure();

            if (compoundStructure != null)
            {
                IEnumerable <CompoundStructureLayer> compoundStructureLayers = compoundStructure.GetLayers();
                if (compoundStructureLayers != null)
                {
                    foreach (CompoundStructureLayer layer in compoundStructureLayers)
                    {
                        layers.Add(layer.Layer(hostObjAttributes, materialGrade, settings, refObjects));
                    }
                }
            }

            construction = BH.Engine.Physical.Create.Construction(hostObjAttributes.FamilyTypeFullName(), layers);

            //Set identifiers, parameters & custom data
            construction.SetIdentifiers(hostObjAttributes);
            construction.CopyParameters(hostObjAttributes, settings.ParameterSettings);
            construction.SetProperties(hostObjAttributes, settings.ParameterSettings);

            refObjects.AddOrReplace(refId, construction);
            return(construction);
        }
Esempio n. 14
0
        /// <summary>
        /// Gets the material ids of finish function of the host object.
        /// </summary>
        /// <param name="hostObject">The host object.</param>
        /// <returns>The material ids.</returns>
        public static ISet <ElementId> GetFinishMaterialIds(HostObject hostObject)
        {
            HashSet <ElementId> matIds = new HashSet <ElementId>();

            ElementId         typeElemId  = hostObject.GetTypeId();
            HostObjAttributes hostObjAttr = hostObject.Document.GetElement(typeElemId) as HostObjAttributes;

            if (hostObjAttr == null)
            {
                return(matIds);
            }

            ElementId         baseMatId = CategoryUtil.GetBaseMaterialIdForElement(hostObject);
            CompoundStructure cs        = hostObjAttr.GetCompoundStructure();

            if (cs != null)
            {
                for (int i = 0; i < cs.LayerCount; ++i)
                {
                    MaterialFunctionAssignment function = cs.GetLayerFunction(i);
                    if (function == MaterialFunctionAssignment.Finish1 || function == MaterialFunctionAssignment.Finish2)
                    {
                        ElementId matId = cs.GetMaterialId(i);
                        if (matId != ElementId.InvalidElementId)
                        {
                            matIds.Add(matId);
                        }
                        else if (baseMatId != ElementId.InvalidElementId)
                        {
                            matIds.Add(baseMatId);
                        }
                    }
                }
            }

            return(matIds);
        }
Esempio n. 15
0
        /***************************************************/

        internal static void CompositePanelWarning(this HostObjAttributes hostObjAttributes)
        {
            BH.Engine.Reflection.Compute.RecordWarning(string.Format("Composite panels are currently not supported in BHoM. A zero thickness panel is created. Element type Id: {0}", hostObjAttributes.Id.IntegerValue));
        }
Esempio n. 16
0
        /// <summary>
        /// Collect information about material layer.
        ///   For IFC4RV Architectural exchange, it will generate IfcMatrialConstituentSet along with the relevant IfcShapeAspect and the width in the quantityset
        ///   For IFC4RV Structural exchange, it will generate multiple components as IfcBuildingElementPart for each layer
        ///   For others IfcMaterialLayer will be created
        /// </summary>
        private void CollectMaterialLayerSet()
        {
            ElementId typeElemId = m_Element.GetTypeId();

            MaterialIds = new List <Tuple <ElementId, string, double> >();
            IFCAnyHandle materialLayerSet = ExporterCacheManager.MaterialSetCache.FindLayerSet(typeElemId);

            // Roofs with no components are only allowed one material.  We will arbitrarily choose the thickest material.
            PrimaryMaterialHandle = ExporterCacheManager.MaterialSetCache.FindPrimaryMaterialHnd(typeElemId);
            if (IFCAnyHandleUtil.IsNullOrHasNoValue(materialLayerSet))
            {
                List <double> widths = new List <double>();
                List <MaterialFunctionAssignment> functions = new List <MaterialFunctionAssignment>();

                HostObjAttributes hostObjAttr = m_Element.Document.GetElement(typeElemId) as HostObjAttributes;
                if (hostObjAttr == null)
                {
                    // It does not have the HostObjAttribute (where we will get the compound structure for material layer set.
                    // We will define a single material instead and create the material layer set of this single material if there is enough information (At least Material id and thickness)
                    FamilyInstance familyInstance = m_Element as FamilyInstance;
                    if (familyInstance == null)
                    {
                        return;
                    }

                    FamilySymbol            familySymbol = familyInstance.Symbol;
                    ICollection <ElementId> famMatIds    = familySymbol.GetMaterialIds(false);
                    if (famMatIds.Count == 0)
                    {
                        // For some reason Plate type may not return any Material id
                        ElementId baseMatId = CategoryUtil.GetBaseMaterialIdForElement(m_Element);
                        Material  material  = m_Element.Document.GetElement(baseMatId) as Material;
                        if (material == null)
                        {
                            return;
                        }

                        string    layerName    = NamingUtil.GetOverrideStringValue(material, "IfcMaterialLayer.Name", material.Name);
                        double    matWidth     = 0.0;
                        Parameter thicknessPar = familySymbol.get_Parameter(BuiltInParameter.CURTAIN_WALL_SYSPANEL_THICKNESS);
                        if (thicknessPar != null)
                        {
                            matWidth = thicknessPar.AsDouble();
                        }
                        widths.Add(matWidth);

                        if (baseMatId != ElementId.InvalidElementId)
                        {
                            MaterialIds.Add(new Tuple <ElementId, string, double>(baseMatId, layerName, matWidth));
                        }
                        // How to get the thickness? For CurtainWall Panel (PanelType), there is a builtin parameter CURTAINWALL_SYSPANEL_THICKNESS

                        functions.Add(MaterialFunctionAssignment.None);
                    }
                    else
                    {
                        foreach (ElementId matid in famMatIds)
                        {
                            // How to get the thickness? For CurtainWall Panel (PanelType), there is a builtin parameter CURTAINWALL_SYSPANEL_THICKNESS
                            Parameter thicknessPar = familySymbol.get_Parameter(BuiltInParameter.CURTAIN_WALL_SYSPANEL_THICKNESS);
                            double    matWidth     = 0.0;
                            if (thicknessPar == null)
                            {
                                matWidth = ParameterUtil.GetSpecialThicknessParameter(familySymbol);
                            }
                            else
                            {
                                matWidth = thicknessPar.AsDouble();
                            }

                            if (MathUtil.IsAlmostZero(matWidth))
                            {
                                continue;
                            }

                            widths.Add(matWidth);
                            ElementId baseMatId = CategoryUtil.GetBaseMaterialIdForElement(m_Element);
                            if (matid != ElementId.InvalidElementId)
                            {
                                Material material = m_Element.Document.GetElement(matid) as Material;
                                if (material != null)
                                {
                                    string layerName = NamingUtil.GetOverrideStringValue(material, "IfcMaterialLayer.Name", material.Name);
                                    MaterialIds.Add(new Tuple <ElementId, string, double>(matid, layerName, matWidth));
                                }
                            }
                            else
                            {
                                MaterialIds.Add(new Tuple <ElementId, string, double>(baseMatId, null, matWidth));
                            }

                            functions.Add(MaterialFunctionAssignment.None);
                        }
                    }
                }
                else
                {
                    ElementId         baseMatId = CategoryUtil.GetBaseMaterialIdForElement(m_Element);
                    CompoundStructure cs        = hostObjAttr.GetCompoundStructure();

                    if (cs != null)
                    {
                        double scaledOffset = 0.0, scaledWallWidth = 0.0, wallHeight = 0.0;
                        Wall   wall = m_Element as Wall;
                        if (wall != null)
                        {
                            scaledWallWidth = UnitUtil.ScaleLength(wall.Width);
                            scaledOffset    = -scaledWallWidth / 2.0;
                            BoundingBoxXYZ boundingBox = wall.get_BoundingBox(null);
                            if (boundingBox != null)
                            {
                                wallHeight = boundingBox.Max.Z - boundingBox.Min.Z;
                            }
                        }

                        //TODO: Vertically compound structures are not yet supported by export.
                        if (!cs.IsVerticallyHomogeneous() && !MathUtil.IsAlmostZero(wallHeight))
                        {
                            cs = cs.GetSimpleCompoundStructure(wallHeight, wallHeight / 2.0);
                        }

                        for (int ii = 0; ii < cs.LayerCount; ++ii)
                        {
                            double matWidth = cs.GetLayerWidth(ii);
                            //if (MathUtil.IsAlmostZero(matWidth))
                            //   continue;

                            ElementId matId = cs.GetMaterialId(ii);
                            if (matId != ElementId.InvalidElementId)
                            {
                                Material material = m_Element.Document.GetElement(matId) as Material;
                                if (material != null)
                                {
                                    string layerName = NamingUtil.GetOverrideStringValue(material, "IfcMaterialLayer.Name", material.Name);
                                    MaterialIds.Add(new Tuple <ElementId, string, double>(matId, layerName, matWidth));
                                }
                            }
                            else
                            {
                                MaterialIds.Add(new Tuple <ElementId, string, double>(baseMatId, null, matWidth));
                            }
                            widths.Add(matWidth);
                            // save layer function into ProductWrapper,
                            // it's used while exporting "Function" of Pset_CoveringCommon
                            functions.Add(cs.GetLayerFunction(ii));
                        }
                    }

                    if (MaterialIds.Count == 0)
                    {
                        double matWidth = cs != null?cs.GetWidth() : 0.0;

                        widths.Add(matWidth);
                        if (baseMatId != ElementId.InvalidElementId)
                        {
                            Material material = m_Element.Document.GetElement(baseMatId) as Material;
                            if (material != null)
                            {
                                string layerName = NamingUtil.GetOverrideStringValue(material, "IfcMaterialLayer.Name", material.Name);
                                MaterialIds.Add(new Tuple <ElementId, string, double>(baseMatId, layerName, matWidth));
                            }
                        }
                        functions.Add(MaterialFunctionAssignment.None);
                    }
                }

                if (m_ProductWrapper != null)
                {
                    m_ProductWrapper.ClearFinishMaterials();
                }

                // We can't create IfcMaterialLayers without creating an IfcMaterialLayerSet.  So we will simply collate here.
                IList <IFCAnyHandle> materialHnds = new List <IFCAnyHandle>();
                IList <int>          widthIndices = new List <int>();
                double thickestLayer = 0.0;
                for (int ii = 0; ii < MaterialIds.Count; ++ii)
                {
                    // Require positive width for IFC2x3 and before, and non-negative width for IFC4.
                    if (widths[ii] < -MathUtil.Eps())
                    {
                        continue;
                    }

                    bool almostZeroWidth = MathUtil.IsAlmostZero(widths[ii]);
                    if (!ExporterCacheManager.ExportOptionsCache.ExportAs4 && almostZeroWidth)
                    {
                        continue;
                    }

                    if (almostZeroWidth)
                    {
                        widths[ii] = 0.0;
                    }

                    IFCAnyHandle materialHnd = CategoryUtil.GetOrCreateMaterialHandle(m_ExporterIFC, MaterialIds[ii].Item1);
                    if (PrimaryMaterialHandle == null || (widths[ii] > thickestLayer))
                    {
                        PrimaryMaterialHandle = materialHnd;
                        thickestLayer         = widths[ii];
                    }

                    widthIndices.Add(ii);
                    materialHnds.Add(materialHnd);

                    if ((m_ProductWrapper != null) && (functions[ii] == MaterialFunctionAssignment.Finish1 || functions[ii] == MaterialFunctionAssignment.Finish2))
                    {
                        m_ProductWrapper.AddFinishMaterial(materialHnd);
                    }
                }

                int numLayersToCreate = widthIndices.Count;
                if (numLayersToCreate == 0)
                {
                    MaterialLayerSetHandle = materialLayerSet;
                    return;
                }

                // If it is a single material, check single material override (only IfcMaterial without IfcMaterialLayerSet with only 1 member)
                if (numLayersToCreate == 1 && ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                {
                    string paramValue;
                    ParameterUtil.GetStringValueFromElementOrSymbol(m_Element, "IfcSingleMaterialOverride", out paramValue);
                    if (!string.IsNullOrEmpty(paramValue))
                    {
                        IFCAnyHandle singleMaterialOverrideHnd = IFCInstanceExporter.CreateMaterial(m_ExporterIFC.GetFile(), paramValue, null, null);
                        ExporterCacheManager.MaterialHandleCache.Register(MaterialIds[0].Item1, singleMaterialOverrideHnd);
                        MaterialLayerSetHandle = singleMaterialOverrideHnd;
                        return;
                    }
                }

                IFCFile  file     = m_ExporterIFC.GetFile();
                Document document = ExporterCacheManager.Document;

                IList <IFCAnyHandle> layers = new List <IFCAnyHandle>(numLayersToCreate);
                IList <Tuple <string, IFCAnyHandle> > layerWidthQuantities = new List <Tuple <string, IFCAnyHandle> >();
                HashSet <string> layerNameUsed = new HashSet <string>();
                double           totalWidth    = 0.0;

                for (int ii = 0; ii < numLayersToCreate; ii++)
                {
                    int    widthIndex  = widthIndices[ii];
                    double scaledWidth = UnitUtil.ScaleLength(widths[widthIndex]);

                    string layerName   = "Layer";
                    string description = null;
                    string category    = null;
                    int?   priority    = null;

                    IFCLogical?isVentilated = null;
                    int        isVentilatedValue;

                    Material material = document.GetElement(MaterialIds[ii].Item1) as Material;
                    if (material != null)
                    {
                        if (ParameterUtil.GetIntValueFromElement(material, "IfcMaterialLayer.IsVentilated", out isVentilatedValue) != null)
                        {
                            if (isVentilatedValue == 0)
                            {
                                isVentilated = IFCLogical.False;
                            }
                            else if (isVentilatedValue == 1)
                            {
                                isVentilated = IFCLogical.True;
                            }
                        }

                        if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                        {
                            layerName = MaterialIds[ii].Item2;
                            if (string.IsNullOrEmpty(layerName))
                            {
                                layerName = "Layer";
                            }

                            // Ensure layer name is unique
                            layerName = NamingUtil.GetUniqueNameWithinSet(layerName, ref layerNameUsed);

                            description = NamingUtil.GetOverrideStringValue(material, "IfcMaterialLayer.Description",
                                                                            IFCAnyHandleUtil.GetStringAttribute(materialHnds[ii], "Description"));
                            category = NamingUtil.GetOverrideStringValue(material, "IfcMaterialLayer.Category",
                                                                         IFCAnyHandleUtil.GetStringAttribute(materialHnds[ii], "Category"));
                            int priorityValue;
                            if (ParameterUtil.GetIntValueFromElement(material, "IfcMaterialLayer.Priority", out priorityValue) != null)
                            {
                                priority = priorityValue;
                            }
                        }
                    }

                    if (ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                    {
                        // Skip component that has zero width (the will be no geometry associated to it
                        if (MathUtil.IsAlmostZero(scaledWidth))
                        {
                            continue;
                        }

                        IFCAnyHandle materialConstituent = IFCInstanceExporter.CreateMaterialConstituent(file, materialHnds[ii],
                                                                                                         name: layerName, description: description, category: category);
                        layers.Add(materialConstituent);

                        IFCAnyHandle layerQtyHnd = IFCInstanceExporter.CreateQuantityLength(file, "Width", description, null, scaledWidth);
                        totalWidth += scaledWidth;
                        layerWidthQuantities.Add(new Tuple <string, IFCAnyHandle>(layerName, layerQtyHnd));
                    }
                    else
                    {
                        IFCAnyHandle materialLayer = IFCInstanceExporter.CreateMaterialLayer(file, materialHnds[ii], scaledWidth, isVentilated,
                                                                                             name: layerName, description: description, category: category, priority: priority);
                        layers.Add(materialLayer);
                    }
                }

                if (layers.Count > 0)
                {
                    Element type         = document.GetElement(typeElemId);
                    string  layerSetName = NamingUtil.GetOverrideStringValue(type, "IfcMaterialLayerSet.Name", m_ExporterIFC.GetFamilyName());
                    string  layerSetDesc = NamingUtil.GetOverrideStringValue(type, "IfcMaterialLayerSet.Description", null);

                    if (ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                    {
                        HashSet <IFCAnyHandle> constituents = new HashSet <IFCAnyHandle>(layers);
                        MaterialLayerSetHandle = IFCInstanceExporter.CreateMaterialConstituentSet(file, constituents, name: layerSetName, description: layerSetDesc);
                        foreach (Tuple <string, IFCAnyHandle> layerWidthQty in layerWidthQuantities)
                        {
                            LayerQuantityWidthHnd.Add(IFCInstanceExporter.CreatePhysicalComplexQuantity(file, layerWidthQty.Item1, null,
                                                                                                        new HashSet <IFCAnyHandle>()
                            {
                                layerWidthQty.Item2
                            }, "Layer", null, null));
                        }
                        // Finally create the total width as a quantity
                        LayerQuantityWidthHnd.Add(IFCInstanceExporter.CreateQuantityLength(file, "Width", null, null, totalWidth));
                    }
                    else
                    {
                        MaterialLayerSetHandle = IFCInstanceExporter.CreateMaterialLayerSet(file, layers, layerSetName, layerSetDesc);
                    }

                    ExporterCacheManager.MaterialSetCache.RegisterLayerSet(typeElemId, MaterialLayerSetHandle, this);
                }

                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(PrimaryMaterialHandle))
                {
                    ExporterCacheManager.MaterialSetCache.RegisterPrimaryMaterialHnd(typeElemId, PrimaryMaterialHandle);
                }
            }
            else
            {
                MaterialLayerSetHandle = materialLayerSet;

                MaterialLayerSetInfo mlsInfo = ExporterCacheManager.MaterialSetCache.FindMaterialLayerSetInfo(typeElemId);
                if (mlsInfo != null)
                {
                    MaterialIds           = mlsInfo.MaterialIds;
                    PrimaryMaterialHandle = mlsInfo.PrimaryMaterialHandle;
                    LayerQuantityWidthHnd = mlsInfo.LayerQuantityWidthHnd;
                }
            }

            return;
        }
Esempio n. 17
0
        Stream(ArrayList data, ElementType sym)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(ElementType)));

            // no data at this level yet

            AnnotationSymbolType annoType = sym as AnnotationSymbolType;

            if (annoType != null)
            {
                Stream(data, annoType);
                return;
            }

            AreaReinforcementType areaReinforcementType = sym as AreaReinforcementType;

            if (areaReinforcementType != null)
            {
                Stream(data, areaReinforcementType);
                return;
            }

            AreaTagType areaTagType = sym as AreaTagType;

            if (areaTagType != null)
            {
                Stream(data, areaTagType);
                return;
            }

            BeamSystemType beamSystemType = sym as BeamSystemType;

            if (beamSystemType != null)
            {
                Stream(data, beamSystemType);
                return;
            }

            DimensionType dimType = sym as DimensionType;

            if (dimType != null)
            {
                Stream(data, dimType);
                return;
            }

            //TF
            FabricSheetType fabricST = sym as FabricSheetType;

            if (fabricST != null)
            {
                Stream(data, fabricST);
                return;
            }

            FabricWireType fabricWT = sym as FabricWireType;

            if (fabricWT != null)
            {
                Stream(data, fabricWT);
                return;
            }
            //TFEND

            GroupType groupType = sym as GroupType;

            if (groupType != null)
            {
                Stream(data, groupType);
                return;
            }

            HostObjAttributes hostAtt = sym as HostObjAttributes;

            if (hostAtt != null)
            {
                Stream(data, hostAtt);
                return;
            }

            InsertableObject insObj = sym as InsertableObject;

            if (insObj != null)
            {
                Stream(data, insObj);
                return;
            }

            LevelType levelType = sym as LevelType;

            if (levelType != null)
            {
                Stream(data, levelType);
                return;
            }

            LineAndTextAttrSymbol lineAndTextAttr = sym as LineAndTextAttrSymbol;

            if (lineAndTextAttr != null)
            {
                Stream(data, lineAndTextAttr);
                return;
            }

            LoadTypeBase loadTypeBase = sym as LoadTypeBase;

            if (loadTypeBase != null)
            {
                Stream(data, loadTypeBase);
                return;
            }

            MEPBuildingConstruction mepBldConst = sym as MEPBuildingConstruction;

            if (mepBldConst != null)
            {
                Stream(data, mepBldConst);
                return;
            }

            PathReinforcementType pathReinforcementType = sym as PathReinforcementType;

            if (pathReinforcementType != null)
            {
                Stream(data, pathReinforcementType);
                return;
            }

            RebarBarType rebarBarType = sym as RebarBarType;

            if (rebarBarType != null)
            {
                Stream(data, rebarBarType);
                return;
            }

            RebarCoverType rebarCoverType = sym as RebarCoverType;

            if (rebarCoverType != null)
            {
                Stream(data, rebarCoverType);
                return;
            }

            RebarHookType rebarHookType = sym as RebarHookType;

            if (rebarHookType != null)
            {
                Stream(data, rebarHookType);
                return;
            }

            RebarShape rebarShape = sym as RebarShape;

            if (rebarShape != null)
            {
                Stream(data, rebarShape);
                return;
            }

            RoomTagType roomTagType = sym as RoomTagType;

            if (roomTagType != null)
            {
                Stream(data, roomTagType);
                return;
            }

            SpaceTagType spaceTagType = sym as SpaceTagType;

            if (spaceTagType != null)
            {
                Stream(data, spaceTagType);
                return;
            }

            TrussType trussType = sym as TrussType;

            if (trussType != null)
            {
                Stream(data, trussType);
                return;
            }

            DistributionSysType distSysType = sym as DistributionSysType;

            if (distSysType != null)
            {
                Stream(data, distSysType);
                return;
            }

            MEPCurveType mepCurType = sym as MEPCurveType;

            if (mepCurType != null)
            {
                Stream(data, mepCurType);
                return;
            }

            FluidType fluidType = sym as FluidType;

            if (fluidType != null)
            {
                Stream(data, fluidType);
                return;
            }

            PipeScheduleType pipeSchedType = sym as PipeScheduleType;

            if (pipeSchedType != null)
            {
                Stream(data, pipeSchedType);
                return;
            }

            VoltageType voltType = sym as VoltageType;

            if (voltType != null)
            {
                Stream(data, voltType);
                return;
            }

            WireType wireType = sym as WireType;

            if (wireType != null)
            {
                Stream(data, wireType);
                return;
            }

            ModelTextType modelTxtType = sym as ModelTextType;

            if (modelTxtType != null)
            {
                Stream(data, modelTxtType);
                return;
            }
        }
Esempio n. 18
0
        public static HostObject ToRevit(this Panel panel, Document document, Core.Revit.ConvertSettings convertSettings)
        {
            Geometry.Spatial.Face3D face3D = panel?.GetFace3D();
            if (face3D == null)
            {
                return(null);
            }

            HostObject result = convertSettings?.GetObject <HostObject>(panel.Guid);

            if (result != null)
            {
                return(result);
            }

            PanelType panelType = panel.PanelType;

            Geometry.Spatial.Vector3D normal = panel.Normal;

            HostObjAttributes hostObjAttributes = panel.Construction.ToRevit(document, panelType, normal, convertSettings);

            if (hostObjAttributes == null)
            {
                hostObjAttributes = Analytical.Query.DefaultConstruction(panelType)?.ToRevit(document, panelType, normal, convertSettings); //Default Construction
            }
            BuiltInParameter[] builtInParameters = null;
            if (hostObjAttributes is Autodesk.Revit.DB.WallType)
            {
                double lowElevation = panel.LowElevation();

                Level level = document.LowLevel(lowElevation);

                Autodesk.Revit.DB.Wall wall = ToRevit_Wall(face3D, document, (Autodesk.Revit.DB.WallType)hostObjAttributes, level);
                if (wall == null)
                {
                    return(result);
                }

                //List<Curve> curveList = new List<Curve>();
                //foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D in face3D.GetEdge3Ds())
                //{
                //    if (Geometry.Spatial.Query.Clockwise(closedPlanar3D))
                //        closedPlanar3D.Reverse();

                //    List<Line> lines = closedPlanar3D.ToRevit();
                //    if (lines == null)
                //        continue;

                //    curveList.AddRange(lines);
                //}

                //if (curveList == null || curveList.Count == 0)
                //    return null;

                //double lowElevation = panel.LowElevation();

                //Level level = document.LowLevel(lowElevation);
                //if (level == null)
                //    return null;

                //Wall wall = Wall.Create(document, curveList, hostObjAttributes.Id, level.Id, false, panel.Normal.ToRevit(false));

                Parameter parameter = null;

                parameter = wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE);
                if (parameter != null)
                {
                    parameter.Set(ElementId.InvalidElementId);
                }

                parameter = wall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);
                if (parameter != null)
                {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                    double height = UnitUtils.ConvertToInternalUnits((panel.HighElevation() - lowElevation), DisplayUnitType.DUT_METERS);
#else
                    double height = UnitUtils.ConvertToInternalUnits((panel.HighElevation() - lowElevation), UnitTypeId.Meters);
#endif


                    parameter.Set(height);
                }

#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                double levelElevation = UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS);
#else
                double levelElevation = UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters);
#endif

                if (Math.Abs(lowElevation - levelElevation) > Core.Tolerance.MacroDistance)
                {
                    parameter = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
                    if (parameter != null)
                    {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                        parameter.Set(UnitUtils.ConvertToInternalUnits(lowElevation - levelElevation, DisplayUnitType.DUT_METERS));
#else
                        parameter.Set(UnitUtils.ConvertToInternalUnits(lowElevation - levelElevation, UnitTypeId.Meters));
#endif
                    }
                }

                builtInParameters = new BuiltInParameter[] { BuiltInParameter.WALL_BASE_CONSTRAINT, BuiltInParameter.WALL_BASE_OFFSET, BuiltInParameter.WALL_HEIGHT_TYPE, BuiltInParameter.WALL_USER_HEIGHT_PARAM, BuiltInParameter.WALL_KEY_REF_PARAM };
                result            = wall;
            }
            else if (hostObjAttributes is Autodesk.Revit.DB.FloorType)
            {
                Geometry.Spatial.IClosedPlanar3D closedPlanar3D_External = face3D.GetExternalEdge3D();
                if (!(closedPlanar3D_External is Geometry.Spatial.ICurvable3D))
                {
                    return(null);
                }

                double elevation = panel.LowElevation();
                Level  level     = document.HighLevel(elevation);

                Geometry.Spatial.Plane plane = new Geometry.Spatial.Plane(new Geometry.Spatial.Point3D(0, 0, elevation), Geometry.Spatial.Vector3D.WorldZ);

                CurveArray curveArray_Sloped = new CurveArray();
                CurveArray curveArray_Plane  = new CurveArray();

                Geometry.Spatial.IClosedPlanar3D closedPlanar3D = face3D.GetExternalEdge3D();
                if (!(closedPlanar3D is Geometry.Spatial.ICurvable3D))
                {
                    return(null);
                }

                List <Geometry.Spatial.Segment3D> segment3Ds = Geometry.Revit.Query.Segment3Ds(closedPlanar3D);
                if (segment3Ds == null || segment3Ds.Count == 0)
                {
                    return(null);
                }

                foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds)
                {
                    curveArray_Sloped.Append(segment3D.ToRevit_Line());

                    Geometry.Spatial.Segment3D segment3D_Temp = Geometry.Spatial.Query.Project(plane, segment3D);
                    if (segment3D_Temp == null)
                    {
                        continue;
                    }

                    curveArray_Plane.Append(segment3D_Temp.ToRevit_Line());
                }

#if Revit2017 || Revit2018 || Revit2019 || Revit2020 || Revit2021
                Autodesk.Revit.DB.Floor floor = document.Create.NewFloor(curveArray_Plane, hostObjAttributes as Autodesk.Revit.DB.FloorType, level, false);
#else
                CurveLoop curveLoop = new CurveLoop();
                foreach (Curve curve in curveArray_Plane)
                {
                    curveLoop.Append(curve);
                }

                Autodesk.Revit.DB.Floor floor = Autodesk.Revit.DB.Floor.Create(document, new CurveLoop[] { curveLoop }, hostObjAttributes.Id, level.Id);
#endif

                if (floor != null)
                {
                    floor.ChangeTypeId(hostObjAttributes.Id);

                    List <Geometry.Spatial.IClosedPlanar3D> closedPlanar3Ds_Internal = face3D.GetInternalEdge3Ds();
                    if (closedPlanar3Ds_Internal != null && closedPlanar3Ds_Internal.Count > 0)
                    {
                        //Requires to be regenerated before inserting openings
                        //https://thebuildingcoder.typepad.com/blog/2013/07/create-a-floor-with-an-opening-or-complex-boundary.html
                        document.Regenerate();

                        foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D_Internal in face3D.GetInternalEdge3Ds())
                        {
                            List <Geometry.Spatial.Segment3D> segment3Ds_Internal = Geometry.Revit.Query.Segment3Ds(closedPlanar3D_Internal);
                            if (segment3Ds_Internal == null || segment3Ds_Internal.Count == 0)
                            {
                                continue;
                            }

                            curveArray_Plane = new CurveArray();
                            //foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds)
                            foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds_Internal)
                            {
                                curveArray_Sloped.Append(segment3D.ToRevit_Line());

                                Geometry.Spatial.Segment3D segment3D_Temp = Geometry.Spatial.Query.Project(plane, segment3D);
                                if (segment3D_Temp == null)
                                {
                                    continue;
                                }

                                curveArray_Plane.Append(segment3D_Temp.ToRevit_Line());
                            }

                            Opening opening = document.Create.NewOpening(floor, curveArray_Plane, true);
                        }
                    }
                }

                if (floor != null)
                {
                    document.Regenerate();

                    SlabShapeEditor slabShapeEditor = floor.SlabShapeEditor;
                    if (slabShapeEditor != null)
                    {
                        slabShapeEditor.ResetSlabShape();

                        foreach (Curve curve in curveArray_Sloped)
                        {
                            XYZ xYZ = curve.GetEndPoint(0);
                            slabShapeEditor.DrawPoint(xYZ);
                        }
                    }
                }

                builtInParameters = new BuiltInParameter[] { BuiltInParameter.LEVEL_PARAM };
                result            = floor;
            }
            else if (hostObjAttributes is Autodesk.Revit.DB.RoofType)
            {
                CurveArray curveArray = new CurveArray();
                foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D in face3D.GetEdge3Ds())
                {
                    List <Geometry.Spatial.Segment3D> segment3Ds = Geometry.Revit.Query.Segment3Ds(closedPlanar3D);
                    if (segment3Ds == null || segment3Ds.Count == 0)
                    {
                        return(null);
                    }

                    segment3Ds.ForEach(x => curveArray.Append(x.ToRevit_Line()));
                }

                Level  level          = document.HighLevel(panel.LowElevation());
                double levelElevation = level.Elevation;

                ModelCurveArray modelCurveArray = new ModelCurveArray();
                RoofBase        roofBase        = document.Create.NewFootPrintRoof(curveArray, level, hostObjAttributes as Autodesk.Revit.DB.RoofType, out modelCurveArray);

                Parameter parameter = roofBase.get_Parameter(BuiltInParameter.ROOF_UPTO_LEVEL_PARAM);
                if (parameter != null)
                {
                    parameter.Set(ElementId.InvalidElementId);
                }

                SlabShapeEditor slabShapeEditor = roofBase.SlabShapeEditor;
                if (slabShapeEditor != null)
                {
                    slabShapeEditor.ResetSlabShape();

                    foreach (Curve curve in curveArray)
                    {
                        XYZ xYZ = curve.GetEndPoint(0);
                        //if (Math.Abs(xYZ.Z - levelElevation) > Core.Tolerance.MicroDistance)
                        slabShapeEditor.DrawPoint(xYZ);
                    }
                }

                builtInParameters = new BuiltInParameter[] { BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM, BuiltInParameter.ROOF_BASE_LEVEL_PARAM, BuiltInParameter.ROOF_UPTO_LEVEL_PARAM };
                result            = roofBase;
            }

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

            List <Aperture> apertures = panel.Apertures;
            if (apertures != null)
            {
                if (result is Autodesk.Revit.DB.Wall && ((Autodesk.Revit.DB.Wall)result).WallType.Kind == WallKind.Curtain)
                {
                }
                else
                {
                    foreach (Aperture aperture in apertures)
                    {
                        Geometry.Spatial.Plane plane_Aperture = aperture?.PlanarBoundary3D?.Plane;
                        if (plane_Aperture == null)
                        {
                            continue;
                        }

                        //bool flipHand = !plane_Panel.AxisX.SameHalf(plane_Aperture.AxisX);
                        //bool flipFacing = !plane_Panel.Normal.SameHalf(plane_Aperture.Normal);

                        FamilyInstance failyInstance_Aperture = aperture.ToRevit(document, result, convertSettings);
                    }
                }
            }

            if (convertSettings.ConvertParameters)
            {
                Core.Revit.Modify.SetValues(result, panel, builtInParameters);
                Core.Revit.Modify.SetValues(result, panel, ActiveSetting.Setting);

                Core.Revit.Modify.SetJson(result, panel.ToJObject()?.ToString());
            }
            //TODO: Implement proper log
            //System.IO.File.AppendAllText(@"C:\Users\DengusiakM\Desktop\SAM\2020-04-16 floorbug\LOG.txt", string.Format("{0}\t{1}\t{2}\n", DateTime.Now.ToString(), panel.Guid, panel.Name));

            convertSettings?.Add(panel.Guid, result);

            return(result);
        }
Esempio n. 19
0
        public static Aperture ToSAM_Aperture(this FamilyInstance familyInstance, Core.Revit.ConvertSettings convertSettings)
        {
            if (familyInstance == null)
            {
                return(null);
            }

            Aperture result = convertSettings?.GetObject <Aperture>(familyInstance.Id);

            if (result != null)
            {
                return(result);
            }

            if (Core.Revit.Query.Simplified(familyInstance))
            {
                result = Core.Revit.Query.IJSAMObject <Aperture>(familyInstance);
                if (result != null)
                {
                    convertSettings?.Add(familyInstance.Id, result);
                    return(result);
                }
            }

            Point3D point3D_Location = Geometry.Revit.Query.Location(familyInstance);

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

            PanelType       panelType_Host       = PanelType.Undefined;
            BuiltInCategory builtInCategory_Host = BuiltInCategory.INVALID;

            if (familyInstance.Host != null)
            {
                HostObject hostObject = familyInstance.Host as HostObject;
                if (hostObject != null)
                {
                    builtInCategory_Host = (BuiltInCategory)hostObject.Category.Id.IntegerValue;

                    List <Face3D> face3Ds_Temp = hostObject.Profiles();
                    if (face3Ds_Temp != null && face3Ds_Temp.Count != 0)
                    {
                        Geometry.Spatial.Plane plane_Host = face3Ds_Temp.Closest(point3D_Location)?.GetPlane();
                        if (plane_Host != null)
                        {
                            point3D_Location = plane_Host.Project(point3D_Location);
                        }
                    }

                    HostObjAttributes hostObjAttributes = familyInstance.Document.GetElement(hostObject.GetTypeId()) as HostObjAttributes;
                    if (hostObjAttributes != null)
                    {
                        panelType_Host = hostObjAttributes.PanelType();
                    }

                    if (panelType_Host == PanelType.Undefined)
                    {
                        panelType_Host = hostObject.PanelType();
                    }
                }
            }

            ApertureConstruction apertureConstruction = ToSAM_ApertureConstruction(familyInstance, convertSettings);

            if (apertureConstruction == null && panelType_Host != PanelType.Undefined)
            {
                apertureConstruction = Analytical.Query.DefaultApertureConstruction(panelType_Host, familyInstance.ApertureType()); //Default Aperture Construction
            }
            Vector3D axisX  = null;
            Vector3D normal = null;
            Vector3D axisY  = null;

            if (builtInCategory_Host == BuiltInCategory.OST_Roofs)
            {
                axisX  = familyInstance.HandOrientation.ToSAM_Vector3D(false);
                axisY  = familyInstance.FacingOrientation.ToSAM_Vector3D(false);
                normal = Geometry.Spatial.Query.AxisY(axisY, axisX);
            }
            else
            {
                axisX  = familyInstance.HandOrientation.ToSAM_Vector3D(false);
                normal = familyInstance.FacingOrientation.ToSAM_Vector3D(false);
                axisY  = Geometry.Spatial.Query.AxisY(normal, axisX);
            }


            Geometry.Spatial.Plane plane = Geometry.Spatial.Create.Plane(point3D_Location, axisX, axisY);
            if (!plane.Normal.SameHalf(normal))
            {
                plane.FlipZ(false);
            }

            List <Face3D> face3Ds = Geometry.Revit.Convert.ToSAM_Face3Ds(familyInstance);

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

            List <Point2D> point2Ds = new List <Point2D>();

            foreach (Face3D face3D_Temp in face3Ds)
            {
                IClosedPlanar3D closedPlanar3D = face3D_Temp.GetExternalEdge3D();
                if (closedPlanar3D is ICurvable3D)
                {
                    List <ICurve3D> curve3Ds = ((ICurvable3D)closedPlanar3D).GetCurves();
                    foreach (ICurve3D curve3D in curve3Ds)
                    {
                        ICurve3D curve3D_Temp = plane.Project(curve3D);
                        point2Ds.Add(plane.Convert(curve3D_Temp.GetStart()));
                    }
                }
            }

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

            //TODO: Working on SAM Families (requested by Michal)

            string parameterName_Height = Core.Revit.Query.Name(ActiveSetting.Setting, typeof(Aperture), typeof(FamilyInstance), "GetHeight");
            string parameterName_Width  = Core.Revit.Query.Name(ActiveSetting.Setting, typeof(Aperture), typeof(FamilyInstance), "GetWidth");

            if (!string.IsNullOrWhiteSpace(parameterName_Height) && !string.IsNullOrWhiteSpace(parameterName_Width))
            {
                Parameter parameter_Height = familyInstance.LookupParameter(parameterName_Height);
                Parameter parameter_Width  = familyInstance.LookupParameter(parameterName_Width);
                if (parameter_Height != null && parameter_Width != null && parameter_Height.HasValue && parameter_Width.HasValue && parameter_Height.StorageType == StorageType.Double && parameter_Width.StorageType == StorageType.Double)
                {
                    double height = UnitUtils.ConvertFromInternalUnits(parameter_Height.AsDouble(), DisplayUnitType.DUT_METERS);
                    double width  = UnitUtils.ConvertFromInternalUnits(parameter_Width.AsDouble(), DisplayUnitType.DUT_METERS);

                    BoundingBox2D boundingBox2D = new BoundingBox2D(point2Ds);
                    double        factor_Height = height / boundingBox2D.Height;
                    double        factor_Width  = width / boundingBox2D.Width;

                    point2Ds = point2Ds.ConvertAll(x => new Point2D(x.X * factor_Width, x.Y * factor_Height));
                }
            }

            Rectangle2D rectangle2D = Geometry.Planar.Create.Rectangle2D(point2Ds);

            result = new Aperture(apertureConstruction, new Face3D(plane, rectangle2D));
            result.UpdateParameterSets(familyInstance, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));

            convertSettings?.Add(familyInstance.Id, result);

            return(result);
        }
Esempio n. 20
0
        public static bool UpdateConstructions(
            this Document document,
            IEnumerable <Panel> panels,
            Core.DelimitedFileTable delimitedFileTable,
            ConstructionLibrary constructionLibrary,
            ApertureConstructionLibrary apertureConstructionLibrary,
            out List <Panel> panels_Result,
            out List <Aperture> apertures_Result,
            out List <ElementType> elementTypes_Panels,
            out List <ElementType> elementTypes_Apertures,
            out ConstructionLibrary constructionLibrary_Result,
            out ApertureConstructionLibrary apertureConstructionLibrary_Result,
            string sourceColumnName,
            string destinationColumnName,
            string templateColumnName,
            string typeColumnName,
            string thicknessColumnName = null)
        {
            panels_Result                      = null;
            apertures_Result                   = null;
            elementTypes_Panels                = null;
            elementTypes_Apertures             = null;
            constructionLibrary_Result         = null;
            apertureConstructionLibrary_Result = null;

            if (document == null || panels == null || delimitedFileTable == null || constructionLibrary == null || apertureConstructionLibrary == null)
            {
                return(false);
            }

            int index_Source = delimitedFileTable.GetColumnIndex(sourceColumnName);

            if (index_Source == -1)
            {
                return(false);
            }

            int index_Template = delimitedFileTable.GetColumnIndex(templateColumnName);

            if (index_Template == -1)
            {
                return(false);
            }

            int index_Destination = delimitedFileTable.GetColumnIndex(destinationColumnName);

            if (index_Destination == -1)
            {
                return(false);
            }

            int index_Type = delimitedFileTable.GetColumnIndex(typeColumnName);

            if (index_Type == -1)
            {
                return(false);
            }

            panels_Result          = new List <Panel>();
            apertures_Result       = new List <Aperture>();
            elementTypes_Panels    = new List <ElementType>();
            elementTypes_Apertures = new List <ElementType>();

            int index_Thickness = delimitedFileTable.GetColumnIndex(thicknessColumnName);

            constructionLibrary_Result         = new ConstructionLibrary(constructionLibrary.Name);
            apertureConstructionLibrary_Result = new ApertureConstructionLibrary(apertureConstructionLibrary.Name);

            Core.Revit.ConvertSettings convertSettings = Core.Revit.Query.ConvertSettings();

            foreach (Panel panel in panels)
            {
                Construction construction = panel?.Construction;
                if (construction == null)
                {
                    continue;
                }

                string name = construction.Name;
                if (name == null)
                {
                    continue;
                }

                string    name_Destination = null;
                string    name_Template    = null;
                string    name_Source      = null;
                PanelType panelType        = PanelType.Undefined;
                double    thickness        = double.NaN;
                for (int i = 0; i < delimitedFileTable.RowCount; i++)
                {
                    string typeName = null;
                    if (delimitedFileTable.TryConvert(i, index_Type, out typeName))
                    {
                        ApertureType apertureType = Analytical.Query.ApertureType(typeName);
                        if (apertureType != ApertureType.Undefined)
                        {
                            continue;
                        }

                        panelType = Analytical.Query.PanelType(typeName as object);
                    }

                    if (!delimitedFileTable.TryConvert(i, index_Source, out name_Source))
                    {
                        continue;
                    }

                    if (!name.Equals(name_Source))
                    {
                        continue;
                    }

                    if (!delimitedFileTable.TryConvert(i, index_Destination, out name_Destination))
                    {
                        name_Destination = null;
                        continue;
                    }

                    if (!delimitedFileTable.TryConvert(i, index_Template, out name_Template))
                    {
                        name_Template = null;
                    }

                    if (index_Thickness != -1)
                    {
                        if (!delimitedFileTable.TryConvert(i, index_Thickness, out thickness))
                        {
                            thickness = double.NaN;
                        }
                    }

                    break;
                }

                if (string.IsNullOrWhiteSpace(name_Destination))
                {
                    name_Destination = name_Template;
                }

                if (string.IsNullOrWhiteSpace(name_Destination))
                {
                    continue;
                }

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

                Construction construction_New = constructionLibrary_Result.GetConstructions(name_Destination)?.FirstOrDefault();
                if (construction_New == null)
                {
                    Construction construction_Temp = constructionLibrary.GetConstructions(name_Template)?.FirstOrDefault();
                    if (construction_Temp == null)
                    {
                        continue;
                    }

                    if (name_Destination.Equals(name_Template))
                    {
                        construction_New = construction_Temp;
                    }
                    else
                    {
                        construction_New = new Construction(construction_Temp, name_Destination);
                    }

                    construction_New.SetValue(ConstructionParameter.Description, construction.Name);
                    construction_New.RemoveValue(ConstructionParameter.DefaultPanelType);

                    if (!double.IsNaN(thickness))
                    {
                        construction_New.SetValue(ConstructionParameter.DefaultThickness, thickness);
                    }

                    constructionLibrary_Result.Add(construction_New);
                }

                HostObjAttributes hostObjAttributes = Convert.ToRevit(construction_New, document, panelType, panel.Normal, convertSettings);
                if (hostObjAttributes == null)
                {
                    if (string.IsNullOrWhiteSpace(name_Template))
                    {
                        Construction construction_Default = Analytical.Query.DefaultConstruction(panelType);
                        if (construction_Default != null)
                        {
                            name_Template = construction_Default.Name;
                        }
                    }

                    if (string.IsNullOrWhiteSpace(name_Template))
                    {
                        continue;
                    }

                    hostObjAttributes = DuplicateByType(document, name_Template, panelType, construction_New) as HostObjAttributes;
                }

                Construction construction_New_Temp = new Construction(hostObjAttributes.ToSAM(new Core.Revit.ConvertSettings(false, true, false)), construction_New.Guid);
                construction_New_Temp = new Construction(construction_New_Temp, construction_New.ConstructionLayers);
                constructionLibrary_Result.Add(construction_New_Temp);

                Panel panel_New = Analytical.Create.Panel(panel, construction_New_Temp);
                if (panel_New.PanelType != panelType)
                {
                    panel_New = Analytical.Create.Panel(panel_New, panelType);
                }

                List <Aperture> apertures = panel_New.Apertures;
                if (apertures != null && apertures.Count != 0)
                {
                    foreach (Aperture aperture in apertures)
                    {
                        panel_New.RemoveAperture(aperture.Guid);

                        ApertureConstruction apertureConstruction = aperture?.ApertureConstruction;
                        if (apertureConstruction == null)
                        {
                            continue;
                        }

                        name = apertureConstruction.Name;
                        if (name == null)
                        {
                            continue;
                        }

                        name_Destination = null;
                        name_Template    = null;
                        name_Source      = null;
                        ApertureType apertureType = ApertureType.Undefined;
                        for (int i = 0; i < delimitedFileTable.RowCount; i++)
                        {
                            string typeName = null;
                            if (!delimitedFileTable.TryGetValue(i, index_Type, out typeName) || string.IsNullOrWhiteSpace(typeName))
                            {
                                continue;
                            }

                            apertureType = Analytical.Query.ApertureType(typeName);
                            if (apertureType == ApertureType.Undefined)
                            {
                                if (typeName.Trim().Equals("Curtain Panels"))
                                {
                                    apertureType = ApertureType.Window;
                                }
                            }

                            if (apertureType == ApertureType.Undefined)
                            {
                                continue;
                            }

                            if (!delimitedFileTable.TryGetValue(i, index_Source, out name_Source) || string.IsNullOrWhiteSpace(name_Source))
                            {
                                continue;
                            }

                            if (!name.Equals(name_Source))
                            {
                                continue;
                            }

                            if (!delimitedFileTable.TryGetValue(i, index_Destination, out name_Destination))
                            {
                                name_Destination = null;
                                continue;
                            }

                            if (!delimitedFileTable.TryGetValue(i, index_Template, out name_Template))
                            {
                                name_Template = null;
                            }

                            break;
                        }


                        if (string.IsNullOrWhiteSpace(name_Destination))
                        {
                            name_Destination = name_Template;
                        }

                        if (string.IsNullOrWhiteSpace(name_Destination))
                        {
                            continue;
                        }

                        if (apertureType == ApertureType.Undefined)
                        {
                            continue;
                        }

                        ApertureConstruction apertureConstruction_New = apertureConstructionLibrary_Result.GetApertureConstructions(name_Destination, Core.TextComparisonType.Equals, true, apertureType)?.FirstOrDefault();
                        if (apertureConstruction_New == null)
                        {
                            ApertureConstruction apertureConstruction_Temp = apertureConstructionLibrary.GetApertureConstructions(name_Template, Core.TextComparisonType.Equals, true, apertureType)?.FirstOrDefault();
                            if (apertureConstruction_Temp == null)
                            {
                                continue;
                            }

                            if (name_Destination.Equals(name_Template))
                            {
                                apertureConstruction_New = apertureConstruction_Temp;
                            }
                            else
                            {
                                apertureConstruction_New = new ApertureConstruction(apertureConstruction_Temp, name_Destination);
                            }

                            apertureConstruction_New.SetValue(ApertureConstructionParameter.Description, apertureConstruction.Name);

                            apertureConstructionLibrary_Result.Add(apertureConstruction_New);
                        }

                        FamilySymbol familySymbol = Convert.ToRevit(apertureConstruction_New, document, convertSettings);
                        if (familySymbol == null)
                        {
                            if (string.IsNullOrWhiteSpace(name_Template))
                            {
                                ApertureConstruction apertureConstruction_Default = Analytical.Query.DefaultApertureConstruction(panelType, apertureType);
                                if (apertureConstruction_Default != null)
                                {
                                    name_Template = apertureConstruction_Default.Name;
                                }
                            }

                            if (string.IsNullOrWhiteSpace(name_Template))
                            {
                                continue;
                            }

                            familySymbol = DuplicateByType(document, name_Template, apertureConstruction_New) as FamilySymbol;
                        }

                        Aperture aperture_New = new Aperture(aperture, apertureConstruction_New);
                        if (panel_New.AddAperture(aperture_New))
                        {
                            elementTypes_Apertures.Add(familySymbol);
                            apertures_Result.Add(aperture_New);
                        }
                    }
                }

                elementTypes_Panels.Add(hostObjAttributes);
                panels_Result.Add(panel_New);
            }

            return(true);
        }
Esempio n. 21
0
        /***************************************************/
        /****              Private Methods              ****/
        /***************************************************/

        private static List <oM.Structure.Elements.Panel> StructuralPanelsFromRevit(this HostObject hostObject, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            settings = settings.DefaultIfNull();

            List <oM.Structure.Elements.Panel> result = refObjects.GetValues <oM.Structure.Elements.Panel>(hostObject.Id);

            if (result != null && result.Count > 0)
            {
                return(result);
            }

            HostObjAttributes hostObjAttributes = hostObject.Document.GetElement(hostObject.GetTypeId()) as HostObjAttributes;
            string            materialGrade     = hostObject.MaterialGrade(settings);
            ISurfaceProperty  property2D        = hostObjAttributes?.SurfacePropertyFromRevit(materialGrade, settings, refObjects);

            if (property2D == null)
            {
                BH.Engine.Reflection.Compute.RecordError(String.Format("Conversion of Revit panel's construction to BHoM ISurfaceProperty failed. A panel without property is returned. Revit ElementId : {0}", hostObjAttributes.Id));
            }

            List <ICurve> outlines = hostObject.AnalyticalOutlines(settings);

            if (outlines != null && outlines.Count != 0)
            {
                hostObject.AnalyticalPullWarning();
                result = BHS.Create.Panel(outlines, property2D, null, hostObject.Name);
            }
            else
            {
                Vector translation = new Vector();
                if (property2D is ConstantThickness && (hostObject is Floor || hostObject is RoofBase))
                {
                    translation = -((ConstantThickness)property2D).Thickness * 0.5 * Vector.ZAxis;
                }

                result = new List <oM.Structure.Elements.Panel>();
                Dictionary <PlanarSurface, List <PlanarSurface> > surfaces = hostObject.PanelSurfaces(null, settings);
                if (surfaces != null)
                {
                    foreach (PlanarSurface planarSurface in surfaces.Keys)
                    {
                        List <ICurve> internalBoundaries = new List <ICurve>();
                        if (surfaces[planarSurface] != null)
                        {
                            internalBoundaries.AddRange(surfaces[planarSurface].Select(x => x.ExternalBoundary.ITranslate(translation)));
                        }

                        result.Add(BHS.Create.Panel(planarSurface.ExternalBoundary.ITranslate(translation), internalBoundaries, property2D, null, hostObject.Name));
                    }
                }
            }

            if (result.Count == 0)
            {
                result.Add(new oM.Structure.Elements.Panel {
                    Property = property2D
                });
                BH.Engine.Reflection.Compute.RecordError(String.Format("Conversion of Revit panel's location to BHoM failed. A panel without location is returned. Revit ElementId : {0}", hostObject.Id));
            }

            //Set identifiers, parameters & custom data
            foreach (oM.Structure.Elements.Panel panel in result)
            {
                panel.SetIdentifiers(hostObject);
                panel.CopyParameters(hostObject, settings.ParameterSettings);
                panel.SetProperties(hostObject, settings.ParameterSettings);
            }

            refObjects.AddOrReplace(hostObject.Id, result);
            return(result);
        }
Esempio n. 22
0
        /***************************************************/
        /****               Public Methods              ****/
        /***************************************************/

        public static ISurfaceProperty SurfacePropertyFromRevit(this HostObjAttributes hostObjAttributes, string materialGrade = null, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            Document document = hostObjAttributes.Document;

            settings = settings.DefaultIfNull();

            string            refId      = hostObjAttributes.Id.ReferenceIdentifier(materialGrade);
            ConstantThickness property2D = refObjects.GetValue <ConstantThickness>(refId);

            if (property2D != null)
            {
                return(property2D);
            }

            IMaterialFragment materialFragment = null;
            double            thickness        = 0;

            IList <CompoundStructureLayer> compoundStructure = hostObjAttributes.GetCompoundStructure()?.GetLayers();

            if (compoundStructure != null)
            {
                bool composite           = false;
                bool nonStructuralLayers = false;

                foreach (CompoundStructureLayer csl in compoundStructure)
                {
                    if (csl.Function == MaterialFunctionAssignment.Structure)
                    {
                        if (thickness != 0)
                        {
                            composite = true;
                            thickness = 0;
                            break;
                        }

                        thickness = csl.Width.ToSI(UnitType.UT_Section_Dimension);

                        Material revitMaterial = document.GetElement(csl.MaterialId) as Material;
                        if (revitMaterial == null)
                        {
                            revitMaterial = hostObjAttributes.Category.Material;
                        }

                        materialFragment = revitMaterial.MaterialFragmentFromRevit(materialGrade, settings, refObjects);
                        if (materialFragment == null)
                        {
                            BH.Engine.Reflection.Compute.RecordWarning("There is a structural layer in wall/floor type without material assigned. A default empty material is returned. ElementId: " + hostObjAttributes.Id.IntegerValue.ToString());
                            materialFragment = Autodesk.Revit.DB.Structure.StructuralMaterialType.Undefined.EmptyMaterialFragment(materialGrade);
                        }
                    }
                    else if (csl.Function == MaterialFunctionAssignment.StructuralDeck)
                    {
                        BH.Engine.Reflection.Compute.RecordWarning(String.Format("A structural deck layer has been found in the Revit compound structure, but was ignored on convert. Revit ElementId: {0}", hostObjAttributes.Id));
                    }
                    else
                    {
                        nonStructuralLayers = true;
                    }
                }

                if (nonStructuralLayers)
                {
                    BH.Engine.Reflection.Compute.RecordWarning(String.Format("Layers marked as nonstructural have been found in the Revit compound structure and were ignored on convert. Revit ElementId: {0}", hostObjAttributes.Id));
                }

                if (composite)
                {
                    hostObjAttributes.CompositePanelWarning();
                }
                else if (thickness == 0)
                {
                    BH.Engine.Reflection.Compute.RecordWarning(string.Format("A zero thickness panel is created. Element type Id: {0}", hostObjAttributes.Id.IntegerValue));
                }
            }
            else
            {
                BH.Engine.Reflection.Compute.RecordWarning(String.Format("Revit panel type does not contain any layers (possibly it is a curtain panel). A BHoM panel type with zero thickness and no material is returned. Revit ElementId: {0}", hostObjAttributes.Id));
            }

            oM.Structure.SurfaceProperties.PanelType panelType = oM.Structure.SurfaceProperties.PanelType.Undefined;
            if (hostObjAttributes is WallType)
            {
                panelType = oM.Structure.SurfaceProperties.PanelType.Wall;
            }
            else if (hostObjAttributes is FloorType)
            {
                panelType = oM.Structure.SurfaceProperties.PanelType.Slab;
            }

            property2D = new ConstantThickness {
                PanelType = panelType, Thickness = thickness, Material = materialFragment, Name = hostObjAttributes.Name
            };

            //Set identifiers, parameters & custom data
            property2D.SetIdentifiers(hostObjAttributes);
            property2D.CopyParameters(hostObjAttributes, settings.ParameterSettings);
            property2D.SetProperties(hostObjAttributes, settings.ParameterSettings);

            refObjects.AddOrReplace(refId, property2D);
            return(property2D);
        }
Esempio n. 23
0
        public static HostObjAttributes ToRevit(this Construction construction, Document document, PanelType panelType, Geometry.Spatial.Vector3D normal, Core.Revit.ConvertSettings convertSettings)
        {
            if (construction == null && panelType == PanelType.Air && normal != null)
            {
                construction = Query.DefaultAirConstruction(normal.PanelType().PanelGroup());
            }

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

            HostObjAttributes result = null;

            if (panelType != PanelType.Shade)
            {
                result = convertSettings?.GetObject <HostObjAttributes>(construction.Guid);
            }
            else
            {
                List <HostObjAttributes> hostObjAttributes = convertSettings?.GetObjects <HostObjAttributes>(construction.Guid);
                if (hostObjAttributes != null && hostObjAttributes.Count != 0)
                {
                    if (normal.PanelType().PanelGroup() == PanelGroup.Wall)
                    {
                        result = hostObjAttributes.Find(x => x is Autodesk.Revit.DB.WallType);
                    }
                    else
                    {
                        result = hostObjAttributes.Find(x => !(x is Autodesk.Revit.DB.WallType));
                    }
                }
            }

            if (result != null)
            {
                return(result);
            }

            FilteredElementCollector filteredElementCollector = Query.FilteredElementCollector(document, panelType)?.OfClass(typeof(HostObjAttributes));

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

            if (normal != null)
            {
                if (panelType == PanelType.Air || panelType == PanelType.Shade)
                {
                    BuiltInCategory builtInCategory = normal.BuiltInCategory();
                    if (builtInCategory == BuiltInCategory.OST_Walls)
                    {
                        filteredElementCollector.OfCategory(builtInCategory);
                    }
                }
            }

            //FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document).OfClass(typeof(HostObjAttributes));

            //BuiltInCategory builtInCategory = panelType.BuiltInCategory();
            //if (normal != null && (builtInCategory == BuiltInCategory.INVALID || panelType == PanelType.Shade))
            //    builtInCategory = normal.BuiltInCategory();

            //if (builtInCategory != BuiltInCategory.INVALID)
            //    filteredElementCollector.OfCategory(builtInCategory);


            string familyName_Source = null;
            string typeName_Source   = null;

            if (!Core.Revit.Query.TryGetFamilyNameAndTypeName(construction.Name, out familyName_Source, out typeName_Source))
            {
                return(null);
            }

            foreach (HostObjAttributes hostObjAttributes in filteredElementCollector)
            {
                string fullName = Core.Revit.Query.FullName(hostObjAttributes);

                string familyName = null;
                string typeName   = null;
                if (!Core.Revit.Query.TryGetFamilyNameAndTypeName(fullName, out familyName, out typeName))
                {
                    continue;
                }

                if (fullName != null && fullName.Equals(construction.Name))
                {
                    return(hostObjAttributes);
                }

                if (!string.IsNullOrWhiteSpace(familyName) && !string.IsNullOrWhiteSpace(familyName_Source))
                {
                    continue;
                }

                if (typeName.Equals(typeName_Source))
                {
                    result = hostObjAttributes;
                }
            }

            convertSettings?.Add(construction.Guid, result);

            return(result);
        }
Esempio n. 24
0
        /// <summary>
        /// Collect information about material layer.
        ///   For IFC4RV Architectural exchange, it will generate IfcMatrialConstituentSet along with the relevant IfcShapeAspect and the width in the quantityset
        ///   For IFC4RV Structural exchange, it will generate multiple components as IfcBuildingElementPart for each layer
        ///   For others IfcMaterialLayer will be created
        /// </summary>
        private void CollectMaterialLayerSet()
        {
            ElementId    typeElemId       = m_Element.GetTypeId();
            IFCAnyHandle materialLayerSet = ExporterCacheManager.MaterialSetCache.FindLayerSet(typeElemId);

            // Roofs with no components are only allowed one material.  We will arbitrarily choose the thickest material.
            m_PrimaryMaterialHandle = ExporterCacheManager.MaterialSetCache.FindPrimaryMaterialHnd(typeElemId);

            bool materialHandleIsNotValid = IFCAnyHandleUtil.IsNullOrHasNoValue(materialLayerSet);

            if (IFCAnyHandleUtil.IsNullOrHasNoValue(materialLayerSet) || materialHandleIsNotValid)
            {
                if (materialHandleIsNotValid)
                {
                    UnregisterIFCHandles();
                }
                m_needToGenerateIFCObjects = true;

                List <double> widths = new List <double>();
                List <MaterialFunctionAssignment> functions = new List <MaterialFunctionAssignment>();

                HostObjAttributes hostObjAttr = m_Element.Document.GetElement(typeElemId) as HostObjAttributes;
                if (hostObjAttr == null)
                {
                    // It does not have the HostObjAttribute (where we will get the compound structure for material layer set.
                    // We will define a single material instead and create the material layer set of this single material if there is enough information (At least Material id and thickness)
                    FamilyInstance familyInstance = m_Element as FamilyInstance;
                    if (familyInstance == null)
                    {
                        return;
                    }

                    FamilySymbol            familySymbol = familyInstance.Symbol;
                    ICollection <ElementId> famMatIds    = familySymbol.GetMaterialIds(false);
                    if (famMatIds.Count == 0)
                    {
                        // For some reason Plate type may not return any Material id
                        ElementId baseMatId = CategoryUtil.GetBaseMaterialIdForElement(m_Element);
                        Material  material  = m_Element.Document.GetElement(baseMatId) as Material;
                        if (material == null)
                        {
                            return;
                        }

                        string    layerName    = NamingUtil.GetMaterialLayerName(material);
                        double    matWidth     = 0.0;
                        Parameter thicknessPar = familySymbol.get_Parameter(BuiltInParameter.CURTAIN_WALL_SYSPANEL_THICKNESS);
                        if (thicknessPar != null)
                        {
                            matWidth = thicknessPar.AsDouble();
                        }
                        widths.Add(matWidth);

                        if (baseMatId != ElementId.InvalidElementId)
                        {
                            MaterialIds.Add(new MaterialInfo(baseMatId, layerName, matWidth, MaterialFunctionAssignment.None));
                        }
                        // How to get the thickness? For CurtainWall Panel (PanelType), there is a builtin parameter CURTAINWALL_SYSPANEL_THICKNESS

                        functions.Add(MaterialFunctionAssignment.None);
                    }
                    else
                    {
                        foreach (ElementId matid in famMatIds)
                        {
                            // How to get the thickness? For CurtainWall Panel (PanelType), there is a builtin parameter CURTAINWALL_SYSPANEL_THICKNESS
                            double matWidth = familySymbol.get_Parameter(BuiltInParameter.CURTAIN_WALL_SYSPANEL_THICKNESS)?.AsDouble() ??
                                              ParameterUtil.GetSpecialThicknessParameter(familySymbol);

                            if (MathUtil.IsAlmostZero(matWidth))
                            {
                                continue;
                            }

                            widths.Add(matWidth);
                            ElementId baseMatId = CategoryUtil.GetBaseMaterialIdForElement(m_Element);
                            if (matid != ElementId.InvalidElementId)
                            {
                                Material material = m_Element.Document.GetElement(matid) as Material;
                                if (material != null)
                                {
                                    string layerName = NamingUtil.GetMaterialLayerName(material);
                                    MaterialIds.Add(new MaterialInfo(matid, layerName, matWidth, MaterialFunctionAssignment.None));
                                }
                            }
                            else
                            {
                                MaterialIds.Add(new MaterialInfo(baseMatId, null, matWidth, MaterialFunctionAssignment.None));
                            }

                            functions.Add(MaterialFunctionAssignment.None);
                        }
                    }
                }
                else
                {
                    ElementId         baseMatId = CategoryUtil.GetBaseMaterialIdForElement(m_Element);
                    CompoundStructure cs        = hostObjAttr.GetCompoundStructure();

                    if (cs != null)
                    {
                        double scaledOffset = 0.0, scaledWallWidth = 0.0, wallHeight = 0.0;
                        Wall   wall = m_Element as Wall;
                        if (wall != null)
                        {
                            scaledWallWidth = UnitUtil.ScaleLength(wall.Width);
                            scaledOffset    = -scaledWallWidth / 2.0;
                            BoundingBoxXYZ boundingBox = wall.get_BoundingBox(null);
                            if (boundingBox != null)
                            {
                                wallHeight = boundingBox.Max.Z - boundingBox.Min.Z;
                            }
                        }

                        //TODO: Vertically compound structures are not yet supported by export.
                        if (!cs.IsVerticallyHomogeneous() && !MathUtil.IsAlmostZero(wallHeight))
                        {
                            cs = cs.GetSimpleCompoundStructure(wallHeight, wallHeight / 2.0);
                        }

                        for (int ii = 0; ii < cs.LayerCount; ++ii)
                        {
                            double matWidth = cs.GetLayerWidth(ii);

                            ElementId matId = cs.GetMaterialId(ii);
                            widths.Add(matWidth);
                            // save layer function into ProductWrapper,
                            // it's used while exporting "Function" of Pset_CoveringCommon
                            functions.Add(cs.GetLayerFunction(ii));

                            if (matId != ElementId.InvalidElementId)
                            {
                                Material material = m_Element.Document.GetElement(matId) as Material;
                                if (material != null)
                                {
                                    string layerName = NamingUtil.GetMaterialLayerName(material);
                                    MaterialIds.Add(new MaterialInfo(matId, layerName, matWidth, functions.Last()));
                                }
                            }
                            else
                            {
                                MaterialIds.Add(new MaterialInfo(baseMatId, null, matWidth, functions.Last()));
                            }
                        }
                    }

                    if (MaterialIds.Count == 0)
                    {
                        double matWidth = cs?.GetWidth() ?? 0.0;
                        widths.Add(matWidth);
                        if (baseMatId != ElementId.InvalidElementId)
                        {
                            Material material = m_Element.Document.GetElement(baseMatId) as Material;
                            if (material != null)
                            {
                                string layerName = NamingUtil.GetMaterialLayerName(material);
                                MaterialIds.Add(new MaterialInfo(baseMatId, layerName, matWidth, MaterialFunctionAssignment.None));
                            }
                        }
                        functions.Add(MaterialFunctionAssignment.None);
                    }
                }
            }
            else
            {
                m_needToGenerateIFCObjects = false;

                m_MaterialLayerSetHandle = materialLayerSet;

                MaterialLayerSetInfo mlsInfo = ExporterCacheManager.MaterialSetCache.FindMaterialLayerSetInfo(typeElemId);
                if (mlsInfo != null)
                {
                    MaterialIds             = mlsInfo.MaterialIds;
                    m_PrimaryMaterialHandle = mlsInfo.PrimaryMaterialHandle;
                    m_LayerQuantityWidthHnd = mlsInfo.LayerQuantityWidthHnd;
                }
            }

            return;
        }
Esempio n. 25
0
        public static List <Aperture> ToSAM_Apertures(this FamilyInstance familyInstance, ConvertSettings convertSettings)
        {
            if (familyInstance == null)
            {
                return(null);
            }

            List <Aperture> result = convertSettings?.GetObjects <Aperture>(familyInstance.Id);

            if (result != null)
            {
                return(result);
            }

            if (Core.Revit.Query.Simplified(familyInstance))
            {
                result = Core.Revit.Query.IJSAMObjects <Aperture>(familyInstance);
                if (result != null)
                {
                    convertSettings?.Add(familyInstance.Id, result);
                    return(result);
                }
            }

            Point3D point3D_Location = Geometry.Revit.Query.LocationPoint3D(familyInstance);

            if (point3D_Location == null)
            {
                List <Solid> solids = Core.Revit.Query.Solids(familyInstance, new Options());
                solids?.RemoveAll(x => x.Volume == 0);
                if (solids == null || solids.Count == 0)
                {
                    return(null);
                }

                if (solids.Count > 1)
                {
                    solids.Sort((x, y) => y.Volume.CompareTo(x.Volume));
                }

                point3D_Location = solids[0].ComputeCentroid()?.ToSAM();
            }

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

            List <Face3D> face3Ds = null;


            PanelType       panelType_Host       = PanelType.Undefined;
            BuiltInCategory builtInCategory_Host = BuiltInCategory.INVALID;
            HostObject      hostObject           = null;

            if (familyInstance.Host != null)
            {
                hostObject = familyInstance.Host as HostObject;

                if (hostObject != null)
                {
                    builtInCategory_Host = (BuiltInCategory)hostObject.Category.Id.IntegerValue;
                }
            }

            //Method 1 of extracting Geometry
            if (face3Ds == null || face3Ds.Count == 0)
            {
                Vector3D axisX  = null;
                Vector3D normal = null;
                Vector3D axisY  = null;
                if (builtInCategory_Host == BuiltInCategory.OST_Roofs)
                {
                    axisX  = familyInstance.HandOrientation.ToSAM_Vector3D(false);
                    axisY  = familyInstance.FacingOrientation.ToSAM_Vector3D(false);
                    normal = Geometry.Spatial.Query.AxisY(axisY, axisX);
                }
                else
                {
                    axisX  = familyInstance.HandOrientation.ToSAM_Vector3D(false);
                    normal = familyInstance.FacingOrientation.ToSAM_Vector3D(false);
                    axisY  = Geometry.Spatial.Query.AxisY(normal, axisX);
                }

                Geometry.Spatial.Plane plane = Geometry.Spatial.Create.Plane(point3D_Location, axisX, axisY);
                if (!plane.Normal.SameHalf(normal))
                {
                    plane.FlipZ(false);
                }

                List <Shell> shells = Geometry.Revit.Convert.ToSAM_Geometries <Shell>(familyInstance);
                if (shells == null || shells.Count == 0)
                {
                    return(null);
                }

                List <Point2D> point2Ds = new List <Point2D>();
                foreach (Shell shell in shells)
                {
                    List <Face3D> face3Ds_Shell = shell?.Face3Ds;
                    if (face3Ds_Shell == null || face3Ds_Shell.Count == 0)
                    {
                        continue;
                    }

                    foreach (Face3D face3D_Temp in face3Ds_Shell)
                    {
                        ISegmentable3D segmentable3D = face3D_Temp.GetExternalEdge3D() as ISegmentable3D;
                        if (segmentable3D == null)
                        {
                            continue;
                        }

                        segmentable3D?.GetPoints()?.ForEach(x => point2Ds.Add(plane.Convert(x)));
                    }
                }

                Face3D face3D = new Face3D(plane, Geometry.Planar.Create.Rectangle2D(point2Ds));
                if (face3D != null && face3D.IsValid() && face3D.GetArea() > Core.Tolerance.MacroDistance)
                {
                    face3Ds = new List <Face3D>()
                    {
                        face3D
                    };
                }
            }

            //Method 2 of extracting Geometry
            if (hostObject != null)
            {
                builtInCategory_Host = (BuiltInCategory)hostObject.Category.Id.IntegerValue;

                Geometry.Spatial.Plane plane_Host = null;
                if (hostObject is CurtainSystem && familyInstance is Autodesk.Revit.DB.Panel)
                {
                    Autodesk.Revit.DB.Panel panel = (Autodesk.Revit.DB.Panel)familyInstance;
                    ElementId uGridLineElementId  = null;
                    ElementId vGridLineElementId  = null;

                    panel.GetRefGridLines(ref uGridLineElementId, ref vGridLineElementId);

                    CurtainSystem curtainSystem = (CurtainSystem)hostObject;

                    List <Polygon3D> polygon3Ds = curtainSystem.CurtainCell(uGridLineElementId, vGridLineElementId)?.Polygon3Ds();
                    if (polygon3Ds != null && polygon3Ds.Count != 0)
                    {
                        polygon3Ds.Sort((x, y) => y.GetArea().CompareTo(x.GetArea()));
                        plane_Host = polygon3Ds[0].GetPlane();
                    }
                }
                else
                {
                    List <Face3D> face3Ds_Temp = hostObject.Profiles();
                    if (face3Ds_Temp != null && face3Ds_Temp.Count != 0)
                    {
                        plane_Host = face3Ds_Temp.Closest(point3D_Location)?.GetPlane();
                    }
                }

                if (plane_Host != null)
                {
                    face3Ds          = face3Ds?.ConvertAll(x => plane_Host.Project(x));
                    point3D_Location = plane_Host.Project(point3D_Location);
                }


                HostObjAttributes hostObjAttributes = familyInstance.Document.GetElement(hostObject.GetTypeId()) as HostObjAttributes;
                if (hostObjAttributes != null)
                {
                    panelType_Host = hostObjAttributes.PanelType();
                }

                if (panelType_Host == PanelType.Undefined)
                {
                    panelType_Host = hostObject.PanelType();
                }

                List <Face3D> face3Ds_Profiles = hostObject.Profiles(familyInstance.Id);
                face3Ds_Profiles?.RemoveAll(x => x == null || !x.IsValid());
                if (face3Ds_Profiles != null && face3Ds_Profiles.Count > 0)
                {
                    if (face3Ds == null || (face3Ds != null && face3Ds_Profiles.ConvertAll(x => x.GetArea()).Sum() <= face3Ds.ConvertAll(x => x.GetArea()).Sum()))
                    {
                        face3Ds = face3Ds_Profiles;
                    }
                }
            }

            ApertureConstruction apertureConstruction = ToSAM_ApertureConstruction(familyInstance, convertSettings);

            if (apertureConstruction == null && panelType_Host != PanelType.Undefined)
            {
                apertureConstruction = Analytical.Query.DefaultApertureConstruction(panelType_Host, familyInstance.ApertureType()); //Default Aperture Construction
            }
            if (face3Ds == null || face3Ds.Count == 0)
            {
                return(result);
            }

            //TODO: Working on SAM Families (requested by Michal)

            string parameterName_Height = Core.Revit.Query.Name(ActiveSetting.Setting, typeof(Aperture), typeof(FamilyInstance), "GetHeight");
            string parameterName_Width  = Core.Revit.Query.Name(ActiveSetting.Setting, typeof(Aperture), typeof(FamilyInstance), "GetWidth");

            if (!string.IsNullOrWhiteSpace(parameterName_Height) && !string.IsNullOrWhiteSpace(parameterName_Width))
            {
                Parameter parameter_Height = familyInstance.LookupParameter(parameterName_Height);
                Parameter parameter_Width  = familyInstance.LookupParameter(parameterName_Width);
                if (parameter_Height != null && parameter_Width != null && parameter_Height.HasValue && parameter_Width.HasValue && parameter_Height.StorageType == StorageType.Double && parameter_Width.StorageType == StorageType.Double)
                {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                    double height = UnitUtils.ConvertFromInternalUnits(parameter_Height.AsDouble(), DisplayUnitType.DUT_METERS);
                    double width  = UnitUtils.ConvertFromInternalUnits(parameter_Width.AsDouble(), DisplayUnitType.DUT_METERS);
#else
                    double height = UnitUtils.ConvertFromInternalUnits(parameter_Height.AsDouble(), UnitTypeId.Meters);
                    double width  = UnitUtils.ConvertFromInternalUnits(parameter_Width.AsDouble(), UnitTypeId.Meters);
#endif
                }
            }

            result = new List <Aperture>();
            foreach (Face3D face3D_Temp in face3Ds)
            {
                Aperture aperture = Analytical.Create.Aperture(apertureConstruction, face3D_Temp);
                if (aperture == null)
                {
                    continue;
                }

                aperture.UpdateParameterSets(familyInstance, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));
                result.Add(aperture);
            }

            convertSettings?.Add(familyInstance.Id, result);

            return(result);
        }
Esempio n. 26
0
        private void Stream(ArrayList data, HostObjAttributes hostAtt)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(HostObjAttributes)));

             data.Add(new Snoop.Data.Object("Compound Structure", hostAtt.GetCompoundStructure()));

             ContFootingType contFootingType = hostAtt as ContFootingType;
             if (contFootingType != null)
             {
            Stream(data, contFootingType);
            return;
             }

             CurtainSystemType curSysType = hostAtt as CurtainSystemType;
             if (curSysType != null)
             {
            Stream(data, curSysType);
            return;
             }

             FloorType floorType = hostAtt as FloorType;
             if (floorType != null)
             {
            Stream(data, floorType);
            return;
             }

             HostedSweepType hostSweepType = hostAtt as HostedSweepType;
             if (hostSweepType != null)
             {
            Stream(data, hostSweepType);
            return;
             }

             RoofType roofType = hostAtt as RoofType;
             if (roofType != null)
             {
            Stream(data, roofType);
            return;
             }

             WallType wallType = hostAtt as WallType;
             if (wallType != null)
             {
            Stream(data, wallType);
            return;
             }
        }
Esempio n. 27
0
        /***************************************************/
        /****               Public Methods              ****/
        /***************************************************/

        public static oM.Physical.Elements.Floor FloorFromRevit(this Floor floor, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            if (floor == null)
            {
                return(null);
            }

            settings = settings.DefaultIfNull();

            oM.Physical.Elements.Floor bHoMFloor = refObjects.GetValue <oM.Physical.Elements.Floor>(floor.Id);
            if (bHoMFloor != null)
            {
                return(bHoMFloor);
            }

            HostObjAttributes hostObjAttributes = floor.Document.GetElement(floor.GetTypeId()) as HostObjAttributes;
            string            materialGrade     = floor.MaterialGrade(settings);

            oM.Physical.Constructions.Construction construction = hostObjAttributes.ConstructionFromRevit(materialGrade, settings, refObjects);

            ISurface location = null;
            List <BH.oM.Physical.Elements.IOpening> openings = new List <oM.Physical.Elements.IOpening>();

            Dictionary <PlanarSurface, List <PlanarSurface> > surfaces = null;
            BoundingBoxXYZ bbox = floor.get_BoundingBox(null);

            if (bbox != null)
            {
                BoundingBoxIntersectsFilter bbif      = new BoundingBoxIntersectsFilter(new Outline(bbox.Min, bbox.Max));
                IList <ElementId>           insertIds = (floor as HostObject).FindInserts(true, true, true, true);
                List <Element> inserts;
                if (insertIds.Count == 0)
                {
                    inserts = new List <Element>();
                }
                else
                {
                    inserts = new FilteredElementCollector(floor.Document, insertIds).WherePasses(bbif).ToList();
                }

                List <FamilyInstance> windows = inserts.Where(x => x is FamilyInstance && x.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Windows).Cast <FamilyInstance>().ToList();
                List <FamilyInstance> doors   = inserts.Where(x => x is FamilyInstance && x.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Doors).Cast <FamilyInstance>().ToList();

                surfaces = floor.PanelSurfaces(windows.Union(doors).Select(x => x.Id), settings);
                if (surfaces != null)
                {
                    List <ISurface> locations = new List <ISurface>(surfaces.Keys);
                    if (locations.Count == 1)
                    {
                        location = locations[0];
                    }
                    else
                    {
                        location = new PolySurface {
                            Surfaces = locations
                        }
                    };

                    foreach (List <PlanarSurface> ps in surfaces.Values)
                    {
                        openings.AddRange(ps.Select(x => new BH.oM.Physical.Elements.Void {
                            Location = x
                        }));
                    }

                    foreach (FamilyInstance window in windows)
                    {
                        BH.oM.Physical.Elements.Window bHoMWindow = window.WindowFromRevit(floor, settings, refObjects);
                        if (bHoMWindow != null)
                        {
                            openings.Add(bHoMWindow);
                        }
                    }

                    foreach (FamilyInstance door in doors)
                    {
                        BH.oM.Physical.Elements.Door bHoMDoor = door.DoorFromRevit(floor, settings, refObjects);
                        if (bHoMDoor != null)
                        {
                            openings.Add(bHoMDoor);
                        }
                    }
                }
            }

            if (surfaces == null || surfaces.Count == 0)
            {
                floor.NoPanelLocationError();
            }

            bHoMFloor = new oM.Physical.Elements.Floor {
                Location = location, Openings = openings, Construction = construction
            };
            bHoMFloor.Name = floor.FamilyTypeFullName();

            //Set identifiers, parameters & custom data
            bHoMFloor.SetIdentifiers(floor);
            bHoMFloor.CopyParameters(floor, settings.ParameterSettings);
            bHoMFloor.SetProperties(floor, settings.ParameterSettings);

            refObjects.AddOrReplace(floor.Id, bHoMFloor);
            return(bHoMFloor);
        }

        /***************************************************/
    }
Esempio n. 28
0
        public static Construction ToSAM(this HostObjAttributes hostObjAttributes, ConvertSettings convertSettings)
        {
            if (hostObjAttributes == null)
            {
                return(null);
            }

            Construction result = convertSettings?.GetObject <Construction>(hostObjAttributes.Id);

            if (result != null)
            {
                return(result);
            }

            string    name      = hostObjAttributes.Name;
            PanelType panelType = hostObjAttributes.PanelType();

            if (panelType == PanelType.Undefined)
            {
                panelType = Query.PanelType((BuiltInCategory)hostObjAttributes.Category.Id.IntegerValue);
            }

            Construction construction = Analytical.Query.DefaultConstruction(panelType);

            if (construction != null && (name.Equals(construction.Name) || name.Equals(construction.UniqueName())))
            {
                result = new Construction(construction);
            }
            else
            {
                result = new Construction(hostObjAttributes.Name);
            }


            result.UpdateParameterSets(hostObjAttributes, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));

            //result.Add(Core.Revit.Query.ParameterSet(hostObjAttributes));

            convertSettings?.Add(hostObjAttributes.Id, result);

            if (panelType != PanelType.Undefined)
            {
                result.SetValue(ConstructionParameter.DefaultPanelType, panelType.Text());
            }
            else
            {
                result.SetValue(ConstructionParameter.DefaultPanelType, null);
            }

            List <ConstructionLayer> constructionLayers = result.ConstructionLayers;

            if (constructionLayers != null && constructionLayers.Count != 0)
            {
                result.SetValue(ConstructionParameter.DefaultThickness, constructionLayers.ConvertAll(x => x.Thickness).Sum());
            }
            else
            {
                CompoundStructure compoundStructure = hostObjAttributes.GetCompoundStructure();
                if (compoundStructure != null)
                {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                    double thickness = UnitUtils.ConvertFromInternalUnits(compoundStructure.GetWidth(), DisplayUnitType.DUT_METERS);
#else
                    double thickness = UnitUtils.ConvertFromInternalUnits(compoundStructure.GetWidth(), UnitTypeId.Meters);
#endif
                    result.SetValue(ConstructionParameter.DefaultThickness, thickness);
                }
            }


            return(result);
        }
Esempio n. 29
0
        public static HostObjAttributes ToRevit(this HostPartitionType hostPartitionType, Document document, Core.Revit.ConvertSettings convertSettings)
        {
            if (hostPartitionType == null)
            {
                return(null);
            }

            HostObjAttributes result = null;

            List <HostObjAttributes> hostObjAttributesList = convertSettings?.GetObjects <HostObjAttributes>(hostPartitionType.Guid);

            if (hostObjAttributesList != null)
            {
                if (hostPartitionType is WallType)
                {
                    result = hostObjAttributesList.Find(x => x is Autodesk.Revit.DB.WallType);
                }
                else if (hostPartitionType is FloorType)
                {
                    result = hostObjAttributesList.Find(x => x is Autodesk.Revit.DB.FloorType);
                }
                else if (hostPartitionType is RoofType)
                {
                    result = hostObjAttributesList.Find(x => x is Autodesk.Revit.DB.RoofType);
                }
            }

            if (result != null)
            {
                return(result);
            }

            FilteredElementCollector filteredElementCollector = Query.FilteredElementCollector_New(document, hostPartitionType.GetType())?.OfClass(typeof(HostObjAttributes));

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

            string familyName_Source = null;
            string typeName_Source   = null;

            if (!Core.Revit.Query.TryGetFamilyNameAndTypeName(hostPartitionType.Name, out familyName_Source, out typeName_Source))
            {
                return(null);
            }

            foreach (HostObjAttributes hostObjAttributes in filteredElementCollector)
            {
                string fullName = Core.Revit.Query.FullName(hostObjAttributes);

                string familyName = null;
                string typeName   = null;
                if (!Core.Revit.Query.TryGetFamilyNameAndTypeName(fullName, out familyName, out typeName))
                {
                    continue;
                }

                if (fullName != null && fullName.Equals(hostPartitionType.Name))
                {
                    result = hostObjAttributes;
                    break;
                }

                if (!string.IsNullOrWhiteSpace(familyName) && !string.IsNullOrWhiteSpace(familyName_Source))
                {
                    continue;
                }


                if (typeName.Equals(typeName_Source))
                {
                    result = hostObjAttributes;
                }
            }

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

            List <Architectural.MaterialLayer> materialLayers = hostPartitionType.MaterialLayers;

            if (materialLayers != null && materialLayers.Count != 0)
            {
                CompoundStructure compoundStructure = result.GetCompoundStructure();
                if (compoundStructure != null)
                {
                    List <Material> materials = new FilteredElementCollector(document).OfClass(typeof(Material)).Cast <Material>().ToList();

                    List <CompoundStructureLayer> compoundStructureLayers = new List <CompoundStructureLayer>();
                    foreach (Architectural.MaterialLayer materialLayer in materialLayers)
                    {
                        Material material = materials.Find(x => x.Name == materialLayer.Name);
                        if (material == null)
                        {
                            continue;
                        }

                        double width = double.NaN;

#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                        width = UnitUtils.ConvertToInternalUnits(materialLayer.Thickness, DisplayUnitType.DUT_METERS);
#else
                        width = UnitUtils.ConvertToInternalUnits(materialLayer.Thickness, UnitTypeId.Meters);
#endif



                        CompoundStructureLayer compoundStructureLayer = new CompoundStructureLayer(width, MaterialFunctionAssignment.Structure, material.Id);
                        if (compoundStructureLayer == null)
                        {
                            continue;
                        }

                        compoundStructureLayers.Add(compoundStructureLayer);
                    }

                    if (compoundStructureLayers != null && compoundStructureLayers.Count != 0)
                    {
                        compoundStructure.SetLayers(compoundStructureLayers);
                        result.SetCompoundStructure(compoundStructure);
                    }
                }
            }

            if (convertSettings.ConvertParameters)
            {
                Core.Revit.Modify.SetValues(result, hostPartitionType);
                Core.Revit.Modify.SetValues(result, hostPartitionType, ActiveSetting.Setting);
            }

            convertSettings?.Add(hostPartitionType.Guid, result);

            return(result);
        }
Esempio n. 30
0
        /// <summary>
        /// Exports materials for host object.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="hostObject">The host object.</param>
        /// <param name="elemHnds">The host IFC handles.</param>
        /// <param name="geometryElement">The geometry element.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        /// <param name="levelId">The level id.</param>
        /// <param name="direction">The IFCLayerSetDirection.</param>
        /// <param name="containsBRepGeometry">True if the geometry contains BRep geoemtry.  If so, we will export an IfcMaterialList</param>
        /// <returns>True if exported successfully, false otherwise.</returns>
        public static bool ExportHostObjectMaterials(ExporterIFC exporterIFC, HostObject hostObject,
                                                     IList <IFCAnyHandle> elemHnds, GeometryElement geometryElement, ProductWrapper productWrapper,
                                                     ElementId levelId, Toolkit.IFCLayerSetDirection direction, bool containsBRepGeometry)
        {
            if (hostObject == null)
            {
                return(true); //nothing to do
            }
            if (elemHnds == null || (elemHnds.Count == 0))
            {
                return(true); //nothing to do
            }
            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                if (productWrapper != null)
                {
                    productWrapper.ClearFinishMaterials();
                }

                double scaledOffset = 0.0, scaledWallWidth = 0.0, wallHeight = 0.0;
                Wall   wall = hostObject as Wall;
                if (wall != null)
                {
                    scaledWallWidth = UnitUtil.ScaleLength(wall.Width);
                    scaledOffset    = -scaledWallWidth / 2.0;
                    BoundingBoxXYZ boundingBox = wall.get_BoundingBox(null);
                    if (boundingBox != null)
                    {
                        wallHeight = boundingBox.Max.Z - boundingBox.Min.Z;
                    }
                }

                ElementId    typeElemId       = hostObject.GetTypeId();
                IFCAnyHandle materialLayerSet = ExporterCacheManager.MaterialLayerSetCache.Find(typeElemId);
                // Roofs with no components are only allowed one material.  We will arbitrarily choose the thickest material.
                IFCAnyHandle primaryMaterialHnd = ExporterCacheManager.MaterialLayerSetCache.FindPrimaryMaterialHnd(typeElemId);
                if (IFCAnyHandleUtil.IsNullOrHasNoValue(materialLayerSet))
                {
                    HostObjAttributes hostObjAttr = hostObject.Document.GetElement(typeElemId) as HostObjAttributes;
                    if (hostObjAttr == null)
                    {
                        return(true); //nothing to do
                    }
                    List <ElementId> matIds = new List <ElementId>();
                    List <double>    widths = new List <double>();
                    List <MaterialFunctionAssignment> functions = new List <MaterialFunctionAssignment>();
                    ElementId         baseMatId = CategoryUtil.GetBaseMaterialIdForElement(hostObject);
                    CompoundStructure cs        = hostObjAttr.GetCompoundStructure();
                    if (cs != null)
                    {
                        //TODO: Vertically compound structures are not yet supported by export.
                        if (!cs.IsVerticallyHomogeneous() && !MathUtil.IsAlmostZero(wallHeight))
                        {
                            cs = cs.GetSimpleCompoundStructure(wallHeight, wallHeight / 2.0);
                        }

                        for (int i = 0; i < cs.LayerCount; ++i)
                        {
                            ElementId matId = cs.GetMaterialId(i);
                            if (matId != ElementId.InvalidElementId)
                            {
                                matIds.Add(matId);
                            }
                            else
                            {
                                matIds.Add(baseMatId);
                            }
                            widths.Add(cs.GetLayerWidth(i));
                            // save layer function into ProductWrapper,
                            // it's used while exporting "Function" of Pset_CoveringCommon
                            functions.Add(cs.GetLayerFunction(i));
                        }
                    }

                    if (matIds.Count == 0)
                    {
                        matIds.Add(baseMatId);
                        widths.Add(cs != null ? cs.GetWidth() : 0);
                        functions.Add(MaterialFunctionAssignment.None);
                    }

                    // We can't create IfcMaterialLayers without creating an IfcMaterialLayerSet.  So we will simply collate here.
                    IList <IFCAnyHandle> materialHnds = new List <IFCAnyHandle>();
                    IList <int>          widthIndices = new List <int>();
                    double thickestLayer = 0.0;
                    for (int ii = 0; ii < matIds.Count; ++ii)
                    {
                        // Require positive width for IFC2x3 and before, and non-negative width for IFC4.
                        if (widths[ii] < -MathUtil.Eps())
                        {
                            continue;
                        }

                        bool almostZeroWidth = MathUtil.IsAlmostZero(widths[ii]);
                        if (ExporterCacheManager.ExportOptionsCache.FileVersion != IFCVersion.IFC4 && almostZeroWidth)
                        {
                            continue;
                        }

                        if (almostZeroWidth)
                        {
                            widths[ii] = 0.0;
                        }

                        IFCAnyHandle materialHnd = CategoryUtil.GetOrCreateMaterialHandle(exporterIFC, matIds[ii]);
                        if (primaryMaterialHnd == null || (widths[ii] > thickestLayer))
                        {
                            primaryMaterialHnd = materialHnd;
                            thickestLayer      = widths[ii];
                        }

                        widthIndices.Add(ii);
                        materialHnds.Add(materialHnd);

                        if ((productWrapper != null) && (functions[ii] == MaterialFunctionAssignment.Finish1 || functions[ii] == MaterialFunctionAssignment.Finish2))
                        {
                            productWrapper.AddFinishMaterial(materialHnd);
                        }
                    }

                    int numLayersToCreate = widthIndices.Count;
                    if (numLayersToCreate == 0)
                    {
                        return(false);
                    }

                    if (!containsBRepGeometry)
                    {
                        IList <IFCAnyHandle> layers = new List <IFCAnyHandle>(numLayersToCreate);

                        for (int ii = 0; ii < numLayersToCreate; ii++)
                        {
                            int          widthIndex    = widthIndices[ii];
                            double       scaledWidth   = UnitUtil.ScaleLength(widths[widthIndex]);
                            IFCAnyHandle materialLayer = IFCInstanceExporter.CreateMaterialLayer(file, materialHnds[ii], scaledWidth, null);
                            layers.Add(materialLayer);
                        }

                        string layerSetName = exporterIFC.GetFamilyName();
                        materialLayerSet = IFCInstanceExporter.CreateMaterialLayerSet(file, layers, layerSetName);

                        ExporterCacheManager.MaterialLayerSetCache.Register(typeElemId, materialLayerSet);
                        ExporterCacheManager.MaterialLayerSetCache.RegisterPrimaryMaterialHnd(typeElemId, primaryMaterialHnd);
                    }
                    else
                    {
                        foreach (IFCAnyHandle elemHnd in elemHnds)
                        {
                            CategoryUtil.CreateMaterialAssociations(exporterIFC, elemHnd, matIds);
                        }
                    }
                }

                // IfcMaterialLayerSetUsage is not supported for IfcWall, only IfcWallStandardCase.
                IFCAnyHandle layerSetUsage = null;
                for (int ii = 0; ii < elemHnds.Count; ii++)
                {
                    IFCAnyHandle elemHnd = elemHnds[ii];
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(elemHnd))
                    {
                        continue;
                    }

                    SpaceBoundingElementUtil.RegisterSpaceBoundingElementHandle(exporterIFC, elemHnd, hostObject.Id, levelId);
                    if (containsBRepGeometry)
                    {
                        continue;
                    }

                    HashSet <IFCAnyHandle> relDecomposesSet = IFCAnyHandleUtil.GetRelDecomposes(elemHnd);

                    IList <IFCAnyHandle> subElemHnds = null;
                    if (relDecomposesSet != null && relDecomposesSet.Count == 1)
                    {
                        IFCAnyHandle relAggregates = relDecomposesSet.First();
                        if (IFCAnyHandleUtil.IsTypeOf(relAggregates, IFCEntityType.IfcRelAggregates))
                        {
                            subElemHnds = IFCAnyHandleUtil.GetAggregateInstanceAttribute <List <IFCAnyHandle> >(relAggregates, "RelatedObjects");
                        }
                    }

                    bool hasSubElems = (subElemHnds != null && subElemHnds.Count != 0);
                    bool isRoof      = IFCAnyHandleUtil.IsTypeOf(elemHnd, IFCEntityType.IfcRoof);
                    if (!hasSubElems && !isRoof && !IFCAnyHandleUtil.IsTypeOf(elemHnd, IFCEntityType.IfcWall))
                    {
                        if (layerSetUsage == null)
                        {
                            bool flipDirSense = true;
                            if (wall != null)
                            {
                                // if we have flipped the center curve on export, we need to take that into account here.
                                // We flip the center curve on export if it is an arc and it has a negative Z direction.
                                LocationCurve locCurve = wall.Location as LocationCurve;
                                if (locCurve != null)
                                {
                                    Curve curve        = locCurve.Curve;
                                    Plane defPlane     = new Plane(XYZ.BasisX, XYZ.BasisY, XYZ.Zero);
                                    bool  curveFlipped = GeometryUtil.MustFlipCurve(defPlane, curve);
                                    flipDirSense = !(wall.Flipped ^ curveFlipped);
                                }
                            }
                            else if (hostObject is Floor)
                            {
                                flipDirSense = false;
                            }

                            double            offsetFromReferenceLine = flipDirSense ? -scaledOffset : scaledOffset;
                            IFCDirectionSense sense = flipDirSense ? IFCDirectionSense.Negative : IFCDirectionSense.Positive;

                            layerSetUsage = IFCInstanceExporter.CreateMaterialLayerSetUsage(file, materialLayerSet, direction, sense, offsetFromReferenceLine);
                        }
                        ExporterCacheManager.MaterialLayerRelationsCache.Add(layerSetUsage, elemHnd);
                    }
                    else
                    {
                        if (hasSubElems)
                        {
                            foreach (IFCAnyHandle subElemHnd in subElemHnds)
                            {
                                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(subElemHnd))
                                {
                                    ExporterCacheManager.MaterialLayerRelationsCache.Add(materialLayerSet, subElemHnd);
                                }
                            }
                        }
                        else if (!isRoof)
                        {
                            ExporterCacheManager.MaterialLayerRelationsCache.Add(materialLayerSet, elemHnd);
                        }
                        else if (primaryMaterialHnd != null)
                        {
                            ExporterCacheManager.MaterialLayerRelationsCache.Add(primaryMaterialHnd, elemHnd);
                        }
                    }
                }

                tr.Commit();
                return(true);
            }
        }
Esempio n. 31
0
        protected override void TrySolveInstance(IGH_DataAccess dataAccess)
        {
            int index = -1;

            Document document = RhinoInside.Revit.Revit.ActiveDBDocument;

            if (document == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            Core.SAMObject sAMObject = null;
            index = Params.IndexOfInputParam("_analytical");
            if (index == -1 || !dataAccess.GetData(index, ref sAMObject))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            List <Panel> panels = null;

            if (sAMObject is Panel)
            {
                panels = new List <Panel>()
                {
                    (Panel)sAMObject
                };
            }
            else if (sAMObject is AdjacencyCluster)
            {
                panels = ((AdjacencyCluster)sAMObject).GetPanels();
            }
            else if (sAMObject is AnalyticalModel)
            {
                panels = ((AnalyticalModel)sAMObject).GetPanels();
            }

            if (panels == null || panels.Count == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            StartTransaction(document);

            List <ElementType> elementTypes = new List <ElementType>();

            for (int i = 0; i < panels.Count; i++)
            {
                Panel panel = panels[i];
                if (panel == null)
                {
                    continue;
                }

                Geometry.Spatial.Vector3D normal = panel.Normal;
                PanelType panelType = panel.PanelType;

                if (panelType == PanelType.Air || panelType == PanelType.Undefined)
                {
                    panels[i] = Create.Panel(panel);
                    ElementType elementType = Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false));
                    if (elementType != null && elementTypes.Find(x => x.Id == elementType.Id) == null)
                    {
                        elementTypes.Add(elementType);
                    }

                    continue;
                }

                PanelType panelType_Normal = Analytical.Revit.Query.PanelType(normal);
                if (panelType_Normal == PanelType.Undefined || panelType.PanelGroup() == panelType_Normal.PanelGroup())
                {
                    panels[i] = Create.Panel(panel);
                    ElementType elementType = Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false));
                    if (elementType != null && elementTypes.Find(x => x.Id == elementType.Id) == null)
                    {
                        elementTypes.Add(elementType);
                    }

                    continue;
                }

                if (panelType.PanelGroup() == PanelGroup.Floor || panelType.PanelGroup() == PanelGroup.Roof)
                {
                    double value = normal.Unit.DotProduct(Geometry.Spatial.Vector3D.WorldY);
                    if (Math.Abs(value) <= Core.Revit.Tolerance.Tilt)
                    {
                        panels[i] = Create.Panel(panel);
                        ElementType elementType = Analytical.Revit.Convert.ToRevit_HostObjAttributes(panel, document, new Core.Revit.ConvertSettings(false, true, false));
                        if (elementType != null && elementTypes.Find(x => x.Id == elementType.Id) == null)
                        {
                            elementTypes.Add(elementType);
                        }

                        continue;
                    }
                }

                HostObjAttributes hostObjAttributes = Analytical.Revit.Modify.DuplicateByType(document, panelType_Normal, panel.Construction) as HostObjAttributes;
                if (hostObjAttributes == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, string.Format("Skipped - Could not duplicate construction for {0} panel (Guid: {1}).", panel.Name, panel.Guid));
                    continue;
                }

                panels[i] = Create.Panel(panel, panelType_Normal);

                if (elementTypes.Find(x => x.Id == hostObjAttributes.Id) == null)
                {
                    elementTypes.Add(hostObjAttributes);
                }
            }


            int index_Analytical = Params.IndexOfOutputParam("analytical");

            if (index_Analytical != -1)
            {
                if (sAMObject is Panel)
                {
                    dataAccess.SetData(index_Analytical, panels?.FirstOrDefault());
                }
                else if (sAMObject is AnalyticalModel)
                {
                    AnalyticalModel analyticalModel = new AnalyticalModel((AnalyticalModel)sAMObject);
                    panels.ForEach(x => analyticalModel.AddPanel(x));
                    dataAccess.SetData(index_Analytical, analyticalModel);
                }
                else if (sAMObject is AdjacencyCluster)
                {
                    AdjacencyCluster adjacencyCluster = new AdjacencyCluster((AdjacencyCluster)sAMObject);
                    panels.ForEach(x => adjacencyCluster.AddObject(x));
                    dataAccess.SetData(index_Analytical, adjacencyCluster);
                }
            }

            int index_ElementType = Params.IndexOfOutputParam("elementType");

            if (index_ElementType != -1)
            {
                dataAccess.SetDataList(index_ElementType, elementTypes);
            }
        }