Exemple #1
0
        /// <summary>
        /// Converts an Ifc File to xBIM if it does not already exists, then converts the geoemtry to Xbim format and profiles the results
        /// </summary>
        /// <param name="args"> file[.ifc, xbim]</param>

        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("No Ifc or xBim file specified");
                return;
            }
            var fileName      = args[0];
            var mainStopWatch = new Stopwatch();

            mainStopWatch.Start();
            using (var model = GetModel(fileName))
            {
                if (model != null)
                {
                    var functionStack = new ConcurrentStack <Tuple <string, double> >();
                    ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                    {
                        if (percentProgress == -1)
                        {
                            functionStack.Push(new Tuple <string, double>(userState.ToString(), DateTime.Now.TimeOfDay.TotalMilliseconds));
                            Logger.InfoFormat("Entering - {0}", userState.ToString());
                        }

                        else if (percentProgress == 101)
                        {
                            Tuple <string, double> func;
                            if (functionStack.TryPop(out func))
                            {
                                Logger.InfoFormat("Complete in \t\t{0:0.0} ms", DateTime.Now.TimeOfDay.TotalMilliseconds - func.Item2);
                            }
                        }
                    };
                    var context = new Xbim3DModelContext(model);
                    context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: progDelegate);

                    mainStopWatch.Stop();
                    Logger.InfoFormat("Xbim total Compile Time \t\t{0:0.0} ms", mainStopWatch.ElapsedMilliseconds);
                    var wexBimFilename = Path.ChangeExtension(fileName, "wexBIM");
                    using (var wexBiMfile = new FileStream(wexBimFilename, FileMode.Create, FileAccess.Write))
                    {
                        using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                        {
                            var stopWatch = new Stopwatch();
                            Logger.InfoFormat("Entering -  Create wexBIM");
                            stopWatch.Start();
                            context.Write(wexBimBinaryWriter);
                            stopWatch.Stop();
                            Logger.InfoFormat("Complete - in \t\t{0:0.0} ms", stopWatch.ElapsedMilliseconds);
                            wexBimBinaryWriter.Close();
                        }
                        wexBiMfile.Close();
                    }

                    model.Close();
                }
            }
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }
Exemple #2
0
        //const string file = "F:\\TUM\\STUDIES\\THESIS\\BIMtoUnity\\xBIM\\IFC_samplefiles\\2011-09-14-Clinic-IFC\\simplegeometry_openings_4.ifc";
        //const string file = "F:\\TUM\\STUDIES\\THESIS\\BIMtoUnity\\xBIM\\IFC_samplefiles\\2011-09-14-Clinic-IFC\\20160414office_model_CV2_fordesign.ifc";
        //const string file = "F:\\TUM\\STUDIES\\THESIS\\BIMtoUnity\\xBIM\\IFC_samplefiles\\2011-09-14-Clinic-IFC\\wall.ifc";

        public static void Main()
        {
            using (var model = IfcStore.Open(file))
            {
                Console.WriteLine("\n" + "---------------------------------------S T A R T---------------------------------------" + "\n");
                Dictionary <string, IfcSpace>          spaceids;
                Dictionary <string, IfcBuildingStorey> storeyids;

                var project = model.Instances.FirstOrDefault <IIfcProject>();

                IEnumerable <IfcSpace> spaces = model.Instances.OfType <IfcSpace>();
                spaceids = getspaceelementids(spaces);

                IEnumerable <IfcBuildingStorey> storeys = model.Instances.OfType <IfcBuildingStorey>();
                storeyids = getstoreyelementids(storeys);

                var context = new Xbim3DModelContext(model);
                context.CreateContext();

                var productshape = context.ShapeInstances();

                var _productShape = context.ShapeInstances().Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded).ToList();

                Console.WriteLine("OPENED MODEL : " + file.Split(new char[] { '\\' }).Last() + " | No of shape Instances in the model is : " + _productShape.Count() + "\n");


                PrintHierarchy(project, 0, spaceids, storeyids, _productShape, context);

                Console.WriteLine("\n" + "---------------------------------------E N D---------------------------------------" + "\n");
                /********************************************************************************/
            }
        }
