Beispiel #1
0
        /// <summary>
        ///  Geländemodell aus Punkten und Bruchlinien
        /// </summary>
        /// <param name="model">       </param>
        /// <param name="points">     Geländepunkte </param>
        /// <param name="breaklines"> Bruchlinien mit indizes der Punkte </param>
        /// <returns>  </returns>
        private static IfcGeometricCurveSet createGeometricCurveSet(IfcStore model, Vector3 origin, Mesh mesh,
                                                                    double?breakDist,
                                                                    out RepresentationType representationType,
                                                                    out RepresentationIdentifier representationIdentifier)
        {
            Serilog.Log.Logger = new LoggerConfiguration()
                                 .MinimumLevel.Debug()
                                 .WriteTo.File(System.Configuration.ConfigurationManager.AppSettings["LogFilePath"])
                                 .CreateLogger();
            //begin a transaction
            using (var txn = model.BeginTransaction("Create DTM"))
            {
                // CartesianPoints erzeugen
                var cps = mesh.Points.Select(p => model.Instances.New <IfcCartesianPoint>(c => c.SetXYZ(p.X - origin.X, p.Y - origin.Y, p.Z - origin.Z))).ToList();

                // DTM
                var dtm = model.Instances.New <IfcGeometricCurveSet>(g =>
                {
                    var edges = new HashSet <TupleIdx>();
                    g.Elements.AddRange(cps);
                    if (breakDist is double dist)
                    {
                        // Hilfsfunktion zum Punkte auf Kante erzeugen
                        void addEdgePoints(Point3 start, Point3 dest)
                        {
                            var dir    = dest - start;
                            double len = Vector3.Norm(dir);
                            double fac = len / dist;
                            if (fac > 1.0)
                            {
                                start         -= origin;
                                dir           /= len;
                                double currLen = dist;
                                while (currLen < len)
                                {
                                    var p = start + (dir * currLen);
                                    g.Elements.Add(model.Instances.New <IfcCartesianPoint>(c => c.SetXYZ(p.X, p.Y, p.Z)));
                                    currLen += dist;
                                }
                            }
                        }

                        // evtl. Bruchlinien erzeugen
                        foreach (var edge in mesh.FixedEdges)
                        {
                            addEdgePoints(mesh.Points[edge.Idx1], mesh.Points[edge.Idx2]);
                            edges.Add(edge);
                        }

                        // Kanten der Faces (falls vorhanden und ohne Doppelung)
                        foreach (var edge in mesh.EdgeIndices.Keys)
                        {
                            if (!edges.Contains(TupleIdx.Flipped(edge)) && edges.Add(edge))
                            {
                                addEdgePoints(mesh.Points[edge.Idx1], mesh.Points[edge.Idx2]);
                            }
                        }
                    }
                    else
                    {
                        // evtl. Bruchlinien erzeugen
                        foreach (var edge in mesh.FixedEdges)
                        {
                            g.Elements.Add(model.Instances.New <IfcPolyline>(p => p.Points.AddRange(new[] { cps[edge.Idx1], cps[edge.Idx2] })));
                            edges.Add(edge);
                        }

                        // Kanten der Faces (falls vorhanden und ohne Doppelung)
                        foreach (var edge in mesh.EdgeIndices.Keys)
                        {
                            if (!edges.Contains(TupleIdx.Flipped(edge)) && edges.Add(edge))
                            {
                                g.Elements.Add(model.Instances.New <IfcPolyline>(p => p.Points.AddRange(new[] { cps[edge.Idx1], cps[edge.Idx2] })));
                            }
                        }
                    }
                });

                txn.Commit();
                representationIdentifier = RepresentationIdentifier.SurveyPoints;
                representationType       = RepresentationType.GeometricCurveSet;
                Log.Information("IfcGeometricCurveSet created");
                return(dtm);
            }
        }
