Esempio n. 1
0
    public static void ChangeInstanceType()
    {
        var start = new HostObject {
            nested = new DerivedObject {
                c = 5
            }
        };

        var end = new HostObject {
            nested = new SimpleObject {
                a = 1,
                b = 2
            }
        };

        var startModel = new SavedObject(start);
        var endModel = new SavedObject(end);

        var delta = new SavedObjectDelta(startModel, endModel);
        delta.ApplyChanges(ref end);

        Assert.AreEqual(start.nested.GetType(), end.nested.GetType());
        Assert.AreEqual(start.nested.a, end.nested.a);
        Assert.AreEqual(start.nested.b, end.nested.b);
        Assert.AreEqual(((DerivedObject)start.nested).c, ((DerivedObject)end.nested).c);
    }
Esempio n. 2
0
        public void Run()
        {
            var hostObject = new HostObject();
            Console.WriteLine("Value is {0}", hostObject.Value);
            Console.WriteLine("Enter code. Type exit to quit");

            var engine = new ScriptEngine();
            var session = engine.CreateSession( hostObject, hostObject.GetType());
            session.AddReference(hostObject.GetType().Assembly);
            string code = string.Empty;
            while (true)
            {
                code = Console.ReadLine();
                if (code == "exit")
                {
                    break;
                }
                try
                {
                    session.Execute(code);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            Console.WriteLine("Value is {0}", hostObject.Value);
            Console.ReadLine();
        }
Esempio n. 3
0
        /// <summary>
        /// Exports a floor to IFC slab.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="floor">
        /// The floor element.
        /// </param>
        /// <param name="geometryElement">
        /// The geometry element.
        /// </param>
        /// <param name="productWrapper">
        /// The ProductWrapper.
        /// </param>
        public static void Export(ExporterIFC exporterIFC, HostObject floor, GeometryElement geometryElement, ProductWrapper productWrapper)
        {
            string ifcEnumType = CategoryUtil.GetIFCEnumTypeName(exporterIFC, floor);

            // export parts or not
            bool exportParts = PartExporter.CanExportParts(floor);
            if (exportParts && !PartExporter.CanExportElementInPartExport(floor, floor.Level.Id, false))
                return;

            ExportFloor(exporterIFC, floor, geometryElement, ifcEnumType, productWrapper, exportParts);
        }
Esempio n. 4
0
    public static void ChangeInstanceTypeToNull()
    {
        var before = new HostObject() {
            nested = new DerivedObject()
        };
        var after = new HostObject();

        var delta = SavedObjectDelta.FromObjects(after, before);
        delta.ApplyChanges(ref before);

        Assert.AreEqual(after.nested, before.nested);
    }
		/// <summary>
		/// Makes a mapping of value from the host type to a script type
		/// </summary>
		/// <param name="value">The source value</param>
		/// <param name="engineMode">JavaScript engine mode</param>
		/// <returns>The mapped value</returns>
		public static object MapToScriptType(object value, JsEngineMode engineMode)
		{
			if (value == null)
			{
				return DBNull.Value;
			}

			if (value is Undefined)
			{
				return null;
			}

			if (TypeConverter.IsPrimitiveType(value.GetType()))
			{
				return value;
			}

			var result = new HostObject(value, engineMode);

			return result;
		}
Esempio n. 6
0
        /***************************************************/
        /****             Fallback methods              ****/
        /***************************************************/

        private static List <Face> LinkPanelFaces(this HostObject hostObject, RevitSettings settings)
        {
            BH.Engine.Reflection.Compute.RecordError($"Querying panel surfaces from links for Revit elements of type {hostObject.GetType().Name} is currently not supported.");
            return(new List <Face>());
        }
Esempio n. 7
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. 8
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;
            //TaskDialog.Show("Revit", "Hello World");

            // Create filters and collect walls/ slabs/ columns id in corresponding collector
            // walls
            IList <ElementId>        walls_id       = new List <ElementId>();
            FilteredElementCollector wall_collector = new FilteredElementCollector(doc).OfClass(typeof(Wall));

            foreach (Element w in wall_collector)
            {
                if (w is Wall)
                {
                    walls_id.Add(w.Id);
                }
            }
            // columns
            IList <ElementId>        columns_id       = new List <ElementId>();
            FilteredElementCollector column_collector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns);

            foreach (Element c in column_collector)
            {
                if (c is FamilyInstance)
                {
                    columns_id.Add(c.Id);
                }
            }
            // slabs
            IList <ElementId>        slabs_id  = new List <ElementId>();
            FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(Floor));

            foreach (Element e in collector)
            {
                if (e is Floor)
                {
                    slabs_id.Add(e.Id);
                }
            }

            //call create parts on walls/ slabs/ columns collectors
            using (Transaction t = new Transaction(doc, "Create Part")) {
                t.Start();
                // Create parts from the selected element
                // There is "CreateParts" but no "CreatePart", so needed to use a list containing the one element
                PartUtils.CreateParts(doc, walls_id);
                PartUtils.CreateParts(doc, columns_id);
                PartUtils.CreateParts(doc, slabs_id);
                t.Commit();
            }

            // start divide parts for walls, columns, slabs
            foreach (ElementId w_id in walls_id)
            {
                ICollection <ElementId> partsList = PartUtils.GetAssociatedParts(doc, w_id, true, true);

                // Get all levels
                ICollection <ElementId> levels = new FilteredElementCollector(doc).OfClass(typeof(Level)).OfCategory(BuiltInCategory.OST_Levels).ToElementIds();

                // Create a list of curves which needs to be used in DivideParts but for this example
                // the divide is being done by levels so the curve list will be empty
                IList <Curve> curve_list = new List <Curve>();

                // Get the host object corresponding to the selected element
                // HostObject is the parent class for walls, roof, floors, etc.
                HostObject hostObj = doc.GetElement(w_id) as HostObject;

                // Get the reference of one of the major faces of the selected element
                // Will be used to create a sketch plane
                Reference r = HostObjectUtils.GetSideFaces(hostObj, ShellLayerType.Exterior).First();

                using (Transaction t = new Transaction(doc, "Divide Part at Levels"))
                {
                    t.Start();
                    //Plane ref_plane = Plane.CreateByNormalAndOrigin(faceNormal, XYZ.Zero);
                    SketchPlane wall_sketchPlane = SketchPlane.Create(doc, r);
                    //SketchPlane sketchPlane = doc.Create.NewSketchPlane(r);
                    // Divide the parts
                    PartUtils.DivideParts(doc, partsList, levels, curve_list, wall_sketchPlane.Id);
                    t.Commit();
                }
            }

            // since walls and columns are all divided by all levels, so just use the sketch-plane of the last wall element
            ElementId borrow_from_wall = walls_id[0];

            foreach (ElementId c_id in columns_id)
            {
                ICollection <ElementId> partsList  = PartUtils.GetAssociatedParts(doc, c_id, true, true);
                ICollection <ElementId> levels     = new FilteredElementCollector(doc).OfClass(typeof(Level)).OfCategory(BuiltInCategory.OST_Levels).ToElementIds();
                IList <Curve>           curve_list = new List <Curve>();
                HostObject hostObj = doc.GetElement(borrow_from_wall) as HostObject;
                Reference  r       = HostObjectUtils.GetSideFaces(hostObj, ShellLayerType.Exterior).First();

                using (Transaction t = new Transaction(doc, "Divide Part at Levels")) {
                    t.Start();
                    SketchPlane column_sketchPlane = SketchPlane.Create(doc, r);
                    PartUtils.DivideParts(doc, partsList, levels, curve_list, column_sketchPlane.Id);
                    t.Commit();
                }
            }

            foreach (ElementId s_id in slabs_id)
            {
                //Selection sel = uidoc.Selection;
                //ISelectionFilter f = new JtElementsOfClassSelectionFilter<Grid>();
                //Reference elemRef = sel.PickObject(ObjectType.Element, f, "Pick a grid");
                //Grid grid = doc.GetElement(elemRef) as Grid;
                //ICollection<ElementId> grid_list = new List<ElementId>();
                //grid_list.Add(grid.Id);
                //IList<Curve> gridCurves = grid.GetCurvesInView(DatumExtentType.Model, view);

                ICollection <ElementId> partsList = PartUtils.GetAssociatedParts(doc, s_id, true, true);

                // Get all levels
                ICollection <ElementId> grids = new FilteredElementCollector(doc).OfClass(typeof(Grid)).OfCategory(BuiltInCategory.OST_Grids).ToElementIds();


                // Create a list of curves which needs to be used in DivideParts but for this example
                // the divide is being done by levels so the curve list will be empty
                IList <Curve> curve_list = new List <Curve>();

                HostObject hostObj = doc.GetElement(s_id) as HostObject;
                Reference  r       = HostObjectUtils.GetTopFaces(hostObj).First();
                using (Transaction t = new Transaction(doc, "Divide Part at Grids")) {
                    t.Start();
                    //Transaction sketchPlaneTransaction = new Transaction(doc, "Create Sketch Plane");
                    SketchPlane grid_sketchPlane = SketchPlane.Create(doc, r);
                    //SketchPlane grid_sketchPlane = null;
                    //sketchPlaneTransaction.Commit();
                    PartUtils.DivideParts(doc, partsList, grids, curve_list, grid_sketchPlane.Id);
                    t.Commit();
                }
            }
            // Set the view's "Parts Visibility" parameter so that parts are shown
            Parameter p = doc.ActiveView.get_Parameter(BuiltInParameter.VIEW_PARTS_VISIBILITY);

            using (Transaction t = new Transaction(doc, "Set View Parameter"))
            {
                t.Start();
                p.Set(0); // 0 = Show Parts, 1 = Show Original, 2 = Show Both
                t.Commit();
            }



            //ICollection<ElementId> elementIdsToDivide = new List<ElementId>();
            //if (PartUtils.AreElementsValidForCreateParts(doc, slabs_id))
            //{
            //    // AreElementsValidForCreateParts returned true, so the selected element is not a part but it is an element that can be used to create a part.
            //    Transaction createPartTransaction = new Transaction(doc, "Create Part");
            //    createPartTransaction.Start();
            //    PartUtils.CreateParts(doc, slabs_id); // create the parts
            //    createPartTransaction.Commit();
            //    foreach (ElementId e_id in slabs_id)
            //    {
            //        elementIdsToDivide = PartUtils.GetAssociatedParts(doc, e_id, true, true);
            //    }// get the id of the newly created part
            //}
            ////else if (pickedElement is Part)
            ////{
            ////    // The selected element is a part, so that part will be divided.
            ////    elementIdsToDivide.Add(pickedElement.Id);
            ////}
            //// Create geometry that will be used to divide the part. For this example, a new part will be divided from the main part that is one quarter of the face. More complex intelligence could be coded to divide the part based on construction logistics or the properties of the materials being used to create the part.
            //XYZ pointRight = null;
            //XYZ pointTop = null;
            //XYZ pointCorner = null;
            //XYZ pointCenter = null;

            //SketchPlane sketchPlane = null;
            //Plane plane = null;

            //Options opt = new Options();
            //opt.ComputeReferences = true;
            //foreach (Element e in slabs)
            //{
            //    GeometryElement geomElem = e.get_Geometry(opt);
            //    foreach (GeometryObject geomObject in geomElem)
            //    {
            //        if (geomObject is Solid) // get the solid geometry of the selected element
            //        {
            //            Solid solid = geomObject as Solid;
            //            FaceArray faceArray = solid.Faces;
            //            foreach (Face face in faceArray)
            //            {
            //                // find the center of the face
            //                BoundingBoxUV bbox = face.GetBoundingBox();
            //                UV center = new UV((bbox.Max.U - bbox.Min.U) / 2 + bbox.Min.U, (bbox.Max.V - bbox.Min.V) / 2 + bbox.Min.V);
            //                XYZ faceNormal = face.ComputeNormal(center);
            //                if (faceNormal.IsAlmostEqualTo(XYZ.BasisZ)) // this example is designed to work with a floor or other element with a large face whose normal is in the Z direction
            //                {
            //                    Transaction sketchPlaneTransaction = new Transaction(doc, "Create Sketch Plane");
            //                    sketchPlaneTransaction.Start();
            //                    plane = Plane.CreateByNormalAndOrigin(faceNormal, XYZ.Zero);
            //                    sketchPlane = SketchPlane.Create(doc, plane);
            //                    //sketchPlane = doc.SketchPlane.Create(face as PlanarFace);
            //                    sketchPlaneTransaction.Commit();

            //                    pointCenter = face.Evaluate(center);

            //                    UV top = new UV((bbox.Max.U - bbox.Min.U) / 2 + bbox.Min.U, bbox.Max.V);
            //                    pointTop = face.Evaluate(top);

            //                    UV right = new UV(bbox.Max.U, (bbox.Max.V - bbox.Min.V) / 2 + bbox.Min.V);
            //                    pointRight = face.Evaluate(right);

            //                    UV corner = new UV(bbox.Max.U, bbox.Max.V);
            //                    pointCorner = face.Evaluate(corner);

            //                    break;
            //                }
            //            }
            //        }
            //    }
            //}

            ////Selection sel = uidoc.Selection;
            ////Reference elemRef = sel.PickObject(
            ////ObjectType.Element, f, "Pick a grid");
            ////Grid grid = doc.GetElement(elemRef) as Grid;

            //// Create the curves that will be used for the part division.
            //IList<Curve> curveList = new List<Curve>();
            ////Curve curve1 = app.Create.NewLine(pointCenter, pointRight, true);
            //Curve curve1 = Line.CreateBound(pointCenter, pointRight);
            //curveList.Add(curve1);
            ////Curve curve2 = app.Create.NewLine(pointRight, pointCorner, true);
            //Curve curve2 = Line.CreateBound(pointRight, pointCorner);
            //curveList.Add(curve2);
            ////Curve curve3 = app.Create.NewLine(pointCorner, pointTop, true);
            //Curve curve3 = Line.CreateBound(pointCorner, pointTop);
            //curveList.Add(curve3);
            ////Curve curve4 = app.Create.NewLine(pointTop, pointCenter, true);
            //Curve curve4 = Line.CreateBound(pointTop, pointCenter);
            //curveList.Add(curve4);

            //// intersectingReferenceIds will be empty for this example.
            //ICollection<ElementId> intersectingReferenceIds = new List<ElementId>();

            //// Divide the part
            //Transaction dividePartTransaction = new Transaction(doc, "Divide Part");
            //dividePartTransaction.Start();
            //PartMaker maker = PartUtils.DivideParts(doc, elementIdsToDivide, intersectingReferenceIds, curveList, sketchPlane.Id);
            //dividePartTransaction.Commit();
            ////ICollection<ElementId> divElems = maker.GetSourceElementIds(); // Get the ids of the divided elements

            //// Set the view's "Parts Visibility" parameter so that parts are shown
            //Parameter partVisInView = doc.ActiveView.get_Parameter(BuiltInParameter.VIEW_PARTS_VISIBILITY);
            //Transaction setPartVizTransaction = new Transaction(doc, "Set View Parameter");
            //setPartVizTransaction.Start();
            //partVisInView.Set(0); // 0 = Show Parts, 1 = Show Original, 2 = Show Both
            //setPartVizTransaction.Commit();
            ////// Access current selection



            return(Result.Succeeded);
        }