Exemple #3
0
        private static string CreateWexBIM(XbimModel model, string fileName)
        {
            try
            {
                var context = new Xbim3DModelContext(model);
                context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary);
                var wexBimFilename = Path.ChangeExtension(fileName, "wexBIM");
                using (var wexBiMfile = new FileStream(wexBimFilename, FileMode.Create, FileAccess.Write))
                {
                    using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                    {
                        //Console.WriteLine("Creating " + wexBimFilename);
                        context.Write(wexBimBinaryWriter);
                        wexBimBinaryWriter.Close();
                    }
                    wexBiMfile.Close();
                }

                return(wexBimFilename);
            }
            catch (Exception ex)
            {
                Log.Error("转换xBIM文件失败:" + ex.Message, ex);
                throw;
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("XbimWebin yourFile.ifc");
                return;
            }
            string fileName = args[0];

            using (var model = IfcStore.Open(fileName))
            {
                var context = new Xbim3DModelContext(model);
                context.CreateContext();

                var wexBimFilename = Path.ChangeExtension(fileName, "wexBIM");
                using (var wexBiMfile = File.Create(wexBimFilename))
                {
                    using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                    {
                        model.SaveAsWexBim(wexBimBinaryWriter);
                        wexBimBinaryWriter.Close();
                    }
                    wexBiMfile.Close();
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Validates all data and creates model.
        /// </summary>
        /// <returns>Returns XbimReferencedModel == null </returns>
        public bool TryBuildAndAddTo(IfcStore destinationFederatedModel)
        {
            //it's already build, so no need to recreate it
            if (ReferencedModel != null)
            {
                return(true);
            }

            if (string.IsNullOrWhiteSpace(Name))
            {
                return(false);
            }

            _xbimReferencedModel = destinationFederatedModel.AddModelReference(Name, OrganisationName, OrganisationRole);
            if (_xbimReferencedModel.Model.GeometryStore.IsEmpty)
            {
                var m3D = new Xbim3DModelContext(_xbimReferencedModel.Model);
                m3D.CreateContext(adjustWcs: adjustWcs);
            }

            if (_xbimReferencedModel == null)
            {
                return(ReferencedModel != null);
            }
            //refresh all
            OnPropertyChanged("Identifier");
            OnPropertyChanged("Name");
            OnPropertyChanged("OrganisationName");
            OnPropertyChanged("OrganisationRole");
            return(ReferencedModel != null);
        }
Exemple #6
0
        private void LoadXbimFile(string dlgFileName)
        {
            // TODO: should do the load on a worker thread so as not to lock the UI.
            // See how we use BackgroundWorker in XbimXplorer

            Clear();

            var model = IfcStore.Open(dlgFileName);

            if (model.GeometryStore.IsEmpty)
            {
                // Create the geometry using the XBIM GeometryEngine
                try
                {
                    var context = new Xbim3DModelContext(model);

                    context.CreateContext();

                    // TODO: SaveAs(xbimFile); // so we don't re-process every time
                }
                catch (Exception geomEx)
                {
                    Logger.LogError(0, geomEx, "Failed to create geometry for {filename}", dlgFileName);
                }
            }
            _wpfControl.ModelProvider.ObjectInstance = model;
        }
Exemple #7
0
        private void ConvertToWexBIM(string filePath)
        {
            //  const string fileName = "../../my.ifc";
            using (var model = IfcStore.Open(filePath))
            {
                var context = new Xbim3DModelContext(model);
                context.CreateContext();


                // physical full path in drive
                var wexBimFullPath = Path.ChangeExtension(filePath, "wexBIM");

                var wexBimFileName = Path.GetFileName(wexBimFullPath);

                ConfigurationManager.AppSettings.Set("wexBIMFileName", wexBimFileName);
                ConfigurationManager.AppSettings.Set("wexBIMFullPath", "../content/data/" + wexBimFileName);

                using (var wexBiMfile = System.IO.File.Create(wexBimFullPath))
                {
                    using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                    {
                        model.SaveAsWexBim(wexBimBinaryWriter);
                        wexBimBinaryWriter.Close();
                    }
                    wexBiMfile.Close();
                }
            }
        }
Exemple #8
0
        public static SceneBuilder ToGltf(IfcStore model)
        {
            var context = new Xbim3DModelContext(model);

            context.CreateContext();

            var ifcProject  = model.Instances.OfType <IIfcProject>().FirstOrDefault();
            var ifcSite     = model.Instances.OfType <IIfcSite>().FirstOrDefault();
            var ifcBuilding = ifcSite.Buildings.FirstOrDefault();
            var ifcStoreys  = ifcBuilding.BuildingStoreys; // 3 in case of office

            var spaceMeshes = new List <XbimShapeTriangulation>();

            foreach (var storey in ifcStoreys)
            {
                var spaces = storey.Spaces;
                foreach (var space in spaces)
                {
                    var ifcmesh = GetMeshes(context, space);
                    spaceMeshes.Add(ifcmesh);
                }
            }

            var mesh      = new MeshBuilder <VERTEX>("mesh");
            var material1 = new MaterialBuilder()
                            .WithDoubleSide(true)
                            .WithMetallicRoughnessShader()
                            .WithChannelParam("BaseColor", new Vector4(1, 0, 0, 1));


            foreach (var meshBim in spaceMeshes)
            {
                var faces    = (List <XbimFaceTriangulation>)meshBim.Faces;
                var vertices = (List <XbimPoint3D>)meshBim.Vertices;

                foreach (var face in meshBim.Faces)
                {
                    var indeces = face.Indices;

                    for (var triangle = 0; triangle < face.TriangleCount; triangle++)
                    {
                        var start = triangle * 3;
                        var p0    = meshBim.Vertices[indeces[start]];
                        var p1    = meshBim.Vertices[indeces[start + 1]];
                        var p2    = meshBim.Vertices[indeces[start + 2]];

                        var prim = mesh.UsePrimitive(material1);
                        prim.AddTriangle(
                            new VERTEX((float)p0.X, (float)p0.Z, (float)p0.Y),
                            new VERTEX((float)p1.X, (float)p1.Z, (float)p1.Y),
                            new VERTEX((float)p2.X, (float)p2.Z, (float)p2.Y));
                    }
                }
            }

            var scene = new SceneBuilder();

            scene.AddRigidMesh(mesh, Matrix4x4.Identity);
            return(scene);
        }
Exemple #9
0
        //private void Add_Click(object sender, RoutedEventArgs e)
        //{
        //    XbimModel model = DataContext as XbimModel;
        //    if (model != null)
        //    {
        //        AddFederatedModel fdlg = new AddFederatedModel();
        //        bool? done = fdlg.ShowDialog();
        //        if (done.HasValue && done.Value == true)
        //        {
        //            string fileName = fdlg.FileName;
        //            string ext = System.IO.Path.GetExtension(fileName);
        //            using (XbimModel refM = new XbimModel())
        //            {
        //                if (string.Compare(ext, ".xbim", true) != 0)
        //                {
        //                    refM.CreateFrom(fileName, null, null, true);
        //                    XbimMesher.GenerateGeometry(refM);
        //                    fileName = System.IO.Path.ChangeExtension(fileName, "xbim");
        //                }
        //            }
        //            IfcRole role = fdlg.Role;
        //            if (role == IfcRole.UserDefined)
        //                model.AddModelReference(fileName, fdlg.OrganisationName, fdlg.RoleName);
        //            else
        //                model.AddModelReference(fileName, fdlg.OrganisationName, role);
        //        }
        //    }
        //}


        private void Add_Click(object sender, RoutedEventArgs e)
        {
            XbimModel model = DataContext as XbimModel;

            if (model != null)
            {
                AddFederatedModel fdlg = new AddFederatedModel();
                bool?done = fdlg.ShowDialog();
                if (done.HasValue && done.Value == true)
                {
                    string fileName = fdlg.FileName;
                    string ext      = System.IO.Path.GetExtension(fileName);
                    using (XbimModel refM = new XbimModel())
                    {
                        if (string.Compare(ext, ".xbim", true) != 0)
                        {
                            refM.CreateFrom(fileName, null, null, true);
                            var m3D = new Xbim3DModelContext(refM);
                            m3D.CreateContext();
                            fileName = System.IO.Path.ChangeExtension(fileName, "xbim");
                        }
                    }
                    IfcRole role = fdlg.Role;
                    if (role == IfcRole.UserDefined)
                    {
                        model.AddModelReference(fileName, fdlg.OrganisationName, fdlg.RoleName);
                    }
                    else
                    {
                        model.AddModelReference(fileName, fdlg.OrganisationName, role);
                    }
                }
            }
        }
Exemple #10
0
        private void Modify_Click(object sender, RoutedEventArgs e)
        {
            XbimModel model = DataContext as XbimModel;

            foreach (var item in FederatedList.SelectedItems)
            {
                if (item is XbimReferencedModel)
                {
                    var rItem = item as XbimReferencedModel;
                    AddFederatedModel fdlg = new AddFederatedModel(rItem);

                    bool?done = fdlg.ShowDialog();
                    if (done.HasValue && done.Value == true)
                    {
                        string fileName = fdlg.FileName;
                        string ext      = System.IO.Path.GetExtension(fileName);
                        using (XbimModel refM = new XbimModel())
                        {
                            if (string.Compare(ext, ".xbim", true) != 0)
                            {
                                refM.CreateFrom(fileName, null, null, true);
                                var m3D = new Xbim3DModelContext(refM);
                                m3D.CreateContext();
                                fileName = System.IO.Path.ChangeExtension(fileName, "xbim");
                            }
                        }
                        using (var txn = model.BeginTransaction())
                        {
                            rItem.DocumentInformation.Name = fileName;
                            txn.Commit();
                        }
                    }
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Constructor of spatial relations analyser of axis aligned bounding boxes of the products.
        /// If you already have a dictionary of the AABBoxes and products you should use the other constructor
        /// </summary>
        /// <param name="model">Building model</param>
        public XbimAABBoxAnalyser(XbimModel model)
        {
            _model = model;
            Xbim3DModelContext context = new Xbim3DModelContext(model);

            if (model.GeometriesCount == 0)
            {
                context.CreateContext();
            }


            //create cached BBoxes
            foreach (var prod in model.IfcProducts.Cast <IfcProduct>())
            {
                XbimRect3D prodBox = XbimRect3D.Empty;
                foreach (var shp in context.ShapeInstancesOf(prod))
                {
                    //bounding boxes are lightweight and are produced when geometry is created at first place

                    //get or cast to BBox
                    var bb = shp.BoundingBox;
                    bb = XbimRect3D.TransformBy(bb, shp.Transformation);
                    if (prodBox.IsEmpty)
                    {
                        prodBox = bb;
                    }
                    else
                    {
                        prodBox.Union(bb);
                    }
                    //add every BBox to the world to get the size and position of the world
                }
                _prodBBs.Add(prod, prodBox);
            }
        }
Exemple #12
0
 static void Main(string[] args)
 {
     string             file    = @"C:\Users\Flo\source\repos\XbimToolkit\IfcFiles\miniExample20080731_CoordView_SweptSolid.ifc";
     var                model   = IfcStore.Open(file, null);
     Xbim3DModelContext context = new Xbim3DModelContext(model);
     var                c       = context.CreateContext();
 }
        private void LoadIFCFile(string dlgFileName)
        {
            var currentIfcStore = DrawingControl.Model as IfcStore;

            currentIfcStore?.Dispose();
            DrawingControl.Model = null;
            var model = IfcStore.Open(dlgFileName);

            if (model.GeometryStore.IsEmpty)
            {
                // Create the geometry using the XBIM GeometryEngine
                try
                {
                    var context = new Xbim3DModelContext(model);
                    context.CreateContext();
                    // TODO: SaveAs(xbimFile); // so we don't re-process every time
                }
                catch (Exception geomEx)
                {
                    //Logger.LogError(0, geomEx, "Failed to create geometry for {filename}", dlgFileName);
                    MessageBox.Show(geomEx.ToString());
                }
            }
            //DrawingControl.Model = model;
            ModelStore = model;
        }
Exemple #14
0
        public static void ConvertFile(string ifcFileFullName, string destinationFolder, string wexBimFileName, string xbimFile)
        {
            string workingDir = destinationFolder;

            if (string.IsNullOrWhiteSpace(destinationFolder))
            {
                workingDir = Path.GetDirectoryName(ifcFileFullName);
            }
            else
            {
                workingDir = destinationFolder;
            }
            if (string.IsNullOrWhiteSpace(workingDir))
            {
                throw new ApplicationException("The destination folder not specified.");
            }
            if (!Path.IsPathRooted(workingDir))
            {
                throw new ApplicationException("The destination folder not rooted.");
            }
            if (!Directory.Exists(workingDir))
            {
                throw new ApplicationException("The destination folder not found.");
            }
            string fileName = Path.GetFileName(ifcFileFullName);
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
            string coreDestinationFileName  = Path.Combine(workingDir, fileNameWithoutExtension);

            if (string.IsNullOrWhiteSpace(wexBimFileName))
            {
                wexBimFileName = Path.ChangeExtension(coreDestinationFileName, "wexbim");
            }
            else
            {
                wexBimFileName = Path.Combine(workingDir, Path.GetFileName(wexBimFileName));
            }
            if (string.IsNullOrWhiteSpace(xbimFile))
            {
                xbimFile = Path.ChangeExtension(coreDestinationFileName, "xbim");
            }
            else
            {
                xbimFile = Path.Combine(workingDir, Path.GetFileName(xbimFile));
            }
            using (FileStream wexBimFile = new FileStream(wexBimFileName, FileMode.Create))
            {
                using (BinaryWriter binaryWriter = new BinaryWriter(wexBimFile))
                {
                    using (XbimModel model = new XbimModel())
                    {
                        model.CreateFrom(ifcFileFullName, xbimFile, null, true, false);
                        Xbim3DModelContext geomContext = new Xbim3DModelContext(model);
                        geomContext.CreateContext(XbimGeometryType.PolyhedronBinary); // System.OutOfMemoryException Exception
                        geomContext.Write(binaryWriter);
                    }
                }
            }
        }
Exemple #15
0
 private void GetModel(object sender, RoutedEventArgs e)
 {
     using (var m = IfcStore.Open(@"C:\Users\Claudio\Dev\XbimTeam\XbimWebUI\Xbim.WeXplorer\tests\data\OneWall.ifc"))
     {
         var c = new Xbim3DModelContext(m);
         c.CreateContext();
         m.SaveAs("model.xbim");
     }
 }
        public override void Calculate()
        {
            if (InputPorts[0].Data == null)
            {
                return;
            }

            //in TTValueColor hashTable
            TTValueColorAll        = new Hashtable();
            TTValueColorExistin    = new Hashtable();
            TTValueColorCalculated = new Hashtable();
            //get all colors available in a list
            Console.WriteLine("Total of " + _Colors.Count + " Colors available!!");

            OutputPorts[0].Data = null;

            _viewPort.Children.Clear();
            _viewPort.Children.Add(new SunLight());

            var IfcVersionType = InputPorts[0].Data.GetType();

            if (IfcVersionType.Name == "ModelInfoIFC2x3")
            {
                var modelId = ((ModelInfoIFC2x3)(InputPorts[0].Data)).ModelId;
                if (modelId == null)
                {
                    return;
                }

                _xModel = DataController.Instance.GetModel(modelId, true);

                var context = new Xbim3DModelContext(_xModel);
                //upgrade to new geometry representation, use the default 3D model
                context.CreateContext();

                worker_DoWork_IFC2x3(_xModel);
                worker = new BackgroundWorker();
            }
            else
            {
                var modelId = ((ModelInfoIFC4)(InputPorts[0].Data)).ModelId;
                if (modelId == null)
                {
                    return;
                }

                _xModel = DataController.Instance.GetModel(modelId, true);

                var context = new Xbim3DModelContext(_xModel);
                //upgrade to new geometry representation, use the default 3D model
                context.CreateContext();

                worker_DoWork_IFC4(_xModel);
                worker = new BackgroundWorker();
            }
        }
Exemple #17
0
        //Use automatic indentation for readability.



        public static void Main()
        {
            using (var model = IfcStore.Open(file))
            {
                Console.WriteLine("\n" + "---------------------------------------S T A R T---------------------------------------" + "\n");
                Dictionary <string, IfcSpace>          spaceids;
                Dictionary <string, IfcBuildingStorey> storeyids;

                var project = model.Instances.FirstOrDefault <IIfcProject>();

                IEnumerable <IfcSpace> spaces = model.Instances.OfType <IfcSpace>();
                spaceids = getspaceelementids(spaces);

                IEnumerable <IfcBuildingStorey> storeys = model.Instances.OfType <IfcBuildingStorey>();
                storeyids = getstoreyelementids(storeys);

                var context = new Xbim3DModelContext(model);
                context.CreateContext();

                var productshape = context.ShapeInstances();

                var _productShape = context.ShapeInstances().Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded).ToList();

                //name of the model
                var name_of_model = file.Split(new char[] { '\\' }).Last();

                //number of shapes in the model
                var number_of_shapes = _productShape.Count();

                Console.WriteLine("OPENED MODEL : " + name_of_model + " | No of shape Instances in the model is : " + number_of_shapes + "\n");


                //get the name of the model without the ifc extention
                var name_of_file = name_of_model.Split('.')[0];

                //creating the xml file in the project directory named after the name of the model
                xmlWriter = new XmlTextWriter(name_of_file + ".xml", null);

                //in order to have the correct xml format
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.WriteStartDocument();
                //writing the start element Shapes with his attribut NumShapes
                xmlWriter.WriteStartElement("Shapes");
                xmlWriter.WriteAttributeString("NumShapes", number_of_shapes.ToString());


                PrintHierarchy(project, 0, spaceids, storeyids, _productShape, number_of_shapes, context);


                xmlWriter.WriteEndDocument();
                xmlWriter.Close();
                Console.WriteLine("\n" + "---------------------------------------E N D---------------------------------------" + "\n");
                /********************************************************************************/
            }
            Console.ReadLine();
        }
        public void ExportByStorey(IfcStore store, bool exportSemantic = true)
        {
            var f   = new FileInfo(store.FileName);
            var dir = f.Directory;

            if (store.GeometryStore.IsEmpty)
            {
                var context = new Xbim3DModelContext(store);
                context.CreateContext();
            }

            foreach (var storey in store.Instances.OfType <IIfcBuildingStorey>())
            {
                // prepare filter
                var        rels = store.Instances.OfType <IIfcRelContainedInSpatialStructure>().Where(x => x.RelatingStructure.EntityLabel == storey.EntityLabel);
                List <int> els  = new List <int>();
                foreach (var rel in rels)
                {
                    els.AddRange(rel.RelatedElements.Select(x => x.EntityLabel));
                }
                elemsToExport = els.ToArray();

                // write gltf
                //
                var bldr = new Builder();
                bldr.BufferInBase64 = true;
                bldr.CustomFilter   = this.Filter;

                var storeyName = storey.Name.ToString();
                if (HasInvalidChars(storeyName))
                {
                    storeyName = storey.EntityLabel.ToString();
                }

                var outName = Path.Combine(
                    dir.FullName,
                    f.Name + "." + storeyName + ".gltf"
                    );
                var ret = bldr.BuildInstancedScene(store);
                if (ret != null && exportSemantic)
                {
                    // actual write if not empty model.
                    //
                    glTFLoader.Interface.SaveModel(ret, outName);

                    // write json
                    //
                    var jsonFileName = Path.ChangeExtension(outName, "json");
                    var bme          = new BuildingModelExtractor();
                    bme.CustomFilter = this.Filter;
                    var rep = bme.GetModel(store);
                    rep.Export(jsonFileName);
                }
            }
        }
        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 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());
            }
        }
Exemple #21
0
 private static FileInfo CreateGeometry(FileInfo f, bool mode, bool useAlternativeExtruder)
 {
     IfcStore.ModelProviderFactory.UseHeuristicModelProvider();
     using (var m = IfcStore.Open(f.FullName))
     {
         var c = new Xbim3DModelContext(m);
         c.CreateContext(null, mode);
         var newName = Path.ChangeExtension(f.FullName, mode + ".xbim");
         m.SaveAs(newName);
         return(new FileInfo(newName));
     }
 }
Exemple #22
0
        // NOTE: I don't recommend you do this under a web server due to the use of unmanaged code and the fact the operation is very expensive in terms of resources
        private void BuildGeometry(XbimModel model, string geometryFileName)
        {
            if (Cached(geometryFileName))
            {
                return;
            }
            var m3DModelContext = new Xbim3DModelContext(model);

            m3DModelContext.CreateContext(XbimGeometryType.PolyhedronBinary);

            ExportGeometryData(geometryFileName, m3DModelContext);
        }
        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();
            }
        }
