private static XbimShapeTriangulation GetMeshes(Xbim3DModelContext context, IIfcProduct product) { XbimShapeTriangulation ifcMesh = null;; var productShape = context.ShapeInstancesOf(product) .Where(p => p.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .Distinct(); if (productShape.Any()) { var shapeInstance = productShape.FirstOrDefault(); var shapeGeometry = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); byte[] data = ((IXbimShapeGeometryData)shapeGeometry).ShapeData; //If you want to get all the faces and triangulation use this using (var stream = new MemoryStream(data)) { using (var reader = new BinaryReader(stream)) { ifcMesh = reader.ReadShapeTriangulation(); } } } return(ifcMesh); }
/***************************************************/ /**** Public Methods ****/ /***************************************************/ public static List <Mesh> Meshes(this XbimShapeInstance instance, Xbim3DModelContext context) { if (instance == null) { BH.Engine.Reflection.Compute.RecordError("The meshes could not be extracted because the IFC element is null."); return(null); } if (context == null) { BH.Engine.Reflection.Compute.RecordError("The meshes could not be extracted because the 3D model context is null."); return(null); } List <Mesh> result; //Instance's geometry XbimShapeGeometry geometry = context.ShapeGeometry(instance); byte[] data = ((IXbimShapeGeometryData)geometry).ShapeData; //If you want to get all the faces and trinagulation use this using (var stream = new MemoryStream(data)) { using (var reader = new BinaryReader(stream)) { XbimShapeTriangulation shape = reader.ReadShapeTriangulation(); result = shape.Meshes(); } } TransformMatrix transform = instance.Transformation.TransformMatrixFromIfc(); return(result.Select(x => x.Transform(transform)).ToList()); }
public static void AddElements(this MeshGeometry3D m, IPersistIfcEntity item, XbimMatrix3D wcsTransform) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null || !(item is IfcProduct)) { return; } switch (fromModel.GeometrySupportLevel) { case 2: var context = new Xbim3DModelContext(fromModel); var productShape = context.ShapeInstancesOf((IfcProduct)item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); if (!productShape.Any() && item is IfcFeatureElement) { productShape = context.ShapeInstancesOf((IfcProduct)item) .Where( s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); } if (!productShape.Any()) { return; } foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry)shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } break; case 1: var xm3d = new XbimMeshGeometry3D(); var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh); foreach (var geomData in geomDataSet) { var gd = geomData.TransformBy(wcsTransform); xm3d.Add(gd); } m.Add(xm3d); break; } }
private static void getgeometry(XbimShapeInstance shape, Xbim3DModelContext m_context, int entityLabel, int number_of_shapes) { XbimShapeTriangulation mesh = null; var geometry = m_context.ShapeGeometry(shape); Console.WriteLine($"{"\n"}{GetIndent(11)}{"--Geometry Type: " + geometry.Format}"); var ms = new MemoryStream(((IXbimShapeGeometryData)geometry).ShapeData); var br = new BinaryReader(ms); mesh = br.ReadShapeTriangulation(); mesh = mesh.Transform(((XbimShapeInstance)shape).Transformation); var facesfound = mesh.Faces.ToList(); var number_of_faces = facesfound.Count(); Console.WriteLine($"{"\n"}{GetIndent(11)}{" -----No. of faces on the shape #" + shape.IfcProductLabel + ": " + number_of_faces}"); //used for an ID for each face int face_index = 0; //used for the total number of triangles int number_of_triangles = 0; //write the Faces element with its count xmlWriter.WriteStartElement("Faces"); xmlWriter.WriteAttributeString("NumFaces", number_of_faces.ToString()); foreach (XbimFaceTriangulation f in facesfound) { number_of_triangles = f.TriangleCount; Console.WriteLine($"{"\n"}{GetIndent(13)}{" -----Triangle count on face: " + f.GetType() + " :mesh is " + number_of_triangles}"); face_index++; composetrianglesets(f, mesh, entityLabel, facesfound.Count(), face_index, number_of_triangles, number_of_shapes); } //this ends the faces element in the xml file xmlWriter.WriteEndElement(); //Console.WriteLine($"{"\n"}{GetIndent(13)}{" -----Vertices of the shape: #" + shape.IfcProductLabel}"); //foreach (var v in mesh.Vertices.ToList()) //{ // Console.WriteLine($"{GetIndent(13)}{" --vertex_" + mesh.Vertices.ToList().IndexOf(v) + " : " + Math.Round((double)v.X, 2) + " | " + Math.Round((double)v.Y, 2) + " | " + Math.Round((double)v.Z, 2)}"); //} Console.WriteLine("\n"); }
public static XbimMeshGeometry3D GetMesh(this XbimModel xbimModel, IEnumerable<IPersistIfcEntity> items, XbimMatrix3D wcsTransform) { var m = new XbimMeshGeometry3D(); if (xbimModel.GeometrySupportLevel == 1) { // this is what happens for version 1 of the engine // foreach (var item in items) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null) continue; var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh); foreach (var geomData in geomDataSet) { // todo: add guidance to the TransformBy method so that users can understand how to stop using it (it's marked absolete) geomData.TransformBy(wcsTransform); m.Add(geomData); // todo: what is the modelid value to be passed? } } } else { // this is what happens for version 2 of the engine // foreach (var item in items) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null || !(item is IfcProduct)) continue; var context = new Xbim3DModelContext(fromModel); var productShape = context.ShapeInstancesOf((IfcProduct) item) .Where( s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType) shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry) shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } } } return m; }
private static void getgeometry(XbimShapeInstance shape, Xbim3DModelContext m_context, int entityLabel, int number_OF_Walls) { XbimShapeTriangulation mesh = null; var geometry = m_context.ShapeGeometry(shape); //Console.WriteLine("====" + geometry.GetType()); Console.WriteLine($"{"\n"}{GetIndent(11)}{"--Geometry Type: " + geometry.Format}"); var ms = new MemoryStream(((IXbimShapeGeometryData)geometry).ShapeData); var br = new BinaryReader(ms); mesh = br.ReadShapeTriangulation(); mesh = mesh.Transform(((XbimShapeInstance)shape).Transformation); var facesfound = mesh.Faces.ToList(); Console.WriteLine($"{"\n"}{GetIndent(11)}{" -----No. of faces on the shape #" + shape.IfcProductLabel + ": " + facesfound.Count()}"); int FaceNum = 0; int Triangle_Count = 0; //xmlWriter.WriteElementString("Faces", facesfound.Count().ToString()); xmlWriter.WriteStartElement("Faces"); xmlWriter.WriteAttributeString("NumFaces", facesfound.Count().ToString()); foreach (XbimFaceTriangulation f in facesfound) { Triangle_Count = f.TriangleCount; Console.WriteLine($"{"\n"}{GetIndent(13)}{" -----Triangle count on face: " + f.GetType() + " :mesh is " +Triangle_Count}"); //foreach (var fi in f.Indices) //{ // Console.WriteLine($"{GetIndent(13)}{" -> " + fi}"); //} FaceNum++; composetrianglesets(f, mesh, entityLabel, facesfound.Count(), FaceNum, Triangle_Count, number_OF_Walls); } //this is for the faces NUmber xmlWriter.WriteEndElement(); // xmlWriter.WriteWhitespace("\n"); //Console.WriteLine($"{"\n"}{GetIndent(13)}{" -----Vertices of the shape: #" + shape.IfcProductLabel}"); //foreach (var v in mesh.Vertices.ToList()) //{ // Console.WriteLine($"{GetIndent(13)}{" --vertex_" + mesh.Vertices.ToList().IndexOf(v) + " : " + Math.Round((double)v.X, 2) + " | " + Math.Round((double)v.Y, 2) + " | " + Math.Round((double)v.Z, 2)}"); //} Console.WriteLine("\n"); }
public static void AddElements(this MeshGeometry3D m, IPersistIfcEntity item, XbimMatrix3D wcsTransform) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null || !(item is IfcProduct)) return; switch (fromModel.GeometrySupportLevel) { case 2: var context = new Xbim3DModelContext(fromModel); var productShape = context.ShapeInstancesOf((IfcProduct) item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); if (!productShape.Any() && item is IfcFeatureElement) { productShape = context.ShapeInstancesOf((IfcProduct) item) .Where( s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); } if (!productShape.Any()) return; foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType) shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry) shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } break; case 1: var xm3d = new XbimMeshGeometry3D(); var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh); foreach (var geomData in geomDataSet) { var gd = geomData.TransformBy(wcsTransform); xm3d.Add(gd); } m.Add(xm3d); break; } }
private void GetGeometryData(XbimModel model, IfcProduct product) { var context = new Xbim3DModelContext(model); //TODO: WCS var metre = model.ModelFactors.OneMetre; var units = model.IfcProject.UnitsInContext.Units .Where <IfcSIUnit>(u => u.UnitType == IfcUnitEnum.LENGTHUNIT) .ToList(); string defaultLengthUnit = ""; if (units.Count > 0) { defaultLengthUnit = units.First().GetSymbol(); } var styles = context.SurfaceStyles().ToList(); var productShape = context.ShapeInstancesOf(product) .Where(p => p.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .Distinct(); if (productShape.Any()) { foreach (var shapeInstance in productShape) { var shapeGeometry = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); XbimColour style = XbimColour.Default; if (shapeInstance.HasStyle) { style = styles.First(s => s.DefinedObjectId == shapeInstance.StyleLabel).ColourMap.FirstOrDefault(); } Console.WriteLine("--Style: {0}", style); Console.WriteLine("-- x:{0:0.0000} \n-- y:{1:0.0000} \n-- z:{2:0.0000} \n", shapeGeometry.BoundingBox.Location.X, shapeGeometry.BoundingBox.Location.Y, shapeGeometry.BoundingBox.Location.Z); Console.WriteLine("-- sx:{0:0.0000} {3} \n-- sy:{1:0.0000} {3} \n-- sz:{2:0.0000} {3} \n", shapeGeometry.BoundingBox.SizeX, shapeGeometry.BoundingBox.SizeY, shapeGeometry.BoundingBox.SizeZ, defaultLengthUnit); } } }
public static MeshGeometry3D WriteTriangles(IIfcProduct ifcElement, Xbim3DModelContext context, XbimMatrix3D wcsTransformation) { MeshBuilder meshBuilder = new MeshBuilder(false, false); // var allTriangles = new List<Triangles>(); // foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded)) foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded)) { XbimShapeGeometry geometry = context.ShapeGeometry(instance); var data = ((IXbimShapeGeometryData)geometry).ShapeData; using (var stream = new MemoryStream(data)) { using (var reader = new BinaryReader(stream)) { XbimShapeTriangulation mesh = reader.ReadShapeTriangulation(); mesh = mesh.Transform(instance.Transformation); // WCS transforms mesh = mesh.Transform(wcsTransformation); foreach (XbimFaceTriangulation face in mesh.Faces) { var j = 0; for (var i = 0; i < face.TriangleCount; i++) { int k = i + j; var point1 = new Point3D { X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z }; j++; k = i + j; var point2 = new Point3D { X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z }; j++; k = i + j; var point3 = new Point3D { X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z }; meshBuilder.AddTriangle(point1, point2, point3); } } } } } return(meshBuilder.ToMesh()); // return allTriangles; }
public void GetGeometryFromXbimModel_IFC4(MeshGeometry3D m, IPersistEntity item, XbimMatrix3D wcsTransform) { if (item.Model == null || !(item is Xbim.Ifc4.Kernel.IfcProduct)) { return; } var context = new Xbim3DModelContext(item.Model); var productShape = context.ShapeInstancesOf((Xbim.Ifc4.Interfaces.IIfcProduct)item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); if (!productShape.Any() && item is Xbim.Ifc4.Interfaces.IIfcFeatureElement) { productShape = context.ShapeInstancesOf((Xbim.Ifc4.Interfaces.IIfcProduct)item) .Where( s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); } if (!productShape.Any()) { return; } foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry)shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } }
private static void getgeometry(XbimShapeInstance shape, Xbim3DModelContext m_context) { XbimShapeTriangulation mesh = null; var geometry = m_context.ShapeGeometry(shape); //Console.WriteLine("====" + geometry.GetType()); Console.WriteLine($"{"\n"}{GetIndent(11)}{"--Geometry Type: " + geometry.Format}"); var ms = new MemoryStream(((IXbimShapeGeometryData)geometry).ShapeData); var br = new BinaryReader(ms); mesh = br.ReadShapeTriangulation(); mesh = mesh.Transform(((XbimShapeInstance)shape).Transformation); var facesfound = mesh.Faces.ToList(); Console.WriteLine($"{"\n"}{GetIndent(11)}{" -----No. of faces on the shape #" + shape.IfcProductLabel + ": " + facesfound.Count()}"); foreach (XbimFaceTriangulation f in facesfound) { Console.WriteLine($"{"\n"}{GetIndent(13)}{" -----Triangle count on face: " + f.GetType() + " :mesh is " + f.TriangleCount}"); //foreach (var fi in f.Indices) //{ // Console.WriteLine($"{GetIndent(13)}{" -> " + fi}"); //} composetrianglesets(f, mesh); } //Console.WriteLine($"{"\n"}{GetIndent(13)}{" -----Vertices of the shape: #" + shape.IfcProductLabel}"); //foreach (var v in mesh.Vertices.ToList()) //{ // Console.WriteLine($"{GetIndent(13)}{" --vertex_" + mesh.Vertices.ToList().IndexOf(v) + " : " + Math.Round((double)v.X, 2) + " | " + Math.Round((double)v.Y, 2) + " | " + Math.Round((double)v.Z, 2)}"); //} Console.WriteLine("\n"); }
static void Main(string[] args) { const string file = @"4walls1floorSite.ifc"; var model = IfcStore.Open(file); var context = new Xbim3DModelContext(model); context.CreateContext(); var instances = context.ShapeInstances(); foreach (var instance in instances) { var geometry = context.ShapeGeometry(instance); var data = ((IXbimShapeGeometryData)geometry).ShapeData; using (var stream = new MemoryStream(data)) { using (var reader = new BinaryReader(stream)) { var mesh = reader.ReadShapeTriangulation(); } } } }
public XbimScene <WpfMeshGeometry3D, WpfMaterial> BuildScene(XbimModel model, Xbim3DModelContext context, List <Type> exclude = null) { var tmpOpaquesGroup = new Model3DGroup(); var retScene = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model); var red = PrepareMesh(new XbimColour("Red", 1.0, 0.0, 0.0, 0.5)); var green = PrepareMesh(new XbimColour("Green", 0.0, 1.0, 0.0, 0.5)); red.WpfModel.SetValue(FrameworkElement.TagProperty, red); green.WpfModel.SetValue(FrameworkElement.TagProperty, green); red.BeginUpdate(); green.BeginUpdate(); tmpOpaquesGroup.Children.Add(red); tmpOpaquesGroup.Children.Add(green); var i = 0; foreach (var shapeInstance in context.ShapeInstances() .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !typeof(IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& * !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/)) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); WpfMeshGeometry3D targetMergeMesh; switch (i++ % 2) { case 0: targetMergeMesh = red; break; default: targetMergeMesh = green; break; } switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.Polyhedron: var shapePoly = (XbimShapeGeometry)shapeGeom; targetMergeMesh.Add( shapePoly.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom), model.UserDefinedId); break; case XbimGeometryType.PolyhedronBinary: targetMergeMesh.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom), model.UserDefinedId ); break; default: throw new ArgumentOutOfRangeException(); } } red.EndUpdate(); green.EndUpdate(); var mv = new ModelVisual3D { Content = tmpOpaquesGroup }; Control.OpaquesVisual3D.Children.Add(mv); // Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); return(retScene); }
/// <summary> /// This version uses the new Geometry representation /// </summary> /// <param name="model"></param> /// <param name="context"></param> /// <param name="exclude">List of type to exclude, by default excplict openings and spaces are excluded if exclude = null</param> /// <returns></returns> public XbimScene<WpfMeshGeometry3D, WpfMaterial> BuildScene(XbimModel model, Xbim3DModelContext context, List<Type> exclude = null) { var scene = new XbimScene<WpfMeshGeometry3D, WpfMaterial>(model); if (context == null) return scene; //get a list of all the unique styles var styles = new Dictionary<int, WpfMaterial>(); var repeatedShapeGeometries = new Dictionary<int, MeshGeometry3D>(); var styleMeshSets = new Dictionary<int, WpfMeshGeometry3D>(); var tmpOpaquesGroup = new Model3DGroup(); var tmpTransparentsGroup = new Model3DGroup(); var sstyles = context.SurfaceStyles(); foreach (var style in sstyles) { var wpfMaterial = new WpfMaterial(); wpfMaterial.CreateMaterial(style); styles.Add(style.DefinedObjectId, wpfMaterial); var mg = new WpfMeshGeometry3D(wpfMaterial, wpfMaterial); mg.WpfModel.SetValue(FrameworkElement.TagProperty, mg); styleMeshSets.Add(style.DefinedObjectId, mg); mg.BeginUpdate(); if (style.IsTransparent) tmpTransparentsGroup.Children.Add(mg); else tmpOpaquesGroup.Children.Add(mg); } if (!styles.Any()) return scene; //this should always return something int i = 0; var shapeInstances = context.ShapeInstances() .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !typeof (IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/); foreach (var shapeInstance in shapeInstances) { Console.WriteLine(i++); var styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; //GET THE ACTUAL GEOMETRY MeshGeometry3D wpfMesh; //see if we have already read it if (repeatedShapeGeometries.TryGetValue(shapeInstance.ShapeGeometryLabel, out wpfMesh)) { var mg = new GeometryModel3D(wpfMesh, styles[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.WcsTransform).ToMatrixTransform3D(); if (styles[styleId].IsTransparent) tmpTransparentsGroup.Children.Add(mg); else tmpOpaquesGroup.Children.Add(mg); } else //we need to get the shape geometry { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapeGeom.ReferenceCount > 1) //only store if we are going to use again { wpfMesh = new MeshGeometry3D(); switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: wpfMesh.Read(shapeGeom.ShapeData); break; case XbimGeometryType.Polyhedron: wpfMesh.Read(((XbimShapeGeometry)shapeGeom).ShapeData); break; } repeatedShapeGeometries.Add(shapeInstance.ShapeGeometryLabel, wpfMesh); var mg = new GeometryModel3D(wpfMesh, styles[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.WcsTransform).ToMatrixTransform3D(); if (styles[styleId].IsTransparent) tmpTransparentsGroup.Children.Add(mg); else tmpOpaquesGroup.Children.Add(mg); } else //it is a one off, merge it with shapes of a similar material { var targetMergeMeshByStyle = styleMeshSets[styleId]; switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.Polyhedron: var shapePoly = (XbimShapeGeometry)shapeGeom; targetMergeMeshByStyle.Add( shapePoly.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.WcsTransform)); break; case XbimGeometryType.PolyhedronBinary: targetMergeMeshByStyle.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.WcsTransform)); break; default: throw new ArgumentOutOfRangeException(); } } } } foreach (var wpfMeshGeometry3D in styleMeshSets.Values) { wpfMeshGeometry3D.EndUpdate(); } //} if (tmpOpaquesGroup.Children.Any()) { var mv = new ModelVisual3D(); mv.Content = tmpOpaquesGroup; Control.Opaques.Children.Add(mv); Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); } if (tmpTransparentsGroup.Children.Any()) { var mv = new ModelVisual3D(); mv.Content = tmpTransparentsGroup; Control.Transparents.Children.Add(mv); if (Control.ModelBounds.IsEmpty) Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); else Control.ModelBounds.Union(mv.Content.Bounds.ToXbimRect3D()); } return scene; }
public static List <Point3D> GetFootPrintNonBREP(IIfcProduct ifcElement, Xbim3DModelContext context) { var resultList = new List <Point3D>(); foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement)) { // Get the IFC Representation of the Footprint of the instance XbimShapeGeometry geometry = context.ShapeGeometry(instance); var data = ((IXbimShapeGeometryData)geometry).ShapeData; using (var stream = new MemoryStream(data)) { using (var reader = new BinaryReader(stream)) { XbimShapeTriangulation mesh = reader.ReadShapeTriangulation(); mesh = mesh.Transform(instance.Transformation); // find the minimal z coordinate double minZ = 10000; foreach (var vertex in mesh.Vertices) { if (vertex.Z <= minZ) { minZ = vertex.Z; } } List <IVertex> points = new List <IVertex>(); foreach (var vertex in mesh.Vertices) { if (vertex.Z != minZ) { continue; } points.Add(new DefaultVertex { Position = new[] { vertex.X, vertex.Y } }); } if (points.Count <= 2) { return(null); } // Compute ConvexHull var cH = ConvexHull.Create(points); foreach (var item in cH.Points) { var point = new Point3D() { X = item.Position[0], Y = item.Position[1], Z = minZ }; bool duplicate = false; foreach (var result in resultList) { if (result == point) { duplicate = true; break; } } if (!duplicate) { resultList.Add(point); } } } } } return(resultList); }
/// <summary> /// Extract Geometries from IFC file. /// </summary> /// <param name="model">IfcStore model.</param> /// <param name="geometries">Geometries data.</param> /// <param name="modelBoundingBox">Bounding box of the ifc model.</param> public static void ExtractGeometries(IfcStore model, ref Dictionary <string, GeometryStore> geometries, ref XbimRect3D modelBoundingBox) { // context is used to extract geometry data var context = new Xbim3DModelContext(model); var meter = context.Model.ModelFactors.OneMeter; context.CreateContext(); // start to extract geometry data var instances = context.ShapeInstances(); XbimColourMap colorMap = new XbimColourMap(); foreach (var instance in instances) // each instance is a mesh { MeshStore meshStore = new MeshStore(); // get the color of this mesh var ss = model.Instances[instance.StyleLabel] as IIfcSurfaceStyle; XbimColour color = XbimColour.DefaultColour; if (ss != null) { var texture = XbimTexture.Create(ss); color = texture.ColourMap.FirstOrDefault(); } else { var styleId = instance.StyleLabel > 0 ? instance.StyleLabel : instance.IfcTypeId; var theType = model.Metadata.GetType((short)styleId); color = colorMap[theType.Name]; } meshStore.Color = string.Format("{0},{1},{2},{3}", (int)(color.Red * 255), (int)(color.Green * 255), (int)(color.Blue * 255), color.Alpha * 255); var geometry = context.ShapeGeometry(instance); var data = (geometry as IXbimShapeGeometryData).ShapeData; // multiple geometry may belong to one product, like frame and glass belong to a ifcwindow var product = model.Instances[instance.IfcProductLabel] as IIfcProduct; if (!geometries.ContainsKey(product.GlobalId)) { geometries.Add(product.GlobalId, new GeometryStore(product.GlobalId, product.Name)); } var geometryStore = geometries[product.GlobalId]; // reading the real geometry data using (var stream = new MemoryStream(data)) { using (var reader = new BinaryReader(stream)) { // triangle the instance and transform it to the correct position var mesh = reader.ReadShapeTriangulation(); mesh = mesh.Transform(instance.Transformation); // geometry data var verticesData = new List <double>(); var normalsData = new List <double>(); var indexesData = new List <int>(); // bouding box for instance. double minX = double.MaxValue, minY = double.MaxValue, minZ = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue, maxZ = double.MinValue; var faces = mesh.Faces as List <XbimFaceTriangulation>; foreach (var face in faces) { foreach (var indice in face.Indices) { indexesData.Add(indice); } foreach (var normal in face.Normals) { normalsData.Add(normal.Normal.X); normalsData.Add(normal.Normal.Y); normalsData.Add(normal.Normal.Z); } } var vertices = mesh.Vertices as List <XbimPoint3D>; foreach (var point in vertices) { double x = point.X / meter, y = point.Y / meter, z = point.Z / meter; verticesData.Add(x); // convert to meter verticesData.Add(y); verticesData.Add(z); // update bounding box minX = Math.Min(minX, x); minY = Math.Min(minY, y); minZ = Math.Min(minZ, z); maxX = Math.Max(maxX, x); maxY = Math.Max(maxY, y); maxZ = Math.Max(maxZ, z); } if (minX == double.MaxValue || minY == double.MaxValue || minZ == double.MaxValue || maxX == double.MinValue || maxY == double.MinValue || maxZ == double.MinValue) { throw new Exception("Invalid Boundingbox"); } // do not trust instance.BoundingBox, it seems to be wrong. XbimRect3D bbox = new XbimRect3D(minX, minY, minZ, maxX - minX, maxY - minY, maxZ - minZ); // update boundingbox of current geometryStore geometryStore.BoundBox = GeometryStore.Union(geometryStore.BoundBox, bbox); // update boundingbox of ifc model modelBoundingBox = GeometryStore.Union(modelBoundingBox, bbox); meshStore.Vertexes = verticesData; meshStore.Normals = normalsData; meshStore.Indexes = indexesData; } } geometryStore.Meshes.Add(meshStore); } }
public static void UpdateElementTransform(IfcStore _model, string projectNumber, string projectName) { DBOperation.beginTransaction(); DBOperation.commitInterval = 5000; string currStep = string.Empty; BIMRLCommon _refBIMRLCommon = new BIMRLCommon(); int commandStatus = -1; int currInsertCount = 0; OracleCommand command = new OracleCommand(" ", DBOperation.DBConn); XbimMatrix3D m3D = new XbimMatrix3D(); if (string.IsNullOrEmpty(projectName)) { projectName = projectNumber + " - Federated"; } string modelName; if (!string.IsNullOrEmpty(_model.FileName)) { modelName = Path.GetFileNameWithoutExtension(_model.FileName); } else { modelName = projectNumber + " - " + projectName; } command.CommandText = "SELECT FEDERATEDID FROM bimrl_federatedmodel WHERE MODELNAME = '" + modelName + "' AND PROJECTNUMBER='" + projectNumber + "' AND PROJECTNAME='" + projectName + "'"; object oFedID = command.ExecuteScalar(); if (oFedID == null) { return; } int fedID = int.Parse(oFedID.ToString()); command.CommandText = "SELECT ELEMENTID, LINENO FROM " + DBOperation.formatTabName("bimrl_element", fedID) + " WHERE GEOMETRYBODY IS NOT NULL"; OracleDataReader reader = command.ExecuteReader(); SortedDictionary <int, string> elemList = new SortedDictionary <int, string>(); while (reader.Read()) { string elemid = reader.GetString(0); int lineNo = reader.GetInt32(1); elemList.Add(lineNo, elemid); } reader.Close(); Xbim3DModelContext context = new Xbim3DModelContext(_model); foreach (KeyValuePair <int, string> elemListItem in elemList) { //IEnumerable<XbimGeometryData> geomDataList = _model.GetGeometryData(elemListItem.Key, XbimGeometryType.TriangulatedMesh); IIfcProduct product = _model.Instances[elemListItem.Key] as IIfcProduct; IEnumerable <XbimShapeInstance> shapeInstances = context.ShapeInstancesOf(product).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded); if (shapeInstances.Count() == 0) { continue; // SKip if the product has no geometry } XbimMeshGeometry3D prodGeom = new XbimMeshGeometry3D(); IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstances.FirstOrDefault().ShapeGeometryLabel); //XbimModelExtensions.Read(prodGeom, shapeGeom.ShapeData, shapeInstances.FirstOrDefault().Transformation); //XbimGeometryData sdoGeomData = geomDataList.First(); //m3D = sdoGeomData.Transform; //m3D = XbimMatrix3D.FromArray(sdoGeomData.DataArray2); // Xbim 3.0 removes Tranform property m3D = shapeInstances.FirstOrDefault().Transformation; string sqlStmt = "update " + DBOperation.formatTabName("BIMRL_ELEMENT", fedID) + " set TRANSFORM_COL1=:1, TRANSFORM_COL2=:2, TRANSFORM_COL3=:3, TRANSFORM_COL4=:4" + " Where elementid = '" + elemListItem.Value + "'"; // int status = DBOperation.updateGeometry(sqlStmt, sdoGeomData); currStep = sqlStmt; command.CommandText = sqlStmt; try { OracleParameter[] sdoGeom = new OracleParameter[4]; for (int i = 0; i < sdoGeom.Count(); ++i) { sdoGeom[i] = command.Parameters.Add((i + 1).ToString(), OracleDbType.Object); sdoGeom[i].Direction = ParameterDirection.Input; sdoGeom[i].UdtTypeName = "MDSYS.SDO_GEOMETRY"; sdoGeom[i].Size = 1; } SdoGeometry trcol1 = new SdoGeometry(); trcol1.Dimensionality = 3; trcol1.LRS = 0; trcol1.GeometryType = (int)SdoGeometryTypes.GTYPE.POINT; int gType = trcol1.PropertiesToGTYPE(); SdoPoint trcol1V = new SdoPoint(); trcol1V.XD = m3D.M11; trcol1V.YD = m3D.M12; trcol1V.ZD = m3D.M13; trcol1.SdoPoint = trcol1V; sdoGeom[1].Value = trcol1; SdoGeometry trcol2 = new SdoGeometry(); trcol2.Dimensionality = 3; trcol2.LRS = 0; trcol2.GeometryType = (int)SdoGeometryTypes.GTYPE.POINT; gType = trcol2.PropertiesToGTYPE(); SdoPoint trcol2V = new SdoPoint(); trcol2V.XD = m3D.M21; trcol2V.YD = m3D.M22; trcol2V.ZD = m3D.M23; trcol2.SdoPoint = trcol2V; sdoGeom[2].Value = trcol2; SdoGeometry trcol3 = new SdoGeometry(); trcol3.Dimensionality = 3; trcol3.LRS = 0; trcol3.GeometryType = (int)SdoGeometryTypes.GTYPE.POINT; gType = trcol3.PropertiesToGTYPE(); SdoPoint trcol3V = new SdoPoint(); trcol3V.XD = m3D.M31; trcol3V.YD = m3D.M32; trcol3V.ZD = m3D.M33; trcol3.SdoPoint = trcol3V; sdoGeom[3].Value = trcol3; SdoGeometry trcol4 = new SdoGeometry(); trcol4.Dimensionality = 3; trcol4.LRS = 0; trcol4.GeometryType = (int)SdoGeometryTypes.GTYPE.POINT; gType = trcol4.PropertiesToGTYPE(); SdoPoint trcol4V = new SdoPoint(); trcol4V.XD = m3D.OffsetX; trcol4V.YD = m3D.OffsetY; trcol4V.ZD = m3D.OffsetZ; trcol4.SdoPoint = trcol4V; sdoGeom[4].Value = trcol4; commandStatus = command.ExecuteNonQuery(); command.Parameters.Clear(); currInsertCount++; if (currInsertCount % DBOperation.commitInterval == 0) { //Do commit at interval but keep the long transaction (reopen) DBOperation.commitTransaction(); } } catch (OracleException e) { string excStr = "%%Error - " + e.Message + "\n\t" + currStep; _refBIMRLCommon.StackPushError(excStr); //command.Dispose(); // Log Oracle error and continue command = new OracleCommand(" ", DBOperation.DBConn); // throw; } catch (SystemException e) { string excStr = "%%Insert Error - " + e.Message + "\n\t" + currStep; _refBIMRLCommon.StackPushError(excStr); throw; } DBOperation.commitTransaction(); command.Dispose(); } }
private void ShowGeometrySummary(XbimModel model) { var context = new Xbim3DModelContext(model); Console.WriteLine(); Console.WriteLine("Styles"); foreach (var styles in context.SurfaceStyles()) { Console.WriteLine("{0,-6} {1,-30} {2,-6}", styles.DefinedObjectId, styles.ColourMap.First(), styles.IsTransparent); } var largest = context.GetLargestRegion(); Console.WriteLine(); Console.WriteLine("Regions"); foreach (var region in context.GetRegions()) { Console.WriteLine("{0,-20} {1,6} {2}", region.Name, region.Population, (region == largest)); } Console.WriteLine("{0,-8}, {1,-8}, {2,6} {3,8}", "Ifc Label", "Label", "Ref Count", "Bytes"); var geometries = GetGeom(model) .OrderByDescending(o => o.Cost) .Distinct() .Take(10); var items = from inst in context.ShapeInstances() join prod in model.Instances.OfType <IfcProduct>() on inst.IfcProductLabel equals prod.EntityLabel select new { Instance = inst, Geometry = context.ShapeGeometry(inst.InstanceLabel), Product = prod }; var expensiveProducts = items .OrderByDescending(o => (o.Geometry.IsValid ? o.Geometry.Cost : 0)) .Take(20); foreach (var geometry in geometries) { Console.WriteLine("{0, -8}, {1,-8}, {2,6} {3,8}", geometry.IfcShapeLabel, geometry.ShapeLabel, geometry.ReferenceCount, geometry.Cost); } Console.WriteLine(); Console.WriteLine("Top 20 expensive items"); foreach (var item in expensiveProducts) { Console.WriteLine("{0,-6} {1,-40} {2,-20} {3,6}", item.Product.EntityLabel, item.Product.Name.ToString().Truncate(40), item.Product.GetType().Name, item.Geometry.Cost ); } }
/// <summary> /// This version uses the new Geometry representation /// </summary> /// <param name="model"></param> /// <param name="context"></param> /// <param name="exclude">List of type to exclude, by default excplict openings and spaces are excluded if exclude = null</param> /// <returns></returns> public XbimScene <WpfMeshGeometry3D, WpfMaterial> BuildScene(XbimModel model, Xbim3DModelContext context, List <Type> exclude = null) { var excludedTypes = new HashSet <short>(); if (exclude == null) { exclude = new List <Type>() { typeof(IfcSpace) // , typeof(IfcFeatureElement) } } ; foreach (var excludedT in exclude) { var ifcT = IfcMetaData.IfcType(excludedT); foreach (var exIfcType in ifcT.NonAbstractSubTypes.Select(IfcMetaData.IfcType)) { excludedTypes.Add(exIfcType.TypeId); } } var scene = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model); if (context == null) { return(scene); } //get a list of all the unique styles var styles = new Dictionary <int, WpfMaterial>(); var repeatedShapeGeometries = new Dictionary <int, MeshGeometry3D>(); var styleMeshSets = new Dictionary <int, WpfMeshGeometry3D>(); var tmpOpaquesGroup = new Model3DGroup(); var tmpTransparentsGroup = new Model3DGroup(); var sstyles = context.SurfaceStyles(); foreach (var style in sstyles) { var wpfMaterial = new WpfMaterial(); wpfMaterial.CreateMaterial(style); styles.Add(style.DefinedObjectId, wpfMaterial); var mg = new WpfMeshGeometry3D(wpfMaterial, wpfMaterial); mg.WpfModel.SetValue(FrameworkElement.TagProperty, mg); styleMeshSets.Add(style.DefinedObjectId, mg); mg.BeginUpdate(); if (style.IsTransparent) { tmpTransparentsGroup.Children.Add(mg); } else { tmpOpaquesGroup.Children.Add(mg); } } if (!styles.Any()) { return(scene); //this should always return something } var shapeInstances = context.ShapeInstances() .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !excludedTypes.Contains(s.IfcTypeId)); // !typeof (IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& // !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/); foreach (var shapeInstance in shapeInstances) { var styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; //GET THE ACTUAL GEOMETRY MeshGeometry3D wpfMesh; //see if we have already read it if (repeatedShapeGeometries.TryGetValue(shapeInstance.ShapeGeometryLabel, out wpfMesh)) { var mg = new GeometryModel3D(wpfMesh, styles[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom).ToMatrixTransform3D(); if (styles[styleId].IsTransparent) { tmpTransparentsGroup.Children.Add(mg); } else { tmpOpaquesGroup.Children.Add(mg); } } else //we need to get the shape geometry { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapeGeom.ReferenceCount > 1) //only store if we are going to use again { wpfMesh = new MeshGeometry3D(); switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: wpfMesh.Read(shapeGeom.ShapeData); break; case XbimGeometryType.Polyhedron: wpfMesh.Read(((XbimShapeGeometry)shapeGeom).ShapeData); break; } repeatedShapeGeometries.Add(shapeInstance.ShapeGeometryLabel, wpfMesh); var mg = new GeometryModel3D(wpfMesh, styles[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom).ToMatrixTransform3D(); if (styles[styleId].IsTransparent) { tmpTransparentsGroup.Children.Add(mg); } else { tmpOpaquesGroup.Children.Add(mg); } } else //it is a one off, merge it with shapes of a similar material { var targetMergeMeshByStyle = styleMeshSets[styleId]; switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.Polyhedron: // var shapePoly = (XbimShapeGeometry)shapeGeom; var asString = Encoding.UTF8.GetString(shapeGeom.ShapeData.ToArray()); targetMergeMeshByStyle.Add( asString, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom), model.UserDefinedId); break; case XbimGeometryType.PolyhedronBinary: var transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom); targetMergeMeshByStyle.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, transform, model.UserDefinedId); break; default: throw new ArgumentOutOfRangeException(); } } } } foreach (var wpfMeshGeometry3D in styleMeshSets.Values) { wpfMeshGeometry3D.EndUpdate(); } //} if (tmpOpaquesGroup.Children.Any()) { var mv = new ModelVisual3D(); mv.Content = tmpOpaquesGroup; Control.OpaquesVisual3D.Children.Add(mv); // Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); } if (tmpTransparentsGroup.Children.Any()) { var mv = new ModelVisual3D(); mv.Content = tmpTransparentsGroup; Control.TransparentsVisual3D.Children.Add(mv); //if (Control.ModelBounds.IsEmpty) Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); //else Control.ModelBounds.Union(mv.Content.Bounds.ToXbimRect3D()); } return(scene); }
public static XbimMeshGeometry3D GetMesh(this XbimModel xbimModel, IEnumerable <IPersistIfcEntity> items, XbimMatrix3D wcsTransform) { var m = new XbimMeshGeometry3D(); if (xbimModel.GeometrySupportLevel == 1) { // this is what happens for version 1 of the engine // foreach (var item in items) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null) { continue; } var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh); foreach (var geomData in geomDataSet) { // todo: add guidance to the TransformBy method so that users can understand how to stop using it (it's marked absolete) geomData.TransformBy(wcsTransform); m.Add(geomData, xbimModel.UserDefinedId); } } } else { // this is what happens for version 2 of the engine // foreach (var item in items) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null || !(item is IfcProduct)) { continue; } var context = new Xbim3DModelContext(fromModel); var productShape = context.ShapeInstancesOf((IfcProduct)item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); // this also returns shapes of voids foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry)shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } } } return(m); }
public XbimScene<WpfMeshGeometry3D, WpfMaterial> BuildScene(XbimModel model, Xbim3DModelContext context, List<Type> exclude = null) { var tmpOpaquesGroup = new Model3DGroup(); var retScene = new XbimScene<WpfMeshGeometry3D, WpfMaterial>(model); var red = PrepareMesh(new XbimColour("Red", 1.0, 0.0, 0.0)); var green = PrepareMesh(new XbimColour("Green", 0.0, 1.0, 0.0)); var amber =PrepareMesh(new XbimColour("Amber", 0.0, 0.0, 1.0, 0.9)); tmpOpaquesGroup.Children.Add(red); tmpOpaquesGroup.Children.Add(green); tmpOpaquesGroup.Children.Add(amber); var i = 0; foreach (var shapeInstance in context.ShapeInstances() .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !typeof (IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/)) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); WpfMeshGeometry3D targetMergeMesh; switch (i++%3) { case 0: targetMergeMesh = red; break; case 1: targetMergeMesh = green; break; default: targetMergeMesh = amber; break; } switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.Polyhedron: var shapePoly = (XbimShapeGeometry)shapeGeom; targetMergeMesh.Add( shapePoly.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom), model.UserDefinedId ); break; case XbimGeometryType.PolyhedronBinary: targetMergeMesh.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom), model.UserDefinedId); break; default: throw new ArgumentOutOfRangeException(); } } var mv = new ModelVisual3D {Content = tmpOpaquesGroup}; Control.OpaquesVisual3D.Children.Add(mv); Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); return retScene; }
private void WriteGeometry(JsonWriter writer) { XbimMatrix3D globalTrans = GetGlobalModelTransform(); //write out the material nodes and then the instances for each material Dictionary <int, XbimTexture> styles = _context.SurfaceStyles().ToDictionary(s => s.DefinedObjectId); foreach (var instanceGroup in _context.ShapeInstancesGroupByStyle()) { if (!instanceGroup.Any()) { continue; //skip emmpty instances; } int styleId = instanceGroup.Key; XbimTexture style = styles[styleId]; writer.WriteStartObject(); //Material node { writer.WritePropertyName("type"); writer.WriteValue("material"); writer.WritePropertyName("id"); writer.WriteValue("M" + styleId); writer.WritePropertyName("color"); writer.WriteStartObject(); //begin color { writer.WritePropertyName("r"); writer.WriteValue(style.ColourMap[0].Red); writer.WritePropertyName("g"); writer.WriteValue(style.ColourMap[0].Green); writer.WritePropertyName("b"); writer.WriteValue(style.ColourMap[0].Blue); } writer.WriteEndObject(); //end color writer.WritePropertyName("alpha"); writer.WriteValue(style.ColourMap[0].Alpha); //all instances of this style writer.WritePropertyName("nodes"); //beginning of the instance nodes writer.WriteStartArray(); foreach (var shapeInstance in instanceGroup) { writer.WriteStartObject(); //start of instance transform { if (_maps.Contains(shapeInstance.ShapeGeometryLabel)) //it is a reference { //write the transform writer.WritePropertyName("type"); //geometry node writer.WriteValue("matrix"); writer.WritePropertyName("id"); writer.WriteValue("I" + shapeInstance.InstanceLabel); writer.WritePropertyName("elements"); XbimMatrix3D m = XbimMatrix3D.Multiply(shapeInstance.Transformation, globalTrans); WriteMatrix(writer, m); writer.WritePropertyName("nodes"); //beginning of the instance nodes writer.WriteStartArray(); //write the map writer.WriteStartObject(); //start of map { writer.WritePropertyName("type"); //geometry node writer.WriteValue("geometry"); writer.WritePropertyName("coreId"); writer.WriteValue("L" + shapeInstance.ShapeGeometryLabel); } writer.WriteEndObject(); //end of map writer.WriteEndArray(); //end of instance tranform nodes } else //write the actual geometry { writer.WritePropertyName("type"); //geometry node writer.WriteValue("geometry"); writer.WritePropertyName("primitive"); //primitive: " writer.WriteValue("triangles"); writer.WritePropertyName("id"); writer.WriteValue("I" + shapeInstance.InstanceLabel); WriteShapeGeometry(writer, _context.ShapeGeometry(shapeInstance), XbimMatrix3D.Multiply(shapeInstance.Transformation, globalTrans)); } } writer.WriteEndObject(); //end of instance transform } writer.WriteEndArray(); //end of instance transform nodes } writer.WriteEndObject(); // end of the material node } }