Esempio n. 9
0
        /// <summary>
        /// Exports a generic element as an IfcSlab.</summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="floor">The floor element.</param>
        /// <param name="geometryElement">The geometry element.</param>
        /// <param name="ifcEnumType">The string value represents the IFC type.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        /// <returns>True if the floor is exported successfully, false otherwise.</returns>
        public static void ExportGenericSlab(ExporterIFC exporterIFC, Element slabElement, GeometryElement geometryElement, string ifcEnumType,
                                             ProductWrapper productWrapper)
        {
            if (geometryElement == null)
            {
                return;
            }

            IFCFile file = exporterIFC.GetFile();

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

                    using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, slabElement, null, null, overrideContainerId, overrideContainerHnd))
                    {
                        using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData())
                        {
                            bool exportParts = PartExporter.CanExportParts(slabElement);

                            IFCAnyHandle ownerHistory   = ExporterCacheManager.OwnerHistoryHandle;
                            IFCAnyHandle localPlacement = placementSetter.LocalPlacement;

                            IFCAnyHandle prodDefHnd    = null;
                            bool         isBRepSlabHnd = false;

                            if (!exportParts)
                            {
                                ecData.SetLocalPlacement(localPlacement);

                                ElementId catId = CategoryUtil.GetSafeCategoryId(slabElement);

                                BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.Medium);
                                BodyData            bodyData;
                                prodDefHnd = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC,
                                                                                                        slabElement, catId, geometryElement, bodyExporterOptions, null, ecData, out bodyData);
                                if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodDefHnd))
                                {
                                    ecData.ClearOpenings();
                                    return;
                                }
                                isBRepSlabHnd = (bodyData.ShapeRepresentationType == ShapeRepresentationType.Brep || bodyData.ShapeRepresentationType == ShapeRepresentationType.Tessellation);
                            }

                            // Create the slab from either the extrusion or the BRep information.
                            string ifcGUID = GUIDUtil.CreateGUID(slabElement);

                            string entityType = IFCValidateEntry.GetValidIFCType <IFCSlabType>(slabElement, ifcEnumType, "FLOOR");

                            IFCAnyHandle slabHnd = IFCInstanceExporter.CreateSlab(exporterIFC, slabElement, ifcGUID, ownerHistory,
                                                                                  localPlacement, exportParts ? null : prodDefHnd, entityType);
                            IFCExportInfoPair exportInfo = new IFCExportInfoPair(IFCEntityType.IfcSlab, entityType);

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

                            if (exportParts)
                            {
                                PartExporter.ExportHostPart(exporterIFC, slabElement, slabHnd, productWrapper, placementSetter, localPlacement, null);
                            }

                            productWrapper.AddElement(slabElement, slabHnd, placementSetter, ecData, true, exportInfo);

                            if (!exportParts)
                            {
                                IFCAnyHandle typeHnd = ExporterUtil.CreateGenericTypeFromElement(slabElement, exportInfo, file, ownerHistory, entityType, productWrapper);
                                ExporterCacheManager.TypeRelationsCache.Add(typeHnd, slabHnd);

                                if (slabElement is HostObject)
                                {
                                    HostObject hostObject = slabElement as HostObject;

                                    HostObjectExporter.ExportHostObjectMaterials(exporterIFC, hostObject, slabHnd,
                                                                                 geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, isBRepSlabHnd, typeHnd);
                                }
                                else if (slabElement is FamilyInstance)
                                {
                                    ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, slabElement);
                                    //Document doc = slabElement.Document;
                                    if (typeHnd != null)
                                    {
                                        CategoryUtil.CreateMaterialAssociation(exporterIFC, typeHnd, matId);
                                    }
                                    else
                                    {
                                        CategoryUtil.CreateMaterialAssociation(exporterIFC, slabHnd, matId);
                                    }
                                }

                                OpeningUtil.CreateOpeningsIfNecessary(slabHnd, slabElement, ecData, null,
                                                                      exporterIFC, ecData.GetLocalPlacement(), placementSetter, productWrapper);
                            }
                        }
                    }
                    tr.Commit();

                    return;
                }
            }
        }
Esempio n. 10
0
        public static DoorWindowInfo CreateWindow(ExporterIFC exporterIFC, FamilyInstance famInst, HostObject hostObj,
                                                  ElementId overrideLevelId, Transform trf)
        {
            DoorWindowInfo doorWindowInfo = new DoorWindowInfo();

            doorWindowInfo.Initialize(false, true, famInst, hostObj);
            doorWindowInfo.CalculateDoorWindowInformation(exporterIFC, famInst, overrideLevelId, trf);

            return(doorWindowInfo);
        }
Esempio n. 11
0
        public static ScriptEngine AddHostObject(this ScriptEngine engine, HostObject hostObject)
        {
            engine.AddHostObject(hostObject.Name, hostObject.Flags, hostObject.Target);

            return(engine);
        }
Esempio n. 12
0
        /***************************************************/

        public static bool SetLocation(this HostObject element, BH.oM.Physical.Elements.ISurface bHoMObject, RevitSettings settings)
        {
            BH.Engine.Reflection.Compute.RecordWarning(String.Format("Update of location of surface-based elements is currently not supported. Possibly DeleteThenCreate PushType could be used instead. Revit ElementId: {0} BHoM_Guid: {1}", element.Id, bHoMObject.BHoM_Guid));
            return(false);
        }
