Beispiel #1
0
 public static Entity AsignarPeriodoContable(int pIdPeriodoContable)
 {
     Entity parametros = new Entity();
     parametros.Set("pIdPeriodoContable", pIdPeriodoContable);
     parametros.Set("pIdEmpresa", Configuracion.IdEmpresa);
     Entity resultado = ManejadorBaseDatos.Instancia.EjecutarSP("asignar_periodo_contable", parametros);
     return resultado;
 }
 public static Entity IngresarTipoCambio(int pIdMonedaBase, int pIdMonedaCambio, decimal pValor)
 {
     Entity parametros = new Entity();
     parametros.Set("pidmonedabase", pIdMonedaBase);
     parametros.Set("pidmonedacambio", pIdMonedaCambio);
     parametros.Set("pvalor", pValor);
     Entity resultado = ManejadorBaseDatos.Instancia.EjecutarSP("ingresar_tipo_cambio", parametros);
     return resultado;
 }
 public static Entity ObtenerTipoCambio(int pIdMonedaBase, int pIdMonedaCambio, DateTime pFecha)
 {
     Entity parametros = new Entity();
     parametros.Set("pmonedabase", pIdMonedaBase);
     parametros.Set("pmonedacambio", pIdMonedaCambio);
     parametros.Set("pfecha", pFecha);
     Entity resultado = ManejadorBaseDatos.Instancia.EjecutarSP("obtener_tipo_cambio", parametros);
     return resultado;
 }
Beispiel #4
0
        public void Update(Entity e, GameTime t)
        {
            // We burn through just enough time for emission to occur.  We
            // update the state, then perform an emission.  Then we pick up
            // where we left off (when the loop loops).
            uint dt = (uint) t.ElapsedGameTime.TotalMilliseconds;
            while (dt > 0) {
                uint emitTime = e.Get(EmitTime);

                uint timeToEmission = e.Get(TimeToEmission);
                if (timeToEmission == 0) {
                    timeToEmission = emitTime;
                }

                uint burntTime = Math.Min(timeToEmission, dt);
                timeToEmission -= burntTime;
                dt -= burntTime;

                e.Set(TimeToEmission, timeToEmission);

                if (timeToEmission == 0 && e.Get(IsEmitting)) {
                    this.onEmit(e);
                }
            }
        }
Beispiel #5
0
        public static float Damage(Entity e, float damageAmount, Entity damager = null)
        {
            float originalHealth = e.Get(Health);
            float finalHealth = Math.Max(0, originalHealth - damageAmount);
            e.Set(Health, finalHealth);

            float damageDealt = originalHealth - finalHealth;

            if (damager != null) {
                damager.ForEach<IDamager>((c) => {
                    c.Damaged(damager, e, damageDealt);
                });
            }

            if (finalHealth == 0) {
                e.ForEach<IKillable>((c) => {
                    c.Kill(e, damager);
                });

                if (damager != null) {
                    damager.ForEach<IKiller>((c) => {
                        c.Killed(damager, e);
                    });
                }
            }

            return damageDealt;
        }
Beispiel #6
0
 public static Entities ObtenerEmpresaGrupo()
 {
     Entity parametros = new Entity();
     parametros.Set("pIdEmpresa", Configuracion.IdEmpresa);
     Entity resultado = ManejadorBaseDatos.Instancia.EjecutarSP("obtener_empresa_grupo", parametros);
     Entities resultado_table = (Entities)resultado.Get("table");
     return resultado_table;
 }
 public override Entity CreateEntityOfSchema()
 {
     Entity entity = new Entity(GetOrCreateSchema());
      IList<String> stringSet = new List<string>() as IList<string>;
      stringSet.Add("abc");
      stringSet.Add("123");
      stringSet.Add("def");
      entity.Set("someStringArray", stringSet);
      return entity;
 }
Beispiel #8
0
 /// <summary>
 /// Create a new component instance and assign it to an entity.
 /// </summary>
 public Component Make(Entity entity)
 {
     Component component = BuildComponent(entity);
       if (component.Family != Family)
       {
     throw new ApplicationException(
       "Component template for family '"+Family+
       "' produced a component of family '"+
       Component.GetFamily()+"'.");
       }
       entity.Set(component);
       return component;
 }
Beispiel #9
0
 public static Entity CrearEmpresaGrupo(String pNombre, String pEsquema, int pCedula, byte[] pLogotipo, String pMonedaLocal, String pMonedaSistema)
 {
     Entity parametros = new Entity();
     parametros.Set("pNombre", pNombre);
     parametros.Set("pEsquema", pEsquema);
     parametros.Set("pCedulaJuridica", pCedula);
     parametros.Set("pLogotipo", pLogotipo);
     parametros.Set("pMonedaLocal", pMonedaLocal);
     parametros.Set("pMonedaSistema", pMonedaSistema);
     Entity resultado = ManejadorBaseDatos.Instancia.EjecutarSP("crear_empresa", parametros, pEsquema);
     return resultado;
 }
Beispiel #10
0
 public static Entity AgregarPeriodoContable(DateTime pFechaInicioC, DateTime pFechaFinalC, DateTime pFechaInicioD,
     DateTime pFechaFinalD, DateTime pFechaInicioV, DateTime pFechaFinalV)
 {
     Entity parametros = new Entity();
     parametros.Set("pFechaInicioC", pFechaInicioC);
     parametros.Set("pFechaFinC", pFechaFinalC);
     parametros.Set("pFechaInicioD", pFechaInicioD);
     parametros.Set("pFechaFinD", pFechaFinalD);
     parametros.Set("pFechaInicioV", pFechaInicioV);
     parametros.Set("pFechaFinV", pFechaFinalV);
     Entity resultado = ManejadorBaseDatos.Instancia.EjecutarSP("crear_periodo_contable", parametros);
     return resultado;
 }
Beispiel #11
0
        public Entity GenerateRotationGizmo()
        {
            var entity = new Entity("RotationGizmo");
            entity.Set(TransformationComponent.Key, new TransformationComponent());

            // TODO: Factorize some of this code with GenerateTranslationGizmo?
            var gizmoActions = new[] { GizmoAction.RotationX, GizmoAction.RotationY, GizmoAction.RotationZ };
            var orientationMatrices = new[] { Matrix.Identity, Matrix.RotationZ((float)Math.PI * 0.5f), Matrix.RotationY(-(float)Math.PI * 0.5f) };
            var colors = new[] { Color.Green, Color.Blue, Color.Red };

            var albedoMaterial = new ShaderMixinSource()
                {
                    "AlbedoDiffuseBase",
                    "AlbedoSpecularBase",
                    new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorFixed", MaterialKeys.DiffuseColor)),
                    new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")), // TODO: Default values!
                };

            for (int axis = 0; axis < 3; ++axis)
            {
                // Rendering
                var circleEffectMeshData = new EffectMeshData();
                circleEffectMeshData.Parameters = new ParameterCollection();
                circleEffectMeshData.MeshData = MeshDataHelper.CreateCircle(20.0f, 32, colors[axis]);
                circleEffectMeshData.EffectData = new EffectData("Gizmo") { AlbedoMaterial = albedoMaterial };

                var circleEntity = new Entity("ArrowCone");
                circleEntity.GetOrCreate(ModelComponent.Key).SubMeshes.Add(circleEffectMeshData);
                circleEntity.Set(TransformationComponent.Key, TransformationMatrix.CreateComponent(orientationMatrices[axis]));

                circleEntity.Set(GizmoColorKey, colors[axis]);
                circleEntity.Set(GizmoActionKey, gizmoActions[axis]);

                entity.GetOrCreate(TransformationComponent.Key).Children.Add(circleEntity.GetOrCreate(TransformationComponent.Key));
            }

            return entity;
        }
