Example #1
0
        /// <summary>Creates a new, AI controlled ship.</summary>
        /// <param name="manager">The manager.</param>
        /// <param name="blueprint">The blueprint.</param>
        /// <param name="faction">The faction the ship will belong to.</param>
        /// <param name="position">The position.</param>
        /// <param name="random">The random.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns>The new ship.</returns>
        public static int CreateAIShip(
            IManager manager,
            string blueprint,
            Factions faction,
            FarPosition position,
            IUniformRandom random,
            ArtificialIntelligence.AIConfiguration configuration = null)
        {
            var entity = FactoryLibrary.SampleShip(manager, blueprint, faction, position, random);

            var input = (ShipControl)manager.GetComponent(entity, ShipControl.TypeId);

            input.Stabilizing = true;
            manager.AddComponent <ArtificialIntelligence>(entity).
            Initialize(random != null ? random.NextUInt32() : 0, configuration).Enabled = false;

            // Add to the index from which entities will automatically removed
            // on cell death and mark it (for translation checks into empty space).
            manager.AddComponent <Indexable>(entity).Initialize(CellSystem.CellDeathAutoRemoveIndexId);
            manager.AddComponent <CellDeath>(entity).Initialize(true);

            // Add to AI index, to allow putting the AI to sleep.
            manager.AddComponent <Indexable>(entity).Initialize(SleepSystem.IndexId);

            return(entity);
        }
Example #2
0
        /// <summary>Renders a single planet.</summary>
        /// <param name="component">The component.</param>
        /// <param name="translation">The translation.</param>
        private void RenderPlanet(PlanetRenderer component, ref FarPosition translation)
        {
            // Get factory, skip if none known.
            var factory = component.Factory;

            if (factory == null)
            {
                return;
            }

            // Load the texture if we don't have it yet.
            LoadPlanetTextures(factory, component, ((ContentSystem)Manager.GetSystem(ContentSystem.TypeId)).Content);

            // The position and orientation we're rendering at and in.
            var transform = ((ITransform)Manager.GetComponent(component.Entity, TransformTypeId));
            var position  = transform.Position;
            var rotation  = transform.Angle;

            // Get position relative to our sun, to rotate atmosphere and shadow.
            var toSun = Vector2.Zero;
            var sun   = GetSun(component.Entity);

            if (sun > 0)
            {
                var sunTransform = ((ITransform)Manager.GetComponent(sun, TransformTypeId));
                if (sunTransform != null)
                {
                    toSun = (Vector2)(sunTransform.Position - position);
                    var matrix = Matrix.CreateRotationZ(-rotation);
                    Vector2.Transform(ref toSun, ref matrix, out toSun);
                    toSun.Normalize();
                }
            }

            // Apply transformation.
            _planet.Center = (Vector2)FarUnitConversion.ToScreenUnits(position + translation);

            // Set remaining parameters for draw.
            _planet.Rotation = rotation;
            _planet.SetSize(component.Radius * 2);
            _planet.SurfaceTexture       = component.Albedo;
            _planet.SurfaceNormals       = component.Normals;
            _planet.SurfaceSpecular      = component.Specular;
            _planet.SurfaceLights        = component.Lights;
            _planet.Clouds               = component.Clouds;
            _planet.SurfaceTint          = factory.SurfaceTint;
            _planet.SpecularAlpha        = factory.SpecularAlpha;
            _planet.SpecularExponent     = factory.SpecularExponent;
            _planet.SpecularOffset       = factory.SpecularOffset;
            _planet.AtmosphereTint       = factory.AtmosphereTint;
            _planet.AtmosphereInner      = factory.AtmosphereInner;
            _planet.AtmosphereOuter      = factory.AtmosphereOuter;
            _planet.AtmosphereInnerAlpha = factory.AtmosphereInnerAlpha;
            _planet.AtmosphereOuterAlpha = factory.AtmosphereOuterAlpha;
            _planet.SurfaceRotation      = component.SurfaceRotation;
            _planet.LightDirection       = toSun;

            // And draw it.
            _planet.Draw();
        }