Exemple #24
0
        internal static List <Data> HierarchyRun(IfcStore model)
        {
            var project = model.Instances.FirstOrDefault <IIfcProject>();

            var context = new Xbim3DModelContext(model);

            context.CreateContext();
            List <XbimShapeInstance> allShapeInstances = context.ShapeInstances().ToList();

            List <Data> data = GetIfc4.GetHierarchialData(project, 0, allShapeInstances);

            return(data);
        }
Exemple #25
0
        public static SceneBuilder ToGltf(IfcStore model)
        {
            var context = new Xbim3DModelContext(model);

            context.CreateContext();
            var geoms = context.ShapeGeometries().ToList();

            Console.WriteLine("Number of geometries: " + geoms.Count);

            var mesh      = new MeshBuilder <VERTEX>("mesh");
            var material1 = new MaterialBuilder()
                            .WithDoubleSide(true)
                            .WithMetallicRoughnessShader()
                            .WithChannelParam("BaseColor", new Vector4(1, 0, 0, 1));


            foreach (var geom in geoms)
            {
                var data = ((IXbimShapeGeometryData)geom).ShapeData;

                using var stream = new MemoryStream(data);
                using var reader = new BinaryReader(stream);
                var meshBim = reader.ReadShapeTriangulation();

                foreach (var face in meshBim.Faces)
                {
                    var indeces = face.Indices;

                    for (var triangle = 0; triangle < face.TriangleCount; triangle++)
                    {
                        var start = triangle * 3;
                        var p0    = meshBim.Vertices[indeces[start]];
                        var p1    = meshBim.Vertices[indeces[start + 1]];
                        var p2    = meshBim.Vertices[indeces[start + 2]];

                        var prim = mesh.UsePrimitive(material1);
                        prim.AddTriangle(
                            new VERTEX((float)p0.X, (float)p0.Y, (float)p0.Z * 10),
                            new VERTEX((float)p1.X, (float)p1.Y, (float)p1.Z * 10),
                            new VERTEX((float)p2.X, (float)p2.Y, (float)p2.Z * 10));
                    }
                }
            }


            var scene = new SceneBuilder();

            scene.AddRigidMesh(mesh, Matrix4x4.Identity);
            return(scene);
        }