Beispiel #12
0
        public static void Run(EngineContext engineContext)
        {
            ParticlePlugin particlePlugin;
            if (!engineContext.DataContext.RenderPassPlugins.TryGetValueCast("ParticlePlugin", out particlePlugin))
                return;

            //engineContext.RenderContext.UIControl.KeyUp += (sender, args) =>
            //    {
            //        if (args.KeyCode >= Keys.F1 && args.KeyCode <= Keys.F12)
            //        {

            //            var stream = new FileStream("picking.txt", FileMode.Append);
            //            var streamWriter = new StreamWriter(stream);
            //            streamWriter.WriteLine("---------------------------------------------");
            //            streamWriter.WriteLine("- {0}", args.KeyCode);
            //            streamWriter.WriteLine("---------------------------------------------");
            //            streamWriter.Flush();
            //            stream.Close();
            //        }
            //    };

            var particleSystem = engineContext.EntityManager.GetSystem<ParticleProcessor>();

            var emitterPositions = new[]
                {
                    new Vector3(-2047.287f, -613.5108f, -400.0f),						// 0
                    new Vector3(-1881.002f, -564.9566f, -400.0f),						// 1
                    new Vector3(-1627.844f, -449.1949f, -400.0f),						// 2
                    new Vector3(-1391.335f, -423.1865f, -400.0f),						// 3
                    new Vector3(-1314.865f, -482.0599f, -400.0f),						// 4
                    new Vector3(-1019.54f, -932.4803f,  -400.0f),						// 5
                    new Vector3(-957.3735f, -988.7004f, -400.0f),						// 6
                    new Vector3(-759.9126f, -1168.646f, -400.0f),						// 7
                    new Vector3(-529.1716f, -1083.003f, -400.0f),						// 8
                    new Vector3(-198.7756f, -1029.24f,  -400.0f),						// 9
                    new Vector3(309.9702f, -832.7861f,  -400.0f),						// 10
                    new Vector3(876.9819f, -667.9489f,  -400.0f),						// 11
                    new Vector3(1908.686f, -1085.583f,  -400.0f),						// 12
                    new Vector3(2308.45f, -995.1572f,   -400.0f),						// 13
                    new Vector3(2864.581f, -906.4545f,  -400.0f),						// 14
                    new Vector3(3770.119f, -832.0695f,  -400.0f),						// 15
                    new Vector3(4561.941f, -728.9376f,  -400.0f),						// 16
                    new Vector3(5429.49f, -722.3638f,   -400.0f),						// 17
                    new Vector3(6447.015f, -310.0454f,  -400.0f),						// 18
                    new Vector3(6420.864f, 532.3475f,   -400.0f),						// 19
                    new Vector3(6157.83f, 658.0294f,    -400.0f),						// 20
                    new Vector3(4732.579f, 955.4061f,   -400.0f),						// 21
                    new Vector3(1630.28f, 1551.338f,    -400.0f),						// 22
                    new Vector3(931.7393f, 1274.533f,   -400.0f),						// 23
                    new Vector3(1586.493f, 1505.558f,   -400.0f),						// 24
                    new Vector3(906.572f, 1268.478f,    -400.0f),						// 25
                    new Vector3(390.1973f, 1314.976f,   -400.0f),						// 26
                    new Vector3(-30.39231f, 1553.894f,  -400.0f),						// 27
                    new Vector3(-356.4023f, 1605.162f,  -400.0f),						// 28
                    new Vector3(-1055.699f, 971.7286f,  -400.0f),						// 29
                    new Vector3(-1218.041f, 727.1427f,  -400.0f),						// 30
                    new Vector3(-1377.148f, 606.9602f,  -400.0f),						// 31
                    new Vector3(-1676.512f, 640.7913f,  -400.0f),						// 32
                    new Vector3(-2089.593f, 833.8343f,  -400.0f),						// 33
                    new Vector3(-2290.1f, 992.6068f,    -400.0f),						// 34
                    new Vector3(-2196.059f, 764.4152f,  -400.0f),						// 35
                    new Vector3(-1448.233f, 391.5037f,  -400.0f),						// 36
                    new Vector3(-1337.535f, 223.827f,   -400.0f),						// 37
                    new Vector3(-1287.335f, -125.6966f, -400.0f),						// 38
                    new Vector3(-4226.484f, -1213.027f, -400.0f),						// 39 - Magma Left
                    new Vector3(-4593.09f, -1091.131f,  -400.0f),						// 40
                    new Vector3(-4803.661f, -958.4816f, -400.0f),						// 41
                    new Vector3(-5262.959f, -1025.99f,  -400.0f),						// 42
                    new Vector3(-5519.119f, -881.3628f, -400.0f),						// 43
                    new Vector3(-5543.972f, -547.7667f, -400.0f),						// 44
                    new Vector3(-5775.069f, -294.6195f, -400.0f),						// 45
                    new Vector3(-6333.859f, -423.4442f, -400.0f),						// 46
                    new Vector3(-6977.528f, 840.5598f,  -400.0f),						// 47
                    new Vector3(-6847.938f, 1640.414f,  -400.0f),						// 48
                    new Vector3(-7259.18f, 1724.889f,   -400.0f),						// 49
                    new Vector3(-7693.181f, 1660.773f,  -400.0f),						// 50
                    new Vector3(-8300.401f, 1609.711f,  -400.0f),						// 51
                    new Vector3(-8704.221f, 1241.705f,  -400.0f),						// 52
                    new Vector3(-9049.8f, 905.2922f,    -400.0f),						// 53
                    new Vector3(-8739.72f, 105.7951f,   -400.0f),						// 54
                    new Vector3(-8515.267f, -371.7517f, -400.0f),						// 55
                    new Vector3(-8110.098f, -316.8557f, -400.0f),						// 56
                    new Vector3(-7915.391f, -304.8632f, -400.0f),						// 57
                    new Vector3(-7191.82f, -353.2674f,  -400.0f),						// 58
                    new Vector3(-6270.604f, -2246.958f, -400.0f),						// 59 - Magma right
                    new Vector3(-6655.961f, -2615.954f, -400.0f),						// 60
                    new Vector3(-7056.6f, -2839.48f,    -400.0f),						// 61
                    new Vector3(-7632.455f, -3047.234f, -400.0f),						// 62
                    new Vector3(-8325.431f, -2937.415f, -400.0f),						// 63
                    new Vector3(-8273.172f, -3403.743f, -400.0f),						// 64
                    new Vector3(-8179.38f, -3616.764f,  -400.0f),						// 65
                    new Vector3(-7814.024f, -4484.587f, -400.0f),						// 66
                    new Vector3(-6525.229f, -4816.507f, -400.0f),						// 67
                    new Vector3(-5648.252f, -4344.051f, -400.0f),						// 68
                    new Vector3(-6140.713f, -3957.125f, -400.0f),						// 69
                    new Vector3(-7001.114f, -3650.077f, -400.0f),						// 70
                };


            var random = new Random(1);

            var emitters = new SmokeParticleEmitterComponent[emitterPositions.Length];
            for (int i = 0; i < emitters.Length; i++)
            {

                var verticalScatter = (float)(2.0 + 3.0 * random.NextDouble());
                var horizontalScatter = (float)(3.0 + 6.0 * random.NextDouble());

                var emitter = new SmokeParticleEmitterComponent()
                    {
                        Count = 256,
                        Description = new SmokeEmitterDescription()
                        {
                            Position = emitterPositions[i],
                            Scatter = new Vector3(horizontalScatter, horizontalScatter, verticalScatter),
                            Velocity = new Vector3(0, 0.0f, 0.5f + 4.0f * (float)random.NextDouble()),
                            MaxTime = 1000.0f + 4000.0f * (float)random.NextDouble(),
                            InitialSize = 50.0f + 30.0f * (float)random.NextDouble(),
                            DeltaSize = 30.0f + 20.0f * (float)random.NextDouble(),
                            Opacity = 0.7f,
                        }
                    };
                emitter.OnUpdateData();

                emitters[i] = emitter;
            }

            var smokeVolTexture = (Texture2D)engineContext.AssetManager.Load<Texture>("/global_data/gdc_demo/fx/smokevol.dds");
            var smokeGradTexture = (Texture2D)engineContext.AssetManager.Load<Texture>("/global_data/gdc_demo/fx/smokegrad.dds");
            particlePlugin.Parameters.Set(SmokeTexture, smokeVolTexture);
            particlePlugin.Parameters.Set(SmokeColor, smokeGradTexture);

            var particleEmitterRootEntity = new Entity("ParticleEmitters");
            particleEmitterRootEntity.Set(TransformationComponent.Key, new TransformationComponent());
            engineContext.EntityManager.AddEntity(particleEmitterRootEntity);

            for (int index = 0; index < emitters.Length; index++)
            {
                var emitter = emitters[index];
                var entity = new Entity(string.Format("ParticleEmitter-{0}", index));
                entity.Set(TransformationComponent.Key, new TransformationComponent(new TransformationTRS { Translation = emitter.Description.Position }));
                entity.Set(ParticleEmitterComponent.Key, emitter);

                particleEmitterRootEntity.Transformation.Children.Add(entity.Transformation);
            }
        }