Example #3
0
        /// <summary>Creates an attacking ship.</summary>
        /// <param name="startPosition">The start position.</param>
        /// <param name="targetPosition">The target position.</param>
        /// <param name="faction">The faction.</param>
        public void CreateAttackingShip(ref FarPosition startPosition, ref FarPosition targetPosition, Factions faction)
        {
            var ship = EntityFactory.CreateAIShip(Manager, "L1_AI_Ship", faction, startPosition, _random);
            var ai   = ((ArtificialIntelligence)Manager.GetComponent(ship, ArtificialIntelligence.TypeId));

            ai.AttackMove(ref targetPosition);
        }
Example #4
0
 public void Drop(string poolName, ref FarPosition position)
 {
     lock (_dropsToSample)
     {
         _dropsToSample.Add(Tuple.Create(poolName, position));
     }
 }
Example #5
0
        /// <summary>Performs the actual drop sampling.</summary>
        /// <param name="poolName">The name of the item pool to sample from.</param>
        /// <param name="position">The position at which to drop the items.</param>
        private void SampleDrop(string poolName, FarPosition position)
        {
            // Get the actual item pool to pull items from.
            var pool = FactoryLibrary.GetItemPool(poolName);

            // Get the list of possible drops.
            var dropInfo = new List <ItemPool.DropInfo>(pool.Items);

            // Randomizer used for sampling of items. Seed it based on the item
            // pool and the drop position, to get a deterministic result for
            // each drop, regardless in which order they happen.
            var hasher = new Hasher();

            hasher.Write(poolName);
            hasher.Write(position);
            var random = new MersenneTwister(hasher.Value);

            // And shuffle it. This is important, to give each entry an equal
            // chance to be picked. Otherwise the first few entries have a much
            // better chance, because we stop after reaching a certain number
            // of items.
            for (var i = dropInfo.Count; i > 1; i--)
            {
                // Pick random element to swap.
                var j = random.NextInt32(i); // 0 <= j <= i - 1
                // Swap.
                var tmp = dropInfo[j];
                dropInfo[j]     = dropInfo[i - 1];
                dropInfo[i - 1] = tmp;
            }

            var dropCount = 0;

            for (int i = 0, j = dropInfo.Count; i < j; i++)
            {
                var item = dropInfo[i];

                // Give the item a chance to be dropped.
                if (item.Probability > random.NextDouble())
                {
                    // Random roll succeeded, drop the item.
                    var entity = FactoryLibrary.SampleItem(Manager, item.ItemName, position, random);

                    // Make the item visible (per default items are hidden).
                    foreach (IDrawable drawable in Manager.GetComponents(entity, DrawableTypeId))
                    {
                        drawable.Enabled = true;
                    }

                    // Did a drop, check if we're done.
                    dropCount++;
                    if (dropCount == pool.MaxDrops)
                    {
                        break;
                    }
                }
            }
        }
Example #6
0
        /// <summary>Samples the attributes to apply to the item.</summary>
        /// <param name="manager">The manager.</param>
        /// <param name="cellCenter">The center of the cell for which the sun system is created.</param>
        /// <param name="random">The randomizer to use.</param>
        /// <return>The entity with the attributes applied.</return>
        public void SampleSunSystem(IManager manager, FarPosition cellCenter, IUniformRandom random)
        {
            var sun = FactoryLibrary.SampleSun(manager, _sun, cellCenter, random);

            if (_planets != null)
            {
                _planets.Sample(manager, sun, random);
            }
        }
Example #7
0
        public static ulong GetSubCellIdFromCoordinates(FarPosition position)
        {
            const float segmentFactor = (float)FarValue.SegmentSize / (float)SubCellSize;
            const float offsetFactor  = 1f / (float)FarValue.SegmentSize * segmentFactor; // = 1f / (float) SubCellSize

            return(BitwiseMagic.Pack(
                       (int)Math.Floor(position.X.Segment * segmentFactor + position.X.Offset * offsetFactor),
                       (int)Math.Floor(position.Y.Segment * segmentFactor + position.Y.Offset * offsetFactor)));
        }