Exemple #26
0
        /// <summary>
        /// Generates the Geometry from the semantic model
        /// </summary>
        /// <remarks>Geometry is stored in the xbim file and optionally exported to a wexbim file
        /// for use in optimised viewers etc</remarks>
        /// <param name="model"></param>
        /// <param name="geometryFileName"></param>
        private static void BuildGeometry(XbimModel model, string geometryFileName = "")
        {
            Console.WriteLine("Generating Geometry...");
            var m3DModelContext = new Xbim3DModelContext(model);

            m3DModelContext.CreateContext(XbimGeometryType.PolyhedronBinary);

            if (!String.IsNullOrEmpty(geometryFileName))
            {
                // This is optional. The generated geometry is already saved in the xbim file, but a wexbim
                // format is much for transmission over a network (and is optimised for display)
                ExportGeometryData(geometryFileName, m3DModelContext);
            }
        }
Exemple #27
0
        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());
            }
        }
        // [DeploymentItem("TestFiles\\LargeTriangulatedCoordinates.ifc")]
        public void LargeCoordinatesDisplacementTest()
        {
            using (var m = new MemoryModel(new Ifc2x3.EntityFactoryIfc2x3()))
            {
                m.LoadStep21("TestFiles\\LargeTriangulatedCoordinates.ifc");
                var c = new Xbim3DModelContext(m);
                c.CreateContext(null, false);

                using (var store = m.GeometryStore.BeginRead())
                {
                    // region should be placed far away from origin
                    var region = store.ContextRegions.FirstOrDefault().MostPopulated();
                    var centre = region.Centre;
                    Assert.IsTrue(centre.X > 300000);
                    Assert.IsTrue(centre.Y > 6200000);

                    var product = m.Instances.FirstOrDefault <IIfcBuildingElementProxy>();

                    Assert.IsNotNull(product.Representation);

                    var instances = store.ShapeInstancesOfEntity(product);
                    Assert.AreEqual(1, instances.Count());

                    var instance = instances.First();
                    var geometry = store.ShapeGeometryOfInstance(instance);

                    // this should be a large displacement
                    var transform = instance.Transformation;
                    var length    = transform.Translation.Length;
                    Assert.IsTrue(length > 6200000);

                    // geometry thould be in small numbers
                    var ms = new MemoryStream(((IXbimShapeGeometryData)geometry).ShapeData);
                    var br = new BinaryReader(ms);
                    var tr = br.ReadShapeTriangulation();

                    var point = tr.Vertices.FirstOrDefault();
                    Assert.IsTrue(point.X < 1000);
                    Assert.IsTrue(point.Y < 1000);
                    Assert.IsTrue(point.Z < 1000);

                    // when transformation is applied to the geometry it should be large
                    tr    = tr.Transform(transform);
                    point = tr.Vertices.FirstOrDefault();
                    Assert.IsTrue(point.X > 300000);
                    Assert.IsTrue(point.Y > 6200000);
                }
            }
        }