Esempio n. 13
0
        /// <summary>
        /// Exports a generic element as an IfcSlab.</summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="floor">The floor element.</param>
        /// <param name="geometryElement">The geometry element.</param>
        /// <param name="ifcEnumType">The string value represents the IFC type.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        /// <returns>True if the floor is exported successfully, false otherwise.</returns>
        public static void ExportGenericSlab(ExporterIFC exporterIFC, Element slabElement, GeometryElement geometryElement, string ifcEnumType,
                                             ProductWrapper productWrapper)
        {
            if (geometryElement == null)
            {
                return;
            }

            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                using (IFCTransformSetter transformSetter = IFCTransformSetter.Create())
                {
                    using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, slabElement))
                    {
                        using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData())
                        {
                            bool exportParts = PartExporter.CanExportParts(slabElement);

                            IFCAnyHandle ownerHistory   = exporterIFC.GetOwnerHistoryHandle();
                            IFCAnyHandle localPlacement = placementSetter.LocalPlacement;

                            IFCAnyHandle prodDefHnd    = null;
                            bool         isBRepSlabHnd = false;

                            if (!exportParts)
                            {
                                ecData.SetLocalPlacement(localPlacement);

                                ElementId catId = CategoryUtil.GetSafeCategoryId(slabElement);

                                BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true);
                                bodyExporterOptions.TessellationLevel = BodyExporter.GetTessellationLevel();
                                BodyData bodyData;
                                prodDefHnd = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC,
                                                                                                        slabElement, catId, geometryElement, bodyExporterOptions, null, ecData, out bodyData);
                                if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodDefHnd))
                                {
                                    ecData.ClearOpenings();
                                    return;
                                }
                                isBRepSlabHnd = (bodyData.ShapeRepresentationType == ShapeRepresentationType.Brep);
                            }

                            // Create the slab from either the extrusion or the BRep information.
                            string ifcGUID = GUIDUtil.CreateGUID(slabElement);

                            string entityType = IFCValidateEntry.GetValidIFCType <IFCSlabType>(slabElement, ifcEnumType, "FLOOR");

                            string ifcName        = NamingUtil.GetNameOverride(slabElement, NamingUtil.GetIFCName(slabElement));
                            string ifcDescription = NamingUtil.GetDescriptionOverride(slabElement, null);
                            string ifcObjectType  = NamingUtil.GetObjectTypeOverride(slabElement, exporterIFC.GetFamilyName());
                            string ifcTag         = NamingUtil.GetTagOverride(slabElement, NamingUtil.CreateIFCElementId(slabElement));

                            IFCAnyHandle slabHnd = IFCInstanceExporter.CreateSlab(file, ifcGUID, ownerHistory, ifcName,
                                                                                  ifcDescription, ifcObjectType, localPlacement, exportParts ? null : prodDefHnd,
                                                                                  ifcTag, entityType);

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

                            if (exportParts)
                            {
                                PartExporter.ExportHostPart(exporterIFC, slabElement, slabHnd, productWrapper, placementSetter, localPlacement, null);
                            }

                            productWrapper.AddElement(slabElement, slabHnd, placementSetter, ecData, true);

                            if (!exportParts)
                            {
                                if (slabElement is HostObject)
                                {
                                    HostObject hostObject = slabElement as HostObject;

                                    HostObjectExporter.ExportHostObjectMaterials(exporterIFC, hostObject, slabHnd,
                                                                                 geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, isBRepSlabHnd);
                                }
                                else if (slabElement is FamilyInstance)
                                {
                                    ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, slabElement);
                                    Document  doc   = slabElement.Document;
                                    CategoryUtil.CreateMaterialAssociation(exporterIFC, slabHnd, matId);
                                }

                                OpeningUtil.CreateOpeningsIfNecessary(slabHnd, slabElement, ecData, null,
                                                                      exporterIFC, ecData.GetLocalPlacement(), placementSetter, productWrapper);
                            }
                        }
                    }
                    tr.Commit();

                    return;
                }
            }
        }
        public static DoorWindowInfo CreateWindow(ExporterIFC exporterIFC, FamilyInstance famInst,  HostObject hostObj,
            ElementId overrideLevelId, Transform trf)
        {
            DoorWindowInfo doorWindowInfo = new DoorWindowInfo();
            doorWindowInfo.Initialize(false, true, famInst, hostObj);
            doorWindowInfo.CalculateDoorWindowInformation(exporterIFC, famInst, overrideLevelId, trf);

            return doorWindowInfo;
        }
        /// <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. 16
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="dataAccess">
        /// The DA object is used to retrieve from inputs and store in outputs.
        /// </param>
        protected override void SolveInstance(IGH_DataAccess dataAccess)
        {
            bool run = false;

            if (!dataAccess.GetData(2, ref run) || !run)
            {
                return;
            }

            bool merge = true;

            if (!dataAccess.GetData(1, ref merge))
            {
                return;
            }

            GH_ObjectWrapper objectWrapper = null;

            if (!dataAccess.GetData(0, ref objectWrapper) || objectWrapper.Value == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            dynamic obj = objectWrapper.Value;

            ElementId aId = obj.Id as ElementId;

            string message = null;

            Document document = obj.Document as Document;

            Autodesk.Revit.DB.Mechanical.Space space = document.GetElement(aId) as Autodesk.Revit.DB.Mechanical.Space;
            if (space == null)
            {
                message = "Invalid Element";
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, message);
                return;
            }

            if (space.Location == null)
            {
                message = string.Format("Cannot generate Panels. Space {0} [ElementId: {1}] not enclosed", space.Name, space.Id.IntegerValue);
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);
                return;
            }

            if (space.Volume < Core.Tolerance.MacroDistance)
            {
                message = string.Format("Space cannot be converted because it has no volume. Space {0} [ElementId: {1}] not enclosed", space.Name, space.Id.IntegerValue);
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);
                return;
            }

            ConvertSettings convertSettings = new ConvertSettings(true, true, true);

            List <Panel> panels = Analytical.Revit.Create.Panels(space, convertSettings);

            if (panels == null || panels.Count == 0)
            {
                message = "Panels ould not be generated";
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, message);
                return;
            }

            panels.RemoveAll(x => x == null);

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

            foreach (Panel panel in panels)
            {
                PanelGroup panelGroup = Analytical.Query.PanelGroup(panel.PanelType);
                if (panelGroup != PanelGroup.Floor && panelGroup != PanelGroup.Roof)
                {
                    continue;
                }

                ElementId elementId = panel.ElementId();
                if (elementId == null || elementId == ElementId.InvalidElementId)
                {
                    panels_Temp.Add(panel);
                    continue;
                }

                HostObject hostObject = document.GetElement(elementId) as HostObject;
                if (hostObject == null)
                {
                    panels_Temp.Add(panel);
                    continue;
                }

                Geometry.Spatial.Plane plane = panel.PlanarBoundary3D.Plane;

                List <Geometry.Spatial.Face3D> face3Ds = Geometry.Revit.Query.Profiles(hostObject);
                if (face3Ds == null || face3Ds.Count == 0)
                {
                    panels_Temp.Add(panel);
                    continue;
                }

                Geometry.Spatial.Plane plane_Face3D = face3Ds.Find(x => plane.Coplanar(x.GetPlane()))?.GetPlane();
                if (plane_Face3D == null)
                {
                    panels_Temp.Add(panel);
                    continue;
                }

                Geometry.Spatial.Point3D point3D_Projected = plane_Face3D.Project(plane.Origin);

                panel.Move(new Geometry.Spatial.Vector3D(plane.Origin, point3D_Projected));
                panels_Temp.Add(panel);
            }

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

            if (merge)
            {
                panels_Temp = Analytical.Query.MergeCoplanarPanels(panels_Temp, Core.Tolerance.MacroDistance, ref redundantPanels, true, Core.Tolerance.MacroDistance);
            }

            dataAccess.SetDataList(0, panels_Temp.FindAll(x => Analytical.Query.PanelGroup(x.PanelType) == PanelGroup.Floor));
            dataAccess.SetDataList(1, panels_Temp.FindAll(x => Analytical.Query.PanelGroup(x.PanelType) == PanelGroup.Roof));
            dataAccess.SetDataList(2, redundantPanels);
        }
Esempio n. 17
0
        /***************************************************/
        /****              Public methods               ****/
        /***************************************************/

        public static List <Face> ILinkPanelFaces(this HostObject hostObject, RevitSettings settings)
        {
            return(LinkPanelFaces(hostObject as dynamic, settings));
        }
Esempio n. 18
0
        public static IOpening ToSAM_Opening(this FamilyInstance familyInstance, ConvertSettings convertSettings)
        {
            if (familyInstance == null)
            {
                return(null);
            }

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

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

            if (Core.Revit.Query.Simplified(familyInstance))
            {
                result = Core.Revit.Query.IJSAMObjects <IOpening>(familyInstance)?.FirstOrDefault();
                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);
            }

            OpeningType openingType = ToSAM_OpeningType(familyInstance.Symbol, convertSettings);

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

            BuiltInCategory builtInCategory_Host = BuiltInCategory.INVALID;

            HostObject hostObject = familyInstance.Host as HostObject;

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

            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_Geometries <Face3D>(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);
            }

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

            result = Analytical.Create.Opening(openingType, new Face3D(plane, rectangle2D));
            result.UpdateParameterSets(familyInstance);

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

            return(result);
        }