Example #8
0
        /// <summary>Finds the closest friendly station and moves to it, if we're close enough we dock (delete the instance).</summary>
        /// <returns>Whether to do the rest of the update.</returns>
        protected override bool UpdateInternal()
        {
            // See if there are any stations nearby.
            var faction  = ((Faction)AI.Manager.GetComponent(AI.Entity, Faction.TypeId)).Value;
            var position = ((ITransform)AI.Manager.GetComponent(AI.Entity, TransformTypeId)).Position;
            var index    = (IndexSystem)AI.Manager.GetSystem(IndexSystem.TypeId);

            // The closest station we were able to find and how far it is away.
            var closestStation  = 0;
            var distanceSquared = float.MaxValue;

            ISet <int> neighbors = new HashSet <int>();

            index[Detectable.IndexId].Find(position, ScanRange, neighbors);
            foreach (IIndexable neighbor in neighbors.Select(AI.Manager.GetComponentById))
            {
                // See if it's a station.
                // TODO...

                // Friend or foe?
                var neighborFaction = ((Faction)AI.Manager.GetComponent(neighbor.Entity, Faction.TypeId));
                if (neighborFaction != null && (neighborFaction.Value & faction) != 0)
                {
                    // Friend. Closer than any other?
                    var neighborPosition        = ((ITransform)AI.Manager.GetComponent(neighbor.Entity, TransformTypeId)).Position;
                    var neighborDistanceSquared = FarPosition.DistanceSquared(position, neighborPosition);
                    if (neighborDistanceSquared < distanceSquared)
                    {
                        distanceSquared = neighborDistanceSquared;
                        closestStation  = neighbor.Entity;
                    }
                }
            }

            // Do we have a closest station?
            if (closestStation > 0)
            {
                var neighborPosition =
                    ((ITransform)AI.Manager.GetComponent(closestStation, TransformTypeId)).Position;
                // Close enough to dock?
                if (FarPosition.DistanceSquared(position, neighborPosition) < DockingRange * DockingRange)
                {
                    // Yes! Kill ourselves.
                    // TODO: display some particle effects to hint we're docking.
                    AI.Manager.RemoveEntity(AI.Entity);
                }
                else
                {
                    // No. Let's try to get there.
                    AI.AttackMove(ref neighborPosition);
                }
            }

            // We never have anything else to do anyway.
            return(false);
        }
Example #9
0
 /// <summary>
 /// Called by the particle effect when it is triggered.
 /// </summary>
 /// <param name="position">The desired position of the trigger.</param>
 /// <param name="impulse">The impulse.</param>
 /// <param name="rotation">The rotation.</param>
 /// <param name="scale">The scale.</param>
 /// <remarks>
 /// This method should not be called directly, the ParticleEffect class
 /// will defer control to this method when the controller is assigned.
 /// </remarks>
 protected internal virtual void Trigger(ref FarPosition position, ref Vector2 impulse, float rotation = 0.0f, float scale = 1.0f)
 {
     if (this.ParticleEffect != null)
     {
         for (int i = 0; i < this.ParticleEffect.Count; i++)
         {
             this.ParticleEffect[i].Trigger(ref position, ref impulse, rotation, scale);
         }
     }
 }
Example #10
0
        /// <summary>Reset the component to its initial state, so that it may be reused without side effects.</summary>
        public override void Reset()
        {
            base.Reset();

            Delay    = 0;
            Position = FarPosition.Zero;
            ComponentsToDisable.Clear();
            RelativeHealth = 1;
            RelativeEnergy = 1;
        }