Exemple #29
0
        private static void WriteWexBim(string fnameIn)
        {
            var fNameOut = Path.ChangeExtension(fnameIn, "wexbim");

            using (var m = IfcStore.Open(fnameIn))
            {
                var m3D = new Xbim3DModelContext(m);
                m3D.CreateContext();
                using (var bw = new BinaryWriter(new FileStream(fNameOut, FileMode.Create)))
                {
                    m.SaveAsWexBim(bw);
                    bw.Close();
                }
            }
        }
 public static Task <Stream> ConvertIfcToWexBimAsync(IfcStore ifcStore)
 {
     return(Task.Run <Stream>(() =>
     {
         var context = new Xbim3DModelContext(ifcStore);
         context.CreateContext();
         var memStream = new MemoryStream();
         using (var wexBimBinaryWriter = new BinaryWriter(memStream, Encoding.Default, true))
         {
             ifcStore.SaveAsWexBim(wexBimBinaryWriter);
         }
         memStream.Position = 0;
         return memStream;
     }));
 }
        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 BindUi(IXbimXplorerPluginMasterWindow mainWindow)
        {
            _parentWindow = mainWindow;
            SetBinding(ModelProperty, new Binding());

            ScriptingControl.OnModelChangedByScript += delegate(object o, ModelChangedEventArgs arg)
            {
                ModelProperty = null;
                var m3D = new Xbim3DModelContext(arg.NewModel);
                m3D.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: null, adjustWCS: false);
                Model = arg.NewModel;
                // todo: Fire Update request of model property (is it needed?)
                // ModelProvider.Refresh();
            };

            ScriptingControl.OnScriptParsed += delegate
            {
                // todo: Fire Update request to parent window
                // GroupControl.Regenerate();
                // SpatialControl.Regenerate();
            };
        }
        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();
            }
        }
        /// <summary>
        /// Validates all data and creates model. 
        /// Provide a "XbimModel model = DataContext as XbimModel;"
        /// </summary>
        /// <returns>Returns XbimReferencedModel == null </returns>
        public bool TryBuild(XbimModel model)
        {
            //it's already build, so no need to recreate it
            if (ReferencedModel != null)
                return true;

		    if (string.IsNullOrWhiteSpace(Name))
                return false;
            var ext = Path.GetExtension(Name).ToLowerInvariant();
            using (var refM = new XbimModel())
            {
                var xbimName = Path.ChangeExtension(Name, "xbim");
                if (ext != ".xbim" && !File.Exists(xbimName))
                {
                    refM.CreateFrom(Name, null, null, true);
                    var m3D = new Xbim3DModelContext(refM);
                    m3D.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: null, adjustWCS: false);
                    Name = Path.ChangeExtension(Name, "xbim");
                }
                Name = xbimName;
            }
            _xbimReferencedModel = model.AddModelReference(Name, OrganisationName, OrganisationRole);

            if (_xbimReferencedModel == null) 
                return ReferencedModel != null;
            //refresh all
            OnPropertyChanged("Identifier");
            OnPropertyChanged("Name");
            OnPropertyChanged("OrganisationName");
            OnPropertyChanged("OrganisationRole");
            return ReferencedModel != null;
        }
        /// <summary>
        /// Validates all data and creates model. 
        /// Provide a "XbimModel model = DataContext as XbimModel;"
        /// </summary>
        /// <returns>Returns XbimReferencedModel == null </returns>
        public bool TryBuild(XbimModel model)
        {
            //it's already build, so no need to recreate it
            if (ReferencedModel != null)
                return true;

            if (string.IsNullOrWhiteSpace(Name))
                return false;
            string ext = Path.GetExtension(Name).ToLowerInvariant();
            using (XbimModel refM = new XbimModel())
            {
                if (ext != ".xbim")
                {
                    refM.CreateFrom(Name, null, null, true);
                    var m3D = new Xbim3DModelContext(refM);
                    m3D.CreateContext();
                    Name = Path.ChangeExtension(Name, "xbim");
                }
            }

            _xbimReferencedModel = model.AddModelReference(Name, OrganisationName, OrganisationRole);

            if (_xbimReferencedModel != null)
            {
                //refresh all
                OnPropertyChanged("Identifier");
                OnPropertyChanged("Name");
                OnPropertyChanged("OrganisationName");
                OnPropertyChanged("OrganisationRole");
            }
            return ReferencedModel != null;
        }
        private void OpenScriptingWindow(object sender, RoutedEventArgs e)
        {
            var win = new ScriptingWindow();
            win.Owner = this;

            win.ScriptingConcrol.DataContext = ModelProvider;
            var binding = new Binding();
            win.ScriptingConcrol.SetBinding(ScriptingControl.ModelProperty, binding);

            win.ScriptingConcrol.OnModelChangedByScript += delegate(object o, ModelChangedEventArgs arg)
            {
                ModelProvider.ObjectInstance = null;
                var m3D = new Xbim3DModelContext(arg.NewModel);
                m3D.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary);
                ModelProvider.ObjectInstance = arg.NewModel;
                ModelProvider.Refresh();
            };

            win.ScriptingConcrol.OnScriptParsed += delegate
            {
                GroupControl.Regenerate();
                //SpatialControl.Regenerate();
            };

            ScriptResults.Visibility = Visibility.Visible;
            win.Closing += delegate {
                ScriptResults.Visibility = Visibility.Collapsed;
            };

            win.Show();
        }
        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());
            }
        }