Esempio n. 19
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 WallType)
            {
                List <Curve> curveList = new List <Curve>();
                foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D in face3D.GetEdge3Ds())
                {
                    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)
                {
                    double height = UnitUtils.ConvertToInternalUnits((panel.HighElevation() - lowElevation), DisplayUnitType.DUT_METERS);
                    parameter.Set(height);
                }

                double levelElevation = UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS);
                if (Math.Abs(lowElevation - levelElevation) > Core.Tolerance.MacroDistance)
                {
                    parameter = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
                    if (parameter != null)
                    {
                        parameter.Set(UnitUtils.ConvertToInternalUnits(lowElevation - levelElevation, DisplayUnitType.DUT_METERS));
                    }
                }

                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 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 = plane.Project(segment3D);
                    if (segment3D_Temp == null)
                    {
                        continue;
                    }

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

                Floor floor = document.Create.NewFloor(curveArray_Plane, hostObjAttributes as FloorType, level, false);

                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)
                            {
                                curveArray_Sloped.Append(segment3D.ToRevit_Line());

                                Geometry.Spatial.Segment3D segment3D_Temp = plane.Project(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 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 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)
            {
                Geometry.Spatial.Plane plane_Panel = panel.PlanarBoundary3D?.Plane;

                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. 20
0
        private async Task doFetch(TaskCompletionSource <HttpResponseMessage> tcs, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try {
                var requestObject = new JSObject();
                requestObject.SetObjectProperty("method", request.Method.Method);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials for
                // standard values and meanings
                requestObject.SetObjectProperty("credentials", DefaultCredentials);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/cache for
                // standard values and meanings
                requestObject.SetObjectProperty("cache", Cache);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/mode for
                // standard values and meanings
                requestObject.SetObjectProperty("mode", Mode);

                // We need to check for body content
                if (request.Content != null)
                {
                    if (request.Content is StringContent)
                    {
                        requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync());
                    }
                    else
                    {
                        using (var uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync()))
                        {
                            requestObject.SetObjectProperty("body", uint8Buffer);
                        }
                    }
                }

                // Process headers
                // Cors has it's own restrictions on headers.
                // https://developer.mozilla.org/en-US/docs/Web/API/Headers
                using (var jsHeaders = new HostObject("Headers")) {
                    if (request.Headers != null)
                    {
                        foreach (var header in request.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                jsHeaders.Invoke("append", header.Key, value);
                            }
                        }
                    }
                    if (request.Content?.Headers != null)
                    {
                        foreach (var header in request.Content.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                jsHeaders.Invoke("append", header.Key, value);
                            }
                        }
                    }
                    requestObject.SetObjectProperty("headers", jsHeaders);
                }

                JSObject           abortController    = null;
                JSObject           signal             = null;
                WasmHttpReadStream wasmHttpReadStream = null;

                CancellationTokenRegistration abortRegistration = default(CancellationTokenRegistration);
                if (cancellationToken.CanBeCanceled)
                {
                    abortController = new HostObject("AbortController");

                    signal = (JSObject)abortController.GetObjectProperty("signal");
                    requestObject.SetObjectProperty("signal", signal);
                    abortRegistration = cancellationToken.Register((Action)(() => {
                        if (abortController.JSHandle != -1)
                        {
                            abortController.Invoke((string)"abort");
                            abortController?.Dispose();
                        }
                        wasmHttpReadStream?.Dispose();
                    }));
                }

                var args = new Core.Array();
                args.Push(request.RequestUri.ToString());
                args.Push(requestObject);

                requestObject.Dispose();

                var response = (Task <object>)fetch.Invoke("apply", window, args);
                args.Dispose();

                var t = await response;

                var status = new WasmFetchResponse((JSObject)t, abortController, abortRegistration);

                //Console.WriteLine($"bodyUsed: {status.IsBodyUsed}");
                //Console.WriteLine($"ok: {status.IsOK}");
                //Console.WriteLine($"redirected: {status.IsRedirected}");
                //Console.WriteLine($"status: {status.Status}");
                //Console.WriteLine($"statusText: {status.StatusText}");
                //Console.WriteLine($"type: {status.ResponseType}");
                //Console.WriteLine($"url: {status.Url}");

                HttpResponseMessage httpresponse = new HttpResponseMessage((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), status.Status.ToString()));

                httpresponse.Content = StreamingSupported && StreamingEnabled
                                    ? new StreamContent(wasmHttpReadStream = new WasmHttpReadStream(status))
                                    : (HttpContent) new WasmHttpContent(status);

                // Fill the response headers
                // CORS will only allow access to certain headers.
                // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors.
                // cors and basic responses are almost identical except that a cors response restricts the headers you can view to
                // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`.
                // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
                //
                // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation
                using (var respHeaders = status.Headers) {
                    // Here we invoke the forEach on the headers object
                    // Note: the Action takes 3 objects and not two.  The other seems to be the Header object.
                    var foreachAction = new Action <object, object, object> ((value, name, other) => {
                        if (!httpresponse.Headers.TryAddWithoutValidation((string)name, (string)value))
                        {
                            if (httpresponse.Content != null)
                            {
                                if (!httpresponse.Content.Headers.TryAddWithoutValidation((string)name, (string)value))
                                {
                                    Console.WriteLine($"Warning: Can not add response header for name: {name} value: {value}");
                                }
                            }
                        }
                        ((JSObject)other).Dispose();
                    });

                    try {
                        respHeaders.Invoke("forEach", foreachAction);
                    } finally {
                        // Do not remove the following line of code.  The httpresponse is used in the lambda above when parsing the Headers.
                        // if a local is captured (used) by a lambda it becomes heap memory as we translate them into fields on an object.
                        // The foreachAction is allocated when marshalled to JavaScript.  Since we do not know when JS is finished with the
                        // Action we need to tell the Runtime to de-allocate the object and remove the instance from JS as well.
                        WebAssembly.Runtime.FreeObject(foreachAction);
                    }
                }

                tcs.SetResult(httpresponse);

                signal?.Dispose();
            } catch (Exception exception) {
                tcs.SetException(exception);
            }
        }
        /// <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. 22
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, IFCAnyHandle typeHnd = null)
        {
            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))
            {
                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;
                    }
                }

                MaterialLayerSetInfo mlsInfo          = new MaterialLayerSetInfo(exporterIFC, hostObject, productWrapper);
                IFCAnyHandle         materialLayerSet = mlsInfo.MaterialLayerSetHandle;
                List <ElementId>     materialIds      = mlsInfo.MaterialIds.Select(x => x.m_baseMatId).ToList();

                // Among all the calls of this method the problem of material association absence was found only
                // for CeilingAndFloor host object type (see JIRA item REVIT-164913)
                if (containsBRepGeometry && (hostObject is CeilingAndFloor) &&
                    materialIds.Count > 0 && !ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                {
                    foreach (IFCAnyHandle elemHnd in elemHnds)
                    {
                        CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, materialIds);
                    }
                }

                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(materialLayerSet))
                {
                    // If there is an override for creating IfcMaterial instead of IfcMaterialLayer for a single material/layer, assign the material directly to type or element(s)
                    if (IFCAnyHandleUtil.IsTypeOf(materialLayerSet, IFCEntityType.IfcMaterial))
                    {
                        if (typeHnd != null)
                        {
                            CategoryUtil.CreateMaterialAssociation(exporterIFC, typeHnd, materialLayerSet);
                        }

                        foreach (IFCAnyHandle elemHnd in elemHnds)
                        {
                            CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, materialLayerSet);
                        }
                    }
                    else
                    {
                        // 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);

                            // Even if it is Tessellated geometry in IFC4RV, the material layer will still be assigned
                            if (containsBRepGeometry && !ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                            {
                                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);
                            bool isDisallowedWallType = (IFCAnyHandleUtil.IsTypeOf(elemHnd, IFCEntityType.IfcWall) && !ExporterCacheManager.ExportOptionsCache.ExportAs4);

                            // Create IfcMaterialLayerSetUsage unless we have sub-elements, are exporting a Roof, or are exporting a pre-IFC4 IfcWall.
                            if (!hasSubElems && !isRoof && !isDisallowedWallType)
                            {
                                bool materialAlreadyAssoc = false;
                                if (typeHnd != null)
                                {
                                    CategoryUtil.CreateMaterialAssociation(exporterIFC, typeHnd, materialLayerSet);
                                }

                                if (ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                                {
                                    if (!materialAlreadyAssoc)
                                    {
                                        CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, materialLayerSet);
                                    }
                                }
                                else
                                {
                                    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;
                                                Transform lcs          = Transform.Identity;
                                                bool      curveFlipped = GeometryUtil.MustFlipCurve(lcs, curve);
                                                flipDirSense = !(wall.Flipped ^ curveFlipped);
                                            }
                                        }
                                        else if (hostObject is CeilingAndFloor)
                                        {
                                            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)
                                    {
                                        // TODO: still need to figure out the best way to create type for the sub elements because at this time a lot of information is not available, e.g.
                                        //    the Revit Element to get the type, other information for name, GUID, etc.
                                        if (!IFCAnyHandleUtil.IsNullOrHasNoValue(subElemHnd))
                                        {
                                            CategoryUtil.CreateMaterialAssociation(exporterIFC, subElemHnd, materialLayerSet);
                                        }
                                    }
                                }
                                else if (!isRoof)
                                {
                                    if (typeHnd != null)
                                    {
                                        CategoryUtil.CreateMaterialAssociation(exporterIFC, typeHnd, materialLayerSet);
                                    }
                                    else
                                    {
                                        CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, materialLayerSet);
                                    }
                                }
                                else if (mlsInfo.PrimaryMaterialHandle != null)
                                {
                                    if (typeHnd != null)
                                    {
                                        CategoryUtil.CreateMaterialAssociation(exporterIFC, typeHnd, materialLayerSet);
                                    }
                                    else
                                    {
                                        CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, materialLayerSet);
                                    }
                                }
                            }
                        }
                    }
                }
                tr.Commit();
                return(true);
            }
        }
Esempio n. 23
0
 private double GetWallHeight( HostObject hostObj )
 {
     return hostObj.get_Parameter( BuiltInParameter.WALL_USER_HEIGHT_PARAM ).AsDouble();
 }
