public override void Update(double dt)
        {
            foreach (var entity in EntityManager.GetAllEntities <CargoComponent>())
            {
                var target = EntityManager.GetComponent <TargetComponent>(entity.Id);
                if (target == null)
                {
                    var currentLocation = EntityManager.GetComponent <PositionComponent>(entity.Id);
                    var closest         =
                        (from person in EntityManager.GetAllEntities <PackageComponent>()
                         where person.Component.Status == PackageStatus.Waiting
                         select new
                    {
                        Person = person,
                        Location = EntityManager.GetComponent <PositionComponent>(person.Component.FromEntity)
                    })
                        .Select(waitingPerson => new {
                        Location = waitingPerson.Location,
                        Distance = Math.Abs(waitingPerson.Location.X - currentLocation.X) + Math.Abs(waitingPerson.Location.Y - currentLocation.Y)
                    })
                        .OrderBy(x => x.Distance)
                        .FirstOrDefault();

                    if (closest != null)
                    {
                        EntityManager.AddComponentToEntity(entity.Id, new TargetComponent {
                            X = closest.Location.X, Y = closest.Location.Y
                        });
                    }
                }
            }
        }
示例#2
0
        public override void Update(double dt)
        {
            foreach (var taxi in EntityManager.GetAllEntities <CargoComponent>())
            {
                if (taxi.Component.People.Count() < taxi.Component.PeopleCapacity)
                {
                    foreach (var person in EntityManager.GetAllEntities <PackageComponent>())
                    {
                        if (person.Component.Status == PackageStatus.Waiting)
                        {
                            var currentPosition    = EntityManager.GetComponent <PositionComponent>(taxi.Id);
                            var fromEntityPosition = EntityManager.GetComponent <PositionComponent>(person.Component.FromEntity);
                            var toEntityPosition   = EntityManager.GetComponent <PositionComponent>(person.Component.ToEntity);

                            if (currentPosition.X == fromEntityPosition.X && currentPosition.Y == fromEntityPosition.Y)
                            {
                                taxi.Component.People.Add(person.Id);
                                EntityManager.AddComponentToEntity(taxi.Id, new TargetComponent {
                                    X = toEntityPosition.X, Y = toEntityPosition.Y
                                });
                                EntityManager.GetComponent <VisualComponent>(taxi.Id).UseAlternativeColor = true;
                                EntityManager.GetComponent <VisualComponent>(person.Component.FromEntity).UseAlternativeColor = false;
                                person.Component.Status = PackageStatus.Moving;
                            }
                        }
                    }
                }
            }
        }
示例#3
0
    static void Main(string[] args)
    {
        #region Composition Root
        var entityManager         = new EntityManager();
        var drawingComponentTypes =
            new Type[] {
            typeof(VisibleComponent),
            typeof(PhysicalComponent)
        };
        var drawingSystem    = new DrawingSystem(drawingComponentTypes);
        var visibleComponent =
            new PoolDecorator <VisibleComponent>(
                new ComponentPool <VisibleComponent>(), entityManager, drawingSystem);
        var physicalComponent =
            new PoolDecorator <PhysicalComponent>(
                new ComponentPool <PhysicalComponent>(), entityManager, drawingSystem);
        entityManager.AddSystems(drawingSystem);
        entityManager.AddComponentPool(visibleComponent);
        entityManager.AddComponentPool(physicalComponent);
        #endregion

        var entity = new Entity(entityManager.CreateEntity());

        entityManager.AddComponentToEntity(
            entity.EntityId,
            new PhysicalComponent()
        {
            X = 0, Y = 0
        });

        Console.WriteLine($"Added physical component, number of drawn entities: {drawingSystem.SystemEntities.Count}.");

        entityManager.AddComponentToEntity(
            entity.EntityId,
            new VisibleComponent()
        {
            Appearance = Appearance.Monster
        });

        Console.WriteLine($"Added visible component, number of drawn entities: {drawingSystem.SystemEntities.Count}.");

        entityManager.RemoveComponentFromEntity <VisibleComponent>(entity.EntityId);

        Console.WriteLine($"Removed visible component, number of drawn entities: {drawingSystem.SystemEntities.Count}.");

        Console.ReadLine();
    }