Beispiel #2
0
        private static void CreateSimpleProperty(IfcStore model, IfcWallStandardCase wall)
        {
            var ifcPropertySingleValue = model.Instances.New <IfcPropertySingleValue>(psv =>
            {
                psv.Name         = "IfcPropertySingleValue:Time";
                psv.Description  = "";
                psv.NominalValue = new IfcTimeMeasure(150.0);
                psv.Unit         = model.Instances.New <IfcSIUnit>(siu =>
                {
                    siu.UnitType = IfcUnitEnum.TIMEUNIT;
                    siu.Name     = IfcSIUnitName.SECOND;
                });
            });
            var ifcPropertyEnumeratedValue = model.Instances.New <IfcPropertyEnumeratedValue>(pev =>
            {
                pev.Name = "IfcPropertyEnumeratedValue:Music";
                pev.EnumerationReference = model.Instances.New <IfcPropertyEnumeration>(pe =>
                {
                    pe.Name = "Notes";
                    pe.EnumerationValues.Add(new IfcLabel("Do"));
                    pe.EnumerationValues.Add(new IfcLabel("Re"));
                    pe.EnumerationValues.Add(new IfcLabel("Mi"));
                    pe.EnumerationValues.Add(new IfcLabel("Fa"));
                    pe.EnumerationValues.Add(new IfcLabel("So"));
                    pe.EnumerationValues.Add(new IfcLabel("La"));
                    pe.EnumerationValues.Add(new IfcLabel("Ti"));
                });
                pev.EnumerationValues.Add(new IfcLabel("Do"));
                pev.EnumerationValues.Add(new IfcLabel("Re"));
                pev.EnumerationValues.Add(new IfcLabel("Mi"));
            });
            var ifcPropertyBoundedValue = model.Instances.New <IfcPropertyBoundedValue>(pbv =>
            {
                pbv.Name            = "IfcPropertyBoundedValue:Mass";
                pbv.Description     = "";
                pbv.UpperBoundValue = new IfcMassMeasure(5000.0);
                pbv.LowerBoundValue = new IfcMassMeasure(1000.0);
                pbv.Unit            = model.Instances.New <IfcSIUnit>(siu =>
                {
                    siu.UnitType = IfcUnitEnum.MASSUNIT;
                    siu.Name     = IfcSIUnitName.GRAM;
                    siu.Prefix   = IfcSIPrefix.KILO;
                });
            });

            var definingValues = new List <IfcReal> {
                new IfcReal(100.0), new IfcReal(200.0), new IfcReal(400.0), new IfcReal(800.0), new IfcReal(1600.0), new IfcReal(3200.0),
            };
            var definedValues = new List <IfcReal> {
                new IfcReal(20.0), new IfcReal(42.0), new IfcReal(46.0), new IfcReal(56.0), new IfcReal(60.0), new IfcReal(65.0),
            };
            var ifcPropertyTableValue = model.Instances.New <IfcPropertyTableValue>(ptv =>
            {
                ptv.Name = "IfcPropertyTableValue:Sound";
                foreach (var item in definingValues)
                {
                    ptv.DefiningValues.Add(item);
                }
                foreach (var item in definedValues)
                {
                    ptv.DefinedValues.Add(item);
                }
                ptv.DefinedUnit = model.Instances.New <IfcContextDependentUnit>(cd =>
                {
                    cd.Dimensions = model.Instances.New <IfcDimensionalExponents>(de =>
                    {
                        de.LengthExponent                   = 0;
                        de.MassExponent                     = 0;
                        de.TimeExponent                     = 0;
                        de.ElectricCurrentExponent          = 0;
                        de.ThermodynamicTemperatureExponent = 0;
                        de.AmountOfSubstanceExponent        = 0;
                        de.LuminousIntensityExponent        = 0;
                    });
                    cd.UnitType = IfcUnitEnum.FREQUENCYUNIT;
                    cd.Name     = "dB";
                });
            });

            var listValues = new List <IfcLabel> {
                new IfcLabel("Red"), new IfcLabel("Green"), new IfcLabel("Blue"), new IfcLabel("Pink"), new IfcLabel("White"), new IfcLabel("Black"),
            };
            var ifcPropertyListValue = model.Instances.New <IfcPropertyListValue>(plv =>
            {
                plv.Name = "IfcPropertyListValue:Colours";
                foreach (var item in listValues)
                {
                    plv.ListValues.Add(item);
                }
            });

            var ifcMaterial = model.Instances.New <IfcMaterial>(m =>
            {
                m.Name = "Brick";
            });
            var ifcPrValueMaterial = model.Instances.New <IfcPropertyReferenceValue>(prv =>
            {
                prv.Name = "IfcPropertyReferenceValue:Material";
                prv.PropertyReference = ifcMaterial;
            });


            var ifcMaterialList = model.Instances.New <IfcMaterialList>(ml =>
            {
                ml.Materials.Add(ifcMaterial);
                ml.Materials.Add(model.Instances.New <IfcMaterial>(m => { m.Name = "Cavity"; }));
                ml.Materials.Add(model.Instances.New <IfcMaterial>(m => { m.Name = "Block"; }));
            });


            var ifcMaterialLayer = model.Instances.New <IfcMaterialLayer>(ml =>
            {
                ml.Material       = ifcMaterial;
                ml.LayerThickness = 100.0;
            });
            var ifcPrValueMatLayer = model.Instances.New <IfcPropertyReferenceValue>(prv =>
            {
                prv.Name = "IfcPropertyReferenceValue:MaterialLayer";
                prv.PropertyReference = ifcMaterialLayer;
            });

            var ifcDocumentReference = model.Instances.New <IfcDocumentReference>(dr =>
            {
                dr.Name     = "Document";
                dr.Location = "c://Documents//TheDoc.Txt";
            });
            var ifcPrValueRef = model.Instances.New <IfcPropertyReferenceValue>(prv =>
            {
                prv.Name = "IfcPropertyReferenceValue:Document";
                prv.PropertyReference = ifcDocumentReference;
            });

            var ifcTimeSeries = model.Instances.New <IfcRegularTimeSeries>(ts =>
            {
                ts.Name               = "Regular Time Series";
                ts.Description        = "Time series of events";
                ts.StartTime          = new IfcDateTime("2015-02-14T12:01:01");
                ts.EndTime            = new IfcDateTime("2015-05-15T12:01:01");
                ts.TimeSeriesDataType = IfcTimeSeriesDataTypeEnum.CONTINUOUS;
                ts.DataOrigin         = IfcDataOriginEnum.MEASURED;
                ts.TimeStep           = 604800; //7 days in secs
            });

            var ifcPrValueTimeSeries = model.Instances.New <IfcPropertyReferenceValue>(prv =>
            {
                prv.Name = "IfcPropertyReferenceValue:TimeSeries";
                prv.PropertyReference = ifcTimeSeries;
            });

            var ifcAddress = model.Instances.New <IfcPostalAddress>(a =>
            {
                a.InternalLocation = "Room 101";
                a.AddressLines.AddRange(new[] { new IfcLabel("12 New road"), new IfcLabel("DoxField") });
                a.Town       = "Sunderland";
                a.PostalCode = "DL01 6SX";
            });
            var ifcPrValueAddress = model.Instances.New <IfcPropertyReferenceValue>(prv =>
            {
                prv.Name = "IfcPropertyReferenceValue:Address";
                prv.PropertyReference = ifcAddress;
            });
            var ifcTelecomAddress = model.Instances.New <IfcTelecomAddress>(a =>
            {
                a.TelephoneNumbers.Add(new IfcLabel("01325 6589965"));
                a.ElectronicMailAddresses.Add(new IfcLabel("*****@*****.**"));
            });
            var ifcPrValueTelecom = model.Instances.New <IfcPropertyReferenceValue>(prv =>
            {
                prv.Name = "IfcPropertyReferenceValue:Telecom";
                prv.PropertyReference = ifcTelecomAddress;
            });



            //lets create the IfcElementQuantity
            var ifcPropertySet = model.Instances.New <IfcPropertySet>(ps =>
            {
                ps.Name        = "Test:IfcPropertySet";
                ps.Description = "Property Set";
                ps.HasProperties.Add(ifcPropertySingleValue);
                ps.HasProperties.Add(ifcPropertyEnumeratedValue);
                ps.HasProperties.Add(ifcPropertyBoundedValue);
                ps.HasProperties.Add(ifcPropertyTableValue);
                ps.HasProperties.Add(ifcPropertyListValue);
                ps.HasProperties.Add(ifcPrValueMaterial);
                ps.HasProperties.Add(ifcPrValueMatLayer);
                ps.HasProperties.Add(ifcPrValueRef);
                ps.HasProperties.Add(ifcPrValueTimeSeries);
                ps.HasProperties.Add(ifcPrValueAddress);
                ps.HasProperties.Add(ifcPrValueTelecom);
            });

            //need to create the relationship
            model.Instances.New <IfcRelDefinesByProperties>(rdbp =>
            {
                rdbp.Name        = "Property Association";
                rdbp.Description = "IfcPropertySet associated to wall";
                rdbp.RelatedObjects.Add(wall);
                rdbp.RelatingPropertyDefinition = ifcPropertySet;
            });
        }
        /// <summary>
        /// This creates a wall and it's geometry, many geometric representations are possible and extruded rectangular footprint is chosen as this is commonly used for standard case walls
        /// </summary>
        /// <param name="model"></param>
        /// <param name="length">Length of the rectangular footprint</param>
        /// <param name="width">Width of the rectangular footprint (width of the wall)</param>
        /// <param name="height">Height to extrude the wall, extrusion is vertical</param>
        /// <returns></returns>
        private IfcWallStandardCase CreateIfcWall(IfcStore model, Wall cadWall, double height)
        {
            //cadWall.Thickness *= 1000;
            //cadWall.StPt.X *= 1000;
            //cadWall.StPt.Y*= 1000;
            //cadWall.EndPt.X *= 1000;
            //cadWall.EndPt.Y *= 1000;

            //dimensions of the new IFC Wall we want to create
            double length = Math.Abs(cadWall.EndPt.X - cadWall.StPt.X) > 0 ? Math.Abs(cadWall.EndPt.X - cadWall.StPt.X)  : Math.Abs(cadWall.EndPt.Y - cadWall.StPt.Y);
            double width  = cadWall.Thickness;

            //begin a transaction
            using (var trans = model.BeginTransaction("Create Wall"))
            {
                IfcWallStandardCase wallToCreate = model.Instances.New <IfcWallStandardCase>();
                wallToCreate.Name = " Wall - Wall:UC305x305x97:" + random.Next(1000, 10000);

                //represent wall as a rectangular profile
                IfcRectangleProfileDef rectProf = IFCHelper.RectProfileCreate(model, length, width);

                //Profile Insertion Point
                rectProf.ProfileInsertionPointSet(model, 0, 0);

                //model as a swept area solid
                IfcDirection extrusionDir = model.Instances.New <IfcDirection>();
                extrusionDir.SetXYZ(0, 0, -1);


                IfcExtrudedAreaSolid body = IFCHelper.ProfileSweptSolidCreate(model, height, rectProf, extrusionDir);

                //parameters to insert the geometry in the model
                body.BodyPlacementSet(model, 0, 0, 0);

                //Create a Definition shape to hold the geometry of the wall 3D body
                IfcShapeRepresentation shape = IFCHelper.ShapeRepresentationCreate(model, "SweptSolid", "Body");
                shape.Items.Add(body);

                //Create a Product Definition and add the model geometry to the wall
                IfcProductDefinitionShape prDefShape = model.Instances.New <IfcProductDefinitionShape>();
                prDefShape.Representations.Add(shape);
                wallToCreate.Representation = prDefShape;

                //Create Local axes system and assign it to the wall
                var midPt = MathHelper.MidPoint3D(cadWall.StPt, cadWall.EndPt);

                IfcCartesianPoint location3D = model.Instances.New <IfcCartesianPoint>();
                location3D.SetXYZ(midPt.X, midPt.Y, midPt.Z);

                var uvWallLongDir = MathHelper.UnitVectorFromPt1ToPt2(cadWall.StPt, cadWall.EndPt);

                IfcDirection localXDir = model.Instances.New <IfcDirection>();
                localXDir.SetXYZ(uvWallLongDir.X, uvWallLongDir.Y, uvWallLongDir.Z);

                IfcDirection localZDir = model.Instances.New <IfcDirection>();
                localZDir.SetXYZ(0, 0, 1);

                IfcAxis2Placement3D ax3D = IFCHelper.LocalAxesSystemCreate(model, location3D, localXDir, localZDir);

                //now place the wall into the model
                IfcLocalPlacement lp = IFCHelper.LocalPlacemetCreate(model, ax3D);

                wallToCreate.ObjectPlacement = lp;


                // IfcPresentationLayerAssignment is required for CAD presentation in IfcWall or IfcWallStandardCase
                var ifcPresentationLayerAssignment = model.Instances.New <IfcPresentationLayerAssignment>();
                ifcPresentationLayerAssignment.Name = "some ifcPresentationLayerAssignment";
                ifcPresentationLayerAssignment.AssignedItems.Add(shape);

                trans.Commit();
                return(wallToCreate);
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("No IIfc or xBim file specified");
                return;
            }
            var fileName = args[0];

            Console.WriteLine("Reading " + fileName);

            using (var model = GetModel(fileName))
            {
                if (model == null)
                {
                    Console.WriteLine("No model to process. Press any key to exit");
                    Console.Read();
                    return;
                }

                var context = new Xbim3DModelContext(model);
                context.CreateContext();
                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);
                        model.SaveAsWexBim(wexBimBinaryWriter);
                        wexBimBinaryWriter.Close();
                    }
                    wexBiMfile.Close();
                }
                //now do COBieExpress
                var cobie               = new MemoryModel(new EntityFactory());
                var cobieExpressFile    = Path.ChangeExtension(fileName, ".cobie");
                var cobieExpressXmlFile = Path.ChangeExtension(fileName, ".cobieXml");
                var cobieExpressZipFile = Path.ChangeExtension(fileName, ".cobieZip");
                var w = new Stopwatch();
                using (var txn = cobie.BeginTransaction("IFC data in"))
                {
                    var exchanger = new IfcToCoBieExpressExchanger(model, cobie);
                    w.Start();
                    exchanger.Convert();
                    w.Stop();
                    txn.Commit();
                }
                Console.WriteLine("COBieExpress model created in {0}ms", w.ElapsedMilliseconds);
                cobie.SaveAsStep21(File.Create(cobieExpressFile));
                cobie.SaveAsStep21Zip(File.Create(cobieExpressZipFile));
                cobie.SaveAsXml(File.Create(cobieExpressXmlFile), new XmlWriterSettings {
                    Indent = true, IndentChars = "\t"
                });


                //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");
                    var credentials = new XbimEditorCredentials()
                    {
                        ApplicationDevelopersName = "XbimTeam",
                        ApplicationFullName       = "Xbim.Exchanger",
                        EditorsOrganisationName   = "Xbim Development Team",
                        EditorsFamilyName         = "Xbim Tester",
                        ApplicationVersion        = "3.0"
                    };
                    Console.WriteLine("Creating " + dPoWFile);
                    using (
                        var ifcModel = IfcStore.Create(credentials, IfcSchemaVersion.Ifc2X3,
                                                       XbimStoreType.EsentDatabase))
                    {
                        using (var txn = ifcModel.BeginTransaction("Convert from COBieLiteUK"))
                        {
                            var coBieLiteUkToIIfcExchanger = new CoBieLiteUkToIfcExchanger(facility, ifcModel);
                            coBieLiteUkToIIfcExchanger.Convert();
                            txn.Commit();
                            //var err = model.Validate(model.Instances, Console.Out);
                        }
                        dPoWFile = Path.ChangeExtension(dPoWFile, "ifc");
                        Console.WriteLine("Creating " + dPoWFile);
                        ifcModel.SaveAs(dPoWFile, IfcStorageType.Ifc);
                        ifcModel.Close();
                    }
                }
                model.Close();
            }
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }
        /// <summary>
        /// Aufrufen der HTML von xBIM WeXplorer, Code für die Verwendung des WebViewers wurde von
        /// http://docs.xbim.net/XbimWebUI/tutorial-5_Colourful_building.html | http://docs.xbim.net/XbimWebUI/5_Colourful_building.live.html  und https://github.com/xBimTeam/XbimWebUI übernommen
        /// </summary>
        private void ClickOnGrafischDarstellen(object sender, RoutedEventArgs e)
        {
            var path = Constants.FolderPath + @"WebViewer\data\templateModel.ifc";

            //Erzeugen der Modell IFC-Datei aus dem Base64String
            Byte[] bytes = Convert.FromBase64String(Permission.ModelFile);
            File.WriteAllBytes(path, bytes);

            string wexBimB64 = "";

            //Erzeugen der wexBim Datei vom Modell. Dateien im wexBim Format werden für den Web Viewer benötigt
            using (var model = IfcStore.Open(path))
            {
                var context = new Xbim3DModelContext(model);
                context.CreateContext();

                var wexBimFilename = Path.ChangeExtension(path, "wexBIM");
                using (var wexBiMfile = File.Create(wexBimFilename))
                {
                    using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                    {
                        model.SaveAsWexBim(wexBimBinaryWriter);
                        wexBimBinaryWriter.Close();
                    }
                    wexBiMfile.Close();
                }

                //Umwandeln des wexBim Datei in einen Base64String um es in der Javascript Datei des Web Viewers zu verwenden.
                var bytesWexBim = File.ReadAllBytes(wexBimFilename);
                wexBimB64 = Convert.ToBase64String(bytesWexBim);
            }

            File.Delete(path);

            //Ermitteln der EntityIds aller veränderten Bauteile
            var        tempNeo4j = new Neo4JConnector(Neo4jAccessData.Uri, Neo4jAccessData.User, Neo4jAccessData.Password, "templateModel");
            List <int> entityIds = new List <int>();

            foreach (var item in Distinctions)
            {
                var wallGlobalId        = tempNeo4j.GetIdForChangedElements(item.WallGlobalId);
                var wallElementGlobalId = tempNeo4j.GetIdForChangedElements(item.WallElementGlobalId);
                if (!entityIds.Contains(wallGlobalId) && wallGlobalId != 0 && wallElementGlobalId == 0)
                {
                    entityIds.Add(wallGlobalId);
                }
                else if (!entityIds.Contains(wallElementGlobalId) && wallElementGlobalId != 0)
                {
                    entityIds.Add(wallElementGlobalId);
                }
            }

            //Speichern der BauteilIds und des Base64Strings der wexBim datei.
            var    pathChangedElements = Constants.FolderPath + @"WebViewer\data\templateModel.js";
            string input = "var data = {\"changedElements\" : [" + String.Join(",", entityIds) + "]};";

            input += $@"var dataWexBimB64 = ""{wexBimB64}"";";
            File.WriteAllText(pathChangedElements, input);

            //Aufrufen des Web Viewers
            System.Diagnostics.Process.Start(Constants.FolderPath + @"WebViewer\webViewer.html");
        }
Beispiel #6
0
 protected virtual void DoCommitAll(IfcStore model)
 {
     Product.Name            = Name;
     Product.GlobalId        = GUID;
     Product.ObjectPlacement = CreatePlacement(model);
 }