Esempio n. 24
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);
        }
        /// <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;
                    }
                }

                List <ElementId> matIds;
                IFCAnyHandle     primaryMaterialHnd;
                IFCAnyHandle     materialLayerSet = ExporterUtil.CollectMaterialLayerSet(exporterIFC, hostObject, productWrapper, out matIds, out primaryMaterialHnd);
                if (containsBRepGeometry && matIds.Count > 0)
                {
                    foreach (IFCAnyHandle elemHnd in elemHnds)
                    {
                        CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, matIds);
                    }
                }

                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(materialLayerSet))
                {
                    // 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);
                        bool isDisallowedWallType = (IFCAnyHandleUtil.IsTypeOf(elemHnd, IFCEntityType.IfcWall) && !ExporterCacheManager.ExportOptionsCache.ExportAs4);

                        // Create IfcMaterialLayerSetUsage unless we have sub-elements, are exporting a Roof, or are exporting a pre-IFC4 IfcWall.
                        if (!hasSubElems && !isRoof && !isDisallowedWallType)
                        {
                            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;
                                        Transform lcs          = Transform.Identity;
                                        bool      curveFlipped = GeometryUtil.MustFlipCurve(lcs, 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);
            }
        }
        public static FamilyInstance ToRevit(this Aperture aperture, Document document, HostObject hostObject, Core.Revit.ConvertSettings convertSettings)
        {
            if (aperture == null || document == null)
            {
                return(null);
            }

            FamilyInstance result = convertSettings?.GetObject <FamilyInstance>(aperture.Guid);

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

            ApertureConstruction apertureConstruction = aperture.ApertureConstruction;

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

            FamilySymbol familySymbol = apertureConstruction.ToRevit(document, convertSettings);

            if (familySymbol == null)
            {
                familySymbol = Analytical.Query.DefaultApertureConstruction(hostObject.PanelType(), apertureConstruction.ApertureType).ToRevit(document, convertSettings); //Default Aperture Construction
            }
            if (familySymbol == null)
            {
                return(null);
            }

            Point3D point3D_Location = aperture.PlanarBoundary3D?.Plane?.Origin;

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

            Level level = Geometry.Revit.Query.LowLevel(document, point3D_Location.Z);

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

            XYZ referenceDirection = new XYZ(0, 0, 0);

            if (hostObject is RoofBase)
            {
                Face3D face3D = aperture.GetFace3D();
                Geometry.Spatial.Plane plane = face3D.GetPlane();

                bool coplanar = plane.Coplanar(Geometry.Spatial.Plane.WorldXY);
                //if(coplanar)
                //{
                //    referenceDirection = new XYZ(0, 0, 1);
                //}

                result = document.Create.NewFamilyInstance(point3D_Location.ToRevit(), familySymbol, referenceDirection, hostObject, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                if (result == null)
                {
                    return(null);
                }

                //List<Geometry.Planar.Point2D> point2Ds = new List<Geometry.Planar.Point2D>();
                //IClosedPlanar3D closedPlanar3D = face3D.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()));
                //    }
                //}

                //Geometry.Planar.Rectangle2D rectangle2D = Geometry.Planar.Create.Rectangle2D(point2Ds);
                Geometry.Planar.Rectangle2D rectangle2D = Analytical.Create.Rectangle2D(aperture.PlanarBoundary3D);
                if (rectangle2D == null)
                {
                    return(null);
                }

                document.Regenerate();
                result = document.GetElement(result.Id) as FamilyInstance;

                Vector3D handOrientation_FamilyInstance   = result.HandOrientation.ToSAM_Vector3D(false);
                Vector3D facingOrientation_FamilyInstance = result.FacingOrientation.ToSAM_Vector3D(false);


                double factor = 0;
                Geometry.Planar.Vector2D direction = rectangle2D.WidthDirection;
                if (!coplanar && Core.Query.Round(direction.Y) < 0)
                {
                    factor = System.Math.PI / 2;
                }

                Vector3D handOrienation_Aperture = plane.Convert(direction);

                Geometry.Spatial.Plane plane_FamilyInstance = new Geometry.Spatial.Plane(point3D_Location, handOrientation_FamilyInstance, facingOrientation_FamilyInstance);
                handOrienation_Aperture = plane_FamilyInstance.Project(handOrienation_Aperture);

                double angle = Geometry.Spatial.Query.SignedAngle(handOrientation_FamilyInstance, handOrienation_Aperture, plane.Normal);

                result.Location.Rotate(Line.CreateUnbound(point3D_Location.ToRevit(), plane.Normal.ToRevit(false)), angle + factor);
                //document.Regenerate();

                //BoundingBox3D boundingBox3D_familyInstance = familyInstance.BoundingBox3D();
                //BoundingBox3D boundingBox3D_Aperture = aperture.GetBoundingBox();
                //if(boundingBox3D_familyInstance.Min.Distance(boundingBox3D_Aperture.Min) > SAM.Core.Tolerance.MacroDistance)
                //    familyInstance.Location.Rotate(Line.CreateUnbound(point3D_Location.ToRevit(), plane.Normal.ToRevit(false)), System.Math.PI / 2);

                //Geometry.Planar.Rectangle2D rectangle2D = Geometry.Planar.Create.Rectangle2D(point2Ds);
                //Geometry.Planar.Vector2D direction = null;
                //if (rectangle2D.Height > rectangle2D.Width)
                //    direction = rectangle2D.HeightDirection;
                //else
                //    direction = rectangle2D.WidthDirection;

                //double angle = plane.Convert(direction).ToRevit(false).AngleTo(new XYZ(0, 1, 0));
                //angle = System.Math.PI  - angle;
                ////if (angle > System.Math.PI)
                ////    angle = -(angle - System.Math.PI);
                //if (direction.X < 0)
                //    angle = -angle;

                //familyInstance.Location.Rotate(Line.CreateUnbound(point3D_Location.ToRevit(), plane.Normal.ToRevit(false)), angle);
            }
            else
            {
                result = document.Create.NewFamilyInstance(point3D_Location.ToRevit(), familySymbol, hostObject, level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
            }


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

            if (result.CanFlipHand)
            {
                document.Regenerate(); //This is needed to get flip correctly pushed to revit
                Vector3D axisX = result.HandOrientation.ToSAM_Vector3D(false);
                if (!axisX.SameHalf(aperture.Plane.AxisX))
                {
                    result.flipHand();
                }
            }

            if (result.CanFlipFacing)
            {
                document.Regenerate(); //This is needed to get flip correctly pushed to revit
                Vector3D normal = result.FacingOrientation.ToSAM_Vector3D(false);
                if (!normal.SameHalf(aperture.Plane.Normal))
                {
                    result.flipFacing();
                }
            }

            if (convertSettings.ConvertParameters)
            {
                Core.Revit.Modify.SetValues(result, aperture, new BuiltInParameter[] { BuiltInParameter.INSTANCE_SILL_HEIGHT_PARAM, BuiltInParameter.INSTANCE_HEAD_HEIGHT_PARAM, BuiltInParameter.FAMILY_LEVEL_PARAM, BuiltInParameter.SCHEDULE_LEVEL_PARAM });
                Core.Revit.Modify.SetValues(result, aperture, ActiveSetting.Setting);

                bool simplified = false;

                //Check if geometry is simplified
                if (!Geometry.Planar.Query.Rectangular(aperture.PlanarBoundary3D?.ExternalEdge2DLoop?.GetClosed2D(), Core.Tolerance.MacroDistance))
                {
                    simplified = true;
                }

                if (!simplified && result.Host is Wall)
                {
                    Face3D face3D = aperture.GetFace3D();
                    Geometry.Spatial.Plane plane = face3D.GetPlane();

                    Geometry.Planar.Rectangle2D rectangle2D = Analytical.Create.Rectangle2D(aperture.PlanarBoundary3D);
                    if (rectangle2D != null)
                    {
                        Vector3D widthDirection  = plane.Convert(rectangle2D.WidthDirection);
                        Vector3D heightDirection = plane.Convert(rectangle2D.HeightDirection);

                        //TODO: Implement code for Tilted Walls
                        Vector3D vector3D_Z = Vector3D.WorldZ;

                        if (!widthDirection.AlmostSimilar(vector3D_Z) && !heightDirection.AlmostSimilar(vector3D_Z))
                        {
                            simplified = true;
                        }
                    }
                }

                Core.Revit.Modify.SetSimplified(result, simplified);
                Core.Revit.Modify.SetJson(result, aperture.ToJObject()?.ToString());
            }

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

            return(result);
        }
Esempio n. 27
0
        /// <summary>
        /// Exports a generic element as an IfcSlab.</summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="floor">The floor element.</param>
        /// <param name="geometryElement">The geometry element.</param>
        /// <param name="ifcEnumType">The string value represents the IFC type.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        /// <returns>True if the floor is exported successfully, false otherwise.</returns>
        public static void ExportGenericSlab(ExporterIFC exporterIFC, Element slabElement, GeometryElement geometryElement, string ifcEnumType,
                                             ProductWrapper productWrapper)
        {
            if (geometryElement == null)
            {
                return;
            }

            bool exportParts = PartExporter.CanExportParts(slabElement);

            IFCFile file = exporterIFC.GetFile();
            IList <IFCAnyHandle> slabHnds        = new List <IFCAnyHandle>();
            IList <IFCAnyHandle> brepSlabHnds    = new List <IFCAnyHandle>();
            IList <IFCAnyHandle> nonBrepSlabHnds = new List <IFCAnyHandle>();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                using (IFCTransformSetter transformSetter = IFCTransformSetter.Create())
                {
                    using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, slabElement))
                    {
                        IFCAnyHandle localPlacement = placementSetter.LocalPlacement;
                        IFCAnyHandle ownerHistory   = exporterIFC.GetOwnerHistoryHandle();
                        bool         exportedAsInternalExtrusion = false;

                        ElementId catId = CategoryUtil.GetSafeCategoryId(slabElement);

                        IList <IFCAnyHandle>             prodReps        = new List <IFCAnyHandle>();
                        IList <ShapeRepresentationType>  repTypes        = new List <ShapeRepresentationType>();
                        IList <IList <CurveLoop> >       extrusionLoops  = new List <IList <CurveLoop> >();
                        IList <IFCExtrusionCreationData> loopExtraParams = new List <IFCExtrusionCreationData>();
                        Plane floorPlane = GeometryUtil.CreateDefaultPlane();

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

                        using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData())
                        {
                            BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true);
                            bodyExporterOptions.TessellationLevel = BodyExporter.GetTessellationLevel();
                            BodyData     bodyData;
                            IFCAnyHandle prodDefHnd = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC,
                                                                                                                 slabElement, catId, geometryElement, bodyExporterOptions, null, ecData, out bodyData);
                            if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodDefHnd))
                            {
                                ecData.ClearOpenings();
                                return;
                            }

                            prodReps.Add(prodDefHnd);
                            repTypes.Add(bodyData.ShapeRepresentationType);
                        }

                        // Create the slab from either the extrusion or the BRep information.
                        string ifcGUID = GUIDUtil.CreateGUID(slabElement);

                        int numReps = exportParts ? 1 : prodReps.Count;

                        string entityType = IFCValidateEntry.GetValidIFCType <IFCSlabType>(slabElement, ifcEnumType, "FLOOR");

                        for (int ii = 0; ii < numReps; ii++)
                        {
                            string ifcName        = NamingUtil.GetNameOverride(slabElement, NamingUtil.GetIFCNamePlusIndex(slabElement, ii == 0 ? -1 : ii + 1));
                            string ifcDescription = NamingUtil.GetDescriptionOverride(slabElement, null);
                            string ifcObjectType  = NamingUtil.GetObjectTypeOverride(slabElement, exporterIFC.GetFamilyName());
                            string ifcTag         = NamingUtil.GetTagOverride(slabElement, NamingUtil.CreateIFCElementId(slabElement));

                            string       currentGUID       = (ii == 0) ? ifcGUID : GUIDUtil.CreateGUID();
                            IFCAnyHandle localPlacementHnd = exportedAsInternalExtrusion ? localPlacements[ii] : localPlacement;

                            IFCAnyHandle slabHnd = IFCInstanceExporter.CreateSlab(file, currentGUID, ownerHistory, ifcName,
                                                                                  ifcDescription, ifcObjectType, localPlacementHnd, exportParts ? null : prodReps[ii],
                                                                                  ifcTag, entityType);

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

                            if (exportParts)
                            {
                                PartExporter.ExportHostPart(exporterIFC, slabElement, slabHnd, productWrapper, placementSetter, localPlacementHnd, null);
                            }

                            slabHnds.Add(slabHnd);

                            if (!exportParts)
                            {
                                if (repTypes[ii] == ShapeRepresentationType.Brep)
                                {
                                    brepSlabHnds.Add(slabHnd);
                                }
                                else
                                {
                                    nonBrepSlabHnds.Add(slabHnd);
                                }
                            }
                        }

                        for (int ii = 0; ii < numReps; ii++)
                        {
                            IFCExtrusionCreationData loopExtraParam = ii < loopExtraParams.Count ? loopExtraParams[ii] : null;
                            productWrapper.AddElement(slabElement, slabHnds[ii], placementSetter, loopExtraParam, true);
                        }

                        if (exportedAsInternalExtrusion)
                        {
                            ExporterIFCUtils.ExportExtrudedSlabOpenings(exporterIFC, slabElement, placementSetter.LevelInfo,
                                                                        localPlacements[0], slabHnds, extrusionLoops, floorPlane, productWrapper.ToNative());
                        }
                    }

                    if (!exportParts)
                    {
                        if (slabElement is HostObject)
                        {
                            HostObject hostObject = slabElement as HostObject;
                            if (nonBrepSlabHnds.Count > 0)
                            {
                                HostObjectExporter.ExportHostObjectMaterials(exporterIFC, hostObject, nonBrepSlabHnds,
                                                                             geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, false);
                            }
                            if (brepSlabHnds.Count > 0)
                            {
                                HostObjectExporter.ExportHostObjectMaterials(exporterIFC, hostObject, brepSlabHnds,
                                                                             geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, true);
                            }
                        }
                        else if (slabElement is FamilyInstance && slabHnds.Count > 0)
                        {
                            ElementId matId = BodyExporter.GetBestMaterialIdFromGeometryOrParameter(geometryElement, exporterIFC, slabElement);
                            Document  doc   = slabElement.Document;
                            foreach (IFCAnyHandle slabHnd in slabHnds)
                            {
                                CategoryUtil.CreateMaterialAssociation(exporterIFC, slabHnd, matId);
                            }
                        }
                    }
                }
                tr.Commit();

                return;
            }
        }
Esempio n. 28
0
        private async Task doFetch(TaskCompletionSource <HttpResponseMessage> tcs, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try {
                var requestObject = new JSObject();

                if (request.Properties.TryGetValue("WebAssemblyFetchOptions", out var fetchOoptionsValue) &&
                    fetchOoptionsValue is IDictionary <string, object> fetchOptions)
                {
                    foreach (var item in fetchOptions)
                    {
                        requestObject.SetObjectProperty(item.Key, item.Value);
                    }
                }

                requestObject.SetObjectProperty("method", request.Method.Method);

                // We need to check for body content
                if (request.Content != null)
                {
                    if (request.Content is StringContent)
                    {
                        requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync());
                    }
                    else
                    {
                        // 2.1.801 seems to have a problem with the line
                        // using (var uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync ()))
                        // so we split it up into two lines.
                        var byteAsync = await request.Content.ReadAsByteArrayAsync();

                        using (var uint8Buffer = Uint8Array.From(byteAsync))
                        {
                            requestObject.SetObjectProperty("body", uint8Buffer);
                        }
                    }
                }

                // Process headers
                // Cors has it's own restrictions on headers.
                // https://developer.mozilla.org/en-US/docs/Web/API/Headers
                using (var jsHeaders = new HostObject("Headers")) {
                    if (request.Headers != null)
                    {
                        foreach (var header in request.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                jsHeaders.Invoke("append", header.Key, value);
                            }
                        }
                    }
                    if (request.Content?.Headers != null)
                    {
                        foreach (var header in request.Content.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                jsHeaders.Invoke("append", header.Key, value);
                            }
                        }
                    }
                    requestObject.SetObjectProperty("headers", jsHeaders);
                }

                WasmHttpReadStream wasmHttpReadStream = null;

                JSObject abortController = new HostObject("AbortController");
                JSObject signal          = (JSObject)abortController.GetObjectProperty("signal");
                requestObject.SetObjectProperty("signal", signal);
                signal.Dispose();

                CancellationTokenSource       abortCts          = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                CancellationTokenRegistration abortRegistration = abortCts.Token.Register((Action)(() => {
                    if (abortController.JSHandle != -1)
                    {
                        abortController.Invoke("abort");
                        abortController?.Dispose();
                    }
                    wasmHttpReadStream?.Dispose();
                }));

                var args = new Runtime.InteropServices.JavaScript.Array();
                args.Push(request.RequestUri.ToString());
                args.Push(requestObject);

                requestObject.Dispose();

                var response = fetch.Invoke("apply", window, args) as Task <object>;
                args.Dispose();
                if (response == null)
                {
                    throw new Exception("Internal error marshalling the response Promise from `fetch`.");
                }

                var t = await response;

                var status = new WasmFetchResponse((JSObject)t, abortController, abortCts, abortRegistration);

                //Console.WriteLine($"bodyUsed: {status.IsBodyUsed}");
                //Console.WriteLine($"ok: {status.IsOK}");
                //Console.WriteLine($"redirected: {status.IsRedirected}");
                //Console.WriteLine($"status: {status.Status}");
                //Console.WriteLine($"statusText: {status.StatusText}");
                //Console.WriteLine($"type: {status.ResponseType}");
                //Console.WriteLine($"url: {status.Url}");

                HttpResponseMessage httpresponse = new HttpResponseMessage((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), status.Status.ToString()));

                var streamingEnabled = request.Properties.TryGetValue("WebAssemblyEnableStreamingResponse", out var streamingEnabledValue) && (bool)streamingEnabledValue;

                httpresponse.Content = StreamingSupported && streamingEnabled
                                        ? new StreamContent(wasmHttpReadStream = new WasmHttpReadStream(status))
                                        : (HttpContent) new WasmHttpContent(status);

                // Fill the response headers
                // CORS will only allow access to certain headers.
                // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors.
                // cors and basic responses are almost identical except that a cors response restricts the headers you can view to
                // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`.
                // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
                //
                // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation
                using (var respHeaders = (JSObject)status.Headers) {
                    if (respHeaders != null)
                    {
                        using (var entriesIterator = (JSObject)respHeaders.Invoke("entries")) {
                            JSObject nextResult = null;
                            try {
                                nextResult = (JSObject)entriesIterator.Invoke("next");
                                while (!(bool)nextResult.GetObjectProperty("done"))
                                {
                                    using (var resultValue = (Runtime.InteropServices.JavaScript.Array)nextResult.GetObjectProperty("value")) {
                                        var name  = (string)resultValue [0];
                                        var value = (string)resultValue [1];
                                        if (!httpresponse.Headers.TryAddWithoutValidation(name, value))
                                        {
                                            if (httpresponse.Content != null)
                                            {
                                                if (!httpresponse.Content.Headers.TryAddWithoutValidation(name, value))
                                                {
                                                    Console.WriteLine($"Warning: Can not add response header for name: {name} value: {value}");
                                                }
                                            }
                                        }
                                    }
                                    nextResult?.Dispose();
                                    nextResult = (JSObject)entriesIterator.Invoke("next");
                                }
                            } finally {
                                nextResult?.Dispose();
                            }
                        }
                    }
                }

                tcs.SetResult(httpresponse);
            } catch (JSException jsExc)  {
                var httpExc = new System.Net.Http.HttpRequestException(jsExc.Message);
                tcs.SetException(httpExc);
            } catch (Exception exception)  {
                tcs.SetException(exception);
            }
        }
