Ejemplo n.º 1
0
        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();
        }
        /// <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());
            }
        }
        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();
        }
Ejemplo n.º 4
0
 public XbimModelHandler(String ModelPath)
 {
     model = new XbimModel();
     model.Open(ModelPath, XbimExtensions.XbimDBAccess.Read);
     //setup a type map
     Init();
 }
Ejemplo n.º 5
0
        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
            }
        }
Ejemplo n.º 6
0
        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
            }
        }
Ejemplo n.º 7
0
        private static XbimModel GetModel(string fileName)
        {
            XbimModel openModel = null;
            var       extension = Path.GetExtension(fileName);

            if (string.IsNullOrWhiteSpace(extension))
            {
                if (File.Exists(Path.ChangeExtension(fileName, "xbim"))) //use xBIM if exists
                {
                    fileName = Path.ChangeExtension(fileName, "xbim");
                }
                else if (File.Exists(Path.ChangeExtension(fileName, "ifc"))) //use ifc if exists
                {
                    fileName = Path.ChangeExtension(fileName, "ifc");
                }
                else if (File.Exists(Path.ChangeExtension(fileName, "ifczip"))) //use ifczip if exists
                {
                    fileName = Path.ChangeExtension(fileName, "ifczip");
                }
                else if (File.Exists(Path.ChangeExtension(fileName, "ifcxml"))) //use ifcxml if exists
                {
                    fileName = Path.ChangeExtension(fileName, "ifcxml");
                }
            }

            if (File.Exists(fileName))
            {
                extension = Path.GetExtension(fileName);
                if (String.Compare(extension, ".xbim", StringComparison.OrdinalIgnoreCase) == 0) //just open xbim
                {
                    try
                    {
                        var model = new XbimModel();
                        model.Open(fileName, XbimDBAccess.ReadWrite);
                        //delete any geometry
                        openModel = model;
                    }
                    catch (Exception e)
                    {
                        Logger.ErrorFormat("Unable to open model {0}, {1}", fileName, e.Message);
                        Console.WriteLine(String.Format("Unable to open model {0}, {1}", fileName, e.Message));
                    }
                }
                else //we need to create the xBIM file
                {
                    var model = new XbimModel();
                    try
                    {
                        model.CreateFrom(fileName, null, null, true);
                        openModel = model;
                    }
                    catch (Exception e)
                    {
                        Logger.ErrorFormat("Unable to open model {0}, {1}", fileName, e.Message);
                        Console.WriteLine(String.Format("Unable to open model {0}, {1}", fileName, e.Message));
                    }
                }
            }
            return(openModel);
        }
Ejemplo n.º 8
0
        private static XbimModel GetModel(string fileName)
        {
            XbimModel openModel = null;
            var       extension = Path.GetExtension(fileName);

            if (string.IsNullOrWhiteSpace(extension))
            {
                if (File.Exists(Path.ChangeExtension(fileName, "xbim"))) //use xBIM if exists
                {
                    fileName = Path.ChangeExtension(fileName, "xbim");
                }
                else if (File.Exists(Path.ChangeExtension(fileName, "ifc"))) //use ifc if exists
                {
                    fileName = Path.ChangeExtension(fileName, "ifc");
                }
                else if (File.Exists(Path.ChangeExtension(fileName, "ifczip"))) //use ifczip if exists
                {
                    fileName = Path.ChangeExtension(fileName, "ifczip");
                }
                else if (File.Exists(Path.ChangeExtension(fileName, "ifcxml"))) //use ifcxml if exists
                {
                    fileName = Path.ChangeExtension(fileName, "ifcxml");
                }
            }

            if (File.Exists(fileName))
            {
                extension = Path.GetExtension(fileName).TrimStart('.');
                if (String.Compare(extension, "xbim", StringComparison.OrdinalIgnoreCase) == 0) //just open xbim
                {
                    try
                    {
                        var model = new XbimModel();
                        Log.Info("Opening " + fileName);
                        model.Open(fileName, XbimDBAccess.ReadWrite);
                        //delete any geometry
                        openModel = model;
                    }
                    catch (Exception e)
                    {
                        Log.Error("无法打开文件:" + fileName, e);
                    }
                }
                else //we need to create the xBIM file
                {
                    var model = new XbimModel();
                    try
                    {
                        Log.Info("Creating " + Path.ChangeExtension(fileName, ".xBIM"));
                        model.CreateFrom(fileName, null, null, true);
                        openModel = model;
                    }
                    catch (Exception e)
                    {
                        Log.Error("无法打开文件:" + fileName, e);
                    }
                }
            }
            return(openModel);
        }
Ejemplo n.º 9
0
 public static void LoadModel(TestContext context)
 {
     if (!File.Exists(SourceFile)) throw new Exception("Cannot find file");
     _model = new XbimModel();
     _model.Open(SourceFile);
     _cobieContext = new COBieContext();
     _cobieContext.Model = _model;
 }
Ejemplo n.º 10
0
        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();
        }
Ejemplo n.º 11
0
 public xBimQueryLanguage()
     : base(caseSensitive: false)
 {
     _model = new XbimModel();
     #if debug
     _model.Open(@"F:\dev\Codeplex\xBIM\XbimFramework\Head\Xbim.Querying\Querying\Test\Duplex-Handover.xBIM");
     #endif
     InitGrammar();
 }
Ejemplo n.º 12
0
 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();
 }
Ejemplo n.º 13
0
 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 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;
 }
Ejemplo n.º 15
0
        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();
        }