Beispiel #7
0
        public static void Create()
        {
            var editor = new XbimEditorCredentials
            {
                ApplicationDevelopersName = "xBIM Team",
                ApplicationFullName       = "xBIM Toolkit",
                ApplicationIdentifier     = "xBIM",
                ApplicationVersion        = "4.0",
                EditorsFamilyName         = "Santini Aichel",
                EditorsGivenName          = "Johann Blasius",
                EditorsOrganisationName   = "Independent Architecture"
            };

            using (var model = IfcStore.Create(editor, IfcSchemaVersion.Ifc4, XbimStoreType.InMemoryModel))
            {
                using (var txn = model.BeginTransaction("Hello Wall"))
                {
                    //there should always be one project in the model
                    var project = model.Instances.New <IfcProject>(p => p.Name = "Basic Creation");
                    //our shortcut to define basic default units
                    project.Initialize(ProjectUnits.SIUnitsUK);

                    //create simple object and use lambda initializer to set the name
                    var wall = model.Instances.New <IfcWall>(w => w.Name = "The very first wall");

                    //set a few basic properties
                    model.Instances.New <IfcRelDefinesByProperties>(rel => {
                        rel.RelatedObjects.Add(wall);
                        rel.RelatingPropertyDefinition = model.Instances.New <IfcPropertySet>(pset => {
                            pset.Name = "Basic set of properties";
                            pset.HasProperties.AddRange(new[] {
                                model.Instances.New <IfcPropertySingleValue>(p =>
                                {
                                    p.Name         = "Text property";
                                    p.NominalValue = new IfcText("Any arbitrary text you like");
                                }),
                                model.Instances.New <IfcPropertySingleValue>(p =>
                                {
                                    p.Name         = "Length property";
                                    p.NominalValue = new IfcLengthMeasure(56.0);
                                }),
                                model.Instances.New <IfcPropertySingleValue>(p =>
                                {
                                    p.Name         = "Number property";
                                    p.NominalValue = new IfcNumericMeasure(789.2);
                                }),
                                model.Instances.New <IfcPropertySingleValue>(p =>
                                {
                                    p.Name         = "Logical property";
                                    p.NominalValue = new IfcLogical(true);
                                })
                            });
                        });
                    });

                    txn.Commit();
                }
                model.SaveAs("BasicWall.ifc");
                model.SaveAs("BasicWall.ifcxml");
            }
        }
Beispiel #8
0
        public void TestDocExtraction()
        {
            var ifcFile  = "Clinic-Handover-v12.ifc";
            var xbimFile = Path.ChangeExtension(ifcFile, "xbim");

            using (var _model = IfcStore.Open(ifcFile))
            {
                var ifcRelAssociatesDocuments = _model.Instances.OfType <IfcRelAssociatesDocument>();

                var dups = ifcRelAssociatesDocuments.GroupBy(d => d.RelatingDocument).SelectMany(grp => grp.Skip(1));
                Dictionary <IfcDocumentSelect, List <IfcRoot> > docToObjs = null;
                if (dups.Any())
                {
                    var dupsMerge = dups.GroupBy(d => d.RelatingDocument).Select(p => new { x = p.Key, y = p.SelectMany(c => c.RelatedObjects) });
                    //remove the duplicates and convert to dictionary
                    docToObjs = ifcRelAssociatesDocuments.Except(dups).ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects.ToList());

                    //add the duplicate doc referenced object lists to the original doc
                    foreach (var item in dupsMerge)
                    {
                        docToObjs[item.x] = docToObjs[item.x].Union(item.y).ToList();
                    }
                }
                else
                {
                    //no duplicates, so just convert to dictionary
                    docToObjs = ifcRelAssociatesDocuments.ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects.ToList());
                }

                //Lets set up some children documents
                using (var txn = _model.BeginTransaction("Add Documents"))
                {
                    foreach (var item in docToObjs)
                    {
                        var doc1 = item.Key as IfcDocumentInformation;
                        if (doc1 != null)
                        {
                            var docRelChild1 = _model.Instances.New <IfcDocumentInformationRelationship>();
                            docRelChild1.RelatingDocument = doc1;
                            //add child docs
                            var childDocA = CreateDocInfo(_model, "ChildDoc1a", @"c:\TestDir\Dir1");
                            var childDocB = CreateDocInfo(_model, "ChildDoc1b", @"c:\TestDir\Dir1");
                            var childDocC = CreateDocInfo(_model, "ChildDoc1c", @"c:\TestDir\Dir1");
                            docRelChild1.RelatedDocuments.Add(childDocA);
                            docRelChild1.RelatedDocuments.Add(childDocB);
                            docRelChild1.RelatedDocuments.Add(childDocC);

                            //add another layer
                            var docRelChild2 = _model.Instances.New <IfcDocumentInformationRelationship>();
                            docRelChild2.RelatingDocument = childDocA;
                            var childDoc2D = CreateDocInfo(_model, "ChildDoc2d", @"c:\TestDir\Dir1\Dir2");
                            var childDoc2E = CreateDocInfo(_model, "ChildDoc2e", @"c:\TestDir\Dir1\Dir2");
                            docRelChild2.RelatedDocuments.Add(childDoc2D);
                            docRelChild2.RelatedDocuments.Add(childDoc2E);

                            //add another layer
                            var docRelChild3 = _model.Instances.New <IfcDocumentInformationRelationship>();
                            docRelChild3.RelatingDocument = childDoc2D;
                            var childDoc3F = CreateDocInfo(_model, "ChildDoc3f", @"c:\TestDir\Dir1\Dir2\Dir3");
                            docRelChild3.RelatedDocuments.Add(childDoc3F);
                        }
                    }

                    CreateDocInfo(_model, "orphanDocA", @"c:");


                    var orphanDocB = _model.Instances.New <IfcDocumentReference>();
                    orphanDocB.Name     = "orphanDocB";
                    orphanDocB.Location = @"x:";
                    txn.Commit();

                    _model.SaveAs("Clinic-Handover_ChildDocs.ifc", StorageType.Ifc);
                }


                //Get all documents information objects held in model
                var docAllInfos = _model.Instances.OfType <IfcDocumentInformation>();
                //Get the child document relationships
                var childDocRels = _model.Instances.OfType <IfcDocumentInformationRelationship>();



                //get the already attached to entity documents
                var docInfosAttached = docToObjs.Select(dictionary => dictionary.Key).OfType <IfcDocumentInformation>();

                //see if we have any documents not attached to IfcRoot objects, but could be attached as children documents to a parent document
                var docInfosNotAttached = docAllInfos.Except(docInfosAttached);

                List <IfcDocumentInformation> docChildren = docInfosAttached.ToList(); //first check on docs attached to IfcRoot Objects
                int idx = 0;
                do
                {
                    //get the relationships that are attached to the docs already associated with an IfcRoot object on first pass, then associated with all children, drilling down until nothing found
                    docChildren         = childDocRels.Where(docRel => docChildren.Contains(docRel.RelatingDocument)).SelectMany(docRel => docRel.RelatedDocuments).ToList(); //docs that are children to attached entity docs, drilling down
                    docInfosNotAttached = docInfosNotAttached.Except(docChildren);                                                                                            //attached by association to the root parent document, so remove from none attached document list
                } while (docChildren.Any() && (++idx < 100));                                                                                                                 //assume that docs are not embedded deeper than 100

                Assert.IsTrue(docInfosNotAttached.Count() == 1);


                //get all the doc reference objects held in the model
                var docAllRefs = _model.Instances.OfType <IfcDocumentReference>();
                //get all attached document references
                var docRefsAttached = docToObjs.Select(dictionary => dictionary.Key).OfType <IfcDocumentReference>();
                //checked on direct attached to object document references
                var docRefsNotAttached = docAllRefs.Except(docRefsAttached).ToList();

                //Check for document references held in the IfcDocumentInformation objects
                var docRefsAttachedDocInfo = docAllInfos.Where(docInfo => docInfo.DocumentReferences != null).SelectMany(docInfo => docInfo.DocumentReferences);
                //remove from Not Attached list
                docRefsNotAttached = docRefsNotAttached.Except(docRefsAttachedDocInfo).ToList();

                Assert.IsTrue(docRefsNotAttached.Count() == 1);

                //reverse lookup to entity to list of documents
                var newDic = docToObjs
                             .SelectMany(pair => pair.Value
                                         .Select(val => new { Key = val, Value = pair.Key }))
                             .GroupBy(item => item.Key)
                             .ToLookup(gr => gr.Key, gr => gr.Select(item => item.Value));

                foreach (var group in newDic)
                {
                    foreach (var item in group)
                    {
                        Assert.IsTrue(item.Count() > 0);
                        //foreach (var doc in item)
                        //{
                        //    if (doc is IfcDocumentInformation)
                        //    {
                        //        Debug.WriteLine("Doc {0}", ((IfcDocumentInformation)doc).Name);
                        //    }
                        //    else
                        //    {
                        //        Debug.WriteLine("Doc {0}", ((IfcDocumentReference)doc).Name);
                        //    }

                        //}
                    }
                }
            }
        }
Beispiel #9
0
        public void ArbitraryClosedProfileDefWithIncorrectPlacementTest()
        {
            using (var model = IfcStore.Create(new XbimEditorCredentials(), IfcSchemaVersion.Ifc4, XbimStoreType.InMemoryModel))
            {
                using (var txn = model.BeginTransaction("Create Column"))
                {
                    IfcProject project = model.Instances.New <IfcProject>();
                    project.Initialize(ProjectUnits.SIUnitsUK);
                    project.Name = "Test Project";

                    IfcColumn col = model.Instances.New <IfcColumn>();
                    col.Name = "Column With ArbitraryClosedProfileDef";


                    //Creating IfcArbitraryClosedProfileDef that will contain IfcCompositeCurve
                    IfcArbitraryClosedProfileDef arbClosedProf = model.Instances.New <IfcArbitraryClosedProfileDef>();

                    //To create IfcArbitraryClosedProfileDef, we'll need to create IfcCompositeCurve
                    //Creating IfcCompositeCurve
                    IfcCompositeCurve myCompCurve = model.Instances.New <IfcCompositeCurve>();

                    //To Create IfcCompositeCurve, We'll need to create IfcCompositeCurveSegment
                    //create IfcCompositeCurveSegment (polyline)
                    IfcCompositeCurveSegment polylineSeg = model.Instances.New <IfcCompositeCurveSegment>();

                    //create IfcCompositeCurveSegment (arc)
                    IfcCompositeCurveSegment arcSeg = model.Instances.New <IfcCompositeCurveSegment>();

                    //Creating IfcPolyline that will be the parent curve for IfcCompositeCurveSegment "polylineSeg"
                    IfcPolyline myPolyline = model.Instances.New <IfcPolyline>();

                    //Creating Points to build the IfcPolyline
                    IfcCartesianPoint p0 = model.Instances.New <IfcCartesianPoint>();
                    p0.SetXY(200, 100);

                    IfcCartesianPoint p1 = model.Instances.New <IfcCartesianPoint>();
                    p1.SetXY(0, 100);

                    IfcCartesianPoint p2 = model.Instances.New <IfcCartesianPoint>();
                    p2.SetXY(0, 0);

                    IfcCartesianPoint p3 = model.Instances.New <IfcCartesianPoint>();
                    p3.SetXY(400, 0);

                    IfcCartesianPoint p4 = model.Instances.New <IfcCartesianPoint>();
                    p4.SetXY(400, 600);

                    IfcCartesianPoint p5 = model.Instances.New <IfcCartesianPoint>();
                    p5.SetXY(0, 600);

                    IfcCartesianPoint p6 = model.Instances.New <IfcCartesianPoint>();
                    p6.SetXY(0, 500);

                    IfcCartesianPoint p7 = model.Instances.New <IfcCartesianPoint>();
                    p7.SetXY(200, 500);

                    //Adding points to the polyline
                    myPolyline.Points.Add(p0);
                    myPolyline.Points.Add(p1);
                    myPolyline.Points.Add(p2);
                    myPolyline.Points.Add(p3);
                    myPolyline.Points.Add(p4);
                    myPolyline.Points.Add(p5);
                    myPolyline.Points.Add(p6);
                    myPolyline.Points.Add(p7);

                    //Assigning myPolyline to the IfcCompositeCurveSegment polylineSeg
                    polylineSeg.ParentCurve = myPolyline;

                    //Creating Arc using IfcTrimmedCurve
                    IfcTrimmedCurve myArc = model.Instances.New <IfcTrimmedCurve>();

                    //To create IfcTrimmedCurve, We'll need to create IfcCircle and trim it using IfcTrimmingSelect
                    IfcCircle myCirc = model.Instances.New <IfcCircle>();
                    myCirc.Radius = 213.554;
                    IfcCartesianPoint cP = model.Instances.New <IfcCartesianPoint>();
                    cP.SetXY(125.1312, 300); //this should really be a 3D point

                    IfcAxis2Placement3D plcmnt = model.Instances.New <IfcAxis2Placement3D>();
                    plcmnt.Location     = cP;
                    plcmnt.RefDirection = model.Instances.New <IfcDirection>();
                    plcmnt.RefDirection.SetXY(0, 1);//this should eb a 3D axis
                    myCirc.Position = plcmnt;

                    myArc.BasisCurve = myCirc;

                    IfcTrimmingSelect v1 = p7;
                    IfcTrimmingSelect v2 = p0;

                    myArc.Trim1.Add(v1);
                    myArc.Trim2.Add(v2);

                    arcSeg.ParentCurve = myArc;

                    //Adding the created two IfcCompositeCurveSegments to the IfcCompositeCurve
                    myCompCurve.Segments.Add(arcSeg);
                    myCompCurve.Segments.Add(polylineSeg);

                    //Assigning IfcCompositeCurve "myCompCurve" to the IfcArbitraryClosedProfileDef
                    arbClosedProf.OuterCurve = myCompCurve;

                    arbClosedProf.ProfileType = IfcProfileTypeEnum.AREA;

                    //model as a swept area solid
                    IfcExtrudedAreaSolid body = model.Instances.New <IfcExtrudedAreaSolid>();
                    body.Depth             = 2000;
                    body.SweptArea         = arbClosedProf;
                    body.ExtrudedDirection = model.Instances.New <IfcDirection>();
                    body.ExtrudedDirection.SetXYZ(0, 0, 1);


                    txn.Commit();
                    var solid = _xbimGeometryCreator.CreateSolid(body);
                    Assert.IsTrue((int)solid.Volume == 239345450);
                }
            }
        }
