Exemplo n.º 1
0
        public void NoOwnerHistoryForInsertCopy()
        {
            using (var source = IfcStore.Create(XbimSchemaVersion.Ifc4, XbimStoreType.InMemoryModel))
            {
                using (var txn = source.BeginTransaction())
                {
                    var create = new Create(source);
                    source.ManageOwnerHistory = false;
                    create.Wall(w => w.Name   = "New wall #1");
                    create.Wall(w => w.Name   = "New wall #2");
                    create.Wall(w => w.Name   = "New wall #3");
                    source.ManageOwnerHistory = true;
                    txn.Commit();
                }

                using (var target = IfcStore.Create(source.SchemaVersion, XbimStoreType.InMemoryModel))
                {
                    using (var txn = target.BeginTransaction())
                    {
                        var map = new XbimInstanceHandleMap(source, target);
                        target.InsertCopy(source.Instances.OfType <IIfcProduct>(), true, true, map);
                        txn.Commit();
                    }

                    Assert.AreEqual(source.Instances.Count, target.Instances.Count);
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// This is a higher level function which uses InsertCopy function alongside with the knowledge of IFC schema to copy over
        /// products with their types and other related information (classification, aggregation, documents, properties) and optionally
        /// geometry. It will also bring in spatial hierarchy relevant to selected products. However, resulting model is not guaranteed
        /// to be compliant with any Model View Definition unless you explicitly check the compliance. Context of a single product tend to
        /// consist from hundreds of objects which need to be identified and copied over so this operation might be potentially expensive.
        /// You should never call this function more than once between two models. It not only selects objects to be copied over but also
        /// excludes other objects from being copied over so that it doesn't bring the entire model in a chain dependencies. This means
        /// that some objects are modified (like spatial relations) and won't get updated which would lead to an inconsistent copy.
        /// </summary>
        /// <param name="model">The target model</param>
        /// <param name="products">Products from other model to be inserted into this model</param>
        /// <param name="includeGeometry">If TRUE, geometry of the products will be copied over.</param>
        /// <param name="keepLabels">If TRUE, entity labels from original model will be used. Always set this to FALSE
        /// if you are going to insert products from multiple source models or if you are going to insert products to a non-empty model</param>
        /// <param name="mappings">Mappings to avoid multiple insertion of objects. Keep a single instance for insertion between two models.
        /// If you also use InsertCopy() function for some other insertions, use the same instance of mappings.</param>
        public static void InsertCopy(this IModel model, IEnumerable <IIfcProduct> products, bool includeGeometry, bool keepLabels,
                                      XbimInstanceHandleMap mappings)
        {
            var context = new CopyContext
            {
                IncludeGeometry = includeGeometry
            };

            var roots = products.Cast <IPersistEntity>().ToList();

            //return if there is nothing to insert
            if (!roots.Any())
            {
                return;
            }

            var source = roots.First().Model;

            if (source == model)
            {
                //don't do anything if the source and target are the same
                return;
            }

            var toInsert = GetEntitiesToInsert(context, source, roots);
            //create new cache is none is defined
            var cache = mappings ?? new XbimInstanceHandleMap(source, model);

            foreach (var entity in toInsert)
            {
                model.InsertCopy(entity, cache,
                                 (property, obj) => Filter(context, property, obj),
                                 true, keepLabels);
            }
        }
Exemplo n.º 3
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
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Inserts deep copy of an object into this model. The entity must originate from the same schema (the same EntityFactory).
        /// This operation happens within a transaction which you have to handle yourself unless you set the parameter "noTransaction" to true.
        /// Insert will happen outside of transactional behaviour in that case. Resulting model is not guaranteed to be valid according to any
        /// model view definition. However, it is granted to be consistent. You can optionally bring in all inverse relationships. Be careful as it
        /// might easily bring in almost full model.
        ///
        /// </summary>
        /// <typeparam name="T">Type of the copied entity</typeparam>
        /// <param name="toCopy">Entity to be copied</param>
        /// <param name="mappings">Mappings of previous inserts</param>
        /// <param name="includeInverses">Option if to bring in all inverse entities (enumerations in original entity)</param>
        /// <param name="keepLabels">Option if to keep entity labels the same</param>
        /// <param name="propTransform">Optional delegate which you can use to filter the content which will get copied over.</param>
        /// <param name="noTransaction">If TRUE all operations inside this function will happen out of transaction.
        /// Also no notifications will be fired from objects.</param>
        /// <returns>Copy from this model</returns>
        public T InsertCopy <T>(T toCopy, XbimInstanceHandleMap mappings, PropertyTranformDelegate propTransform, bool includeInverses,
                                bool keepLabels, bool noTransaction) where T : IPersistEntity
        {
            if (noTransaction)
            {
                IsTransactional = false;
            }
            T result;

            try
            {
                result = ModelHelper.InsertCopy(this, toCopy, mappings, propTransform, includeInverses, keepLabels,
                                                (type, i) => _instances.New(type, i));
            }
            catch
            {
                throw;
            }
            finally
            {
                //make sure model is transactional at the end again
                IsTransactional = true;
            }
            return(result);
        }
Exemplo n.º 5
0
        public void ExtractSemanticModel()
        {
            const string original = "SampleHouse4.ifc";

            using (var model = new IO.Memory.MemoryModel(new Ifc4.EntityFactory()))
            {
                model.LoadStep21(original);
                var roots = model.Instances.OfType <Ifc4.Kernel.IfcRoot>();
                using (var iModel = new IO.Memory.MemoryModel(new Ifc4.EntityFactory()))
                {
                    using (var txn = iModel.BeginTransaction("Insert copy"))
                    {
                        var mappings = new XbimInstanceHandleMap(model, iModel);
                        foreach (var root in roots)
                        {
                            iModel.InsertCopy(root, mappings, Filter, false, true);
                        }
                        txn.Commit();
                        using (var fileStream = new StreamWriter("..\\..\\SampleHouseSemantic4.ifc"))
                        {
                            iModel.SaveAsStep21(fileStream);
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        public void CreatingPartialFileWithStore()
        {
            using (var source = IfcStore.Open("SampleHouse4.ifc"))
            {
                var products = source.Instances.OfType <IfcBuildingElement>();

                using (var target = IfcStore.Create(source.SchemaVersion, XbimStoreType.InMemoryModel))
                    using (var txn = target.BeginTransaction("Insert Copy"))
                    {
                        var map = new XbimInstanceHandleMap(source, target);
                        target.InsertCopy(products, true, false, map);

                        txn.Commit();

                        var expected = products.Count();
                        var actual   = target.Instances.OfType <IfcBuildingElement>().Count();

                        Assert.AreEqual(expected, actual);

                        var owners = target.Instances.OfType <IIfcOwnerHistory>();

                        Assert.IsTrue(owners.Count() > 0);
                    }
            }
        }
Exemplo n.º 7
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
            }
        }
Exemplo n.º 8
0
        public void CopyWallsOver()
        {
            const string original = "SampleHouse.ifc";
            const string inserted = "SampleHouseWalls.ifc";

            object semanticFilter(Xbim.Common.Metadata.ExpressMetaProperty property, object parentObject)
            {
                //leave out geometry and placement
                if (parentObject is IIfcProduct &&
                    (property.PropertyInfo.Name == "Representation" || // nameof() removed to allow for VS2013 compatibility
                     property.PropertyInfo.Name == "ObjectPlacement")) // nameof() removed to allow for VS2013 compatibility
                {
                    return(null);
                }

                //leave out mapped geometry
                if (parentObject is IIfcTypeProduct &&
                    property.PropertyInfo.Name == "RepresentationMaps") // nameof() removed to allow for VS2013 compatibility
                {
                    return(null);
                }


                //only bring over IsDefinedBy and IsTypedBy inverse relationships which will take over all properties and types
                if (property.EntityAttribute.Order < 0 && !(
                        property.PropertyInfo.Name == "IsDefinedBy" || // nameof() removed to allow for VS2013 compatibility
                        property.PropertyInfo.Name == "IsTypedBy"      // nameof() removed to allow for VS2013 compatibility
                        ))
                {
                    return(null);
                }

                return(property.PropertyInfo.GetValue(parentObject, null));
            }

            IfcStore.ModelProviderFactory.UseMemoryModelProvider();
            using (var model = IfcStore.Open(original))
            {
                var walls = model.Instances.OfType <IIfcWall>();
                using (var iModel = IfcStore.Create(((IModel)model).SchemaVersion, XbimStoreType.InMemoryModel))
                {
                    using (var txn = iModel.BeginTransaction("Insert copy"))
                    {
                        //single map should be used for all insertions between two models
                        var map = new XbimInstanceHandleMap(model, iModel);

                        foreach (var wall in walls)
                        {
                            iModel.InsertCopy(wall, map, semanticFilter, true, false);
                        }

                        txn.Commit();
                    }

                    iModel.SaveAs(inserted);
                }
            }
        }
Exemplo n.º 9
0
        public void CopyWallsOver()
        {
            const string original = "SampleHouse.ifc";
            const string inserted = "SampleHouseWalls.ifc";

            PropertyTranformDelegate semanticFilter = (property, parentObject) =>
            {
                //leave out geometry and placement
                if (parentObject is IIfcProduct &&
                    (property.PropertyInfo.Name == nameof(IIfcProduct.Representation) ||
                     property.PropertyInfo.Name == nameof(IIfcProduct.ObjectPlacement)))
                {
                    return(null);
                }

                //leave out mapped geometry
                if (parentObject is IIfcTypeProduct &&
                    property.PropertyInfo.Name == nameof(IIfcTypeProduct.RepresentationMaps))
                {
                    return(null);
                }


                //only bring over IsDefinedBy and IsTypedBy inverse relationships which will take over all properties and types
                if (property.EntityAttribute.Order < 0 && !(
                        property.PropertyInfo.Name == nameof(IIfcProduct.IsDefinedBy) ||
                        property.PropertyInfo.Name == nameof(IIfcProduct.IsTypedBy)
                        ))
                {
                    return(null);
                }

                return(property.PropertyInfo.GetValue(parentObject, null));
            };

            using (var model = IfcStore.Open(original))
            {
                var walls = model.Instances.OfType <IIfcWall>();
                using (var iModel = IfcStore.Create(model.IfcSchemaVersion, XbimStoreType.InMemoryModel))
                {
                    using (var txn = iModel.BeginTransaction("Insert copy"))
                    {
                        //single map should be used for all insertions between two models
                        var map = new XbimInstanceHandleMap(model, iModel);

                        foreach (var wall in walls)
                        {
                            iModel.InsertCopy(wall, map, semanticFilter, true, false);
                        }

                        txn.Commit();
                    }

                    iModel.SaveAs(inserted);
                }
            }
        }
Exemplo n.º 10
0
        protected XbimInstanceHandleMap HandleMapOf(IPersistEntity p)
        {
            XbimInstanceHandleMap map;

            if (!HandleMaps.TryGetValue(p.Model, out map))
            {
                map = new XbimInstanceHandleMap(p.Model, Builder.Store);
                HandleMaps.Add(p.Model, map);
            }
            return(map);
        }
Exemplo n.º 11
0
        public void ExtractIfcGeometryEntitiesTest()
        {
            using (var source = new XbimModel())
            {
                PropertyTranformDelegate propTransform = delegate(IfcMetaProperty prop, object toCopy)
                {
                    if (typeof(IfcProduct).IsAssignableFrom(toCopy.GetType()))
                    {
                        if (prop.PropertyInfo.Name == "ObjectPlacement" || prop.PropertyInfo.Name == "Representation")
                        {
                            return(null);
                        }
                    }
                    if (typeof(IfcTypeProduct).IsAssignableFrom(toCopy.GetType()))
                    {
                        if (prop.PropertyInfo.Name == "RepresentationMaps")
                        {
                            return(null);
                        }
                    }
                    return(prop.PropertyInfo.GetValue(toCopy, null));//just pass through the value
                };

                //source.Open("BIM Logo-LetterM.xBIM");
                //source.SaveAs("WithGeometry.ifc");
                string modelName     = @"4walls1floorSite";
                string xbimModelName = Path.ChangeExtension(modelName, "xbim");

                source.CreateFrom(Path.ChangeExtension(modelName, "ifc"), null, null, true);

                using (var target = XbimModel.CreateModel(Path.ChangeExtension(modelName + "_NoGeom", "xbim")))
                {
                    target.AutoAddOwnerHistory = false;
                    using (var txn = target.BeginTransaction())
                    {
                        var copied = new XbimInstanceHandleMap(source, target);

                        foreach (var item in source.Instances.OfType <IfcRoot>())
                        {
                            target.InsertCopy(item, copied, txn, propTransform, false);
                        }
                        txn.Commit();
                    }

                    target.SaveAs(Path.ChangeExtension(modelName + "_NoGeom", "ifc"));
                    target.Close();
                }

                source.Close();
                // XbimModel.Compact(Path.ChangeExtension(modelName + "_NoGeom", "xbim"), Path.ChangeExtension(modelName + "_NoGeom_Compacted", "xbim"));
                //the two files should be the same
            }
        }
Exemplo n.º 12
0
        private void BtnRun_OnClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtInputFile.Text) ||
                string.IsNullOrWhiteSpace(TxtOutputFile.Text))
            {
                MessageBox.Show("You have to specify input and output file.");
                return;
            }

            Cursor = Cursors.Wait;
            var  w = Stopwatch.StartNew();
            long originalCount;
            long resultCount;

            using (var source = IfcStore.Open(TxtInputFile.Text))
            {
                using (var target = IfcStore.Create(source.IfcSchemaVersion, XbimStoreType.InMemoryModel))
                {
                    //insertion itself will be configured to happen out of transaction but other operations might need to be transactional
                    using (var txn = target.BeginTransaction("COBie data extraction"))
                    {
                        var toInsert = GetProductsToInsert(source);
                        var cache    = new XbimInstanceHandleMap(source, target);
                        target.InsertCopy(toInsert, CheckBoxIncludeGeometry.IsChecked ?? false, true, cache);
                        txn.Commit();
                    }

                    target.SaveAs(TxtOutputFile.Text);
                    originalCount = source.Instances.Count;
                    resultCount   = target.Instances.Count;
                }
            }
            Cursor = Cursors.Arrow;
            w.Stop();

            var originalSize   = new FileInfo(TxtInputFile.Text).Length;
            var cobieSize      = new FileInfo(TxtOutputFile.Text).Length;
            var processingTime = w.ElapsedMilliseconds;
            var msg            = string.Format("COBie content extracted in {0}s \n" +
                                               "Original size: {1:n0}B \n" +
                                               "Resulting size: {2:n0}B \n" +
                                               "Number of objects in original: {3:n0} \n" +
                                               "Number of objects in result: {4:n0}",
                                               processingTime / 1000,
                                               originalSize,
                                               cobieSize,
                                               originalCount,
                                               resultCount);

            MessageBox.Show(this, msg);
            Close();
        }
Exemplo n.º 13
0
        public void ExtractIfcGeometryEntitiesTest()
        {
            using (var source = new XbimModel())
            {
                PropertyTranformDelegate propTransform = delegate(IfcMetaProperty prop, object toCopy)
                {

                    if (typeof(IfcProduct).IsAssignableFrom(toCopy.GetType()))
                    {
                        if (prop.PropertyInfo.Name == "ObjectPlacement" || prop.PropertyInfo.Name == "Representation")
                            return null;
                    }   
                    if(typeof(IfcTypeProduct).IsAssignableFrom(toCopy.GetType()))
                    {
                        if (prop.PropertyInfo.Name == "RepresentationMaps" )
                            return null;
                    }
                    return prop.PropertyInfo.GetValue(toCopy, null);//just pass through the value               
                };

                //source.Open("BIM Logo-LetterM.xBIM");
                //source.SaveAs("WithGeometry.ifc");
                string modelName = @"4walls1floorSite";
                string xbimModelName = Path.ChangeExtension(modelName,"xbim");
                
                source.CreateFrom( Path.ChangeExtension(modelName,"ifc"), null, null, true);
               
                using (var target = XbimModel.CreateModel(Path.ChangeExtension(modelName + "_NoGeom", "xbim")))
                {
                    target.AutoAddOwnerHistory = false;
                    using (var txn = target.BeginTransaction())
                    {
                        var copied = new XbimInstanceHandleMap(source, target);

                        foreach (var item in source.Instances.OfType<IfcRoot>())
                        {
                            target.InsertCopy(item, copied, txn, propTransform, false);
                        }
                        txn.Commit();
                    }
                    
                    target.SaveAs(Path.ChangeExtension(modelName + "_NoGeom", "ifc"));
                    target.Close();
                    
                }
                
                source.Close();
               // XbimModel.Compact(Path.ChangeExtension(modelName + "_NoGeom", "xbim"), Path.ChangeExtension(modelName + "_NoGeom_Compacted", "xbim"));
                //the two files should be the same
            }
        }
Exemplo n.º 14
0
        public void MergeProductsTest()
        {
            const string model1File = "TestSourceFiles\\4walls1floorSite.ifc";
            const string copyFile   = "copy.ifc";
            const string model2File = "TestSourceFiles\\House.ifc";
            var          newModel   = new MemoryModel(new Ifc2x3.EntityFactoryIfc2x3());

            using (var model1 = MemoryModel.OpenRead(model1File))
            {
                PropertyTranformDelegate propTransform = delegate(ExpressMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return(value);
                };

                using (var model2 = MemoryModel.OpenRead(model2File))
                {
                    var rencontre = false;
                    using (var txn = newModel.BeginTransaction("test"))
                    {
                        var copied = new XbimInstanceHandleMap(model1, newModel);
                        foreach (var item in model1.Instances.OfType <IfcProduct>())
                        {
                            newModel.InsertCopy(item, copied, propTransform, false, false);
                        }
                        copied = new XbimInstanceHandleMap(model2, newModel);
                        foreach (var item in model2.Instances.OfType <IfcProduct>())
                        {
                            var buildingElement = item as IfcBuildingElement;
                            if (model1.Instances.OfType <IfcBuildingElement>()
                                .Any(item1 => buildingElement != null && buildingElement.GlobalId == item1.GlobalId))
                            {
                                rencontre = true;
                            }
                            if (!rencontre)
                            {
                                newModel.InsertCopy(item, copied, propTransform, false, false);
                            }
                        }

                        txn.Commit();
                    }
                    using (var file = File.Create(copyFile))
                    {
                        newModel.SaveAsStep21(file);
                        file.Close();
                    }
                }
            }
        }
Exemplo n.º 15
0
        private static IfcStore GetSubModel(IfcStore model, params int[] ids)
        {
            var result = IfcStore.Create(model.SchemaVersion, XbimStoreType.InMemoryModel);

            using (var txn = result.BeginTransaction())
            {
                var map      = new XbimInstanceHandleMap(model, result);
                var toInsert = ids.Select(id => model.Instances[id]).OfType <IIfcProduct>();
                result.InsertCopy(toInsert, true, true, map);
                txn.Commit();
            }

            return(result);
        }
Exemplo n.º 16
0
        public static void Run()
        {
            using (var source = new MemoryModel(new Xbim.Ifc4.EntityFactoryIfc4()))
            {
                var     i = source.Instances;
                IfcUnit unit;
                using (var txn = source.BeginTransaction("Creation"))
                {
                    unit = i.New <IfcDerivedUnit>(u =>
                    {
                        u.UnitType = Xbim.Ifc4.Interfaces.IfcDerivedUnitEnum.LINEARVELOCITYUNIT;
                        u.Elements.AddRange(new[] {
                            i.New <IfcDerivedUnitElement>(e => {
                                e.Exponent = 1;
                                e.Unit     = i.New <IfcSIUnit>(m => {
                                    m.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.LENGTHUNIT;
                                    m.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.METRE;
                                    m.Prefix   = null;
                                });
                            }),
                            i.New <IfcDerivedUnitElement>(e => {
                                e.Exponent = -2;
                                e.Unit     = i.New <IfcSIUnit>(s => {
                                    s.UnitType = Xbim.Ifc4.Interfaces.IfcUnitEnum.TIMEUNIT;
                                    s.Name     = Xbim.Ifc4.Interfaces.IfcSIUnitName.SECOND;
                                    s.Prefix   = null;
                                });
                            })
                        });
                    });
                    txn.Commit();
                }

                using (var target = new MemoryModel(new Xbim.Ifc4.EntityFactoryIfc4()))
                {
                    // if you do more inserts, this makes sure that entities once copied over will be reused
                    var map = new XbimInstanceHandleMap(source, target);
                    using (var txn = target.BeginTransaction("Inserting unit"))
                    {
                        // inserts unit and all direct attributes, no inverse attributes, doesn't do any special transformations
                        // and creates new local IDs (entity labels (#4564)) for inserted entities (this makes sure that it doesn't clash with the
                        // data already existing in the model)
                        target.InsertCopy(unit, map, null, false, false);
                        txn.Commit();
                    }
                }
            }
        }
Exemplo n.º 17
0
        public void MergeProductsTest()
        {
            const string model1File = "4walls1floorSite.ifc";
            const string copyFile   = "copy.ifc";
            const string model2File = "House.ifc";
            var          newModel   = IfcStore.Create(IfcSchemaVersion.Ifc2X3, XbimStoreType.InMemoryModel);

            using (var model1 = IfcStore.Open(model1File))
            {
                PropertyTranformDelegate propTransform = delegate(ExpressMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return(value);
                };


                using (var model2 = IfcStore.Open(model2File))
                {
                    var rencontre = false;
                    using (var txn = newModel.BeginTransaction())
                    {
                        var copied = new XbimInstanceHandleMap(model1, newModel);
                        foreach (var item in model1.Instances.OfType <IfcProduct>())
                        {
                            newModel.InsertCopy(item, copied, propTransform, false, false);
                        }
                        copied = new XbimInstanceHandleMap(model2, newModel);
                        foreach (var item in model2.Instances.OfType <IfcProduct>())
                        {
                            var buildingElement = item as IfcBuildingElement;
                            if (model1.Instances.OfType <IfcBuildingElement>()
                                .Any(item1 => buildingElement != null && buildingElement.GlobalId == item1.GlobalId))
                            {
                                rencontre = true;
                            }
                            if (!rencontre)
                            {
                                newModel.InsertCopy(item, copied, propTransform, false, false);
                            }
                        }

                        txn.Commit();
                    }
                    newModel.SaveAs(copyFile);
                }
                newModel.Close();
            }
        }
Exemplo n.º 18
0
        public void IfcStoreInsertCopyCloneTests()
        {
            using (var store = IfcStore.Open(@"Resources\Ifc4-Storey-With-4Walls.ifc"))
            {
                var testStore = IfcStore.Create(store.SchemaVersion, Xbim.IO.XbimStoreType.InMemoryModel);
                var map       = new XbimInstanceHandleMap(store, testStore);

                using (var tx = testStore.BeginTransaction("Test"))
                {
                    foreach (var e in store.Instances)
                    {
                        Assert.IsNotNull(testStore.InsertCopy(e, map, (m, p) => m.PropertyInfo.GetValue(p), true, true));
                    }
                    tx.Commit();
                }
                Assert.IsTrue(store.Instances.All(i => map.Keys.Count(k => k.EntityLabel == i.EntityLabel) == 1));
            }
        }
Exemplo n.º 19
0
        private static void Expand <IParentEntity, IUniqueEntity>(IModel model, Func <IParentEntity, ICollection <IUniqueEntity> > accessor) where IParentEntity : IPersistEntity where IUniqueEntity : IPersistEntity
        {
            //get duplicates in one go to avoid exponential search
            var candidates = new Dictionary <IUniqueEntity, List <IParentEntity> >();

            foreach (var entity in model.Instances.OfType <IParentEntity>())
            {
                foreach (var val in accessor(entity))
                {
                    List <IParentEntity> assets;
                    if (!candidates.TryGetValue(val, out assets))
                    {
                        assets = new List <IParentEntity>();
                        candidates.Add(val, assets);
                    }
                    assets.Add(entity);
                }
            }

            var multi = candidates.Where(a => a.Value.Count > 1);
            var map   = new XbimInstanceHandleMap(model, model);

            foreach (var kvp in multi)
            {
                var value    = kvp.Key;
                var entities = kvp.Value;

                //skip the first
                for (int i = 1; i < entities.Count; i++)
                {
                    //clear map to create complete copy every time
                    map.Clear();
                    var copy = model.InsertCopy(value, map, null, false, false);

                    //remove original and add fresh copy
                    var entity     = entities[i];
                    var collection = accessor(entity);
                    collection.Remove(value);
                    collection.Add(copy);
                }
            }
        }
Exemplo n.º 20
0
        public void CopyAllEntitiesTest()
        {
            const string sourceFile = "TestSourceFiles\\4walls1floorSite.ifc";
            var          copyFile   = "copy.ifc";

            using (var source = MemoryModel.OpenRead(sourceFile))
            {
                PropertyTranformDelegate propTransform = delegate(ExpressMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return(value);
                };
                using (var target = new MemoryModel(new Ifc2x3.EntityFactoryIfc2x3()))
                {
                    using (var txn = target.BeginTransaction("Inserting copies"))
                    {
                        target.Header.FileDescription = source.Header.FileDescription;
                        target.Header.FileName        = source.Header.FileName;
                        target.Header.FileSchema      = source.Header.FileSchema;

                        var map = new XbimInstanceHandleMap(source, target);

                        foreach (var item in source.Instances)
                        {
                            target.InsertCopy(item, map, propTransform, true, true);
                        }
                        txn.Commit();
                    }
                    using (var outFile = File.Create(copyFile))
                    {
                        target.SaveAsStep21(outFile);
                        outFile.Close();
                    }
                }

                //the two files should be the same
                FileCompare(sourceFile, copyFile);
            }
        }
Exemplo n.º 21
0
        public void CopyAllEntitiesTest()
        {
            var sourceFile = "source.ifc";
            var copyFile   = "copy.ifc";

            using (var source = new Ifc2x3.IO.XbimModel())
            {
                PropertyTranformDelegate propTransform = delegate(ExpressMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return(value);
                };
                //source.CreateFrom(@"C:\Users\Steve\Downloads\Test Models\crash\NBS_LakesideRestaurant_EcoBuild2015_Revit2014_.ifc","source.xbim",null,true);

                //source.CreateFrom(@"C:\Users\Steve\Downloads\Test Models\Wall with complex openings.ifc", "source.xbim",null,true);
                source.Open("BIM Logo-LetterM.xBIM");
                source.SaveAs(sourceFile);
                using (var target = Ifc2x3.IO.XbimModel.CreateTemporaryModel())
                {
                    target.AutoAddOwnerHistory = false;
                    using (var txn = target.BeginTransaction())
                    {
                        target.Header = source.Header;
                        var copied = new XbimInstanceHandleMap(source, target);

                        foreach (var item in source.Instances)
                        {
                            target.InsertCopy(item, copied, txn, propTransform, true);
                        }
                        txn.Commit();
                    }
                    target.SaveAs(copyFile);
                }
                source.Close();
                //the two files should be the same
                FileCompare(sourceFile, copyFile);
            }
        }
Exemplo n.º 22
0
        public void SplitIntoStories(IfcStore store)
        {
            var stories = store.Instances.OfType <IIfcBuildingStorey>().ToList();

            for (int i = 0; i < stories.Count(); i++)
            {
                var story    = stories[i];
                var rels     = store.Instances.OfType <IIfcRelContainedInSpatialStructure>().Where(x => x.RelatingStructure.EntityLabel == story.EntityLabel);
                var elements = rels.SelectMany(r => r.RelatedElements).Distinct();

                using (var model = IfcStore.Create(credentials, store.IfcSchemaVersion, XbimStoreType.InMemoryModel))
                {
                    using (var txn = model.BeginTransaction("Data creation"))
                    {
                        var map = new XbimInstanceHandleMap(store, model);
                        model.InsertCopy(elements, true, true, map);

                        txn.Commit();
                    }

                    model.SaveAs($"{i}_{story.Name.ToString()}.ifc", Xbim.IO.IfcStorageType.Ifc);
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Implementation of IModel variant of InsertCopy() function
        /// </summary>
        /// <typeparam name="T">Type of the object to be inserted. This must be a type supported by this model</typeparam>
        /// <param name="toCopy">Object to copy</param>
        /// <param name="mappings">Mappings make sure object is only inserted once. You should use one instance of mappings for all InsertCopy() calls between two models</param>
        /// <param name="propTransform">Delegate which can be used to transform properties. You can use this to filter out certain properties or referenced objects</param>
        /// <param name="includeInverses">If TRUE interse relations are also copied over. This may potentially bring over almost entire model if not controlled by propTransform delegate</param>
        /// <param name="keepLabels">If TRUE entity labels of inserted objects will be the same as the labels of original objects. This should be FALSE if you are inserting objects to existing model
        /// or if you are inserting objects from multiple source models into a single target model where entity labels may potentially clash.</param>
        /// <returns>New created object in this model which is a deep copy of original object</returns>
        public T InsertCopy <T>(T toCopy, XbimInstanceHandleMap mappings, PropertyTranformDelegate propTransform, bool includeInverses, bool keepLabels) where T : IPersistEntity
        {
            var txn = CurrentTransaction as XbimReadWriteTransaction;

            return(Cache.InsertCopy(toCopy, mappings, txn, includeInverses, propTransform, keepLabels));
        }
Exemplo n.º 24
0
 public T InsertCopy <T>(T toCopy, XbimInstanceHandleMap mappings, PropertyTranformDelegate propTransform, bool includeInverses,
                         bool keepLabels) where T : IPersistEntity
 {
     return(_model.InsertCopy(toCopy, mappings, propTransform, includeInverses, keepLabels));
 }
Exemplo n.º 25
0
 public void InsertCopy(IEnumerable <CobieComponent> components, bool keepLabels, XbimInstanceHandleMap mappings)
 {
     foreach (var component in components)
     {
         InsertCopy(component, mappings, InsertCopyComponentFilter, true, keepLabels);
     }
 }
Exemplo n.º 26
0
        public ActionResult SubmitBlahBlah(List <int> axesIds, SubmissionStages subItem)
        {
            List <string>      files = Directory.GetFiles(FileStruc.CurrentVersion).ToList();
            List <IIfcProduct> Axes;

            List <IIfcProduct> lstProductSubmission;
            List <Line>        lstAxesLines = new List <Line>();
            string             ifcFile      = files.Where(a => Path.GetExtension(a) == ".ifc").FirstOrDefault();

            using (var model = IfcStore.Open(ifcFile))
            {
                Axes = model.Instances.OfType <IIfcProduct>().Where(b => axesIds.Contains(b.EntityLabel)).ToList();
                List <IIfcProduct> lstProduct = model.Instances.OfType <IIfcProduct>().Where(p => lstProductId.Contains(p.EntityLabel)).ToList();

                List <Line> lstLines = IFCHelper.AxesLinesGet(Axes);


                //Axes Boundaries
                LinearPath linPathSubmittal = MathHelper.LinPathAxesIntersection(lstLines);

                Dictionary <int, LinearPath> dicElement = IFCHelper.DicLinPathOfProductsGet(lstProduct);

                //get products within the axes boundary
                Dictionary <int, LinearPath> elementsWithinAxesBoundary = CadHelper.SubmittedElementsGet(linPathSubmittal, dicElement);

                //reinforcement IFC file
                using (IfcStore subModelRFT = IFCHelper.CreateandInitModel("Reinforcement File", model.Instances.OfType <IfcProject>().FirstOrDefault().UnitsInContext))
                {
                    IfcBuilding bldng = IFCHelper.CreateBuilding(subModelRFT, "bldngRFT", new Point3D(0, 0, 0));
                    using (var txn = subModelRFT.BeginTransaction("I"))
                    {
                        IfcBuildingStorey storey = subModelRFT.Instances.New <IfcBuildingStorey>();
                        bldng.AddToSpatialDecomposition(storey);
                        switch (subItem)
                        {
                        case SubmissionStages.FormWork:
                            for (int i = 0; i < elementsWithinAxesBoundary.Values.ToList().Count; i++)
                            {
                                IIfcProduct            product = lstProduct.FirstOrDefault(p => p.EntityLabel == elementsWithinAxesBoundary.Keys.ToList()[i]);
                                IIfcRepresentationItem repItem = product.Representation.Representations.First.Items.First;
                                double height = (repItem as IIfcExtrudedAreaSolid).Depth;

                                IfcOpeningElement open;
                                XbimCreateBuilding.CreateFormWork(subModelRFT, elementsWithinAxesBoundary.Values.ToList()[i], DefaultValues.FormWorkThickness,
                                                                  height, out open, "", false, false, false);
                            }
                            //switch (elemTypeFormwork)
                            //{
                            //    case ElementType.PCF:
                            //        break;
                            //    case ElementType.RCF:
                            //        break;
                            //    case ElementType.SEM:
                            //        break;
                            //    case ElementType.SHW:
                            //        break;
                            //    case ElementType.RTW:
                            //        break;
                            //    case ElementType.COL:
                            //        for (int i = 0; i < elementsWithinAxesBoundary.Values.ToList().Count; i++)
                            //        {
                            //            Column col = new Column(elementsWithinAxesBoundary.Values.ToList()[i]);
                            //            ReinforcedCadColumn rftCol = new ReinforcedCadColumn(col, 0);

                            //            IIfcProduct product = lstProduct.FirstOrDefault(p => p.EntityLabel == elementsWithinAxesBoundary.Keys.ToList()[i]);
                            //            IIfcRepresentationItem repItem = product.Representation.Representations.First.Items.First;
                            //            double height = (repItem as IIfcExtrudedAreaSolid).Depth;

                            //            IfcOpeningElement open;
                            //            XbimCreateBuilding.CreateFormWork(subModelRFT, rftCol.CadColumn.ColPath, DefaultValues.FormWorkThickness,
                            //                height, out open, false, false, false);

                            //        }
                            //        break;
                            //    case ElementType.SLB:
                            //        break;
                            //    default:
                            //        break;
                            //}

                            break;

                        case SubmissionStages.Concrete:
                            lstProductSubmission = lstProduct.Where(p => elementsWithinAxesBoundary.ContainsKey(p.EntityLabel)).ToList();
                            var map = new XbimInstanceHandleMap(model, subModelRFT);
                            for (int i = 0; i < lstProductSubmission.Count; i++)
                            {
                                IIfcProduct product = subModelRFT.InsertCopy(lstProductSubmission[i], map, null, false, false);
                                storey.AddElement(product as IfcProduct);
                            }
                            break;

                        case SubmissionStages.Reinforcement:
                            Enum.TryParse(ElementTypeSubmitted, out ElementType elemType);

                            switch (elemType)
                            {
                            case ElementType.PCF:
                                break;

                            case ElementType.RCF:
                                break;

                            case ElementType.SEM:
                                break;

                            case ElementType.SHW:
                                break;

                            case ElementType.RTW:
                                break;

                            case ElementType.COL:
                                for (int i = 0; i < elementsWithinAxesBoundary.Values.ToList().Count; i++)
                                {
                                    Column col = new Column(elementsWithinAxesBoundary.Values.ToList()[i]);
                                    ReinforcedCadColumn rftCol = new ReinforcedCadColumn(col, 0);

                                    IIfcProduct            product = lstProduct.FirstOrDefault(p => p.EntityLabel == elementsWithinAxesBoundary.Keys.ToList()[i]);
                                    IIfcRepresentationItem repItem = product.Representation.Representations.First.Items.First;
                                    double height = (repItem as IIfcExtrudedAreaSolid).Depth;

                                    XbimCreateBuilding.CreateColumnRft(rftCol, storey, subModelRFT, height, "");
                                }
                                break;

                            case ElementType.SLB:
                                break;

                            default:
                                break;
                            }
                            break;

                        default:
                            break;
                        }

                        txn.Commit();
                        subModelRFT.SaveAs(@"E:\01. Work\demo.ifc");
                        var context = new Xbim3DModelContext(subModelRFT);
                        context.CreateContext();

                        //var wexBimFilename = Path.ChangeExtension(, "wexBIM");
                        using (var wexBiMfile = System.IO.File.Create((@"E:\01. Work\demo.wexBIM")))
                        {
                            using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                            {
                                subModelRFT.SaveAsWexBim(wexBimBinaryWriter);
                                wexBimBinaryWriter.Close();
                            }
                            wexBiMfile.Close();
                        }
                    }
                }
            }

            return(new EmptyResult());
        }
        public void CompleteProductInsert()
        {
            const string original = "TestFiles\\4walls1floorSite.ifc";

            using (var model = new IO.Memory.MemoryModel(ef2x3))
            {
                var errs = model.LoadStep21(original);
                Assert.AreEqual(0, errs);
                using (model.BeginEntityCaching())
                    using (model.BeginInverseCaching())
                    {
                        var products = model.Instances.OfType <IfcProduct>();
                        using (var iModel = new IO.Memory.MemoryModel(ef2x3))
                        {
                            var map = new XbimInstanceHandleMap(model, iModel);
                            using (var txn = iModel.BeginTransaction("Insert copy"))
                            {
                                var w = new Stopwatch();
                                w.Start();
                                iModel.InsertCopy(products, true, false, map);
                                txn.Commit();
                                w.Stop();

                                var copies = Path.ChangeExtension(original, ".copy.ifc");
                                using (var f = File.Create(copies))
                                {
                                    iModel.SaveAsIfc(f);
                                    f.Close();
                                }
                            }

                            // use all caching we can for this
                            using (iModel.BeginEntityCaching())
                                using (iModel.BeginInverseCaching())
                                {
                                    // number of products should be the same
                                    var origProdCount = model.Instances.CountOf <IfcProduct>();
                                    var prodCount     = iModel.Instances.CountOf <IfcProduct>();
                                    Assert.AreEqual(origProdCount, prodCount);

                                    // number of geometry representations should be the same
                                    var origRepCount = model.Instances.CountOf <IfcProductRepresentation>();
                                    var repCount     = model.Instances.CountOf <IfcProductRepresentation>();
                                    Assert.AreEqual(origRepCount, repCount);

                                    // number of geometry representations should be the same
                                    var origRepItemCount = model.Instances.CountOf <IfcRepresentationItem>();
                                    var repItemCount     = model.Instances.CountOf <IfcRepresentationItem>();
                                    Assert.AreEqual(origRepItemCount, repItemCount);

                                    // number of representation items in every product should be the same
                                    foreach (var product in model.Instances.OfType <IfcProduct>())
                                    {
                                        var iProduct = map[new XbimInstanceHandle(product)].GetEntity() as IfcProduct;

                                        var count  = product.Representation?.Representations.SelectMany(r => r.Items).Count();
                                        var iCount = iProduct.Representation?.Representations.SelectMany(r => r.Items).Count();

                                        Assert.AreEqual(count, iCount);
                                    }
                                }
                        }
                    }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Given a list of IFC entity labels in the source model, extracts them and inserts them in the target model
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var serviceProvider = ConfigureServices();

            SetupXbimLogging(serviceProvider);
            IfcStore.ModelProviderFactory.UseHeuristicModelProvider();

            Logger.LogInformation("{0} Started", AppName);

            var arguments = Params.ParseParams(args);

            if (arguments.IsValid)
            {
                try
                {
                    ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                    {
                        Console.Write("{0:D2}%", percentProgress);
                        ResetCursor(Console.CursorTop);
                    };

                    using (var source = IfcStore.Open(arguments.SourceModelName))
                    {
                        Logger.LogInformation("Reading {0}", arguments.SourceModelName);
                        Logger.LogInformation("Extracting and copying to " + arguments.TargetModelName);
                        using (var target = IfcStore.Create(source.SchemaVersion, XbimStoreType.InMemoryModel))
                        {
                            var maps = new XbimInstanceHandleMap(source, target); //prevents the same thing being written twice
                            using (var txn = target.BeginTransaction())
                            {
                                try
                                {
                                    var toInsert =
                                        arguments.EntityLabels.Select(label => source.Instances[label]).ToList();
                                    var products = toInsert.OfType <IIfcProduct>().ToList();
                                    var others   = toInsert.Except(products).ToList();
                                    if (arguments.IncludeProject) //add in the project and geom rep
                                    {
                                        others.AddRange(source.Instances.OfType <IIfcProject>());
                                    }
                                    if (products.Any())
                                    {
                                        //this will insert products including their spatial containment,
                                        //decomposition, properties and other related information
                                        target.InsertCopy(products, arguments.IncludeGeometry, arguments.KeepLabels, maps);
                                    }
                                    if (others.Any())
                                    {
                                        //if any of the specified objects were not products, insert them straight
                                        foreach (var entity in others)
                                        {
                                            target.InsertCopy(entity, maps, null, false, arguments.KeepLabels);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogError(ex, "Some entity labels don't exist in the source file.");
                                    return;
                                }
                                txn.Commit();
                            }

                            File.Delete(arguments.TargetModelName);
                            Logger.LogInformation("Saving to {filename}", arguments.TargetModelName);
                            target.SaveAs(arguments.TargetModelName, null, progDelegate);
                            Logger.LogInformation("Success");
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.LogError(e, "Failed to extract data");
                }
            }
            else
            {
                Logger.LogError("Supplied params are invalid. ");
                Console.WriteLine("XbimExtract source destination [--IncludeProject=[true|false] | --KeepLabels=[true|false] ==IncludeGeeometry=[true|false]]");
            }

            Logger.LogInformation("{0} Ended", AppName);

#if DEBUG
            Console.WriteLine("Press any key...");
            Console.ReadKey();
#endif
        }
Exemplo n.º 29
0
        private void CopyInstance(XbimModel newmodel, XbimModel model, IPersistIfcEntity ent)
        {
            newmodel.AutoAddOwnerHistory = false;
            using (XbimReadWriteTransaction txn = newmodel.BeginTransaction("CopyInstance"))
            {
                PropertyTranformDelegate propTransform = delegate (IfcMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return value;
                };

                var copied = new XbimInstanceHandleMap(model, newmodel);

                try
                {
                    newmodel.InsertCopy(ent, copied, txn, propTransform);
                }
                catch(Exception ex)
                {
                    AddMessages(" " + ex.Message);
                    Debug.WriteLine(" " + ex.Message);
                }

                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                }
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Given a list of IFC entity labels in the source model, extracts them and inserts them in the target model
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();
            Logger.InfoFormat("{0} Started", AppName);

            var arguments = Params.ParseParams(args);

            if (arguments.IsValid)
            {
                try
                {
                    ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                    {
                        Console.Write("{0:D5}", percentProgress);
                        ResetCursor(Console.CursorTop);
                    };

                    using (var source = IfcStore.Open(arguments.SourceModelName))
                    {
                        Logger.InfoFormat("Reading {0}", arguments.SourceModelName);
                        Logger.InfoFormat("Extracting and copying to " + arguments.TargetModelName);
                        using (var target = IfcStore.Create(source.IfcSchemaVersion, XbimStoreType.InMemoryModel))
                        {
                            var maps = new XbimInstanceHandleMap(source, target); //prevents the same thing being written twice
                            using (var txn = target.BeginTransaction())
                            {
                                try
                                {
                                    var toInsert =
                                        arguments.EntityLabels.Select(label => source.Instances[label]).ToList();
                                    var products = toInsert.OfType <IIfcProduct>().ToList();
                                    var others   = toInsert.Except(products).ToList();

                                    if (products.Any())
                                    {
                                        //this will insert products including their spatial containment,
                                        //decomposition, properties and other related information
                                        target.InsertCopy(products, true, true, maps);
                                    }
                                    if (others.Any())
                                    {
                                        //if any of the specified objects were not products, insert them straight
                                        foreach (var entity in others)
                                        {
                                            target.InsertCopy(entity, maps, null, false, true);
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    Logger.Error("Some entity labels don't exist in the source file.");
                                    return;
                                }
                                txn.Commit();
                            }

                            File.Delete(arguments.TargetModelName);
                            Logger.Info("Saving to " + arguments.TargetModelName);
                            target.SaveAs(arguments.TargetModelName, null, progDelegate);
                            Logger.Info("Success");
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.FatalFormat("{0}\n{1}", e.Message, e.StackTrace);
                }
            }
            else
            {
                Logger.Error("Supplied params are invalid");
            }

            Logger.InfoFormat("{0} Ended", AppName);

#if DEBUG
            Console.WriteLine("Press any key...");
            Console.ReadKey();
#endif
        }
Exemplo n.º 31
0
        //TODO: Consider deprecating / refactoring in favour of IfcStore.InsertCopy?

        /// <summary>
        /// This is a higher level function which uses InsertCopy function alongside with the knowledge of IFC schema to copy over
        /// products with their types and other related information (classification, aggregation, documents, properties) and optionally
        /// geometry. It will also bring in spatial hierarchy relevant to selected products. However, resulting model is not guaranteed
        /// to be compliant with any Model View Definition unless you explicitly check the compliance. Context of a single product tend to
        /// consist from hundreds of objects which need to be identified and copied over so this operation might be potentially expensive.
        /// You should never call this function more than once between two models. It not only selects objects to be copied over but also
        /// excludes other objects from being coppied over so that it doesn't bring the entire model in a chain dependencies. This means
        /// that some objects are modified (like spatial relations) and won't get updated which would lead to an inconsistent copy.
        /// </summary>
        /// <param name="target">The target model</param>
        /// <param name="products">Products from other model to be inserted into this model</param>
        /// <param name="includeGeometry">If TRUE, geometry of the products will be copied over.</param>
        /// <param name="keepLabels">If TRUE, entity labels from original model will be used. Always set this to FALSE
        /// if you are going to insert products from multiple source models or if you are going to insert products to a non-empty model</param>
        /// <param name="progress">A progress delegate</param>
        public void InsertCopy(IModel target, IEnumerable <IIfcProduct> products, bool includeGeometry, bool keepLabels,
                               IProgress <double> progress = null)
        {
            var primaryElements = new List <IIfcProduct>();

            var roots = products.Cast <IPersistEntity>().ToList();

            //return if there is nothing to insert
            if (!roots.Any())
            {
                progress?.Report(1.0);
                return;
            }

            var source = roots.First().Model;

            if (source == target)
            {
                //don't do anything if the source and target are the same
                return;
            }

            var toInsert = GetEntitiesToInsert(source, roots, out primaryElements);
            var project  = source.Instances.FirstOrDefault <IIfcProject>();

            if (project != null)
            {
                toInsert.Add(project);
            }

            double count = toInsert.Count;
            //create new cache is none is defined
            var cache = new XbimInstanceHandleMap(source, target);

            var includeSiteGeometry = false;

            if (!_siteGeometryExists)
            {
                lock (source)
                {
                    if (!_siteGeometryExists)
                    {
                        var hasSite = toInsert.OfType <IIfcRelAggregates>().Any(e => e.RelatingObject is IIfcSite);
                        if (hasSite)
                        {
                            includeSiteGeometry = true;
                            _siteGeometryExists = true;
                        }
                    }
                }
            }

            var filter = GetFilter(primaryElements, includeGeometry, includeSiteGeometry, target.Metadata);

            var counter = 0;

            foreach (var entity in toInsert)
            {
                target.InsertCopy(entity, cache, filter, true, keepLabels);
                counter++;
                if (counter % 20 == 0)
                {
                    progress?.Report(counter / count);
                }
            }

            progress?.Report(1.0);
        }
Exemplo n.º 32
0
        private void SelectionToIFC_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new SaveFileDialog
            {
                Filter           = "IFC|*.ifc|IFC XML|*.ifcXML",
                AddExtension     = true,
                FilterIndex      = 0,
                FileName         = App.Settings.LastIFC,
                InitialDirectory = System.IO.Path.GetDirectoryName(App.Settings.LastIFC),
                Title            = "Export selection to new IFC..."
            };

            if (dlg.ShowDialog() != true)
            {
                return;
            }

            // keep for next run
            App.Settings.LastIFC = dlg.FileName;

            // positive filter for declared requirement sets (property set templates)
            var psets = ContextSelector.RequirementSets.Where(r => r.IsSelected).Select(r => r.PsetTemplate);

            if (!psets.Any())
            {
                psets = ContextSelector.RequirementSets.Select(r => r.PsetTemplate);
            }
            var psetFilter = new HashSet <IfcPropertySetTemplate>(psets);

            // positive filter for declared requirements (propertytemplates)
            var properties = ContextSelector.Requirements.Where(r => r.IsSelected).Select(r => r.PropertyTemplate);

            if (!properties.Any())
            {
                properties = ContextSelector.Requirements.Select(r => r.PropertyTemplate);
            }
            var propertyFilter = new HashSet <IfcPropertyTemplate>(properties);

            // root elements for copy operation
            var requirementSets = ContextSelector.LevelsOfInformationNeeded;
            var declareRels     = requirementSets.SelectMany(r => r.Relations).Where(r => r.RelatedDefinitions
                                                                                     .Any(d => psetFilter.Contains(d) || propertyFilter.Contains(d)))
                                  .Distinct()
                                  .ToList();
            var projLibFilter = new HashSet <int>(declareRels.Select(r => r.RelatingContext.EntityLabel));

            // further refinement
            requirementSets = requirementSets
                              .Where(r => projLibFilter.Contains(r.Entity.EntityLabel))
                              .ToList();

            // positive filter for context relations
            var requirementsFilter = new HashSet <int>(requirementSets.Select(r => r.Entity.EntityLabel));

            // context items to copy
            var breakedownRels = requirementSets.SelectMany(r => r.BreakedownItems)
                                 .SelectMany(i => i.Relations)
                                 .Distinct()
                                 .Where(r => r.RelatedObjects.Any(o => projLibFilter.Contains(o.EntityLabel)))
                                 .ToList();
            var milestoneRels = requirementSets.SelectMany(r => r.Milestones)
                                .SelectMany(i => i.Relations)
                                .Distinct()
                                .Where(r => r.RelatedObjects.Any(o => projLibFilter.Contains(o.EntityLabel)))
                                .ToList();
            var reasonRels = requirementSets.SelectMany(r => r.Reasons)
                             .SelectMany(i => i.Relations)
                             .Distinct()
                             .Where(r => r.RelatedObjects.Any(o => projLibFilter.Contains(o.EntityLabel)))
                             .ToList();
            var actorRels = requirementSets.SelectMany(r => r.Actors)
                            .SelectMany(i => i.Relations)
                            .Distinct()
                            .Where(r => r.RelatedObjects.Any(o => projLibFilter.Contains(o.EntityLabel)))
                            .ToList();



            // actual copy logic
            var source = _model.Internal;

            using (var target = IfcStore.Create(Xbim.Common.Step21.XbimSchemaVersion.Ifc4, Xbim.IO.XbimStoreType.InMemoryModel))
            {
                using (var txn = target.BeginTransaction("Copy part of LOIN"))
                {
                    var map = new XbimInstanceHandleMap(source, target);

                    // use relations as roots, filter collections accordingly
                    foreach (var rel in breakedownRels)
                    {
                        target.InsertCopy(rel, map, (prop, obj) =>
                        {
                            if (prop.IsInverse)
                            {
                                return(null);
                            }
                            if (obj is IfcRelAssociatesClassification rc && prop.Name == nameof(IfcRelAssociatesClassification.RelatedObjects))
                            {
                                return(rc.RelatedObjects
                                       .Where(o => requirementsFilter.Contains(o.EntityLabel))
                                       .ToList());
                            }
                            return(prop.PropertyInfo.GetValue(obj));
                        }, false, false);
Exemplo n.º 33
0
 /// <summary>
 /// Inserts a deep copy of the toCopy object into this model
 /// All property values are copied to the maximum depth
 /// Inverse properties are not copied
 /// </summary>
 /// <param name="toCopy">Instance to copy</param>
 /// <param name="mappings">Supply a dictionary of mappings if repeat copy insertions are to be made</param>
 /// <param name="txn"></param>
 /// <param name="includeInverses"></param>
 /// <returns></returns>
 public T InsertCopy <T>(T toCopy, XbimInstanceHandleMap mappings, XbimReadWriteTransaction txn, bool includeInverses = false) where T : IPersistEntity
 {
     return(Cache.InsertCopy(toCopy, mappings, txn, includeInverses));
 }
Exemplo n.º 34
0
        private IfcProduct CopyProduct(XbimModel newmodel, XbimModel model, IfcProduct _prod)
        {
            using (XbimReadWriteTransaction txn = newmodel.BeginTransaction("CopyProduct"))
            {
                PropertyTranformDelegate propTransform = delegate (IfcMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return value;
                };

                var copied = new XbimInstanceHandleMap(model, newmodel);
                IPersistIfcEntity ent = _prod as IPersistIfcEntity;
                XbimInstanceHandle toCopyHandle = ent.GetHandle();
                XbimInstanceHandle copyHandle;
                if (copied.TryGetValue(toCopyHandle, out copyHandle))
                {
                    //Debug.Assert(copyHandle != null);
                    txn.Commit();
                    return copyHandle.GetEntity() as IfcProduct;
                }
                txn.Pulse();
                IfcType ifcType = IfcMetaData.IfcType(ent);
                //int copyLabel = ent.EntityLabel;
                var _ent = newmodel.Instances.New(ifcType.Type);
                copyHandle = _ent.GetHandle();//InsertNew(ifcType.Type, copyLabel);
                copied.Add(toCopyHandle, copyHandle);
                if (typeof(IfcCartesianPoint) == ifcType.Type || typeof(IfcDirection) == ifcType.Type)//special cases for cartesian point and direction for efficiency
                {
                    IPersistIfcEntity v = (IPersistIfcEntity)Activator.CreateInstance(ifcType.Type, new object[] { ent });
                    v.Bind(newmodel, copyHandle.EntityLabel, true);
                    v.Activate(true);
                    txn.Commit();
                    return copyHandle.GetEntity() as IfcProduct;
                    //read.TryAdd(copyHandle.EntityLabel, v);
                    //createdNew.TryAdd(copyHandle.EntityLabel, v);
                    //return (T)v;
                }
                else
                {
                    IPersistIfcEntity theCopy = (IPersistIfcEntity)Activator.CreateInstance(copyHandle.EntityType);
                    theCopy.Bind(newmodel, copyHandle.EntityLabel, true);
                    //read.TryAdd(copyHandle.EntityLabel, theCopy);
                    //createdNew.TryAdd(copyHandle.EntityLabel, theCopy);
                    // IfcRoot rt = theCopy as IfcRoot;
                    IEnumerable<IfcMetaProperty> props = ifcType.IfcProperties.Values.Where(p => !p.IfcAttribute.IsDerivedOverride);
                    // if (rt != null) rt.OwnerHistory = _model.OwnerHistoryAddObject;
                    foreach (IfcMetaProperty prop in props)
                    {
                        //if (rt != null && prop.PropertyInfo.Name == "OwnerHistory") //don't add the owner history in as this will be changed later
                        //    continue;
                        object value;
                        if (propTransform != null)
                            value = propTransform(prop, ent);
                        else
                            value = prop.PropertyInfo.GetValue(ent, null);
                        if (value != null)
                        {
                            Type theType = value.GetType();
                            //if it is an express type or a value type, set the value
                            if (theType.IsValueType || typeof(ExpressType).IsAssignableFrom(theType))
                            {
                                prop.PropertyInfo.SetValue(theCopy, value, null);
                            }

                        }
                    }
                    //  if (rt != null) rt.OwnerHistory = this.OwnerHistoryAddObject;
                    _prod = theCopy as IfcProduct;
                }

                if (newmodel.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return _prod;
                }
            }
            return null;
        }
Exemplo n.º 35
0
        private void CopyInstances(XbimModel newmodel, XbimModel model)
        {
            newmodel.AutoAddOwnerHistory = false;
            using (XbimReadWriteTransaction txn = newmodel.BeginTransaction("CopyInstances"))
            {
                PropertyTranformDelegate propTransform = delegate (IfcMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return value;
                };

                var copied = new XbimInstanceHandleMap(model, newmodel);

                foreach (var ent in model.Instances)
                {
                    newmodel.InsertCopy(ent, copied, txn, propTransform);
                }

                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                }
            }
        }