Ejemplo n.º 16
0
        private static XbimModel GetModel(string fileName)
        {
            XbimModel openModel = null;
            var extension = Path.GetExtension(fileName);
            if (string.IsNullOrWhiteSpace(extension))
            {
                if (File.Exists(Path.ChangeExtension(fileName, "xbim"))) //use xBIM if exists
                    fileName = Path.ChangeExtension(fileName, "xbim");
                else if (File.Exists(Path.ChangeExtension(fileName, "ifc"))) //use ifc if exists
                    fileName = Path.ChangeExtension(fileName, "ifc");
                else if (File.Exists(Path.ChangeExtension(fileName, "ifczip"))) //use ifczip if exists
                    fileName = Path.ChangeExtension(fileName, "ifczip");
                else if (File.Exists(Path.ChangeExtension(fileName, "ifcxml"))) //use ifcxml if exists
                    fileName = Path.ChangeExtension(fileName, "ifcxml");
            }

            if (File.Exists(fileName))
            {
                extension = Path.GetExtension(fileName);
                if (String.Compare(extension, ".xbim", StringComparison.OrdinalIgnoreCase) == 0) //just open xbim
                {

                    try
                    {
                        var model = new XbimModel();
                        model.Open(fileName, XbimDBAccess.ReadWrite);
                        //delete any geometry
                        openModel = model;
                    }
                    catch (Exception e)
                    {
                        Logger.ErrorFormat("Unable to open model {0}, {1}", fileName, e.Message);
                        Console.WriteLine(String.Format("Unable to open model {0}, {1}", fileName, e.Message));
                    }

                }
                else //we need to create the xBIM file
                {
                    var model = new XbimModel();
                    try
                    {
                        model.CreateFrom(fileName, null, null, true);
                        openModel = model;
                    }
                    catch (Exception e)
                    {
                        Logger.ErrorFormat("Unable to open model {0}, {1}", fileName, e.Message);
                        Console.WriteLine(String.Format("Unable to open model {0}, {1}", fileName, e.Message));
                    }

                }
            }
            return openModel;
        }
Ejemplo n.º 17
0
        public void TestRoles()
        {
            COBieBinaryDeserialiser deserialiser = new COBieBinaryDeserialiser(cobieFile);
            COBieWorkbook workbook = deserialiser.Deserialise();
            using (XbimModel model = new XbimModel())
            {
                model.Open(xbimFile);
                workbook.ValidateRoles(model, COBieMergeRoles.Mechanical | COBieMergeRoles.Electrical | COBieMergeRoles.Plumbing);
            }

            Assert.IsNotNull(workbook);
        }
Ejemplo n.º 18
0
        private void OnClick_LoadModel(object sender, RoutedEventArgs e)
        {
            string fileName = string.Empty;
            string saveTxt  = txtDBName.Text;

            txtDBName.SetCurrentValue(TextBlock.TextProperty, "Loading file, please wait...");

            using (System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog())
            {
                dlg.Title         = "Select Model";
                dlg.Filter        = "All XBim Files|*.ifc;*.ifcxml;*.ifczip;*.xbim;*.xbimf|IFC Files|*.ifc;*.ifcxml;*.ifczip|Xbim Files|*.xbim|Xbim Federated Files|*.xbimf";
                dlg.FilterIndex   = 0;
                dlg.ValidateNames = true;
                System.Windows.Forms.DialogResult dlgresult = dlg.ShowDialog();
                if (dlgresult == System.Windows.Forms.DialogResult.OK)
                {
                    fileName = dlg.FileName;
                }
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                txtDBName.SetCurrentValue(TextBlock.TextProperty, "Loading file, please wait...");
                if (Model != null)
                {
                    Model.Close();
                }
                XbimModel model   = new XbimModel();
                string    fileExt = System.IO.Path.GetExtension(fileName);
                if ((fileExt.Equals(".xbim", StringComparison.OrdinalIgnoreCase)) ||
                    (fileExt.Equals(".xbimf", StringComparison.OrdinalIgnoreCase))
                    )
                {
                    model.Open(fileName, XbimDBAccess.ReadWrite);
                    //model.CacheStart();
                }
                else //ifc file
                {
                    string xbimFile = System.IO.Path.ChangeExtension(fileName, "xBIM");
                    //ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                    //{
                    //    progressBar.Value = percentProgress;
                    //};
                    model.CreateFrom(fileName, xbimFile, null, true, false);
                }
                Model = model;
            }
            else
            {
                txtDBName.SetCurrentValue(TextBlock.TextProperty, saveTxt);
            }
        }
Ejemplo n.º 19
0
 public XbimReferencedModel(IfcDocumentInformation documentInformation)
 {
     DocumentInformation = documentInformation;
     if (!File.Exists(documentInformation.Name))
     {
         throw new XbimException("Reference model not found:" + documentInformation.Name);
     }
     Model = new XbimModel();
     if (!Model.Open(documentInformation.Name, XbimDBAccess.Read))
     {
         throw new XbimException("Unable to open reference model: " + documentInformation.Name);
     }
 }
Ejemplo n.º 20
0
        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();
        }
Ejemplo n.º 21
0
 public XbimReferencedModel(IfcDocumentInformation documentInformation)
 {
     DocumentInformation = documentInformation;
     if (!File.Exists(documentInformation.Name))
     {
         throw new XbimException("Reference model not found:" + documentInformation.Name);
     }
     Model = new XbimModel();
     if (!Model.Open(documentInformation.Name, XbimDBAccess.Read))
     {
         throw new XbimException("Unable to open reference model: " + documentInformation.Name);
     }
 }
Ejemplo n.º 22
0
        public void ReadIfc(string filepath)
        {
            var ifcFileName = filepath;

            var tempFilename = Path.GetTempFileName();
            var model = new XbimModel();

            model.CreateFrom(ifcFileName, tempFilename);
            model.Open(tempFilename);

            var products = model.Instances.OfType<IfcProduct>();
            var storeys = model.Instances.OfType<IfcBuildingStorey>().ToList();
        }
        public void ScaledPositioningBoxes()
        {
            // this test is currently failing because some core functions do not work on old geometry models
            // it has to be decided if the function needs to be implemented for v3.1 models as well.
            //
            var m = new List <XbimModel>();

            var m0 = new XbimModel();

            m0.Open(@"Scale\P1_cm.xBIM");
            m.Add(m0);

            var m1 = new XbimModel();

            m1.Open(@"Scale\P2_cm.xBIM");
            m.Add(m1);

            var m2 = new XbimModel();

            m2.Open(@"Scale\P2_mm.xBIM");
            m.Add(m2);

            var m3 = new XbimModel();

            m3.Open(@"Scale\GeomV1\P2_mm.xBIM");
            m.Add(m3);

            // var p = new List<XbimModelPositioning>();
            var r = new List <XbimRect3D>();

            foreach (var xbimModel in m)
            {
                var tmp = new XbimModelPositioning(xbimModel);
                r.Add(tmp.GetLargestRegionRectInMeters());
            }

            HaveSameSize(r[1], r[2]);
            HaveSameSize(r[1], r[3]);
            // HaveSameSize(r[0], r[2]);
            // HaveSameSize(r[0], r[3]);

            HaveSameLocation(r[1], r[2]);
            HaveSameLocation(r[1], r[3]);
            // NeedToBeSame(r[1], r[0]);
            // NeedToBeSame(r[0], r[3]);

            foreach (var xbimModel in m)
            {
                xbimModel.Close();
            }
        }