Beispiel #10
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);
        private IfcAlignment CreateArcAlignment(IfcStore m, string txt)
        {
            const int    LENGTH    = 150000;
            const double DIRECTION = 0;
            const int    RADIUS    = 150000;
            bool         ISCCW     = true;

            const int    DISTANCE = 0;
            const double LENGTH2  = 150000;
            const double HEIGHT   = 15000;
            const double GRADIENT = 0.02;

            using (var txn = m.BeginTransaction("CreateArcAlignment"))
            {
                var alignCurve = m.Instances.New <IfcAlignmentCurve>(ac =>
                {
                    var alignment2Dhorizontal = m.Instances.New <IfcAlignment2DHorizontal>(az =>
                    {
                        var horizontalSeq = m.Instances.New <IfcAlignment2DHorizontalSegment>(hs =>
                        {
                            hs.TangentialContinuity = true;
                            hs.CurveGeometry        = toolkit_factory.MakeCircleSeqment2D(m, Origin2D, DIRECTION, LENGTH, RADIUS, ISCCW);
                        });
                        az.Segments.Add(horizontalSeq);
                    });
                    ac.Horizontal = alignment2Dhorizontal;

                    var alignment2Dvertical = m.Instances.New <IfcAlignment2DVertical>(av =>
                    {
                        var alignment2DverSeqLine = m.Instances.New <IfcAlignment2DVerSegLine>(sl =>
                        {
                            sl.TangentialContinuity = true;
                            sl.StartDistAlong       = DISTANCE;
                            sl.HorizontalLength     = LENGTH2;
                            sl.StartHeight          = HEIGHT;
                            sl.StartGradient        = GRADIENT;
                        });
                        av.Segments.Add(alignment2DverSeqLine);
                    });
                    ac.Vertical = alignment2Dvertical;
                });
                var align = m.Instances.New <IfcAlignment>(a =>
                {
                    a.Axis            = alignCurve;
                    a.Name            = txt;
                    a.ObjectPlacement = m.Instances.New <IfcLocalPlacement>(lp => lp.RelativePlacement = WCS);

                    var shaperepresentation            = m.Instances.New <IfcShapeRepresentation>();
                    shaperepresentation.ContextOfItems = m.Instances.OfType <IfcGeometricRepresentationContext>().
                                                         Where(c => c.CoordinateSpaceDimension == 3).FirstOrDefault();
                    shaperepresentation.RepresentationIdentifier = "Body";
                    shaperepresentation.RepresentationType       = "AdvancedSweptSolid";

                    //the items of shaperepresentation ouught to be IfcGeometricalRepresentationItem
                    //so create IfcGeometricalRepresentationItem

                    var sectionsolidhorizontal       = m.Instances.New <IfcSectionedSolidHorizontal>();
                    sectionsolidhorizontal.Directrix = alignCurve;
                    //var p1 = toolkit_factory.MakeCartesianPoint(m, -1000, 0);
                    //var p2 = toolkit_factory.MakeCartesianPoint(m, 100, 0);
                    //var line = toolkit_factory.MakePolyLine(m, new List<IfcCartesianPoint>() { p1, p2 });
                    //var profile = toolkit_factory.MakeCenterLineProfile(m, line, 25);
                    //sectionsolidhorizontal.CrossSections.Add(profile);
                    //sectionsolidhorizontal.CrossSections.Add(profile);
                    //var posStart = toolkit_factory.MakeDistanceExpresstion(m, DISTANCE);
                    //var posEnd = toolkit_factory.MakeDistanceExpresstion(m, LENGTH);
                    //sectionsolidhorizontal.CrossSectionPositions.Add(posStart);
                    //sectionsolidhorizontal.CrossSectionPositions.Add(posEnd);

                    var crosssection = toolkit_factory.MakeCircleProfile(m, 40);
                    sectionsolidhorizontal.CrossSections.Add(crosssection);
                    sectionsolidhorizontal.CrossSections.Add(crosssection);
                    sectionsolidhorizontal.CrossSectionPositions.Add(toolkit_factory.MakeDistanceExpresstion(m, DISTANCE));
                    sectionsolidhorizontal.CrossSectionPositions.Add(toolkit_factory.MakeDistanceExpresstion(m, LENGTH));
                    sectionsolidhorizontal.FixedAxisVertical = true;

                    var styleitem = m.Instances.New <IfcStyledItem>(si =>
                    {
                        si.Item          = sectionsolidhorizontal;
                        var surfacestyle = m.Instances.New <IfcSurfaceStyle>(ss =>
                        {
                            var styleshading = m.Instances.New <IfcSurfaceStyleRendering>(ssr =>
                            {
                                var surfacecolor = m.Instances.New <IfcColourRgb>(cr =>
                                {
                                    cr.Red   = 0;
                                    cr.Green = 1;
                                    cr.Blue  = 0;
                                });
                                ssr.SurfaceColour = surfacecolor;
                                ssr.Transparency  = 0;
                            });
                            ss.Side = IfcSurfaceSide.POSITIVE;
                            ss.Styles.Add(styleshading);
                        });
                        si.Styles.Add(surfacestyle);
                    });
                    shaperepresentation.Items.Add(sectionsolidhorizontal);

                    a.Representation = m.Instances.New <IfcProductDefinitionShape>(pd => pd.Representations.Add(shaperepresentation));

                    /*IfcProductRepresentation PR = null;
                     * IfcShapeRepresentation rep = null;
                     * IfcSectionedSolidHorizontal ssh = null;
                     * ssh=toolkit_factory.CreateSolidShapeBaseOnCurve(m, alignCurve, 0, LENGTH);
                     * toolkit_factory.SetSurfaceColor(m, ssh, 0, 1, 0);
                     * rep.Items.Add(ssh);
                     * IfcGeometricRepresentationContext geocontext = null;
                     * geocontext.CoordinateSpaceDimension = 3;
                     * rep.ContextOfItems = geocontext;
                     * rep.RepresentationIdentifier = "Body";
                     * rep.RepresentationType = "AdvancedSweptSolid";
                     * PR.Representations.Add(rep);
                     * var PR = m.Instances.New<IfcShapeRepresentation>();
                     * m.Instances.Where(c => c is IfcProductRepresentation).FirstOrDefault();
                     * m.Instances.Where(c => c is IfcShapeRepresentation).FirstOrDefault();
                     * a.Representation = PR;*/
                });
                txn.Commit();
                return(align);
            }
        }