Esempio n. 29
0
        private async Task ConnectAsyncJavaScript(Uri uri, CancellationToken cancellationToken)
        {
            var tcsConnect = new TaskCompletionSource <bool> ();

            // For Abort/Dispose.  Calling Abort on the request at any point will close the connection.
            cts.Token.Register(AbortRequest);

            // Wrap the cancellationToken in a using so that it can be disposed of whether
            // we successfully connected or failed trying.
            // Otherwise any timeout/cancellation would apply to the full session.
            // In the failure case we need to release the references and dispose of the objects.
            using (cancellationToken.Register(() => tcsConnect.TrySetCanceled())) {
                try {
                    Core.Array subProtocols = null;
                    if (Options.RequestedSubProtocols.Count > 0)
                    {
                        subProtocols = new Core.Array();
                        foreach (var item in Options.RequestedSubProtocols)
                        {
                            subProtocols.Push(item);
                        }
                    }
                    innerWebSocket = new HostObject("WebSocket", uri.ToString(), subProtocols);

                    subProtocols?.Dispose();

                    // Setup the onError callback
                    onError = new Action <JSObject> ((errorEvt) => {
                        errorEvt.Dispose();
                    });

                    // Attach the onError callback
                    innerWebSocket.SetObjectProperty("onerror", onError);

                    // Setup the onClose callback
                    onClose = new Action <JSObject> ((closeEvt) => {
                        innerWebSocketCloseStatus            = (WebSocketCloseStatus)closeEvt.GetObjectProperty("code");
                        innerWebSocketCloseStatusDescription = closeEvt.GetObjectProperty("reason")?.ToString();
                        var mess = new ReceivePayload(WebSocketHelpers.EmptyPayload, WebSocketMessageType.Close);
                        receiveMessageQueue.BufferPayload(mess);

                        if (!tcsConnect.Task.IsCanceled && !tcsConnect.Task.IsCompleted && !tcsConnect.Task.IsFaulted)
                        {
                            tcsConnect.SetException(new WebSocketException(WebSocketError.NativeError));
                        }
                        else
                        {
                            tcsClose?.SetResult(true);
                        }

                        closeEvt.Dispose();
                    });

                    // Attach the onClose callback
                    innerWebSocket.SetObjectProperty("onclose", onClose);

                    // Setup the onOpen callback
                    onOpen = new Action <JSObject> ((evt) => {
                        if (!cancellationToken.IsCancellationRequested)
                        {
                            // Change internal state to 'connected' to enable the other methods
                            if (Interlocked.CompareExchange(ref state, connected, connecting) != connecting)
                            {
                                // Aborted/Disposed during connect.
                                throw new ObjectDisposedException(GetType().FullName);
                            }

                            tcsConnect.SetResult(true);
                        }

                        evt.Dispose();
                    });

                    // Attach the onOpen callback
                    innerWebSocket.SetObjectProperty("onopen", onOpen);

                    // Setup the onMessage callback
                    onMessage = new Action <JSObject> ((messageEvent) => {
                        ThrowIfNotConnected();

                        // get the events "data"
                        var eventData = messageEvent.GetObjectProperty("data");

                        // If the messageEvent's data property is marshalled as a JSObject then we are dealing with
                        // binary data
                        if (eventData is JSObject)
                        {
                            // TODO: Handle ArrayBuffer binary type but have only seen 'blob' so far without
                            // changing the default websocket binary type manually.
                            if (innerWebSocket.GetObjectProperty("binaryType").ToString() == "blob")
                            {
                                Action <JSObject> loadend = null;
                                // Create a new "FileReader" object
                                using (var reader = new HostObject("FileReader")) {
                                    loadend = new Action <JSObject> ((loadEvent) => {
                                        using (var target = (JSObject)loadEvent.GetObjectProperty("target")) {
                                            if ((int)target.GetObjectProperty("readyState") == 2)
                                            {
                                                using (var binResult = (ArrayBuffer)target.GetObjectProperty("result")) {
                                                    var mess = new ReceivePayload(binResult, WebSocketMessageType.Binary);
                                                    receiveMessageQueue.BufferPayload(mess);
                                                    Runtime.FreeObject(loadend);
                                                }
                                            }
                                        }
                                        loadEvent.Dispose();
                                    });

                                    reader.Invoke("addEventListener", "loadend", loadend);

                                    using (var blobData = (JSObject)messageEvent.GetObjectProperty("data"))
                                        reader.Invoke("readAsArrayBuffer", blobData);
                                }
                            }
                            else
                            {
                                throw new NotImplementedException($"WebSocket bynary type '{innerWebSocket.GetObjectProperty ("binaryType").ToString ()}' not supported.");
                            }
                        }
                        else if (eventData is string)
                        {
                            var mess = new ReceivePayload(Encoding.UTF8.GetBytes(((string)eventData).ToString()), WebSocketMessageType.Text);
                            receiveMessageQueue.BufferPayload(mess);
                        }
                        messageEvent.Dispose();
                    });

                    // Attach the onMessage callaback
                    innerWebSocket.SetObjectProperty("onmessage", onMessage);

                    await tcsConnect.Task;
                } catch (Exception wse) {
                    ConnectExceptionCleanup();
                    WebSocketException wex = new WebSocketException("WebSocket connection failure.", wse);
                    throw wex;
                }
            }
        }
 public override void Initialize(HostObject hostObj)
 {
     _host = hostObj;
 }
Esempio n. 31
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 IFCProductWrapper.
        /// </param>
        /// <param name="levelId">
        /// The level id.
        /// </param>
        /// <param name="direction">
        /// The IFCLayerSetDirection.
        /// </param>
        /// <returns>
        /// True if exported successfully, false otherwise.
        /// </returns>
        public static bool ExportHostObjectMaterials(ExporterIFC exporterIFC, HostObject hostObject,
                                                     IList <IFCAnyHandle> elemHnds, GeometryElement geometryElement, IFCProductWrapper productWrapper,
                                                     ElementId levelId, Toolkit.IFCLayerSetDirection direction)
        {
            if (hostObject == null)
            {
                return(true); //nothing to do
            }
            if (elemHnds == null || (elemHnds.Count == 0))
            {
                return(true); //nothing to do
            }
            IFCFile file = exporterIFC.GetFile();

            // Roofs with no components are only allowed one material.  We will arbitrarily choose the thickest material.
            IFCAnyHandle primaryMaterialHnd = null;

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

                double scale = exporterIFC.LinearScale;

                double scaledOffset = 0.0, scaledWallWidth = 0.0, wallHeight = 0.0;
                Wall   wall = hostObject as Wall;
                if (wall != null)
                {
                    scaledWallWidth = wall.Width * scale;
                    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);
                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 IFCProductWrapper,
                            // 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);
                    }

                    List <IFCAnyHandle> layers = new List <IFCAnyHandle>();
                    double thickestLayer       = 0.0;
                    for (int i = 0; i < matIds.Count; ++i)
                    {
                        if (widths[i] < MathUtil.Eps())
                        {
                            continue;
                        }

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

                        double       scaledWidth   = widths[i] * scale;
                        IFCAnyHandle materialLayer = IFCInstanceExporter.CreateMaterialLayer(file, materialHnd, scaledWidth, null);
                        layers.Add(materialLayer);
                        if ((productWrapper != null) && (functions[i] == MaterialFunctionAssignment.Finish1 || functions[i] == MaterialFunctionAssignment.Finish2))
                        {
                            productWrapper.AddFinishMaterial(materialHnd);
                        }
                    }

                    if (layers.Count == 0)
                    {
                        return(false);
                    }

                    string layerSetName = NamingUtil.CreateIFCFamilyName(exporterIFC, -1);
                    materialLayerSet = IFCInstanceExporter.CreateMaterialLayerSet(file, layers, layerSetName);

                    ExporterCacheManager.MaterialLayerSetCache.Register(typeElemId, materialLayerSet);
                }

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

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

                    IList <IFCAnyHandle> subElemHnds = new List <IFCAnyHandle>();
                    if (relDecomposesSet != null && relDecomposesSet.Count == 1)
                    {
                        IFCAnyHandle relAggregates = relDecomposesSet.First();
                        if (IFCAnyHandleUtil.IsTypeOf(relAggregates, IFCEntityType.IfcRelAggregates))
                        {
                            IFCData ifcData = relAggregates.GetAttribute("RelatedObjects");
                            if (ifcData.PrimitiveType == IFCDataPrimitiveType.Aggregate)
                            {
                                IFCAggregate aggregate = ifcData.AsAggregate();
                                if (aggregate != null && aggregate.Count > 0)
                                {
                                    foreach (IFCData val in aggregate)
                                    {
                                        if (val.PrimitiveType == IFCDataPrimitiveType.Instance)
                                        {
                                            subElemHnds.Add(val.AsInstance());
                                        }
                                    }
                                }
                            }
                        }
                    }

                    bool hasSubElems = !(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);
                        }
                    }

                    exporterIFC.RegisterSpaceBoundingElementHandle(elemHnd, hostObject.Id, levelId);
                }

                tr.Commit();
                return(true);
            }
        }