Ejemplo n.º 24
0
        public void ScaledPositioningBoxes()
        {
            var m = new List <XbimModel>();

            var m0 = new XbimModel();

            m0.Open(@"Scale\P1_cm.xBIM");
            m.Add(m0);

            var m1 = new XbimModel();

            m1.Open(@"Scale\P2_cm.xBIM");
            m.Add(m1);

            var m2 = new XbimModel();

            m2.Open(@"Scale\P2_mm.xBIM");
            m.Add(m2);

            var m3 = new XbimModel();

            m3.Open(@"Scale\GeomV1\P2_mm.xBIM");
            m.Add(m3);

            //var p = new List<XbimModelPositioning>();
            var r = new List <XbimRect3D>();

            foreach (var xbimModel in m)
            {
                var tmp = new XbimModelPositioning(xbimModel);
                // p.Add(tmp);
                r.Add(tmp.GetLargestRegionRectInMeters());
            }

            HaveSameSize(r[1], r[2]);
            HaveSameSize(r[1], r[3]);
            //HaveSameSize(r[0], r[2]);
            // HaveSameSize(r[0], r[3]);

            HaveSameLocation(r[1], r[2]);
            HaveSameLocation(r[1], r[3]);
            // NeedToBeSame(r[1], r[0]);
            //NeedToBeSame(r[0], r[3]);

            foreach (var xbimModel in m)
            {
                xbimModel.Close();
            }
        }
Ejemplo n.º 25
0
        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();
        }
Ejemplo n.º 26
0
        private void StartComparison_Click(object sender, RoutedEventArgs e)
        {
            VersionComparison vc = new VersionComparison();
            vc.OnMessage += (x) => {
                Application.Current.Dispatcher.BeginInvoke(new Action( () => Messages.Items.Add(x)));
            };

            XbimModel Base = new XbimModel();
            XbimModel Revision = new XbimModel();

            Base.Open(BaselineTextBox.Text, Xbim.XbimExtensions.XbimDBAccess.Read);
            Revision.Open(RevisedTextBox.Text, Xbim.XbimExtensions.XbimDBAccess.Read);

            Messages.Items.Clear();
            vc.StartComparison(Base, Revision, Filter.Text);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Create the COBieBuilder, holds COBieWorkBook
        /// </summary>
        /// <param name="parameters">Params</param>
        /// <returns>COBieBuilder</returns>
        private COBieWorkbook GenerateFederatedCOBieWorkBook(Params parameters)
        {
            string               xbimFile    = parameters.ModelFile;
            COBieBuilder         builder     = null;
            COBieWorkbook        fedWorkBook = null;
            List <COBieWorkbook> workbooks   = new List <COBieWorkbook>();

            LogBackground(String.Format("Loading federated model {0}...", xbimFile));
            using (XbimModel model = new XbimModel())
            {
                model.Open(xbimFile, XbimDBAccess.ReadWrite);
                Model = model; //used to check we close file on Close event

                // Build context on the XBimF model to link roles
                COBieContext context = new COBieContext(_worker.ReportProgress);
                context.TemplateFileName = parameters.TemplateFile;
                context.Model            = model;
                context.Exclude          = UserFilters;
                foreach (var ModelRoles in context.MapMergeRoles)
                {
                    XbimModel       refModel = ModelRoles.Key;
                    COBieMergeRoles roles    = ModelRoles.Value;

                    COBieContext refContext = new COBieContext(_worker.ReportProgress);
                    refContext.TemplateFileName        = parameters.TemplateFile;
                    refContext.Model                   = refModel;
                    refContext.MapMergeRoles[refModel] = roles;
                    refContext.Exclude                 = UserFilters;

                    // Create COBieReader
                    LogBackground("Generating COBie data...");
                    builder = new COBieBuilder(refContext);
                    workbooks.Add(builder.Workbook);
                }
            }
            if (workbooks.Count > 1)
            {
                FederateCOBie fedCOBie = new FederateCOBie(_worker.ReportProgress);
                fedWorkBook = fedCOBie.Merge(workbooks);
            }
            else if (workbooks.Count == 1)
            {
                fedWorkBook = workbooks[0];
            }

            return(fedWorkBook);
        }
        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();
            }
        }