Beispiel #12
0
        public static void UpdateElementTransform(IfcStore _model, string projectNumber, string projectName)
        {
            DBOperation.beginTransaction();
            DBOperation.commitInterval = 5000;
            string      currStep        = string.Empty;
            BIMRLCommon _refBIMRLCommon = new BIMRLCommon();

            int commandStatus   = -1;
            int currInsertCount = 0;

            OracleCommand command = new OracleCommand(" ", DBOperation.DBConn);
            XbimMatrix3D  m3D     = new XbimMatrix3D();

            if (string.IsNullOrEmpty(projectName))
            {
                projectName = projectNumber + " - Federated";
            }

            string modelName;

            if (!string.IsNullOrEmpty(_model.FileName))
            {
                modelName = Path.GetFileNameWithoutExtension(_model.FileName);
            }
            else
            {
                modelName = projectNumber + " - " + projectName;
            }

            command.CommandText = "SELECT FEDERATEDID FROM bimrl_federatedmodel WHERE MODELNAME = '" + modelName + "' AND PROJECTNUMBER='" + projectNumber + "' AND PROJECTNAME='" + projectName + "'";
            object oFedID = command.ExecuteScalar();

            if (oFedID == null)
            {
                return;
            }

            int fedID = int.Parse(oFedID.ToString());

            command.CommandText = "SELECT ELEMENTID, LINENO FROM " + DBOperation.formatTabName("bimrl_element", fedID) + " WHERE GEOMETRYBODY IS NOT NULL";
            OracleDataReader reader = command.ExecuteReader();
            SortedDictionary <int, string> elemList = new SortedDictionary <int, string>();

            while (reader.Read())
            {
                string elemid = reader.GetString(0);
                int    lineNo = reader.GetInt32(1);
                elemList.Add(lineNo, elemid);
            }
            reader.Close();

            Xbim3DModelContext context = new Xbim3DModelContext(_model);

            foreach (KeyValuePair <int, string> elemListItem in elemList)
            {
                //IEnumerable<XbimGeometryData> geomDataList = _model.GetGeometryData(elemListItem.Key, XbimGeometryType.TriangulatedMesh);
                IIfcProduct product = _model.Instances[elemListItem.Key] as IIfcProduct;

                IEnumerable <XbimShapeInstance> shapeInstances = context.ShapeInstancesOf(product).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded);
                if (shapeInstances.Count() == 0)
                {
                    continue;    // SKip if the product has no geometry
                }
                XbimMeshGeometry3D     prodGeom  = new XbimMeshGeometry3D();
                IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstances.FirstOrDefault().ShapeGeometryLabel);
                //XbimModelExtensions.Read(prodGeom, shapeGeom.ShapeData, shapeInstances.FirstOrDefault().Transformation);

                //XbimGeometryData sdoGeomData = geomDataList.First();
                //m3D = sdoGeomData.Transform;
                //m3D = XbimMatrix3D.FromArray(sdoGeomData.DataArray2);       // Xbim 3.0 removes Tranform property
                m3D = shapeInstances.FirstOrDefault().Transformation;
                string sqlStmt = "update " + DBOperation.formatTabName("BIMRL_ELEMENT", fedID) + " set TRANSFORM_COL1=:1, TRANSFORM_COL2=:2, TRANSFORM_COL3=:3, TRANSFORM_COL4=:4"
                                 + " Where elementid = '" + elemListItem.Value + "'";
                // int status = DBOperation.updateGeometry(sqlStmt, sdoGeomData);
                currStep            = sqlStmt;
                command.CommandText = sqlStmt;

                try
                {
                    OracleParameter[] sdoGeom = new OracleParameter[4];
                    for (int i = 0; i < sdoGeom.Count(); ++i)
                    {
                        sdoGeom[i]             = command.Parameters.Add((i + 1).ToString(), OracleDbType.Object);
                        sdoGeom[i].Direction   = ParameterDirection.Input;
                        sdoGeom[i].UdtTypeName = "MDSYS.SDO_GEOMETRY";
                        sdoGeom[i].Size        = 1;
                    }

                    SdoGeometry trcol1 = new SdoGeometry();
                    trcol1.Dimensionality = 3;
                    trcol1.LRS            = 0;
                    trcol1.GeometryType   = (int)SdoGeometryTypes.GTYPE.POINT;
                    int      gType   = trcol1.PropertiesToGTYPE();
                    SdoPoint trcol1V = new SdoPoint();
                    trcol1V.XD       = m3D.M11;
                    trcol1V.YD       = m3D.M12;
                    trcol1V.ZD       = m3D.M13;
                    trcol1.SdoPoint  = trcol1V;
                    sdoGeom[1].Value = trcol1;

                    SdoGeometry trcol2 = new SdoGeometry();
                    trcol2.Dimensionality = 3;
                    trcol2.LRS            = 0;
                    trcol2.GeometryType   = (int)SdoGeometryTypes.GTYPE.POINT;
                    gType = trcol2.PropertiesToGTYPE();
                    SdoPoint trcol2V = new SdoPoint();
                    trcol2V.XD       = m3D.M21;
                    trcol2V.YD       = m3D.M22;
                    trcol2V.ZD       = m3D.M23;
                    trcol2.SdoPoint  = trcol2V;
                    sdoGeom[2].Value = trcol2;

                    SdoGeometry trcol3 = new SdoGeometry();
                    trcol3.Dimensionality = 3;
                    trcol3.LRS            = 0;
                    trcol3.GeometryType   = (int)SdoGeometryTypes.GTYPE.POINT;
                    gType = trcol3.PropertiesToGTYPE();
                    SdoPoint trcol3V = new SdoPoint();
                    trcol3V.XD       = m3D.M31;
                    trcol3V.YD       = m3D.M32;
                    trcol3V.ZD       = m3D.M33;
                    trcol3.SdoPoint  = trcol3V;
                    sdoGeom[3].Value = trcol3;

                    SdoGeometry trcol4 = new SdoGeometry();
                    trcol4.Dimensionality = 3;
                    trcol4.LRS            = 0;
                    trcol4.GeometryType   = (int)SdoGeometryTypes.GTYPE.POINT;
                    gType = trcol4.PropertiesToGTYPE();
                    SdoPoint trcol4V = new SdoPoint();
                    trcol4V.XD       = m3D.OffsetX;
                    trcol4V.YD       = m3D.OffsetY;
                    trcol4V.ZD       = m3D.OffsetZ;
                    trcol4.SdoPoint  = trcol4V;
                    sdoGeom[4].Value = trcol4;

                    commandStatus = command.ExecuteNonQuery();
                    command.Parameters.Clear();

                    currInsertCount++;

                    if (currInsertCount % DBOperation.commitInterval == 0)
                    {
                        //Do commit at interval but keep the long transaction (reopen)
                        DBOperation.commitTransaction();
                    }
                }
                catch (OracleException e)
                {
                    string excStr = "%%Error - " + e.Message + "\n\t" + currStep;
                    _refBIMRLCommon.StackPushError(excStr);
                    //command.Dispose();   // Log Oracle error and continue
                    command = new OracleCommand(" ", DBOperation.DBConn);
                    // throw;
                }
                catch (SystemException e)
                {
                    string excStr = "%%Insert Error - " + e.Message + "\n\t" + currStep;
                    _refBIMRLCommon.StackPushError(excStr);
                    throw;
                }

                DBOperation.commitTransaction();
                command.Dispose();
            }
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            if (args.Count() == 0 || args[0].Equals("-h"))
            {
                Console.WriteLine("Usage:");
                Console.WriteLine(" - The option below will load both model to BIMRL DB and compare them afterward:");
                Console.WriteLine("      BIMRLDiffModelCmd <DB connect string> -o <report json file> <the IFC file (New)> <the IFC file (Reference)> [<option file>]");
                Console.WriteLine(" - The option below will load the new model to BIMRL DB and compare it with the existing reference:");
                Console.WriteLine("      BIMRLDiffModelCmd <DB connect string> -o <report json file> -r <reference BIMRL model ID> <the IFC file (New)> [<option file>]");
                Console.WriteLine("  Supported file types: *.ifc|*.ifcxml|*.ifczip|*.xbimf");
                return;
            }

            if (!args[1].Equals("-o") && args.Length < 5)
            {
                Console.WriteLine("Usage: BIMRLDiffModelCmd <DB connect string> -o <report json file> <the IFC file(New)> <the IFC file(Reference)>");
                Console.WriteLine("   or: BIMRLDiffModelCmd <DB connect string> -o <report json file> -r <reference BIMRL model ID> <the IFC file (New)>");
                return;
            }

            string dbConnectStr = args[0];

            string[] conn = dbConnectStr.Split(new char[] { '/', '@' });
            if (conn.Count() < 3)
            {
                Console.WriteLine("%Error: Connection string is not in the right format. Use: <username>/<password>@<db>. For example: bimrl/bimrlpwd@pdborcl");
                return;
            }
            try
            {
                DBOperation.ConnectToDB(conn[0], conn[1], conn[2]);
            }
            catch
            {
                Console.WriteLine("%Error: Connection to DB Error");
                return;
            }

            string      newModelFile       = "";
            string      outputFileName     = args[2];
            string      outputFileFullPath = Path.GetFullPath(outputFileName);
            int         refModelID         = -1;
            int         newModelID         = -1;
            BIMRLCommon bimrlCommon        = new BIMRLCommon();

            DBOperation.UIMode = false;
            string optionFile = "";

            if (args[3].Equals("-r"))
            {
                if (!int.TryParse(args[4], out refModelID))
                {
                    Console.WriteLine("%Error: Referenced Model ID must be an integer number: " + args[4]);
                    return;
                }
                if (args.Count() < 6)
                {
                    Console.WriteLine("%Error: Missing IFC file name (New)!");
                    return;
                }

                // Check ID is a valid model ID in the DB
                BIMRLQueryModel bQM       = new BIMRLQueryModel(bimrlCommon);
                DataTable       modelInfo = bQM.checkModelExists(refModelID);
                if (modelInfo.Rows.Count == 0)
                {
                    Console.WriteLine("%Error: Referenced Model ID " + refModelID.ToString() + " does not exist in the DB, load it first!");
                    return;
                }

                newModelFile = args[5];
                if (!File.Exists(newModelFile))
                {
                    Console.WriteLine("%Error: New Model file is not found!");
                    return;
                }

                if (args.Count() >= 7)
                {
                    optionFile = args[6];
                }
            }
            else
            {
                string refModelFile = args[4];
                if (!File.Exists(refModelFile))
                {
                    Console.WriteLine("%Error: Referenced Model file is not found!");
                    return;
                }
                newModelFile = args[3];
                if (!File.Exists(newModelFile))
                {
                    Console.WriteLine("%Error: New Model file is not found!");
                    return;
                }

                // Load the referenced Model
                IfcStore refModel = LoadModel.OpenModel(refModelFile);
                if (refModel != null)
                {
                    refModelID = LoadModel.LoadModelToBIMRL(refModel);
                }

                if (refModel == null || refModelID == -1)
                {
                    Console.WriteLine("%Error: Load referenced Model " + refModelFile + " failed!");
                    return;
                }

                if (args.Count() >= 6)
                {
                    optionFile = args[5];
                }
            }

            // Load the new model
            IfcStore newModel = LoadModel.OpenModel(newModelFile);

            if (newModel != null)
            {
                newModelID = LoadModel.LoadModelToBIMRL(newModel);
            }

            if (newModel == null || newModelID == -1)
            {
                Console.WriteLine("%Error: Load referenced Model " + newModelFile + " failed!");
                return;
            }

            // Compare
            BIMRLDiffOptions options = new BIMRLDiffOptions();

            if (File.Exists(optionFile))
            {
                options = JsonConvert.DeserializeObject <BIMRLDiffOptions>(File.ReadAllText(optionFile));
                if (options == null)
                {
                    options = BIMRLDiffOptions.SelectAllOptions();
                }
            }
            else
            {
                options = BIMRLDiffOptions.SelectAllOptions();
            }

            // For the purpose of Model Diff, no enhanced BIMRL data processing is needed. This saves time and space.
            //   If the model requires the enhanced data, it can be done either load the model beforehand, or run the enhancement using BIMRL_ETLMain.XplorerPlugin UI
            DBOperation.OnepushETL = false;

            BIMRLDiffModels diffModels = new BIMRLDiffModels(newModelID, refModelID, bimrlCommon);

            diffModels.RunDiff(outputFileFullPath, options: options);
        }
 public SurfaceLayerStylerConfiguration(IfcStore model) : this()
 {
     Model = model;
     PopulateTree();
 }
        public override void Calculate()
        {
            //Find all ConceptRoots (example Slabs) in Model View

            //Filter IFC for ConceptRoots

            //Find all Concept in Model View and their referencing ConceptTemplate in Templates

            //save the TemplateRule(in Rules<Concept<Model View) information for further use

            //filter IFC for TemplateRule value


            Console.WriteLine(" 1 BEGIN");

            //get xbim-model of the ifc-file from the IfcParseNode
            Console.WriteLine(InputPorts[0].Data.GetType().ToString());

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

            if (IfcVersionType.Name == "ModelInfoIFC2x3")
            {
                var modelid = ((ModelInfoIFC2x3)(InputPorts[0].Data)).ModelId;
                List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> elementsids = ((ModelInfoIFC2x3)(InputPorts[0].Data)).ElementIds;
                if (modelid == null)
                {
                    return;
                }
                Console.WriteLine("modelid={0}", modelid);

                xModel = DataController.Instance.GetModel(modelid);

                /*
                 * foreach (IfcGloballyUniqueId uid in elementsids)
                 * {
                 *   Console.WriteLine(uid);
                 * }
                 */
                Console.WriteLine("elementsids.Count()={0}", elementsids.Count());  //-->1076

                var comboBox = ControlElements[2] as ComboBox;
                if (comboBox != null && comboBox.Items.Count > 0)
                {
                    comboBox.SelectedItem = -1;
                    comboBox.Items.Clear();
                }



                //Console.WriteLine("xModel.IfcSite.Count()={0}", IfcCount);

                /*
                 * foreach (IfcGloballyUniqueId el in elementsids)
                 * {
                 *  Console.WriteLine(el.ToString());
                 * }
                 */

                //outputInfo = new ModelInfo(modelid);
                //xModel = DataController.Instance.GetModel(modelid);

                Console.WriteLine(" 2 ");

                //get the mvd-file from the IfcMvdXMLReader
                MvdXMLReader mvd = (MvdXMLReader)InputPorts[1].Data;

                //We find all applicableEntities from all ConceptTemplates and all EntityNames from EntiryRules
                //The ifc-elements of these entity-types are going to be the output
                ChosenEntities = new HashSet <String>();

                Dictionary <string, ConceptTemplate> dict = mvd.templates.getConceptTemplates();

                Console.WriteLine("BEGIN");
                FindEntityNames(dict);
                Console.WriteLine("END");
                foreach (string s in ChosenEntities)
                {
                    Console.WriteLine(s);     //-->
                }


                // var ifcwindow = xModel.IfcProducts.OfType<Xbim.Ifc2x3.SharedBldgElements.IfcWindow>().ToList();
                var ifcLocalPlacement   = xModel.Instances.OfType <Xbim.Ifc2x3.GeometricConstraintResource.IfcLocalPlacement>().ToList();
                var ifcAxis2Placement3D = xModel.Instances.OfType <Xbim.Ifc2x3.GeometryResource.IfcAxis2Placement3D>().ToList();
                var ifcCartesianPoint   = xModel.Instances.OfType <Xbim.Ifc2x3.GeometryResource.IfcCartesianPoint>().ToList();
                var ifcDirection        = xModel.Instances.OfType <Xbim.Ifc2x3.GeometryResource.IfcDirection>().ToList();
                //there are Not in the IFC file
                var ifcRelNests = xModel.Instances.OfType <Xbim.Ifc2x3.Kernel.IfcRelNests>().ToList();
                //var ifcFlowDirectionEnum = xModel.Instances.OfType<Xbim.Ifc2x3.SharedBldgServiceElements.IfcFlowDirectionEnum>().ToList();
                // IfcDistributionSystemEnum --> NOT FOUND

                List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> IfcLocalPlacementFiltered    = new List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> IfcAxis2Placement3DFiltered  = new List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> IfcCartesianPointFiltered    = new List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> IfcDirectionFiltered         = new List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> IfcRelNestsFiltered          = new List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> IfcFlowDirectionEnumFiltered = new List <Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId> {
                };

                foreach (var item in ifcLocalPlacement)
                {
                    //IfcLocalPlacementFiltered.Add(item.GlobalId);
                }
            }
            else if (IfcVersionType.Name == "ModelInfoIFC4")
            {
                var modelid = ((ModelInfoIFC4)(InputPorts[0].Data)).ModelId;
                List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> elementsids = ((ModelInfoIFC4)(InputPorts[0].Data)).ElementIds;
                if (modelid == null)
                {
                    return;
                }
                Console.WriteLine("modelid={0}", modelid);

                xModel = DataController.Instance.GetModel(modelid);

                /*
                 * foreach (IfcGloballyUniqueId uid in elementsids)
                 * {
                 *   Console.WriteLine(uid);
                 * }
                 */
                Console.WriteLine("elementsids.Count()={0}", elementsids.Count());  //-->1076

                var comboBox = ControlElements[2] as ComboBox;
                if (comboBox != null && comboBox.Items.Count > 0)
                {
                    comboBox.SelectedItem = -1;
                    comboBox.Items.Clear();
                }


                //Console.WriteLine("xModel.IfcSite.Count()={0}", IfcCount);

                /*
                 * foreach (IfcGloballyUniqueId el in elementsids)
                 * {
                 *  Console.WriteLine(el.ToString());
                 * }
                 */

                //outputInfo = new ModelInfo(modelid);
                //xModel = DataController.Instance.GetModel(modelid);

                Console.WriteLine(" 2 ");

                //get the mvd-file from the IfcMvdXMLReader
                MvdXMLReader mvd = (MvdXMLReader)InputPorts[1].Data;

                //We find all applicableEntities from all ConceptTemplates and all EntityNames from EntiryRules
                //The ifc-elements of these entity-types are going to be the output
                ChosenEntities = new HashSet <String>();

                Dictionary <string, ConceptTemplate> dict = mvd.templates.getConceptTemplates();

                Console.WriteLine("BEGIN");
                FindEntityNames(dict);
                Console.WriteLine("END");
                foreach (string s in ChosenEntities)
                {
                    Console.WriteLine(s);     //-->
                }


                // var ifcwindow = xModel.IfcProducts.OfType<Xbim.Ifc4.SharedBldgElements.IfcWindow>().ToList();
                var ifcLocalPlacement   = xModel.Instances.OfType <Xbim.Ifc4.GeometricConstraintResource.IfcLocalPlacement>().ToList();
                var ifcAxis2Placement3D = xModel.Instances.OfType <Xbim.Ifc4.GeometryResource.IfcAxis2Placement3D>().ToList();
                var ifcCartesianPoint   = xModel.Instances.OfType <Xbim.Ifc4.GeometryResource.IfcCartesianPoint>().ToList();
                var ifcDirection        = xModel.Instances.OfType <Xbim.Ifc4.GeometryResource.IfcDirection>().ToList();
                //there are Not in the IFC file
                var ifcRelNests = xModel.Instances.OfType <Xbim.Ifc4.Kernel.IfcRelNests>().ToList();
                //var ifcFlowDirectionEnum = xModel.Instances.OfType<Xbim.Ifc4.SharedBldgServiceElements.IfcFlowDirectionEnum>().ToList();
                // IfcDistributionSystemEnum --> NOT FOUND

                List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> IfcLocalPlacementFiltered    = new List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> IfcAxis2Placement3DFiltered  = new List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> IfcCartesianPointFiltered    = new List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> IfcDirectionFiltered         = new List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> IfcRelNestsFiltered          = new List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> {
                };
                List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> IfcFlowDirectionEnumFiltered = new List <Xbim.Ifc4.UtilityResource.IfcGloballyUniqueId> {
                };

                foreach (var item in ifcLocalPlacement)
                {
                    //IfcLocalPlacementFiltered.Add(item.GlobalId);
                }
            }
        }