Esempio n. 32
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. 33
0
        public void BindSignature_General()
        {
            var typeArgs1 = new[]
            {
                typeof(Random),
                typeof(string),
                typeof(Dictionary <string, DateTime>)
            };

            var typeArgs2 = new[]
            {
                typeof(Random),
                typeof(string),
                typeof(Dictionary <string, TimeSpan>)
            };

            var args1 = new object[]
            {
                int.MinValue,
                Math.E,
                "blah",
                new OutArg <DateTime>(DateTime.MinValue),
                new RefArg <TimeSpan>(TimeSpan.MinValue),
                DayOfWeek.Sunday
            };

            var args2 = new object[]
            {
                int.MaxValue,
                Math.PI,
                "meh",
                new OutArg <DateTime>(DateTime.MaxValue),
                new RefArg <TimeSpan>(TimeSpan.MaxValue),
                DayOfWeek.Saturday
            };

            {
                var sig1 = new BindSignature(HostType.Wrap(typeof(string)), "foo", typeArgs1, args1);
                var sig2 = new BindSignature(new HostVariable <string>(null), "foo", typeArgs1, args1);
                AssertNotEqual(sig1, sig2);
            }

            {
                var sig1 = new BindSignature(new HostVariable <string>(null), "foo", typeArgs1, args1);
                var sig2 = new BindSignature(HostObject.Wrap("baz"), "foo", typeArgs1, args1);
                AssertNotEqual(sig1, sig2);
            }

            {
                var sig1 = new BindSignature(HostType.Wrap(typeof(string)), "foo", typeArgs1, args1);
                var sig2 = new BindSignature(HostObject.Wrap("baz"), "foo", typeArgs1, args1);
                AssertNotEqual(sig1, sig2);
            }

            {
                var sig1 = new BindSignature(new HostVariable <string>(null), "foo", typeArgs1, args1);
                var sig2 = new BindSignature(new HostVariable <string>("baz"), "foo", typeArgs1, args1);
                AssertNotEqual(sig1, sig2);
            }

            {
                var sig1 = new BindSignature(new HostVariable <string>("baz"), "foo", typeArgs1, args1);
                var sig2 = new BindSignature(HostObject.Wrap("qux"), "foo", typeArgs1, args1);
                AssertEqual(sig1, sig2);
            }

            {
                var sig1 = new BindSignature(HostType.Wrap(typeof(string)), "foo", typeArgs1, args1);
                var sig2 = new BindSignature(HostType.Wrap(typeof(string)), "bar", typeArgs1, args1);
                AssertNotEqual(sig1, sig2);
            }

            {
                var sig1 = new BindSignature(HostType.Wrap(typeof(string)), "foo", typeArgs1, args1);
                var sig2 = new BindSignature(HostType.Wrap(typeof(string)), "foo", typeArgs2, args1);
                AssertNotEqual(sig1, sig2);
            }

            {
                var sig1 = new BindSignature(HostType.Wrap(typeof(string)), "foo", typeArgs1, args1);
                var sig2 = new BindSignature(HostType.Wrap(typeof(string)), "foo", typeArgs1, args2);
                AssertEqual(sig1, sig2);
            }
        }
Esempio n. 34
0
        public static List <Panel> ToSAM(this HostObject hostObject, ConvertSettings convertSettings)
        {
            if (hostObject == null || !hostObject.IsValidObject)
            {
                return(null);
            }

            List <Panel> result = convertSettings?.GetObjects <Panel>(hostObject.Id);

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

            ElementId elementId_Type = hostObject.GetTypeId();

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

            result = new List <Panel>();

            PanelType    panelType    = Query.PanelType(hostObject);
            Construction construction = ((HostObjAttributes)hostObject.Document.GetElement(elementId_Type)).ToSAM(convertSettings);

            if (construction == null)
            {
                construction = Analytical.Query.DefaultConstruction(panelType); //Default Construction
            }
            PanelType panelType_Temp = Query.PanelType(construction);

            if (panelType_Temp != PanelType.Undefined)
            {
                panelType = panelType_Temp;
            }

            List <Geometry.Spatial.Face3D> face3Ds = hostObject.Profiles();

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

            LogicalOrFilter logicalOrFilter = new LogicalOrFilter(new List <ElementFilter>()
            {
                new ElementCategoryFilter(BuiltInCategory.OST_Windows), new ElementCategoryFilter(BuiltInCategory.OST_Doors)
            });
            IEnumerable <ElementId> elementIds = hostObject.GetDependentElements(logicalOrFilter);

            if (hostObject is Wall)
            {
                List <Autodesk.Revit.DB.Panel> panels = Create.Panels((Wall)hostObject, convertSettings);
                if (panels != null && panels.Count > 0)
                {
                    List <ElementId> elementIds_Temp = panels.ConvertAll(x => x.Id);
                    if (elementIds != null && elementIds.Count() > 0)
                    {
                        elementIds_Temp.AddRange(elementIds);
                    }

                    elementIds = elementIds_Temp;
                }
            }

            foreach (Geometry.Spatial.Face3D face3D in face3Ds)
            {
                if (face3D == null)
                {
                    continue;
                }

                Panel panel = new Panel(construction, panelType, face3D);
                panel.UpdateParameterSets(hostObject, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));

                if (elementIds != null && elementIds.Count() > 0)
                {
                    foreach (ElementId elementId in elementIds)
                    {
                        Element element = hostObject.Document.GetElement(elementId);
                        if (element == null)
                        {
                            continue;
                        }

                        if (!(element is FamilyInstance))
                        {
                            continue;
                        }

                        Aperture aperture = ToSAM_Aperture((FamilyInstance)element, convertSettings);
                        panel.AddAperture(aperture);
                    }
                }

                result.Add(panel);
            }

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

            return(result);
        }
Esempio n. 35
0
        public static List <Panel> ToSAM(this HostObject hostObject, ConvertSettings convertSettings)
        {
            if (hostObject == null || !hostObject.IsValidObject)
            {
                return(null);
            }

            if (hostObject is WallSweep)
            {
                return(((WallSweep)hostObject).ToSAM_Panels(convertSettings));
            }

            List <Panel> result = convertSettings?.GetObjects <Panel>(hostObject.Id);

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

            ElementId elementId_Type = hostObject.GetTypeId();

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

            Document document = hostObject.Document;

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

            result = new List <Panel>();

            PanelType    panelType    = Query.PanelType(hostObject);
            Construction construction = ((HostObjAttributes)document.GetElement(elementId_Type)).ToSAM(convertSettings);

            if (construction == null)
            {
                construction = Analytical.Query.DefaultConstruction(panelType); //Default Construction
            }
            PanelType panelType_Temp = Query.PanelType(construction);

            if (panelType_Temp != PanelType.Undefined)
            {
                panelType = panelType_Temp;
            }

            List <Face3D> face3Ds = hostObject.Profiles();

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

            LogicalOrFilter logicalOrFilter = new LogicalOrFilter(new List <ElementFilter>()
            {
                new ElementCategoryFilter(BuiltInCategory.OST_Windows), new ElementCategoryFilter(BuiltInCategory.OST_Doors)
            });

#if Revit2017
            IEnumerable <ElementId> elementIds = null;
#else
            IEnumerable <ElementId> elementIds = hostObject.GetDependentElements(logicalOrFilter);
#endif

            if (hostObject is Autodesk.Revit.DB.Wall || hostObject is CurtainSystem)
            {
                List <Autodesk.Revit.DB.Panel> panels = Core.Revit.Query.Panels(hostObject as dynamic);
                if (panels != null && panels.Count > 0)
                {
                    List <ElementId> elementIds_Temp = panels.ConvertAll(x => x.Id);
                    if (elementIds != null && elementIds.Count() > 0)
                    {
                        elementIds_Temp.AddRange(elementIds);
                    }

                    elementIds = elementIds_Temp;
                }
            }

            List <Aperture> apertures = new List <Aperture>();
            if (elementIds != null && elementIds.Count() > 0)
            {
                foreach (ElementId elementId in elementIds)
                {
                    FamilyInstance familyInstance = document.GetElement(elementId) as FamilyInstance;
                    if (familyInstance == null)
                    {
                        continue;
                    }

                    List <Aperture> apertures_Temp = ToSAM_Apertures(familyInstance, convertSettings);
                    if (apertures_Temp == null)
                    {
                        continue;
                    }

                    apertures.AddRange(apertures_Temp);
                }
            }


            foreach (Face3D face3D in face3Ds)
            {
                if (face3D == null)
                {
                    continue;
                }

                //Panel panel = Analytical.Create.Panel(construction, panelType, face3D.Reduce(0.2)); Double check why Reduce have been used turn off on 27.10.2021 when mesh roof in sam teplate gave gap
                Panel panel = Analytical.Create.Panel(construction, panelType, face3D);
                panel.UpdateParameterSets(hostObject, ActiveSetting.Setting.GetValue <Core.TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));

                foreach (Aperture aperture in apertures)
                {
                    panel.AddAperture(aperture);
                }

                result.Add(panel);
            }

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

            //Handling WallSweeps
            //if(hostObject is Wall)
            //{
            //    elementIds = hostObject.GetDependentElements(new ElementCategoryFilter(BuiltInCategory.OST_Cornices));
            //    if (elementIds != null && elementIds.Count() != 0)
            //    {
            //        //Fix it
            //        foreach (ElementId elementId in elementIds)
            //        {
            //            WallSweep wallSweep = document.GetElement(elementId) as WallSweep;
            //            if (wallSweep == null)
            //            {
            //                continue;
            //            }

            //            List<Panel> panels_WallSweep = wallSweep.ToSAM_Panels(convertSettings);
            //            if (panels_WallSweep == null || panels_WallSweep.Count == 0)
            //            {
            //                continue;
            //            }

            //            result.AddRange(panels_WallSweep);
            //        }
            //    }
            //}

            return(result);
        }
Esempio n. 36
0
        /***************************************************/
        /****             Fallback methods              ****/
        /***************************************************/

        private static List <CurtainGrid> CurtainGrids(this HostObject hostObject)
        {
            return(new List <CurtainGrid>());
        }
Esempio n. 37
0
        private void Stream( ArrayList data, HostObject hostObj )
        {
            data.Add( new Snoop.Data.ClassSeparator( typeof( HostObject ) ) );

              Wall wall = hostObj as Wall;
              if( wall != null )
              {
            Stream( data, wall );
            return;
              }

              CeilingAndFloor ceilFloor = hostObj as CeilingAndFloor;
              if( ceilFloor != null )
              {
            Stream( data, ceilFloor );
            return;
              }

              WallFoundation contFooting = hostObj as WallFoundation;
              if( contFooting != null )
              {
            Stream( data, contFooting );
            return;
              }

              CurtainGridLine gridLine = hostObj as CurtainGridLine;
              if( gridLine != null )
              {
            Stream( data, gridLine );
            return;
              }

              CurtainSystemBase curtainSysBase = hostObj as CurtainSystemBase;
              if( curtainSysBase != null )
              {
            Stream( data, curtainSysBase );
            return;
              }

              HostedSweep hostedSweep = hostObj as HostedSweep;
              if( hostedSweep != null )
              {
            Stream( data, hostedSweep );
            return;
              }

              RoofBase roofBase = hostObj as RoofBase;
              if( roofBase != null )
              {
            Stream( data, roofBase );
            return;
              }

              MEPCurve mepCur = hostObj as MEPCurve;
              if( mepCur != null )
              {
            Stream( data, mepCur );
            return;
              }

              Wire wire = hostObj as Wire;
              if( wire != null )
              {
            Stream( data, wire );
            return;
              }
        }
