public void FileVersionIsCorrect() { var m = new XbimModel(); m.Open("Monolith_v10.xBIM"); Assert.AreEqual(1, m.GeometrySupportLevel, "GeometrySupportLevel for Monolith_v10 should be 1"); m.Close(); m.Open("Monolith_v20.xBIM"); Assert.AreEqual(2, m.GeometrySupportLevel, "GeometrySupportLevel for Monolith_v20 should be 2"); m.Close(); }
public void CanGetRawGeometry() { var m = new XbimModel(); m.Open("Monolith_v20.xBIM"); var w1 = m.Instances.OfType<IfcWall>().FirstOrDefault(); var msh = m.GetMesh(new[] {w1}, XbimMatrix3D.Identity); Assert.AreEqual(24, msh.PositionCount, "Unexpected value"); m.Close(); m.Open("Monolith_v10.xBIM"); w1 = m.Instances.OfType<IfcWall>().FirstOrDefault(); msh = m.GetMesh(new[] { w1 }, XbimMatrix3D.Identity); Assert.AreEqual(24, msh.PositionCount, "Unexpected value"); m.Close(); }
public void EscapeHeaderTests() { const string path = @"x:\path1\path2\filename.ifc"; const string umlaut = "name with umlaut ü"; using (var model = XbimModel.CreateTemporaryModel()) { model.Initialise("Creating Author", " Creating Organisation", "This Application", "This Developer", "v1.1"); using (var txn = model.BeginTransaction()) { model.IfcProject.Name = "Project Name"; txn.Commit(); } model.Header.FileName.Name = path; model.Header.FileName.Organization.Add(umlaut); model.SaveAs("testOutput.ifc"); } using (var model = new XbimModel()) { model.CreateFrom("testOutput.ifc", null, null, true); Assert.IsTrue(model.Header.FileName.Name == path); Assert.IsTrue(model.Header.FileName.Organization.FirstOrDefault() == umlaut); model.Close(); } }
public void CopyAllEntitiesTest() { using (var source = new XbimModel()) { PropertyTranformDelegate propTransform = delegate(IfcMetaProperty prop, object toCopy) { var value = prop.PropertyInfo.GetValue(toCopy, null); return value; }; source.Open("BIM Logo-LetterM.xBIM"); source.SaveAs("WithGeometry.ifc"); using (var target = XbimModel.CreateTemporaryModel()) { target.AutoAddOwnerHistory = false; using (var txn = target.BeginTransaction()) { var copied = new XbimInstanceHandleMap(source, target); foreach (var item in source.Instances) { target.InsertCopy(item, copied, txn, propTransform); } txn.Commit(); } target.SaveAs("WithoutGeometry.ifc"); } source.Close(); //the two files should be the same } }
public void QueryingNestedPropFunction() { // DirectoryInfo d = new DirectoryInfo("."); // to find folder location XbimModel model = new XbimModel(); model.Open(SourceModelFileName, XbimDBAccess.Read); var chkCnt = model.Query("select @12275.Representation.Representations"); Assert.AreEqual(3, ((IEnumerable<object>)chkCnt).Count()); model.Close(); }
private static void CreateXbimFile(string fileName) { string xbimFileName = Path.ChangeExtension(fileName, ".xbim"); XbimModel model = new XbimModel(); model.CreateFrom(fileName, xbimFileName, null); model.Open(xbimFileName, XbimDBAccess.ReadWrite); XbimScene.ConvertGeometry(model.Instances.OfType<IfcProduct>().Where(t => !(t is IfcFeatureElement)),null, false); model.Close(); }
public void OpenIfcXmlFile() { using (var model = new XbimModel()) { model.CreateFrom("4walls1floorSite.ifcxml"); model.Close(); } }
public IModel OpenIfcModel() { IModel model = new XbimModel(); string xbimName = Path.ChangeExtension(TestSourceFileIfc, "xbim"); model.CreateFrom(TestSourceFileIfc, xbimName); model.Close(); model = new XbimModel(); model.Open(xbimName); return model; }
private void OpenIfcFile(object s, DoWorkEventArgs args) { var worker = s as BackgroundWorker; var ifcFilename = args.Argument as string; var model = new XbimModel(); try { _temporaryXbimFileName = Path.GetTempFileName(); SetOpenedModelFileName(ifcFilename); if (worker != null) { model.CreateFrom(ifcFilename, _temporaryXbimFileName, worker.ReportProgress, true); var context = new Xbim3DModelContext(model);//upgrade to new geometry represenation, uses the default 3D model context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: worker.ReportProgress, adjustWCS: false); if (worker.CancellationPending) //if a cancellation has been requested then don't open the resulting file { try { model.Close(); if (File.Exists(_temporaryXbimFileName)) { File.Delete(_temporaryXbimFileName); //tidy up; } _temporaryXbimFileName = null; SetOpenedModelFileName(null); } // ReSharper disable once EmptyGeneralCatchClause catch { } return; } } args.Result = model; } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("Error reading " + ifcFilename); var indent = "\t"; while (ex != null) { sb.AppendLine(indent + ex.Message); ex = ex.InnerException; indent += "\t"; } args.Result = new Exception(sb.ToString()); } }
public void FileVersionIsCorrect() { var m = new XbimModel(); m.Open("Monolith-NoGeomTables.xBIM", XbimDBAccess.ReadWrite); Assert.AreEqual(0, m.GeometrySupportLevel, "GeometrySupportLevel should be 0"); m.Close(); m.Open("Monolith_Nogeom_Version1Schema.xBIM"); Assert.AreEqual(0, m.GeometrySupportLevel, "GeometrySupportLevel should be 0"); m.Close(); m.Open("Monolith_v10.xBIM"); Assert.AreEqual(1, m.GeometrySupportLevel, "GeometrySupportLevel for Monolith_v10 should be 1"); m.Close(); m.Open("Monolith_v20.xBIM"); Assert.AreEqual(2, m.GeometrySupportLevel, "GeometrySupportLevel for Monolith_v20 should be 2"); m.Close(); }
public void OpenIfcXmlFileFromStream() { using (var fileStream = new FileStream("4walls1floorSite.ifcxml", FileMode.Open, FileAccess.Read)) { using (var model = new XbimModel()) { model.CreateFrom(fileStream, XbimStorageType.IFC, "4walls1floorSite.xbim"); model.Close(); } fileStream.Close(); } }
public void ExtractIfcGeometryEntitiesTest() { using (var source = new XbimModel()) { PropertyTranformDelegate propTransform = delegate(IfcMetaProperty prop, object toCopy) { if (typeof(IfcProduct).IsAssignableFrom(toCopy.GetType())) { if (prop.PropertyInfo.Name == "ObjectPlacement" || prop.PropertyInfo.Name == "Representation") { return(null); } } if (typeof(IfcTypeProduct).IsAssignableFrom(toCopy.GetType())) { if (prop.PropertyInfo.Name == "RepresentationMaps") { return(null); } } return(prop.PropertyInfo.GetValue(toCopy, null));//just pass through the value }; //source.Open("BIM Logo-LetterM.xBIM"); //source.SaveAs("WithGeometry.ifc"); string modelName = @"4walls1floorSite"; string xbimModelName = Path.ChangeExtension(modelName, "xbim"); source.CreateFrom(Path.ChangeExtension(modelName, "ifc"), null, null, true); using (var target = XbimModel.CreateModel(Path.ChangeExtension(modelName + "_NoGeom", "xbim"))) { target.AutoAddOwnerHistory = false; using (var txn = target.BeginTransaction()) { var copied = new XbimInstanceHandleMap(source, target); foreach (var item in source.Instances.OfType <IfcRoot>()) { target.InsertCopy(item, copied, txn, propTransform, false); } txn.Commit(); } target.SaveAs(Path.ChangeExtension(modelName + "_NoGeom", "ifc")); target.Close(); } source.Close(); // XbimModel.Compact(Path.ChangeExtension(modelName + "_NoGeom", "xbim"), Path.ChangeExtension(modelName + "_NoGeom_Compacted", "xbim")); //the two files should be the same } }
public void OpenIfcZipFileFromStream() { using (var fileStream = new FileStream("4walls1floorSite.ifczip", FileMode.Open, FileAccess.Read)) { using (var model = new XbimModel()) { model.CreateFrom(fileStream, XbimStorageType.IFC, "4walls1floorSite.xbim"); model.Close(); } fileStream.Close(); } }
public void ModelRootBasicQuery() { // DirectoryInfo d = new DirectoryInfo("."); // to find folder location XbimModel model = new XbimModel(); model.Open(SourceModelFileName, XbimDBAccess.Read); var cnt = model.Instances.OfType("IfcWall", false).Count(); var chkCnt = model.Query("select @ifcWall"); var c2 = chkCnt as IEnumerable<IPersistIfcEntity>; int cnt2 = c2.Count(); Assert.AreEqual(cnt, cnt2); model.Close(); }
private static void IfcFeaturesClassificationIsCorrect(string ifcFileFullName) { var xbimFileFullName = Path.ChangeExtension(ifcFileFullName, ".xbim"); using (var m = new XbimModel()) { m.CreateFrom(ifcFileFullName, xbimFileFullName, null, true, true); var context = new Xbim3DModelContext(m); context.CreateContext(XbimGeometryType.PolyhedronBinary); TestForClassificationOfIfcFeatureElements(context); m.Close(); } }
private void OpenIfcFile(object s, DoWorkEventArgs args) { var worker = s as BackgroundWorker; var ifcFilename = args.Argument as string; var model = new XbimModel(); try { _temporaryXbimFileName = Path.GetTempFileName(); _openedModelFileName = ifcFilename; if (worker != null) { model.CreateFrom(ifcFilename, _temporaryXbimFileName, worker.ReportProgress, true); if (worker.CancellationPending) // if a cancellation has been requested then don't open the resulting file { try { model.Close(); if (File.Exists(_temporaryXbimFileName)) { File.Delete(_temporaryXbimFileName); } _temporaryXbimFileName = null; _openedModelFileName = null; } catch (Exception ex) { Debug.WriteLine(ex.Message); } return; } } args.Result = model; } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("Error reading " + ifcFilename); var indent = "\t"; while (ex != null) { sb.AppendLine(indent + ex.Message); ex = ex.InnerException; indent += "\t"; } args.Result = new Exception(sb.ToString()); } }
/// <summary> /// This is called when we explcitly want to open an xBIM file /// </summary> /// <param name = "s"></param> /// <param name = "args"></param> private void OpenXbimFile(object s, DoWorkEventArgs args) { var worker = s as BackgroundWorker; var fileName = args.Argument as string; var model = new XbimModel(); try { var dbAccessMode = _fileAccessMode; if (worker != null) { model.Open(fileName, dbAccessMode, worker.ReportProgress); //load entities into the model if (model.IsFederation) { // needs to open the federation in rw mode if (dbAccessMode != XbimDBAccess.ReadWrite) { model.Close(); model.Open(fileName, XbimDBAccess.ReadWrite, worker.ReportProgress); // federations need to be opened in read/write for the editor to work } // sets a convenient integer to all children for model identification // this is used by the federated model selection mechanisms. var i = 0; foreach (var item in model.AllModels) { item.Tag = i++; } } } args.Result = model; } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("Error reading " + fileName); var indent = "\t"; while (ex != null) { sb.AppendLine(indent + ex.Message); ex = ex.InnerException; indent += "\t"; } args.Result = new Exception(sb.ToString()); } }
private void OpenIfcFile(object s, DoWorkEventArgs args) { BackgroundWorker worker = s as BackgroundWorker; string ifcFilename = args.Argument as string; XbimModel model = new XbimModel(); try { _temporaryXbimFileName = Path.GetTempFileName(); _openedModelFileName = ifcFilename; model.CreateFrom(ifcFilename, _temporaryXbimFileName, worker.ReportProgress, true, false); Xbim3DModelContext context = new Xbim3DModelContext(model);//upgrade to new geometry represenation, uses the default 3D model context.CreateContext(progDelegate: worker.ReportProgress); if (worker.CancellationPending == true) //if a cancellation has been requested then don't open the resulting file { try { model.Close(); if (File.Exists(_temporaryXbimFileName)) { File.Delete(_temporaryXbimFileName); //tidy up; } _temporaryXbimFileName = null; _openedModelFileName = null; } catch (Exception) { } return; } args.Result = model; } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Error reading " + ifcFilename); string indent = "\t"; while (ex != null) { sb.AppendLine(indent + ex.Message); ex = ex.InnerException; indent += "\t"; } args.Result = new Exception(sb.ToString()); } }
public void GroupNRM() { Debug.WriteLine(Directory.GetCurrentDirectory()); XbimModel model = new XbimModel(); model.Open(TestXbimFile, XbimExtensions.XbimDBAccess.ReadWrite); GroupsFromXml g = new GroupsFromXml(model); g.CreateGroups(XmlNRM_ClassFile); GroupingByXml grouping = new GroupingByXml(model); grouping.GroupElements(XmlNRM_RulesFile); model.Close(); }
public void CanUpgradeDbStucture() { using (var m = new XbimModel()) { m.Open(@"Persistency\Monolith_v10.xBIM", XbimDBAccess.Exclusive); Assert.AreEqual(1, m.GeometrySupportLevel, "GeometrySupportLevel for Monolith_v10 should be 1"); var updated = m.EnsureGeometryTables(); Assert.AreEqual(updated, true, "Should complete returning true"); m.DeleteGeometryCache(); Assert.AreEqual(0, m.GeometrySupportLevel, "GeometrySupportLevel for Monolith_v10 should be 0 after removing it."); m.Close(); } }
public void ConverIfcToWexBim() { const string ifcFileFullName = @"Lakeside_Restaurant.ifc"; var fileName = Path.GetFileName(ifcFileFullName); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); var workingDir = Directory.GetCurrentDirectory(); var coreFileName = Path.Combine(workingDir, fileNameWithoutExtension); var wexBimFileName = Path.ChangeExtension(coreFileName, "wexbim"); var xbimFile = Path.ChangeExtension(coreFileName, "xbim"); try { using (var wexBimFile = new FileStream(wexBimFileName, FileMode.Create)) { using (var binaryWriter = new BinaryWriter(wexBimFile)) { using (var model = new XbimModel()) { try { model.CreateFrom(ifcFileFullName, xbimFile, null, true); var geomContext = new Xbim3DModelContext(model); geomContext.CreateContext(XbimGeometryType.PolyhedronBinary); geomContext.Write(binaryWriter); } finally { model.Close(); binaryWriter.Flush(); wexBimFile.Close(); } } } } } catch (Exception e) { Assert.Fail("Failed to process " + ifcFileFullName + " - " + e.Message); } }
public void GeometryVersionUpgradeTest() { using (var model = new XbimModel()) { // start afresh model.Open(@"GConv\Monolith_v10.xBIM", XbimDBAccess.Exclusive); Assert.AreEqual(1, model.GeometrySupportLevel); // now remove the existing geometry model.DeleteGeometryCache(); Assert.AreEqual(0, model.GeometrySupportLevel); // now create the geometry back model.EnsureGeometryTables(); // update the database structure first var context = new Xbim3DModelContext(model); context.CreateContext(XbimGeometryType.PolyhedronBinary); // then populate it // final tests Assert.AreEqual(2, model.GeometrySupportLevel); // and tidy up model.Close(); } }
public void QueryingSelectFunction() { // DirectoryInfo d = new DirectoryInfo("."); // to find folder location XbimModel model = new XbimModel(); model.Open(SourceModelFileName, XbimDBAccess.Read); var cnt = model.Instances.OfType("IfcWall", false).Count(); var chkCnt = model.Query("select @ifcWall.Count()"); Assert.AreEqual(cnt.ToString(), chkCnt.ToString()); model.Close(); }
public static void ConvertIfcToWexbimAndCobie(Stream input, CloudBlockBlob outputWexbimBlob, CloudBlockBlob outputCobieBlob, string inputExtension) { //temp files var fileName = Path.GetTempPath() + Guid.NewGuid() + inputExtension; var xbimFileName = Path.ChangeExtension(fileName, ".xBIM"); var wexBimFileName = Path.ChangeExtension(fileName, ".wexBIM"); var cobieFileName = Path.ChangeExtension(fileName, ".json"); try { using (var fileStream = File.OpenWrite(fileName)) { input.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); //open the model and import using (var model = new XbimModel()) { model.CreateFrom(fileName, null, null, true); var m3DModelContext = new Xbim3DModelContext(model); using (var wexBimFile = new FileStream(wexBimFileName, FileMode.Create)) { using (var bw = new BinaryWriter(wexBimFile)) { m3DModelContext.CreateContext(XbimGeometryType.PolyhedronBinary); m3DModelContext.Write(bw); bw.Close(); wexBimFile.Close(); outputWexbimBlob.UploadFromFile(wexBimFileName, FileMode.Open); } } using (var cobieFile = new FileStream(cobieFileName, FileMode.Create)) { var helper = new CoBieLiteHelper(model, "UniClass"); var facility = helper.GetFacilities().FirstOrDefault(); if (facility != null) { using (var writer = new StreamWriter(cobieFile)) { CoBieLiteHelper.WriteJson(writer, facility); writer.Close(); outputCobieBlob.UploadFromFile(cobieFileName, FileMode.Open); } } } model.Close(); } } } finally { //tidy up if (File.Exists(fileName)) { File.Delete(fileName); } if (File.Exists(xbimFileName)) { File.Delete(xbimFileName); } if (File.Exists(wexBimFileName)) { File.Delete(wexBimFileName); } if (File.Exists(cobieFileName)) { File.Delete(cobieFileName); } } }
private ProcessResult ProcessFile(string ifcFile, StreamWriter writer) { RemoveFiles(ifcFile); long geomTime = -1; long parseTime = -1; using (EventTrace eventTrace = LoggerFactory.CreateEventTrace()) { ProcessResult result = new ProcessResult() { Errors = -1 }; try { Stopwatch watch = new Stopwatch(); watch.Start(); using (XbimModel model = ParseModelFile(ifcFile, Params.Caching)) { parseTime = watch.ElapsedMilliseconds; string xbimFilename = BuildFileName(ifcFile, ".xbim"); //model.Open(xbimFilename, XbimDBAccess.ReadWrite); //if (_params.GeometryV1) // XbimMesher.GenerateGeometry(model, Logger, null); //else //{ Xbim3DModelContext context = new Xbim3DModelContext(model); context.CreateContext(XbimGeometryType.PolyhedronBinary); //} geomTime = watch.ElapsedMilliseconds - parseTime; //XbimSceneBuilder sb = new XbimSceneBuilder(); //string xbimSceneName = BuildFileName(ifcFile, ".xbimScene"); //sb.BuildGlobalScene(model, xbimSceneName); // sceneTime = watch.ElapsedMilliseconds - geomTime; IIfcFileHeader header = model.Header; watch.Stop(); IfcOwnerHistory ohs = model.Instances.OfType <IfcOwnerHistory>().FirstOrDefault(); result = new ProcessResult { ParseDuration = parseTime, GeometryDuration = geomTime, // SceneDuration = sceneTime, FileName = ifcFile.Remove(0, Params.TestFileRoot.Length).TrimStart('\\'), Entities = model.Instances.Count, IfcSchema = header.FileSchema.Schemas.FirstOrDefault(), IfcDescription = String.Format("{0}, {1}", header.FileDescription.Description.FirstOrDefault(), header.FileDescription.ImplementationLevel), GeometryEntries = model.GeometriesCount, IfcLength = ReadFileLength(ifcFile), XbimLength = ReadFileLength(xbimFilename), SceneLength = 0, IfcProductEntries = model.Instances.CountOf <IfcProduct>(), IfcSolidGeometries = model.Instances.CountOf <IfcSolidModel>(), IfcMappedGeometries = model.Instances.CountOf <IfcMappedItem>(), BooleanGeometries = model.Instances.CountOf <IfcBooleanResult>(), BReps = model.Instances.CountOf <IfcFaceBasedSurfaceModel>() + model.Instances.CountOf <IfcShellBasedSurfaceModel>() + model.Instances.CountOf <IfcManifoldSolidBrep>(), Application = ohs == null ? "Unknown" : ohs.OwningApplication.ToString(), }; model.Close(); } } catch (Exception ex) { Logger.Error(String.Format("Problem converting file: {0}", ifcFile), ex); result.Failed = true; } finally { result.Errors = (from e in eventTrace.Events where (e.EventLevel == EventLevel.ERROR) select e).Count(); result.Warnings = (from e in eventTrace.Events where (e.EventLevel == EventLevel.WARN) select e).Count(); result.FileName = ifcFile.Remove(0, Params.TestFileRoot.Length).TrimStart('\\'); if (eventTrace.Events.Count > 0) { CreateLogFile(ifcFile, eventTrace.Events); } writer.WriteLine(result.ToCsv()); writer.Flush(); } return(result); } }
public void AddRecordsCountRollbackTest() { using (XbimModel model = new XbimModel()) { Assert.IsTrue(model.Open(SourceFile, XbimDBAccess.ReadWrite)); int inserts = 100; long initTotalCount = model.Instances.Count; long initPointCount = model.Instances.CountOf<IfcCartesianPoint>(); using (var txn = model.BeginTransaction()) { for (int i = 0; i < inserts; i++) { model.Instances.New<IfcCartesianPoint>(p => p.SetXYZ(1, 2, 3)); } long newTotalCount = model.Instances.Count; long newPointCount = model.Instances.CountOf<IfcCartesianPoint>(); Assert.AreEqual(inserts + initTotalCount, newTotalCount); Assert.AreEqual(inserts + initPointCount, newPointCount); } long finalCount = model.Instances.Count; long finalPointCount = model.Instances.CountOf<IfcCartesianPoint>(); model.Close(); Assert.AreEqual(finalCount, initTotalCount); //check everything undid Assert.AreEqual(initPointCount, finalPointCount); } }
private string CreateSemanticContent(string xbimSourceFile) { string xbimFilePath = Path.GetDirectoryName(xbimSourceFile); string nonGeomXbimFileName = CreateTempFile(xbimFilePath, ".xbim"); // create xbim semantic file without geometry XbimModel modelServer = new XbimModel(); modelServer.Open(xbimSourceFile); //srl to fix throw new Exception("To Fix"); // modelServer.ExtractSemantic(nonGeomXbimFileName, XbimStorageType.XBIM, null); modelServer.Close(); return nonGeomXbimFileName; }
public void CheckReferenceModels() { using (XbimModel model = XbimModel.CreateModel("ReferenceTestModel.xBIM")) { using (var txn = model.BeginTransaction()) { //create an author of the referenced model IfcOrganization org = model.Instances.New<IfcOrganization>(); IfcActorRole role = model.Instances.New<IfcActorRole>(); role.Role=IfcRole.Architect; org.Name="Grand Designers"; org.AddRole(role); //reference in the other model model.AddModelReference(SourceFile, org); txn.Commit(); } //ensure everything is closed model.Close(); //open the referenced model to get count long originalCount; using ( XbimModel original = new XbimModel()) { original.Open(SourceFile); originalCount = original.Instances.Count; original.Close(); } //open the referencing model to get count long referencingCount; using (XbimModel referencing = new XbimModel()) { referencing.Open("ReferenceTestModel.xBIM"); referencingCount = referencing.InstancesLocal.Count; foreach (var refModel in referencing.RefencedModels) { referencingCount += refModel.Model.Instances.Count; } referencing.Close(); } //there should be 3 more instances than in the original model Assert.IsTrue(3 == (referencingCount - originalCount)); } }
public void CheckModelDispose() { long c1; using (XbimModel model1 = new XbimModel()) { model1.Open(ModelA, XbimDBAccess.ReadWrite); c1 = model1.Instances.Count; } //dispose should close the model, allowing us to open it for reading and writing XbimModel model2 = new XbimModel(); model2.Open(ModelA, XbimDBAccess.ReadWrite); long c2 = model2.Instances.Count; model2.Close(); Assert.AreEqual(c1, c2); }
private void OpenFile(object s, DoWorkEventArgs args) { var worker = s as BackgroundWorker; var model = new XbimModel(); try { if (worker != null) { IsLoading = true; _openedModelFileName = _ifcFilename; _temporaryXbimFileName = Path.GetTempFileName(); model.CreateFrom(_ifcFilename, _temporaryXbimFileName, worker.ReportProgress, true); //upgrade to new geometry represenation, uses the default 3D model var context = new Xbim3DModelContext(model); context.CreateContext(XbimGeometryType.PolyhedronBinary, worker.ReportProgress, false); if (worker.CancellationPending) { try { model.Close(); if (File.Exists(_temporaryXbimFileName)) { File.Delete(_temporaryXbimFileName); _temporaryXbimFileName = null; } } catch (Exception) { // ignored } } } args.Result = model; } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("Error reading " + _ifcFilename); var indent = "\t"; while (ex != null) { sb.AppendLine(indent + ex.Message); ex = ex.InnerException; indent += "\t"; } args.Result = new Exception(sb.ToString()); } }
private static string CreateIfcFile(string sourceFilePath, string targetPath = null) { string ext = Path.GetExtension(sourceFilePath); if (ext.ToLower() == ".ifcxml" || ext.ToLower() == ".xml") { string ifcFilePath = Path.GetDirectoryName(sourceFilePath); string ifcFileName = CreateTempFile(ifcFilePath, ".ifc"); string xbimFileName = CreateTempFile(ifcFilePath, ".xbim"); // convert xml to xbim first using (XbimModel modelServer = new XbimModel()) { modelServer.CreateFrom(sourceFilePath, xbimFileName); modelServer.Open(xbimFileName); modelServer.SaveAs(ifcFileName,XbimStorageType.IFC); modelServer.Close(); } return ifcFileName; } else if (ext.ToLower() == ".xbim") { string xbimFilePath = Path.GetDirectoryName(sourceFilePath); string ifcFileName = CreateTempFile(xbimFilePath, ".ifc"); if (targetPath != null) ifcFileName = targetPath; using (XbimModel modelServer = new XbimModel()) { modelServer.Open(sourceFilePath); modelServer.SaveAs(ifcFileName, XbimStorageType.IFC); modelServer.Close(); } return ifcFileName; } return ""; }
public void Test_OpenXbim_FileModel() { IModel model = new XbimModel(); model.Open(TestSourceFileXbim); model.Close(); }
private List<int> GetFileBadLabels(string fileName1, string fileName2) { List<int> badLabels = new List<int>(); using (XbimModel modelServer = new XbimModel()) { modelServer.Open(fileName1); using (XbimModel modelServer2 = new XbimModel()) { modelServer2.Open(fileName2); foreach (var entity in modelServer.Instances) { int entityLabel = entity.EntityLabel; byte[] b1 = modelServer.GetEntityBinaryData(entity); int posLabel = Math.Abs(entityLabel); // we have entityLabel from 1st file, this should be in second file as well IPersistIfcEntity entity2 = null; bool isBadEntity = false; entity2 = modelServer2.Instances[entityLabel]; //GetInstance(modelServer2, entityLabel); //modelServer2.GetInstance(entityLabel); if (entity2 != null) { byte[] b2 = modelServer2.GetEntityBinaryData(entity2); IStructuralEquatable eqb1 = b1; bool isEqual = eqb1.Equals(b2, StructuralComparisons.StructuralEqualityComparer); if (!isEqual) { // they may be equal but showing unequal because of decimal precision // check if its decimal and if yes, then lower the precision and compare //if (!CompareBytes(modelServer, entity, b1, b2)) isBadEntity = true; throw new Exception("Entity mismatch: EntityLabel: " + posLabel + " \n" + b1.ToString() + " \n" + b2.ToString()); } } else { // file1 entity dosent exist in file2 isBadEntity = true; } if (isBadEntity) { // add label to badLabels List badLabels.Add(posLabel); } } modelServer2.Close(); } modelServer.Close(); } return badLabels; }
public void GlobalCountTest() { XbimModel model = new XbimModel(); model.Open(ModelA); //get the cached count long c = model.Instances.Count; //read every record foreach (var entity in model.Instances) { c--; } model.Close(); Assert.AreEqual(c, 0); }
private void OpenIfcFile(object s, DoWorkEventArgs args) { var worker = s as BackgroundWorker; var ifcFilename = args.Argument as string; var model = new XbimModel(); try { _temporaryXbimFileName = Path.GetTempFileName(); _openedModelFileName = ifcFilename; if (worker != null) { model.CreateFrom(ifcFilename, _temporaryXbimFileName, worker.ReportProgress, true); var context = new Xbim3DModelContext(model);//upgrade to new geometry represenation, uses the default 3D model context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: worker.ReportProgress); if (worker.CancellationPending) //if a cancellation has been requested then don't open the resulting file { try { model.Close(); if (File.Exists(_temporaryXbimFileName)) File.Delete(_temporaryXbimFileName); //tidy up; _temporaryXbimFileName = null; _openedModelFileName = null; } // ReSharper disable once EmptyGeneralCatchClause catch { } return; } } args.Result = model; } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("Error reading " + ifcFilename); var indent = "\t"; while (ex != null) { sb.AppendLine(indent + ex.Message); ex = ex.InnerException; indent += "\t"; } args.Result = new Exception(sb.ToString()); } }
public void OpenModelTwice() { XbimModel model1 = new XbimModel(); model1.Open(SourceFile, XbimDBAccess.Read); XbimModel model2 = new XbimModel(); model2.Open(SourceFile, XbimDBAccess.Read); long c1 = model1.Instances.Count; long c2 = model2.Instances.Count; model1.Close(); model2.Close(); Assert.AreEqual(c1,c2); }
private static string CreateIfcXmlFile(string sourceFilePath, string targetPath = null) { string ext = Path.GetExtension(sourceFilePath); if (ext.ToLower() == ".ifc") { //string ifcFilePath = Path.GetDirectoryName(sourceFilePath); //string xbimFileName = ifcFilePath + "\\Temp\\" + Path.GetRandomFileName() + ".xbim"; //XbimFileModelServer modelServer = new XbimFileModelServer(); //modelServer.ImportIfc(sourceFilePath, xbimFileName); //modelServer.Close(); //modelServer.Dispose(); //// now use the xbim file to create ifcXml file //string ifcXmlFileName = ifcFilePath + "\\Temp\\" + Path.GetRandomFileName() + ".ifcxml"; //modelServer = new XbimFileModelServer(xbimFileName, FileAccess.ReadWrite); //modelServer.Export(XbimStorageType.IFCXML, ifcXmlFileName); //modelServer.Close(); //modelServer.Dispose(); //return ifcXmlFileName; } else if (ext.ToLower() == ".xbim") { string xbimFilePath = Path.GetDirectoryName(sourceFilePath); string ifcXmlFileName = CreateTempFile(xbimFilePath, ".ifcxml"); if (targetPath != null) ifcXmlFileName = targetPath; using (XbimModel modelServer = new XbimModel()) { modelServer.Open(sourceFilePath); modelServer.SaveAs(ifcXmlFileName, XbimStorageType.IFCXML); modelServer.Close(); } return ifcXmlFileName; } return ""; }
static int Main(string[] args) { int totErrors = 0; // We need to use the logger early to initialise before we use EventTrace Logger.Debug("XbimConvert starting..."); arguments = Params.ParseParams(args); if (!arguments.IsValid) { return(-1); } var SubMode = SearchOption.TopDirectoryOnly; if (arguments.ProcessSubDir) { SubMode = SearchOption.AllDirectories; } var files = Directory.GetFiles(arguments.Specdir, arguments.Specpart, SubMode); if (files.Length == 0) { Console.WriteLine("Invalid IFC filename or filter: {0}, current directory is: {1}", args[0], Directory.GetCurrentDirectory()); return(-1); } long parseTime = 0; long geomTime = 0; foreach (var origFileName in files) { using (EventTrace eventTrace = LoggerFactory.CreateEventTrace()) { try { Console.WriteLine("Starting conversion of {0}", origFileName); Logger.InfoFormat("Starting conversion of {0}", origFileName); string xbimFileName = BuildFileName(origFileName, ".xbim"); //string xbimGeometryFileName = BuildFileName(arguments.IfcFileName, ".xbimGC"); System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState) { if (!arguments.IsQuiet) { Console.Write(string.Format("{0:D5} Converted", percentProgress)); ResetCursor(Console.CursorTop); } }; watch.Start(); using (XbimModel model = ParseModelFile(origFileName, xbimFileName, arguments.Caching)) { parseTime = watch.ElapsedMilliseconds; if (!arguments.NoGeometry) { // prods left null would default to excluding ifcfeatureElements in the mesher. //IEnumerable<IfcProduct> prods = null; //if (arguments.GeometryGeneration == Params.GeometryGenerationOptions.All) // prods = model.InstancesLocal.OfType<IfcProduct>(); // this one includes ifcfeatureElements instead. //XbimMesher.GenerateGeometry(model, Logger, progDelegate, prods); //if (arguments.GeomVersion == 1) // XbimMesher.GenerateGeometry(model, Logger, progDelegate); //else //assume 2; var m3D = new Xbim3DModelContext(model); try { m3D.CreateContext(progDelegate: progDelegate); } catch (Exception ce) { Console.WriteLine("Error compiling geometry\n" + ce.Message); } geomTime = watch.ElapsedMilliseconds - parseTime; //if (arguments.GenerateScene) //{ // Stopwatch sceneTimer = new Stopwatch(); // if (!arguments.IsQuiet) // Console.Write("Scene generation started..."); // sceneTimer.Start(); // XbimSceneBuilder sb = new XbimSceneBuilder(); // sb.Options = arguments.GenerateSceneOptions; // string xbimSceneName = BuildFileName(xbimFileName, ".xbimScene"); // sb.BuildGlobalScene(model, xbimSceneName, // !arguments.IsQuiet ? Logger : null // ); // sceneTimer.Stop(); // if (!arguments.IsQuiet) // Console.WriteLine(string.Format(" Completed in {0} ms", sceneTimer.ElapsedMilliseconds)); //} } model.Close(); watch.Stop(); } // XbimModel.Terminate(); GC.Collect(); ResetCursor(Console.CursorTop + 1); Console.WriteLine("Success. Parsed in " + parseTime + " ms, geometry meshed in " + geomTime + " ms, total time " + (parseTime + geomTime) + " ms."); } catch (Exception e) { if (e is XbimException || e is NotImplementedException) { // Errors we have already handled or know about. Keep details brief in the log Logger.ErrorFormat("One or more errors converting {0}. Exiting...", origFileName); CreateLogFile(origFileName, eventTrace.Events); DisplayError(string.Format("One or more errors converting {0}, {1}", origFileName, e.Message)); } else { // Unexpected failures. Log exception details Logger.Fatal(String.Format("Fatal Error converting {0}. Exiting...", origFileName), e); CreateLogFile(origFileName, eventTrace.Events); DisplayError(string.Format("Fatal Error converting {0}, {1}", origFileName, e.Message)); } } int errors = (from e in eventTrace.Events where (e.EventLevel > EventLevel.INFO) select e).Count(); if (errors > 0) { CreateLogFile(origFileName, eventTrace.Events); } totErrors += errors; } } GetInput(); Logger.Info("XbimConvert finished successfully..."); return(totErrors); }
private static string CreateXbimFile(string sourceFilePath, string targetPath = null) { string ext = Path.GetExtension(sourceFilePath); if (ext.ToLower() == ".ifc") { string ifcFilePath = Path.GetDirectoryName(sourceFilePath); string xbimFileName = CreateTempFile(ifcFilePath, ".xbim"); if (targetPath != null) xbimFileName = targetPath; using (XbimModel modelServer = new XbimModel()) { modelServer.CreateFrom(sourceFilePath, xbimFileName); modelServer.Close(); } return xbimFileName; } else if (ext.ToLower() == ".ifcxml" || ext.ToLower() == ".xml") { string ifcxmlFilePath = Path.GetDirectoryName(sourceFilePath); string xbimFileName = CreateTempFile(ifcxmlFilePath, ".xbim"); if (targetPath != null) xbimFileName = targetPath; using (XbimModel modelServer = new XbimModel()) { modelServer.CreateFrom(sourceFilePath, xbimFileName); modelServer.Close(); } return xbimFileName; } return ""; }
/// <summary> /// Retrieves model metrics for future analysis /// </summary> /// <param name="args"></param> static void Main(string[] args) { Params arguments = Params.ParseParams(args); if (arguments.IsValid) { if (!arguments.SourceIsXbimFile) //need to parse the file { using (EventTrace eventTrace = LoggerFactory.CreateEventTrace()) { using (var model = new XbimModel()) { model.CreateFrom(arguments.SourceModelName, null, null, true); var m3D = new Xbim3DModelContext(model); arguments.SourceModelName = Path.ChangeExtension(arguments.SourceModelName, ".xbim"); m3D.CreateContext(); model.Close(); } CreateLogFile(arguments.SourceModelName, eventTrace.Events); } } Console.WriteLine("Analysing....."); var metrics = new XbimModelMetrics(); using (var model = new XbimModel()) { model.Open(arguments.SourceModelName); metrics["Number Of IfcProducts"] = model.Instances.OfType <IfcProduct>().Count(); var shapeDefinitions = model.Instances.OfType <IfcProductDefinitionShape>().ToList(); metrics["Number Of IfcProductDefinitionShape"] = shapeDefinitions.Count(); var rep = shapeDefinitions.SelectMany(shape => shape.Representations.SelectMany(a => a.Items).Where(s => s.IsSolidModel())); metrics["Number Of Shape Items"] = rep.Count(); metrics["Number Of IfcCartesianPoint"] = model.Instances.OfType <IfcCartesianPoint>().Count(); metrics["Number Of IfcFaceBasedSurfaceModel"] = model.Instances.OfType <IfcFaceBasedSurfaceModel>().Count(); metrics["Number Of IfcShellBasedSurfaceModel"] = model.Instances.OfType <IfcShellBasedSurfaceModel>().Count(); metrics["Number Of IfcSolidModel"] = model.Instances.OfType <IfcSolidModel>().Count(); metrics["Number Of IfcHalfSpaceSolid"] = model.Instances.OfType <IfcHalfSpaceSolid>().Count(); metrics["Number Of IfcBooleanResult"] = model.Instances.OfType <IfcBooleanResult>().Count(); metrics["Number Of IfcMappedItem"] = model.Instances.OfType <IfcMappedItem>().Count(); double totalVoids = 0; double maxVoidsPerElement = 0; double totalElements = 0; foreach (var relVoids in model.Instances.OfType <IfcRelVoidsElement>().GroupBy(r => r.RelatingBuildingElement)) { var voidCount = relVoids.Count(); totalVoids += voidCount; totalElements++; double newmaxVoidsPerElement = Math.Max(maxVoidsPerElement, voidCount); if (newmaxVoidsPerElement != maxVoidsPerElement) { maxVoidsPerElement = newmaxVoidsPerElement; Console.WriteLine("Element is #{0}", relVoids.Key.EntityLabel); } } metrics["Total Of Openings Cut"] = totalVoids; metrics["Number Of Element with Openings"] = totalElements; metrics["Maximum openings in an Element"] = maxVoidsPerElement; metrics["Average openings in an Element"] = totalVoids == 0 ? 0.0 : totalElements / totalVoids; //if the model has shape geometry report on that var context = new Xbim3DModelContext(model); metrics["Number of Shape Geometries"] = context.ShapeGeometries().Count(); metrics["Number of Shape Instances"] = context.ShapeInstances().Count(); // metrics["Number of Surface Styles"] = context.().Count(); model.Close(); } foreach (var metric in metrics) { Console.WriteLine("{0} = {1}", metric.Key, metric.Value); } } Console.WriteLine("Press Enter to continue..."); Console.ReadLine(); }