Exemple #38
0
 private static void WriteWexBim(string fnameIn)
 {
     var fNameOut = Path.ChangeExtension(fnameIn, "wexbim");
     using (var m = new XbimModel())
     {
         m.CreateFrom(fnameIn, null, null, true, true);
         var m3D = new Xbim3DModelContext(m);
         m3D.CreateContext(XbimGeometryType.PolyhedronBinary);
         using (var bw = new BinaryWriter(new FileStream(fNameOut, FileMode.Create)))
         {
             m3D.Write(bw);
             bw.Close();
         }
     }
 }
        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 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 Add_Click(object sender, RoutedEventArgs e)
 //{
 //    XbimModel model = DataContext as XbimModel;
 //    if (model != null)
 //    {
 //        AddFederatedModel fdlg = new AddFederatedModel();
 //        bool? done = fdlg.ShowDialog();
 //        if (done.HasValue && done.Value == true)
 //        {
 //            string fileName = fdlg.FileName;
 //            string ext = System.IO.Path.GetExtension(fileName);
 //            using (XbimModel refM = new XbimModel())
 //            {
 //                if (string.Compare(ext, ".xbim", true) != 0)
 //                {
 //                    refM.CreateFrom(fileName, null, null, true);
 //                    XbimMesher.GenerateGeometry(refM);
 //                    fileName = System.IO.Path.ChangeExtension(fileName, "xbim");
 //                }
 //            }
 //            IfcRole role = fdlg.Role;
 //            if (role == IfcRole.UserDefined)
 //                model.AddModelReference(fileName, fdlg.OrganisationName, fdlg.RoleName);
 //            else
 //                model.AddModelReference(fileName, fdlg.OrganisationName, role);
 //        }
 //    }
 //}
 private void Add_Click(object sender, RoutedEventArgs e)
 {
     XbimModel model = DataContext as XbimModel;
     if (model != null)
     {
         AddFederatedModel fdlg = new AddFederatedModel();
         bool? done = fdlg.ShowDialog();
         if (done.HasValue && done.Value == true)
         {
             string fileName = fdlg.FileName;
             string ext = System.IO.Path.GetExtension(fileName);
             using (XbimModel refM = new XbimModel())
             {
                 if (string.Compare(ext, ".xbim", true) != 0)
                 {
                     refM.CreateFrom(fileName, null, null, true);
                     var m3D = new Xbim3DModelContext(refM);
                     m3D.CreateContext();
                     fileName = System.IO.Path.ChangeExtension(fileName, "xbim");
                 }
             }
             IfcRole role = fdlg.Role;
             if (role == IfcRole.UserDefined)
                 model.AddModelReference(fileName, fdlg.OrganisationName, fdlg.RoleName);
             else
                 model.AddModelReference(fileName, fdlg.OrganisationName, role);
         }
     }
 }
        public void ReadAndWriteWexBimFile()
        {
            using (var m = new XbimModel())
            {
                m.CreateFrom("SolidTestFiles\\19 - TwoProxy.ifc", null, null, true, true);
                var m3D = new Xbim3DModelContext(m);
                m3D.CreateContext(XbimGeometryType.PolyhedronBinary);
                using (var bw = new BinaryWriter(new FileStream("test.wexBIM", FileMode.Create)))
                {
                    m3D.Write(bw);
                    bw.Close();
                }
                using (var fs = new FileStream(@"test.wexBIM", FileMode.Open, FileAccess.Read))
                {
                    using (var br = new BinaryReader(fs))
                    {
                        var magicNumber = br.ReadInt32();
                        var version = br.ReadByte();
                        var shapeCount = br.ReadInt32();
                        var vertexCount = br.ReadInt32();
                        var triangleCount = br.ReadInt32();
                        var matrixCount = br.ReadInt32();
                        var productCount = br.ReadInt32();
                        var styleCount = br.ReadInt32();
                        var meter =  br.ReadSingle();
                        Assert.IsTrue(meter>0);
                        var regionCount = br.ReadInt16();
                        for (int i = 0; i < regionCount; i++)
                        {
                            var population = br.ReadInt32();
                            var centreX = br.ReadSingle();
                            var centreY = br.ReadSingle();
                            var centreZ = br.ReadSingle();
                            var boundsBytes = br.ReadBytes(6 * sizeof(float));
                            var modelBounds = XbimRect3D.FromArray(boundsBytes);
                        }

                        for (int i = 0; i < styleCount; i++)
                        {
                            var styleId = br.ReadInt32();
                            var red = br.ReadSingle();
                            var green = br.ReadSingle();
                            var blue = br.ReadSingle();
                            var alpha = br.ReadSingle();
                        }
                        for (int i = 0; i < productCount ; i++)
                        {
                            var productLabel = br.ReadInt32();
                            var productType = br.ReadInt16();
                            var boxBytes = br.ReadBytes(6 * sizeof(float));
                            XbimRect3D bb = XbimRect3D.FromArray(boxBytes);
                        }
                        for (int i = 0; i < shapeCount; i++)
                        {
                            var shapeRepetition = br.ReadInt32();
                            Assert.IsTrue(shapeRepetition > 0);
                            if (shapeRepetition > 1)
                            {
                                for (int j = 0; j < shapeRepetition; j++)
                                {
                                    var ifcProductLabel = br.ReadInt32();
                                    var instanceTypeId = br.ReadInt16();
                                    var instanceLabel = br.ReadInt32();
                                    var styleId = br.ReadInt32();
                                    var transform = XbimMatrix3D.FromArray(br.ReadBytes(sizeof(float) * 16));
                                }
                                var triangulation = br.ReadShapeTriangulation();
                            }
                            else if (shapeRepetition == 1)
                            {
                                var ifcProductLabel = br.ReadInt32();
                                var instanceTypeId = br.ReadInt16();
                                var instanceLabel = br.ReadInt32();
                                var styleId = br.ReadInt32();
                                var triangulation = br.ReadShapeTriangulation();
                            }
                        }
                    }
                }

            }
        }
 //Needed Geometry to test, but Steve's comment on "need to resolve generate geometry" may see GenerateGeometry change
 private void GenerateGeometry(COBieContext context)
 {
     //now convert the geometry
     XbimModel model = context.Model;
     int total = (int)model.Instances.CountOf<IfcProduct>();
     ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
     {
         context.UpdateStatus("Creating Geometry File", total, (total * percentProgress / 100));
     };
     var m3D = new Xbim3DModelContext(model);
     try
     {
         m3D.CreateContext(progDelegate: progDelegate);
     }
     catch (Exception ce)
     {
         context.UpdateStatus("Error compiling geometry\n" + ce.Message, total, 100);
     }
 }