Example #11
0
        // TODO in case we need this somewhere else it might be a good idea to move this to the EntityFactory
        private void CreateAsteroid(FarPosition position, IUniformRandom random, ContentManager content)
        {
            // Randomly scale and rotate it.
            var scale = (float)random.NextDouble(0.5f, 1f);
            var angle = (float)random.NextDouble() * MathHelper.TwoPi;

            // Determine shape for physics system.
            var textureName = "Textures/Asteroids/rock_" + random.NextInt32(1, 14);
            var texture     = content.Load <Texture2D>(textureName);
            var hull        = new List <Vector2>(TextureConverter.DetectVertices(texture, 8f, textureName: textureName)[0]);

            for (var k = 0; k < hull.Count; ++k)
            {
                hull[k] -= new Vector2(texture.Width / 2f, texture.Height / 2f);
                hull[k]  = XnaUnitConversion.ToSimulationUnits(hull[k]) * scale;
            }
            var polygons = EarClipDecomposer.ConvexPartition(hull);

            // Create physical representation.
            var entity = Manager.AddEntity();
            var body   = Manager.AddBody(entity, position, angle, Body.BodyType.Dynamic);

            foreach (var polygon in polygons)
            {
                Manager.AttachPolygon(body, polygon, density: 1000f, restitution: 0.2f);
            }
            // Slow down to allow reaching sleep state again.
            body.LinearDamping  = 0.05f * Space.Util.Settings.TicksPerSecond;
            body.AngularDamping = 0.025f * Space.Util.Settings.TicksPerSecond;

            // Bounds of the asteroid for rendering culling. We use the diagonal for a loose fit that
            // contains every possible rotated state of the texture.
            var width    = UnitConversion.ToSimulationUnits(texture.Width);
            var height   = UnitConversion.ToSimulationUnits(texture.Height);
            var diagonal = (float)Math.Sqrt(width * width + height * height);
            var bounds   = new FarRectangle(-diagonal / 2, -diagonal / 2, diagonal, diagonal);

            // Rendering stuff.
            Manager.AddComponent <Indexable>(entity).Initialize(bounds, CameraSystem.IndexId);
            Manager.AddComponent <Indexable>(entity).Initialize(bounds, InterpolationSystem.IndexId);
            Manager.AddComponent <SimpleTextureDrawable>(entity).Initialize(textureName, scale);

            // Auto removal.
            Manager.AddComponent <CellDeath>(entity).Initialize(true);
            Manager.AddComponent <Indexable>(entity).Initialize(CellSystem.CellDeathAutoRemoveIndexId);

            // Make it destructible.
            var health = Manager.AddComponent <Health>(entity);

            health.Value        = health.MaxValue = 200 * scale;
            health.Regeneration = 0f;

            // As they don't move on their own, start asteroids as sleeping to save performance.
            body.IsAwake = false;
        }
Example #12
0
        /// <summary>Samples a new ship with the specified name.</summary>
        /// <param name="manager">The manager.</param>
        /// <param name="name">The logical name of the ship to sample.</param>
        /// <param name="faction">The faction the ship will belong to.</param>
        /// <param name="position">The initial position of the ship.</param>
        /// <param name="random">The randomizer to use.</param>
        /// <returns>The sampled ship.</returns>
        public static int SampleShip(
            IManager manager, string name, Factions faction, FarPosition position, IUniformRandom random)
        {
            if (string.IsNullOrWhiteSpace(name) || !Factories.ContainsKey(name))
            {
                return(0);
            }
            var factory = Factories[name] as ShipFactory;

            return(factory != null?factory.Sample(manager, faction, position, random) : 0);
        }
Example #13
0
        public void Display(int value, FarPosition position, Color color, float scale, float duration)
        {
            // Don't draw stuff that's way off-screen.
            if (!IsInBounds(position))
            {
                return;
            }
            var sb = new StringBuilder();

            sb.Append(value);
            Display(sb, position, color, scale, duration);
        }
Example #14
0
        /// <summary>Samples a new sun system with the specified name.</summary>
        /// <param name="manager">The manager.</param>
        /// <param name="name">The logical name of the ship to sample.</param>
        /// <param name="cellCenter">The center of the cell for which the sun is created.</param>
        /// <param name="random">The randomizer to use.</param>
        /// <returns>The sampled sun.</returns>
        public static void SampleSunSystem(IManager manager, string name, FarPosition cellCenter, IUniformRandom random)
        {
            if (string.IsNullOrWhiteSpace(name) || !Factories.ContainsKey(name))
            {
                return;
            }
            var factory = Factories[name] as SunSystemFactory;

            if (factory != null)
            {
                factory.SampleSunSystem(manager, cellCenter, random);
            }
        }
Example #15
0
        /// <summary>Check if we reached our target.</summary>
        /// <returns>Whether to do the rest of the update.</returns>
        protected override bool UpdateInternal()
        {
            var position = ((ITransform)AI.Manager.GetComponent(AI.Entity, TransformTypeId)).Position;

            if (FarPosition.DistanceSquared(position, Target) < ReachedEpsilon * ReachedEpsilon)
            {
                // We have reached our target, pop self.
                AI.PopBehavior();
                return(false);
            }

            return(true);
        }
Example #16
0
 /// <summary>
 /// Called by the particle effect when it is triggered.
 /// </summary>
 /// <param name="position">The desired position of the trigger.</param>
 /// <param name="impulse"></param>
 /// <param name="rotation"></param>
 /// <param name="scale"></param>
 /// <remarks>
 /// This method should not be called directly, the ParticleEffect class
 /// will defer control to this method when the controller is assigned.
 /// </remarks>
 protected internal override void Trigger(ref FarPosition position, ref Vector2 impulse, float rotation = 0.0f, float scale = 1.0f)
 {
     foreach (TimelineEvent timelineEvent in this.Timeline)
     {
         this.EventQueue.Add(new TimelineEvent
         {
             EmitterName     = timelineEvent.EmitterName,
             TimeOffset      = timelineEvent.TimeOffset + this.TotalSeconds,
             TriggerPosition = position,
             TriggerImpulse  = impulse,
             TriggerRotation = rotation,
             TriggerScale    = scale
         });
     }
 }
Example #17
0
        /// <summary>
        ///     Gets the closest enemy based on the specified criteria. This checks all enemies in the specified range, but
        ///     only takes into consideration those that pass the filter function. The enemy with the lowest distance will be
        ///     returned. Note that the filter function may also "transform" the id, for example to allow selecting the actual
        ///     owner of an entity (normally: projectiles).
        /// </summary>
        /// <param name="range">The maximum range up to which to search.</param>
        /// <param name="filter">The filter function, if any.</param>
        /// <returns></returns>
        protected int GetClosestEnemy(float range, Func <int, int> filter = null)
        {
            // See if there are any enemies nearby, if so attack them.
            var faction     = ((Faction)AI.Manager.GetComponent(AI.Entity, Faction.TypeId)).Value;
            var position    = ((ITransform)AI.Manager.GetComponent(AI.Entity, TransformTypeId)).Position;
            var index       = (IndexSystem)AI.Manager.GetSystem(IndexSystem.TypeId);
            var shipInfo    = (ShipInfo)AI.Manager.GetComponent(AI.Entity, ShipInfo.TypeId);
            var sensorRange = shipInfo != null?UnitConversion.ToSimulationUnits(shipInfo.RadarRange) : 0f;

            sensorRange = sensorRange > 0 ? Math.Min(sensorRange, range) : range;
            ISet <int> neighbors = new HashSet <int>();

            index[PhysicsSystem.IndexId].Find(position, sensorRange, neighbors);
            var closest         = 0;
            var closestDistance = float.PositiveInfinity;

            foreach (IIndexable neighbor in neighbors.Select(AI.Manager.GetComponentById))
            {
                // Apply our filter, if we have one.
                var filteredNeighbor = neighbor.Entity;
                if (filter != null)
                {
                    filteredNeighbor = filter(neighbor.Entity);
                }
                if (filteredNeighbor == 0)
                {
                    continue;
                }
                // Friend or foe? Don't care if it's a friend. Also filter based on passed
                // filter function.
                var neighborFaction = (Faction)AI.Manager.GetComponent(filteredNeighbor, Faction.TypeId);
                if (neighborFaction != null && (neighborFaction.Value & faction) == 0)
                {
                    // It's an enemy. Check the distance.
                    var enemyPosition =
                        ((ITransform)AI.Manager.GetComponent(filteredNeighbor, TransformTypeId)).Position;
                    var distance = FarPosition.Distance(enemyPosition, position);
                    if (distance < closestDistance)
                    {
                        closest         = filteredNeighbor;
                        closestDistance = distance;
                    }
                }
            }

            // Return whatever we found.
            return(closest);
        }
Example #18
0
        /// <summary>Creates a new, player controlled ship.</summary>
        /// <param name="manager">The manager.</param>
        /// <param name="playerClass">The player's class, which determines the blueprint.</param>
        /// <param name="playerNumber">The player for whom to create the ship.</param>
        /// <param name="position">The position at which to spawn and respawn the ship.</param>
        /// <returns>The new ship.</returns>
        public static int CreatePlayerShip(
            IManager manager, PlayerClassType playerClass, int playerNumber, FarPosition position)
        {
            // Player ships must be 'static', i.e. not have random attributes, so we don't need a randomizer.
            var entity = FactoryLibrary.SampleShip(
                manager, playerClass.GetShipFactoryName(), playerNumber.ToFaction(), position, null);

            // Remember the class.
            manager.AddComponent <PlayerClass>(entity).Initialize(playerClass);

            // Mark it as the player's avatar.
            manager.AddComponent <Avatar>(entity).Initialize(playerNumber);

            // Make it respawn (after 5 seconds).
            manager.AddComponent <Respawn>(entity).Initialize(
                (int)(5 * Settings.TicksPerSecond),
                new HashSet <Type>
            {
                // Make ship uncontrollable.
                typeof(ShipControl),
                typeof(WeaponControl),
                // Disable collisions.
                typeof(Body),
                // And movement.
                typeof(Gravitation),
                // Hide it.
                typeof(ShipDrawable),
                typeof(ParticleEffects),
                // And don't regenerate.
                typeof(Health),
                typeof(Energy)
            },
                position);

            // Allow leveling up.
            manager.AddComponent <Experience>(entity).Initialize(100, 100f, 2.15f);

            // Make player ships collide more precisely. We don't much care for NPC ships tunneling
            // through stuff (unlikely as that may be anyways), but we really don't want it to happen
            // for a player ship.
            var body = (Body)manager.GetComponent(entity, Body.TypeId);

            body.IsBullet = true;

            return(entity);
        }
Example #19
0
        /// <summary>
        /// Triggers the ParticleEffect at the specified position.
        /// </summary>
        public virtual void Trigger(ref FarPosition position, ref Vector2 impulse, float rotation = 0.0f, float scale = 1.0f)
        {
            if (this.Controllers.Count > 0)
            {
                for (int i = 0; i < this.Controllers.Count; i++)
                {
                    this.Controllers[i].Trigger(ref position, ref impulse, rotation, scale);
                }
            }

            else
            {
                for (int i = 0; i < this.Count; i++)
                {
                    this[i].Trigger(ref position, ref impulse, rotation, scale);
                }
            }
        }
Example #20
0
        /// <summary>Samples the attributes to apply to the item.</summary>
        /// <param name="manager"> </param>
        /// <param name="faction">The faction the ship belongs to.</param>
        /// <param name="position">The position at which to spawn the ship.</param>
        /// <param name="random">The randomizer to use.</param>
        /// <return>The entity with the attributes applied.</return>
        public int Sample(IManager manager, Factions faction, FarPosition position, IUniformRandom random)
        {
            var entity = CreateShip(manager, faction, position);

            // Create initial equipment.
            var equipment = (ItemSlot)manager.GetComponent(entity, ItemSlot.TypeId);

            equipment.Item = FactoryLibrary.SampleItem(manager, _items.Name, position, random);
            if (equipment.Item > 0)
            {
                foreach (var item in _items.Slots)
                {
                    SampleItems(manager, position, random, equipment.Item, item);
                }
            }

            // Add our attributes.
            var attributes = (Attributes <AttributeType>)manager.GetComponent(entity, Attributes <AttributeType> .TypeId);

            foreach (var attribute in _attributes)
            {
                var modifier = attribute.SampleAttributeModifier(random);
                if (modifier.ComputationType == AttributeComputationType.Multiplicative)
                {
                    throw new InvalidOperationException("Base attributes must be additive.");
                }
                attributes.SetBaseValue(modifier.Type, modifier.Value);
            }

            // Fill up our values.
            var health = ((Health)manager.GetComponent(entity, Health.TypeId));
            var energy = ((Energy)manager.GetComponent(entity, Energy.TypeId));

            health.Value = health.MaxValue;
            energy.Value = energy.MaxValue;

            // Add experience points if we're worth any.
            if (_xp > 0)
            {
                manager.AddComponent <ExperiencePoints>(entity).Initialize(_xp);
            }

            return(entity);
        }
Example #21
0
        /// <summary>Renders the specified sun.</summary>
        /// <param name="component">The component.</param>
        /// <param name="transform">The transform.</param>
        /// <param name="translation">The translation.</param>
        private void RenderSun(SunRenderer component, Matrix transform, FarPosition translation)
        {
            // Get absolute position of sun.
            var position = ((ITransform)Manager.GetComponent(component.Entity, TransformTypeId)).Position;

            // Apply transformation.
            _sun.Center = (Vector2)FarUnitConversion.ToScreenUnits(position + translation);
            _sun.SetTransform(transform);
            _sun.Color = component.Tint;

            // Set remaining parameters for draw.
            _sun.SetSize(component.Radius * 2);
            _sun.SurfaceRotation             = component.SurfaceRotation;
            _sun.PrimaryTurbulenceRotation   = component.PrimaryTurbulenceRotation;
            _sun.SecondaryTurbulenceRotation = component.SecondaryTurbulenceRotation;

            // And draw it.
            _sun.Draw();
        }
Example #22
0
        /// <summary>Initialize with the specified parameters.</summary>
        /// <param name="delay">The delay.</param>
        /// <param name="disableComponents">The disable components.</param>
        /// <param name="position">The position.</param>
        /// <param name="relativeHealth">The relative health.</param>
        /// <param name="relativeEnergy">The relative energy.</param>
        public Respawn Initialize(
            int delay,
            IEnumerable <Type> disableComponents,
            FarPosition position,
            float relativeHealth = 1f,
            float relativeEnergy = 1f)
        {
            Delay    = delay;
            Position = position;
            if (disableComponents != null)
            {
                foreach (var type in disableComponents)
                {
                    ComponentsToDisable.Add(Engine.ComponentSystem.Manager.GetComponentTypeId(type));
                }
            }
            RelativeHealth = relativeHealth;
            RelativeEnergy = relativeEnergy;

            return(this);
        }
Example #23
0
        /// <summary>Samples a new item with the specified name at the specified position.</summary>
        /// <param name="manager">The manager.</param>
        /// <param name="name">The logical name of the item to sample.</param>
        /// <param name="position">The position at which to spawn the item.</param>
        /// <param name="random">The randomizer to use.</param>
        /// <returns>The sampled item.</returns>
        public static int SampleItem(IManager manager, string name, FarPosition position, IUniformRandom random)
        {
            if (string.IsNullOrWhiteSpace(name) || !Factories.ContainsKey(name))
            {
                return(0);
            }
            var factory = Factories[name] as ItemFactory;

            if (factory == null)
            {
                return(0);
            }
            var item      = factory.Sample(manager, random);
            var transform = ((Transform)manager.GetComponent(item, Transform.TypeId));

            if (transform != null)
            {
                transform.Position = position;
                transform.Update();
            }
            return(item);
        }
Example #24
0
        public void Play(string effect, FarPosition position, Vector2 impulse, float rotation = 0.0f, float scale = 1.0f)
        {
            if (!Enabled)
            {
                return;
            }

            // Check if it's in bounds, i.e. whether we have to render it at all.
            var camera = (CameraSystem)Manager.GetSystem(CameraSystem.TypeId);

            if (!camera.ComputeVisibleBounds().Contains(position))
            {
                return;
            }

            // Let there be graphics!
            position = FarUnitConversion.ToScreenUnits(position);
            lock (this)
            {
                GetEffect(effect).Trigger(ref position, ref impulse, rotation, scale);
            }
        }
Example #25
0
        /// <summary>Samples the items for the specified item info and children (recursively).</summary>
        /// <param name="manager">The manager.</param>
        /// <param name="position">The position.</param>
        /// <param name="random">The random.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="itemInfo">The item info.</param>
        private static void SampleItems(
            IManager manager, FarPosition position, IUniformRandom random, int parent, ItemInfo itemInfo)
        {
            // Create the actual item.
            var itemId = FactoryLibrary.SampleItem(manager, itemInfo.Name, position, random);

            if (itemId < 1)
            {
                // No such item.
                return;
            }
            var item = (Item)manager.GetComponent(itemId, Item.TypeId);

            // Then equip it in the parent.
            foreach (ItemSlot slot in manager.GetComponents(parent, ItemSlot.TypeId))
            {
                if (slot.Item == 0 && slot.Validate(item))
                {
                    // Found a suitable empty slot, equip here.
                    slot.Item = itemId;

                    // Recurse to generate children.
                    foreach (var childInfo in itemInfo.Slots)
                    {
                        SampleItems(manager, position, random, itemId, childInfo);
                    }

                    // Done.
                    return;
                }
            }

            // If we get here we couldn't find a slot to equip the item in.
            manager.RemoveEntity(itemId);

            Logger.Warn("Parent item did not have a slot for the requested child item.");
        }
Example #26
0
 public void Display(StringBuilder value, FarPosition position, Color color, float scale, float duration)
 {
     // Don't draw stuff that's way off-screen.
     if (!IsInBounds(position))
     {
         return;
     }
     Debug.Assert(duration > 0);
     lock (this)
     {
         var texture = RenderToTexture(value, scale);
         position.X -= UnitConversion.ToSimulationUnits(texture.Width / 2f);
         position.Y -= UnitConversion.ToSimulationUnits(texture.Height / 2f);
         _texts.Add(
             new FloatingText
         {
             Value           = texture,
             Color           = color,
             Position        = position,
             TotalTimeToLive = (uint)Math.Ceiling(duration * Settings.TicksPerSecond),
             TimeToLive      = (uint)Math.Ceiling(duration * Settings.TicksPerSecond)
         });
     }
 }
Example #27
0
 /// <summary>
 /// Called by the particle effect when it is triggered.
 /// </summary>
 /// <param name="position">The desired position of the trigger.</param>
 /// <param name="impulse"></param>
 /// <param name="rotation"></param>
 /// <param name="scale"></param>
 /// <remarks>
 /// This method should not be called directly, the ParticleEffect class
 /// will defer control to this method when the controller is assigned.
 /// </remarks>
 protected internal override void Trigger(ref FarPosition position, ref Vector2 impulse, float rotation = 0.0f, float scale = 1.0f)
 {
     this.QueuedTriggers.Enqueue(Tuple.Create(position, impulse, rotation, scale));
 }
Example #28
0
 /// <summary>
 ///  Triggers the Emitter at the specified position...
 /// </summary>
 /// <exception cref="System.InvalidOperationException">Thrown if the Emitter has not been initialised.</exception>
 public void Trigger(FarPosition position, Vector2 impulse, float rotation = 0.0f, float scale = 1.0f)
 {
     this.Trigger(ref position, ref impulse, rotation, scale);
 }
Example #29
0
        /// <summary>Reset this behavior so it can be reused later on.</summary>
        public override void Reset()
        {
            base.Reset();

            Target = FarPosition.Zero;
        }
Example #30
0
 /// <summary>
 ///  Triggers the Emitter at the specified position...
 /// </summary>
 /// <exception cref="System.InvalidOperationException">Thrown if the Emitter has not been initialised.</exception>
 public void Trigger(FarPosition position, float rotation = 0.0f, float scale = 1.0f)
 {
     this.Trigger(ref position, rotation, scale);
 }