Beispiel #16
0
        public void IfcStoreCreateStoreTest()
        {
            var credentials = new XbimEditorCredentials
            {
                ApplicationIdentifier     = "XbimTest1",
                ApplicationDevelopersName = "Tester",
                EditorsOrganisationName   = "XbimTeam"
            };

            using (var store = IfcStore.Create(credentials, XbimSchemaVersion.Ifc2X3, XbimStoreType.EsentDatabase))
            {
                using (var txn = store.BeginTransaction())
                {
                    var door = store.Instances.New <IfcDoor>();
                    door.Name = "Door 1";
                    txn.Commit();
                }
                store.SaveAs("esent2x3.ifc");
                store.Close();
            }
            using (var store = IfcStore.Create(credentials, XbimSchemaVersion.Ifc4, XbimStoreType.EsentDatabase))
            {
                using (var txn = store.BeginTransaction())
                {
                    var door = store.Instances.New <Ifc4.SharedBldgElements.IfcDoor>();
                    door.Name = "Door 1";
                    txn.Commit();
                }
                store.SaveAs("esent4.ifc");
                store.Close();
            }

            using (var store = IfcStore.Create(credentials, XbimSchemaVersion.Ifc2X3, XbimStoreType.InMemoryModel))
            {
                using (var txn = store.BeginTransaction())
                {
                    var door = store.Instances.New <IfcDoor>();
                    door.Name = "Door 1";
                    txn.Commit();
                }
                store.SaveAs("Memory2X3.ifc");
                store.Close();
            }

            using (var store = IfcStore.Create(credentials, XbimSchemaVersion.Ifc4, XbimStoreType.InMemoryModel))
            {
                using (var txn = store.BeginTransaction())
                {
                    var door = store.Instances.New <Ifc4.SharedBldgElements.IfcDoor>();
                    door.Name = "Door 1";
                    txn.Commit();
                }
                store.SaveAs("Memory4.ifc");
                store.Close();
            }

            var modelStore    = new HeuristicModelProvider();
            var schemaVersion = modelStore.GetXbimSchemaVersion("Esent2X3.ifc");

            Assert.IsTrue(schemaVersion == XbimSchemaVersion.Ifc2X3);
            schemaVersion = modelStore.GetXbimSchemaVersion("Esent4.ifc");
            Assert.IsTrue(schemaVersion == XbimSchemaVersion.Ifc4);
            schemaVersion = modelStore.GetXbimSchemaVersion("Memory2X3.ifc");
            Assert.IsTrue(schemaVersion == XbimSchemaVersion.Ifc2X3);
            schemaVersion = modelStore.GetXbimSchemaVersion("Memory4.ifc");
            Assert.IsTrue(schemaVersion == XbimSchemaVersion.Ifc4);
        }
Beispiel #17
0
 public IfcGroupsViewModel(IfcStore model)
 {
     _model = model;
 }
Beispiel #18
0
 public ModelOptions(IfcStore model, Model_info.Environment environment)
 {
     Model            = model;
     this.Environment = environment;
 }
Beispiel #19
0
 protected virtual IfcProductDefinitionShape CreateRepresentations(IfcStore model)
 {
     return(model.Instances.New <IfcProductDefinitionShape>());
 }
Beispiel #20
0
 public override List <IfcBuildingElement> ToBuildingElementIfc(IfcStore model)
 {
     throw new ArgumentException("Rebars should be converted to IfcReinforcingElement");
 }