Esempio n. 38
0
        /***************************************************/
        /****            Interface methods              ****/
        /***************************************************/

        public static List <CurtainGrid> ICurtainGrids(this HostObject hostObject)
        {
            return(CurtainGrids(hostObject as dynamic));
        }
        private void Initialize(bool isDoor, bool isWindow, FamilyInstance famInst, HostObject hostObject)
        {
            HostObject = hostObject;
            InsertInstance = famInst;

            ExportingDoor = isDoor;
            if (isDoor) 
		        PreDefinedType = "DOOR";

            ExportingWindow = isWindow;
            if (isWindow) 
		        PreDefinedType = "WINDOW";

            FlippedSymbol = false;

            DoorOperationTypeString = "NOTDEFINED";
            WindowPartitioningTypeString = "NOTDEFINED";

            FlippedX = (famInst == null) ? false : famInst.HandFlipped;
            FlippedY = (famInst == null) ? false : famInst.FacingFlipped;

            Wall wall = (hostObject == null) ? null : hostObject as Wall;
            Curve centerCurve = WallExporter.GetWallAxis(wall);
            HasRealWallHost = ((wall != null) && (centerCurve != null) && ((centerCurve is Line) || (centerCurve is Arc)));
        }
 public static DoorWindowInfo CreateWindow(ExporterIFC exporterIFC, FamilyInstance famInst, HostObject hostObj,
                                           ElementId overrideLevelId, Transform trf)
 {
     return(DoorWindowInfo.CreateWindow(exporterIFC, famInst, hostObj, overrideLevelId, trf));
 }
        /// <summary>
        /// Exports materials for host object.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="hostObject">The host object.</param>
        /// <param name="elemHnd">The host IFC handle.</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.  If null, we will calculate.</param>
        /// <returns>True if exported successfully, false otherwise.</returns>
        public static bool ExportHostObjectMaterials(ExporterIFC exporterIFC, HostObject hostObject,
            IFCAnyHandle elemHnd, GeometryElement geometryElement, ProductWrapper productWrapper,
            ElementId levelId, Toolkit.IFCLayerSetDirection direction, bool? containsBRepGeometry)
        {
            IList<IFCAnyHandle> elemHnds = new List<IFCAnyHandle>();
            elemHnds.Add(elemHnd);

            // Setting doesContainBRepGeometry to false below preserves the original behavior that we created IfcMaterialLists for all geometries.
            // TODO: calculate, or pass in, a valid bool value for Ceilings, Roofs, and Wall Sweeps.
            bool doesContainBRepGeometry = containsBRepGeometry.HasValue ? containsBRepGeometry.Value : false;
            return ExportHostObjectMaterials(exporterIFC, hostObject, elemHnds, geometryElement, productWrapper, levelId, direction, doesContainBRepGeometry);
        }
        /// <summary>
        /// Export Curtain Walls and Roofs.
        /// </summary>
        /// <param name="exporterIFC">
        /// The ExporterIFC object.
        /// </param>
        /// <param name="allSubElements">
        /// Collection of elements contained in the host curtain element.
        /// </param>
        /// <param name="hostElement">
        /// The host element to be exported.
        /// </param>
        /// <param name="productWrapper">
        /// The IFCProductWrapper.
        /// </param>
        public static void ExportBase(ExporterIFC exporterIFC, ElementSet allSubElements,
           HostObject hostElement, IFCProductWrapper wrapper)
        {
            IFCFile file = exporterIFC.GetFile();
            IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle();

            IFCPlacementSetter setter = null;
            IFCProductWrapper curtainWallSubWrapper = null;
            try
            {
                IFCAnyHandle localPlacement = IFCAnyHandle.Create();
                bool canExportCurtainWallAsContainer = CanExportCurtainWallAsContainer(allSubElements);
                IFCAnyHandle rep = IFCAnyHandle.Create();
                if (canExportCurtainWallAsContainer)
                {
                    curtainWallSubWrapper = IFCProductWrapper.Create(exporterIFC, true);
                    setter = IFCPlacementSetter.Create(exporterIFC, hostElement);
                    localPlacement = setter.GetPlacement();
                    rep = ExportCurtainObjectCommonAsOneBRep(allSubElements, hostElement, exporterIFC, setter, localPlacement);
                }
                else
                {
                    ExportCurtainObjectCommonAsContainer(allSubElements, hostElement, exporterIFC, out curtainWallSubWrapper);
                    // This has to go LAST.  Why?  Because otherwise we apply the level transform twice -- once in the familyTrf, once here.
                    // This will be used just to put the CurtainWall on the right level.
                    setter = IFCPlacementSetter.Create(exporterIFC, hostElement);
                    localPlacement = setter.GetPlacement();
                }

                if (!rep.HasValue)
                    return;

                IFCLabel objectType = NamingUtil.CreateIFCObjectName(exporterIFC, hostElement);

                IFCExtrusionCreationData extraParams = new IFCExtrusionCreationData();
                extraParams.SetLocalPlacement(localPlacement);

                IFCAnyHandle prodRepHnd = IFCAnyHandle.Create();
                IFCAnyHandle elemHnd = IFCAnyHandle.Create();
                IFCLabel elemGUID = IFCLabel.CreateGUID(hostElement);
                IFCLabel elemName = NamingUtil.GetNameOverride(hostElement, exporterIFC.GetNameFromExportState());
                IFCLabel elemDesc = NamingUtil.GetDescriptionOverride(hostElement, IFCLabel.Create());
                IFCLabel elemType = NamingUtil.GetObjectTypeOverride(hostElement, objectType);
                IFCLabel elemId = NamingUtil.CreateIFCElementId(hostElement);
                if (hostElement is Wall || hostElement is CurtainSystem)
                {
                    elemHnd = file.CreateCurtainWall(elemGUID, ownerHistory, elemName, elemDesc, elemType, localPlacement, elemId, prodRepHnd);
                }
                else if (hostElement is RoofBase)
                {
                    string ifcEnumType = CategoryUtil.GetIFCEnumTypeName(exporterIFC, hostElement);
                    elemHnd = file.CreateRoof(elemGUID, ownerHistory, elemName, elemDesc, elemType, localPlacement, elemId, ifcEnumType, prodRepHnd);
                }
                else
                {
                    return;
                }

                if (!elemHnd.HasValue)
                    return;

                wrapper.AddElement(elemHnd, setter, extraParams, true);
                OpeningUtil.CreateOpeningsIfNecessary(elemHnd, hostElement, extraParams, exporterIFC, localPlacement, setter, wrapper);

                ExporterIFCUtils.CreateCurtainWallPropertySet(exporterIFC, hostElement, wrapper);
                ICollection<IFCAnyHandle> relatedElementIds = curtainWallSubWrapper.GetAllObjects();
                if (relatedElementIds.Count > 0)
                {
                    IFCLabel guid = IFCLabel.CreateGUID();
                    IFCLabel nameOpt = IFCLabel.Create();
                    IFCLabel descOpt = IFCLabel.Create();
                    file.CreateRelAggregates(guid, ownerHistory, nameOpt, descOpt, elemHnd, relatedElementIds);
                }
                exporterIFC.RegisterSpaceBoundingElementHandle(elemHnd, hostElement.Id, ElementId.InvalidElementId);
            }
            finally
            {
                if (setter != null)
                    setter.Dispose();
                if (curtainWallSubWrapper != null)
                    curtainWallSubWrapper.Dispose();
            }
        }
        /// <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. 44
0
 /// <summary>
 /// Exports materials for host object.
 /// </summary>
 /// <param name="exporterIFC">
 /// The ExporterIFC object.
 /// </param>
 /// <param name="hostObject">
 /// The host object.
 /// </param>
 /// <param name="elemHnd">
 /// The host IFC handle.
 /// </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>
 /// <returns>
 /// True if exported successfully, false otherwise.
 /// </returns>
 public static bool ExportHostObjectMaterials(ExporterIFC exporterIFC, HostObject hostObject,
     IFCAnyHandle elemHnd, GeometryElement geometryElement, ProductWrapper productWrapper,
     ElementId levelId, Toolkit.IFCLayerSetDirection direction)
 {
     IList<IFCAnyHandle> elemHnds = new List<IFCAnyHandle>();
     elemHnds.Add(elemHnd);
     return ExportHostObjectMaterials(exporterIFC, hostObject, elemHnds, geometryElement, productWrapper, levelId, direction);
 }
        public static ScriptEngine AddHostObject(this ScriptEngine engine, HostObject hostObject)
        {
            engine.AddHostObject(hostObject.Name, hostObject.Flags, hostObject.Target);

            return engine;
        }
Esempio n. 46
0
        /// <summary>
        /// Gets the material ids of the host object.
        /// </summary>
        /// <param name="hostObject">The host object.</param>
        /// <returns>The material ids.</returns>
        public static IList<ElementId> GetMaterialIds(HostObject hostObject)
        {
            ElementId typeElemId = hostObject.GetTypeId();
            HostObjAttributes hostObjAttr = hostObject.Document.GetElement(typeElemId) as HostObjAttributes;
            if (hostObjAttr == null)
                return null;

            CompoundStructure cs = hostObjAttr.GetCompoundStructure();
            IList<ElementId> matIds = new List<ElementId>();
            if (cs != null)
            {
                ElementId baseMatId = CategoryUtil.GetBaseMaterialIdForElement(hostObject);

                for (int i = 0; i < cs.LayerCount; ++i)
                {
                    ElementId matId = cs.GetMaterialId(i);
                    if (matId != ElementId.InvalidElementId)
                    {
                        matIds.Add(matId);
                    }
                    else
                    {
                        matIds.Add(baseMatId);
                    }
                }
            }

            return matIds;
        }
 public static DoorWindowInfo CreateWindow(ExporterIFC exporterIFC, FamilyInstance famInst, HostObject hostObj,
     ElementId overrideLevelId, Transform trf)
 {
     return DoorWindowInfo.CreateWindow(exporterIFC, famInst, hostObj, overrideLevelId, trf);
 }
Esempio n. 48
0
        public static List <Face3D> Profiles(this HostObject hostObject, ElementId generatingElementId)
        {
            if (hostObject == null || generatingElementId == null)
            {
                return(null);
            }

            List <Face3D> face3Ds_HostObject = Profiles(hostObject);

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

            List <Face3D> face3Ds_GeneratingElement = hostObject.Face3Ds(generatingElementId);

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

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

            foreach (Face3D face3D_HostObject in face3Ds_HostObject)
            {
                if (face3D_HostObject == null)
                {
                    continue;
                }

                PlanarIntersectionResult planarIntersectionResult = Spatial.Create.PlanarIntersectionResult(face3D_HostObject, face3Ds_GeneratingElement);
                if (planarIntersectionResult == null || !planarIntersectionResult.Intersecting)
                {
                    continue;
                }

                List <Face3D> face3Ds_Temp = planarIntersectionResult.Face3Ds();
                if (face3Ds_Temp != null && face3Ds_Temp.Count != 0)
                {
                    foreach (Face3D face3D in face3Ds_Temp)
                    {
                        if (face3D == null || !face3D.IsValid() || face3D.GetArea() < Core.Tolerance.MacroDistance)
                        {
                            continue;
                        }

                        result.Add(face3D);
                    }
                }

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

                List <ISegmentable2D> segmentable2Ds = planarIntersectionResult.GetGeometry2Ds <ISegmentable2D>();
                if (segmentable2Ds != null && segmentable2Ds.Count > 2)
                {
                    List <Point2D> point2Ds = new List <Point2D>();
                    segmentable2Ds.ForEach(x => point2Ds.AddRange(x.GetPoints()));
                    point2Ds = Planar.Query.ConvexHull(point2Ds);
                    if (point2Ds != null && point2Ds.Count > 2)
                    {
                        Polygon2D polygon2D = new Polygon2D(point2Ds);
                        if (segmentable2Ds.ConvertAll(x => x.GetLength()).Sum() / polygon2D.GetLength() > 0.51)
                        {
                            Rectangle2D rectangle2D = Planar.Create.Rectangle2D(point2Ds);
                            if (rectangle2D != null)
                            {
                                result.Add(new Face3D(planarIntersectionResult.Plane.Convert(rectangle2D)));
                            }
                        }
                    }
                }
            }

            return(result);
        }