示例#4
0
        // Outline:
        //      - Each frame, it checks to see if someone is on it. If so, it's triggered.
        //      - If it's not triggered, it advances animation to max, at a certain framerate (could use FrameAnimation)
        //      - If it's triggered, it counts down
        public static void LandMineRiseFall(EntityManager em, ScriptContainer scriptContainer, int entityLiveId, GameTime gameTime)
        {
            float ellapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            bool isTriggered = scriptContainer.PropertyBag.GetBooleanValue(LandMineIsTriggeredId);

            if (!isTriggered)
            {
                Placement   placement = (Placement)em.GetComponent(entityLiveId, ComponentTypeIds.Placement);
                Point       spot      = placement.Position.ToInteger();
                MessageData data      = new MessageData(spot.X, spot.Y, ComponentTypeIds.Player);
                em.SendMessage(Messages.QueryComponentAtGrid, ref data, null);
                if (data.Handled)
                {
                    // Before allowing it to be triggered, the area must be cleared (so the player who dropped it doesn't trigger it)
                    // Check to see if a Player component is on there, and if so set outselves to triggered.
                    if (data.Int32 == EntityManager.InvalidEntityUniqueId)
                    {
                        // No one on it. Now it's ok to be triggered.
                        scriptContainer.PropertyBag.SetValue(LandMineAreaClearedId, true);
                    }

                    bool areaCleared = scriptContainer.PropertyBag.GetBooleanValue(LandMineAreaClearedId);
                    if (areaCleared && (data.Int32 != EntityManager.InvalidEntityUniqueId))
                    {
                        // Someone is on it.
                        isTriggered = true;
                        scriptContainer.PropertyBag.SetValue(LandMineIsTriggeredId, isTriggered);
                        scriptContainer.PropertyBag.SetValue(LandMineFuseCountdownId, scriptContainer.PropertyBag.GetSingleValue(LandMineFuseTimeId));
                    }
                }
            }

            Entity entity = em.GetEntityByLiveId(entityLiveId);

            if (isTriggered)
            {
                float timeLeft = scriptContainer.PropertyBag.GetSingleValue(LandMineFuseCountdownId);
                timeLeft -= ellapsed;
                scriptContainer.PropertyBag.SetValue(LandMineFuseCountdownId, timeLeft);

                if (timeLeft <= 0f)
                {
                    em.SendMessage(entity, Messages.TriggerBomb, null); // BOOM
                }
            }

            // Move up or down based on whether we're triggered.
            bool           allocatedNew;
            FrameAnimation frameAnimation = (FrameAnimation)em.AddComponentToEntity(entity, ComponentTypeIds.FrameAnimation, out allocatedNew);

            frameAnimation.Direction = isTriggered ? -1 : 1;
            frameAnimation.Loop      = false;
            frameAnimation.FrameRate = GameConstants.LandMineAnimationFrameRate;
        }
示例#5
0
        public static void DestroyOnExplosionAndRevealPowerUp(EntityManager em, int entityLiveId, uint message, ref MessageData data)
        {
            // TODO: There is a bug where two power ups can appear in the same spot if that block is hit by
            // two explosions in the same update cycle. We need to check if the block is on the delete list (since
            // we delay deletion). An alternative is that we could just remove the handler?
            Debug.Assert(message == Messages.HitByInitialExplosion);
            em.DelayFreeByLiveId(entityLiveId, EntityFreeOptions.Deep);

            if (random.NextDouble() < GameConstants.PowerUpChance)
            {
                // Choose based on weights
                float totalWeight = 0f;
                foreach (PowerUpProbabilities pup in powerUpTemplates)
                {
                    totalWeight += pup.Probability;
                }
                float  choice    = (float)random.NextDouble();
                string template  = null;
                float  accWeight = 0f;
                foreach (PowerUpProbabilities pup in powerUpTemplates)
                {
                    accWeight += pup.Probability;
                    if (choice <= (accWeight / totalWeight))
                    {
                        template = pup.TemplateName;
                        break;
                    }
                }

                Entity entityPowerUp = em.AllocateForGeneratedContent(template, Universe.TopLevelGroupUniqueIdBase);
                Helpers.TransferPlacement(em, entityLiveId, entityPowerUp.LiveId);
                // Depending on our game settings, power ups may or may not be affected by explosions
                if (true) // For now we'll always assume they are
                {
                    bool           allocatedNew;
                    MessageHandler messageHandler = (MessageHandler)em.AddComponentToEntity(entityPowerUp, ComponentTypeIds.MessageHandler, out allocatedNew);
                    messageHandler.Add(new MessageAndHandler(Messages.HitByInitialExplosion, "SimplyDestroy".CRC32Hash()));
                }
            }
            data.Handled = true;
        }
示例#6
0
        protected override void OnProcessEntities(GameTime gameTime, IEnumerable <int> entityIdCollection)
        {
            float ellapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            foreach (int liveId in entityIdCollection)
            {
                GameState gameState = gameStateComponents.GetComponentFor(liveId);
                entityGrid.Bounds       = gameState.Bounds;
                gameState.TimeRemaining = Math.Max(0, gameState.TimeRemaining - ellapsed);;

                if (cachedBounds != gameState.Bounds)
                {
                    cachedBounds = gameState.Bounds;
                    Util.Helpers.CalculateDeathSpiralPoints(cachedBounds, deathBlockSpiralPoints);
                }

                MaybeSendDeathBlock(gameState);

                // Let's do some other tasks.
                if (!gameState.IsGameOver)
                {
                    MessageData data = new MessageData();
                    EntityManager.SendMessage(Messages.QueryWinningPlayer, ref data, null);
                    if (data.Handled)
                    {
                        gameState.WinningPlayerUniqueId = data.Int32;
                        // The game is over. This is the uniqueId of the player that won.
                        if (gameState.WinningPlayerUniqueId != EntityManager.InvalidEntityUniqueId)
                        {
                            gameState.IsGameOver = true;
                            bool          allocatedNew;
                            InputHandlers ih = (InputHandlers)EntityManager.AddComponentToEntity(EntityManager.GetEntityByLiveId(liveId), ComponentTypeIds.InputHandlers, out allocatedNew);
                            ih.InputHandlerIds.Add("RestartGame".CRC32Hash());
                        }
                    }
                }
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _keyboardInputObservable.SubscribeKey(KeyCombination.LeftAlt && KeyCombination.Enter, CombinationDirection.Down, ToggleFullScren);

            _keyboardInputObservable.SubscribeKey(KeyCombination.Esc, CombinationDirection.Down, Exit);
            _keyboardInputObservable.SubscribeKey(KeyCombination.P, CombinationDirection.Down, () => _camera.Projection = ProjectionMode.Perspective);
            _keyboardInputObservable.SubscribeKey(KeyCombination.O, CombinationDirection.Down, () => _camera.Projection = ProjectionMode.Orthographic);
            _keyboardInputObservable.SubscribeKey(KeyCombination.F, CombinationDirection.Down, () => _synchronizeCameras = !_synchronizeCameras);

            _entityManager = new EntityManager();

            var terrainSystem = new TerrainSystem(FractalBrownianMotionSettings.Default);
            _systems = new List<IEntitySystem>
            {
                terrainSystem,
                new FreeCameraSystem(_keyboardInputProcessor, _mouseInputProcessor,_camera),
                new LightMoverSystem(),
                new OceanSystem(),
                new CubeMeshSystem(),
                new InputSystem(_keyboardInputProcessor)
                //new ChunkedLODSystem(_lodCamera),
                //new RenderSystem(_camera),
            };

            var light = new Entity(Guid.NewGuid().ToString());
            _entityManager.Add(light);
            _entityManager.AddComponentToEntity(light, new PositionalLightComponent { Position = new Vector3d(0, 20, 0) });
            _entityManager.AddComponentToEntity(light, new InputComponent(Key.J, Key.L, Key.M, Key.N, Key.U, Key.I));

            const int numberOfChunksX = 20;
            const int numberOfChunksY = 20;
            for (var i = 0; i < numberOfChunksX; i++)
            {
                for (var j = 0; j < numberOfChunksY; j++)
                {
                    var entity = new Entity(Guid.NewGuid().ToString());
                    _entityManager.Add(entity);
                    _entityManager.AddComponentToEntity(entity, new ChunkComponent(i, j));
                    _entityManager.AddComponentToEntity(entity, new StaticMesh());
                }
            }

            var settingsViewModel = new SettingsViewModel(new NoiseFactory.NoiseParameters());
            settingsViewModel.SettingsChanged += () =>
            {
                var settings = settingsViewModel.Assemble();
                terrainSystem.SetTerrainSettings(new NoiseFactory.RidgedMultiFractal().Create(settings));
            };

            _terrain = new Terrain(new ChunkedLod());
            _cube = new Cube();
        }
        private Node CreateNode(Box3D bounds, int level, EntityManager entityManager)
        {
            var mesh = MeshCreator.CreateXZGrid(10, 10);
            var staticMesh = new StaticMesh
            {
                Color = new Vector4(0f, 0f, 1f, 1f),
                ModelMatrix = Matrix4.Identity,
            };

            var size = bounds.Max - bounds.Min;
            var mesh3V3N = mesh.Transformed(Matrix4.CreateScale((float)size.X, 1, (float)size.Z) * Matrix4.CreateTranslation((Vector3)bounds.Center));
            var improvedPerlinNoise = new ImprovedPerlinNoise(4711);
            for (int i = 0; i < mesh3V3N.Vertices.Length; i++)
            {
                var vertex = mesh3V3N.Vertices[i];
                var height = improvedPerlinNoise.Noise(vertex.Position.X, vertex.Position.Z) * 0.2;
                mesh3V3N.Vertices[i] = new Vertex3V3N
                {
                    Normal = new Vector3(0, 1, 0),
                    Position = new Vector3(vertex.Position.X, (float)height, vertex.Position.Z)
                };
            }

            staticMesh.Update(mesh3V3N);

            var entity = new Entity(Guid.NewGuid().ToString());
            entityManager.Add(entity);
            entityManager.AddComponentToEntity(entity, staticMesh);

            if (level == 0)
            {
                return new Node(bounds, new Node[] { }, entity, 1);
            }

            var min = bounds.Min;
            var max = bounds.Max;
            var center = bounds.Center;

            return new Node(bounds,
                new[]
                {
                    CreateNode(new Box3D(bounds.Min, center), level -1, entityManager),
                    CreateNode(new Box3D(new Vector3d(center.X, 0, min.Z), new Vector3d(max.X, 0, center.Z)), level -1, entityManager),
                    CreateNode(new Box3D(new Vector3d(min.X, 0, center.Z), new Vector3d(center.X, 0, max.Z)), level - 1, entityManager),
                    CreateNode(new Box3D(center, max), level - 1, entityManager)
                }, entity, Math.Pow(2, level));
        }
        public void Update(double elapsedTime, EntityManager entityManager)
        {
            foreach (var water in entityManager.GetEntitiesWithComponent<OceanComponent>())
            {
                var waterComponent = entityManager.GetComponent<OceanComponent>(water);
                var waterMesh = entityManager.GetComponent<StaticMesh>(water);
                if (waterMesh == null)
                {
                    waterMesh = new StaticMesh
                    {
                        Color = new Vector4(0f, 0f, 1f, 0f),
                        ModelMatrix = Matrix4.Identity
                    };
                    entityManager.AddComponentToEntity(water, waterMesh);
                }

                var mesh = CreateMesh(waterComponent);
                waterMesh.Update(mesh);
                for (var i = 0; i < waterMesh.Mesh.Vertices.Length; i++)
                {
                    var position = waterMesh.Mesh.Vertices[i].Position;
                    var vector3D = Gerstner2.CalculateWave((Vector3d)position, elapsedTime, _waveSettings);

                    waterMesh.Mesh.Vertices[i] = new Vertex3V3N
                    {
                        Position = (Vector3)vector3D
                    };
                }
                waterMesh.Mesh.CalculateNormals();
                waterMesh.Update(waterMesh.Mesh);
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();
            StartJobThread();

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _keyboardInputObservable.SubscribeKey(KeyCombination.LeftAlt && KeyCombination.Enter, CombinationDirection.Down, ToggleFullScren);

            _keyboardInputObservable.SubscribeKey(KeyCombination.Esc, CombinationDirection.Down, Exit);
            _keyboardInputObservable.SubscribeKey(KeyCombination.P, CombinationDirection.Down, () => _camera.Projection  = ProjectionMode.Perspective);
            _keyboardInputObservable.SubscribeKey(KeyCombination.O, CombinationDirection.Down, () => _camera.Projection  = ProjectionMode.Orthographic);
            _keyboardInputObservable.SubscribeKey(KeyCombination.F, CombinationDirection.Down, () => _synchronizeCameras = !_synchronizeCameras);

            _entityManager = new EntityManager();

            var terrainSystem = new TerrainSystem(FractalBrownianMotionSettings.Default);

            _systems = new List <IEntitySystem>
            {
                terrainSystem,
                new FreeCameraSystem(_keyboardInputProcessor, _mouseInputProcessor, _camera),
                new LightMoverSystem(),
                new OceanSystem(),
                new CubeMeshSystem(),
                new InputSystem(_keyboardInputProcessor)
                //new ChunkedLODSystem(_lodCamera),
                //new RenderSystem(_camera),
            };

            var light = new Entity(Guid.NewGuid().ToString());

            _entityManager.Add(light);
            _entityManager.AddComponentToEntity(light, new PositionalLightComponent {
                Position = new Vector3d(0, 20, 0)
            });
            _entityManager.AddComponentToEntity(light, new InputComponent(Key.J, Key.L, Key.M, Key.N, Key.U, Key.I));

            const int numberOfChunksX = 20;
            const int numberOfChunksY = 20;

            for (var i = 0; i < numberOfChunksX; i++)
            {
                for (var j = 0; j < numberOfChunksY; j++)
                {
                    var entity = new Entity(Guid.NewGuid().ToString());
                    _entityManager.Add(entity);
                    _entityManager.AddComponentToEntity(entity, new ChunkComponent(i, j));
                    _entityManager.AddComponentToEntity(entity, new StaticMesh());
                }
            }

            var settingsViewModel = new SettingsViewModel(new NoiseFactory.NoiseParameters());

            settingsViewModel.SettingsChanged += () =>
            {
                var settings = settingsViewModel.Assemble();
                terrainSystem.SetTerrainSettings(new NoiseFactory.RidgedMultiFractal().Create(settings));
            };

            _terrain = new Terrain(new ChunkedLod());
            _cube    = new Cube();
        }