public static WpfMeshGeometry3D GetGeometry(IPersistEntity selection, XbimMatrix3D modelTransform, WpfMaterial mat) { var tgt = new WpfMeshGeometry3D(mat, mat); tgt.BeginUpdate(); using (var geomstore = selection.Model.GeometryStore) { using (var geomReader = geomstore.BeginRead()) { foreach (var shapeInstance in geomReader.ShapeInstancesOfEntity(selection).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded)) { IXbimShapeGeometryData shapegeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapegeom.Format != (byte)XbimGeometryType.PolyhedronBinary) { continue; } var transform = shapeInstance.Transformation * modelTransform; tgt.Add( shapegeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, transform, (short)selection.Model.UserDefinedId ); } } } tgt.EndUpdate(); return(tgt); }
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; } }
internal bool TryMoveNextRegion(ref IXbimShapeGeometryData regions) { if (TryMoveNext()) { GetShapeGeometryData(regions); return(true); } return(false); }
/// <summary> /// Returns the next Shape geometry after a move or a seek call /// </summary> /// <param name="sg"></param> /// <returns></returns> public bool TryMoveNextShapeGeometry(ref IXbimShapeGeometryData sg) { if (Api.TryMoveNext(this.Sesid, this.Table)) { GetShapeGeometryData(sg); return(true); } else { return(false); } }
private void GetShapeGeometryData(IXbimShapeGeometryData sg) { Api.RetrieveColumns(Sesid, Table, _colValues); sg.ShapeLabel = Api.RetrieveColumnAsInt32(Sesid, Table, _colIdShapeLabel, RetrieveColumnGrbit.RetrieveFromIndex).Value; sg.IfcShapeLabel = _colValIfcShapeLabel.Value.Value; sg.GeometryHash = _colValGeometryHash.Value.Value; sg.ReferenceCount = _colValReferenceCount.Value.Value; sg.LOD = _colValLOD.Value.Value; sg.Format = _colValFormat.Value.Value; sg.ShapeDataCompressed = _colValShapeData.Value; sg.BoundingBox = _colValBoundingBox.Value; }
/// <summary> /// Seeks and returns the first shape geometry /// </summary> /// <param name="sg"></param> public bool TryMoveFirstShapeGeometry(ref IXbimShapeGeometryData sg) { Api.JetSetCurrentIndex(Sesid, Table, geometryTablePrimaryIndex); if (TryMoveFirst()) { GetShapeGeometryData(sg); return(true); } else { return(false); } }
/// <summary> /// Returns the shape geometry for the specified label if it exists /// </summary> /// <param name="shapeGeometryLabel"></param> /// <param name="sg"></param> /// <returns></returns> public bool TryGetShapeGeometry(int shapeGeometryLabel, ref IXbimShapeGeometryData sg) { Api.JetSetCurrentIndex(Sesid, Table, geometryTablePrimaryIndex); Api.MakeKey(Sesid, Table, shapeGeometryLabel, MakeKeyGrbit.NewKey); if (Api.TrySeek(Sesid, Table, SeekGrbit.SeekEQ)) { GetShapeGeometryData(sg); return(true); } else { return(false); } }
public bool TryMoveFirstRegion(ref IXbimShapeGeometryData sg) { Api.JetSetCurrentIndex(Sesid, Table, geometryTableReferenceIndex); Api.MakeKey(Sesid, Table, -1, MakeKeyGrbit.NewKey); //regions are store with cost = -1 and ref count = -1 Api.MakeKey(Sesid, Table, -1, MakeKeyGrbit.None); if (Api.TrySeek(Sesid, Table, SeekGrbit.SeekGE)) { Api.MakeKey(Sesid, Table, -1, MakeKeyGrbit.NewKey); Api.MakeKey(Sesid, Table, -1, MakeKeyGrbit.FullColumnEndLimit); if (Api.TrySetIndexRange(Sesid, Table, SetIndexRangeGrbit.RangeUpperLimit | SetIndexRangeGrbit.RangeInclusive)) { GetShapeGeometryData(sg); return(true); } } return(false); }
internal void AddShape(IGeometryStoreReader geomReader, XbimShapeInstance shapeInstance, CoordinatesMode mode) { // XbimMatrix3D modelTransform = XbimMatrix3D.Identity; IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapeGeom.Format != (byte)XbimGeometryType.PolyhedronBinary) { return; } // var transform = XbimMatrix3D.Multiply(, modelTransform); if (mode == CoordinatesMode.IncludeShapeTransform) { AddMesh(shapeGeom.ShapeData, shapeInstance.Transformation); } else { AddMesh(shapeGeom.ShapeData); } }
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; } } }
public static WpfMeshGeometry3D GetGeometry(EntitySelection selection, XbimModelPositioningCollection positions, Material mat) { var tgt = new WpfMeshGeometry3D(mat, mat); tgt.BeginUpdate(); foreach (var modelgroup in selection.GroupBy(i => i.Model)) { var model = modelgroup.Key; var modelTransform = positions[model]?.Transform; if (modelTransform != null) { using (var geomstore = model.GeometryStore) using (var geomReader = geomstore.BeginRead()) { foreach (var item in modelgroup) { foreach (var shapeInstance in geomReader.ShapeInstancesOfEntity(item).Where(x => x.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)) { IXbimShapeGeometryData shapegeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapegeom.Format != (byte)XbimGeometryType.PolyhedronBinary) { continue; } var transform = shapeInstance.Transformation * modelTransform; tgt.Add( shapegeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, transform, (short)model.UserDefinedId ); } } } } } tgt.EndUpdate(); return(tgt); }
public int AddGeometry(IXbimShapeGeometryData shapeGeom) { var mainId = 0; using (var update = new Update(Sesid, Table, JET_prep.Insert)) { _colValIfcShapeLabel.Value = shapeGeom.IfcShapeLabel; _colValGeometryHash.Value = shapeGeom.GeometryHash; _colValCost.Value = shapeGeom.Cost; _colValReferenceCount.Value = shapeGeom.ReferenceCount; _colValLOD.Value = shapeGeom.LOD; _colValFormat.Value = shapeGeom.Format; _colValShapeData.Value = shapeGeom.ShapeDataCompressed; _colValBoundingBox.Value = shapeGeom.BoundingBox; Api.SetColumns(Sesid, Table, _colValues); mainId = Api.RetrieveColumnAsInt32(Sesid, Table, _colIdShapeLabel, RetrieveColumnGrbit.RetrieveCopy).Value; update.Save(); UpdateCount(1); shapeGeom.ShapeLabel = mainId; } return(mainId); }
/// <summary> /// This version uses the new Geometry representation /// </summary> /// <param name="model"></param> /// <param name="modelTransform">The transform to place the models geometry in the right place</param> /// <param name="opaqueShapes"></param> /// <param name="transparentShapes"></param> /// <param name="isolateInstances">List of instances to be isolated</param> /// <param name="hideInstances">List of instances to be hidden</param> /// <param name="excludeTypes">List of type to exclude, by default excplict openings and spaces are excluded if exclude = null</param> /// <returns></returns> public XbimScene <WpfMeshGeometry3D, WpfMaterial> BuildScene(IModel model, XbimMatrix3D modelTransform, ModelVisual3D opaqueShapes, ModelVisual3D transparentShapes, List <IPersistEntity> isolateInstances = null, List <IPersistEntity> hideInstances = null, List <Type> excludeTypes = null) { var excludedTypes = model.DefaultExclusions(excludeTypes); var onlyInstances = isolateInstances?.Where(i => i.Model == model).ToDictionary(i => i.EntityLabel); var hiddenInstances = hideInstances?.Where(i => i.Model == model).ToDictionary(i => i.EntityLabel); var scene = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model); var timer = new Stopwatch(); timer.Start(); using (var geomStore = model.GeometryStore) { using (var geomReader = geomStore.BeginRead()) { // we are keeping the style to decide if a new element needs to be transparent. // var materialsByStyleId = new Dictionary <int, WpfMaterial>(); var repeatedShapeGeometries = new Dictionary <int, MeshGeometry3D>(); var tmpOpaquesGroup = new Model3DGroup(); var tmpTransparentsGroup = new Model3DGroup(); //get a list of all the unique style ids then build their style and mesh // var sstyleIds = geomReader.StyleIds; foreach (var styleId in sstyleIds) { var wpfMaterial = GetWpfMaterial(model, styleId); materialsByStyleId.Add(styleId, wpfMaterial); } var shapeInstances = GetShapeInstancesToRender(geomReader, excludedTypes); var tot = 1; if (ProgressChanged != null) { // only enumerate if there's a need for progress update tot = shapeInstances.Count(); } var prog = 0; var lastProgress = 0; // !typeof (IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& // !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/); // foreach (var shapeInstance in shapeInstances .Where(s => null == onlyInstances || onlyInstances.Count == 0 || onlyInstances.Keys.Contains(s.IfcProductLabel)) .Where(s => null == hiddenInstances || hiddenInstances.Count == 0 || !hiddenInstances.Keys.Contains(s.IfcProductLabel))) { int id = shapeInstance.IfcProductLabel; //LINKS TO ACTUAL ELEMENT ShadedElement el = elements[id]; var i = model.Instances[id]; // logging var currentProgress = 100 * prog++ / tot; if (currentProgress != lastProgress && ProgressChanged != null) { ProgressChanged(this, new ProgressChangedEventArgs(currentProgress, "Creating visuals")); lastProgress = currentProgress; } // work out style var styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; WpfMaterial selectedMaterial; if (!materialsByStyleId.TryGetValue(styleId, out selectedMaterial)) { // if the style is not available we build one by ExpressType selectedMaterial = GetWpfMaterialByType(model, shapeInstance.IfcTypeId); materialsByStyleId.Add(styleId, selectedMaterial); } int colorIndex = (int)el.currCriticality; selectedMaterial = new WpfMaterial(colsPerCriticality[colorIndex]); //GET THE ACTUAL GEOMETRY MeshGeometry3D wpfMesh; //see if we have already read it if (!repeatedShapeGeometries.TryGetValue(shapeInstance.ShapeGeometryLabel, out wpfMesh)) { IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if ((XbimGeometryType)shapeGeom.Format != XbimGeometryType.PolyhedronBinary) { continue; } wpfMesh = new MeshGeometry3D(); wpfMesh.Read(shapeGeom.ShapeData); if (shapeGeom.ReferenceCount > 1) //only store if we are going to use again { repeatedShapeGeometries.Add(shapeInstance.ShapeGeometryLabel, wpfMesh); } } var mg = new GeometryModel3D(wpfMesh, selectedMaterial); mg.BackMaterial = mg.Material; mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform).ToMatrixTransform3D(); if (materialsByStyleId[styleId].IsTransparent) { tmpTransparentsGroup.Children.Add(mg); } else { tmpOpaquesGroup.Children.Add(mg); } } if (tmpOpaquesGroup.Children.Any()) { var mv = new ModelVisual3D { Content = tmpOpaquesGroup }; opaqueShapes.Children.Add(mv); } if (tmpTransparentsGroup.Children.Any()) { var mv = new ModelVisual3D { Content = tmpTransparentsGroup }; transparentShapes.Children.Add(mv); } } } Logger.LogDebug("Time to load visual components: {0:F3} seconds", timer.Elapsed.TotalSeconds); ProgressChanged?.Invoke(this, new ProgressChangedEventArgs(0, "Ready")); return(scene); }
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); }
XbimScene <WpfMeshGeometry3D, WpfMaterial> ILayerStyler.BuildScene(IModel model, XbimMatrix3D modelTransform, ModelVisual3D opaqueShapes, ModelVisual3D transparentShapes, List <Type> exclude) { var excludedTypes = model.DefaultExclusions(exclude); var tmpOpaquesGroup = new Model3DGroup(); var retScene = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model); var meshes = new List <WpfMeshGeometry3D>(); if (_discriminator == null) { _discriminator = new VisualDiscriminator(_window.Doc); } if (_model.Instances == null || !_model.Instances.Any()) { return(retScene); } var red = PrepareMesh(_colourFail); meshes.Add(red); var green = PrepareMesh(_colourPass); meshes.Add(green); var blue = PrepareMesh(_colourNa); meshes.Add(blue); var amber = PrepareMesh(_colourWarning); meshes.Add(amber); foreach (var mesh in meshes) { mesh.WpfModel.SetValue(FrameworkElement.TagProperty, mesh); mesh.BeginUpdate(); tmpOpaquesGroup.Children.Add(mesh); } using (var geomStore = model.GeometryStore) { using (var geomReader = geomStore.BeginRead()) { var shapeInstances = geomReader.ShapeInstances .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !excludedTypes.Contains(s.IfcTypeId)); foreach (var shapeInstance in shapeInstances) { var ent = _model.Instances[shapeInstance.IfcProductLabel]; var grp = _discriminator.GetLayerGroup(ent); if (grp == VisualDiscriminator.LayerGroup.Null) { continue; } if (!UseBlue && grp == VisualDiscriminator.LayerGroup.Blue) { continue; } if (!UseAmber && grp == VisualDiscriminator.LayerGroup.Amber) { continue; } WpfMeshGeometry3D targetMergeMesh = null; switch (grp) { case VisualDiscriminator.LayerGroup.Red: targetMergeMesh = red; break; case VisualDiscriminator.LayerGroup.Green: targetMergeMesh = green; break; case VisualDiscriminator.LayerGroup.Blue: targetMergeMesh = blue; break; case VisualDiscriminator.LayerGroup.Amber: targetMergeMesh = amber; break; } if (targetMergeMesh == null) { continue; } IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapeGeom.Format == (byte)XbimGeometryType.PolyhedronBinary) { var transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform); targetMergeMesh.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, transform, (short)model.UserDefinedId); } } } } foreach (var mesh in meshes) { mesh.EndUpdate(); } if (!tmpOpaquesGroup.Children.Any()) { return(retScene); } var mv = new ModelVisual3D { Content = tmpOpaquesGroup }; opaqueShapes.Children.Add(mv); // no transparents are present //if (tmpTransparentsGroup.Children.Any()) //{ // var mv = new ModelVisual3D { Content = tmpTransparentsGroup }; // transparentShapes.Children.Add(mv); //} return(retScene); }
/// <summary> /// This version uses the new Geometry representation /// </summary> /// <param name="model"></param> /// <param name="modelTransform">The transform to place the models geometry in the right place</param> /// <param name="opaqueShapes"></param> /// <param name="transparentShapes"></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(IModel model, XbimMatrix3D modelTransform, ModelVisual3D opaqueShapes, ModelVisual3D transparentShapes, List <Type> exclude = null) { var excludedTypes = model.DefaultExclusions(exclude); var scene = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model); var timer = new Stopwatch(); timer.Start(); using (var geomStore = model.GeometryStore) { using (var geomReader = geomStore.BeginRead()) { var materialsByStyleId = new Dictionary <int, WpfMaterial>(); var repeatedShapeGeometries = new Dictionary <int, MeshGeometry3D>(); var meshesByStyleId = new Dictionary <int, WpfMeshGeometry3D>(); var tmpOpaquesGroup = new Model3DGroup(); var tmpTransparentsGroup = new Model3DGroup(); //get a list of all the unique style ids then build their style and mesh var sstyleIds = geomReader.StyleIds; foreach (var styleId in sstyleIds) { var wpfMaterial = GetWpfMaterial(model, styleId); materialsByStyleId.Add(styleId, wpfMaterial); var mg = GetNewStyleMesh(wpfMaterial, tmpTransparentsGroup, tmpOpaquesGroup); meshesByStyleId.Add(styleId, mg); } var shapeInstances = geomReader.ShapeInstances .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !excludedTypes.Contains(s.IfcTypeId)); var tot = shapeInstances.Count(); var prog = 0; var lastProgress = 0; // !typeof (IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& // !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/); foreach (var shapeInstance in shapeInstances) { // logging var currentProgress = 100 * prog++ / tot; if (currentProgress != lastProgress && ProgressChanged != null) { ProgressChanged(this, new ProgressChangedEventArgs(currentProgress, "Creating visuals")); lastProgress = currentProgress; // Log.DebugFormat("Progress to {0}% time: {1} seconds", lastProgress, timer.Elapsed.TotalSeconds.ToString("F3")); // Debug.Print("Progress to {0}% time:\t{1} seconds", lastProgress, timer.Elapsed.TotalSeconds.ToString("F3")); } // work out style var styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; if (!materialsByStyleId.ContainsKey(styleId)) { // if the style is not available we build one by ExpressType var material2 = GetWpfMaterialByType(model, shapeInstance.IfcTypeId); materialsByStyleId.Add(styleId, material2); var mg = GetNewStyleMesh(material2, tmpTransparentsGroup, tmpOpaquesGroup); meshesByStyleId.Add(styleId, mg); } //GET THE ACTUAL GEOMETRY MeshGeometry3D wpfMesh; //see if we have already read it if (UseMaps && repeatedShapeGeometries.TryGetValue(shapeInstance.ShapeGeometryLabel, out wpfMesh)) { var mg = new GeometryModel3D(wpfMesh, materialsByStyleId[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform) .ToMatrixTransform3D(); if (materialsByStyleId[styleId].IsTransparent) { tmpTransparentsGroup.Children.Add(mg); } else { tmpOpaquesGroup.Children.Add(mg); } } else //we need to get the shape geometry { IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (UseMaps && 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, materialsByStyleId[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform).ToMatrixTransform3D(); if (materialsByStyleId[styleId].IsTransparent) { tmpTransparentsGroup.Children.Add(mg); } else { tmpOpaquesGroup.Children.Add(mg); } } else //it is a one off, merge it with shapes of same style { var targetMergeMeshByStyle = meshesByStyleId[styleId]; if (shapeGeom.Format != (byte)XbimGeometryType.PolyhedronBinary) { continue; } var transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform); targetMergeMeshByStyle.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, transform, (short)model.UserDefinedId); } } } foreach (var wpfMeshGeometry3D in meshesByStyleId.Values) { wpfMeshGeometry3D.EndUpdate(); } //} if (tmpOpaquesGroup.Children.Any()) { var mv = new ModelVisual3D { Content = tmpOpaquesGroup }; opaqueShapes.Children.Add(mv); // Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); } if (tmpTransparentsGroup.Children.Any()) { var mv = new ModelVisual3D { Content = tmpTransparentsGroup }; transparentShapes.Children.Add(mv); //if (Control.ModelBounds.IsEmpty) Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); //else Control.ModelBounds.Union(mv.Content.Bounds.ToXbimRect3D()); } } } Log.DebugFormat("Time to load visual components: {0} seconds", timer.Elapsed.TotalSeconds.ToString("F3")); if (ProgressChanged != null) { ProgressChanged(this, new ProgressChangedEventArgs(0, "Ready")); } 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); }
/// <summary> /// Returns the next Shape geometry after a move or a seek call /// </summary> /// <param name="sg"></param> /// <returns></returns> public bool TryMoveNextShapeGeometry(ref IXbimShapeGeometryData sg) { if (Api.TryMoveNext(this.sesid, this.table)) { GetShapeGeometryData(sg); return true; } else return false; }
private void GetShapeGeometryData(IXbimShapeGeometryData sg) { Api.RetrieveColumns(sesid, table, _colValues); sg.ShapeLabel = Api.RetrieveColumnAsInt32(sesid, table, _colIdShapeLabel, RetrieveColumnGrbit.RetrieveFromIndex).Value; sg.IfcShapeLabel = _colValIfcShapeLabel.Value.Value; sg.GeometryHash = _colValGeometryHash.Value.Value; sg.ReferenceCount = _colValReferenceCount.Value.Value; sg.LOD = _colValLOD.Value.Value; sg.Format = _colValFormat.Value.Value; sg.ShapeDataCompressed = _colValShapeData.Value; sg.BoundingBox = _colValBoundingBox.Value; }
/// <summary> /// 获取几何数据 /// </summary> /// <param name="model"></param> /// <param name="shapeInstances"></param> /// <param name="geomReader"></param> /// <param name="materialsByStyleId"></param> public static void GetIFCPointFaceMaterial(IModel model, IEnumerable <XbimShapeInstance> shapeInstances, IGeometryStoreReader geomReader, Dictionary <int, WpfMaterial> materialsByStyleId) { if (shapeInstances != null) { int index = 0; //string jsonString = ""; StringBuilder jsonString = new StringBuilder(); foreach (var shapeInstance in shapeInstances) { //string faces_json = ""; StringBuilder faces_json = new StringBuilder(); string point_json = ""; //globalId var productId = shapeInstance.IfcProductLabel; IIfcProduct product = model.Instances[productId] as IIfcProduct; var globalId = product.GlobalId; //获取该实例的材质信息 var styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; var materialsByStyle = materialsByStyleId[styleId]; //var isTransparent = materialsByStyle.IsTransparent.ToString().ToLower();//是否透明 var materialsItem = materialsByStyle.Description.Split(' ');//材质描述 string materialString = ""; for (int i = 0; i < materialsItem.Length; i++) { if (i == 1 || i == 2 || i == 3 || i == 4) { materialString += ",\"" + materialsItem[i].Replace(":", "\":") + ""; } } if (materialString.Length > 0) { materialString = materialString.Substring(1).ToString(); } //求单个模型4向矩阵信息 var transfor = shapeInstance.Transformation; string matrixA = transfor.M11.ToString() + "," + transfor.M12.ToString() + "," + transfor.M13.ToString() + "," + transfor.M14.ToString() + ","; string matrixB = transfor.M21.ToString() + "," + transfor.M22.ToString() + "," + transfor.M23.ToString() + "," + transfor.M24.ToString() + ","; string matrixC = transfor.M31.ToString() + "," + transfor.M32.ToString() + "," + transfor.M33.ToString() + "," + transfor.M34.ToString() + ","; string matrixXYZ = transfor.OffsetX.ToString() + "," + transfor.OffsetY.ToString() + "," + transfor.OffsetZ.ToString() + ","; string matrixD = transfor.M44.ToString(); //拼接4向矩阵数据 string matrixString = matrixA + matrixB + matrixC + matrixXYZ + matrixD; var matrixItem = matrixString.Split(',');//字符串数组 //添加每个模型的position数据 double[] position = new double[3]; //转换成Int数组 double[] intItem = new double[16]; for (int i = 0; i < matrixItem.Length; i++) { intItem[i] = Convert.ToDouble(matrixItem[i]); } position[0] = intItem[12]; position[1] = intItem[13]; position[2] = intItem[14]; string matrix4 = JsonConvert.SerializeObject(intItem); string positionString = JsonConvert.SerializeObject(position); IXbimShapeGeometryData geometrya = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); var data = ((IXbimShapeGeometryData)geometrya).ShapeData; using (var stream = new MemoryStream(data)) { using (var reader = new BinaryReader(stream)) { var mesh = reader.ReadShapeTriangulation(); //查找模型所有的面 List <XbimFaceTriangulation> Faces = mesh.Faces as List <XbimFaceTriangulation>; if (Faces.Count > 0) { foreach (var item in Faces) { faces_json.Append(",{"); faces_json.Append("\"IsPlanar\":" + item.IsPlanar.ToString().ToLower()); faces_json.Append(",\"TriangleCount\":" + item.TriangleCount); faces_json.Append(",\"NormalCount\":" + 1); //faces_json.Append(",\"NormalCount\":" + item.NormalCount); faces_json.Append(",\"Indices\":" + JsonConvert.SerializeObject(item.Indices)); faces_json.Append(",\"Normals\":["); var normals = item.Normals; //normal由于重复暂时只取一个,能极大减小数据量 faces_json.Append("{\"X\":" + normals[0].Normal.X + ",\"Y\":" + normals[0].Normal.Y + ",\"Z\":" + normals[0].Normal.Z + ",\"Length\":" + normals[0].Normal.Length + ",\"Modulus\":" + normals[0].Normal.Modulus + ",\"U\":" + normals[0].U + ",\"V\":" + normals[0].V + "}"); faces_json.Append("]}"); } } //faces_json = JsonConvert.SerializeObject(Faces); //查找模型所有的点坐标 List <XbimPoint3D> Point = mesh.Vertices as List <XbimPoint3D>; point_json = JsonConvert.SerializeObject(Point); //将模型数据转换成json格式,保存至xxx.json文件 if (index != 0) { jsonString.Append(","); } jsonString.Append("{\"ObjectID\":\"" + globalId + "\",\"Position\":" + positionString + ",\"Matrix4\":" + matrix4 + ",\"Faces\":[" + faces_json.ToString().Substring(1) + "],\"Points\":" + point_json + ",\"Material\":{" + materialString + "}}"); //jsonString += ",{\"ObjectID\":\"" + globalId + "\",\"Matrix4\":" + matrix4 + ",\"Faces\":[" + faces_json.Substring(1) + "],\"Points\":" + point_json + ",\"Material\":{\"IsTransparent\":" + isTransparent + "," + materialString + "}}"; index++; } } } if (jsonString.Length > 0) { string jsonObject = "{\"ID\":\"" + GuidTo16String() + "\",\"Name\":\"" + IfcFileName + "\",\"Position\":" + JsonConvert.SerializeObject(namePosition[IfcFileName]) + ",\"Geometry\":["; jsonObject += jsonString.ToString(); //jsonObject += jsonString.ToString().Substring(1).ToString(); jsonObject += "]}"; if (jsonObject.Length > 2) { string fileNewName = filePath.Replace(".ifc", "") + "_M.json"; byte[] myByte = System.Text.Encoding.UTF8.GetBytes(jsonObject); using (FileStream fs = new FileStream(fileNewName, FileMode.Create)) { fs.Write(myByte, 0, myByte.Length); } } } } }
/// <summary> /// This version uses the new Geometry representation /// </summary> /// <param name="model"></param> /// <param name="modelTransform">The transform to place the models geometry in the right place</param> /// <param name="opaqueShapes"></param> /// <param name="transparentShapes"></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(IModel model, XbimMatrix3D modelTransform, ModelVisual3D opaqueShapes, ModelVisual3D transparentShapes, List <Type> exclude = null) { var excludedTypes = model.DefaultExclusions(exclude); var scene = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model); var timer = new Stopwatch(); timer.Start(); using (var geomStore = model.GeometryStore) { using (var geomReader = geomStore.BeginRead()) { var materialsByStyleId = new Dictionary <int, WpfMaterial>(); var repeatedShapeGeometries = new Dictionary <int, MeshGeometry3D>(); var meshesByStyleId = new Dictionary <int, WpfMeshGeometry3D>(); var tmpOpaquesGroup = new Model3DGroup(); var tmpTransparentsGroup = new Model3DGroup(); //get a list of all the unique style ids then build their style and mesh var sstyleIds = geomReader.StyleIds; foreach (var styleId in sstyleIds) { var wpfMaterial = GetWpfMaterial(model, styleId); materialsByStyleId.Add(styleId, wpfMaterial); var mg = GetNewStyleMesh(wpfMaterial, tmpTransparentsGroup, tmpOpaquesGroup); meshesByStyleId.Add(styleId, mg); } var shapeInstances = GetShapeInstancesToRender(geomReader, excludedTypes); var tot = 1; if (ProgressChanged != null) { // only enumerate if there's a need for progress update tot = shapeInstances.Count(); } var prog = 0; var lastProgress = 0; // !typeof (IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& // !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/); foreach (var shapeInstance in shapeInstances) { // logging var currentProgress = 100 * prog++ / tot; if (currentProgress != lastProgress && ProgressChanged != null) { ProgressChanged(this, new ProgressChangedEventArgs(currentProgress, "Creating visuals")); lastProgress = currentProgress; } // work out style var styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; if (!materialsByStyleId.ContainsKey(styleId)) { // if the style is not available we build one by ExpressType var material2 = GetWpfMaterialByType(model, shapeInstance.IfcTypeId); materialsByStyleId.Add(styleId, material2); var mg = GetNewStyleMesh(material2, tmpTransparentsGroup, tmpOpaquesGroup); meshesByStyleId.Add(styleId, mg); } //GET THE ACTUAL GEOMETRY MeshGeometry3D wpfMesh; //see if we have already read it if (UseMaps && repeatedShapeGeometries.TryGetValue(shapeInstance.ShapeGeometryLabel, out wpfMesh)) { var mg = new GeometryModel3D(wpfMesh, materialsByStyleId[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform) .ToMatrixTransform3D(); if (materialsByStyleId[styleId].IsTransparent) { tmpTransparentsGroup.Children.Add(mg); } else { tmpOpaquesGroup.Children.Add(mg); } } else //we need to get the shape geometry { IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (UseMaps && 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, materialsByStyleId[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform).ToMatrixTransform3D(); if (materialsByStyleId[styleId].IsTransparent) { tmpTransparentsGroup.Children.Add(mg); } else { tmpOpaquesGroup.Children.Add(mg); } } else //it is a one off, merge it with shapes of same style { var targetMergeMeshByStyle = meshesByStyleId[styleId]; // replace target mesh beyond suggested size // https://docs.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/maximize-wpf-3d-performance // if (targetMergeMeshByStyle.PositionCount > 20000 || targetMergeMeshByStyle.TriangleIndexCount > 60000 ) { targetMergeMeshByStyle.EndUpdate(); var replace = GetNewStyleMesh(materialsByStyleId[styleId], tmpTransparentsGroup, tmpOpaquesGroup); meshesByStyleId[styleId] = replace; targetMergeMeshByStyle = replace; } // end replace if (shapeGeom.Format != (byte)XbimGeometryType.PolyhedronBinary) { continue; } var transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform); targetMergeMeshByStyle.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, transform, (short)model.UserDefinedId); } } } foreach (var wpfMeshGeometry3D in meshesByStyleId.Values) { wpfMeshGeometry3D.EndUpdate(); } if (tmpOpaquesGroup.Children.Any()) { var mv = new ModelVisual3D { Content = tmpOpaquesGroup }; opaqueShapes.Children.Add(mv); } if (tmpTransparentsGroup.Children.Any()) { var mv = new ModelVisual3D { Content = tmpTransparentsGroup }; transparentShapes.Children.Add(mv); } } } Log.DebugFormat("Time to load visual components: {0:F3} seconds", timer.Elapsed.TotalSeconds); ProgressChanged?.Invoke(this, new ProgressChangedEventArgs(0, "Ready")); return(scene); }
/// <summary> /// Exports a gltf file from a meshed model /// </summary> /// <param name="model">The model needs to have the geometry meshes already cached</param> /// <param name="exclude">The types of elements that are going to be omitted (e.g. ifcSpaces).</param> /// <param name="EntityLebels">Only entities in the collection are exported; if null exports the whole model</param> /// <returns></returns> public gltf.Gltf BuildInstancedScene(IModel model, List <Type> exclude = null, HashSet <int> EntityLebels = null) { Init(); Dictionary <int, ShapeComponentIds> geometries = new Dictionary <int, ShapeComponentIds>(); // this needs a previously meshed xbim file. // var s = new Stopwatch(); s.Start(); int iCnt = 0; Random r = new Random(); var excludedTypes = DefaultExclusions(model, exclude); using (var geomStore = model.GeometryStore) using (var geomReader = geomStore.BeginRead()) { // process the materials and styles var sstyleIds = geomReader.StyleIds; foreach (var styleId in sstyleIds) { PrepareStyleMaterial(model, styleId); } int productLabel = 0; var shapeInstances = GetShapeInstancesToRender(geomReader, excludedTypes, EntityLebels); // foreach (var shapeInstance in shapeInstances.OrderBy(x=>x.IfcProductLabel)) gltf.Mesh targetMesh = null; foreach (var shapeInstance in shapeInstances.OrderBy(x => x.IfcProductLabel)) { if (CustomFilter != null) { var skip = CustomFilter(shapeInstance.IfcProductLabel, model); if (skip) { continue; } } // we start with a shape instance and then load its geometry. // a product (e.g. wall or window) in the scene returns: // - a node // - pointing to a mesh, with a transform // - 1 mesh // - with as many mesh primitives as needed to render the different parts // - pointers to the a material and accessors as needed // - 3 accessors per primitive // - vertices, normals, indices // - bufferviews can be reused by different accessors // - data in the buffer, of course if (productLabel != shapeInstance.IfcProductLabel) { // need new product // create node var nodeIndex = _nodes.Count; var entity = model.Instances[shapeInstance.IfcProductLabel] as IIfcProduct; if (entity == null) { // fire error here. } var tnode = new gltf.Node(); tnode.Name = entity.Name + $" #{entity.EntityLabel}"; tnode.Matrix = GetTransformInMeters(model, shapeInstance); // create mesh var meshIndex = _meshes.Count; targetMesh = new gltf.Mesh { Name = $"Instance {productLabel}" }; // link node to mesh tnode.Mesh = meshIndex; // add all to lists _nodes.Add(tnode); _meshes.Add(targetMesh); } // now the geometry // IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapeGeom.Format != (byte)XbimGeometryType.PolyhedronBinary) { continue; } // work out colour id; // the colour is associated with the instance, not the geometry. // positives are styles, negatives are types var colId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; int materialIndex; if (!styleDic.TryGetValue(colId, out materialIndex)) { // if the style is not available we build one by ExpressType materialIndex = PrepareTypeMaterial(model, shapeInstance.IfcTypeId); styleDic.Add(colId, materialIndex); } // note: at a first investigation it looks like the shapeInstance.Transformation is the same for all shapes of the same product if (shapeGeom.ReferenceCount > 1) { // retain the information to reuse the map multiple times // // if g is not found in the dictionary then build it and add it ShapeComponentIds components; if (!geometries.TryGetValue(shapeGeom.ShapeLabel, out components)) { // mesh var xbimMesher = new XbimMesher(); xbimMesher.AddMesh(shapeGeom.ShapeData); components = AddGeom( xbimMesher.PositionsAsSingleList(model.ModelFactors.OneMeter), xbimMesher.Indices, xbimMesher.NormalsAsSingleList() ); geometries.Add(shapeGeom.ShapeLabel, components); } if (components != null) { var arr = GetTransformInMeters(model, shapeInstance); AddComponentsToMesh(targetMesh, components, materialIndex); } } else { // repeat the geometry only once // var xbimMesher = new XbimMesher(); xbimMesher.AddMesh(shapeGeom.ShapeData); var trsf = GetTransformInMeters(model, shapeInstance); var components = AddGeom( xbimMesher.PositionsAsSingleList(model.ModelFactors.OneMeter), xbimMesher.Indices, xbimMesher.NormalsAsSingleList() ); AddComponentsToMesh(targetMesh, components, materialIndex); } iCnt++; if (iCnt % 100 == 0) { Debug.WriteLine($"added {iCnt} elements in {s.ElapsedMilliseconds}ms."); } } } Debug.WriteLine($"added {iCnt} elements in {s.ElapsedMilliseconds}ms."); return(Build()); }
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(); } }
public int AddGeometry(IXbimShapeGeometryData shapeGeom) { int mainId = 0; using (var update = new Update(sesid, table, JET_prep.Insert)) { _colValIfcShapeLabel.Value = shapeGeom.IfcShapeLabel; _colValGeometryHash.Value = shapeGeom.GeometryHash; _colValCost.Value = shapeGeom.Cost; _colValReferenceCount.Value = shapeGeom.ReferenceCount; _colValLOD.Value = shapeGeom.LOD; _colValFormat.Value = shapeGeom.Format; _colValShapeData.Value = shapeGeom.ShapeDataCompressed; _colValBoundingBox.Value = shapeGeom.BoundingBox; Api.SetColumns(sesid, table, _colValues); mainId = Api.RetrieveColumnAsInt32(sesid, table, _colIdShapeLabel, RetrieveColumnGrbit.RetrieveCopy).Value; update.Save(); UpdateCount(1); shapeGeom.ShapeLabel = mainId; } return mainId; }
/// <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); }
/// <summary> /// Seeks and returns the first shape geometry /// </summary> /// <param name="sg"></param> public bool TryMoveFirstShapeGeometry(ref IXbimShapeGeometryData sg) { Api.JetSetCurrentIndex(sesid, table, geometryTablePrimaryIndex); if (TryMoveFirst()) { GetShapeGeometryData(sg); return true; } else { return false; } }
XbimScene <WpfMeshGeometry3D, WpfMaterial> ILayerStyler.BuildScene(IModel model, XbimMatrix3D modelTransform, ModelVisual3D opaqueShapes, ModelVisual3D transparentShapes, List <Type> exclude) { var excludedTypes = model.DefaultExclusions(exclude); var tmpOpaquesGroup = new Model3DGroup(); var retScene = new XbimScene <WpfMeshGeometry3D, WpfMaterial>(model); if (_model.Instances == null || !_model.Instances.Any()) { return(retScene); } // define colours var colours = new Dictionary <LayerGroup, XbimColour>(); colours.Add(LayerGroup.Green, new XbimColour("Green", 0.0, 1.0, 0.0, 0.5)); colours.Add(LayerGroup.Red, new XbimColour("Red", 1.0, 0.0, 0.0, 0.5)); colours.Add(LayerGroup.Amber, new XbimColour("Amber", .5, 0.5, .5, .8)); // actually grey // prepare meshes // var meshes = new List <WpfMeshGeometry3D>(); // this list gets added to the scene at the end. // this dictionary holds the list of meshes that are currently used, as they are filled (in size), // new ones get replaced // var meshDic = new Dictionary <LayerGroup, WpfMeshGeometry3D>(); foreach (var group in colours.Keys) { var newItem = PrepareMesh(colours[group]); meshDic.Add(group, newItem); meshes.Add(newItem); } foreach (var mesh in meshes) { mesh.WpfModel.SetValue(FrameworkElement.TagProperty, mesh); mesh.BeginUpdate(); tmpOpaquesGroup.Children.Add(mesh); } using (var geomStore = model.GeometryStore) { using (var geomReader = geomStore.BeginRead()) { var shapeInstances = geomReader.ShapeInstances .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !excludedTypes.Contains(s.IfcTypeId)); foreach (var shapeInstance in shapeInstances) { var ent = _model.Instances[shapeInstance.IfcProductLabel]; var grp = GetLayerGroup(ent); if (grp == LayerGroup.Null) { continue; } if (!UseAmber && grp == LayerGroup.Amber) { continue; } WpfMeshGeometry3D targetMergeMesh; meshDic.TryGetValue(grp, out targetMergeMesh); if (targetMergeMesh == null) { continue; } // replace target mesh beyond suggested size // https://docs.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/maximize-wpf-3d-performance // if (targetMergeMesh.PositionCount > 20000 || targetMergeMesh.TriangleIndexCount > 60000 ) { // end current mesh targetMergeMesh.EndUpdate(); // prepare new one and add to the list var replace = PrepareMesh(colours[grp]); meshes.Add(replace); // swap mesh in dicionary and for this loop meshDic[grp] = replace; targetMergeMesh = replace; // prepare in output replace.WpfModel.SetValue(FrameworkElement.TagProperty, replace); replace.BeginUpdate(); tmpOpaquesGroup.Children.Add(replace); } IXbimShapeGeometryData shapeGeom = geomReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapeGeom.Format == (byte)XbimGeometryType.PolyhedronBinary) { var transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, modelTransform); targetMergeMesh.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, transform, (short)model.UserDefinedId); } } } } foreach (var mesh in meshDic.Values) { mesh.EndUpdate(); } if (!tmpOpaquesGroup.Children.Any()) { return(retScene); } var mv = new ModelVisual3D { Content = tmpOpaquesGroup }; opaqueShapes.Children.Add(mv); return(retScene); }
/// <summary> /// Returns the shape geometry for the specified label if it exists /// </summary> /// <param name="shapeGeometryLabel"></param> /// <param name="sg"></param> /// <returns></returns> public bool TryGetShapeGeometry(int shapeGeometryLabel, ref IXbimShapeGeometryData sg) { Api.JetSetCurrentIndex(sesid, table, geometryTablePrimaryIndex); Api.MakeKey(sesid, table, shapeGeometryLabel, MakeKeyGrbit.NewKey); if (Api.TrySeek(sesid, table, SeekGrbit.SeekEQ)) { GetShapeGeometryData(sg); return true; } else { return false; } }
public BimStore3DModel Load(string fileName) { var bimStoreItems = new Dictionary <IPersistEntity, List <Tuple <MeshGeometry3D, MaterialModel, XbimMatrix3D> > > (); //ID - ifcProductLabel var ifcModel = IfcStore.Open(fileName, null, null, (progress, state) => { reportProgress?.Invoke(progress, state); }, XbimDBAccess.Exclusive); //Prepare var modelPosition = new XbimModelPositioning(ifcModel); var context = new Xbim3DModelContext(ifcModel); context.CreateContext(); //Clear materials MaterialManager.Clear(); var materialsByStyleId = new Dictionary <int, MaterialModel>(); var excludedTypes = GenerateDefaultExclusions(ifcModel, DefaultExcludedTypes); using (var geometryStore = ifcModel.ReferencingModel.GeometryStore) { using (var geometryReader = geometryStore.BeginRead()) { var shapeInstances = GetShapeInstancesToRender(geometryReader, excludedTypes); foreach (var shapeInstance in shapeInstances) { #region Material var styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; MaterialModel material; if (!materialsByStyleId.ContainsKey(styleId)) { material = MaterialModelCreator.Create(ifcModel, shapeInstance.IfcTypeId); materialsByStyleId.Add(styleId, material); MaterialManager.Add(material); } else { material = materialsByStyleId[styleId]; } #endregion #region Geometry IXbimShapeGeometryData shapeGeometry = geometryReader.ShapeGeometry(shapeInstance.ShapeGeometryLabel); var geometry3D = new MeshGeometry3D(); switch ((XbimGeometryType)shapeGeometry.Format) { case XbimGeometryType.PolyhedronBinary: geometry3D.Read(shapeGeometry.ShapeData); break; case XbimGeometryType.Polyhedron: geometry3D.Read(((XbimShapeGeometry)shapeGeometry).ShapeData); break; } #endregion var ifcProduct = ifcModel.Model.Instances.FirstOrDefault(i => i.EntityLabel == shapeInstance.IfcProductLabel); if (ifcProduct != null) { if (!bimStoreItems.ContainsKey(ifcProduct)) { bimStoreItems.Add(ifcProduct, new List <Tuple <MeshGeometry3D, MaterialModel, XbimMatrix3D> >(new [] { new Tuple <MeshGeometry3D, MaterialModel, XbimMatrix3D>(geometry3D, material, XbimMatrix3D.Multiply(modelPosition.Transform, shapeInstance.Transformation)), })); } else { bimStoreItems[ifcProduct].Add(new Tuple <MeshGeometry3D, MaterialModel, XbimMatrix3D>(geometry3D, material, XbimMatrix3D.Multiply(modelPosition.Transform, shapeInstance.Transformation))); } } } } } //Generate model var bimStore3D = new BimStore3DModel(context.Model as IfcStore); foreach (var bimStoreItem in bimStoreItems) { bimStore3D.Add( new BimStoreItem3DModel(bimStoreItem.Key, new List <BimGeometry3DModel>( bimStoreItem.Value.Select(x => new BimGeometry3DModel( x.Item1.ToMeshModel(), x.Item2, x.Item3.ToMatrix3D()))))); } return(bimStore3D); }