Beispiel #21
0
        private static IfcStore GetModel(string fileName)
        {
            IfcStore openModel = null;
            var      extension = Path.GetExtension(fileName);

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

            if (!File.Exists(fileName))
            {
                return(null);
            }

            extension = Path.GetExtension(fileName);
            if (string.Compare(extension, ".xbim", StringComparison.OrdinalIgnoreCase) == 0) //just open xbim
            {
                try
                {
                    Console.WriteLine("Opening " + fileName);
                    var model = IfcStore.Open(fileName);
                    //delete any geometry
                    openModel = model;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unable to open model {0}, {1}", fileName, e.Message);
                    Console.WriteLine("Unable to open model {0}, {1}", fileName, e.Message);
                }
            }
            else     //we need to create the xBIM file
            {
                try
                {
                    Console.WriteLine("Creating " + Path.GetFileNameWithoutExtension(fileName));
                    openModel = IfcStore.Open(fileName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unable to open model {0}, {1}", fileName, e.Message);
                    Console.WriteLine("Unable to open model {0}, {1}", fileName, e.Message);
                }
            }
            return(openModel);
        }
Beispiel #22
0
        public override List <IfcReinforcingElement> ToReinforcingElementIfc(IfcStore model)
        {
            using (var transaction = model.BeginTransaction("Create Mesh Element"))
            {
                var rebars = new List <IfcReinforcingElement>();

                switch (SpacingType)
                {
                case RebarSpacingType.NormalSpacing:
                {
                    MeshFaceList             faces                 = OriginRebarShape.RebarMesh.Faces;
                    MeshVertexList           vertices              = OriginRebarShape.RebarMesh.Vertices;
                    List <IfcCartesianPoint> ifcVertices           = IfcTools.VerticesToIfcCartesianPoints(model, vertices);
                    IfcFaceBasedSurfaceModel faceBasedSurfaceModel =
                        IfcTools.CreateIfcFaceBasedSurfaceModel(model, faces, ifcVertices);
                    var shape = IfcTools.CreateIfcShapeRepresentation(model, "Mesh");
                    shape.Items.Add(faceBasedSurfaceModel);
                    var ifcRelAssociatesMaterial = IfcTools.CreateIfcRelAssociatesMaterial(model, Material.Name, Material.Grade);

                    foreach (var insertPlane in RebarInsertPlanes)
                    {
                        var rebar = model.Instances.New <IfcReinforcingBar>();
                        rebar.Name            = "Rebar";
                        rebar.NominalDiameter = Diameter;
                        rebar.BarLength       = (int)Math.Round(OriginRebarShape.RebarCurve.GetLength());
                        rebar.SteelGrade      = Material.Grade;

                        IfcTools.ApplyRepresentationAndPlacement(model, rebar, shape, insertPlane);

                        ifcRelAssociatesMaterial.RelatedObjects.Add(rebar);

                        rebars.Add(rebar);
                    }

                    break;
                }

                case RebarSpacingType.CustomSpacing:

                    for (int i = 0; i < RebarGroupMesh.Count; i++)
                    {
                        MeshFaceList             faces                 = RebarGroupMesh[i].Faces;
                        MeshVertexList           vertices              = RebarGroupMesh[i].Vertices;
                        List <IfcCartesianPoint> ifcVertices           = IfcTools.VerticesToIfcCartesianPoints(model, vertices);
                        IfcFaceBasedSurfaceModel faceBasedSurfaceModel =
                            IfcTools.CreateIfcFaceBasedSurfaceModel(model, faces, ifcVertices);
                        var shape = IfcTools.CreateIfcShapeRepresentation(model, "Mesh");
                        shape.Items.Add(faceBasedSurfaceModel);
                        var ifcRelAssociatesMaterial = IfcTools.CreateIfcRelAssociatesMaterial(model, Material.Name, Material.Grade);

                        var rebar = model.Instances.New <IfcReinforcingBar>();
                        rebar.Name            = "Rebar";
                        rebar.NominalDiameter = Diameter;
                        rebar.BarLength       = (int)Math.Round(RebarGroupCurves[i].GetLength());
                        rebar.SteelGrade      = Material.Grade;

                        IfcTools.ApplyRepresentationAndPlacement(model, rebar, shape, Plane.WorldXY);

                        ifcRelAssociatesMaterial.RelatedObjects.Add(rebar);

                        rebars.Add(rebar);
                    }

                    break;

                default:
                    throw new ArgumentException("Spacing type not recognized");
                }


                transaction.Commit();

                return(rebars);
            }
        }
        public static void ResolveQuantitySet(IfcStore ifcStore)
        {
            Dictionary <IfcObject, List <IfcPropertySet> > qSetsByIfcObject = new Dictionary <IfcObject, List <IfcPropertySet> >();

            using (var txn = ifcStore.BeginTransaction("QuantitySet Creation Ifc2x3"))
            {
                List <IIfcRelDefinesByProperties> relProps = ifcStore.Instances.OfType <IIfcRelDefinesByProperties>()
                                                             .Where(relProp => relProp.RelatingPropertyDefinition.Name.ToString().Contains("BaseQuantities")).ToList();

                foreach (IIfcRelDefinesByProperties relProp in relProps)
                {
                    IEnumerable <IIfcRelDefinesByProperties> propertyDefinitionOf = relProp.RelatingPropertyDefinition.PropertyDefinitionOf;

                    foreach (IIfcRelDefinesByProperties relation in propertyDefinitionOf)
                    {
                        if (relation.RelatingPropertyDefinition is IIfcElementQuantity)
                        {
                            IIfcElementQuantity qset = (IIfcElementQuantity)relation.RelatingPropertyDefinition;

                            IfcPropertySet pset = ifcStore.Instances.New <IfcPropertySet>(pSet =>
                            {
                                pSet.Name = qset.Name.ToString().StartsWith("Qto_")
                                           ? "LIBAL_" + qset.Name.ToString()
                                       : "LIBAL_Qto_" + qset.Name.ToString();

                                Xbim.Common.IItemSet <IIfcPhysicalQuantity> quantities = qset.Quantities;
                                foreach (IIfcPhysicalQuantity quan in quantities)
                                {
                                    var value = resolveValue(quan);
                                    var unit  = resolveUnit(quan);
                                    var name  = quan.Name.ToString();

                                    if (value != null)
                                    {
                                        pSet.HasProperties.Add(ifcStore.Instances.New <IfcPropertySingleValue>(p =>
                                        {
                                            p.Name         = name;
                                            p.NominalValue = value;
                                            p.Unit         = unit;
                                        }));
                                    }
                                }
                            });

                            Xbim.Common.IItemSet <IIfcObject> relatedObjects = relation.RelatedObjects;

                            foreach (IfcObject ifcObject in relatedObjects)
                            {
                                if (!qSetsByIfcObject.ContainsKey(ifcObject))
                                {
                                    qSetsByIfcObject.Add(ifcObject, new List <IfcPropertySet>());
                                }

                                List <IfcPropertySet> psets = qSetsByIfcObject[ifcObject];
                                psets.Add(pset);
                            }
                        }
                    }
                }

                txn.Commit();
            }

            using (var txn = ifcStore.BeginTransaction("QuantitySet Reference Creation Ifc2x3"))
            {
                foreach (IfcObject key in qSetsByIfcObject.Keys)
                {
                    List <IfcPropertySet> psets = qSetsByIfcObject[key];

                    foreach (IfcPropertySet pset in psets)
                    {
                        var pSetRel = ifcStore.Instances.New <IfcRelDefinesByProperties>(r =>
                        {
                            r.RelatingPropertyDefinition = pset;
                        });
                        pSetRel.RelatedObjects.Add(key);
                    }
                }

                txn.Commit();
            }
        }
        }     //打开一个openfiledialog,并获取选择的文件名

        public static IfcStore FederationFromDialogbox(string[] files)
        {
            IfcStore fedModel = null;

            if (files == null || files.Length == 0)
            {
                return(fedModel);
            }
            else
            {
                //use the first filename it's extension to decide which action should happen
                var s = System.IO.Path.GetExtension(files[0]);
                //if (s == null) return ifcStore;
                var firstExtension = s.ToLower();
                if (firstExtension == ".ifc")
                {
                    // create temp file as a placeholder for the temporory xbim file
                    fedModel = IfcStore.Create(null, XbimSchemaVersion.Ifc2X3, XbimStoreType.InMemoryModel);
                    using (var txn = fedModel.BeginTransaction())
                    {
                        var project = fedModel.Instances.New <Xbim.Ifc2x3.Kernel.IfcProject>();
                        project.Name = "默认项目名称";
                        project.Initialize(ProjectUnits.SIUnitsUK);
                        txn.Commit();
                    }
                    var informUser = true;
                    for (var i = 0; i < files.Length; i++)
                    {
                        var fileName           = files[i];
                        var temporaryReference = new XbimReferencedModelViewModel
                        {
                            Name             = fileName,
                            OrganisationName = "机构 " + i,
                            OrganisationRole = "未定义"
                        };

                        var       buildRes  = false;
                        Exception exception = null;
                        try
                        {
                            buildRes = temporaryReference.TryBuildAndAddTo(fedModel);  //验证所有数据并创建模型。
                        }
                        catch (Exception ex)
                        {
                            //usually an EsentDatabaseSharingViolationException, user needs to close db first
                            exception = ex;
                        }

                        if (buildRes || !informUser)
                        {
                            continue;
                        }
                        var msg = exception == null ? "" : "\r\nMessage: " + exception.Message;
                        var res = MessageBox.Show(fileName + " couldn't be opened." + msg + "\r\nShow this message again?",
                                                  "Failed to open a file", MessageBoxButton.YesNoCancel, MessageBoxImage.Error);
                        if (res == MessageBoxResult.No)
                        {
                            informUser = false;
                        }
                        else if (res == MessageBoxResult.Cancel)
                        {
                            fedModel = null;
                        }
                        //return fedModel;
                    }
                }
            }
            return(fedModel);
        }
Beispiel #25
0
        /// <summary>
        /// This creates a wall and it's geometry, many geometric representations are possible and extruded rectangular footprint is chosen as this is commonly used for standard case walls
        /// </summary>
        /// <param name="model"></param>
        /// <param name="length">Length of the rectangular footprint</param>
        /// <param name="width">Width of the rectangular footprint (width of the wall)</param>
        /// <param name="height">Height to extrude the wall, extrusion is vertical</param>
        /// <returns></returns>
        static private IfcWallStandardCase CreateWall(IfcStore model, double length, double width, double height)
        {
            //
            //begin a transaction
            using (var txn = model.BeginTransaction("Create Wall"))
            {
                var wall = model.Instances.New <IfcWallStandardCase>();
                wall.Name = "A Standard rectangular wall";

                //represent wall as a rectangular profile
                var rectProf = model.Instances.New <IfcRectangleProfileDef>();
                rectProf.ProfileType = IfcProfileTypeEnum.AREA;
                rectProf.XDim        = width;
                rectProf.YDim        = length;

                var insertPoint = model.Instances.New <IfcCartesianPoint>();
                insertPoint.SetXY(0, 400); //insert at arbitrary position
                rectProf.Position          = model.Instances.New <IfcAxis2Placement2D>();
                rectProf.Position.Location = insertPoint;

                //model as a swept area solid
                var body = model.Instances.New <IfcExtrudedAreaSolid>();
                body.Depth             = height;
                body.SweptArea         = rectProf;
                body.ExtrudedDirection = model.Instances.New <IfcDirection>();
                body.ExtrudedDirection.SetXYZ(0, 0, 1);

                //parameters to insert the geometry in the model
                var origin = model.Instances.New <IfcCartesianPoint>();
                origin.SetXYZ(0, 0, 0);
                body.Position          = model.Instances.New <IfcAxis2Placement3D>();
                body.Position.Location = origin;

                //Create a Definition shape to hold the geometry
                var shape        = model.Instances.New <IfcShapeRepresentation>();
                var modelContext = model.Instances.OfType <IfcGeometricRepresentationContext>().FirstOrDefault();
                shape.ContextOfItems           = modelContext;
                shape.RepresentationType       = "SweptSolid";
                shape.RepresentationIdentifier = "Body";
                shape.Items.Add(body);

                //Create a Product Definition and add the model geometry to the wall
                var rep = model.Instances.New <IfcProductDefinitionShape>();
                rep.Representations.Add(shape);
                wall.Representation = rep;

                //now place the wall into the model
                var lp   = model.Instances.New <IfcLocalPlacement>();
                var ax3D = model.Instances.New <IfcAxis2Placement3D>();
                ax3D.Location     = origin;
                ax3D.RefDirection = model.Instances.New <IfcDirection>();
                ax3D.RefDirection.SetXYZ(0, 1, 0);
                ax3D.Axis = model.Instances.New <IfcDirection>();
                ax3D.Axis.SetXYZ(0, 0, 1);
                lp.RelativePlacement = ax3D;
                wall.ObjectPlacement = lp;


                // Where Clause: The IfcWallStandard relies on the provision of an IfcMaterialLayerSetUsage
                var ifcMaterialLayerSetUsage = model.Instances.New <IfcMaterialLayerSetUsage>();
                var ifcMaterialLayerSet      = model.Instances.New <IfcMaterialLayerSet>();
                var ifcMaterialLayer         = model.Instances.New <IfcMaterialLayer>();
                ifcMaterialLayer.LayerThickness = 10;
                ifcMaterialLayerSet.MaterialLayers.Add(ifcMaterialLayer);
                ifcMaterialLayerSetUsage.ForLayerSet             = ifcMaterialLayerSet;
                ifcMaterialLayerSetUsage.LayerSetDirection       = IfcLayerSetDirectionEnum.AXIS2;
                ifcMaterialLayerSetUsage.DirectionSense          = IfcDirectionSenseEnum.NEGATIVE;
                ifcMaterialLayerSetUsage.OffsetFromReferenceLine = 150;

                // Add material to wall
                var material = model.Instances.New <IfcMaterial>();
                material.Name = "some material";
                var ifcRelAssociatesMaterial = model.Instances.New <IfcRelAssociatesMaterial>();
                ifcRelAssociatesMaterial.RelatingMaterial = material;
                ifcRelAssociatesMaterial.RelatedObjects.Add(wall);

                ifcRelAssociatesMaterial.RelatingMaterial = ifcMaterialLayerSetUsage;

                // IfcPresentationLayerAssignment is required for CAD presentation in IfcWall or IfcWallStandardCase
                var ifcPresentationLayerAssignment = model.Instances.New <IfcPresentationLayerAssignment>();
                ifcPresentationLayerAssignment.Name = "some ifcPresentationLayerAssignment";
                ifcPresentationLayerAssignment.AssignedItems.Add(shape);


                // linear segment as IfcPolyline with two points is required for IfcWall
                var ifcPolyline = model.Instances.New <IfcPolyline>();
                var startPoint  = model.Instances.New <IfcCartesianPoint>();
                startPoint.SetXY(0, 0);
                var endPoint = model.Instances.New <IfcCartesianPoint>();
                endPoint.SetXY(4000, 0);
                ifcPolyline.Points.Add(startPoint);
                ifcPolyline.Points.Add(endPoint);

                var shape2D = model.Instances.New <IfcShapeRepresentation>();
                shape2D.ContextOfItems           = modelContext;
                shape2D.RepresentationIdentifier = "Axis";
                shape2D.RepresentationType       = "Curve2D";
                shape2D.Items.Add(ifcPolyline);
                rep.Representations.Add(shape2D);
                txn.Commit();
                return(wall);
            }
        }
Beispiel #26
0
        public Ifc(List <ElementGroup> elementGroups, string projectName, string buildingName, string path)
        {
            using (IfcStore model = CreateAndInitModel(projectName))
            {
                if (model != null)
                {
                    IfcBuilding building = CreateBuilding(model, buildingName);

                    foreach (var elementGroup in elementGroups)
                    {
                        switch (elementGroup.ElementType)
                        {
                        case ElementType.PadFooting:
                        case ElementType.StripFooting:
                        case ElementType.Beam:
                        case ElementType.Column:
                        {
                            List <IfcBuildingElement> currentElementGroup = elementGroup.ToBuildingElementIfc(model);
                            foreach (var buildingElement in currentElementGroup)
                            {
                                using (var transaction = model.BeginTransaction("Add element"))
                                {
                                    building.AddElement(buildingElement);
                                    transaction.Commit();
                                }
                            }

                            break;
                        }

                        case ElementType.Rebar:
                        {
                            List <IfcReinforcingElement> currentElementGroup = elementGroup.ToReinforcingElementIfc(model);
                            foreach (var buildingElement in currentElementGroup)
                            {
                                using (var transaction = model.BeginTransaction("Add element"))
                                {
                                    building.AddElement(buildingElement);
                                    transaction.Commit();
                                }
                            }

                            break;
                        }

                        default:
                            throw new ArgumentException("Unknown element type");
                        }
                    }

                    if (path.Substring(path.Length - 4) != ".ifc")
                    {
                        throw new ArgumentException("Path should end up with .ifc");
                    }

                    try
                    {
                        model.SaveAs(path, StorageType.Ifc);
                    }
                    catch (Exception e)
                    {
                        throw new ArgumentException("Couldn't save the file. " + e);
                    }
                }
            }
        }
Beispiel #27
0
        private static void CreateElementQuantity(IfcStore model, IfcWallStandardCase wall)
        {
            //Create a IfcElementQuantity
            //first we need a IfcPhysicalSimpleQuantity,first will use IfcQuantityLength
            var ifcQuantityArea = model.Instances.New <IfcQuantityLength>(qa =>
            {
                qa.Name        = "IfcQuantityArea:Area";
                qa.Description = "";
                qa.Unit        = model.Instances.New <IfcSIUnit>(siu =>
                {
                    siu.UnitType = IfcUnitEnum.LENGTHUNIT;
                    siu.Prefix   = IfcSIPrefix.MILLI;
                    siu.Name     = IfcSIUnitName.METRE;
                });
                qa.LengthValue = 100.0;
            });
            //next quantity IfcQuantityCount using IfcContextDependentUnit
            var ifcContextDependentUnit = model.Instances.New <IfcContextDependentUnit>(cd =>
            {
                cd.Dimensions = model.Instances.New <IfcDimensionalExponents>(de =>
                {
                    de.LengthExponent                   = 1;
                    de.MassExponent                     = 0;
                    de.TimeExponent                     = 0;
                    de.ElectricCurrentExponent          = 0;
                    de.ThermodynamicTemperatureExponent = 0;
                    de.AmountOfSubstanceExponent        = 0;
                    de.LuminousIntensityExponent        = 0;
                });
                cd.UnitType = IfcUnitEnum.LENGTHUNIT;
                cd.Name     = "Elephants";
            });
            var ifcQuantityCount = model.Instances.New <IfcQuantityCount>(qc =>
            {
                qc.Name       = "IfcQuantityCount:Elephant";
                qc.CountValue = 12;
                qc.Unit       = ifcContextDependentUnit;
            });


            //next quantity IfcQuantityLength using IfcConversionBasedUnit
            var ifcConversionBasedUnit = model.Instances.New <IfcConversionBasedUnit>(cbu =>
            {
                cbu.ConversionFactor = model.Instances.New <IfcMeasureWithUnit>(mu =>
                {
                    mu.ValueComponent = new IfcRatioMeasure(25.4);
                    mu.UnitComponent  = model.Instances.New <IfcSIUnit>(siu =>
                    {
                        siu.UnitType = IfcUnitEnum.LENGTHUNIT;
                        siu.Prefix   = IfcSIPrefix.MILLI;
                        siu.Name     = IfcSIUnitName.METRE;
                    });
                });
                cbu.Dimensions = model.Instances.New <IfcDimensionalExponents>(de =>
                {
                    de.LengthExponent                   = 1;
                    de.MassExponent                     = 0;
                    de.TimeExponent                     = 0;
                    de.ElectricCurrentExponent          = 0;
                    de.ThermodynamicTemperatureExponent = 0;
                    de.AmountOfSubstanceExponent        = 0;
                    de.LuminousIntensityExponent        = 0;
                });
                cbu.UnitType = IfcUnitEnum.LENGTHUNIT;
                cbu.Name     = "Inch";
            });
            var ifcQuantityLength = model.Instances.New <IfcQuantityLength>(qa =>
            {
                qa.Name        = "IfcQuantityLength:Length";
                qa.Description = "";
                qa.Unit        = ifcConversionBasedUnit;
                qa.LengthValue = 24.0;
            });

            //lets create the IfcElementQuantity
            var ifcElementQuantity = model.Instances.New <IfcElementQuantity>(eq =>
            {
                eq.Name        = "Test:IfcElementQuantity";
                eq.Description = "Measurement quantity";
                eq.Quantities.Add(ifcQuantityArea);
                eq.Quantities.Add(ifcQuantityCount);
                eq.Quantities.Add(ifcQuantityLength);
            });

            //need to create the relationship
            model.Instances.New <IfcRelDefinesByProperties>(rdbp =>
            {
                rdbp.Name        = "Area Association";
                rdbp.Description = "IfcElementQuantity associated to wall";
                rdbp.RelatedObjects.Add(wall);
                rdbp.RelatingPropertyDefinition = ifcElementQuantity;
            });
        }
Beispiel #28
0
        private void CreateWorker()
        {
            _worker = new BackgroundWorker
            {
                WorkerReportsProgress      = true,
                WorkerSupportsCancellation = true
            };
            _worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
            {
                ActivityProgress = args.ProgressPercentage;
                ActivityStatus   = (string)args.UserState;
                Debug.WriteLine("{0}% {1}", args.ProgressPercentage, (string)args.UserState);
            };

            _worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
            {
                if (args.Result is IfcStore) //all ok
                {
                    _model           = args.Result as IfcStore;
                    ActivityProgress = 0;
                    // prepare the facility
                    SubmissionFacility = FacilityFromIfcConverter.FacilityFromModel(_model);

                    if (SubmissionFacility == null)
                    {
                        return;
                    }
                    var jsonFileName = Path.ChangeExtension(SubmissionFileSource, "json");
                    if (!File.Exists(jsonFileName))
                    {
                        SubmissionFacility.WriteJson(jsonFileName);
                    }

                    ValidateLoadedFacilities();
                }
                else if (args.Result is Facility) //all ok; this is the model facility
                {
                    ValidateLoadedFacilities();
                }
                else //we have a problem
                {
                    var errMsg = args.Result as String;
                    if (!string.IsNullOrEmpty(errMsg))
                    {
                        ActivityStatus = "Error Opening File";
                    }
                    if (args.Result is Exception)
                    {
                        var sb     = new StringBuilder();
                        var ex     = args.Result as Exception;
                        var indent = "";
                        while (ex != null)
                        {
                            sb.AppendFormat("{0}{1}\n", indent, ex.Message);
                            ex      = ex.InnerException;
                            indent += "\t";
                        }
                        ActivityStatus = "Error Opening Ifc File\r\n\r\n" + sb;
                    }
                    ActivityProgress = 0;
                    ActivityStatus   = "Error/Ready";
                }
            };
        }
        private IfcSlab CreateIfcSlab(IfcStore model, Slab cadSlab)
        {
            //cadSlab.Length *= 1000;
            //cadSlab.Width *= 1000;
            //cadSlab.Thickness *= 1000;
            //cadSlab.CenterPt.X *= 1000;
            //cadSlab.CenterPt.Y *= 1000;

            //cadSlab.PtLengthDir.X *= 1000;
            //cadSlab.PtLengthDir.Y *= 1000;
            //
            double length = cadSlab.Length;
            double width  = cadSlab.Width;

            //begin a transaction
            using (ITransaction trans = model.BeginTransaction("Create Slab"))
            {
                IfcSlab slabToCreate = model.Instances.New <IfcSlab>();
                slabToCreate.Name = " Slab - Slab:UC305x305x97:" + random.Next(1000, 10000);

                //represent Element as a rectangular profile
                IfcRectangleProfileDef rectProf = IFCHelper.RectProfileCreate(model, length, width);

                //Profile insertion point
                rectProf.ProfileInsertionPointSet(model, 0, 0);


                //model as a swept area solid
                IfcDirection extrusionDir = model.Instances.New <IfcDirection>();
                extrusionDir.SetXYZ(0, 0, -1);

                IfcExtrudedAreaSolid body = IFCHelper.ProfileSweptSolidCreate(model, cadSlab.Thickness, rectProf, extrusionDir);


                //parameters to insert the geometry in the model
                body.BodyPlacementSet(model, 0, 0, 0);


                //Create a Definition shape to hold the geometry
                IfcShapeRepresentation shape = IFCHelper.ShapeRepresentationCreate(model, "SweptSolid", "Body");
                shape.Items.Add(body);



                //Create a Product Definition and add the model geometry to the wall
                IfcProductDefinitionShape prDefRep = model.Instances.New <IfcProductDefinitionShape>();
                prDefRep.Representations.Add(shape);
                slabToCreate.Representation = prDefRep;

                //Create Local axes system and assign it to the column
                IfcCartesianPoint location3D = model.Instances.New <IfcCartesianPoint>();
                location3D.SetXYZ(cadSlab.CenterPt.X, cadSlab.CenterPt.Y, cadSlab.CenterPt.Z);

                var uvColLongDir = MathHelper.UnitVectorFromPt1ToPt2(cadSlab.CenterPt, cadSlab.PtLengthDir);

                IfcDirection localXDir = model.Instances.New <IfcDirection>();
                localXDir.SetXYZ(uvColLongDir.X, uvColLongDir.Y, uvColLongDir.Z);

                IfcDirection localZDir = model.Instances.New <IfcDirection>();
                localZDir.SetXYZ(0, 0, 1);

                IfcAxis2Placement3D ax3D = IFCHelper.LocalAxesSystemCreate(model, location3D, localXDir, localZDir);

                //now place the slab into the model
                IfcLocalPlacement lp = IFCHelper.LocalPlacemetCreate(model, ax3D);
                slabToCreate.ObjectPlacement = lp;


                trans.Commit();
                return(slabToCreate);
            }
        }
        public static void AttachSpaceProperties()
        {
            var editor = new XbimEditorCredentials
            {
                ApplicationDevelopersName = "xbim developer",
                ApplicationFullName       = "xbim toolkit",
                ApplicationIdentifier     = "xbim",
                ApplicationVersion        = "4.0",
                EditorsFamilyName         = "Santini Aichel",
                EditorsGivenName          = "Johann Blasius",
                EditorsOrganisationName   = "Independent Architecture"
            };

            using (var model = IfcStore.Create(editor, Xbim.Common.Step21.XbimSchemaVersion.Ifc4, XbimStoreType.InMemoryModel))
            {
                using (var cache = model.BeginInverseCaching())
                {
                    // do all analytics to keep fast search indices
                }

                var i = model.Instances;
                using (var txn = model.BeginTransaction("Spaces creation"))
                {
                    // create 100 testing spaces
                    var spaces = Enumerable.Range(1, 100)
                                 .Select(n => i.New <IfcSpace>(s => s.Name = $"Space {n:D3}"))
                                 .ToList();

                    var psetNames = Enumerable.Range(0, 100)
                                    .Select(n => $"XBIM_Automated_Test_{n:D3}")
                                    .ToList();
                    var pNames = Enumerable.Range(0, 100)
                                 .Select(n => $"Property {n:D3}")
                                 .ToList();
                    var pValues = Enumerable.Range(0, 100)
                                  .Select(n => $"Value {n:D3}")
                                  .ToList();
                    var pNameValue = pNames
                                     .Zip(pValues, (n, v) => (new { name = n, value = v }))
                                     .ToList();

                    // start measuring the time
                    var w = Stopwatch.StartNew();
                    foreach (var space in spaces)
                    {
                        foreach (var psetName in psetNames)
                        {
                            var properties = pNameValue
                                             .Select(property => i.New <IfcPropertySingleValue>(p =>
                            {
                                p.Name         = property.name;
                                p.NominalValue = new IfcLabel(property.value);
                            }))
                                             .ToList();
                            i.New <IfcRelDefinesByProperties>(r =>
                            {
                                r.RelatedObjects.Add(space);
                                r.RelatingPropertyDefinition = i.New <IfcPropertySet>(ps =>
                                {
                                    ps.Name = psetName;
                                    ps.HasProperties.AddRange(properties);
                                });
                            });
                        }
                    }
                    w.Stop();
                    Console.WriteLine($"{spaces.Count * psetNames.Count} property sets and {spaces.Count * psetNames.Count * psetNames.Count} properties created in {w.ElapsedMilliseconds}ms");
                    txn.Commit();
                }

                var fileName = "spaces_with_properties.ifc";
                var sw       = Stopwatch.StartNew();
                model.SaveAs(fileName);
                sw.Stop();

                var info = new FileInfo(fileName);
                Console.WriteLine($"Model saved in {sw.ElapsedMilliseconds}ms. File size {info.Length}B");
            }
        }