Ejemplo n.º 29
0
        public void CreateFederation()
        {
            using (var fedModel = XbimModel.CreateTemporaryModel())
            {
                fedModel.Initialise("Federation Creating Author", "Federation Creating Organisation", "This Application", "This Developer", "v1.1");
                using (var txn = fedModel.BeginTransaction())
                {
                    fedModel.IfcProject.Name = "Federation Project Name";
                    txn.Commit();
                }
                //now add federated models
                fedModel.AddModelReference(ModelA, "The Architects Name", IfcRole.Architect);
                fedModel.AddModelReference(ModelB, "The Owners Name", IfcRole.BuildingOwner);
                // fedModel.AddModelReference(ModelC, "The Cost Consultants Name", IfcRole.UserDefined, "Cost Consultant");
                fedModel.SaveAs("Federated Model", XbimStorageType.IFC);
            } //close and automatically delete the temporary database
            //Now open the Ifc file and see what we have
            using (var fed = new XbimModel())
            {
                fed.CreateFrom("Federated Model.ifc", "Federated Model.xBIMF"); //use xBIMF to help us distinguish
                fed.Open("Federated Model.xBIMF", XbimExtensions.XbimDBAccess.Read);

                //check the various ways of access objects give consistent results.
                var  localInstances    = fed.InstancesLocal.Count;
                var  totalInstances    = fed.Instances.Count;
                long refInstancesCount = 0;
                foreach (var refModel in fed.ReferencedModels)
                {
                    refInstancesCount += refModel.Model.Instances.Count;
                }

                Assert.IsTrue(totalInstances == refInstancesCount + localInstances);

                long enumeratingInstancesCount = 0;
                foreach (var item in fed.Instances)
                {
                    enumeratingInstancesCount++;
                }
                Assert.IsTrue(totalInstances == enumeratingInstancesCount);

                long fedProjectCount   = fed.Instances.OfType <IfcProject>().Count();
                long localProjectCount = fed.InstancesLocal.OfType <IfcProject>().Count();
                Assert.IsTrue(fedProjectCount == 3);
                Assert.IsTrue(localProjectCount == 1);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Open federated file
        /// </summary>
        /// <param name="file">FileInfo</param>
        /// <returns>bool</returns>
        public bool Open(FileInfo file)
        {
            if (_fedModel != null)
            {
                _fedModel.Close();
            }

            if (file.Exists)
            {
                _fedModel = new XbimModel();
                return(_fedModel.Open(file.FullName, XbimDBAccess.ReadWrite));
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 31
0
        public void Should_Return_Spaces()
        {
            using (XbimModel model = new XbimModel())
            {
                model.Open(SourceFile, XbimDBAccess.ReadWrite);
                COBieContext cobieContext = new COBieContext();
                cobieContext.Model = model;

                COBieQueries cobieEngine = new COBieQueries(cobieContext);

                var spaces = cobieEngine.GetCOBieSpaceSheet();

                Assert.AreEqual(22, spaces.Rows.Count);

                FormatRows(spaces);
            }
        }
Ejemplo n.º 32
0
        private void StartComparison_Click(object sender, RoutedEventArgs e)
        {
            VersionComparison vc = new VersionComparison();

            vc.OnMessage += (x) => {
                Application.Current.Dispatcher.BeginInvoke(new Action(() => Messages.Items.Add(x)));
            };

            XbimModel Base     = new XbimModel();
            XbimModel Revision = new XbimModel();

            Base.Open(BaselineTextBox.Text, Xbim.XbimExtensions.XbimDBAccess.Read);
            Revision.Open(RevisedTextBox.Text, Xbim.XbimExtensions.XbimDBAccess.Read);

            Messages.Items.Clear();
            vc.StartComparison(Base, Revision, Filter.Text);
        }
Ejemplo n.º 33
0
        public void CreateFederation()
        {
            using (XbimModel fedModel = XbimModel.CreateTemporaryModel())
            {
                fedModel.Initialise("Federation Creating Author", "Federation Creating Organisation", "This Application", "This Developer", "v1.1");
                using (var txn = fedModel.BeginTransaction())
                {
                    fedModel.IfcProject.Name = "Federation Project Name";
                    txn.Commit();
                }
                //now add federated models
                fedModel.AddModelReference(ModelA, "The Architects Name", IfcRole.Architect);
                fedModel.AddModelReference(ModelB, "The Owners Name", IfcRole.BuildingOwner);
                fedModel.AddModelReference(ModelC, "The Cost Consultants Name", "Cost Consultant");
                fedModel.SaveAs("Federated Model", XbimStorageType.IFC);
            } //close and automatically delete the temporary database
            //Now open the Ifc file and see what we have
            using (XbimModel fed = new XbimModel())
            {
                fed.CreateFrom("Federated Model.ifc", "Federated Model.xBIMF"); //use xBIMF to help us distinguish
                fed.Open("Federated Model.xBIMF", XbimExtensions.XbimDBAccess.Read);

                //check the various ways of access objects give consistent results.
                long localInstances = fed.InstancesLocal.Count;
                long totalInstances = fed.Instances.Count;
                long refInstancesCount = 0;
                foreach (var refModel in fed.RefencedModels)
                {
                    refInstancesCount += refModel.Model.Instances.Count;
                }

                Assert.IsTrue(totalInstances == refInstancesCount + localInstances);

                long enumeratingInstancesCount = 0;
                foreach (IPersistIfcEntity item in fed.Instances)
                {
                    enumeratingInstancesCount++;
                }
                Assert.IsTrue(totalInstances == enumeratingInstancesCount);

                long fedProjectCount = fed.Instances.OfType<IfcProject>().Count();
                long localProjectCount = fed.InstancesLocal.OfType<IfcProject>().Count();
                Assert.IsTrue(fedProjectCount == 4);
                Assert.IsTrue(localProjectCount == 1);
            }
        }
        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();
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Create the COBieBuilder, holds COBieWorkBook
        /// </summary>
        /// <param name="parameters">Params</param>
        /// <returns>COBieBuilder</returns>
        private COBieBuilder GenerateCOBieWorkBook(Params parameters)
        {
            string       xbimFile = string.Empty;
            string       fileExt  = Path.GetExtension(parameters.ModelFile);
            COBieBuilder builder  = null;

            LogBackground(String.Format("Loading model {0}...", Path.GetFileName(parameters.ModelFile)));
            using (XbimModel model = new XbimModel())
            {
                if ((fileExt.Equals(".xbim", StringComparison.OrdinalIgnoreCase)) ||
                    (fileExt.Equals(".xbimf", StringComparison.OrdinalIgnoreCase))
                    )
                {
                    xbimFile = parameters.ModelFile;
                    model.Open(xbimFile, XbimDBAccess.ReadWrite);
                    //model.CacheStart();
                }
                else //ifc file
                {
                    xbimFile = Path.ChangeExtension(parameters.ModelFile, "xBIM");
                    model.CreateFrom(parameters.ModelFile, xbimFile, _worker.ReportProgress, true, false);
                }
                //model.Open(xbimFile, XbimDBAccess.ReadWrite);


                // Build context
                COBieContext context = new COBieContext(_worker.ReportProgress);
                context.TemplateFileName     = parameters.TemplateFile;
                context.Model                = model;
                context.MapMergeRoles[model] = Roles;
                context.Exclude              = UserFilters;
                Model = model; //used to check we close file on Close event
                //Create Scene, required for Coordinates sheet
                if (!SkipGeoChkBox.Checked)
                {
                    GenerateGeometry(context);
                }


                // Create COBieReader
                LogBackground("Generating COBie data...");
                builder = new COBieBuilder(context);
            }
            return(builder);
        }
Ejemplo n.º 36
0
        public void ScaledPositioningBoxes()
        {
            var m = new List<XbimModel>();

            var m0 = new XbimModel();
            m0.Open(@"Scale\P1_cm.xBIM");
            m.Add(m0);
            
            var m1 = new XbimModel();
            m1.Open(@"Scale\P2_cm.xBIM");
            m.Add(m1);

            var m2 = new XbimModel();
            m2.Open(@"Scale\P2_mm.xBIM");
            m.Add(m2);

            var m3 = new XbimModel();
            m3.Open(@"Scale\GeomV1\P2_mm.xBIM");
            m.Add(m3);

            //var p = new List<XbimModelPositioning>();
            var r = new List<XbimRect3D>();
            foreach (var xbimModel in m)
            {
                var tmp = new XbimModelPositioning(xbimModel);
                // p.Add(tmp);
                r.Add(tmp.GetLargestRegionRectInMeters());
            }

            HaveSameSize(r[1], r[2]);
            HaveSameSize(r[1], r[3]);
            //HaveSameSize(r[0], r[2]);
            // HaveSameSize(r[0], r[3]);
            
            HaveSameLocation(r[1], r[2]);
            HaveSameLocation(r[1], r[3]);
            // NeedToBeSame(r[1], r[0]);
            //NeedToBeSame(r[0], r[3]);

            foreach (var xbimModel in m)
            {
                xbimModel.Close();
            }            
        }
Ejemplo n.º 37
0
        public void QueryingSelectAllModel()
        {
            // DirectoryInfo d = new DirectoryInfo("."); // to find folder location
            using (XbimModel model = new XbimModel())
            {
                model.Open(SourceModelFileName, XbimDBAccess.Read);
                var cnt = model.Query(@"select @*");
                Assert.IsNotNull(cnt);

                dynamic doors = model.Query(@"select @IfcDoor.Where(@OverallHeight==2090)");
                Assert.IsNotNull(doors);
                Assert.AreEqual(36, doors.Count);

                doors = model.Query(@"select @IfcDoor.Where(@OverallHeight==2090 && @OverallWidth==790)");
                Assert.IsNotNull(doors);
                Assert.AreEqual(4, doors.Count);

                model.Close();
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Generate Facilities for a xbim or ifc type file
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="fileExt"></param>
        /// <returns></returns>
        private List <Facility> GenerateFileFacility(Params parameters, string fileExt)
        {
            var facilities = new List <Facility>();

            using (var model = new XbimModel())
            {
                if (fileExt.Equals(".xbim", StringComparison.OrdinalIgnoreCase))
                {
                    model.Open(parameters.ModelFile, XbimExtensions.XbimDBAccess.Read, Worker.ReportProgress);
                }
                else
                {
                    var xbimFile = Path.ChangeExtension(parameters.ModelFile, "xbim");
                    model.CreateFrom(parameters.ModelFile, xbimFile, Worker.ReportProgress, true, true);
                }
                var ifcToCoBieLiteUkExchanger = new IfcToCOBieLiteUkExchanger(model, facilities, Worker.ReportProgress, parameters.Filter, parameters.ConfigFile, parameters.ExtId, parameters.SysMode);
                facilities = ifcToCoBieLiteUkExchanger.Convert();
            }
            return(facilities);
        }
Ejemplo n.º 39
0
        public void ValidIdentityInFederation()
        {
            using (var fedModel = XbimModel.CreateTemporaryModel())
            {
                fedModel.Initialise("Federation Creating Author", "Federation Creating Organisation", "This Application", "This Developer", "v1.1");
                using (var txn = fedModel.BeginTransaction())
                {
                    fedModel.IfcProject.Name = "Federation Project Name";
                    txn.Commit();
                }
                //now add federated models
                fedModel.AddModelReference(ModelFedP1, "The Architects Name", IfcRole.Architect);
                fedModel.AddModelReference(ModelFedP2, "The Owners Name", IfcRole.BuildingOwner);
                fedModel.SaveAs("P1P2Federation", XbimStorageType.IFC);
            } //close and automatically delete the temporary database
            //Now open the Ifc file and see what we have
            using (var fed = new XbimModel())
            {
                fed.CreateFrom("P1P2Federation.ifc", "P1P2Federation.xBIMF"); //use xBIMF to help us distinguish
                fed.Open("P1P2Federation.xBIMF", XbimExtensions.XbimDBAccess.Read);
                fed.EnsureUniqueUserDefinedId();

                var mustDiffer =
                    fed.Instances.OfType<IfcGeometricRepresentationSubContext>()
                        .Where(x => x.ContextIdentifier == @"Body").ToArray();
                
                // we are expecting two items (one body from each model loaded)
                // they happen to share the same entitylabel, but they have different models.

                var first = mustDiffer[0];
                var second = mustDiffer[1];

                Assert.IsFalse(first == second);

                var tst = new HashSet<IfcGeometricRepresentationContext>();
                tst.Add(first);
                tst.Add(second);
            }
        }
Ejemplo n.º 40
0
        public void ValidIdentityInFederation()
        {
            using (var fedModel = XbimModel.CreateTemporaryModel())
            {
                fedModel.Initialise("Federation Creating Author", "Federation Creating Organisation", "This Application", "This Developer", "v1.1");
                using (var txn = fedModel.BeginTransaction())
                {
                    fedModel.IfcProject.Name = "Federation Project Name";
                    txn.Commit();
                }
                //now add federated models
                fedModel.AddModelReference(ModelFedP1, "The Architects Name", IfcRole.Architect);
                fedModel.AddModelReference(ModelFedP2, "The Owners Name", IfcRole.BuildingOwner);
                fedModel.SaveAs("P1P2Federation", XbimStorageType.IFC);
            } //close and automatically delete the temporary database
            //Now open the Ifc file and see what we have
            using (var fed = new XbimModel())
            {
                fed.CreateFrom("P1P2Federation.ifc", "P1P2Federation.xBIMF"); //use xBIMF to help us distinguish
                fed.Open("P1P2Federation.xBIMF", XbimExtensions.XbimDBAccess.Read);
                fed.EnsureUniqueUserDefinedId();

                var mustDiffer =
                    fed.Instances.OfType <IfcGeometricRepresentationSubContext>()
                    .Where(x => x.ContextIdentifier == @"Body").ToArray();

                // we are expecting two items (one body from each model loaded)
                // they happen to share the same entitylabel, but they have different models.

                var first  = mustDiffer[0];
                var second = mustDiffer[1];

                Assert.IsFalse(first == second);

                var tst = new HashSet <IfcGeometricRepresentationContext>();
                tst.Add(first);
                tst.Add(second);
            }
        }
Ejemplo n.º 41
0
        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();
            }
        }
Ejemplo n.º 42
0
        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();
            }
        }
Ejemplo n.º 43
0
        public void TestShapeGeometriesEnumerability()
        {
            using (var model = new XbimModel())
            {
                model.Open(@"EsentTestFiles\TwoWalls.xbim");
                var geomContext = new Xbim3DModelContext(model);

                var lst = new Dictionary <int, int>();

                // ShapeGeometries does not have duplicates...
                lst.Clear();
                foreach (var g1 in geomContext.ShapeGeometries())
                {
                    lst.Add(g1.ShapeLabel, g1.IfcShapeLabel);
                }

                // ... so it shouldn't even through the ToArray() function.
                lst.Clear();
                foreach (var g1 in geomContext.ShapeGeometries().ToArray())
                {
                    lst.Add(g1.ShapeLabel, g1.IfcShapeLabel);
                }
            }
        }
Ejemplo n.º 44
0
        public void Run()
        {
            //to start we need an ifc file, here it is Clinic_Example.ifc
            string ifcFile  = @"IfcFiles/Clinic_Example.ifc";
            string xbimFile = Path.ChangeExtension(ifcFile, "xBIM");  //will generate if not existing

            if (File.Exists(ifcFile))
            {
                using (XbimModel model = new XbimModel())
                {
                    if (File.Exists(xbimFile))
                    {
                        //assume the xbim file has the geometry already generated from ifc file, as below
                        model.Open(xbimFile, XbimDBAccess.Read);
                    }
                    else
                    {
                        //create the xbim file from the ifc file
                        model.CreateFrom(ifcFile, xbimFile, delegate(int percentProgress, object userState)
                        {
                            Console.Write("\rReading File {0}", percentProgress);
                        });

                        model.Open(xbimFile, XbimDBAccess.ReadWrite); //readwrite as we need to add the geometry
                        //add the the geometry information to the model
                        int total = (int)model.Instances.CountOf <IfcProduct>();
                        ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                        {
                            Console.Write("\rGeometry {0} / {1}", total, (total * percentProgress / 100));
                        };
                        XbimMesher.GenerateGeometry(model, null, progDelegate);
                    }

                    //get all the IfcDoors in the model
                    IEnumerable <IfcDoor> ifcDoors = model.IfcProducts.OfType <IfcDoor>(); //get all the ifcdoors for this model
                    if (ifcDoors.Any())
                    {
                        IfcDoor          ifcDoor = ifcDoors.First(); //we use the first door to get the bounding box from
                        XbimGeometryData geoData = model.GetGeometryData(ifcDoor, XbimGeometryType.BoundingBox).FirstOrDefault();
                        if (geoData != null)
                        {
                            XbimRect3D boundBox = XbimRect3D.FromArray(geoData.ShapeData); //size information for the IfcDoor, but the information is for the bounding box which encloses the door

                            //if want want in World space
                            XbimMatrix3D worldMatrix = geoData.Transform;
                            //if we want to convert to World space we can use the geoData.Transform property and create the world matrix
                            XbimPoint3D MinPtOCS = new XbimPoint3D(boundBox.X, boundBox.Y, boundBox.Z);
                            XbimPoint3D MaxPtOCS = new XbimPoint3D(boundBox.X + boundBox.SizeX, boundBox.Y + boundBox.SizeY, boundBox.Z + boundBox.SizeZ);
                            //transformed values, may no longer a valid bounding box in the new space if any Pitch or Yaw, i.e. stairs ceiling supports
                            XbimPoint3D MinPtWCS = worldMatrix.Transform(MinPtOCS);
                            XbimPoint3D MaxPtWCS = worldMatrix.Transform(MaxPtOCS);
                            //if you product is at any angle to the World space then the bounding box can be recalculated,
                            //a example of this can be found here https://sbpweb.svn.codeplex.com/svn/SBPweb.Workbench/Workbench%20Framework%202.0.0.x/Presentation/Windows.WPF/Utils/Maths.cs
                            //in the TransformBounds function
                            Console.WriteLine("\n-------------Bounding Box Information-------------");
                            Console.WriteLine("Entity Type = {0}", IfcMetaData.GetType(geoData.IfcTypeId).Name);
                            Console.WriteLine("Entity Label = {0}", Math.Abs(ifcDoor.EntityLabel).ToString());
                            Console.WriteLine("Size X = {0:F2}", boundBox.SizeX.ToString());
                            Console.WriteLine("Size Y = {0:F2}", boundBox.SizeY.ToString());
                            Console.WriteLine("Size Z = {0:F2}", boundBox.SizeZ.ToString());
                            Console.WriteLine("Object space minimum point {0}", MinPtOCS);
                            Console.WriteLine("Object space maximum point {0}", MaxPtOCS);
                            Console.WriteLine("World space minimum point {0}", MinPtWCS);
                            Console.WriteLine("World space maximum point {0}", MaxPtWCS);
                            Console.WriteLine("---------------------------------------------");
                        }
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Failed to find any IfcDoor's in {0}", ifcFile));
                        return;  //exit
                    }
                }
            }
            else
            {
                Console.WriteLine(string.Format("Failed to find {0} in executable directory", ifcFile));
            }
            Console.WriteLine("\nFinished");
        }
        /// <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 OpenFederationCmdExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var dlg = new OpenFileDialog();
            dlg.Filter = "Xbim Federation Files|*.xbimf|Xbim Model Files|*.ifc"; // Filter files by extension
            dlg.CheckFileExists = true;
            dlg.Multiselect = true;
            var done = dlg.ShowDialog(this);
            if (done.Value)
            {
                if (dlg.FileNames.Any()) // collection is not empty
                {
                    //use the first filename it's extension to decide which action should happen
                    string s = Path.GetExtension(dlg.FileNames[0]);
                    if (s != null)
                    {
                        var firstExtension = s.ToLower();

                        XbimModel fedModel = null;
                        if (firstExtension == ".xbimf")
                        {
                            if (dlg.FileNames.Length > 1)
                            {
                                var res = MessageBox.Show("Multiple files selected, open " + dlg.FileNames[0] + "?", "Cannot open multiple Xbim files",
                                    MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                                if (res == MessageBoxResult.Cancel)
                                    return;
                            }
                            fedModel = new XbimModel();
                            fedModel.Open(dlg.FileNames[0], XbimDBAccess.ReadWrite);
                        }
                        else if (firstExtension == ".ifc")
                        {
                            //create temp file as a placeholder for the temperory xbim file
                            var filePath = Path.GetTempFileName();
                            filePath = Path.ChangeExtension(filePath, "xbimf");
                            fedModel = XbimModel.CreateModel(filePath);
                            fedModel.Initialise("Default Author", "Default Organization");
                            using (var txn = fedModel.BeginTransaction())
                            {
                                fedModel.IfcProject.Name = "Default Project Name";
                                txn.Commit();
                            }

                            var informUser = true;
                            for (var i = 0; i < dlg.FileNames.Length; i++)
                            {
                                var fileName = dlg.FileNames[i];
                                var builder = new XbimReferencedModelViewModel();
                                builder.Name = fileName;
                                builder.OrganisationName = "OrganisationName " + i;
                                builder.OrganisationRole = "Undefined";

                                var buildRes = false;
                                Exception exception = null;
                                try
                                {
                                    buildRes = builder.TryBuild(fedModel);
                                }
                                catch (Exception ex)
                                {
                                    //usually an EsentDatabaseSharingViolationException, user needs to close db first
                                    exception = ex;
                                }

                                if (!buildRes && informUser)
                                {
                                    var msg = exception == null ? "" : "\r\nMessage: " + exception.Message;
                                    var res = MessageBox.Show(fileName + " couldn't be opened." + msg + "\r\nShow this message again?",
                                        "Failed to open a file", MessageBoxButton.YesNoCancel, MessageBoxImage.Error);
                                    if (res == MessageBoxResult.No)
                                        informUser = false;
                                    else if (res == MessageBoxResult.Cancel)
                                    {
                                        fedModel = null;
                                        break;
                                    }
                                }
                            }
                        }
                        if (fedModel != null)
                        {
                            CloseAndDeleteTemporaryFiles();
                            ModelProvider.ObjectInstance = fedModel;
                            ModelProvider.Refresh();

                        }
                    }
                }
            }
        }
Ejemplo n.º 47
0
        public void Run()
        {
            //to start we need an ifc file, here it is Clinic_Example.ifc
            string ifcFile = @"IfcFiles/Clinic_Example.ifc";
            string xbimFile = Path.ChangeExtension(ifcFile, "xBIM");  //will generate if not existing
            
            if (File.Exists(ifcFile))
            {
                using (XbimModel model = new XbimModel())
                {
                    if (File.Exists(xbimFile))
                    {
                        //assume the xbim file has the geometry already generated from ifc file, as below
                        model.Open(xbimFile, XbimDBAccess.Read);
                    }
                    else
                    {
                        //create the xbim file from the ifc file
                        model.CreateFrom(ifcFile, xbimFile, delegate(int percentProgress, object userState)
                        {
                            Console.Write("\rReading File {0}", percentProgress);
                        });

                        model.Open(xbimFile, XbimDBAccess.ReadWrite); //readwrite as we need to add the geometry
                        //add the the geometry information to the model
                        int total = (int)model.Instances.CountOf<IfcProduct>();
                        ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                        {
                            Console.Write("\rGeometry {0} / {1}", total, (total * percentProgress / 100));
                        };
                        XbimMesher.GenerateGeometry(model, null, progDelegate);
                    }
                    
                     //get all the IfcDoors in the model
                     IEnumerable<IfcDoor> ifcDoors = model.IfcProducts.OfType<IfcDoor>(); //get all the ifcdoors for this model
                     if (ifcDoors.Any()) 
                     {
                         IfcDoor ifcDoor = ifcDoors.First(); //we use the first door to get the bounding box from
                         XbimGeometryData geoData = model.GetGeometryData(ifcDoor, XbimGeometryType.BoundingBox).FirstOrDefault();
                         if (geoData != null)
                         {
                             XbimRect3D boundBox = XbimRect3D.FromArray(geoData.ShapeData);//size information for the IfcDoor, but the information is for the bounding box which encloses the door 

                             //if want want in World space 
                             XbimMatrix3D worldMatrix = geoData.Transform;
                             //if we want to convert to World space we can use the geoData.Transform property and create the world matrix
                             XbimPoint3D MinPtOCS = new XbimPoint3D(boundBox.X, boundBox.Y, boundBox.Z);
                             XbimPoint3D MaxPtOCS = new XbimPoint3D(boundBox.X + boundBox.SizeX, boundBox.Y + boundBox.SizeY, boundBox.Z + boundBox.SizeZ);
                             //transformed values, may no longer a valid bounding box in the new space if any Pitch or Yaw, i.e. stairs ceiling supports
                             XbimPoint3D MinPtWCS = worldMatrix.Transform(MinPtOCS);
                             XbimPoint3D MaxPtWCS = worldMatrix.Transform(MaxPtOCS);
                             //if you product is at any angle to the World space then the bounding box can be recalculated, 
                            //a example of this can be found here https://sbpweb.svn.codeplex.com/svn/SBPweb.Workbench/Workbench%20Framework%202.0.0.x/Presentation/Windows.WPF/Utils/Maths.cs 
                            //in the TransformBounds function
                            Console.WriteLine("\n-------------Bounding Box Information-------------");
                            Console.WriteLine("Entity Type = {0}", IfcMetaData.GetType(geoData.IfcTypeId).Name);
                            Console.WriteLine("Entity Label = {0}", Math.Abs(ifcDoor.EntityLabel).ToString());
                            Console.WriteLine("Size X = {0:F2}", boundBox.SizeX.ToString());
                            Console.WriteLine("Size Y = {0:F2}", boundBox.SizeY.ToString());
                            Console.WriteLine("Size Z = {0:F2}", boundBox.SizeZ.ToString());
                            Console.WriteLine("Object space minimum point {0}", MinPtOCS);
                            Console.WriteLine("Object space maximum point {0}", MaxPtOCS);
                            Console.WriteLine("World space minimum point {0}", MinPtWCS);
                            Console.WriteLine("World space maximum point {0}", MaxPtWCS);
                            Console.WriteLine("---------------------------------------------");
                         }
                     }
                     else
                     {
                         Console.WriteLine(string.Format("Failed to find any IfcDoor's in {0}", ifcFile));
                         return; //exit
                     }
                }
            }
            else
            {
                Console.WriteLine(string.Format("Failed to find {0} in executable directory", ifcFile));
            }
            Console.WriteLine("\nFinished");
          
        }
Ejemplo n.º 48
0
        public void Run()
        {
            //to start we need an ifc file, here it is Clinic_Example.ifc
            string ifcFile  = @"IfcFiles/Clinic_Example.ifc";
            string xbimFile = Path.ChangeExtension(ifcFile, "xBIM");  //will generate if not existing

            if (File.Exists(ifcFile))
            {
                using (XbimModel model = new XbimModel())
                {
                    if (File.Exists(xbimFile))
                    {
                        //assume the xbim file has the geometry already generated from ifc file, as below
                        model.Open(xbimFile, XbimDBAccess.Read);
                    }
                    else
                    {
                        //create the xbim file from the ifc file
                        model.CreateFrom(ifcFile, xbimFile, delegate(int percentProgress, object userState)
                        {
                            Console.Write("\rReading File {0}", percentProgress);
                        });

                        model.Open(xbimFile, XbimDBAccess.ReadWrite); //readwrite as we need to add the geometry
                        //add the the geometry information to the model
                        int total = (int)model.Instances.CountOf <IfcProduct>();
                        ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                        {
                            Console.Write("\rGeometry {0} / {1}", total, (total * percentProgress / 100));
                        };
                        XbimMesher.GenerateGeometry(model, null, progDelegate);
                    }
                    XbimScene <XbimMeshGeometry3D, WpfMaterial> scene = GetModelScene(model);

                    IEnumerable <IfcDoor> ifcDoors = model.IfcProducts.OfType <IfcDoor>(); //get all the ifcdoors for this model
                    if (ifcDoors.Any())
                    {
                        IfcDoor ifcDoor = ifcDoors.First(); //we use the first door
                        int     entLbl  = Math.Abs(ifcDoor.EntityLabel);

                        foreach (var layer in scene.Layers)                  //loop material layers
                        {
                            var hidden = layer.Hidden as XbimMeshGeometry3D; //stored the points in Hidden
                            if (hidden != null)
                            {
                                foreach (var m in hidden.Meshes) //display simple count information
                                {
                                    if (m.EntityLabel != entLbl)
                                    {
                                        continue;                          //skip doors that do not match label
                                    }
                                    int startIndex                     = m.StartPosition;
                                    int endIndex                       = m.EndPosition;
                                    int startTriIndex                  = m.StartTriangleIndex;
                                    int endTriIndex                    = m.EndTriangleIndex;
                                    List <XbimPoint3D>  vertex         = hidden.Positions.GetRange(startIndex, (endIndex - startIndex) + 1);
                                    List <XbimVector3D> normals        = hidden.Normals.GetRange(startIndex, (endIndex - startIndex) + 1);
                                    List <int>          triangleIndexs = hidden.TriangleIndices.GetRange(startIndex, (endTriIndex - startTriIndex) + 1);
                                    Console.WriteLine("\n-------------Geometry Triangle Information-------------");
                                    Console.WriteLine("Entity Type = IfcDoor");
                                    Console.WriteLine("Entity Label = {0}", entLbl);
                                    Console.WriteLine("Layer = {0}", layer.Name);
                                    Console.WriteLine("Vertex count = {0}", vertex.Count);
                                    Console.WriteLine("Normal count = {0}", normals.Count);
                                    Console.WriteLine("TriangleIndexs count = {0}", triangleIndexs.Count);
                                    Console.WriteLine("---------------------------------------------------------");
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 49
0
 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();
 }
Ejemplo n.º 50
0
        /// <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();
        }
Ejemplo n.º 51
0
        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);
            }
        }
Ejemplo n.º 52
0
        public void OpenReadOnly()
        {
            Assert.IsTrue(XbimModel.ModelOpenCount == 0);
            using (XbimModel m = new XbimModel())
            {
                m.Open(ModelA, XbimDBAccess.Read);
                Assert.IsTrue(XbimModel.ModelOpenCount == 1);
                using (XbimModel m2 = new XbimModel())
                {
                    m2.Open(ModelA, XbimDBAccess.Read);
                    Assert.IsTrue(XbimModel.ModelOpenCount == 2);

                }
            }
            Assert.IsTrue(XbimModel.ModelOpenCount == 0);
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Loads a model (semantic and geometric) from a previously created .xbim file
 /// </summary>
 /// <param name="model"></param>
 /// <param name="semanticFileName"></param>
 private void ReloadModel(XbimModel model, string semanticFileName)
 {
     model.Open(semanticFileName, XbimExtensions.XbimDBAccess.Read, null);
 }