Beispiel #1
0
        static void Main(string[] args)
        {
            ReplaceInFile("C:\\Users\\Javier\\Desktop\\hola.txt", "C:\\Users\\Javier\\Desktop\\hola3.txt", "las personas","el mundo");
            ///////////////////////////
            //Se prueba objeto entity
            ///////////////////////////

            //Método Set (no case sensitive)
            Entity e = new Entity();
            e.Set("Nombre", "Javier");
            e.Set("Nombre", "Alonso");
            e.Set("Apellido", "Alvarez");
            e.Set("edad", 20);
            e.Set("fecha_nacimiento", new DateTime(1992,2,2));

            //Método Get (no case sensitive)
            Console.WriteLine("Información de Javier:");
            Console.WriteLine("Nombre: " + (string)e.Get("Nombre"));
            Console.WriteLine("Apellido: " + (string)e.Get("apellido"));
            Console.WriteLine("Edad: " + (int)e.Get("edad"));
            Console.WriteLine("Fecha de Nacimiento: " + (DateTime)e.Get("fecha_nacimiento"));

            ///////////////////////////
            ///////////////////////////

            ManejadorBaseDatos.Instancia.EjecutarScript("AYA");
            ///////////////////////////
            //Se prueba DA
            ///////////////////////////

            // Prueba Carga XML con DA
            Entities sp = new XMLLoader().loadXML("C://Users//Javier//.netbeans//7.1.2//config//GF3//domain1//tmsite//da//da.xml");

            // Prueba Ejecutar SP con objeto entity
            Entity parametros = new Entity();
            parametros.Set("pID", 1);
            parametros.Set("pCarro","Toyota");
            parametros.Set("pNombre","Javier");

            ///////////////////////////
            ///////////////////////////

            Console.ReadKey();
        }
Beispiel #2
0
        public void Update(Entity e, KeyboardState s)
        {
            var v = Vector2.Zero;
            if (s.IsKeyDown(Keys.Left )) { v.X -= 1; }
            if (s.IsKeyDown(Keys.Right)) { v.X += 1; }
            if (s.IsKeyDown(Keys.Down )) { v.Y += 1; }
            if (s.IsKeyDown(Keys.Up   )) { v.Y -= 1; }

            if (v != Vector2.Zero) {
                v.Normalize();
            }

            e.Set(Located.Velocity, v * e.Get(MovementSpeed));
        }
Beispiel #3
0
        public void GetComponents_Should_return_fast_access_to_component()
        {
            using World world = new World(4);

            Entity entity1 = world.CreateEntity();
            Entity entity2 = world.CreateEntity();
            Entity entity3 = world.CreateEntity();
            Entity entity4 = world.CreateEntity();

            entity1.Set("1");
            entity2.Set("2");
            entity3.Set("3");
            entity4.Set("4");

            Components <string> strings = world.GetComponents <string>();

            Check.That(entity1.Get <string>()).IsEqualTo(strings[entity1]);
            Check.That(entity2.Get <string>()).IsEqualTo(strings[entity2]);
            Check.That(entity3.Get <string>()).IsEqualTo(strings[entity3]);
            Check.That(entity4.Get <string>()).IsEqualTo(strings[entity4]);
        }
        public virtual T Get(Func <T, bool> where,
                             params Expression <Func <T, object> >[] navigationProperties)
        {
            T item = null;

            using (var context = new Entity())
            {
                IQueryable <T> dbQuery = context.Set <T>();

                //Apply eager loading
                foreach (Expression <Func <T, object> > navigationProperty in navigationProperties)
                {
                    dbQuery = dbQuery.Include <T, object>(navigationProperty);
                }

                item = dbQuery
                       .AsNoTracking()         //Don't track any changes for the selected item
                       .FirstOrDefault(where); //Apply where clause
            }
            return(item);
        }