Exemple #44
0
        static void Main(string[] args)
        {
            
            if (args.Length < 1)
            {
                Console.WriteLine("No Ifc or xBim file specified");
                return;
            }
            var fileName = args[0];
            Console.WriteLine("Reading " + fileName);
           
            using (var model = GetModel(fileName))
            {
                if (model != null)
                {
                   
                    var context = new Xbim3DModelContext(model);
                    context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary);
                    var wexBimFilename = Path.ChangeExtension(fileName, "wexBIM");
                    using (var wexBiMfile = new FileStream(wexBimFilename, FileMode.Create, FileAccess.Write))
                    {
                        using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                        {
                            Console.WriteLine("Creating " + wexBimFilename);
                            context.Write(wexBimBinaryWriter);
                            wexBimBinaryWriter.Close();
                        }
                        wexBiMfile.Close();
                    }
                    //now do the DPoW files
                    var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                    var fileDirectoryName = Path.GetDirectoryName(fileName);
                    var facilities = new List<Facility>();
                    var ifcToCoBieLiteUkExchanger = new IfcToCOBieLiteUkExchanger(model, facilities);
                    facilities = ifcToCoBieLiteUkExchanger.Convert();
                    
                    var facilityNumber = 0;

                    foreach (var facility in facilities)
                    {
                        var dpow = "DPoW";
                        if (facilities.Count > 1) 
                            dpow += ++facilityNumber;
                        // ReSharper disable AssignNullToNotNullAttribute
                        var dPoWFile = Path.Combine(fileDirectoryName, fileNameWithoutExtension + "_" + dpow);
                        // ReSharper restore AssignNullToNotNullAttribute
                        dPoWFile = Path.ChangeExtension(dPoWFile, "json");
                        Console.WriteLine("Creating " + dPoWFile);

                        facility.WriteJson(dPoWFile);
                        string cobieFile = Path.ChangeExtension(dPoWFile, "Xlsx");
                        Console.WriteLine("Creating " + cobieFile);
                        string error;
                        facility.WriteCobie(cobieFile, out error);
                        if (!string.IsNullOrWhiteSpace(error))
                            Console.WriteLine("COBie Errors: " + error);

                        dPoWFile = Path.ChangeExtension(dPoWFile, "xml");
                        Console.WriteLine("Creating " + dPoWFile);
                       // facility.WriteXml(dPoWFile);
                        var req = Facility.ReadJson(@"..\..\Tests\ValidationFiles\Lakeside_Restaurant-stage6-COBie.json");
                        var validator = new FacilityValidator();
                        var result = validator.Validate(req, facility);
                        var verificationResults = Path.ChangeExtension(dPoWFile, "verified.xlsx");
                        Console.WriteLine("Creating " + verificationResults);
                        //create report
                        using (var stream = File.Create(verificationResults))
                        {
                            var report = new ExcelValidationReport();
                            report.Create(result, stream, ExcelValidationReport.SpreadSheetFormat.Xlsx);
                            stream.Close();
                        }

                        facility.ValidateUK2012(Console.Out,true);
                        string cobieValidatedFile = Path.ChangeExtension(dPoWFile, "Validated.Xlsx");
                        facility.WriteCobie(cobieValidatedFile, out error);
                        dPoWFile = Path.ChangeExtension(dPoWFile, "xbim");
                        Console.WriteLine("Creating " + dPoWFile);
                        using (var ifcModel = XbimModel.CreateModel(dPoWFile))
                        {
                            ifcModel.Initialise("Xbim Tester", "XbimTeam", "Xbim.Exchanger", "Xbim Development Team", "3.0");
                            ifcModel.ReloadModelFactors();
                            using (var txn = ifcModel.BeginTransaction("Convert from COBieLiteUK"))
                            {
                                var coBieLiteUkToIfcExchanger = new CoBieLiteUkToIfcExchanger(facility, ifcModel);
                                coBieLiteUkToIfcExchanger.Convert();
                                txn.Commit();
                                //var err = model.Validate(model.Instances, Console.Out);
                            }
                            dPoWFile = Path.ChangeExtension(dPoWFile, "ifc");
                            Console.WriteLine("Creating " + dPoWFile);
                            ifcModel.SaveAs(dPoWFile, XbimStorageType.IFC);
                            ifcModel.Close();
                        }
                    }
                    model.Close();
                }
            }
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }
        // NOTE: I don't recommend you do this under a web server due to the use of unmanaged code and the fact the operation is very expensive in terms of resources
        private void BuildGeometry(XbimModel model, string geometryFileName)
        {
            if (Cached(geometryFileName))
            {
                return;
            }
            var m3DModelContext = new Xbim3DModelContext(model);
            m3DModelContext.CreateContext(XbimGeometryType.PolyhedronBinary);

            ExportGeometryData(geometryFileName, m3DModelContext);
        }
        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 = ReadFileLength(xbimSceneName),
                            IfcProductEntries = model.Instances.CountOf<IfcProduct>(),
                            IfcSolidGeometries = model.Instances.CountOf<IfcSolidModel>(),
                            IfcMappedGeometries = model.Instances.CountOf<IfcMappedItem>(),
                            BooleanGeometries = model.Instances.CountOf<IfcBooleanResult>(),
                            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);
                    }

                    lock (thisLock)
                    {
                        writer.WriteLine(result.ToCsv());
                        writer.Flush();
                    }
                }
                return result;
            }
        }
        private void Modify_Click(object sender, RoutedEventArgs e)
        {
            XbimModel model = DataContext as XbimModel;
            foreach (var item in FederatedList.SelectedItems)
            {
                if (item is XbimReferencedModel)
                {
                    var rItem = item as XbimReferencedModel;
                    AddFederatedModel fdlg = new AddFederatedModel(rItem);

                    bool? done = fdlg.ShowDialog();
                    if (done.HasValue && done.Value == true)
                    {
                        string fileName = fdlg.FileName;
                        string ext = System.IO.Path.GetExtension(fileName);
                        using (XbimModel refM = new XbimModel())
                        {
                            if (string.Compare(ext, ".xbim", true) != 0)
                            {
                                refM.CreateFrom(fileName, null, null, true);
                                var m3D = new Xbim3DModelContext(refM);
                                m3D.CreateContext();
                                fileName = System.IO.Path.ChangeExtension(fileName, "xbim");
                            }
                        }
                        using (var txn = model.BeginTransaction())
                        {
                            rItem.DocumentInformation.Name = fileName;
                            txn.Commit();
                        }
                    }
                }
            }
        }