Beispiel #13
0
        // Setup routine: updates parameters of the window to the appropriate values on load
        internal void UpdateInitialParameters(Document doc)
        {
            Transaction t = new Transaction(doc, "Update parameters");
               t.Start();

               SchemaBuilder builder = new SchemaBuilder(m_schemaId); //(new Guid("{4DE4BE80-0857-4785-A7DF-8A8918851CB2}"));
               builder.AddSimpleField("Position", typeof(XYZ)).SetUnitType(UnitType.UT_Length);
               builder.AddSimpleField("Orientation", typeof(XYZ)).SetUnitType(UnitType.UT_Length);
               builder.SetSchemaName("WallPositionData");
               builder.SetDocumentation("Two points in a Window element that assist in placing a section view.");
               builder.SetVendorId("adsk");
               builder.SetApplicationGUID(doc.Application.ActiveAddInId.GetGUID());

               m_schema = builder.Finish();

               t.Commit();

               t.Start();
               Field fieldPosition = m_schema.GetField("Position");
               Field fieldOrientation = m_schema.GetField("Orientation");

               FamilyInstance window = doc.get_Element(m_windowId) as FamilyInstance;

               Entity storageEntity = new Entity(m_schema);

               LocationPoint lp = window.Location as LocationPoint;
               XYZ location = lp.Point;

               storageEntity.Set<XYZ>(fieldPosition, location, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);

               XYZ orientation = window.FacingOrientation;
               storageEntity.Set<XYZ>(fieldOrientation, orientation, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
               window.SetEntity(storageEntity);

               t.Commit();
        }
Beispiel #14
0
        /// <summary>
        /// Update the address saved into the extensible storage using values from the UI 
        /// </summary>
        /// <param name="document">The document storing the saved address.</param>
        /// <param name="addressItem">address information from the UI to be saved into extensible storage</param>
        public void UpdateAddress(Document document, IFCAddressItem addressItem)
        {
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                IList<DataStorage> oldSavedAddress = GetAddressInStorage(document, m_schema);
                if (oldSavedAddress.Count > 0)
                {
                    Transaction deleteTransaction = new Transaction(document, "Delete old IFC address");
                    deleteTransaction.Start();
                    List<ElementId> dataStorageToDelete = new List<ElementId>();
                    foreach (DataStorage dataStorage in oldSavedAddress)
                    {
                        dataStorageToDelete.Add(dataStorage.Id);
                    }
                    document.Delete(dataStorageToDelete);
                    deleteTransaction.Commit();
                }
            }

            // Update the address using the new information
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                Transaction transaction = new Transaction(document, "Update saved IFC Address");
                transaction.Start();

                DataStorage addressStorage = DataStorage.Create(document);

                Entity mapEntity = new Entity(m_schema);
                IDictionary<string, string> mapData = new Dictionary<string, string>();
                if (addressItem.Purpose != null) mapData.Add(s_addressPurpose, addressItem.Purpose.ToString());
                if (addressItem.Description != null) mapData.Add(s_addressDescription, addressItem.Description.ToString());
                if (addressItem.UserDefinedPurpose != null) mapData.Add(s_addressUserDefinedPurpose, addressItem.UserDefinedPurpose.ToString());
                if (addressItem.InternalLocation != null) mapData.Add(s_addressInternalLocation, addressItem.InternalLocation.ToString());
                if (addressItem.AddressLine1 != null) mapData.Add(s_addressAddressLine1, addressItem.AddressLine1.ToString());
                if (addressItem.AddressLine2 != null) mapData.Add(s_addressAddressLine2, addressItem.AddressLine2.ToString());
                if (addressItem.POBox != null) mapData.Add(s_addressPOBox, addressItem.POBox.ToString());
                if (addressItem.TownOrCity != null) mapData.Add(s_addressTownOrCity, addressItem.TownOrCity.ToString());
                if (addressItem.RegionOrState != null) mapData.Add(s_addressRegionOrState, addressItem.RegionOrState.ToString());
                if (addressItem.PostalCode != null) mapData.Add(s_addressPostalCode, addressItem.PostalCode.ToString());
                if (addressItem.Country != null) mapData.Add(s_addressCountry, addressItem.Country.ToString());

                mapEntity.Set<IDictionary<string, String>>(s_addressMapField, mapData);
                addressStorage.SetEntity(mapEntity);

                transaction.Commit();
            }
        }
        /// <summary>
        /// Updates the setups to save into the document.
        /// </summary>
        /// <param name="document">The document storing the saved configuration.</param>
        public void UpdateSavedConfigurations(Document document)
        {
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }

            // Are there any setups to save or resave?
            List<IFCExportConfiguration> setupsToSave = new List<IFCExportConfiguration>();
            foreach (IFCExportConfiguration configuration in m_configurations.Values)
            {
                if (configuration.IsBuiltIn)
                    continue;

                // Store in-session settings in the cached in-session configuration
                if (configuration.IsInSession)
                {
                    IFCExportConfiguration.SetInSession(configuration);
                    continue;
                }

                setupsToSave.Add(configuration);
           }

           // If there are no setups to save, and if the schema is not present (which means there are no
           // previously existing setups which might have been deleted) we can skip the rest of this method.
           if (setupsToSave.Count <= 0 && m_schema == null)
               return;

           if (m_schema == null)
           {
                SchemaBuilder builder = new SchemaBuilder(s_schemaId);
                builder.SetSchemaName("IFCExportConfiguration");
                builder.AddSimpleField(s_setupName, typeof(String));
                builder.AddSimpleField(s_setupDescription, typeof(String));
                builder.AddSimpleField(s_setupVersion, typeof(int));
                builder.AddSimpleField(s_setupFileFormat, typeof(int));
                builder.AddSimpleField(s_setupSpaceBoundaries, typeof(int));
                builder.AddSimpleField(s_setupQTO, typeof(bool));
                builder.AddSimpleField(s_splitWallsAndColumns, typeof(bool));
                builder.AddSimpleField(s_setupCurrentView, typeof(bool));
                builder.AddSimpleField(s_setupExport2D, typeof(bool));
                builder.AddSimpleField(s_setupExportRevitProps, typeof(bool));
                builder.AddSimpleField(s_setupUse2DForRoomVolume, typeof(bool));
                builder.AddSimpleField(s_setupUseFamilyAndTypeName, typeof(bool));
                builder.AddSimpleField(s_setupExportPartsAsBuildingElements, typeof(bool));

                m_schema = builder.Finish();
           }

           // Overwrite all saved configs with the new list
           Transaction transaction = new Transaction(document, "Update IFC export setups");
           transaction.Start();
           IList<DataStorage> savedConfigurations = GetSavedConfigurations(document);
           int savedConfigurationCount = savedConfigurations.Count<DataStorage>();
           int savedConfigurationIndex = 0;
           foreach (IFCExportConfiguration configuration in setupsToSave)
           {
                DataStorage configStorage;
                if (savedConfigurationIndex >= savedConfigurationCount)
                {
                    configStorage = DataStorage.Create(document);
                }
                else
                {
                    configStorage = savedConfigurations[savedConfigurationIndex];
                    savedConfigurationIndex ++;
                }
                Entity entity = new Entity(m_schema);
                entity.Set(s_setupName, configuration.Name);
                entity.Set(s_setupDescription, configuration.Description);
                entity.Set(s_setupVersion, (int)configuration.IFCVersion);
                entity.Set(s_setupFileFormat, (int)configuration.IFCFileType);
                entity.Set(s_setupSpaceBoundaries, configuration.SpaceBoundaries);
                entity.Set(s_setupQTO, configuration.ExportBaseQuantities);
                entity.Set(s_setupCurrentView, configuration.VisibleElementsOfCurrentView);
                entity.Set(s_splitWallsAndColumns, configuration.SplitWallsAndColumns);
                entity.Set(s_setupExport2D, configuration.Export2DElements);
                entity.Set(s_setupExportRevitProps, configuration.ExportInternalRevitPropertySets);
                entity.Set(s_setupUse2DForRoomVolume, configuration.Use2DRoomBoundaryForVolume);
                entity.Set(s_setupUseFamilyAndTypeName, configuration.UseFamilyAndTypeNameForReference);
                entity.Set(s_setupExportPartsAsBuildingElements, configuration.ExportPartsAsBuildingElements);

                configStorage.SetEntity(entity);
            }

            List<ElementId> elementsToDelete = new List<ElementId>();
            for (; savedConfigurationIndex < savedConfigurationCount; savedConfigurationIndex++)
            {
                DataStorage configStorage = savedConfigurations[savedConfigurationIndex];
                elementsToDelete.Add(configStorage.Id);
            }
            if (elementsToDelete.Count > 0)
                document.Delete(elementsToDelete);

            transaction.Commit();
        }
Beispiel #16
0
        public static async Task GenerateTestPrefabs(EngineContext engineContext)
        {
            var entityCube = new Entity("Cube");
            var meshComponent = new ModelComponent();
            meshComponent.SubMeshes.Add(new EffectMeshData { EffectData = new EffectData("SimpleCube"), MeshData = MeshDataHelper.CreateBox(100.0f, 100.0f, 100.0f, Color.Gray) });
            entityCube.Set(ModelComponent.Key, meshComponent);
            entityCube.Set(TransformationComponent.Key, new TransformationComponent());
            engineContext.AssetManager.Url.Set(entityCube, "/global_data/cube.hotei#/root");
            engineContext.AssetManager.Save(entityCube);

            var entitySphere = new Entity("Cube");
            meshComponent = new ModelComponent();
            meshComponent.SubMeshes.Add(new EffectMeshData { EffectData = new EffectData("SimpleCube"), MeshData = MeshDataHelper.CreateSphere(100.0f, 30, 30, Color.Gray) });
            entitySphere.Set(ModelComponent.Key, meshComponent);
            entitySphere.Set(TransformationComponent.Key, new TransformationComponent());
            engineContext.AssetManager.Url.Set(entitySphere, "/global_data/sphere.hotei#/root");
            engineContext.AssetManager.Save(entitySphere);
        }
        /// <summary>
        /// Update the file Header (from the UI) into the document 
        /// </summary>
        /// <param name="document">The document storing the saved File Header.</param>
        /// <param name="fileHeaderItem">The File Header item to save.</param>
        public void UpdateFileHeader(Document document, IFCFileHeaderItem fileHeaderItem)
        {
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                IList<DataStorage> oldSavedFileHeader = GetFileHeaderInStorage(document, m_schema);
                if (oldSavedFileHeader.Count > 0)
                {
                    Transaction deleteTransaction = new Transaction(document, "Delete old IFC File Header");
                    deleteTransaction.Start();
                    List<ElementId> dataStorageToDelete = new List<ElementId>();
                    foreach (DataStorage dataStorage in oldSavedFileHeader)
                    {
                        dataStorageToDelete.Add(dataStorage.Id);
                    }
                    document.Delete(dataStorageToDelete);
                    deleteTransaction.Commit();
                }
            }

            // Update the address using the new information
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                Transaction transaction = new Transaction(document, "Update saved IFC File Header");
                transaction.Start();

                DataStorage fileHeaderStorage = DataStorage.Create(document);

                Entity mapEntity = new Entity(m_schema);
                IDictionary<string, string> mapData = new Dictionary<string, string>();
                if (fileHeaderItem.FileDescription != null) mapData.Add(s_FileDescription, fileHeaderItem.FileDescription.ToString());
                if (fileHeaderItem.SourceFileName != null) mapData.Add(s_SourceFileName, fileHeaderItem.SourceFileName.ToString());
                if (fileHeaderItem.AuthorName != null) mapData.Add(s_AuthorName, fileHeaderItem.AuthorName.ToString());
                if (fileHeaderItem.AuthorEmail != null) mapData.Add(s_AuthorEmail, fileHeaderItem.AuthorEmail.ToString());
                if (fileHeaderItem.Organization != null) mapData.Add(s_Organization, fileHeaderItem.Organization.ToString());
                if (fileHeaderItem.Authorization != null) mapData.Add(s_Authorization, fileHeaderItem.Authorization.ToString());
                if (fileHeaderItem.ApplicationName != null) mapData.Add(s_ApplicationName, fileHeaderItem.ApplicationName.ToString());
                if (fileHeaderItem.VersionNumber != null) mapData.Add(s_VersionNumber, fileHeaderItem.VersionNumber.ToString());
                if (fileHeaderItem.FileSchema != null) mapData.Add(s_FileSchema, fileHeaderItem.FileSchema.ToString());

                mapEntity.Set<IDictionary<string, String>>(s_FileHeaderMapField, mapData);
                fileHeaderStorage.SetEntity(mapEntity);

                transaction.Commit();
            }
        }
        public void StoreData(FamilySymbol titleblock)
        {
            Schema schema = Schema.Lookup(new Guid("1a68d420-96dd-44aa-a1de-000774a6104b"));
            Entity entity = new Entity(schema);

            Field field_titleblockName = schema.GetField("titleblockName");

            Field field_cellSizeDistance_X = schema.GetField("cellSizeDistance_X");
            Field field_lowerGap_X = schema.GetField("lowerGap_X");
            Field field_additionalEdge_X = schema.GetField("additionalEdge_X");
            Field field_fineTune_X = schema.GetField("fineTune_X");

            Field field_cellSizeDistance_Y = schema.GetField("cellSizeDistance_Y");
            Field field_lowerGap_Y = schema.GetField("lowerGap_Y");
            Field field_additionalEdge_Y = schema.GetField("additionalEdge_Y");
            Field field_fineTune_Y = schema.GetField("fineTune_Y");

            Field field_cellGrid_Length = schema.GetField("cellGrid_Length");
            Field field_cellGrid_Height = schema.GetField("cellGrid_Height");

            entity.Set<string>(field_titleblockName, titleblockName);

            entity.Set<string>(field_cellSizeDistance_X, cellSizeDistance_X, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_lowerGap_X, lowerGap_X, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_additionalEdge_X, additionalEdge_X, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_fineTune_X, fineTune_X, DisplayUnitType.DUT_DECIMAL_INCHES);

            entity.Set<string>(field_cellSizeDistance_Y, cellSizeDistance_Y, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_lowerGap_Y, lowerGap_Y, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_additionalEdge_Y, additionalEdge_Y, DisplayUnitType.DUT_DECIMAL_INCHES);
            entity.Set<string>(field_fineTune_Y, fineTune_Y, DisplayUnitType.DUT_DECIMAL_INCHES);

            entity.Set<string>(field_cellGrid_Length, cellGrid_Length);
            entity.Set<string>(field_cellGrid_Height, cellGrid_Height);
            titleblock.SetEntity(entity); // store the entity in the element
        }
Beispiel #19
0
        /// <summary>
        /// Ejecuta un sp apartir de un objeto entity
        /// </summary>
        /// <param name="pSP">entity que contiene informacion del sp</param>
        /// <returns>entity con el resultado de la ejecución del sp</returns>
        public Entity EjecutarSPAux(Entity pSP, String pEsquema)
        {
            Entity resultado = new Entity();
            SqlConnection conexion;
            try
            {
                conexion = new SqlConnection(_ConnectionString);
                conexion.Open();
                String nombreSP = pEsquema+"."+(String)pSP.Get("SP");
                Entities parametros = (Entities)pSP.Get("Parametros");
                Boolean retornaDatos = (Boolean)pSP.Get("Retorna");

                SqlDataAdapter adapter = new SqlDataAdapter();

                SqlCommand sp = new SqlCommand();
                sp.Connection = conexion;
                sp.CommandType = System.Data.CommandType.StoredProcedure;
                sp.CommandText = nombreSP;

                foreach (Entity parametro in parametros)
                {
                    SqlParameter sqlParametro = new SqlParameter((String)parametro.Get("Nombre"), parametro.Get("Valor"));
                    if (sqlParametro.Value == null)
                    {
                        sqlParametro.Value = DBNull.Value;
                    }
                    if (((String)parametro.Get("Tipo")).Equals("Input"))
                    {
                        sqlParametro.Direction = System.Data.ParameterDirection.Input;
                    }
                    else if (((String)parametro.Get("Tipo")).Equals("Output"))
                    {
                        sqlParametro.Direction = System.Data.ParameterDirection.Output;
                    }
                    sp.Parameters.Add(sqlParametro);
                }

                if (retornaDatos)
                {
                    adapter.SelectCommand = sp;

                    DataSet dataset = new DataSet();
                    adapter.Fill(dataset);
                    foreach (DataTable table in dataset.Tables)
                    {
                        Entities result = new Entities();
                        foreach (DataRow row in table.Rows)
                        {
                            Entity fila = new Entity();
                            for (int i = 0; i < (row.ItemArray.Length); i++)
                            {
                                fila.Set(row.Table.Columns[i].ColumnName, row.ItemArray[i]);
                            }
                            result.Add(fila);
                        }
                        resultado.Set(table.TableName, result);
                    }

                }
                else
                {
                    sp.ExecuteNonQuery();
                }
                resultado.Set("Estado", true);
                resultado.Set("Error", "");
                conexion.Close();
            }
            catch (SqlException e)
            {
                resultado.Set("Estado", false);
                resultado.Set("Error", e.Message);
            }

            return resultado;
        }
        /// <summary>
        /// Updates the setups to save into the document.
        /// </summary>
        /// <param name="document">The document storing the saved configuration.</param>
        public void UpdateSavedConfigurations(Document document)
        {
            // delete the old schema and the DataStorage.
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                IList<DataStorage> oldSavedConfigurations = GetSavedConfigurations(document, m_schema);
                if (oldSavedConfigurations.Count > 0)
                {
                    Transaction deleteTransaction = new Transaction(document, "Delete old IFC export setups");
                    deleteTransaction.Start();
                    List<ElementId> dataStorageToDelete = new List<ElementId>();
                    foreach (DataStorage dataStorage in oldSavedConfigurations)
                    {
                        dataStorageToDelete.Add(dataStorage.Id);
                    }
                    document.Delete(dataStorageToDelete);
                    deleteTransaction.Commit();
                }
            }

            // update the configurations to new map schema.
            if (m_mapSchema == null)
            {
                m_mapSchema = Schema.Lookup(s_mapSchemaId);
            }

            // Are there any setups to save or resave?
            List<IFCExportConfiguration> setupsToSave = new List<IFCExportConfiguration>();
            foreach (IFCExportConfiguration configuration in m_configurations.Values)
            {
                if (configuration.IsBuiltIn)
                    continue;

                // Store in-session settings in the cached in-session configuration
                if (configuration.IsInSession)
                {
                    IFCExportConfiguration.SetInSession(configuration);
                    continue;
                }

                setupsToSave.Add(configuration);
           }

           // If there are no setups to save, and if the schema is not present (which means there are no
           // previously existing setups which might have been deleted) we can skip the rest of this method.
            if (setupsToSave.Count <= 0 && m_mapSchema == null)
               return;

           if (m_mapSchema == null)
           {
               SchemaBuilder builder = new SchemaBuilder(s_mapSchemaId);
               builder.SetSchemaName("IFCExportConfigurationMap");
               builder.AddMapField(s_configMapField, typeof(String), typeof(String));
               m_mapSchema = builder.Finish();
           }

           // Overwrite all saved configs with the new list
           Transaction transaction = new Transaction(document, "Update IFC export setups");
           transaction.Start();
           IList<DataStorage> savedConfigurations = GetSavedConfigurations(document, m_mapSchema);
           int savedConfigurationCount = savedConfigurations.Count<DataStorage>();
           int savedConfigurationIndex = 0;
           foreach (IFCExportConfiguration configuration in setupsToSave)
           {
                DataStorage configStorage;
                if (savedConfigurationIndex >= savedConfigurationCount)
                {
                    configStorage = DataStorage.Create(document);
                }
                else
                {
                    configStorage = savedConfigurations[savedConfigurationIndex];
                    savedConfigurationIndex ++;
                }             

                Entity mapEntity = new Entity(m_mapSchema);
                IDictionary<string, string> mapData = new Dictionary<string, string>();
                mapData.Add(s_setupName, configuration.Name);
                mapData.Add(s_setupDescription, configuration.Description);
                mapData.Add(s_setupVersion, configuration.IFCVersion.ToString());
                mapData.Add(s_setupFileFormat, configuration.IFCFileType.ToString());
                mapData.Add(s_setupSpaceBoundaries, configuration.SpaceBoundaries.ToString());
                mapData.Add(s_setupQTO, configuration.ExportBaseQuantities.ToString());
                mapData.Add(s_setupCurrentView, configuration.VisibleElementsOfCurrentView.ToString());
                mapData.Add(s_splitWallsAndColumns, configuration.SplitWallsAndColumns.ToString());
                mapData.Add(s_setupExport2D, configuration.Export2DElements.ToString());
                mapData.Add(s_setupExportRevitProps, configuration.ExportInternalRevitPropertySets.ToString());
                mapData.Add(s_setupExportIFCCommonProperty, configuration.ExportIFCCommonPropertySets.ToString());
                mapData.Add(s_setupUse2DForRoomVolume, configuration.Use2DRoomBoundaryForVolume.ToString());
                mapData.Add(s_setupUseFamilyAndTypeName, configuration.UseFamilyAndTypeNameForReference.ToString());
                mapData.Add(s_setupExportPartsAsBuildingElements, configuration.ExportPartsAsBuildingElements.ToString());
                mapData.Add(s_setupExportSurfaceStyles, configuration.ExportSurfaceStyles.ToString());
                mapData.Add(s_setupExportAdvancedSweptSolids, configuration.ExportAdvancedSweptSolids.ToString());
                mapData.Add(s_setupExportBoundingBox, configuration.ExportBoundingBox.ToString());
                mapEntity.Set<IDictionary<string, String>>(s_configMapField, mapData);

                configStorage.SetEntity(mapEntity);
            }

            List<ElementId> elementsToDelete = new List<ElementId>();
            for (; savedConfigurationIndex < savedConfigurationCount; savedConfigurationIndex++)
            {
                DataStorage configStorage = savedConfigurations[savedConfigurationIndex];
                elementsToDelete.Add(configStorage.Id);
            }
            if (elementsToDelete.Count > 0)
                document.Delete(elementsToDelete);

            transaction.Commit();
        }
Beispiel #21
0
        public static async Task Run(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;
            renderingSetup.RegisterLighting(engineContext);

            ParticlePlugin particlePlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("ParticlePlugin", out particlePlugin))
            {
                ScriptParticleSmoke.Run(engineContext);
            }


            var yebisPlugin = engineContext.RenderContext.RenderPassPlugins.OfType<YebisPlugin>().FirstOrDefault();
            if (yebisPlugin != null)
            {
                var yebisConfig = AppConfig.GetConfiguration<YebisConfig>("Yebis");

                // yebisPlugin.ToneMap.Type = ToneMapType.Linear;
                yebisPlugin.ToneMap.Gamma = yebisConfig.Gamma;
                yebisPlugin.ColorCorrection.Saturation = yebisConfig.Saturation;
                yebisPlugin.ColorCorrection.Contrast = yebisConfig.Contrast;
                yebisPlugin.ColorCorrection.Brightness = yebisConfig.Brightness;
                yebisPlugin.ColorCorrection.ColorTemperature = yebisConfig.ColorTemperature;
                yebisPlugin.Lens.Vignette.Enable = true;
                yebisPlugin.Lens.Vignette.PowerOfCosine = 5.0f;
                yebisPlugin.Lens.Distortion.Enable = true;
                yebisPlugin.Lens.Distortion.EdgeRoundness = 0.1f;
                yebisPlugin.Lens.Distortion.EdgeSmoothness = 1.0f;
            }
            
            // Run the script to animate the intro fade-in/fade-out
            engineContext.Scheduler.Add(async () => await AnimateIntroAndEndScene(engineContext));

            var cameraEntityRootPrefab = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/gdc_demo/char/camera.hotei#");
            var lightCamEntityRootPrefab = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/gdc_demo/char/light_cam.hotei#");

            var lightCamEntityRoot = Prefab.Inherit(lightCamEntityRootPrefab);
            var cameraEntityRoot = Prefab.Inherit(cameraEntityRootPrefab);

            engineContext.EntityManager.AddEntity(cameraEntityRoot);
            engineContext.EntityManager.AddEntity(lightCamEntityRoot);
            Scheduler.Current.Add(() => AnimScript.AnimateFBXModel(engineContext, cameraEntityRoot, CaveSceneTotalTime, CaveSceneRestart));
            Scheduler.Current.Add(() => AnimScript.AnimateFBXModel(engineContext, lightCamEntityRoot, CaveSceneTotalTime, CaveSceneRestart));

            foreach(var light in ParameterContainerExtensions.CollectEntityTree(lightCamEntityRoot))
            {
                var lightComp = light.Get(LightComponent.Key);
                if (lightComp != null)
                {
                    
                    if (!lightComp.ShadowMap && lightComp.Type == LightType.Directional)
                    {
                        lightComp.Intensity *= 0.1f;
                    }
                }
            }

            var config = AppConfig.GetConfiguration<Script1.Config>("Script1");

            var shadowMap1 = new Entity();
            var shadowMap2 = new Entity();
            shadowMap1.Set(TransformationComponent.Key, TransformationTRS.CreateComponent());
            shadowMap2.Set(TransformationComponent.Key, TransformationTRS.CreateComponent());
            shadowMap1.Set(LightComponent.Key, new LightComponent { Type = LightType.Directional, Intensity = 0.9f, Color = new Color3(0.9f, 0.9f, 1.0f), LightDirection = new Vector3(-0.2f, -0.1f, -1.0f), ShadowMap = true, DecayStart = 40000.0f });
            shadowMap2.Set(LightComponent.Key, new LightComponent { Type = LightType.Directional, Color = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(-0.5f, 0.1f, -1.0f), ShadowMap = true, DecayStart = 40000.0f });
            shadowMap1.Set(LightShaftsComponent.Key, new LightShaftsComponent { Color = new Color3(1.0f, 1.0f, 1.0f), LightShaftsBoundingBoxes =
                {
                    new EffectMeshData { MeshData = MeshDataHelper.CreateBox(1, 1, 1, Color.White, true), Parameters = new ParameterCollection { { TransformationKeys.World, Matrix.Scaling(3000, 3500, 3000) * Matrix.Translation(-2500, 0, 1500) } } }
                } });
            shadowMap2.Set(LightShaftsComponent.Key, new LightShaftsComponent { Color = new Color3(1.0f, 1.0f, 1.0f), LightShaftsBoundingBoxes =
                {
                    new EffectMeshData { MeshData = MeshDataHelper.CreateBox(1, 1, 1, Color.White, true), Parameters = new ParameterCollection { { TransformationKeys.World, Matrix.Scaling(3500, 3500, 3000) * Matrix.Translation(-3000, 0, 1500) } } }
                } });

            engineContext.EntityManager.AddEntity(shadowMap1);
            engineContext.EntityManager.AddEntity(shadowMap2);


            var dragon = await LoadDragon(engineContext);
            await LoadCave(engineContext, dragon);

            var dragonHead = engineContext.EntityManager.Entities.FirstOrDefault(x => x.Name == "English DragonHead");
            TransformationTRS headCameraTransfo = null;
            if (dragonHead != null)
            {
                var headCamera = new Entity("Head camera");
                headCamera.Set(CameraComponent.Key, new CameraComponent { AspectRatio = 16.0f / 9.0f, VerticalFieldOfView = (float)Math.PI * 0.3f, Target = dragonHead, AutoFocus = true, NearPlane = 10.0f });
                headCamera.Set(TransformationComponent.Key, new TransformationComponent(new TransformationTRS { Translation = new Vector3(100.0f, -100.0f, 300.0f) }));
                //engineContext.EntitySystem.Entities.Add(headCamera);
                dragonHead.Transformation.Children.Add(headCamera.Transformation);
            }

            engineContext.Scheduler.Add(() => AnimateLights(engineContext));

            // Performs several full GC after the scene has been loaded
            for (int i = 0; i < 10; i++)
            {
                GC.Collect();
                Thread.Sleep(1);
            }

            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                if (headCameraTransfo != null)
                {
                    var time = (double)DateTime.UtcNow.Ticks / (double)TimeSpan.TicksPerSecond;
                    float rotationSpeed = 0.317f;
                    var position = new Vector2((float)Math.Cos(time * rotationSpeed), (float)Math.Sin(time * rotationSpeed)) * 330.0f * ((float)Math.Sin(time * 0.23f) * 0.4f + 0.9f);
                    headCameraTransfo.Translation = new Vector3(position.X, -150.0f + (float)Math.Cos(time * rotationSpeed) * 50.0f, position.Y);
                }

                if (engineContext.InputManager.IsKeyPressed(Keys.F1))
                {
                    bool isWireframeEnabled = renderingSetup.ToggleWireframe();
                    if (yebisPlugin != null)
                    {
                        yebisPlugin.DepthOfField.Enable = !isWireframeEnabled;
                        yebisPlugin.Lens.Vignette.Enable = !isWireframeEnabled;
                        yebisPlugin.Lens.Distortion.Enable = !isWireframeEnabled;
                    }
                }

                if (engineContext.InputManager.IsKeyPressed(Keys.D1))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(0);
                if (engineContext.InputManager.IsKeyPressed(Keys.D2))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(10);
                if (engineContext.InputManager.IsKeyPressed(Keys.D3))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(20);
                if (engineContext.InputManager.IsKeyPressed(Keys.D4))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(30);
                if (engineContext.InputManager.IsKeyPressed(Keys.D5))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(40);
                if (engineContext.InputManager.IsKeyPressed(Keys.D6))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(50);
                if (engineContext.InputManager.IsKeyPressed(Keys.D7))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(60);
                if (engineContext.InputManager.IsKeyPressed(Keys.D8))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(70);

                if (engineContext.InputManager.IsKeyPressed(Keys.T))
                {
                    if (particlePlugin != null)
                    {
                        particlePlugin.EnableSorting = !particlePlugin.EnableSorting;
                    }
                }

            }
        }
Beispiel #22
0
        public static async Task SetupFactory(EngineContext engineContext, string effectName = "Simple")
        {
            var renderingSetup = RenderingSetup.Singleton;

            renderingSetup.RegisterLighting(engineContext);

            // Setup lighting
            LightingPlugin lightingPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("LightingPlugin", out lightingPlugin))
            {
                var shadowMapEntity = new Entity();
                shadowMapEntity.Set(TransformationComponent.Key, TransformationTRS.CreateComponent());
                shadowMapEntity.Set(LightComponent.Key, new LightComponent { Type = LightType.Directional, Intensity = 0.9f, Color = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(-1.0f, -1.0f, -1.0f), ShadowMap = true, DecayStart = 40000.0f });
                engineContext.EntityManager.AddEntity(shadowMapEntity);
            }

            // Load asset
            var entity = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/factoryfbx.hotei#");

            // Flip it and scale it
            var transformationComponent = (TransformationTRS)entity.Transformation.Value;
            transformationComponent.Scaling *= 0.1f;

            //await engineContext.EntitySystem.Prepare(entity);
            await engineContext.EntityManager.AddEntityAsync(entity);
        }
        /// <summary>
        /// Update the IFC Classification (from the UI) into the document.
        /// </summary>
        /// <param name="document">The document storing the saved Classification.</param>
        /// <param name="fileHeaderItem">The Classification item to save.</param>
        public static void UpdateClassification(Document document, IFCClassification classification)
        {
            // TO DO: To handle individual item and not the whole since in the future we may support multiple classification systems!!!
            Schema schema = GetSchema();
            if (schema != null)
            {
                IList<DataStorage> oldSavedClassification = GetClassificationInStorage(document, schema);
                if (oldSavedClassification.Count > 0)
                {
                    Transaction deleteTransaction = new Transaction(document, "Delete old IFC Classification");
                    deleteTransaction.Start();
                    List<ElementId> dataStorageToDelete = new List<ElementId>();
                    foreach (DataStorage dataStorage in oldSavedClassification)
                    {
                        dataStorageToDelete.Add(dataStorage.Id);
                    }
                    document.Delete(dataStorageToDelete);
                    deleteTransaction.Commit();
                }
            }

            // Update the address using the new information
            if (schema != null)
            {
                Transaction transaction = new Transaction(document, "Update saved IFC classification");
                transaction.Start();

                DataStorage classificationStorage = DataStorage.Create(document);

                Entity entIFCClassification = new Entity(schema);
                if (classification.ClassificationName != null) entIFCClassification.Set<string>(s_ClassificationName, classification.ClassificationName.ToString());
                if (classification.ClassificationSource != null) entIFCClassification.Set<string>(s_ClassificationSource, classification.ClassificationSource.ToString());
                if (classification.ClassificationEdition != null) entIFCClassification.Set<string>(s_ClassificationEdition, classification.ClassificationEdition.ToString());
                if (classification.ClassificationEditionDate != null)
                {
                    entIFCClassification.Set<Int32>(s_ClassificationEditionDate_Day, classification.ClassificationEditionDate.Day);
                    entIFCClassification.Set<Int32>(s_ClassificationEditionDate_Month, classification.ClassificationEditionDate.Month);
                    entIFCClassification.Set<Int32>(s_ClassificationEditionDate_Year, classification.ClassificationEditionDate.Year);
                }
                if (classification.ClassificationLocation != null) entIFCClassification.Set<string>(s_ClassificationLocation, classification.ClassificationLocation.ToString());
                if (classification.ClassificationFieldName != null) entIFCClassification.Set<string>(s_ClassificationFieldName, classification.ClassificationFieldName.ToString());
                classificationStorage.SetEntity(entIFCClassification);
                transaction.Commit();
            }
        }
        /// <summary>
        /// Delete any obsolete schemas in the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <remarks>This creates a transaction, so it should be called outside of a transaction.</remarks>
        public static void DeleteObsoleteSchemas(Document document)
        {
            Schema schemaV1 = GetSchemaV1();
            // Potentially delete obsolete schema.
            if (schemaV1 != null)
            {
                Schema schema = GetSchema();

                IList<IFCClassification> classifications;
                bool hasOldClassifications = GetSavedClassifications(document, schemaV1, out classifications);
                if (hasOldClassifications)
                {
                    try
                    {
                        Transaction transaction = new Transaction(document, "Upgrade saved IFC classification");
                        transaction.Start();

                        IList<DataStorage> oldSchemaData = GetClassificationInStorage(document, schemaV1);
                        IList<ElementId> oldDataToDelete = new List<ElementId>();

                        foreach (DataStorage oldData in oldSchemaData)
                        {
                            Entity savedClassification = oldData.GetEntity(schemaV1);

                            DataStorage classificationStorage = DataStorage.Create(document);
                            Entity entIFCClassification = new Entity(schema);
                            string classificationName = savedClassification.Get<string>(s_ClassificationName);
                            if (classificationName != null) entIFCClassification.Set<string>(s_ClassificationName, classificationName);

                            string classificationSource = savedClassification.Get<string>(s_ClassificationSource);
                            if (classificationSource != null) entIFCClassification.Set<string>(s_ClassificationSource, classificationSource);

                            string classificationEdition = savedClassification.Get<string>(s_ClassificationEdition);
                            if (classificationEdition != null) entIFCClassification.Set<string>(s_ClassificationEdition, classificationEdition);

                            Int32 classificationEditionDateDay = savedClassification.Get<Int32>(s_ClassificationEditionDate_Day);
                            Int32 classificationEditionDateMonth = savedClassification.Get<Int32>(s_ClassificationEditionDate_Month);
                            Int32 classificationEditionDateYear = savedClassification.Get<Int32>(s_ClassificationEditionDate_Year);

                            entIFCClassification.Set<Int32>(s_ClassificationEditionDate_Day, classificationEditionDateDay);
                            entIFCClassification.Set<Int32>(s_ClassificationEditionDate_Month, classificationEditionDateMonth);
                            entIFCClassification.Set<Int32>(s_ClassificationEditionDate_Year, classificationEditionDateYear);

                            string classificationLocation = savedClassification.Get<string>(s_ClassificationLocation);
                            if (classificationLocation != null) entIFCClassification.Set<string>(s_ClassificationLocation, classificationLocation);

                            classificationStorage.SetEntity(entIFCClassification);
                            oldDataToDelete.Add(oldData.Id);
                        }

                        if (oldDataToDelete.Count > 0)
                            document.Delete(oldDataToDelete);
                        transaction.Commit();
                    }
                    catch
                    {
                        // We don't really care if it fails, but we don't want it to crash export.  Eventually we should log this.
                    }
                }
            }
        }
    public Result Execute(
      ExternalCommandData commandData,
      ref string message,
      ElementSet elements)
    {
      UIDocument uiDoc = commandData.Application.ActiveUIDocument;
      Document doc = uiDoc.Document;

      // Create transaction for working with schema

      Transaction trans = new Transaction(doc, "Extensible Storage");
      trans.Start();

      // Select a wall element

      Wall wall = null;

      try
      {
        Reference r = uiDoc.Selection.PickObject(ObjectType.Element,
          new WallSelectionFilter());

        wall = doc.GetElement(r) as Wall;
      }
      catch (Autodesk.Revit.Exceptions.OperationCanceledException)
      {
        message = "Nothing selected; please select a wall to attach extensible data to.";
        return Result.Failed;
      }

      Debug.Assert(null != wall, "expected a wall to be selected");

      if (null == wall)
      {
        message = "Please select a wall to attach extensible data to.";
        return Result.Failed;
      }

      // Create a schema builder

      SchemaBuilder builder = new SchemaBuilder(_guid);

      // Set read and write access levels

      builder.SetReadAccessLevel(AccessLevel.Public);
      builder.SetWriteAccessLevel(AccessLevel.Public);

      // Note: if this was set as vendor or application access, 
      // we would have been additionally required to use SetVendorId

      // Set name to this schema builder

      builder.SetSchemaName("WallSocketLocation");
      builder.SetDocumentation("Data store for socket related info in a wall");

      // Create field1

      FieldBuilder fieldBuilder1 =
        builder.AddSimpleField("SocketLocation", typeof(XYZ));

      // Set unit type

      fieldBuilder1.SetUnitType(UnitType.UT_Length);

      // Add documentation (optional)

      // Create field2

      FieldBuilder fieldBuilder2 =
        builder.AddSimpleField("SocketNumber", typeof(string));

      //fieldBuilder2.SetUnitType(UnitType.UT_Custom);

      // Register the schema object

      Schema schema = builder.Finish();

      // Create an entity (object) for this schema (class)

      Entity ent = new Entity(schema);
      Field socketLocation = schema.GetField("SocketLocation");
      ent.Set<XYZ>(socketLocation, new XYZ(2, 0, 0), DisplayUnitType.DUT_METERS);

      Field socketNumber = schema.GetField("SocketNumber");
      ent.Set<string>(socketNumber, "200");

      wall.SetEntity(ent);

      // Now create another entity (object) for this schema (class)

      Entity ent2 = new Entity(schema);
      Field socketNumber1 = schema.GetField("SocketNumber");
      ent2.Set<String>(socketNumber1, "400");
      wall.SetEntity(ent2);

      // Note: this will replace the previous entity on the wall 

      // List all schemas in the document

      string s = string.Empty;
      IList<Schema> schemas = Schema.ListSchemas();
      foreach (Schema sch in schemas)
      {
        s += "\r\nSchema Name: " + sch.SchemaName;
      }
      TaskDialog.Show("Schema details", s);

      // List all Fields for our schema

      s = string.Empty;
      Schema ourSchema = Schema.Lookup(_guid);
      IList<Field> fields = ourSchema.ListFields();
      foreach (Field fld in fields)
      {
        s += "\r\nField Name: " + fld.FieldName;
      }
      TaskDialog.Show("Field details", s);

      // Extract the value for the field we created

      Entity wallSchemaEnt = wall.GetEntity(Schema.Lookup(_guid));

      XYZ wallSocketPos = wallSchemaEnt.Get<XYZ>(
        Schema.Lookup(_guid).GetField("SocketLocation"),
        DisplayUnitType.DUT_METERS);

      s = "SocketLocation: " + Format.PointString(wallSocketPos);

      string wallSocketNumber = wallSchemaEnt.Get<String>(
        Schema.Lookup(_guid).GetField("SocketNumber"));

      s += "\r\nSocketNumber: " + wallSocketNumber;

      TaskDialog.Show("Field values", s);

      trans.Commit();

      return Result.Succeeded;
    }
Beispiel #26
0
 public override Entity CreateEntityOfSchema()
 {
     Entity entity = new Entity(GetOrCreateSchema());
      entity.Set("someBool", true);
      return entity;
 }
Beispiel #27
0
        public void TestEntitySetup()
        {
            // Create some components.
              Component stats = new StatsComponent();
              Component pos = new PosComponent();

              Assert.AreEqual(null, stats.Entity);
              Assert.AreEqual(null, pos.Entity);

              // Create an entity, it starts with nothing but an id.
              Entity ent = new Entity("1")
            // Give it some components (using a handly fluent interface idiom).
            .Set(stats)
            .Set(pos);

              // Read the components back. Thanks to generic magic, we don't need to
              // refer to component families explicitly at all.
              StatsComponent stats2;
              Assert.IsTrue(ent.TryGet(out stats2));
              Assert.AreEqual(stats, stats2);

              PosComponent pos2;
              Assert.IsTrue(ent.TryGet(out pos2));
              Assert.AreEqual(pos, pos2);

              Assert.AreEqual(ent, stats.Entity);
              Assert.AreEqual(ent, pos.Entity);

              // Now for a somewhat subtle pitfall from the generic magic:
              try
              {
            // We declare something as just a Component and try to get it.
            Component comp;
            ent.TryGet(out comp);
            Assert.Fail("Exception didn't happen.");
              }
              catch(ApplicationException)
              {
            // The base component class doesn't have a valid family. Trying to get
            // a variable without a subcomponent type that has a specified family
            // causes a runtime exception.
              }

              // Another bad thing to do is to add a Component without a proper
              // GetFamily method:
              try
              {
            ent.Set(new BadComponent());
            Assert.Fail("Exception didn't happen.");
              }
              catch(ApplicationException)
              {
            // This also crashes, since the component type fails to describe
            // itself properly.
              }

              // Checking for null components.
              try
              {
            ent.Set(null);
            Assert.Fail("Exception didn't happen.");
              }
              catch(ArgumentNullException)
              {
              }

              // Removing a component.
              ent.Clear(pos.Family);

              Assert.IsTrue(ent.TryGet(out stats2));

              Assert.IsFalse(ent.TryGet(out pos2));

              Assert.AreEqual(ent, stats.Entity);
              Assert.AreEqual(null, pos.Entity);
        }
        /// <summary>
        /// Updates the setups to save into the document.
        /// </summary>
        public void UpdateSavedConfigurations()
        {
            // delete the old schema and the DataStorage.
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                IList<DataStorage> oldSavedConfigurations = GetSavedConfigurations(m_schema);
                if (oldSavedConfigurations.Count > 0)
                {
                    Transaction deleteTransaction = new Transaction(IFCCommandOverrideApplication.TheDocument, 
                        Properties.Resources.DeleteOldSetups);
                    try
                    {
                        deleteTransaction.Start();
                        List<ElementId> dataStorageToDelete = new List<ElementId>();
                        foreach (DataStorage dataStorage in oldSavedConfigurations)
                        {
                            dataStorageToDelete.Add(dataStorage.Id);
                        }
                        IFCCommandOverrideApplication.TheDocument.Delete(dataStorageToDelete);
                        deleteTransaction.Commit();
                    }
                    catch (System.Exception)
                    {
                        if (deleteTransaction.HasStarted())
                            deleteTransaction.RollBack();
                    }
                }
            }

            // update the configurations to new map schema.
            if (m_mapSchema == null)
            {
                m_mapSchema = Schema.Lookup(s_mapSchemaId);
            }

            // Are there any setups to save or resave?
            List<IFCExportConfiguration> setupsToSave = new List<IFCExportConfiguration>();
            foreach (IFCExportConfiguration configuration in m_configurations.Values)
            {
                if (configuration.IsBuiltIn)
                    continue;

                // Store in-session settings in the cached in-session configuration
                if (configuration.IsInSession)
                {
                    IFCExportConfiguration.SetInSession(configuration);
                    continue;
                }

                setupsToSave.Add(configuration);
           }

           // If there are no setups to save, and if the schema is not present (which means there are no
           // previously existing setups which might have been deleted) we can skip the rest of this method.
            if (setupsToSave.Count <= 0 && m_mapSchema == null)
               return;

           if (m_mapSchema == null)
           {
               SchemaBuilder builder = new SchemaBuilder(s_mapSchemaId);
               builder.SetSchemaName("IFCExportConfigurationMap");
               builder.AddMapField(s_configMapField, typeof(String), typeof(String));
               m_mapSchema = builder.Finish();
           }

           // Overwrite all saved configs with the new list
           Transaction transaction = new Transaction(IFCCommandOverrideApplication.TheDocument, Properties.Resources.UpdateExportSetups);
           try
           {
               transaction.Start();
               IList<DataStorage> savedConfigurations = GetSavedConfigurations(m_mapSchema);
               int savedConfigurationCount = savedConfigurations.Count<DataStorage>();
               int savedConfigurationIndex = 0;
               foreach (IFCExportConfiguration configuration in setupsToSave)
               {
                   DataStorage configStorage;
                   if (savedConfigurationIndex >= savedConfigurationCount)
                   {
                       configStorage = DataStorage.Create(IFCCommandOverrideApplication.TheDocument);
                   }
                   else
                   {
                       configStorage = savedConfigurations[savedConfigurationIndex];
                       savedConfigurationIndex++;
                   }

                   Entity mapEntity = new Entity(m_mapSchema);
                   IDictionary<string, string> mapData = new Dictionary<string, string>();
                   mapData.Add(s_setupName, configuration.Name);
                   mapData.Add(s_setupVersion, configuration.IFCVersion.ToString());
                   mapData.Add(s_setupFileFormat, configuration.IFCFileType.ToString());
                   mapData.Add(s_setupSpaceBoundaries, configuration.SpaceBoundaries.ToString());
                   mapData.Add(s_setupQTO, configuration.ExportBaseQuantities.ToString());
                   mapData.Add(s_setupCurrentView, configuration.VisibleElementsOfCurrentView.ToString());
                   mapData.Add(s_splitWallsAndColumns, configuration.SplitWallsAndColumns.ToString());
                   mapData.Add(s_setupExport2D, configuration.Export2DElements.ToString());
                   mapData.Add(s_setupExportRevitProps, configuration.ExportInternalRevitPropertySets.ToString());
                   mapData.Add(s_setupExportIFCCommonProperty, configuration.ExportIFCCommonPropertySets.ToString());
                   mapData.Add(s_setupUse2DForRoomVolume, configuration.Use2DRoomBoundaryForVolume.ToString());
                   mapData.Add(s_setupUseFamilyAndTypeName, configuration.UseFamilyAndTypeNameForReference.ToString());
                   mapData.Add(s_setupExportPartsAsBuildingElements, configuration.ExportPartsAsBuildingElements.ToString());
                   mapData.Add(s_useActiveViewGeometry, configuration.UseActiveViewGeometry.ToString());
                   mapData.Add(s_setupExportSpecificSchedules, configuration.ExportSpecificSchedules.ToString());
                   mapData.Add(s_setupExportBoundingBox, configuration.ExportBoundingBox.ToString());
                   mapData.Add(s_setupExportSolidModelRep, configuration.ExportSolidModelRep.ToString());
                   mapData.Add(s_setupExportSchedulesAsPsets, configuration.ExportSchedulesAsPsets.ToString());
                   mapData.Add(s_setupExportUserDefinedPsets, configuration.ExportUserDefinedPsets.ToString());
                   mapData.Add(s_setupExportUserDefinedPsetsFileName, configuration.ExportUserDefinedPsetsFileName);
                   mapData.Add(s_setupExportLinkedFiles, configuration.ExportLinkedFiles.ToString());
                   mapData.Add(s_setupIncludeSiteElevation, configuration.IncludeSiteElevation.ToString());
                   mapData.Add(s_setupStoreIFCGUID, configuration.StoreIFCGUID.ToString());
                   mapData.Add(s_setupActivePhase, configuration.ActivePhaseId.ToString());
                   mapData.Add(s_setupExportRoomsInView, configuration.ExportRoomsInView.ToString());
                   mapEntity.Set<IDictionary<string, String>>(s_configMapField, mapData);

                   configStorage.SetEntity(mapEntity);
               }

               List<ElementId> elementsToDelete = new List<ElementId>();
               for (; savedConfigurationIndex < savedConfigurationCount; savedConfigurationIndex++)
               {
                   DataStorage configStorage = savedConfigurations[savedConfigurationIndex];
                   elementsToDelete.Add(configStorage.Id);
               }
               if (elementsToDelete.Count > 0)
                   IFCCommandOverrideApplication.TheDocument.Delete(elementsToDelete);

               transaction.Commit();
           }
           catch (System.Exception)
           {
               if (transaction.HasStarted())
                   transaction.RollBack();
           }
        }
        /// <summary>
        /// Updates the entity in the pipe fitting and accessory pressure drop UI data. 
        /// </summary>
        /// <param name="data">
        /// The pipe fitting and accessory pressure drop UI data.
        /// </param>
        /// <param name="dbServerId">
        /// The corresponding DB server Id of the UI server.
        /// </param>
        /// <param name="schemaField">
        /// The schema field to be updated.
        /// </param>
        /// <param name="newValue">
        /// The new value to be set to the schema field.
        /// </param>
        /// <returns>
        /// True if the entity in the UI data is updated, false otherwise.
        /// </returns>
        public static bool UpdateEntities(PipeFittingAndAccessoryPressureDropUIData data, Guid dbServerId, string schemaField, string newValue)
        {
            bool isUpdated = false;

             ExternalService service = ExternalServiceRegistry.GetService(ExternalServices.BuiltInExternalServices.PipeFittingAndAccessoryPressureDropService);
             if (service == null)
            return isUpdated;

             IPipeFittingAndAccessoryPressureDropServer dbServer = service.GetServer(dbServerId) as IPipeFittingAndAccessoryPressureDropServer;
             if (dbServer == null)
             {
            return isUpdated;
             }

             Schema schema = dbServer.GetDataSchema();
             if (schema == null)
            return isUpdated;

             Field field = schema.GetField(schemaField);
             if (field == null)
            return isUpdated;

             Entity entity = new Entity(schema);
             entity.Set<string>(field, newValue);

             IList<PipeFittingAndAccessoryPressureDropUIDataItem> uiDataItems = data.GetUIDataItems();
             foreach (PipeFittingAndAccessoryPressureDropUIDataItem uiDataItem in uiDataItems)
             {

            Entity oldEntity = uiDataItem.GetEntity();
            if (oldEntity == null && entity == null)
            {
               continue;
            }

            if (oldEntity == null || entity == null)
            {
               uiDataItem.SetEntity(entity);
               isUpdated = true;
               continue;
            }

            if ((!oldEntity.IsValid()) && (!entity.IsValid()))
            {
               continue;
            }

            if ((!oldEntity.IsValid()) || (!entity.IsValid()))
            {
               uiDataItem.SetEntity(entity);
               isUpdated = true;
               continue;
            }

            string oldValue = oldEntity.Get<string>(schemaField);
            if (oldValue != newValue)
            {
               uiDataItem.SetEntity(entity);
               isUpdated = true;
               continue;
            }
             }

             return isUpdated;
        }
 /// <summary>
 /// Fills required attributes
 /// </summary>
 /// <param name="entity">entity for filling</param>
 /// <param name="attributes">Required attributes.</param>
 public void AddAttributes(Entity entity, IDictionary<string, object> attributes) {
     if (attributes == null) {
         return;
     }
     foreach(var attributeName in attributes.Keys) {
         entity.Set(attributeName, attributes[attributeName]);
     }
 }