Beispiel #5
0
        public void Apply(Entity entity)
        {
            SkeletonSquadComponent squad = entity.Get <SkeletonSquadComponent>();

            foreach (var e in squad.Value)
            {
                if (e.Has <ActiveSkeletonComponent>())
                {
                    e.Remove <ActiveSkeletonComponent>();
                }
            }

            Entity skeleton = _factory.MakeSkeleton();

            skeleton.Set(new ActiveSkeletonComponent());

            squad.Value.Add(skeleton);
            entity.Set(squad);

            entity.World.Publish(new SkeletonSpawnedMessage());
        }
        public void UpdateMovesPlayerToNextFloorIfPlayerStandsAboveStairsDownAndShiftDotKeysAreDown(Keys shiftKey)
        {
            // Arrange
            const int StairsX = 3;
            const int StairsY = 3;

            var player = new Entity();

            player.Set(new MoveToKeyboardComponent(player));
            var system = new MovementSystem(player);

            var map = new ArrayMap <AbstractMapTile>(5, 5);

            for (var y = 0; y < map.Height; y++)
            {
                for (var x = 0; x < map.Width; x++)
                {
                    map[x, y] = new FloorTile();
                }
            }

            map[StairsX, StairsY] = new StairsDownTile();
            EventBus.Instance.Broadcast("Map changed", map);

            player.Position.X = StairsX;
            player.Position.Y = StairsY;

            SadConsole.Global.KeyboardState.KeysDown.Add(AsciiKey.Get(shiftKey));
            SadConsole.Global.KeyboardState.KeysDown.Add(AsciiKey.Get(Keys.OemPeriod));

            bool usedStairs = false;

            EventBus.Instance.Register <string>("Player used stairs", (floorNumber) => usedStairs = true);

            // Act
            system.Update(0);

            // Assert
            Assert.That(usedStairs, Is.True);
        }
        public RandomMovement()
        {
            var world      = GameContext.World;
            var mapContext = GameContext.Map;

            _tree = new BehaviourTreeBuilder()
                    .Sequence("start")
                    .Do("check activity", t =>
            {
                if (entity.Has <BaseAction>())
                {
                    return(BehaviourTreeStatus.Running);
                }
                return(BehaviourTreeStatus.Success);
            })
                    .Sequence("createPath")
                    .Do("await", t =>
            {
                if (_time <= 1)
                {
                    _time += 0.007f;
                    return(BehaviourTreeStatus.Running);
                }
                _time = 0;
                return(BehaviourTreeStatus.Success);
            })
                    .Do("create", t =>
            {
                if (!TryGetPoint(out var point, mapContext))
                {
                    return(BehaviourTreeStatus.Success);
                }
                if (mapContext.PathFinder.TryGetPath(_objectToMove, point, out var first, out var last, 1f))
                {
                    entity.Set <BaseAction>(first);
                }

                return(BehaviourTreeStatus.Success);
            })
Beispiel #8
0
        public void LinkTo(Entity?possibleEntity)
        {
            if (possibleEntity == null)
            {
                Debug.LogWarning("Not linked!");
                return;
            }

            Entity        entity = (Entity)possibleEntity;
            ViewComponent view   = entity.Has <ViewComponent>()
                ? entity.Get <ViewComponent>()
                : new ViewComponent {
                Value = new HashSet <IRenderable>()
            };

            foreach (IRenderable renderable in gameObject.GetComponentsInChildren <IRenderable>())
            {
                view.Value.Add(renderable);
            }

            entity.Set(view);
        }
        public void Update(GameTime time, Entity entity)
        {
            var newState = MouseExtended.GetState();

            if (!CanHandleInput(newState))
            {
                mouseState = newState;
                return;
            }

            var position = entity.Get <Position>();
            var pointed  = GameContext.PointedEntity != null?GameContext.PointedEntity.Value.Get <Position>() : null;

            BaseAction after       = null;
            var        mapPosition = mouseState.MapPosition(GameContext.Camera);

            if (pointed != null)
            {
                after = GetAfterAction(entity, GameContext.PointedEntity.Value);
            }
            else if (!GameContext.Map.MovementGrid.IsWalkableAt(mapPosition.X, mapPosition.Y))
            {
                return;
            }

            if (GameContext.Map.PathFinder.TryGetPath(position, mapPosition, out var first, out var last, 2f))
            {
                if (after != null)
                {
                    var action = last ?? first;
                    action.Alternative = after;
                    action.Abort();
                }

                entity.Set <BaseAction>(first);
            }

            mouseState = newState;
        }
Beispiel #10
0
        public void GetAllComponents_Should_return_component()
        {
            using World world = new World(2);

            world.SetMaximumComponentCount <int>(2);
            Entity entity  = world.CreateEntity();
            Entity entity2 = world.CreateEntity();

            entity.Set(1);
            entity2.Set(2);

            Span <int> components = world.GetAllComponents <int>();

            Check.That(components[0]).IsEqualTo(entity.Get <int>());
            Check.That(components[1]).IsEqualTo(entity2.Get <int>());

            components[0] = 10;
            components[1] = 20;

            Check.That(components[0]).IsEqualTo(entity.Get <int>());
            Check.That(components[1]).IsEqualTo(entity2.Get <int>());
        }
        public void UpdateChangesPlayerPositionIfNewPositionIsWalkable(bool isDestinationWalkable)
        {
            // Arrange
            var player = new Entity();
            var system = new MovementSystem(player);

            player.Set(new MoveToKeyboardComponent(player));
            player.Position.X = 3;
            system.Add(player);
            player.Position.Y = 3;

            var playerMoved = false;

            var map = new ArrayMap <AbstractMapTile>(5, 5);

            for (var y = 0; y < map.Height; y++)
            {
                for (var x = 0; x < map.Width; x++)
                {
                    map[x, y] = new FloorTile();
                }
            }

            map[player.Position.X - 1, player.Position.Y].IsWalkable = isDestinationWalkable;
            SadConsole.Global.KeyboardState.KeysPressed.Add(AsciiKey.Get(Keys.Left));

            // Update the map in the movement system
            EventBus.Instance.Broadcast("Map changed", map);
            EventBus.Instance.Register <Player>("Player moved", (data) => playerMoved = true);

            var expectedX = isDestinationWalkable ? player.Position.X - 1 : player.Position.X;

            // Act
            system.Update(0);

            // Assert
            Assert.That(player.Position.X, Is.EqualTo(expectedX));       // Position changed
            Assert.That(playerMoved, Is.EqualTo(isDestinationWalkable)); // Event fired (or not)
        }
Beispiel #12
0
 /// <summary>
 /// Add to an entity to make it represent a sprite that will not move.
 /// </summary>
 public static void StaticSprite(Entity entity, Vector2 position, Texture2D texture, Rectangle source = default)
 {
     if (source == default)
     {
         var aa = new AABB(position.X, position.Y, texture.Width, texture.Height);
         entity.Set(aa);
         entity.Set(new SpriteC(texture));
         entity.Set(new Transform(position.X, position.Y));
     }
     else
     {
         var aa = new AABB(position.X, position.Y, source.Width, source.Height);
         entity.Set(aa);
         entity.Set(new SpriteC(texture, Color.White, source));
         entity.Set(new Transform(position.X, position.Y));
     }
 }
        void ActorHandler(Entity e, GameObjectTypeInfo type, TiledMapObject tiledMapObj)
        {
            if (type.TypeName == "player")
            {
                e.Set(new Storage());
                GameContext.Player = e;
                e.Set <IGameAI>(new PlayerControl());
            }
            if (type.TypeName == "enemy")
            {
                var sprite = e.Get <RenderingObject>();
                e.Set(new Cursor("sword", new Rectangle((int)sprite.Origin.X, (int)sprite.Origin.Y, sprite.Bounds.Width, sprite.Bounds.Height)));
                e.Set(GameObjectType.Enemy);
                e.Set <IGameAI>(new RandomMovement());
            }

            e.Set(new ActionPoints
            {
                Max    = 10,
                Remain = 10
            });
            e.Set(new Serializable());
            e.Set(new AllowedToAct());
        }
        public void Update_Should_call_update()
        {
            using (World world = new World(3))
            {
                Entity entity1 = world.CreateEntity();
                entity1.Set <bool>();

                Entity entity2 = world.CreateEntity();
                entity2.Set <bool>();

                Entity entity3 = world.CreateEntity();
                entity3.Set <bool>();

                using (ISystem <int> system = new System(world))
                {
                    system.Update(0);
                }

                Check.That(entity1.Get <bool>()).IsTrue();
                Check.That(entity2.Get <bool>()).IsTrue();
                Check.That(entity3.Get <bool>()).IsTrue();
            }
        }
Beispiel #15
0
        public void Optimize_Should_sort_inner_storages()
        {
            using World world   = new World();
            using EntitySet set = world.GetEntities().With <int>().AsSet();

            Entity e1 = world.CreateEntity();
            Entity e2 = world.CreateEntity();
            Entity e3 = world.CreateEntity();
            Entity e4 = world.CreateEntity();

            e4.Set(4);
            e3.Set(3);
            e2.Set(2);
            e1.Set(1);

            Check.That(set.GetEntities().ToArray()).ContainsExactly(e4, e3, e2, e1);
            Check.That(world.Get <int>().ToArray()).ContainsExactly(4, 3, 2, 1);

            world.Optimize();

            Check.That(set.GetEntities().ToArray()).ContainsExactly(e1, e2, e3, e4);
            Check.That(world.Get <int>().ToArray()).ContainsExactly(1, 2, 3, 4);
        }
 public static void AddEntityData(this Element elem, Document doc, string entityFileName = "TS_Mark", string data = "mark")
 {
     doc.Invoke(m =>
     {
         SchemaBuilder schemaBuilder = new SchemaBuilder(new Guid("11111111-aaaa-2222-bbbb-333333333333"));
         // allow anyone to read the object
         schemaBuilder.SetReadAccessLevel(AccessLevel.Public);
         // restrict writing to this vendor only
         schemaBuilder.SetWriteAccessLevel(AccessLevel.Public);
         // create a field to store an XYZ
         FieldBuilder fieldBuilder = schemaBuilder.AddSimpleField(entityFileName, typeof(string));
         //fieldBuilder.SetUnitType(UnitType.UT_Length);
         fieldBuilder.SetDocumentation("A mark for TS");
         schemaBuilder.SetSchemaName(data);
         Schema schema = schemaBuilder.Finish(); // register the Schema object
         // create an entity (object) for this schema (class)
         Entity entity = new Entity(schema);
         // get the field from the schema
         Field fieldSpliceLocation = schema.GetField(entityFileName);
         entity.Set <string>(fieldSpliceLocation, data); // set the value for this entity
         elem.SetEntity(entity);                         // store the entity in the element
     });
 }
Beispiel #17
0
        public static void UpdateRegexRuleInExtensibleStorage(string documentGuid, string regexRuleGuid, RegexRule newRegexRule)
        {
            Document document = RegularApp.DocumentCacheService.GetDocument(documentGuid);
            KeyValuePair <DataStorage, Entity> ruleInExtensibleStorage = GetRegexRuleInExtensibleStorage(documentGuid, regexRuleGuid);
            Entity regexRuleEntity = ruleInExtensibleStorage.Value;

            if (regexRuleEntity == null)
            {
                return;
            }
            DataStorage dataStorage = ruleInExtensibleStorage.Key;

            string    serializedRegexRule = regexRuleEntity.Get <string>("SerializedRegexRule");
            RegexRule regexRule           = SerializationUtils.DeserializeRegexRule(serializedRegexRule);
            string    previousName        = regexRule.RuleName;

            using (Transaction transaction = new Transaction(document, $"Regular - Modifying Rule {previousName}"))
            {
                transaction.Start();
                regexRuleEntity.Set("SerializedRegexRule", SerializationUtils.SerializeRegexRule(newRegexRule));
                dataStorage.SetEntity(regexRuleEntity);
                transaction.Commit();
            }
        }
Beispiel #18
0
        //----------------------------------------------------------
        public static void SetDataStorage(Material material, string guid, string name_para, string value)
        {
            try
            {
                SchemaBuilder sb1 = new SchemaBuilder(new Guid(guid));
                sb1.SetReadAccessLevel(AccessLevel.Public);
                sb1.SetWriteAccessLevel(AccessLevel.Public);
                sb1.SetVendorId("pentacons");
                sb1.SetSchemaName(name_para);

                FieldBuilder fieldUser = sb1.AddSimpleField(name_para, typeof(string));
                fieldUser.SetDocumentation("Set");
                Schema schema = sb1.Finish();
                Entity entity = new Entity(schema);

                Field field = schema.GetField(name_para);
                entity.Set(field, value);
                material.SetEntity(entity);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #19
0
        /// <summary>
        /// 通过storageEntity获取对应dataField的值
        /// </summary>
        public static string GetData(Document doc, IExtensibleStorageEntity storageEntity, string dataField)
        {
            var    schema = GetSchema(storageEntity.SchemaId, storageEntity.SchemaName, storageEntity.FieldNames);
            Entity entity;
            var    storage = GetStorageByName(doc, storageEntity.StorageName);

            if (storage == null)
            {
                storage = CreateStorage(doc, storageEntity.StorageName);
                entity  = new Entity(schema);
                entity.Set <string>(schema.GetField(dataField), "");
                storage.SetEntity(entity);
            }
            entity = storage.GetEntity(schema);
            if (entity.IsValid())
            {
                return(entity.Get <string>(schema.GetField(dataField)));
            }
            else
            {
                RemoveStorage(doc, storageEntity);
                return(GetData(doc, storageEntity, dataField));
            }
        }
Beispiel #20
0
        /// <summary>
        /// Update the linked database
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool UpdateLinkedDatabase(Document doc, string fileName)
        {
            bool updated = false;

            try
            {
                if (null == settingSchema)
                {
                    settingSchema = CreateSettingSchema();
                }

                if (null != settingSchema)
                {
                    IList <DataStorage> savedStorage = GetDataStorage(doc, settingSchema);
                    if (savedStorage.Count > 0)
                    {
                        foreach (DataStorage ds in savedStorage)
                        {
                            doc.Delete(ds.Id);
                        }
                    }

                    DataStorage storage = DataStorage.Create(doc);
                    Entity      entity  = new Entity(settingSchemaId);
                    entity.Set <string>(s_linkedDBName, fileName);

                    storage.SetEntity(entity);
                    updated = true;
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
            return(updated);
        }
        public void Update_Should_not_call_update_When_disabled()
        {
            using (World world = new World(3))
            {
                Entity entity1 = world.CreateEntity();
                entity1.Set <bool>();

                Entity entity2 = world.CreateEntity();
                entity2.Set <bool>();

                Entity entity3 = world.CreateEntity();
                entity3.Set <bool>();

                using (ISystem <int> system = new System(world))
                {
                    system.IsEnabled = false;
                    system.Update(0);
                }

                Check.That(entity1.Get <bool>()).IsFalse();
                Check.That(entity2.Get <bool>()).IsFalse();
                Check.That(entity3.Get <bool>()).IsFalse();
            }
        }
Beispiel #22
0
        /// <summary>
        ///     Sets the IEnumerable type field's value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        public static void SetListFieldValue <T>(this Entity entity, string fieldName, IEnumerable <T> value)
        {
            if (entity is null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            if (fieldName is null)
            {
                throw new ArgumentNullException(nameof(fieldName));
            }

            if (value is null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (!typeof(T).IsPrimitive)
            {
                throw new NotSupportedException(nameof(T));
            }

            entity.Set(fieldName, value);
        }
Beispiel #23
0
        public void ContainsEntity_Should_return_weither_an_entity_is_in_or_not()
        {
            using World world = new World();

            Entity entity = world.CreateEntity();

            entity.Set(42);

            using EntityMap <int> map = world.GetEntities().AsMap <int>();

            Check.That(map.ContainsEntity(entity)).IsTrue();

            entity.Disable <int>();

            Check.That(map.ContainsEntity(entity)).IsFalse();

            entity.Enable <int>();

            Check.That(map.ContainsEntity(entity)).IsTrue();

            entity.Remove <int>();

            Check.That(map.ContainsEntity(entity)).IsFalse();
        }
Beispiel #24
0
        /// <summary>
        /// 取数据Collection
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public static PipeAnnotationEntityCollection GetCollection(Document doc)
        {
            if (Collection != null)
            {
                return(Collection);
            }

            var    schema  = GetSchema(SchemaId, SchemaName);
            var    storage = GetStorage(doc);
            Entity entity;

            if (storage == null)
            {
                storage = CreateStorage(doc, StorageName);
                entity  = new Entity(schema);
                entity.Set <string>(schema.GetField(FieldName), "");
                storage.SetEntity(entity);
            }
            entity = storage.GetEntity(schema);
            string data = entity.Get <string>(schema.GetField(FieldName));

            Collection = new PipeAnnotationEntityCollection(data);
            return(Collection);
        }
        public void Copy_Should_return_different_instance()
        {
            using World world = new();

            EntityQueryBuilder builder = world.GetEntities().WithEither <bool>().WithoutEither <double>().With((in bool b) => b);
            EntityQueryBuilder copy    = builder.Copy();

            Check.That(copy).IsNotEqualTo(builder);

            using EntitySet s1 = builder.With <int>().AsSet();
            using EntitySet s2 = copy.Without <int>().AsSet();

            Entity e  = world.CreateEntity();
            Entity e1 = world.CreateEntity();
            Entity e2 = world.CreateEntity();

            e.Set(false);
            e1.Set(true);
            e1.Set(42);
            e2.Set(true);

            Check.That(s1.GetEntities().ToArray()).ContainsExactly(e1);
            Check.That(s2.GetEntities().ToArray()).ContainsExactly(e2);
        }
Beispiel #26
0
        public void Execute(UIApplication uiapp)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name);

                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("ClearValues");

                    Schema schema_FurnLocations_Index = Schema.Lookup(new Guid(Schema_FurnLocations.myConstantStringSchema_FurnLocations_Index));
                    Entity ent_Parent = doc.ProjectInformation.GetEntity(schema_FurnLocations_Index);

                    IDictionary <string, Entity> dict_Parent = ent_Parent.Get <IDictionary <string, Entity> >("FurnLocations_Index", DisplayUnitType.DUT_MILLIMETERS);

                    dict_Parent.Clear();

                    ent_Parent.Set <IDictionary <string, Entity> >("FurnLocations_Index", dict_Parent, DisplayUnitType.DUT_MILLIMETERS);

                    doc.ProjectInformation.SetEntity(ent_Parent);

                    tx.Commit();
                }
            }

            #region catch and finally
            catch (Exception ex)
            {
                _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE13_ExtensibleStorage_ClearAndEmpty" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion
        }
Beispiel #27
0
        public static bool SetLinkedHostInfo(Element massElement, string hostCategory, string hostUniqueId, XYZ centroid, double userHeight)
        {
            bool result = false;

            try
            {
                if (null == m_schema)
                {
                    m_schema = CreateSchema();
                }

                if (null != m_schema)
                {
                    Entity entity = massElement.GetEntity(m_schema);
                    if (entity.IsValid())
                    {
                        massElement.DeleteEntity(m_schema);
                    }
                    entity = new Entity(m_schema);
                    entity.Set <string>(m_schema.GetField(s_SourceCategory), hostCategory);
                    entity.Set <string>(m_schema.GetField(s_LinkedSourceId), hostUniqueId);
#if RELEASE2021
                    entity.Set <XYZ>(m_schema.GetField(s_SourceCentroid), centroid, UnitTypeId.Feet);
                    entity.Set <double>(m_schema.GetField(s_MassHeight), userHeight, UnitTypeId.Feet);
#else
                    entity.Set <XYZ>(m_schema.GetField(s_SourceCentroid), centroid, DisplayUnitType.DUT_DECIMAL_FEET);
                    entity.Set <double>(m_schema.GetField(s_MassHeight), userHeight, DisplayUnitType.DUT_DECIMAL_FEET);
#endif
                    massElement.SetEntity(entity);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to set linked mass info.\n" + ex.Message, "Set Linked Masses", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(result);
        }
        /// <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_setupExportUserDefinedParameterMapping, configuration.ExportUserDefinedParameterMapping.ToString());
                    mapData.Add(s_setupExportUserDefinedParameterMappingFileName, configuration.ExportUserDefinedParameterMappingFileName);
                    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());
                    mapData.Add(s_useOnlyTriangulation, configuration.UseOnlyTriangulation.ToString());
                    mapData.Add(s_excludeFilter, configuration.ExcludeFilter.ToString());
                    mapData.Add(s_setupSitePlacement, configuration.SitePlacement.ToString());
                    mapData.Add(s_useTypeNameOnlyForIfcType, configuration.UseTypeNameOnlyForIfcType.ToString());
                    mapData.Add(s_useVisibleRevitNameAsEntityName, configuration.UseVisibleRevitNameAsEntityName.ToString());
                    // For COBie v2.4
                    mapData.Add(s_cobieCompanyInfo, configuration.COBieCompanyInfo);
                    mapData.Add(s_cobieProjectInfo, configuration.COBieProjectInfo);
                    mapData.Add(s_includeSteelElements, configuration.IncludeSteelElements.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();
                }
            }
        }
Beispiel #29
0
        /// <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)
            {
                Transaction transaction = new Transaction(document, "Update saved IFC File Header");
                transaction.Start();

                IList <DataStorage> oldSavedFileHeader = GetFileHeaderInStorage(document, m_schema);
                if (oldSavedFileHeader.Count > 0)
                {
                    List <ElementId> dataStorageToDelete = new List <ElementId>();
                    foreach (DataStorage dataStorage in oldSavedFileHeader)
                    {
                        dataStorageToDelete.Add(dataStorage.Id);
                    }
                    document.Delete(dataStorageToDelete);
                }

                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 Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiDoc =
                commandData.Application.ActiveUIDocument;

            Reference r;

            try
            {
                r = uiDoc.Selection.PickObject(ObjectType.Element);
            }
            catch (Exception ex)
            {
                return(Result.Cancelled);
            }

            var element =
                uiDoc
                .Document
                .GetElement(r.ElementId);
            // Create a new instance of the class
            IntEntity intEntity =
                new IntEntity();

            // Set property value
            intEntity.SomeValue = 777;

            // attach to the element
            element.SetEntity(intEntity);


            //read entity
            var intEntity2 =
                element.GetEntity <IntEntity>();

            if (intEntity2 != null)
            {
                TaskDialog.Show(intEntity2.GetType().Name, intEntity2.SomeValue.ToString());
            }


            // 1. Looking for the schema in the memory
            Schema schema = Schema.Lookup(new Guid("4E5B6F62-B8B3-4A2F-9B06-DDD953D4D4BC"));

            // 2. Check if schema exists in the memory or not
            if (schema == null)
            {
                //3. Create it, if not
                schema = CreateSchema();
            }

            // 4. Create entity of the specific schema
            var entity = new Entity(schema);

            // 5. Set the value for the Field.
            // HERE WE HAVE TO REMEMEBER THE NAME OF THE SCHEMA FIELD
            entity.Set("SomeValue", 888);

            // 6. Attach entity to the element
            element.SetEntity(entity);

            // read

            var schema2 =
                Schema.Lookup(new Guid("4E5B6F62-B8B3-4A2F-9B06-DDD953D4D4BC"));

            if (schema2 != null)
            {
                var entity2   = element.GetEntity(schema2);
                var someValue =
                    entity2.Get <int>("SomeValue");
                TaskDialog.Show("Entity value", someValue.ToString());
            }


            //write entity with map and array field

            // Check if schema exists in the memory.
            var schema3 =
                Schema.Lookup(new Guid("1899FD3C-7046-4B53-945A-AA1370B8C577"));

            if (schema3 == null)
            {
                // create if not
                schema3 = CreateComplexSchema();
            }

            var entity4 =
                new Entity(schema3);

            //Map fields
            IDictionary <int, Entity> mapOfEntities =
                new Dictionary <int, Entity>();

            // create sub-entity 1
            var entity7 =
                new Entity(new Guid("4E5B6F62-B8B3-4A2F-9B06-DDD953D4D4BC"));

            entity7.Set("SomeValue", 7);

            // create sub-entity 2
            var entity8 =
                new Entity(new Guid("4E5B6F62-B8B3-4A2F-9B06-DDD953D4D4BC"));

            entity8.Set("SomeValue", 8);

            mapOfEntities.Add(7, entity7);
            mapOfEntities.Add(8, entity8);

            entity4.Set("MapField", mapOfEntities);

            element.SetEntity(entity4);


            //Change value in map field

            var entity10 =
                element.GetEntity(schema3);

            var mapField =
                entity10.Get <IDictionary <int, Entity> >("MapField");

            if (mapField != null)
            {
                if (mapField.ContainsKey(8))
                {
                    var entity11 = mapField[8];
                    entity11.Set("SomeValue", 999);

                    // write changes =
                    entity10.Set("MapField", mapField);

                    element.SetEntity(entity10);
                }
            }


            // the same with Extension
            ComplexEntity complexEntity =
                new ComplexEntity();

            complexEntity.MapField =
                new Dictionary <int, IntEntity>
            {
                { 9, new IntEntity()
                  {
                      SomeValue = 9
                  } },
                { 10, new IntEntity()
                  {
                      SomeValue = 10
                  } }
            };

            element.SetEntity(complexEntity);

            //Change value in map field
            var complexEntity2 =
                element.GetEntity <ComplexEntity>();

            if (complexEntity2 != null)
            {
                if (complexEntity.MapField.ContainsKey(9))
                {
                    var entityInMapField =
                        complexEntity.MapField[9];
                    entityInMapField.SomeValue = 9898;

                    element.SetEntity(complexEntity2);
                }
            }

            return(Result.Succeeded);
        }
Beispiel #31
0
        // The Execute method for the updater
        public void Execute(UpdaterData data)
        {
            try
            {
                Document       doc     = data.GetDocument();
                FamilyInstance window  = doc.get_Element(m_windowId) as FamilyInstance;
                Element        section = doc.get_Element(m_sectionId);

                // iterate through modified elements to find the one we want the section to follow
                foreach (ElementId id in data.GetModifiedElementIds())
                {
                    if (id == m_windowId)
                    {
                        //Let's take this out temporarily.
                        bool enableLookup = false;
                        if (enableLookup)
                        {
                            m_schema = Schema.Lookup(m_schemaId); // (new Guid("{4DE4BE80-0857-4785-A7DF-8A8918851CB2}"));
                        }
                        Entity storedEntity = null;
                        storedEntity = window.GetEntity(m_schema);

                        //
                        // first we look-up X-Y-Z parameters, which we know are set on our windows
                        // and the values are set to the current coordinates of the window instance
                        Field fieldPosition = m_schema.GetField("Position");
                        XYZ   oldPosition   = storedEntity.Get <XYZ>(fieldPosition, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);

                        TaskDialog.Show("Old position", oldPosition.ToString());

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

                        // XYZ has operator overloads
                        XYZ translationVec = newPosition - oldPosition;

                        // move the section by the same vector
                        if (!translationVec.IsZeroLength())
                        {
                            ElementTransformUtils.MoveElement(doc, section.Id, translationVec);
                        }
                        TaskDialog.Show("Moving", "Moving");

                        // Lookup the normal vector (i,j,we assume k=0)
                        Field fieldOrientation = m_schema.GetField("Orientation");
                        // Establish the old and new orientation vectors
                        XYZ oldNormal = storedEntity.Get <XYZ>(fieldOrientation, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);


                        XYZ newNormal = window.FacingOrientation;

                        // If different, rotate the section by the angle around the location point of the window

                        double angle = oldNormal.AngleTo(newNormal);

                        // Need to adjust the rotation angle based on the direction of rotation (not covered by AngleTo)
                        XYZ    cross = oldNormal.CrossProduct(newNormal).Normalize();
                        double sign  = 1.0;
                        if (!cross.IsAlmostEqualTo(XYZ.BasisZ))
                        {
                            sign = -1.0;
                        }
                        angle *= sign;
                        if (Math.Abs(angle) > 0)
                        {
                            Line axis = doc.Application.Create.NewLineBound(newPosition, newPosition + XYZ.BasisZ);
                            ElementTransformUtils.RotateElement(doc, section.Id, axis, angle);
                        }

                        // update the parameters on the window instance (to be the current position and orientation)
                        storedEntity.Set <XYZ>(fieldPosition, newPosition, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);


                        storedEntity.Set <XYZ>(fieldOrientation, newNormal, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES);
                        window.SetEntity(storedEntity);
                    }
                }
            }
            catch (System.Exception ex)
            {
                TaskDialog.Show("Exception", ex.ToString());
            }


            return;
        }
        public DefaultGame()
        {
            _deviceManager  = new GraphicsDeviceManager(this);
            IsFixedTimeStep = false;
            _deviceManager.GraphicsProfile                = GraphicsProfile.HiDef;
            _deviceManager.IsFullScreen                   = true;
            _deviceManager.PreferredBackBufferWidth       = ResolutionWidth;
            _deviceManager.PreferredBackBufferHeight      = ResolutionHeight;
            _deviceManager.SynchronizeWithVerticalRetrace = false;
            _deviceManager.ApplyChanges();
            GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
            GraphicsDevice.BlendState      = BlendState.AlphaBlend;
            Content.RootDirectory          = "Content";

            _batch = new SpriteBatch(GraphicsDevice);
            using (Stream stream = File.OpenRead(@"Content\square.png"))
            {
                _square = Texture2D.FromStream(GraphicsDevice, stream);
            }
            _font = Content.Load <SpriteFont>("font");

            _world = new World();

            EntityMap <GridId> grid = _world.GetEntities().With <Behavior>().AsMap <GridId>(BoidsCount);

            _runner = new DefaultParallelRunner(Environment.ProcessorCount);
            _system = new SequentialSystem <float>(
                new ResetBehaviorSystem(_world, _runner),
                new SetBehaviorSystem(_world, _runner, grid),
                new BoidsSystem(_world, _runner, grid),
                new MoveSystem(_world, _runner));

            _drawSystem = new DrawSystem(_square, _world, _runner);

            _world.CreateBehaviors();

            Random random = new();

            for (int i = 0; i < BoidsCount; ++i)
            {
                Entity entity = _world.CreateEntity();
                entity.Set(new DrawInfo
                {
                    Color    = new Color((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), 1f),
                    Position = new Vector2((float)random.NextDouble() * _deviceManager.PreferredBackBufferWidth, (float)random.NextDouble() * _deviceManager.PreferredBackBufferHeight),
                    Size     = new Vector2(random.Next(10, 15), random.Next(20, 30)),
                });

                Vector2 velocity = new((float)random.NextDouble() - .5f, (float)random.NextDouble() - .5f);
                if (velocity != Vector2.Zero)
                {
                    velocity.Normalize();
                }

                entity.Set(new Velocity {
                    Value = velocity * (MinVelocity + ((float)random.NextDouble() * (MaxVelocity - MinVelocity)))
                });
                entity.Set <Acceleration>();
                entity.Set(entity.Get <DrawInfo>().Position.ToGridId());
            }

            _world.Optimize();

            _watch = Stopwatch.StartNew();
        }
Beispiel #33
0
 private void FormEllipsePoints(Entity entity)
 {
     ellipsePoints = entity.Get<List<Vector2D>>();
     ellipsePoints.Clear();
     ellipsePoints.Add(center);
     for (int i = 0; i < pointsCount; i++)
         FormRotatedEllipsePoint(i);
     entity.Set(ellipsePoints);
 }