Exemple #48
0
        /// <summary>
        /// Converts an Ifc File to xBIM if it does not already exists, then converts the geoemtry to Xbim format and profiles the results
        /// </summary>
        /// <param name="args"> file[.ifc, xbim]</param>
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("No Ifc or xBim file specified");
                return;
            }
            var fileName = args[0];
            var mainStopWatch = new Stopwatch();
            mainStopWatch.Start();
            using (var model = GetModel(fileName))
            {
                if (model != null)
                {
                    var functionStack = new ConcurrentStack<Tuple<string,double>>();
                    ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                    {
                        if (percentProgress == -1)
                        {
                            functionStack.Push(new Tuple<string,double>(userState.ToString(), DateTime.Now.TimeOfDay.TotalMilliseconds));
                            Logger.InfoFormat("Entering - {0}", userState.ToString());
                        }

                        else if (percentProgress == 101)
                        {
                            Tuple<string,double> func;
                            if(functionStack.TryPop(out func))
                                Logger.InfoFormat("Complete in \t\t{0:0.0} ms", DateTime.Now.TimeOfDay.TotalMilliseconds - func.Item2);
                        }
                    };
                    var context = new Xbim3DModelContext(model);
                    context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: progDelegate);

                    mainStopWatch.Stop();
                    Logger.InfoFormat("Xbim total Compile Time \t\t{0:0.0} ms", mainStopWatch.ElapsedMilliseconds);
                    var wexBimFilename = Path.ChangeExtension(fileName, "wexBIM");
                    using (var wexBiMfile = new FileStream(wexBimFilename, FileMode.Create, FileAccess.Write))
                    {
                        using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                        {
                            var stopWatch = new Stopwatch();
                            Logger.InfoFormat("Entering -  Create wexBIM");
                            stopWatch.Start();
                            context.Write(wexBimBinaryWriter);
                            stopWatch.Stop();
                            Logger.InfoFormat("Complete - in \t\t{0:0.0} ms", stopWatch.ElapsedMilliseconds);
                            wexBimBinaryWriter.Close();
                        }
                        wexBiMfile.Close();
                    }

                    model.Close();
                }
            }
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }