private void DoExplorePlanet(MilitaryTask Task)
 {
     bool flag1 = true;
     foreach (Building building in Task.GetTargetPlanet().BuildingList)
     {
         if (!string.IsNullOrEmpty(building.EventTriggerUID))
         {
             flag1 = false;
             break;
         }
     }
     bool flag2 = false;
     foreach (Ship ship in (List<Ship>)this.Ships)
     {
         if (ship.TroopList.Count > 0)
             flag2 = true;
     }
     foreach (PlanetGridSquare planetGridSquare in Task.GetTargetPlanet().TilesList)
     {
         if (planetGridSquare.TroopsHere.Count > 0 && planetGridSquare.TroopsHere[0].GetOwner() == this.Owner)
         {
             flag2 = true;
             break;
         }
     }
     if (flag1 || !flag2 || Task.GetTargetPlanet().Owner != null)
     {
         Task.EndTask();
     }
     else
     {
         switch (this.TaskStep)
         {
             case 0:
                 List<Planet> list1 = new List<Planet>();
                 foreach (Planet planet in this.Owner.GetPlanets())
                 {
                     if (planet.HasShipyard)
                         list1.Add(planet);
                 }
                 IOrderedEnumerable<Planet> orderedEnumerable1 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list1, (Func<Planet, float>)(planet => Vector2.Distance(Task.AO, planet.Position)));
                 if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable1) <= 0)
                     break;
                 Vector2 fVec = Vector2.Normalize(Task.AO - Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position);
                 Vector2 vector2 = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position;
                 this.MoveToNow(vector2, Math.Abs(MathHelper.ToRadians(HelperFunctions.findAngleToTarget(vector2, Task.AO))), fVec);
                 foreach (Ship ship in (List<Ship>)this.Ships)
                     ship.GetAI().HasPriorityOrder = true;
                 this.TaskStep = 1;
                 break;
             case 1:
                 bool flag3 = true;
                 bool flag4 = false;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     if (!ship.disabled && ship.hasCommand && ship.Active)
                     {
                         if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 5000.0)
                             flag3 = false;
                         if (ship.InCombat)
                             flag4 = true;
                         if (!flag3)
                             break;
                     }
                 }
                 if (!flag3 && !flag4)
                     break;
                 this.TaskStep = 2;
                 Vector2 MovePosition = Task.GetTargetPlanet().Position + Vector2.Normalize(this.findAveragePosition() - Task.GetTargetPlanet().Position) * 50000f;
                 this.Position = MovePosition;
                 this.FormationWarpTo(MovePosition, MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.findAveragePosition(), Task.AO)), Vector2.Normalize(Task.AO - this.findAveragePosition()));
                 break;
             case 2:
                 bool flag5 = true;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     ship.GetAI().HasPriorityOrder = false;
                     if (!ship.disabled && ship.hasCommand && ship.Active)
                     {
                         if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 5000.0)
                             flag5 = false;
                         if (!flag5)
                             break;
                     }
                 }
                 if (!flag5)
                     break;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     ship.GetAI().State = AIState.HoldPosition;
                     if (ship.Role == "troop")
                         ship.GetAI().HoldPosition();
                 }
                 this.InterceptorDict.Clear();
                 this.TaskStep = 3;
                 break;
             case 3:
                 this.EnemyClumpsDict.Clear();
                 List<Ship> list2 = new List<Ship>();
                 List<GameplayObject> nearby1 = UniverseScreen.ShipSpatialManager.GetNearby(this.Position);
                 for (int index1 = 0; index1 < nearby1.Count; ++index1)
                 {
                     Ship ship1 = nearby1[index1] as Ship;
                     if (ship1 != null)
                     {
                         ship1.GetAI().HasPriorityOrder = false;
                         if (ship1.loyalty != this.Owner && (ship1.loyalty.isFaction || this.Owner.GetRelations()[ship1.loyalty].AtWar) && (!list2.Contains(ship1) && (double)Vector2.Distance(ship1.Center, Task.AO) < (double)Task.AORadius && !this.EnemyClumpsDict.ContainsKey(ship1.Center)))
                         {
                             this.EnemyClumpsDict.Add(ship1.Center, new List<Ship>());
                             this.EnemyClumpsDict[ship1.Center].Add(ship1);
                             list2.Add(ship1);
                             List<GameplayObject> nearby2 = UniverseScreen.ShipSpatialManager.GetNearby(this.Position);
                             for (int index2 = 0; index2 < nearby2.Count; ++index2)
                             {
                                 Ship ship2 = nearby2[index2] as Ship;
                                 if (ship2 != null && ship2.loyalty != this.Owner && (ship2.loyalty == ship1.loyalty && (double)Vector2.Distance(ship1.Center, ship2.Center) < 10000.0) && !list2.Contains(ship2))
                                     this.EnemyClumpsDict[ship1.Center].Add(ship2);
                             }
                         }
                     }
                 }
                 if (this.EnemyClumpsDict.Count == 0)
                 {
                     this.TaskStep = 5;
                     break;
                 }
                 else
                 {
                     List<Vector2> list3 = new List<Vector2>();
                     foreach (KeyValuePair<Vector2, List<Ship>> keyValuePair in this.EnemyClumpsDict)
                         list3.Add(keyValuePair.Key);
                     IOrderedEnumerable<Vector2> orderedEnumerable2 = Enumerable.OrderBy<Vector2, float>((IEnumerable<Vector2>)list3, (Func<Vector2, float>)(clumpPos => Vector2.Distance(this.findAveragePosition(), clumpPos)));
                     List<Ship> list4 = new List<Ship>();
                     foreach (Ship toAttack in this.EnemyClumpsDict[Enumerable.First<Vector2>((IEnumerable<Vector2>)orderedEnumerable2)])
                     {
                         float num = 0.0f;
                         foreach (Ship ship in (List<Ship>)this.Ships)
                         {
                             if (!list4.Contains(ship) && ((double)num == 0.0 || (double)num < (double)toAttack.GetStrength()))
                             {
                                 ship.GetAI().Intercepting = true;
                                 ship.GetAI().OrderAttackSpecificTarget(toAttack);
                                 list4.Add(ship);
                                 num += ship.GetStrength();
                             }
                         }
                     }
                     List<Ship> list5 = new List<Ship>();
                     foreach (Ship ship in (List<Ship>)this.Ships)
                     {
                         if (!list4.Contains(ship))
                             list5.Add(ship);
                     }
                     foreach (Ship ship in list5)
                         ship.GetAI().OrderAttackSpecificTarget(list4[0].GetAI().Target as Ship);
                     this.TaskStep = 4;
                     if (this.InterceptorDict.Count != 0)
                         break;
                     this.TaskStep = 4;
                     break;
                 }
             case 4:
                 float num1 = 0.0f;
                 float num2 = 0.0f;
                 float num3 = 0.0f;
                 float num4 = 0.0f;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     num1 += ship.Ordinance;
                     num2 += ship.OrdinanceMax;
                     foreach (Weapon weapon in ship.Weapons)
                     {
                         if ((double)weapon.OrdinanceRequiredToFire > 0.0)
                             num3 = weapon.DamageAmount / weapon.fireDelay;
                         if ((double)weapon.PowerRequiredToFire > 0.0)
                             num4 = weapon.DamageAmount / weapon.fireDelay;
                     }
                 }
                 float num5 = num3 + num4;
                 if ((double)num3 >= 0.5 * (double)num5 && (double)num1 <= 0.100000001490116 * (double)num2)
                 {
                     this.TaskStep = 5;
                     break;
                 }
                 else
                 {
                     bool flag6 = false;
                     foreach (Ship ship in (List<Ship>)this.Ships)
                     {
                         if (!ship.InCombat)
                         {
                             flag6 = true;
                             break;
                         }
                     }
                     if (!flag6)
                         break;
                     this.TaskStep = 3;
                     break;
                 }
             case 5:
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     ship.GetAI().Intercepting = true;
                     ship.GetAI().OrderLandAllTroops(Task.GetTargetPlanet());
                 }
                 this.Position = Task.GetTargetPlanet().Position;
                 this.AssembleFleet(this.facing, Vector2.Normalize(this.Position - this.findAveragePosition()));
                 break;
         }
     }
 }
 private void DoGlassPlanet(MilitaryTask Task)
 {
     if (Task.GetTargetPlanet().Owner == this.Owner || Task.GetTargetPlanet().Owner == null)
         Task.EndTask();
     else if (Task.GetTargetPlanet().Owner != null & Task.GetTargetPlanet().Owner != this.Owner && !Task.GetTargetPlanet().Owner.GetRelations()[this.Owner].AtWar)
     {
         Task.EndTask();
     }
     else
     {
         switch (this.TaskStep)
         {
             case 0:
                 List<Planet> list1 = new List<Planet>();
                 foreach (Planet planet in this.Owner.GetPlanets())
                 {
                     if (planet.HasShipyard)
                         list1.Add(planet);
                 }
                 IOrderedEnumerable<Planet> orderedEnumerable1 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list1, (Func<Planet, float>)(planet => Vector2.Distance(Task.AO, planet.Position)));
                 if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable1) <= 0)
                     break;
                 Vector2 fVec = Vector2.Normalize(Task.AO - Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position);
                 Vector2 vector2 = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position;
                 this.MoveToNow(vector2, Math.Abs(MathHelper.ToRadians(HelperFunctions.findAngleToTarget(vector2, Task.AO))), fVec);
                 this.TaskStep = 1;
                 break;
             case 1:
                 bool flag = true;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     if (!ship.disabled && ship.hasCommand && ship.Active)
                     {
                         if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 15000.0)
                             flag = false;
                         int num = ship.InCombat ? 1 : 0;
                         if (!flag)
                             break;
                     }
                 }
                 if (!flag)
                     break;
                 Vector2 MovePosition = Task.GetTargetPlanet().Position + Vector2.Normalize(this.findAveragePosition() - Task.GetTargetPlanet().Position) * 150000f;
                 this.Position = MovePosition;
                 this.FormationWarpTo(MovePosition, MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.findAveragePosition(), Task.AO)), Vector2.Normalize(Task.AO - this.findAveragePosition()));
                 foreach (Ship ship in (List<Ship>)this.Ships)
                     ship.GetAI().HasPriorityOrder = true;
                 this.TaskStep = 2;
                 break;
             case 2:
                 if (Task.WaitForCommand && (double)this.Owner.GetGSAI().ThreatMatrix.PingRadarStr(Task.GetTargetPlanet().Position, 30000f, this.Owner) > 250.0)
                     break;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                     ship.GetAI().OrderBombardPlanet(Task.GetTargetPlanet());
                 this.TaskStep = 4;
                 break;
             case 4:
                 float num1 = 0.0f;
                 float num2 = 0.0f;
                 float num3 = 0.0f;
                 float num4 = 0.0f;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     num1 += ship.Ordinance;
                     num2 += ship.OrdinanceMax;
                     foreach (Weapon weapon in ship.Weapons)
                     {
                         if ((double)weapon.OrdinanceRequiredToFire > 0.0)
                             num3 = weapon.DamageAmount / weapon.fireDelay;
                         if ((double)weapon.PowerRequiredToFire > 0.0)
                             num4 = weapon.DamageAmount / weapon.fireDelay;
                     }
                 }
                 float num5 = num3 + num4;
                 if ((double)num3 >= 0.5 * (double)num5 && (double)num1 <= 0.100000001490116 * (double)num2)
                 {
                     this.TaskStep = 5;
                     break;
                 }
                 else
                 {
                     this.TaskStep = 2;
                     break;
                 }
             case 5:
                 List<Planet> list2 = new List<Planet>();
                 foreach (Planet planet in this.Owner.GetPlanets())
                 {
                     if (planet.HasShipyard)
                         list2.Add(planet);
                 }
                 IOrderedEnumerable<Planet> orderedEnumerable2 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list2, (Func<Planet, float>)(p => Vector2.Distance(this.Position, p.Position)));
                 if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable2) <= 0)
                     break;
                 this.Position = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable2).Position;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                     ship.GetAI().OrderResupply(Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable2), true);
                 this.TaskStep = 6;
                 break;
             case 6:
                 float num6 = 0.0f;
                 float num7 = 0.0f;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     if (ship.GetAI().State != AIState.Resupply)
                     {
                         this.TaskStep = 5;
                         return;
                     }
                     else
                     {
                         ship.GetAI().HasPriorityOrder = true;
                         num6 += ship.Ordinance;
                         num7 += ship.OrdinanceMax;
                     }
                 }
                 if ((double)num6 != (double)num7)
                     break;
                 this.TaskStep = 0;
                 break;
         }
     }
 }
        private void DoAssaultPlanet(MilitaryTask Task)
        {
            if (Task.GetTargetPlanet().Owner == this.Owner || Task.GetTargetPlanet().Owner == null || Task.GetTargetPlanet().Owner != null && !this.Owner.GetRelations()[Task.GetTargetPlanet().Owner].AtWar)
            {
                if (Task.GetTargetPlanet().Owner == this.Owner)
                {
                    MilitaryTask militaryTask = new MilitaryTask();
                    militaryTask.AO = Task.GetTargetPlanet().Position;
                    militaryTask.AORadius = 50000f;
                    militaryTask.WhichFleet = Task.WhichFleet;
                    militaryTask.SetEmpire(this.Owner);
                    militaryTask.type = MilitaryTask.TaskType.DefendPostInvasion;
                    this.Owner.GetGSAI().TaskList.QueuePendingRemoval(Task);
                    this.Task = militaryTask;
                    lock (GlobalStats.TaskLocker)
                        this.Owner.GetGSAI().TaskList.Add(Task);
                }
                else
                    Task.EndTask();
            }
            else
            {
                float num1 = 0.0f;
                foreach (Ship ship in (List<Ship>)this.Ships)
                    num1 += ship.GetStrength();
                if ((double)num1 == 0.0)
                    Task.EndTask();
                int num2 = 0;
                int num3 = 0;
                foreach (Ship ship in (List<Ship>)this.Ships)
                {
                    if ((double)ship.GetStrength() > 0.0)
                        ++num3;
                    num2 += ship.TroopList.Count;
                }
                if (num2 == 0)
                {
                    foreach (Troop troop in Task.GetTargetPlanet().TroopsHere)
                    {
                        if (troop.GetOwner() == this.Owner)
                            ++num2;
                    }
                }
                if (num2 == 0 || num3 == 0)
                {
                    if (num3 == 0)
                        Task.IsCoreFleetTask = false;
                    Task.EndTask();
                    this.Task = (MilitaryTask)null;
                    this.TaskStep = 0;
                }
                else
                {
                    switch (this.TaskStep)
                    {
                        case 0:
                            List<Planet> list1 = new List<Planet>();
                            this.Owner.GetPlanets().thisLock.EnterReadLock();
                            foreach (Planet planet in this.Owner.GetPlanets().OrderBy(combat=> combat.ParentSystem.DangerTimer))
                            {
                                if (planet.HasShipyard )
                                    list1.Add(planet);
                            }
                            this.Owner.GetPlanets().thisLock.ExitReadLock();
                            IOrderedEnumerable<Planet> orderedEnumerable1 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list1, (Func<Planet, float>)(planet => Vector2.Distance(Task.AO, planet.Position)));
                            if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable1) > 0)
                            {
                                Vector2 fVec = Vector2.Normalize(Task.AO - Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position);
                                Vector2 vector2 = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position;
                                this.MoveToNow(vector2, Math.Abs(MathHelper.ToRadians(HelperFunctions.findAngleToTarget(vector2, Task.AO))), fVec);
                                foreach (Ship ship in (List<Ship>)this.Ships)
                                    ship.GetAI().HasPriorityOrder = true;
                                this.TaskStep = 1;
                                break;
                            }
                            else
                            {
                                Task.EndTask();
                                break;
                            }
                        case 1:
                            bool flag1 = true;
                            this.Ships.thisLock.EnterReadLock();
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                if (!ship.disabled && ship.hasCommand && ship.Active)
                                {
                                    if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 5000.0)
                                    {
                                        flag1 = false;
                                        this.Ships.thisLock.ExitReadLock();
                                    }
                                    else if (ship.GetAI().BadGuysNear)
                                    {
                                        this.Ships.thisLock.ExitReadLock();
                                        Task.EndTask();
                                        flag1 = false;

                                    }
                                    int num4 = ship.InCombat ? 1 : 0;
                                    if (!flag1)
                                        break;
                                }
                            }

                            if (!flag1)
                                break;
                            this.Ships.thisLock.ExitReadLock();
                            this.TaskStep = 2;
                            Vector2 MovePosition = Task.GetTargetPlanet().Position + Vector2.Normalize(this.findAveragePosition() - Task.GetTargetPlanet().Position) * 125000f;
                            this.Position = MovePosition;
                            this.FormationWarpTo(MovePosition, MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.findAveragePosition(), Task.AO)), Vector2.Normalize(Task.AO - this.findAveragePosition()));
                            break;
                        case 2:
                            bool flag2 = true;
                            this.Ships.thisLock.EnterReadLock();
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                if (!ship.disabled && ship.hasCommand && ship.Active)
                                {
                                    if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 25000.0)
                                        flag2 = false;
                                    if (!flag2)
                                        break;
                                }
                            }
                            this.Ships.thisLock.ExitReadLock();
                            if (!flag2)
                                break;
                            this.Ships.thisLock.EnterReadLock();
                                foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                ship.GetAI().HasPriorityOrder = false;
                                ship.GetAI().State = AIState.HoldPosition;
                                if (ship.BombBays.Count > 0)
                                    ship.GetAI().OrderBombardPlanet(Task.GetTargetPlanet());
                                else if (ship.Role == "troop")
                                    ship.GetAI().HoldPosition();
                            }
                                this.Ships.thisLock.ExitReadLock();
                            this.InterceptorDict.Clear();
                            this.TaskStep = 3;
                            break;
                        case 3:
                            float num5 = 0.0f;
                            float num6 = 0.0f;
                            float num7 = 0.0f;
                            float num8 = 0.0f;
                            this.Ships.thisLock.EnterReadLock();
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                num5 += ship.Ordinance;
                                num6 += ship.OrdinanceMax;
                                foreach (Weapon weapon in ship.Weapons)
                                {
                                    if ((double)weapon.OrdinanceRequiredToFire > 0.0)
                                        num7 = weapon.DamageAmount / weapon.fireDelay;
                                    if ((double)weapon.PowerRequiredToFire > 0.0)
                                        num8 = weapon.DamageAmount / weapon.fireDelay;
                                }
                            }
                            this.Ships.thisLock.ExitReadLock();
                            float num9 = num7 + num8;
                            if ((double)num7 >= 0.5 * (double)num9 && (double)num5 <= 0.100000001490116 * (double)num6)
                            {
                                this.TaskStep = 5;
                                break;
                            }
                            else
                            {

                                foreach (Ship key in (List<Ship>)Task.GetTargetPlanet().system.ShipList)
                                {
                                    if (key.loyalty != this.Owner && (key.loyalty.isFaction || this.Owner.GetRelations()[key.loyalty].AtWar) && ((double)Vector2.Distance(key.Center, Task.GetTargetPlanet().Position) < 15000.0 && !this.InterceptorDict.ContainsKey(key)))
                                        this.InterceptorDict.Add(key, new List<Ship>());
                                }
                                List<Ship> list2 = new List<Ship>();
                                foreach (KeyValuePair<Ship, List<Ship>> keyValuePair in this.InterceptorDict)
                                {
                                    List<Ship> list3 = new List<Ship>();
                                    if ((double)Vector2.Distance(keyValuePair.Key.Center, Task.GetTargetPlanet().Position) > 20000.0 || !keyValuePair.Key.Active)
                                    {
                                        list2.Add(keyValuePair.Key);
                                        foreach (Ship ship in keyValuePair.Value)
                                        {
                                            lock (ship)
                                            {
                                                ship.GetAI().OrderQueue.Clear();
                                                ship.GetAI().Intercepting = false;
                                                ship.GetAI().OrderOrbitPlanet(Task.GetTargetPlanet());
                                                ship.GetAI().State = AIState.AwaitingOrders;
                                                ship.GetAI().Intercepting = false;
                                            }
                                        }
                                    }
                                    foreach (Ship ship in keyValuePair.Value)
                                    {
                                        if (!ship.Active)
                                            list3.Add(ship);
                                    }
                                    foreach (Ship ship in list3)
                                        keyValuePair.Value.Remove(ship);
                                }
                                foreach (Ship key in list2)
                                    this.InterceptorDict.Remove(key);
                                foreach (KeyValuePair<Ship, List<Ship>> keyValuePair1 in this.InterceptorDict)
                                {
                                    List<Ship> list3 = new List<Ship>();
                                    foreach (Ship ship in (List<Ship>)this.Ships)
                                    {
                                        if (ship.Role != "troop")
                                            list3.Add(ship);
                                    }
                                    List<Ship> list4 = new List<Ship>();
                                    foreach (KeyValuePair<Ship, List<Ship>> keyValuePair2 in this.InterceptorDict)
                                    {
                                        list4.Add(keyValuePair2.Key);
                                        foreach (Ship ship in keyValuePair2.Value)
                                            list3.Remove(ship);
                                    }
                                    foreach (Ship toAttack in (IEnumerable<Ship>)Enumerable.OrderByDescending<Ship, float>((IEnumerable<Ship>)list4, (Func<Ship, float>)(ship => ship.GetStrength())))
                                    {
                                        IOrderedEnumerable<Ship> orderedEnumerable2 = Enumerable.OrderByDescending<Ship, float>((IEnumerable<Ship>)list3, (Func<Ship, float>)(ship => ship.GetStrength()));
                                        float num4 = 0.0f;
                                        foreach (Ship ship in (IEnumerable<Ship>)orderedEnumerable2)
                                        {
                                            if ((double)num4 != 0.0)
                                            {
                                                if ((double)num4 >= (double)toAttack.GetStrength() * 1.5)
                                                    break;
                                            }
                                            ship.GetAI().Intercepting = true;
                                            list3.Remove(ship);
                                            ship.GetAI().OrderAttackSpecificTarget(toAttack);
                                            this.InterceptorDict[toAttack].Add(ship);
                                            num4 += ship.GetStrength();
                                        }
                                    }
                                }
                                if (this.InterceptorDict.Count == 0 || (double)this.Owner.GetGSAI().ThreatMatrix.PingRadarStr(Task.GetTargetPlanet().Position, 25000f, this.Owner) < 500.0)
                                    this.TaskStep = 4;
                                lock (GlobalStats.TaskLocker)
                                {
                                    this.Owner.GetGSAI().TaskList.thisLock.EnterReadLock();
                                    using (List<MilitaryTask>.Enumerator resource_0 = this.Owner.GetGSAI().TaskList.GetEnumerator())
                                    {
                                        while (resource_0.MoveNext())
                                        {
                                            MilitaryTask local_43 = resource_0.Current;
                                            if (local_43.WaitForCommand && local_43.GetTargetPlanet() != null && local_43.GetTargetPlanet() == Task.GetTargetPlanet())
                                                local_43.WaitForCommand = false;
                                        }
                                        this.Owner.GetGSAI().TaskList.thisLock.ExitReadLock();
                                        break;
                                    }
                                    this.Owner.GetGSAI().TaskList.thisLock.ExitReadLock();
                                }
                            }
                        case 4:
                            int num10 = 0;
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                if (ship.BombBays.Count > 0 && (double)ship.Ordinance / (double)ship.OrdinanceMax > 0.200000002980232)
                                {
                                    num10 += ship.BombBays.Count;
                                    ship.GetAI().OrderBombardPlanet(Task.GetTargetPlanet());
                                }
                            }
                            float num11 = 0.0f;
                            float num12 = 0.0f;
                            float num13 = 0.0f;
                            float num14 = 0.0f;
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                num11 += ship.Ordinance;
                                num12 += ship.OrdinanceMax;
                                foreach (Weapon weapon in ship.Weapons)
                                {
                                    if ((double)weapon.OrdinanceRequiredToFire > 0.0)
                                        num13 = weapon.DamageAmount / weapon.fireDelay;
                                    if ((double)weapon.PowerRequiredToFire > 0.0)
                                        num14 = weapon.DamageAmount / weapon.fireDelay;
                                }
                            }
                            float num15 = num13 + num14;
                            if ((double)num13 >= 0.5 * (double)num15 && (double)num11 <= 0.100000001490116 * (double)num12)
                            {
                                this.TaskStep = 5;
                                break;
                            }
                            else
                            {
                                bool flag3 = true;
                                float groundStrOfPlanet = this.GetGroundStrOfPlanet(Task.GetTargetPlanet());
                                float num4 = 0.0f;
                                foreach (Ship ship in (List<Ship>)this.Ships)
                                {
                                    foreach (Troop troop in ship.TroopList)
                                        num4 += (float)troop.Strength;
                                }
                                if ((double)num4 > (double)groundStrOfPlanet || num10 < 6)
                                {
                                    flag3 = true;
                                }
                                else
                                {
                                    int num16 = 0;
                                    foreach (Ship ship in (List<Ship>)this.Ships)
                                    {
                                        if (ship.BombBays.Count > 0)
                                        {
                                            ++num16;
                                            if ((double)ship.Ordinance / (double)ship.OrdinanceMax > 0.200000002980232)
                                            {
                                                flag3 = false;
                                                break;
                                            }
                                        }
                                    }
                                    if (num16 == 0)
                                        flag3 = true;
                                }
                                if (flag3)
                                {
                                    foreach (Ship ship in (List<Ship>)this.Ships)
                                    {
                                        if (ship.BombBays.Count > 0)
                                        {
                                            ship.GetAI().State = AIState.AwaitingOrders;
                                            ship.GetAI().OrderQueue.Clear();
                                        }
                                    }
                                    this.Position = Task.GetTargetPlanet().Position;
                                    this.AssembleFleet(this.facing, Vector2.Normalize(this.Position - this.findAveragePosition()));
                                    using (List<Ship>.Enumerator enumerator = this.Ships.GetEnumerator())
                                    {
                                        while (enumerator.MoveNext())
                                            enumerator.Current.GetAI().OrderLandAllTroops(Task.GetTargetPlanet());
                                        break;
                                    }
                                }
                                else
                                {
                                    this.Ships.thisLock.EnterReadLock();
                                    using (List<Ship>.Enumerator enumerator = this.Ships.GetEnumerator())
                                    {
                                        while (enumerator.MoveNext())
                                        {
                                            Ship current = enumerator.Current;
                                            if (current.BombBays.Count > 0)
                                                current.GetAI().OrderBombardPlanet(Task.GetTargetPlanet());
                                        }
                                        this.Ships.thisLock.ExitReadLock();
                                        break;
                                    }
                                    this.Ships.thisLock.ExitReadLock();
                                }
                            }
                        case 5:
                            List<Planet> list5 = new List<Planet>();
                            this.Owner.GetPlanets().thisLock.EnterReadLock();
                            foreach (Planet planet in this.Owner.GetPlanets())
                            {
                                if (planet.HasShipyard)
                                    list5.Add(planet);
                            }
                            this.Owner.GetPlanets().thisLock.ExitReadLock();
                            IOrderedEnumerable<Planet> orderedEnumerable3 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list5, (Func<Planet, float>)(p => Vector2.Distance(this.Position, p.Position)));
                            if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable3) > 0)
                            {
                                this.Position = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable3).Position;
                                foreach (Ship ship in (List<Ship>)this.Ships)
                                    ship.GetAI().OrderResupply(Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable3), true);
                                this.TaskStep = 6;
                                break;
                            }
                            else
                            {
                                Task.EndTask();
                                break;
                            }
                        case 6:
                            float num17 = 0.0f;
                            float num18 = 0.0f;
                            foreach (Ship ship in (List<Ship>)this.Ships)
                            {
                                ship.GetAI().HasPriorityOrder = true;
                                num17 += ship.Ordinance;
                                num18 += ship.OrdinanceMax;
                            }
                            if ((double)num17 < (double)num18 * 0.899999976158142)
                                break;
                            this.TaskStep = 0;
                            break;
                    }
                }
            }
        }
 private void DoCohesiveClearAreaOfEnemies(MilitaryTask Task)
 {
     switch (this.TaskStep)
     {
         case 0:
             this.TaskStep = 1;
             this.DoCohesiveClearAreaOfEnemies(Task);
             break;
         case 1:
             List<ThreatMatrix.Pin> list1 = new List<ThreatMatrix.Pin>();
             Dictionary<ThreatMatrix.Pin, float> dictionary1 = new Dictionary<ThreatMatrix.Pin, float>();
             foreach (KeyValuePair<Guid, ThreatMatrix.Pin> keyValuePair1 in this.Owner.GetGSAI().ThreatMatrix.Pins)
             {
                 if (!(keyValuePair1.Value.EmpireName == this.Owner.data.Traits.Name) && (EmpireManager.GetEmpireByName(keyValuePair1.Value.EmpireName).isFaction || this.Owner.GetRelations()[EmpireManager.GetEmpireByName(keyValuePair1.Value.EmpireName)].AtWar) && (!list1.Contains(keyValuePair1.Value) && (double)Vector2.Distance(keyValuePair1.Value.Position, Task.AO) < (double)Task.AORadius))
                 {
                     dictionary1.Add(keyValuePair1.Value, keyValuePair1.Value.Strength);
                     list1.Add(keyValuePair1.Value);
                     foreach (KeyValuePair<Guid, ThreatMatrix.Pin> keyValuePair2 in this.Owner.GetGSAI().ThreatMatrix.Pins)
                     {
                         if (!(keyValuePair2.Value.EmpireName == this.Owner.data.Traits.Name) && keyValuePair2.Value.EmpireName == keyValuePair1.Value.EmpireName && ((double)Vector2.Distance(keyValuePair1.Value.Position, keyValuePair2.Value.Position) < 150000.0 && !list1.Contains(keyValuePair2.Value)))
                         {
                             Dictionary<ThreatMatrix.Pin, float> dictionary2;
                             ThreatMatrix.Pin index;
                             (dictionary2 = dictionary1)[index = keyValuePair1.Value] = dictionary2[index] + keyValuePair2.Value.Strength;
                         }
                     }
                 }
             }
             float strength = this.GetStrength();
             this.targetPosition = Vector2.Zero;
             foreach (KeyValuePair<ThreatMatrix.Pin, float> keyValuePair in dictionary1)
             {
                 if ((double)strength > (double)keyValuePair.Value * 1.35000002384186 && (double)keyValuePair.Value > 750.0)
                     this.targetPosition = keyValuePair.Key.Position;
             }
             if (this.targetPosition != Vector2.Zero)
             {
                 Vector2 fvec = Vector2.Normalize(Task.AO - this.targetPosition);
                 this.FormationWarpTo(this.targetPosition, Math.Abs(MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.targetPosition, Task.AO))), fvec);
                 this.TaskStep = 2;
                 break;
             }
             else
             {
                 this.Task.EndTask();
                 break;
             }
         case 2:
             if ((double)this.Owner.GetGSAI().ThreatMatrix.PingRadarStr(this.targetPosition, 20000f, this.Owner) == 0.0)
             {
                 this.TaskStep = 1;
                 break;
             }
             else
             {
                 if ((double)Vector2.Distance(this.targetPosition, this.findAveragePosition()) >= 25000.0)
                     break;
                 this.TaskStep = 3;
                 break;
             }
         case 3:
             this.EnemyClumpsDict.Clear();
             List<Ship> list2 = new List<Ship>();
             Vector2 averagePosition = this.findAveragePosition();
             List<GameplayObject> nearby1 = UniverseScreen.ShipSpatialManager.GetNearby(this.Position);
             for (int index1 = 0; index1 < nearby1.Count; ++index1)
             {
                 Ship ship1 = nearby1[index1] as Ship;
                 if (ship1 != null && ship1.loyalty != this.Owner && (ship1.loyalty.isFaction || this.Owner.GetRelations()[ship1.loyalty].AtWar) && (!list2.Contains(ship1) && (double)Vector2.Distance(ship1.Center, averagePosition) < 50000.0 && !this.EnemyClumpsDict.ContainsKey(ship1.Center)))
                 {
                     this.EnemyClumpsDict.Add(ship1.Center, new List<Ship>());
                     this.EnemyClumpsDict[ship1.Center].Add(ship1);
                     list2.Add(ship1);
                     List<GameplayObject> nearby2 = UniverseScreen.ShipSpatialManager.GetNearby(this.Position);
                     for (int index2 = 0; index2 < nearby2.Count; ++index2)
                     {
                         Ship ship2 = nearby2[index2] as Ship;
                         if (ship2 != null && ship2.loyalty != this.Owner && (ship2.loyalty == ship1.loyalty && (double)Vector2.Distance(ship1.Center, ship2.Center) < 10000.0) && !list2.Contains(ship2))
                             this.EnemyClumpsDict[ship1.Center].Add(ship2);
                     }
                 }
             }
             if (this.EnemyClumpsDict.Count == 0)
             {
                 Task.EndTask();
                 break;
             }
             else
             {
                 List<Vector2> list3 = new List<Vector2>();
                 foreach (KeyValuePair<Vector2, List<Ship>> keyValuePair in this.EnemyClumpsDict)
                     list3.Add(keyValuePair.Key);
                 IOrderedEnumerable<Vector2> orderedEnumerable = Enumerable.OrderBy<Vector2, float>((IEnumerable<Vector2>)list3, (Func<Vector2, float>)(clumpPos => Vector2.Distance(this.findAveragePosition(), clumpPos)));
                 List<Ship> list4 = new List<Ship>();
                 foreach (Ship toAttack in this.EnemyClumpsDict[Enumerable.First<Vector2>((IEnumerable<Vector2>)orderedEnumerable)])
                 {
                     float num = 0.0f;
                     foreach (Ship ship in (List<Ship>)this.Ships)
                     {
                         if (!list4.Contains(ship) && ((double)num == 0.0 || (double)num < (double)toAttack.GetStrength()))
                         {
                             ship.GetAI().Intercepting = true;
                             ship.GetAI().OrderAttackSpecificTarget(toAttack);
                             list4.Add(ship);
                             num += ship.GetStrength();
                         }
                     }
                 }
                 List<Ship> list5 = new List<Ship>();
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     if (!list4.Contains(ship))
                         list5.Add(ship);
                 }
                 foreach (Ship ship in list5)
                 {
                     ship.GetAI().Intercepting = true;
                     ship.GetAI().OrderAttackSpecificTarget(list4[0].GetAI().Target as Ship);
                 }
                 this.TaskStep = 4;
                 break;
             }
         case 4:
             float num1 = 0.0f;
             float num2 = 0.0f;
             float num3 = 0.0f;
             float num4 = 0.0f;
             foreach (Ship ship in (List<Ship>)this.Ships)
             {
                 num1 += ship.Ordinance;
                 num2 += ship.OrdinanceMax;
                 foreach (Weapon weapon in ship.Weapons)
                 {
                     if ((double)weapon.OrdinanceRequiredToFire > 0.0)
                         num3 = weapon.DamageAmount / weapon.fireDelay;
                     if ((double)weapon.PowerRequiredToFire > 0.0)
                         num4 = weapon.DamageAmount / weapon.fireDelay;
                 }
             }
             float num5 = num3 + num4;
             if ((double)num3 >= 0.5 * (double)num5 && (double)num1 <= 0.100000001490116 * (double)num2)
             {
                 this.TaskStep = 5;
                 break;
             }
             else
             {
                 bool flag = false;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     if (!ship.GetAI().BadGuysNear || ship.isInDeepSpace)
                     {
                         flag = true;
                         break;
                     }
                 }
                 if (!flag)
                     break;
                 this.TaskStep = 3;
                 break;
             }
         case 5:
             foreach (Ship ship in (List<Ship>)this.Ships)
                 ship.GetAI().OrderResupplyNearest();
             this.TaskStep = 6;
             break;
         case 6:
             float num6 = 0.0f;
             float num7 = 0.0f;
             foreach (Ship ship in (List<Ship>)this.Ships)
             {
                 if (ship.GetAI().State != AIState.Resupply)
                 {
                     Task.EndTask();
                     return;
                 }
                 else
                 {
                     ship.GetAI().HasPriorityOrder = true;
                     num6 += ship.Ordinance;
                     num7 += ship.OrdinanceMax;
                 }
             }
             if ((double)num6 != (double)num7)
                 break;
             this.TaskStep = 1;
             break;
     }
 }
        //added by gremlin deveksmod military planner
        private void RunMilitaryPlanner()
        {
            float SizeLimiter = GlobalStats.MemoryLimiter;
             int ShipCountLimit = GlobalStats.ShipCountLimit;
            List<AO>.Enumerator enumerator;
            if(!this.empire.MinorRace)
                this.RunGroundPlanner();
            this.numberOfShipGoals = 0;
            foreach (Planet p in this.empire.GetPlanets())
            {
               // if (!p.HasShipyard || (p.GetMaxProductionPotential() <2f
                if ((p.GetMaxProductionPotential() < 2f //||( this.empire.data.Traits.Cybernetic !=0 && p.GetMaxProductionPotential()-p.consumption <2f)
                    || p.ps == Planet.GoodState.IMPORT
                    ))   //p.GetNetProductionPerTurn() < .5f))
                {
                    continue;
                }

                this.numberOfShipGoals = this.numberOfShipGoals + (int)((p.ProductionHere)/50); //(int)(p.ProductionHere /(1+ p.ConstructionQueue.Sum(q => q.Cost)));
            }
            float numgoals = 0f;
            float offenseUnderConstruction = 0f;
            float UnderConstruction = 0f;
            float TroopStrengthUnderConstruction = 0f;
            foreach (Goal g in this.Goals)
            //Parallel.ForEach(this.Goals, g =>
            {
                if (g.GoalName == "BuildOffensiveShips")
                {
                    if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                    {
                        UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCostRealism();
                    }
                    else
                    {
                        UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCost(this.empire);
                    }
                    offenseUnderConstruction += ResourceManager.ShipsDict[g.ToBuildUID].BaseStrength;
                    foreach (Troop t in ResourceManager.ShipsDict[g.ToBuildUID].TroopList)
                    {
                        TroopStrengthUnderConstruction = TroopStrengthUnderConstruction + (float)t.Strength;
                    }
                    numgoals = numgoals + 1f;
                }
                if (g.GoalName != "BuildConstructionShip")
                {
                    continue;
                }
                if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                {
                    UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCostRealism();
                }
                else
                {
                    UnderConstruction = UnderConstruction + ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCost(this.empire);
                }
            }
            //this.GetAShip(0);
            //float offensiveStrength = offenseUnderConstruction + this.empire.GetForcePoolStrength();

            bool atWar = this.empire.GetRelations().Where(war => war.Value.AtWar).Count() > 0;
            //int prepareWar = this.empire.GetRelations().Where(angry => angry.Value.TotalAnger > angry.Value.Trust).Count();
            //prepareWar += this.empire.GetRelations().Where(angry => angry.Value.PreparingForWar).Count();
            float noIncome = this.FindTaxRateToReturnAmount(UnderConstruction);

            //float tax = atWar ? .40f + (prepareWar * .05f) : .25f + (prepareWar * .05f);  //.45f - (tasks);
            //float offenseNeeded = this.empire.GetRelations().Where(war => war.Value.AtWar || war.Value.PreparingForWar || war.Value.Trust < war.Value.TotalAnger).Sum(power => power.Key.currentMilitaryStrength);
            float offenseNeeded =  this.empire.GetRelations().Where(war => !war.Key.isFaction && war.Value.AtWar || war.Value.PreparingForWar).Sum(power => power.Key.currentMilitaryStrength);
            float offenseNeededThreat = this.ThreatMatrix.Pins.Values.Sum(power => power.Strength); //.Where(faction=>  EmpireManager.GetEmpireByName(faction.EmpireName).isFaction).Sum(power => power.Strength);
            //if (offenseNeededThreat > 0)
            //    System.Diagnostics.Debug.WriteLine("threat: " + offenseNeededThreat);
            float offenseNeededRatio = ((offenseNeeded  + offenseNeededThreat)+1) / (this.empire.currentMilitaryStrength +1);
            //float prepareWar2 = this.empire.GetRelations().Where(angry => angry.Value.TotalAnger > angry.Value.Trust).Sum(power => power.Key.currentMilitaryStrength / (power.Value.Trust /power.Value.TotalAnger) );

            //float tax = offenseNeededRatio > 0.0 ? offenseNeededRatio * (.6f - (this.empire.data.TaxRate)) : this.empire.data.TaxRate;
            float tax = offenseNeededRatio*.1f;// > 0.0 ? offenseNeededRatio * (.6f - (this.empire.data.TaxRate)) : this.empire.data.TaxRate;
            if (tax > .25f)
                tax = .25f;
            else
                if (tax < .05f)
                    tax = .05f;

            //float Capacity = this.empire.EstimateIncomeAtTaxRate(tax) + this.empire.Money * -.1f -UnderConstruction + this.empire.GetAverageNetIncome();
            float Capacity = this.empire.Money * .1f - UnderConstruction -this.empire.GetTotalShipMaintenance();// +this.empire.GetAverageNetIncome();
            float allowable_deficit = this.empire.Money * -.1f; //>0?(1 - (this.empire.Money * 10 / this.empire.Money)):0); //-Capacity;// +(this.empire.Money * -.1f);
                //-Capacity;

            //if ((allowable_deficit >= 0f || noIncome >.5f) && atWar)
            //{
            //    allowable_deficit = -(this.empire.Money*.5f );//- this.empire.GrossTaxes );// 0f;
            //}

            this.buildCapacity = Capacity - allowable_deficit;// +this.empire.GetTotalShipMaintenance(); ;
                //this.empire.GetTotalShipMaintenance();

            this.GetAShip(0);
            if (Capacity <= allowable_deficit )//|| (this.empire.data.TaxRate >=.5f && this.empire.GetAverageNetIncome()<0)) //(Capacity <= 0f)
            {
                float HowMuchWeAreScrapping = 0f;

                foreach (Ship ship1 in this.empire.GetShips())
                {
                    if (ship1.GetAI().State != AIState.Scrap)
                    {
                        continue;
                    }
                    if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                    {
                        HowMuchWeAreScrapping = HowMuchWeAreScrapping + ship1.GetMaintCostRealism();
                    }
                    else
                    {
                        HowMuchWeAreScrapping = HowMuchWeAreScrapping + ship1.GetMaintCost(this.empire);
                    }
                }
                if (HowMuchWeAreScrapping < Math.Abs(Capacity))
                {
                    float Added = 0f;

                    //added by gremlin clear out building ships before active ships.
                    if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                    {
                        foreach (Goal g in this.Goals.Where(goal => goal.GoalName == "BuildOffensiveShips").OrderByDescending(goal => ResourceManager.ShipsDict[goal.ToBuildUID].GetMaintCostRealism()))
                        {
                            bool flag = false;
                            if (g.GetPlanetWhereBuilding() == null)
                                continue;
                            foreach (QueueItem shipToRemove in g.GetPlanetWhereBuilding().ConstructionQueue)
                            {

                                if (shipToRemove.Goal != g)
                                {
                                    continue;

                                }
                                g.GetPlanetWhereBuilding().ProductionHere += shipToRemove.productionTowards;
                                g.GetPlanetWhereBuilding().ConstructionQueue.QueuePendingRemoval(shipToRemove);
                                this.Goals.QueuePendingRemoval(g);
                                Added += ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCostRealism();
                                flag = true;
                                break;

                            }
                            if (flag)
                                g.GetPlanetWhereBuilding().ConstructionQueue.ApplyPendingRemovals();

                        }
                    }
                    else
                    {
                        foreach (Goal g in this.Goals.Where(goal => goal.GoalName == "BuildOffensiveShips").OrderByDescending(goal => ResourceManager.ShipsDict[goal.ToBuildUID].GetMaintCost(this.empire)))
                        {
                            bool flag = false;
                            if (g.GetPlanetWhereBuilding() == null)
                                continue;
                            foreach (QueueItem shipToRemove in g.GetPlanetWhereBuilding().ConstructionQueue)
                            {

                                if (shipToRemove.Goal != g)
                                {
                                    continue;

                                }
                                g.GetPlanetWhereBuilding().ProductionHere += shipToRemove.productionTowards;
                                g.GetPlanetWhereBuilding().ConstructionQueue.QueuePendingRemoval(shipToRemove);
                                this.Goals.QueuePendingRemoval(g);
                                Added += ResourceManager.ShipsDict[g.ToBuildUID].GetMaintCost(this.empire);
                                flag = true;
                                break;

                            }
                            if (flag)
                                g.GetPlanetWhereBuilding().ConstructionQueue.ApplyPendingRemovals();

                        }
                    }

                    this.Goals.ApplyPendingRemovals();

                }

            }
            //Capacity = this.empire.EstimateIncomeAtTaxRate(tax) - UnderConstruction;

            //if (allowable_deficit > 0f || noIncome > tax)
            //{
            //    allowable_deficit = Math.Abs(allowable_deficit);
            //}

            while (Capacity > 0 //this.buildCapacity > 0 //Capacity > allowable_deficit
                && numgoals < this.numberOfShipGoals
                && (Empire.universeScreen.globalshipCount < ShipCountLimit+ recyclepool
                || this.empire.empireShipTotal <this.empire.EmpireShipCountReserve)) //shipsize < SizeLimiter)
            {

                string s = this.GetAShip(this.buildCapacity-allowable_deficit);//Capacity - allowable_deficit);
                if (s == null)
                {
                    break;
                }
                if(this.recyclepool>0)
                {
                    this.recyclepool--;
                }

                Goal g = new Goal(s, "BuildOffensiveShips", this.empire)
                {
                    type = GoalType.BuildShips
                };
                this.Goals.Add(g);
                if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useProportionalUpkeep)
                {
                    Capacity = Capacity - ResourceManager.ShipsDict[s].GetMaintCostRealism();
                }
                else
                {
                    Capacity = Capacity - ResourceManager.ShipsDict[s].GetMaintCost(this.empire);
                }
                numgoals = numgoals + 1f;
            }

            //this.GetAShip(0);
            int numWars = 0;
            foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relationship in this.empire.GetRelations())
            {
                if (!Relationship.Value.AtWar || Relationship.Key.isFaction)
                {
                    continue;
                }
                numWars++;
            }
            foreach (Goal g in this.Goals)
            //Parallel.ForEach(this.Goals, g =>
            {
                if (g.type != GoalType.Colonize || g.Held)
                {
                    if (g.type != GoalType.Colonize || !g.Held || g.GetMarkedPlanet().Owner == null)
                    {
                        continue;
                    }
                    foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relationship in this.empire.GetRelations())
                    {
                        this.empire.GetGSAI().CheckClaim(Relationship, g.GetMarkedPlanet());
                    }
                    this.Goals.QueuePendingRemoval(g);
                    lock (GlobalStats.TaskLocker)
                    {
                        foreach (MilitaryTask task in this.TaskList)
                        {
                            foreach (Guid held in task.HeldGoals)
                            {
                                if (held != g.guid)
                                {
                                    continue;
                                }
                                this.TaskList.QueuePendingRemoval(task);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    if (g.GetMarkedPlanet() != null)
                    {
                        foreach (KeyValuePair<Guid, ThreatMatrix.Pin> pin in this.ThreatMatrix.Pins.Where(pin => !((Vector2.Distance(g.GetMarkedPlanet().Position, pin.Value.Position) >= 75000f) || EmpireManager.GetEmpireByName(pin.Value.EmpireName) == this.empire || pin.Value.Strength <= 0f || !this.empire.GetRelations()[EmpireManager.GetEmpireByName(pin.Value.EmpireName)].AtWar)))
                        {
                            if (Vector2.Distance(g.GetMarkedPlanet().Position, pin.Value.Position) >= 75000f || EmpireManager.GetEmpireByName(pin.Value.EmpireName) == this.empire || pin.Value.Strength <= 0f || !this.empire.GetRelations()[EmpireManager.GetEmpireByName(pin.Value.EmpireName)].AtWar && !EmpireManager.GetEmpireByName(pin.Value.EmpireName).isFaction)
                            {
                                continue;
                            }
                            List<Goal> tohold = new List<Goal>()
                        {
                            g
                        };
                            MilitaryTask task = new MilitaryTask(g.GetMarkedPlanet().Position, 125000f, tohold, this.empire);
                            lock (GlobalStats.TaskLocker)
                            {
                                this.TaskList.Add(task);
                                break;
                            }
                        }
                    }
                }
            }
            if (this.empire.data.DiplomaticPersonality.Name == "Aggressive" || this.empire.data.DiplomaticPersonality.Name == "Ruthless" || this.empire.data.EconomicPersonality.Name == "Expansionist")
            {
                foreach (Goal g in this.Goals)
                {
                    if (g.type != GoalType.Colonize || g.Held)
                    {
                        continue;
                    }
                    bool OK = true;
                    lock (GlobalStats.TaskLocker)
                    {
                        foreach (MilitaryTask mt in this.TaskList)
                        //Parallel.ForEach(this.TaskList, (mt,state) =>
                        {
                            if ((mt.type != MilitaryTask.TaskType.DefendClaim
                                && mt.type != MilitaryTask.TaskType.ClearAreaOfEnemies )
                                || g.GetMarkedPlanet() != null
                                && !(mt.TargetPlanetGuid == g.GetMarkedPlanet().guid))

                            {
                                continue;
                            }
                            OK = false;
                            break;
                        }
                    }
                    if (!OK)
                    {
                        continue;
                    }
                    if (g.GetMarkedPlanet() == null)
                        continue;
                    MilitaryTask task = new MilitaryTask()
                    {
                        AO = g.GetMarkedPlanet().Position
                    };
                    task.SetEmpire(this.empire);
                    task.AORadius = 75000f;
                    task.SetTargetPlanet(g.GetMarkedPlanet());
                    task.TargetPlanetGuid = g.GetMarkedPlanet().guid;
                    task.type = MilitaryTask.TaskType.DefendClaim;
                    lock (GlobalStats.TaskLocker)
                    {
                        this.TaskList.Add(task);
                    }
                }
            }
            this.Goals.ApplyPendingRemovals();
            lock (GlobalStats.TaskLocker)
            {
                List<MilitaryTask> ToughNuts = new List<MilitaryTask>();
                List<MilitaryTask> InOurSystems = new List<MilitaryTask>();
                List<MilitaryTask> InOurAOs = new List<MilitaryTask>();
                List<MilitaryTask> Remainder = new List<MilitaryTask>();
                foreach (MilitaryTask task in this.TaskList.OrderBy(target=> target.GetTargetPlanet()!=null ? Vector2.Distance(target.GetTargetPlanet().Position,this.empire.GetWeightedCenter()):0f))
                {
                    if (task.type != MilitaryTask.TaskType.AssaultPlanet)
                    {
                        continue;
                    }
                    if (task.IsToughNut)
                    {
                        ToughNuts.Add(task);
                    }
                    else if (!this.empire.GetOwnedSystems().Contains(task.GetTargetPlanet().system))
                    {
                        bool dobreak = false;
                        foreach (KeyValuePair<Guid, Planet> entry in Ship.universeScreen.PlanetsDict)
                        {
                            if (task.GetTargetPlanet() != entry.Value)
                            {
                                continue;
                            }
                            enumerator = this.AreasOfOperations.GetEnumerator();
                            try
                            {
                                while (enumerator.MoveNext())
                                {
                                    AO area = enumerator.Current;
                                    if (Vector2.Distance(entry.Value.Position, area.Position) >= area.Radius)
                                    {
                                        continue;
                                    }
                                    InOurAOs.Add(task);
                                    dobreak = true;
                                    break;
                                }
                                break;
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                        }
                        if (dobreak)
                        {
                            continue;
                        }
                        Remainder.Add(task);
                    }
                    else
                    {
                        InOurSystems.Add(task);
                    }
                }
                List<MilitaryTask> TNInOurSystems = new List<MilitaryTask>();
                List<MilitaryTask> TNInOurAOs = new List<MilitaryTask>();
                List<MilitaryTask> TNRemainder = new List<MilitaryTask>();
                foreach (MilitaryTask task in ToughNuts)
                {
                    if (!this.empire.GetOwnedSystems().Contains(task.GetTargetPlanet().system))
                    {
                        bool dobreak = false;
                        foreach (KeyValuePair<Guid, Planet> entry in Ship.universeScreen.PlanetsDict)
                        {
                            if (task.GetTargetPlanet() != entry.Value)
                            {
                                continue;
                            }
                            enumerator = this.AreasOfOperations.GetEnumerator();
                            try
                            {
                                while (enumerator.MoveNext())
                                {
                                    AO area = enumerator.Current;
                                    if (Vector2.Distance(entry.Value.Position, area.Position) >= area.Radius)
                                    {
                                        continue;
                                    }
                                    TNInOurAOs.Add(task);
                                    dobreak = true;
                                    break;
                                }
                                break;
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                        }
                        if (dobreak)
                        {
                            continue;
                        }
                        TNRemainder.Add(task);
                    }
                    else
                    {
                        TNInOurSystems.Add(task);
                    }
                }
                foreach (MilitaryTask task in TNInOurAOs.OrderBy(target=>  Vector2.Distance(target.GetTargetPlanet().Position,this.empire.GetWeightedCenter())))
                //Parallel.ForEach(TNInOurAOs, task =>
                {
                    if (task.GetTargetPlanet().Owner == null || task.GetTargetPlanet().Owner == this.empire || this.empire.GetRelations()[task.GetTargetPlanet().Owner].ActiveWar == null || (float)this.empire.TotalScore <= (float)task.GetTargetPlanet().Owner.TotalScore * 1.5f)
                    {
                        continue;
                        //return;
                    }
                    task.Evaluate(this.empire);
                }//);
                foreach (MilitaryTask task in TNInOurSystems)
                //Parallel.ForEach(TNInOurSystems, task =>
                {
                    task.Evaluate(this.empire);
                }//);
                foreach (MilitaryTask task in TNRemainder)
                {
                    if (task.GetTargetPlanet().Owner == null || task.GetTargetPlanet().Owner == this.empire || this.empire.GetRelations()[task.GetTargetPlanet().Owner].ActiveWar == null || (float)this.empire.TotalScore <= (float)task.GetTargetPlanet().Owner.TotalScore * 1.5f)
                    {
                        continue;
                    }
                    task.Evaluate(this.empire);
                }
                foreach (MilitaryTask task in InOurAOs)
                {
                    task.Evaluate(this.empire);
                }
                foreach (MilitaryTask task in InOurSystems)
                {
                    task.Evaluate(this.empire);
                }
                foreach (MilitaryTask task in Remainder)
                {
                    task.Evaluate(this.empire);
                }
                foreach (MilitaryTask task in this.TaskList)
                {
                    if (task.type != MilitaryTask.TaskType.AssaultPlanet)
                    {
                        task.Evaluate(this.empire);
                    }
                    if (task.type != MilitaryTask.TaskType.AssaultPlanet && task.type != MilitaryTask.TaskType.GlassPlanet || task.GetTargetPlanet().Owner != null && task.GetTargetPlanet().Owner != this.empire)
                    {
                        continue;
                    }
                    task.EndTask();
                }
                this.TaskList.AddRange(this.TasksToAdd);
                this.TasksToAdd.Clear();
                this.TaskList.ApplyPendingRemovals();
            }
        }
 private void RunWarPlanner()
 {
     foreach (KeyValuePair<Empire, Relationship> r in this.empire.GetRelations())
     {
         if (r.Key.isFaction)
         {
             r.Value.AtWar = false;
         }
         else
         {
             if (r.Value.PreparingForWar)
             {
                 switch (r.Value.PreparingForWarType)
                 {
                     case WarType.BorderConflict:
                         List<Planet> list1 = new List<Planet>();
                         IOrderedEnumerable<Planet> orderedEnumerable1 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)r.Key.GetPlanets(), (Func<Planet, float>)(planet => this.GetDistanceFromOurAO(planet)));
                         for (int index = 0; index < Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable1); ++index)
                         {
                             list1.Add(Enumerable.ElementAt<Planet>((IEnumerable<Planet>)orderedEnumerable1, index));
                             if (index == 2)
                                 break;
                         }
                         using (List<Planet>.Enumerator enumerator = list1.GetEnumerator())
                         {
                             while (enumerator.MoveNext())
                             {
                                 Planet current = enumerator.Current;
                                 bool flag = true;
                                 lock (GlobalStats.TaskLocker)
                                 {
                                     foreach (MilitaryTask item_0 in (List<MilitaryTask>)this.TaskList)
                                     {
                                         if (item_0.GetTargetPlanet() == current && item_0.type == MilitaryTask.TaskType.AssaultPlanet)
                                         {
                                             flag = false;
                                             break;
                                         }
                                     }
                                 }
                                 if (flag)
                                 {
                                     MilitaryTask militaryTask = new MilitaryTask(current, this.empire);
                                     lock (GlobalStats.TaskLocker)
                                         this.TaskList.Add(militaryTask);
                                 }
                             }
                             break;
                         }
                     case WarType.ImperialistWar:
                         List<Planet> list2 = new List<Planet>();
                         IOrderedEnumerable<Planet> orderedEnumerable2 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)r.Key.GetPlanets(), (Func<Planet, float>)(planet => this.GetDistanceFromOurAO(planet)));
                         for (int index = 0; index < Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable2); ++index)
                         {
                             list2.Add(Enumerable.ElementAt<Planet>((IEnumerable<Planet>)orderedEnumerable2, index));
                             if (index == 2)
                                 break;
                         }
                         using (List<Planet>.Enumerator enumerator = list2.GetEnumerator())
                         {
                             while (enumerator.MoveNext())
                             {
                                 Planet current = enumerator.Current;
                                 bool flag = true;
                                 lock (GlobalStats.TaskLocker)
                                 {
                                     foreach (MilitaryTask item_1 in (List<MilitaryTask>)this.TaskList)
                                     {
                                         if (item_1.GetTargetPlanet() == current && item_1.type == MilitaryTask.TaskType.AssaultPlanet)
                                         {
                                             flag = false;
                                             break;
                                         }
                                     }
                                 }
                                 if (flag)
                                 {
                                     MilitaryTask militaryTask = new MilitaryTask(current, this.empire);
                                     lock (GlobalStats.TaskLocker)
                                         this.TaskList.Add(militaryTask);
                                 }
                             }
                             break;
                         }
                 }
             }
             if (r.Value.AtWar)
             {
                 int num = (int)this.empire.data.difficulty;
                 this.FightDefaultWar(r);
             }
         }
     }
 }
 public void FactionUpdate()
 {
     string name = this.empire.data.Traits.Name;
     if (name != null && name == "Corsairs")
     {
         bool AttackingSomeone = false;
         lock (GlobalStats.TaskLocker)
         {
             foreach (MilitaryTask task in this.TaskList)
             {
                 if (task.type != MilitaryTask.TaskType.CorsairRaid)
                 {
                     continue;
                 }
                 AttackingSomeone = true;
             }
         }
         if (!AttackingSomeone)
         {
             foreach (KeyValuePair<Empire, Relationship> r in this.empire.GetRelations())
             {
                 if (!r.Value.AtWar || r.Key.GetPlanets().Count <= 0 || this.empire.GetShips().Count <= 0)
                 {
                     continue;
                 }
                 Vector2 center = new Vector2();
                 foreach (Ship ship in this.empire.GetShips())
                 {
                     center = center + ship.Center;
                 }
                 center = center / (float)this.empire.GetShips().Count;
                 IOrderedEnumerable<Planet> sortedList =
                     from planet in r.Key.GetPlanets()
                     orderby Vector2.Distance(planet.Position, center)
                     select planet;
                 MilitaryTask task = new MilitaryTask(this.empire);
                 task.SetTargetPlanet(sortedList.First<Planet>());
                 task.TaskTimer = 300f;
                 task.type = MilitaryTask.TaskType.CorsairRaid;
                 lock (GlobalStats.TaskLocker)
                 {
                     this.TaskList.Add(task);
                 }
             }
         }
     }
     lock (GlobalStats.TaskLocker)
     {
         foreach (MilitaryTask task in this.TaskList)
         {
             if (task.type != MilitaryTask.TaskType.Exploration)
             {
                 task.Evaluate(this.empire);
             }
             else
             {
                 task.EndTask();
             }
         }
     }
 }
        //added by gremlin assaultrequistion forces
        private void RequisitionAssaultForcesDevek()
        {
            List<Troop>.Enumerator enumerator;
            if (this.IsToughNut)
            {
                this.DoToughNutRequisition();
                return;
            }
            IOrderedEnumerable<AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;
            if (sorted.Count<AO>() == 0)
            {
                return;
            }
            AO ClosestAO = sorted.First<AO>();
            if (this.TargetPlanet.Owner == null || !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
            {
                this.EndTask();
                return;
            }
            if (this.empire.GetRelations()[this.TargetPlanet.Owner].Treaty_Peace)
            {
                this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar = false;
                this.EndTask();
                return;
            }
            float EnemyTroopStrength = this.TargetPlanet.GetGroundStrengthOther(this.empire);
            //this.TargetPlanet.GetGroundStrengthOther(this.empire);
            //foreach (PlanetGridSquare pgs in this.TargetPlanet.TilesList)
            //{

            //    if (pgs.TroopsHere.Count <= 0)
            //    {
            //        if (pgs.building == null || pgs.building.CombatStrength <= 0)
            //        {
            //            continue;
            //        }
            //        EnemyTroopStrength = EnemyTroopStrength + (float)(pgs.building.CombatStrength + 5);
            //    }
            //    else if(pgs.TroopsHere[0].GetOwner() != this.empire)
            //    {
            //        EnemyTroopStrength = EnemyTroopStrength + (float)pgs.TroopsHere[0].Strength;
            //    }
            //}
            if (EnemyTroopStrength < 20f)
            {
                EnemyTroopStrength = 25f;
            }

            List<Ship> PotentialAssaultShips = new List<Ship>();
            List<Troop> PotentialTroops = new List<Troop>();
            List<Ship> PotentialBombers = new List<Ship>();
            //added by gremlin trying to get AI to use ships with assault bays.
            foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
            {
                if ((!ship.HasTroopBay || ship.TroopList.Count <= 0) && !(ship.Role == "troop") || ship.fleet != null)
                {
                    if (!ship.HasTroopBay && !ship.hasTransporter || ship.TroopList.Count == 0 || ship.fleet == null)
                    {
                        continue;
                    }
                }
                PotentialAssaultShips.Add(ship);
            }
            List<Planet> shipyards = new List<Planet>();
            foreach (Planet planet1 in ClosestAO.GetPlanets())
            {
                if (!planet1.HasShipyard)
                {
                    continue;
                }
                shipyards.Add(planet1);
            }
            IOrderedEnumerable<Planet> planets =
                from p in shipyards
                orderby Vector2.Distance(p.Position, this.TargetPlanet.Position)
                select p;
            if (planets.Count<Planet>() == 0)
            {
                return;
            }
            IOrderedEnumerable<Planet> sortedList =
                from planet in ClosestAO.GetPlanets()
                orderby Vector2.Distance(planet.Position, planets.First<Planet>().Position)
                select planet;
            foreach (Planet planet2 in sortedList)
            {
                foreach (Troop t in planet2.TroopsHere)
                {
                    if (t.GetOwner() != this.empire || planet2.ParentSystem.combatTimer >0)
                    {
                        continue;
                    }
                    t.SetPlanet(planet2);
                    PotentialTroops.Add(t);
                }
            }
            float ourAvailableStrength = 0f;
            foreach (Ship ship in PotentialAssaultShips)
            {
                foreach (Troop t in ship.TroopList)
                {
                    ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
                }
            }

            bool GoodToGo = false;
            foreach (Troop t in PotentialTroops)
            {
                ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
            }
            float MinimumEscortStrength = 0f;
            int count = 0;
            float OurPresentStrength = 0f;
            foreach (Ship ship in this.TargetPlanet.system.ShipList)
            {
                if (ship.loyalty == this.TargetPlanet.Owner)
                {
                    MinimumEscortStrength = MinimumEscortStrength + ship.GetStrength();
                    count++;
                }
                if (ship.loyalty != this.empire)
                {
                    continue;
                }
                OurPresentStrength = OurPresentStrength + ship.GetStrength();
            }
            MinimumEscortStrength = MinimumEscortStrength + 0.4f * MinimumEscortStrength +EnemyTroopStrength ;

            this.MinimumTaskForceStrength = MinimumEscortStrength;
            BatchRemovalCollection<Ship> elTaskForce = new BatchRemovalCollection<Ship>();
            float tfstrength = 0f;
            foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
            {
                if (ship.InCombat || ship.fleet != null || (ship.Role == "station" || ship.Role == "platform") || tfstrength >= MinimumEscortStrength || ship.GetStrength() <= 0f)
                {
                    continue;
                }
                tfstrength = tfstrength + ship.GetStrength();
                elTaskForce.Add(ship);
            }
            //&& this.TargetPlanet.GetGroundLandingSpots() <this.TargetPlanet.GetPotentialGroundTroops(this.empire) *.5 )
            if (ourAvailableStrength > EnemyTroopStrength * 1.65f && this.TargetPlanet.GetGroundLandingSpots() >5 && tfstrength >= this.MinimumTaskForceStrength)
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                {
                    this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                }
                GoodToGo = true;
                Fleet newFleet = new Fleet()
                {
                    Owner = this.empire,
                    Name = "Invasion Fleet"
                };
                int i = 1;
                while (i < 10)
                {
                    if (this.empire.GetGSAI().UsedFleets.Contains(i))
                    {
                        i++;
                    }
                    else
                    {
                        float ForceStrength = 0f;
                        List<Ship>.Enumerator enumerator1 = PotentialAssaultShips.GetEnumerator();
                        try
                        {
                            do
                            {
                                if (!enumerator1.MoveNext())
                                {
                                    break;
                                }
                                Ship ship = enumerator1.Current;
                                newFleet.AddShip(ship);
                                foreach (Troop t in ship.TroopList)
                                {
                                    ForceStrength = ForceStrength + (float)t.Strength;
                                }
                            }
                            while (ForceStrength <= EnemyTroopStrength * 2f);
                        }
                        finally
                        {
                            ((IDisposable)enumerator1).Dispose();
                        }
                        List<Troop>.Enumerator enumerator2 = PotentialTroops.GetEnumerator();
                        try
                        {
                            do
                            {
                            Label1:
                                if (!enumerator2.MoveNext())
                                {
                                    break;
                                }
                                Troop t = enumerator2.Current;
                                if (t.GetPlanet() != null)
                                {
                                    (new List<Troop>()).Add(t);
                                    if (t.GetOwner() != null)
                                    {
                                        newFleet.AddShip(t.Launch());
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                    }
                                    else
                                    {
                                        goto Label1;
                                    }
                                }
                                else
                                {
                                    goto Label1;
                                }
                            }
                            while (ForceStrength <= EnemyTroopStrength + EnemyTroopStrength * 0.3f);
                        }
                        finally
                        {
                            ((IDisposable)enumerator2).Dispose();
                        }
                        this.empire.GetFleetsDict()[i] = newFleet;
                        this.empire.GetGSAI().UsedFleets.Add(i);
                        this.WhichFleet = i;
                        newFleet.Task = this;
                        foreach (Ship ship in elTaskForce)
                        {
                            newFleet.AddShip(ship);
                            ship.GetAI().OrderQueue.Clear();
                            ship.GetAI().State = AIState.AwaitingOrders;
                            ClosestAO.GetOffensiveForcePool().Remove(ship);
                            ClosestAO.GetWaitingShips().Remove(ship);
                        }
                        newFleet.AutoArrange();
                        break;
                    }
                }
                this.Step = 1;
            }
            else if (ourAvailableStrength >= EnemyTroopStrength && tfstrength >= this.MinimumTaskForceStrength)
            {
                foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
                {
                    if ((ship.Role == "station" || ship.Role == "platform") || ship.BombBays.Count <= 0)
                    {
                        continue;
                    }
                    PotentialBombers.Add(ship);
                    if (elTaskForce.Contains(ship))
                    {
                        continue;
                    }
                    elTaskForce.Add(ship);
                }
                if (PotentialBombers.Count > 0)
                {
                    if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                    {
                        this.EndTask();
                        return;
                    }
                    if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                    {
                        this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                    }
                    GoodToGo = true;
                    Fleet newFleet = new Fleet()
                    {
                        Owner = this.empire,
                        Name = "Invasion Fleet"
                    };
                    int i = 1;
                    while (i < 10)
                    {
                        if (this.empire.GetGSAI().UsedFleets.Contains(i))
                        {
                            i++;
                        }
                        else
                        {
                            float ForceStrength = 0f;
                            List<Ship>.Enumerator enumerator3 = PotentialAssaultShips.GetEnumerator();
                            try
                            {
                                do
                                {
                                    if (!enumerator3.MoveNext())
                                    {
                                        break;
                                    }
                                    Ship ship = enumerator3.Current;
                                    newFleet.AddShip(ship);
                                    foreach (Troop t in ship.TroopList)
                                    {
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                    }
                                }
                                while (ForceStrength <= EnemyTroopStrength * 2f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator3).Dispose();
                            }
                            enumerator = PotentialTroops.GetEnumerator();
                            try
                            {
                                do
                                {
                                Label0:
                                    if (!enumerator.MoveNext())
                                    {
                                        break;
                                    }
                                    Troop t = enumerator.Current;
                                    if (t.GetPlanet() != null && t != null)
                                    {
                                        (new List<Troop>()).Add(t);
                                        Ship launched = t.Launch();
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                        newFleet.AddShip(launched);
                                    }
                                    else
                                    {
                                        goto Label0;
                                    }
                                }
                                while (ForceStrength <= EnemyTroopStrength + EnemyTroopStrength * 0.3f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                            this.empire.GetFleetsDict()[i] = newFleet;
                            this.empire.GetGSAI().UsedFleets.Add(i);
                            this.WhichFleet = i;
                            newFleet.Task = this;
                            foreach (Ship ship in elTaskForce)
                            {
                                newFleet.AddShip(ship);
                                ship.GetAI().OrderQueue.Clear();
                                ship.GetAI().State = AIState.AwaitingOrders;
                                ClosestAO.GetOffensiveForcePool().Remove(ship);
                                ClosestAO.GetWaitingShips().Remove(ship);
                            }
                            newFleet.AutoArrange();
                            break;
                        }
                    }
                    this.Step = 1;
                }
            }
            else if (ourAvailableStrength > EnemyTroopStrength * 1.5f)
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (ClosestAO.GetCoreFleet().Task == null && ClosestAO.GetCoreFleet().GetStrength() > this.MinimumTaskForceStrength)
                {
                    MilitaryTask clearArea = new MilitaryTask(ClosestAO.GetCoreFleet().Owner)
                    {
                        AO = this.TargetPlanet.Position,
                        AORadius = 75000f,
                        type = MilitaryTask.TaskType.ClearAreaOfEnemies
                    };
                    ClosestAO.GetCoreFleet().Owner.GetGSAI().TasksToAdd.Add(clearArea);
                    clearArea.WhichFleet = ClosestAO.WhichFleet;
                    ClosestAO.GetCoreFleet().Task = clearArea;
                    clearArea.IsCoreFleetTask = true;
                    ClosestAO.GetCoreFleet().TaskStep = 1;
                    clearArea.Step = 1;
                    if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                    {
                        this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                    }
                }
            }
            else if (EnemyTroopStrength > 100f)
            {
                this.IsToughNut = true;
            }
            if (!GoodToGo)
            {
                this.NeededTroopStrength = (int)(EnemyTroopStrength + EnemyTroopStrength * 0.3f - ourAvailableStrength);

            }
        }
        public void Update()
        {
            foreach (Ship ship in this.OffensiveForcePool)
            {
                if (ship.Active && ship.fleet == null && ship.Role != "troop")
                {
                    continue;
                }
                //this.OffensiveForcePool.Remove(ship);
                this.OffensiveForcePool.QueuePendingRemoval(ship);
            }
            this.OffensiveForcePool.ApplyPendingRemovals();

            if (this.ShipsWaitingForCoreFleet.Count > 0 && this.CoreFleet.Ships.Count < this.ThreatLevel +1
                && (this.CoreFleet.Ships.Count == 0 || this.CoreFleet.Task == null))
            {
                foreach (Ship waiting in this.ShipsWaitingForCoreFleet)
                {
                    if (waiting.fleet == null)
                    {
                        this.CoreFleet.AddShip(waiting);
                        waiting.GetAI().OrderQueue.Clear();
                        waiting.GetAI().HasPriorityOrder = false;
                    }
                    this.OffensiveForcePool.Remove(waiting);
                }
                this.ShipsWaitingForCoreFleet.Clear();
                this.CoreFleet.Position = this.CoreWorld.Position;
                this.CoreFleet.AutoArrange();
                this.CoreFleet.MoveToNow(this.Position, 0f, new Vector2(0f, -1f));
            }
            if (this.CoreFleet.Task == null)
            {
                AO turnsToRelax = this;
                turnsToRelax.TurnsToRelax = turnsToRelax.TurnsToRelax + 1;
            }
            if (this.ThreatLevel  * ( 1-( this.TurnsToRelax /10)) < this.CoreFleet.GetStrength())
            {
                if (this.CoreFleet.Task == null && this.CoreWorld.Owner != Ship.universeScreen.player)
                {
                    MilitaryTask clearArea = new MilitaryTask(this.CoreFleet.Owner)
                    {
                        AO = this.Position,
                        AORadius = this.Radius,
                        type = MilitaryTask.TaskType.CohesiveClearAreaOfEnemies,
                        WhichFleet = this.WhichFleet,
                        IsCoreFleetTask = true
                    };
                    this.CoreFleet.Task = clearArea;
                    this.CoreFleet.TaskStep = 1;
                    if (this.CoreFleet.Owner == null)
                    {
                        this.CoreFleet.Owner = this.CoreWorld.Owner;
                        //lock (GlobalStats.TaskLocker)
                        {
                            this.CoreFleet.Owner.GetGSAI().TaskList.Add(clearArea);
                        }
                    }
                    else
                    {
                        //lock (GlobalStats.TaskLocker)
                        {
                            this.CoreFleet.Owner.GetGSAI().TaskList.Add(clearArea);
                        }
                    }
                }
                this.TurnsToRelax = 1;
            }
        }
        public override void LoadContent()
        {
            GlobalStats.ResearchRootUIDToDisplay = "Colonization";
            SystemInfoUIElement.SysFont = Fonts.Arial12Bold;
            SystemInfoUIElement.DataFont = Fonts.Arial10;
            this.NotificationManager = new NotificationManager(this.ScreenManager, this);
            this.aw = new AutomationWindow(this.ScreenManager, this);
            for (int index = 0; (double)index < (double)this.Size.X / 5000.0; ++index)
            {
                NebulousOverlay nebulousOverlay = new NebulousOverlay();
                float z = RandomMath.RandomBetween(-200000f, -2E+07f);
                nebulousOverlay.Path = "Textures/smoke";
                nebulousOverlay.Position = new Vector3(RandomMath.RandomBetween(-0.5f * this.Size.X, this.Size.X + 0.5f * this.Size.X), RandomMath.RandomBetween(-0.5f * this.Size.X, this.Size.X + 0.5f * this.Size.X), z);
                float radians = RandomMath.RandomBetween(0.0f, 6.283185f);
                nebulousOverlay.Scale = RandomMath.RandomBetween(10f, 100f);
                nebulousOverlay.WorldMatrix = Matrix.CreateScale(50f) * Matrix.CreateScale(nebulousOverlay.Scale) * Matrix.CreateRotationZ(radians) * Matrix.CreateTranslation(nebulousOverlay.Position);
                this.Stars.Add(nebulousOverlay);
            }
            this.LoadGraphics();
            UniverseScreen.DeepSpaceManager.Setup((int)this.Size.X, (int)this.Size.Y, (int)(500000.0 * (double)this.GameScale), new Vector2(this.Size.X / 2f, this.Size.Y / 2f));
            UniverseScreen.ShipSpatialManager.Setup((int)this.Size.X, (int)this.Size.Y, (int)(500000.0 * (double)this.GameScale), new Vector2(this.Size.X / 2f, this.Size.Y / 2f));
            this.DoParticleLoad();
            this.bg3d = new Background3D(this);
            this.starfield = new Starfield(Vector2.Zero, this.ScreenManager.GraphicsDevice, this.ScreenManager.Content);
            this.starfield.LoadContent();
            GameplayObject.audioListener = this.listener;
            Weapon.audioListener = this.listener;
            GameplayObject.audioListener = this.listener;
            this.projection = Matrix.CreatePerspectiveFieldOfView(0.7853982f, (float)this.ScreenManager.GraphicsDevice.Viewport.Width / (float)this.ScreenManager.GraphicsDevice.Viewport.Height, 1000f, 3E+07f);
            this.SetLighting(this.UseRealLights);
            foreach (SolarSystem solarSystem in UniverseScreen.SolarSystemList)
            {
                foreach (string FleetUID in solarSystem.DefensiveFleets)
                {
                    Fleet defensiveFleetAt = HelperFunctions.CreateDefensiveFleetAt(FleetUID, EmpireManager.GetEmpireByName("The Remnant"), solarSystem.PlanetList[0].Position);
                    MilitaryTask militaryTask = new MilitaryTask();
                    militaryTask.AO = solarSystem.PlanetList[0].Position;
                    militaryTask.AORadius = 120000f;
                    militaryTask.type = MilitaryTask.TaskType.DefendSystem;
                    defensiveFleetAt.Task = militaryTask;
                    defensiveFleetAt.TaskStep = 3;
                    militaryTask.WhichFleet = EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().Count + 10;
                    EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().TryAdd(EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().Count + 10, defensiveFleetAt);
                    EmpireManager.GetEmpireByName("The Remnant").GetGSAI().TaskList.Add(militaryTask);
                    militaryTask.Step = 2;
                }
                if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.customRemnantElements)
                {
                    foreach (Planet p in solarSystem.PlanetList)
                    {
                        foreach (string FleetUID in p.PlanetFleets)
                        {
                            Fleet planetFleetAt = HelperFunctions.CreateDefensiveFleetAt(FleetUID, EmpireManager.GetEmpireByName("The Remnant"), p.Position);
                            MilitaryTask militaryTask = new MilitaryTask();
                            militaryTask.AO = solarSystem.PlanetList[0].Position;
                            militaryTask.AORadius = 120000f;
                            militaryTask.type = MilitaryTask.TaskType.DefendSystem;
                            planetFleetAt.Task = militaryTask;
                            planetFleetAt.TaskStep = 3;
                            militaryTask.WhichFleet = EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().Count + 10;
                            EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().TryAdd(EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().Count + 10, planetFleetAt);
                            EmpireManager.GetEmpireByName("The Remnant").GetGSAI().TaskList.Add(militaryTask);
                            militaryTask.Step = 2;
                        }
                    }
                }

                foreach (SolarSystem.FleetAndPos fleetAndPos in solarSystem.FleetsToSpawn)
                {
                    Fleet defensiveFleetAt = HelperFunctions.CreateDefensiveFleetAt(fleetAndPos.fleetname, EmpireManager.GetEmpireByName("The Remnant"), solarSystem.Position + fleetAndPos.Pos);
                    MilitaryTask militaryTask = new MilitaryTask();
                    militaryTask.AO = solarSystem.Position + fleetAndPos.Pos;
                    militaryTask.AORadius = 75000f;
                    militaryTask.type = MilitaryTask.TaskType.DefendSystem;
                    defensiveFleetAt.Task = militaryTask;
                    defensiveFleetAt.TaskStep = 3;
                    militaryTask.WhichFleet = EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().Count + 10;
                    EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().TryAdd(EmpireManager.GetEmpireByName("The Remnant").GetFleetsDict().Count + 10, defensiveFleetAt);
                    EmpireManager.GetEmpireByName("The Remnant").GetGSAI().TaskList.Add(militaryTask);
                    militaryTask.Step = 2;
                }
                foreach (string key in solarSystem.ShipsToSpawn)
                    ResourceManager.CreateShipAt(key, EmpireManager.GetEmpireByName("The Remnant"), solarSystem.PlanetList[0], true);
                foreach (Planet p in solarSystem.PlanetList)
                {
                    if (p.Owner != null)
                    {
                        foreach (string key in p.Guardians)
                            ResourceManager.CreateShipAt(key, p.Owner, p, true);
                    }
                    else
                    {
                        //Added by McShooterz: alternate hostile fleets populate universe
                        if (GlobalStats.ActiveModInfo != null && ResourceManager.HostileFleets.Fleets.Count > 0)
                        {
                            if (p.Guardians.Count > 0)
                            {
                                int randomFleet = HelperFunctions.GetRandomIndex(ResourceManager.HostileFleets.Fleets.Count);
                                foreach (string ship in ResourceManager.HostileFleets.Fleets[randomFleet].Ships)
                                {
                                    ResourceManager.CreateShipAt(ship, EmpireManager.GetEmpireByName(ResourceManager.HostileFleets.Fleets[randomFleet].Empire), p, true);
                                }
                            }
                        }
                        else
                        {
                            foreach (string key in p.Guardians)
                                ResourceManager.CreateShipAt(key, EmpireManager.GetEmpireByName("The Remnant"), p, true);
                            if (p.CorsairPresence)
                            {
                                ResourceManager.CreateShipAt("Corsair Asteroid Base", EmpireManager.GetEmpireByName("Corsairs"), p, true).TetherToPlanet(p);
                                ResourceManager.CreateShipAt("Corsair", EmpireManager.GetEmpireByName("Corsairs"), p, true);
                                ResourceManager.CreateShipAt("Captured Gunship", EmpireManager.GetEmpireByName("Corsairs"), p, true);
                                ResourceManager.CreateShipAt("Captured Gunship", EmpireManager.GetEmpireByName("Corsairs"), p, true);
                            }
                        }
                    }
                }
                foreach (Anomaly anomaly in solarSystem.AnomaliesList)
                {
                    if (anomaly.type == "DP")
                        this.anomalyManager.AnomaliesList.Add((Anomaly)new DimensionalPrison(solarSystem.Position + anomaly.Position));
                }
            }
            float num = 10f;
            Matrix matrix = this.view;
            this.MaxCamHeight = 4E+07f;
            while ((double)num < (double)(this.ScreenManager.GraphicsDevice.PresentationParameters.BackBufferWidth + 50))
            {
                Vector2 vector2_1 = new Vector2(this.Size.X / 2f, this.Size.Y / 2f);
                Matrix view = Matrix.CreateTranslation(0.0f, 0.0f, 0.0f) * Matrix.CreateRotationY(MathHelper.ToRadians(180f)) * Matrix.CreateRotationX(MathHelper.ToRadians(0.0f)) * Matrix.CreateLookAt(new Vector3(-vector2_1.X, vector2_1.Y, this.MaxCamHeight), new Vector3(-vector2_1.X, vector2_1.Y, 0.0f), new Vector3(0.0f, -1f, 0.0f));
                Vector3 vector3_1 = this.ScreenManager.GraphicsDevice.Viewport.Project(Vector3.Zero, this.projection, view, Matrix.Identity);
                Vector2 vector2_2 = new Vector2(vector3_1.X, vector3_1.Y);
                Vector3 vector3_2 = this.ScreenManager.GraphicsDevice.Viewport.Project(new Vector3(this.Size, 0.0f), this.projection, view, Matrix.Identity);
                num = new Vector2(vector3_2.X, vector3_2.Y).X - vector2_2.X;
                if ((double)num < (double)(this.ScreenManager.GraphicsDevice.PresentationParameters.BackBufferWidth + 50))
                    this.MaxCamHeight -= 0.1f * this.MaxCamHeight;
            }
            if (MaxCamHeight > 23000000) MaxCamHeight = 23000000;
            if (!this.loading)
            {
                this.camPos.X = this.playerShip.Center.X;
                this.camPos.Y = this.playerShip.Center.Y;
                this.camHeight = 2750f;
            }
            this.transitionDestination = new Vector3(this.camPos.X, this.camPos.Y, this.camHeight);
            foreach (NebulousOverlay nebulousOverlay in this.Stars)
                this.star_particles.AddParticleThreadA(nebulousOverlay.Position, Vector3.Zero);
            if (this.MultiThread)
            {
                this.WorkerThread = new Thread(new ThreadStart(this.Worker));
                this.WorkerThread.IsBackground = true;
                this.WorkerThread.Start();
                //this.ShipUpdateThread = new Thread(new ThreadStart(this.ShipUpdater));
                //this.ShipUpdateThread.IsBackground = true;
            #if !ALTERTHREAD
                this.SystemResetEvents = new ManualResetEvent[4];
                this.SystemGateKeeper = new AutoResetEvent[4];
                List<SolarSystem> list1 = new List<SolarSystem>();
                List<SolarSystem> list2 = new List<SolarSystem>();
                List<SolarSystem> list3 = new List<SolarSystem>();
                List<SolarSystem> list4 = new List<SolarSystem>();
                Rectangle rect1 = new Rectangle(0, 0, (int)this.Size.X / 2, (int)this.Size.Y / 2);
                Rectangle rect2 = new Rectangle((int)this.Size.X / 2, 0, (int)this.Size.X / 2, (int)this.Size.Y / 2);
                Rectangle rect3 = new Rectangle(0, (int)this.Size.Y / 2, (int)this.Size.X / 2, (int)this.Size.Y / 2);
                Rectangle rect4 = new Rectangle((int)this.Size.X / 2, (int)this.Size.Y / 2, (int)this.Size.X / 2, (int)this.Size.Y / 2);
                this.SystemResetEvents[0] = new ManualResetEvent(false);
                this.SystemGateKeeper[0] = new AutoResetEvent(false);
                this.SystemResetEvents[1] = new ManualResetEvent(false);
                this.SystemGateKeeper[1] = new AutoResetEvent(false);
                this.SystemResetEvents[2] = new ManualResetEvent(false);
                this.SystemGateKeeper[2] = new AutoResetEvent(false);
                this.SystemResetEvents[3] = new ManualResetEvent(false);
                this.SystemGateKeeper[3] = new AutoResetEvent(false);
                for (int index = 0; index < UniverseScreen.SolarSystemList.Count; ++index)
                {
                    if (HelperFunctions.CheckIntersection(rect1, UniverseScreen.SolarSystemList[index].Position))
                    {
                        UniverseScreen.SolarSystemList[index].IndexOfResetEvent = 0;
                        list1.Add(UniverseScreen.SolarSystemList[index]);
                    }
                    if (HelperFunctions.CheckIntersection(rect2, UniverseScreen.SolarSystemList[index].Position))
                    {
                        UniverseScreen.SolarSystemList[index].IndexOfResetEvent = 1;
                        list2.Add(UniverseScreen.SolarSystemList[index]);
                    }
                    if (HelperFunctions.CheckIntersection(rect3, UniverseScreen.SolarSystemList[index].Position))
                    {
                        UniverseScreen.SolarSystemList[index].IndexOfResetEvent = 2;
                        list3.Add(UniverseScreen.SolarSystemList[index]);
                    }
                    if (HelperFunctions.CheckIntersection(rect4, UniverseScreen.SolarSystemList[index].Position))
                    {
                        UniverseScreen.SolarSystemList[index].IndexOfResetEvent = 3;
                        list4.Add(UniverseScreen.SolarSystemList[index]);
                    }
                }
                Thread thread1 = new Thread(new ParameterizedThreadStart(this.SystemUpdater));
                this.SystemUpdateThreadList.Add(thread1);
                thread1.Start((object)list1);
                thread1.IsBackground = true;
                Thread thread2 = new Thread(new ParameterizedThreadStart(this.SystemUpdater));
                this.SystemUpdateThreadList.Add(thread2);
                thread2.Start((object)list2);
                thread2.IsBackground = true;
                Thread thread3 = new Thread(new ParameterizedThreadStart(this.SystemUpdater));
                this.SystemUpdateThreadList.Add(thread3);
                thread3.Start((object)list3);
                thread3.IsBackground = true;
                Thread thread4 = new Thread(new ParameterizedThreadStart(this.SystemUpdater));
                this.SystemUpdateThreadList.Add(thread4);
                thread4.Start((object)list4);
                thread4.IsBackground = true;
            #endif
                //Thread thread5 = new Thread(new ThreadStart(this.DeepSpaceThread));
               // this.SystemUpdateThreadList.Add(thread5);
               // thread5.Start();
               // thread5.IsBackground = true;
                //Thread thread6 = new Thread(new ThreadStart(this.EmpireThread));
                //this.SystemUpdateThreadList.Add(thread6);
                //thread6.Start();
                //thread6.IsBackground = true;

            }
            this.PlanetsDict.Clear();
            this.SolarSystemDict.Clear();
            foreach (SolarSystem solarSystem in UniverseScreen.SolarSystemList)
            {
                this.SolarSystemDict.Add(solarSystem.guid, solarSystem);
                foreach (Planet planet in solarSystem.PlanetList)
                    this.PlanetsDict.Add(planet.guid, planet);
            }
            foreach (Ship ship in (List<Ship>)this.MasterShipList)
            {
                if (ship.TetherGuid != Guid.Empty)
                    ship.TetherToPlanet(this.PlanetsDict[ship.TetherGuid]);
            }
        }
        public override void Update(float elapsedTime)
        {
            if (!this.Active)
                return;
            //if (!GlobalStats.WarpInSystem && this.system != null)
            //    this.InhibitedTimer = 1f;
            //else
                if (this.FTLmodifier < 1.0 && this.system != null && (this.engineState == Ship.MoveState.Warp && this.velocityMaximum < this.GetSTLSpeed()))
                this.HyperspaceReturn();
            if (this.ScuttleTimer > -1.0 || this.ScuttleTimer <-1.0)
            {
                this.ScuttleTimer -= elapsedTime;
                if (this.ScuttleTimer <= 0.0)
                    this.Die((GameplayObject)null, true);
            }
            if ((this.system != null && this.system.isVisible) || this.system == null)
            {
                BoundingSphere sphere = new BoundingSphere(new Vector3(this.Position, 0.0f), 2000f);
                if (Ship.universeScreen.Frustum.Contains(sphere) != ContainmentType.Disjoint && Ship.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView)
                {
                    this.InFrustum = true;
                    this.ShipSO.Visibility = ObjectVisibility.Rendered;
                }
                else
                {
                    this.InFrustum = false;
                    this.ShipSO.Visibility = ObjectVisibility.None;
                }

            }
            else
            {
                this.InFrustum = false;
                this.ShipSO.Visibility = ObjectVisibility.None;
            }
            foreach (ProjectileTracker projectileTracker in (List<ProjectileTracker>)this.ProjectilesFired)
            {
                projectileTracker.Timer -= elapsedTime;
                if ((double)projectileTracker.Timer <= 0.0)
                    this.ProjectilesFired.QueuePendingRemoval(projectileTracker);
            }
            this.ProjectilesFired.ApplyPendingRemovals();
            this.ShieldRechargeTimer += elapsedTime;
            this.InhibitedTimer -= elapsedTime;
            this.Inhibited = this.InhibitedTimer > 0.0;
            if (this.Inhibited && this.engineState == Ship.MoveState.Warp)
            {
                this.HyperspaceReturn();
            }
            if (this.TetheredTo != null)
            {
                this.Position = this.TetheredTo.Position + this.TetherOffset;
                this.Center = this.TetheredTo.Position + this.TetherOffset;
            }
            if (this.Mothership != null && !this.Mothership.Active)
                this.Mothership = (Ship)null;
            if (this.dying)
            {
                this.ThrusterList.Clear();
                this.dietimer -= elapsedTime;
                if ((double)this.dietimer <= 1.89999997615814 && this.dieCue == null && this.InFrustum)
                {
                    if (this.Size < 80)
                    {
                        this.dieCue = AudioManager.GetCue("sd_explosion_ship_warpdet_small");
                        this.dieCue.Apply3D(Ship.universeScreen.listener, this.emitter);
                        this.dieCue.Play();
                    }
                    else if (this.Size >= 80 && this.Size < 250)
                    {
                        this.dieCue = AudioManager.GetCue("sd_explosion_ship_warpdet_medium");
                        this.dieCue.Apply3D(Ship.universeScreen.listener, this.emitter);
                        this.dieCue.Play();
                    }
                    else
                    {
                        this.dieCue = AudioManager.GetCue("sd_explosion_ship_warpdet_large");
                        this.dieCue.Apply3D(Ship.universeScreen.listener, this.emitter);
                        this.dieCue.Play();
                    }
                }
                if ((double)this.dietimer <= 0.0)
                {
                    this.reallyDie = true;
                    this.Die(this.LastDamagedBy, true);
                    return;
                }
                else
                {
                    if ((double)this.Velocity.Length() > (double)this.velocityMaximum)
                        this.Velocity = Vector2.Normalize(this.Velocity) * this.velocityMaximum;
                    Ship ship1 = this;
                    Vector2 vector2_1 = ship1.Position + this.Velocity * elapsedTime;
                    ship1.Position = vector2_1;
                    Ship ship2 = this;
                    Vector2 vector2_2 = ship2.Center + this.Velocity * elapsedTime;
                    ship2.Center = vector2_2;
                    int num1 = (int)(this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, 60f);
                    if (num1 >= 57 && this.InFrustum)
                    {
                        float radius = this.ShipSO.WorldBoundingSphere.Radius;
                        Vector3 vector3 = new Vector3((this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius));
                        ExplosionManager.AddExplosion(vector3, radius, 2.5f, 0.2f);
                        Ship.universeScreen.flash.AddParticleThreadA(vector3, Vector3.Zero);
                    }
                    if (num1 >= 40)
                    {
                        Vector3 position = new Vector3((this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween(0.0f, this.Radius));
                        Ship.universeScreen.sparks.AddParticleThreadA(position, Vector3.Zero);
                    }
                    this.yRotation += this.xdie * elapsedTime;
                    this.xRotation += this.ydie * elapsedTime;
                    Ship ship3 = this;
                    double num2 = (double)ship3.Rotation + (double)this.zdie * (double)elapsedTime;
                    ship3.Rotation = (float)num2;
                    if (this.ShipSO == null)
                        return;
                    if (Ship.universeScreen.viewState == UniverseScreen.UnivScreenState.ShipView && this.inSensorRange)
                    {
                        this.ShipSO.World = Matrix.Identity * Matrix.CreateRotationY(this.yRotation) * Matrix.CreateRotationX(this.xRotation) * Matrix.CreateRotationZ(this.Rotation) * Matrix.CreateTranslation(new Vector3(this.Center, 0.0f));
                        if (this.shipData.Animated)
                        {
                            this.ShipSO.SkinBones = this.animationController.SkinnedBoneTransforms;
                            this.animationController.Update(Game1.Instance.TargetElapsedTime, Matrix.Identity);
                        }
                    }
                    for (int index = 0; index < this.Projectiles.Count; ++index)
                    {
                        Projectile projectile = this.Projectiles[index];
                        if (projectile != null)
                        {
                            if (projectile.Active)
                                projectile.Update(elapsedTime);
                            else
                                this.Projectiles.QueuePendingRemoval(projectile);
                        }
                    }
                    this.emitter.Position = new Vector3( this.Center, 0);//GlobalStats.Config.EffectsVolume * -5000);
                    foreach (ModuleSlot moduleSlot in this.ModuleSlotList)
                    //Parallel.ForEach<ModuleSlot>(this.ModuleSlotList, moduleSlot =>
                    {
                        moduleSlot.module.UpdateWhileDying(elapsedTime);
                    }//);
                }
            }
            else if (!this.dying)
            {
                if (this.system != null && (double)elapsedTime > 0.0)
                {
                    foreach (Planet p in this.system.PlanetList)
                    {
                        if ((double)Vector2.Distance(p.Position, this.Center) < 3000.0)
                        {
                            if (this.loyalty == Ship.universeScreen.player && !p.ExploredDict[this.loyalty])
                            {
                                foreach (Building building in p.BuildingList)
                                {
                                    if (!string.IsNullOrEmpty(building.EventTriggerUID))
                                        Ship.universeScreen.NotificationManager.AddFoundSomethingInteresting(p);
                                }
                            }
                            if (!p.ExploredDict[this.loyalty])
                            {
                                p.ExploredDict[this.loyalty] = true;
                                foreach (Building building in p.BuildingList)
                                {
                                    if (!string.IsNullOrEmpty(building.EventTriggerUID) && this.loyalty != Ship.universeScreen.player && p.Owner == null)
                                    {
                                        MilitaryTask militaryTask = new MilitaryTask();
                                        militaryTask.AO = p.Position;
                                        militaryTask.AORadius = 50000f;
                                        militaryTask.SetTargetPlanet(p);
                                        militaryTask.type = MilitaryTask.TaskType.Exploration;
                                        militaryTask.SetEmpire(this.loyalty);
                                        lock (GlobalStats.TaskLocker)
                                            this.loyalty.GetGSAI().TaskList.Add(militaryTask);
                                    }
                                }
                                //added by gremlin put shahmatts exploration notifications here
                            }
                        }
                    }
                    if (this.InCombat && this.GetAI().Target != null && this.GetAI().Target.GetSystem() != null && this.GetAI().Target.GetSystem() == this.GetSystem())
                    {
                        this.system.CombatInSystem = true;
                        this.system.combatTimer = 15f;
                    }
                }
                if (this.disabled)
                {
                    for (int index = 0; index < 5; ++index)
                    {
                        Vector3 vector3 = new Vector3((this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween((float)(-(double)this.radius / 3.0), this.radius / 3f), (this.system != null ? this.system.RNG : Ship.universeScreen.DeepSpaceRNG).RandomBetween((float)(-(double)this.radius / 3.0), this.radius / 3f), 0.0f);
                        Ship.universeScreen.lightning.AddParticleThreadA(new Vector3(this.Center, 0.0f) + vector3, Vector3.Zero);
                    }
                }
                Ship ship1 = this;
                double num1 = (double)ship1.Rotation + (double)this.RotationalVelocity * (double)elapsedTime;
                ship1.Rotation = (float)num1;
                if ((double)Math.Abs(this.RotationalVelocity) > 0.0)
                    this.isTurning = true;
                if (!this.isSpooling && this.Afterburner != null && this.Afterburner.IsPlaying)
                    this.Afterburner.Stop(AudioStopOptions.Immediate);
                this.ClickTimer -= elapsedTime;
                if ((double)this.ClickTimer < 0.0)
                    this.ClickTimer = 10f;
                if (this.Active)
                {
                    this.InCombatTimer -= elapsedTime;
                    if (this.InCombatTimer > 0.0)
                    {
                        this.InCombat = true;
                    }
                    else
                    {
                        if (this.InCombat)
                            this.InCombat = false;
                        try
                        {
                            if (this.AI.State == AIState.Combat)
                            {
                                if (this.loyalty != Ship.universeScreen.player)
                                {
                                    this.AI.State = AIState.AwaitingOrders;
                                    this.GetAI().OrderQueue.Clear();
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    this.Velocity.Length();
                    Ship ship2 = this;
                    Vector2 vector2_1 = ship2.Position + this.Velocity * elapsedTime;
                    ship2.Position = vector2_1;
                    Ship ship3 = this;
                    Vector2 vector2_2 = ship3.Center + this.Velocity * elapsedTime;
                    ship3.Center = vector2_2;
                    this.UpdateShipStatus(elapsedTime);
                    if (!this.Active)
                        return;
                    if (!this.disabled && !Ship.universeScreen.Paused) //this.hasCommand &&
                        this.AI.Update(elapsedTime);
                    if (this.InFrustum)
                    {
                        if (this.ShipSO == null)
                            return;
                        this.ShipSO.World = Matrix.Identity * Matrix.CreateRotationY(this.yRotation) * Matrix.CreateRotationZ(this.Rotation) * Matrix.CreateTranslation(new Vector3(this.Center, 0.0f));
                        if (this.shipData.Animated && this.animationController != null)
                        {
                            this.ShipSO.SkinBones = this.animationController.SkinnedBoneTransforms;
                            this.animationController.Update(Game1.Instance.TargetElapsedTime, Matrix.Identity);
                        }
                        else if (this.shipData != null && this.animationController != null && this.shipData.Animated)
                        {
                            this.ShipSO.SkinBones = this.animationController.SkinnedBoneTransforms;
                            this.animationController.Update(Game1.Instance.TargetElapsedTime, Matrix.Identity);
                        }
                        foreach (Thruster thruster in this.ThrusterList)
                        {
                            thruster.SetPosition();
                            Vector2 vector2_3 = new Vector2((float)Math.Sin((double)this.Rotation), -(float)Math.Cos((double)this.Rotation));
                            vector2_3 = Vector2.Normalize(vector2_3);
                            float num2 = this.Velocity.Length() / this.velocityMaximum;
                            if (this.isThrusting)
                            {
                                if (this.engineState == Ship.MoveState.Warp)
                                {
                                    if ((double)thruster.heat < (double)num2)
                                        thruster.heat += 0.06f;
                                    this.pointat = new Vector3(vector2_3.X, vector2_3.Y, 0.0f);
                                    this.scalefactors = new Vector3(thruster.tscale, thruster.tscale, thruster.tscale);
                                    thruster.update(thruster.WorldPos, this.pointat, this.scalefactors, thruster.heat, 0.004f, Color.OrangeRed, Color.LightBlue, Ship.universeScreen.camPos);
                                }
                                else
                                {
                                    if ((double)thruster.heat < (double)num2)
                                        thruster.heat += 0.06f;
                                    if ((double)thruster.heat > 0.600000023841858)
                                        thruster.heat = 0.6f;
                                    this.pointat = new Vector3(vector2_3.X, vector2_3.Y, 0.0f);
                                    this.scalefactors = new Vector3(thruster.tscale, thruster.tscale, thruster.tscale);
                                    thruster.update(thruster.WorldPos, this.pointat, this.scalefactors, thruster.heat, 1.0f / 500.0f, Color.OrangeRed, Color.LightBlue, Ship.universeScreen.camPos);
                                }
                            }
                            else
                            {
                                this.pointat = new Vector3(vector2_3.X, vector2_3.Y, 0.0f);
                                this.scalefactors = new Vector3(thruster.tscale, thruster.tscale, thruster.tscale);
                                thruster.heat = 0.01f;
                                thruster.update(thruster.WorldPos, this.pointat, this.scalefactors, 0.1f, 1.0f / 500.0f, Color.OrangeRed, Color.LightBlue, Ship.universeScreen.camPos);
                            }
                        }
                    }
                    if (this.isSpooling)
                        this.fightersOut = false;
                    if (this.isSpooling && !this.Inhibited)
                    {
                        this.JumpTimer -= elapsedTime;
                        //task gremlin move fighter recall here.

                        if (this.JumpTimer <= 4.0) // let's see if we can sync audio to behaviour with new timers
                        {
                            if (Vector2.Distance(this.Center, new Vector2(Ship.universeScreen.camPos.X, Ship.universeScreen.camPos.Y)) < 100000.0 && (this.Jump == null || this.Jump != null && !this.Jump.IsPlaying) && Ship.universeScreen.camHeight < 250000)
                            {
                                this.Jump = AudioManager.GetCue(this.GetStartWarpCue());
                                this.Jump.Apply3D(GameplayObject.audioListener, this.emitter);
                                this.Jump.Play();

                            }
                        }
                        if (this.JumpTimer <= 0.1)
                        {
                            if (this.engineState == Ship.MoveState.Sublight )//&& (!this.Inhibited && this.GetFTLSpeed() > this.velocityMaximum))
                            {
                                FTL ftl = new FTL();
                                ftl.Center = new Vector2(this.Center.X, this.Center.Y);
                                //lock (FTLManager.FTLLock)
                                FTLManager.FTLList.thisLock.EnterWriteLock();
                                    FTLManager.FTLList.Add(ftl);
                                    FTLManager.FTLList.thisLock.ExitWriteLock();
                                this.engineState = Ship.MoveState.Warp;
                            }
                            else
                                this.engineState = Ship.MoveState.Sublight;
                            this.isSpooling = false;
                            this.ResetJumpTimer();
                        }
                    }
                    if (this.isPlayerShip())
                    {
                        if ((!this.isSpooling || !this.Active) && this.Afterburner != null)
                        {
                            if (this.Afterburner.IsPlaying)
                                this.Afterburner.Stop(AudioStopOptions.Immediate);
                            this.Afterburner = (Cue)null;
                        }
                        if (this.isThrusting && this.drone == null && this.AI.State == AIState.ManualControl)
                        {
                            this.drone = AudioManager.GetCue("starcruiser_drone01");
                            this.drone.Play();
                        }
                        else if ((!this.isThrusting || !this.Active) && this.drone != null)
                        {
                            if (this.drone.IsPlaying)
                                this.drone.Stop(AudioStopOptions.Immediate);
                            this.drone = (Cue)null;
                        }
                    }
                    this.emitter.Position = new Vector3(this.Center, 0);

                }
                if (elapsedTime > 0.0f)
                {
                    //if (this.GetAI().fireTask != null && !this.GetAI().fireTask.IsCompleted)
                    //{
                    //    this.GetAI().fireTask.Wait();

                    //}
                    //task gremlin look at parallel here for weapons
                    foreach (Projectile projectile in (List<Projectile>)this.Projectiles)
                    //Parallel.ForEach<Projectile>(this.projectiles, projectile =>
                    {
                        if (projectile != null && projectile.Active)
                            projectile.Update(elapsedTime);
                        else
                        {
                           // projectile.Die(null, true);
                            this.Projectiles.QueuePendingRemoval(projectile);
                        }
                    }//);

                    foreach (Beam beam in (List<Beam>)this.beams)
                    {
                        Vector2 origin = new Vector2();
                        if (beam.moduleAttachedTo != null)
                        {
                            ShipModule shipModule = beam.moduleAttachedTo;
                            origin = (int)shipModule.XSIZE != 1 || (int)shipModule.YSIZE != 3 ? ((int)shipModule.XSIZE != 2 || (int)shipModule.YSIZE != 5 ? new Vector2(shipModule.Center.X - 8f + (float)(16 * (int)shipModule.XSIZE / 2), shipModule.Center.Y - 8f + (float)(16 * (int)shipModule.YSIZE / 2)) : new Vector2(shipModule.Center.X - 80f + (float)(16 * (int)shipModule.XSIZE / 2), shipModule.Center.Y - 8f + (float)(16 * (int)shipModule.YSIZE / 2))) : new Vector2(shipModule.Center.X - 50f + (float)(16 * (int)shipModule.XSIZE / 2), shipModule.Center.Y - 8f + (float)(16 * (int)shipModule.YSIZE / 2));
                            Vector2 target = new Vector2(shipModule.Center.X - 8f, shipModule.Center.Y - 8f);
                            float angleToTarget = HelperFunctions.findAngleToTarget(origin, target);
                            Vector2 angleAndDistance = HelperFunctions.findPointFromAngleAndDistance(shipModule.Center, MathHelper.ToDegrees(shipModule.Rotation) - angleToTarget, 8f * (float)Math.Sqrt(2.0));
                            float num2 = (float)((int)shipModule.XSIZE * 16 / 2);
                            float num3 = (float)((int)shipModule.YSIZE * 16 / 2);
                            float distance = (float)Math.Sqrt((double)((float)Math.Pow((double)num2, 2.0) + (float)Math.Pow((double)num3, 2.0)));
                            float radians = 3.141593f - (float)Math.Asin((double)num2 / (double)distance) + shipModule.GetParent().Rotation;
                            origin = HelperFunctions.findPointFromAngleAndDistance(angleAndDistance, MathHelper.ToDegrees(radians), distance);

                            int Thickness = this.system != null ? (int)this.system.RNG.RandomBetween((float)beam.thickness - 0.25f * (float)beam.thickness, (float)beam.thickness + 0.1f * (float)beam.thickness) : (int)Ship.universeScreen.DeepSpaceRNG.RandomBetween((float)beam.thickness - 0.25f * (float)beam.thickness, (float)beam.thickness + 0.1f * (float)beam.thickness);
                            beam.Update(beam.moduleAttachedTo != null ? origin : beam.owner.Center, beam.followMouse ? Ship.universeScreen.mouseWorldPos : beam.Destination, Thickness, Ship.universeScreen.view, Ship.universeScreen.projection, elapsedTime);
                            if ((double)beam.duration < 0.0 && !beam.infinite)
                            {
                                beam.Die(null, false);
                                this.beams.QueuePendingRemoval(beam);
                            }
                        }
                        else
                        {
                            beam.Die(null, false);
                            this.beams.QueuePendingRemoval(beam);
                        }
                    }//);
                    //this.beams.thisLock.ExitReadLock();

                    this.beams.ApplyPendingRemovals();
                    //foreach (Projectile projectile in this.projectiles.pendingRemovals)
                    //    projectile.Die(null,false);
                    this.Projectiles.ApplyPendingRemovals();

                }
            }
        }
        /**
            This method allocates any available manpower into a TaskForce for offensive measures; and de-allocates the TaskForce from other fleet contingents.
            Deprecated? --> DOToughtNutRequisition?
        */
        private void DoToughNutRequisitionORIG()
        {
            float EnemyTroopStr = this.GetEnemyTroopStr();
            float EnemyShipStr = this.GetEnemyStrAtTarget();
            //create collection of sorted AOs
            IOrderedEnumerable<Ship_Game.Gameplay.AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations //foreach AO, order by enemy & distance, then "select" for addition into collection
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;
            //if target is empty, AO's absent, exit method call
            if (sorted.Count<Ship_Game.Gameplay.AO>() == 0)
            {
                return;
            }
            //else, there are targets
            List<Ship> Bombers = new List<Ship>();
            List<Ship> EverythingElse = new List<Ship>();
            List<Troop> Troops = new List<Troop>();
            //calculate this faction's strength
            foreach (Ship_Game.Gameplay.AO area in sorted)
            {
                //claculate opposition fleet strength
                foreach (Ship ship in this.empire.GetShips())
                {
                    //if ship in ships in AO are null, or outside area of operation, or in combat , or in defensive DefensiveForcePool, increment to next ship
                    //(unavilable to be requisitioned for offense)
                    if (ship.GetStrength() == 0f
                        || Vector2.Distance(ship.Center, area.Position) >= area.Radius
                        || ship.InCombat
                        || ship.fleet != null
                        || this.empire.GetGSAI().DefensiveCoordinator.DefensiveForcePool.Contains(ship))// ship.GetAI().SystemToDefend !=null) //&& ship.fleet != null & ship.fleet.Task == null)
                                                                                                        //ships managed by the DefensiveCoordinator or unable to be re-allocated for offense
                    {
                        continue;
                    }
                    //for valid ships in this faction's empire
                    if (ship.BombBays.Count <= 0)
                    {
                        EverythingElse.Add(ship);
                    }
                    else
                    {
                        Bombers.Add(ship);
                    }
                }
                //claculate ground troops that may be allocated for offensive
                foreach (Planet p in area.GetPlanets())
                {
                    if (p.RecentCombat)
                    {
                        continue;
                    }
                    foreach (Troop t in p.TroopsHere)
                    {
                        if (t.GetOwner() != this.empire)
                        {
                            continue;
                        }
                        Troops.Add(t);
                    }
                }
            }
            //determine TaskForce to match calculated opposition strength
            List<Ship> TaskForce = new List<Ship>();
            float strAdded = 0f;
            List<Ship>.Enumerator enumerator = EverythingElse.GetEnumerator(); //enumerator returns position information
            try
            {
                do
                {
                    // Returns:
                    //     true if the enumerator was successfully advanced to the next element; false if
                    //     the enumerator has passed the end of the collection.
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    Ship ship = enumerator.Current;
                    TaskForce.Add(ship); //add ships that are idle (without destination ~ MoveNext)
                    strAdded = strAdded + ship.GetStrength(); //sum the strength of the task force
                }
                while (strAdded <= EnemyShipStr );//* 1.65f); //continue requisitoining ships until TaskForceStrength is greater than EnemyShipStr
            }
            finally
            {
                ((IDisposable)enumerator).Dispose(); //de-allocate object
            }
            List<Ship> BombTaskForce = new List<Ship>();
            int numBombs = 0;
            foreach (Ship ship in Bombers)
            {
                if (numBombs >= 20)
                {
                    continue; //bomber fleet should consist of at max twenth bombers
                }
                BombTaskForce.Add(ship);
                numBombs = numBombs + ship.BombBays.Count;
            }
            List<Troop> PotentialTroops = new List<Troop>();
            float troopStr = 0f;
            List<Troop>.Enumerator enumerator1 = Troops.GetEnumerator();
            int numOfTroops=0;
            try
            {
                do
                {
                    if (!enumerator1.MoveNext())
                    {
                        break;
                    }
                    numOfTroops++;
                    Troop t = enumerator1.Current;
                    PotentialTroops.Add(t);
                    troopStr = troopStr + t.Strength;
                }
                while (troopStr <= EnemyTroopStr * 1.25f || numOfTroops <15 ); //create sufficient ground force for offensive action
            }
            finally
            {
                ((IDisposable)enumerator1).Dispose();
            }
            //if this faction ship strength is greater than opposition 160% of opposition
            //Ermenildo V. Castro, Jr.
            //07/25/15
            //"* 1.65f" --> "* 3f"
            if (strAdded > EnemyShipStr * 3f)//1.65f)
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                {
                    this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                }
                //retrieve closest area of operations target
                Ship_Game.Gameplay.AO ClosestAO = sorted.First<Ship_Game.Gameplay.AO>();
                //create assault MilitaryTask
                MilitaryTask assault = new MilitaryTask(this.empire) //declarative property instantiation, constructor supplement
                {
                    AO = this.TargetPlanet.Position,
                    AORadius = 75000f,
                    type = MilitaryTask.TaskType.AssaultPlanet
                };
                ClosestAO.GetCoreFleet().Owner.GetGSAI().TasksToAdd.Add(assault);
                assault.WhichFleet = ClosestAO.WhichFleet; //assault fleet, WhichFleet, is assigned the fleet closest to target AO
                ClosestAO.GetCoreFleet().Task = assault;
                assault.IsCoreFleetTask = true;
                assault.Step = 1; //Step, used for?
                assault.TargetPlanet = this.TargetPlanet;
                ClosestAO.GetCoreFleet().TaskStep = 0;
                ClosestAO.GetCoreFleet().Name = "Doom Fleet";
                foreach (Ship ship in TaskForce)
                {
                    if (ship.fleet != null)
                    {
                        ship.fleet.Ships.Remove(ship); //remove ship from global empire fleet pool
                    }
                    ship.GetAI().OrderQueue.Clear(); //ship, rescind previous orders
                    this.empire.GetGSAI().DefensiveCoordinator.remove(ship); //remove ship from defensive coordinator pool
                    //foreach (KeyValuePair<SolarSystem, SystemCommander> entry in this.empire.GetGSAI().DefensiveCoordinator.DefenseDict)
                    //{

                    //    List<Ship> toRemove = new List<Ship>();
                    //    foreach (KeyValuePair<Guid, Ship> defender in entry.Value.ShipsDict)
                    //    {
                    //        if (defender.Key != ship.guid)
                    //        {
                    //            continue;
                    //        }
                    //        toRemove.Add(defender.Value);
                    //    }
                    //    foreach (Ship s in toRemove)
                    //    {
                    //        entry.Value.ShipsDict.Remove(s.guid);

                    //    }
                    //}
                    ship.fleet = null; //ship is unassigned to any fleet
                }
                //ASSIGN SHIPS
                foreach (Ship ship in TaskForce)
                {
                    ClosestAO.GetCoreFleet().AddShip(ship); //TaskForce ship is added into the core fleet
                }
                //ASSIGN GROUND TROOPS
                foreach (Troop t in PotentialTroops)
                {
                    if (t.GetPlanet() == null)
                    {
                        continue;
                    }
                    (new List<Troop>()).Add(t);
                    Ship launched = t.Launch(); //launch troop from ground
                    ClosestAO.GetCoreFleet().AddShip(launched); //add troop transport into core fleet
                }
                ClosestAO.GetCoreFleet().AutoArrange();
                //ASSIGN BOMBERS
                if (Bombers.Count > 0 && numBombs > 6)
                {
                    MilitaryTask GlassPlanet = new MilitaryTask(this.empire) //task this empire to glass opposition planet
                    { //multiple properties assignment declaration
                        AO = this.TargetPlanet.Position,//the target planet
                        AORadius = 75000f,
                        type = MilitaryTask.TaskType.GlassPlanet,
                        TargetPlanet = this.TargetPlanet,
                        WaitForCommand = true
                    };
                    Fleet bomberFleet = new Fleet()
                    {
                        Owner = this.empire
                    };
                    bomberFleet.Owner.GetGSAI().TasksToAdd.Add(GlassPlanet);
                    GlassPlanet.WhichFleet = this.empire.GetUnusedKeyForFleet();
                    this.empire.GetFleetsDict().TryAdd(GlassPlanet.WhichFleet, bomberFleet);
                    bomberFleet.Task = GlassPlanet;
                    bomberFleet.Name = "Bomber Fleet";
                    foreach (Ship ship in BombTaskForce)
                    {
                        if (ship.fleet != null)
                        {
                            ship.fleet.Ships.Remove(ship);
                        }
                        ship.GetAI().OrderQueue.Clear();
                        this.empire.GetGSAI().DefensiveCoordinator.remove(ship);

                        ship.fleet = null;
                    }
                    foreach (Ship ship in BombTaskForce)
                    {
                        bomberFleet.AddShip(ship);
                    }
                    bomberFleet.AutoArrange();
                }
                this.Step = 1; //What is step for?
                this.empire.GetGSAI().TaskList.QueuePendingRemoval(this); //remove this MilitaryTask from queue
            }
        }
        /**
            Variant of DoToughNutRequisitionORGI

        */
        private void DoToughNutRequisition()
        {
            float EnemyTroopStr = this.GetEnemyTroopStr();
            float EnemyShipStr = this.GetEnemyStrAtTarget();
            //sorted area of operations by this.empire strength > opposition strength at target
            //  & sorted by nearest distance AO
            IOrderedEnumerable<AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations
                //orderby ao.GetOffensiveForcePool().Sum(bombs => bombs.BombBays.Count) > 0 descending
                orderby ao.GetOffensiveForcePool().Where(combat => !combat.InCombat).Sum(strength => strength.BaseStrength) >= this.MinimumTaskForceStrength descending
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;

            if (sorted.Count<AO>() == 0)
            {
                return;//a target is unavailable
            }
            //a target is available
            List<Ship> Bombers = new List<Ship>();
            List<Ship> EverythingElse = new List<Ship>();
            List<Troop> Troops = new List<Troop>();
            foreach (AO area in sorted)
            {
                foreach (Ship ship in this.empire.GetShips().OrderBy(str=> str.BaseStrength))
                {
                    if ((ship.Role == "station" || ship.Role == "platform")
                        || ship.BaseStrength == 0f
                        || Vector2.Distance(ship.Center, area.Position) >= area.Radius
                        || ship.InCombat
                        || ship.fleet != null
                        || this.empire.GetGSAI().DefensiveCoordinator.DefensiveForcePool.Contains(ship))//&& ship.fleet.Task == null) //&& ship.fleet != null && ship.fleet.Task == null)
                    {
                        continue;
                    }
                    if (ship.BombBays.Count <= 0)
                    {
                        EverythingElse.Add(ship);
                    }
                    else
                    {
                        Bombers.Add(ship);
                    }
                }
                foreach (Planet p in area.GetPlanets())
                {
                    if (p.RecentCombat || p.ParentSystem.combatTimer>0)
                    {
                        continue;
                    }
                    foreach (Troop t in p.TroopsHere)
                    {
                        if (t.GetOwner() != this.empire)
                        {
                            continue;
                        }
                        Troops.Add(t);
                    }
                }
            }
            List<Ship> TaskForce = new List<Ship>();
            float strAdded = 0f;
            List<Ship>.Enumerator enumerator = EverythingElse.GetEnumerator();
            try
            {
                do
                {
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    Ship ship = enumerator.Current;
                    TaskForce.Add(ship);
                    strAdded = strAdded + ship.GetStrength();
                }
                while (strAdded <= EnemyShipStr * 3f);//1.65f); //Ermenildo V. Castro, Jr. 07/25/15
            }
            finally
            {
                ((IDisposable)enumerator).Dispose();
            }
            List<Ship> BombTaskForce = new List<Ship>();
            int numBombs = 0;
            foreach (Ship ship in Bombers)
            {
                if (numBombs >= 20)
                {
                    continue;
                }
                BombTaskForce.Add(ship);
                numBombs = numBombs + ship.BombBays.Count;
            }
            List<Troop> PotentialTroops = new List<Troop>();
            float troopStr = 0f;
            List<Troop>.Enumerator enumerator1 = Troops.GetEnumerator();
            int numOfTroops =0;
            try
            {
                do
                {
                    if (numOfTroops > 15 || !enumerator1.MoveNext())
                    {
                        break;
                    }
                    numOfTroops++;
                    Troop t = enumerator1.Current;
                    PotentialTroops.Add(t);
                    troopStr = troopStr + (float)t.Strength;
                }
                while (troopStr <= EnemyTroopStr * 3f);//1.25f ); //Ermenildo V. Castro, Jr. 07/25/15
            }
            finally
            {
                ((IDisposable)enumerator1).Dispose();
            }
            if (strAdded > EnemyShipStr * 3f)//1.65f) //Ermenildo V. Castro, Jr. 07/25/15
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                {
                    this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                }
                AO ClosestAO = sorted.First<AO>();
                MilitaryTask assault = new MilitaryTask(this.empire)
                {
                    AO = this.TargetPlanet.Position,
                    AORadius = 75000f,
                    type = MilitaryTask.TaskType.AssaultPlanet
                };
                ClosestAO.GetCoreFleet().Owner.GetGSAI().TasksToAdd.Add(assault);
                assault.WhichFleet = ClosestAO.WhichFleet;
                ClosestAO.GetCoreFleet().Task = assault;
                assault.IsCoreFleetTask = true;
                assault.Step = 1;

                assault.TargetPlanet = this.TargetPlanet;
                ClosestAO.GetCoreFleet().TaskStep = 0;
                ClosestAO.GetCoreFleet().Name = "Doom Fleet";
                foreach (Ship ship in TaskForce)
                {
                    if (ship.fleet != null)
                    {
                        ship.fleet.Ships.Remove(ship);
                    }
                    ship.GetAI().OrderQueue.Clear();
                    this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                    //foreach (KeyValuePair<SolarSystem, SystemCommander> entry in this.empire.GetGSAI().DefensiveCoordinator.DefenseDict)
                    //{
                    //    List<Ship> toRemove = new List<Ship>();
                    //    foreach (KeyValuePair<Guid, Ship> defender in entry.Value.ShipsDict)
                    //    {
                    //        if (defender.Key != ship.guid)
                    //        {
                    //            continue;
                    //        }
                    //        toRemove.Add(defender.Value);
                    //    }
                    //    foreach (Ship s in toRemove)
                    //    {
                    //        entry.Value.ShipsDict.Remove(s.guid);
                    //    }
                    //}
                    ship.fleet = null;
                }
                foreach (Ship ship in TaskForce)
                {
                    ClosestAO.GetCoreFleet().AddShip(ship);
                }
                foreach (Troop t in PotentialTroops)
                {
                    if (t.GetPlanet() == null)
                    {
                        continue;
                    }
                    (new List<Troop>()).Add(t);
                    Ship launched = t.Launch();
                    ClosestAO.GetCoreFleet().AddShip(launched);
                }
                ClosestAO.GetCoreFleet().AutoArrange();
                if (Bombers.Count > 0 && numBombs > 6)
                {
                    MilitaryTask GlassPlanet = new MilitaryTask(this.empire)
                    {
                        AO = this.TargetPlanet.Position,
                        AORadius = 75000f,
                        type = MilitaryTask.TaskType.GlassPlanet,
                        TargetPlanet = this.TargetPlanet,
                        WaitForCommand = true
                    };

                    Fleet bomberFleet = new Fleet()
                    {
                        Owner = this.empire
                    };
                    bomberFleet.Owner.GetGSAI().TasksToAdd.Add(GlassPlanet);
                    GlassPlanet.WhichFleet = this.empire.GetUnusedKeyForFleet();
                    this.empire.GetFleetsDict().TryAdd(GlassPlanet.WhichFleet, bomberFleet);
                    bomberFleet.Task = GlassPlanet;
                    bomberFleet.Name = "Bomber Fleet";
                    foreach (Ship ship in BombTaskForce)
                    {
                        if (ship.fleet != null)
                        {
                            ship.fleet.Ships.Remove(ship);
                        }
                        ship.GetAI().OrderQueue.Clear();
                        this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                        //foreach (KeyValuePair<SolarSystem, SystemCommander> entry in this.empire.GetGSAI().DefensiveCoordinator.DefenseDict)
                        //{
                        //    List<Ship> toRemove = new List<Ship>();
                        //    foreach (KeyValuePair<Guid, Ship> defender in entry.Value.ShipsDict)
                        //    {
                        //        if (defender.Key != ship.guid)
                        //        {
                        //            continue;
                        //        }
                        //        toRemove.Add(defender.Value);
                        //    }
                        //    foreach (Ship s in toRemove)
                        //    {
                        //        entry.Value.ShipsDict.Remove(s.guid);
                        //    }
                        //}
                        ship.fleet = null;
                    }
                    foreach (Ship ship in BombTaskForce)
                    {
                        bomberFleet.AddShip(ship);
                    }
                    bomberFleet.AutoArrange();
                }
                this.Step = 1;
                this.empire.GetGSAI().TaskList.QueuePendingRemoval(this);
            }
        }
 private void DoPostInvasionDefense(MilitaryTask Task)
 {
     --this.defenseTurns;
     if (this.defenseTurns <= 0)
     {
         Task.EndTask();
     }
     else
     {
         switch (this.TaskStep)
         {
             case -1:
                 bool flag1 = true;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     if (!ship.disabled && ship.hasCommand && ship.Active)
                     {
                         if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 5000.0)
                             flag1 = false;
                         int num = ship.InCombat ? 1 : 0;
                         if (!flag1)
                             break;
                     }
                 }
                 if (!flag1)
                     break;
                 this.TaskStep = 2;
                 this.FormationWarpTo(Task.AO, MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.findAveragePosition(), Task.AO)), Vector2.Normalize(Task.AO - this.findAveragePosition()));
                 using (List<Ship>.Enumerator enumerator = this.Ships.GetEnumerator())
                 {
                     while (enumerator.MoveNext())
                         enumerator.Current.GetAI().HasPriorityOrder = true;
                     break;
                 }
             case 0:
                 List<Planet> list1 = new List<Planet>();
                 foreach (Planet planet in this.Owner.GetPlanets())
                 {
                     if (planet.HasShipyard)
                         list1.Add(planet);
                 }
                 IOrderedEnumerable<Planet> orderedEnumerable1 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list1, (Func<Planet, float>)(planet => Vector2.Distance(Task.AO, planet.Position)));
                 if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable1) <= 0)
                     break;
                 Vector2 fVec = Vector2.Normalize(Task.AO - Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position);
                 Vector2 vector2 = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable1).Position;
                 this.MoveToNow(vector2, Math.Abs(MathHelper.ToRadians(HelperFunctions.findAngleToTarget(vector2, Task.AO))), fVec);
                 this.TaskStep = 1;
                 break;
             case 1:
                 bool flag2 = true;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     if (!ship.disabled && ship.hasCommand && ship.Active)
                     {
                         if ((double)Vector2.Distance(ship.Center, this.Position + ship.FleetOffset) > 5000.0)
                             flag2 = false;
                         int num = ship.InCombat ? 1 : 0;
                         if (!flag2)
                             break;
                     }
                 }
                 if (!flag2)
                     break;
                 this.TaskStep = 2;
                 this.FormationWarpTo(Task.AO, MathHelper.ToRadians(HelperFunctions.findAngleToTarget(this.findAveragePosition(), Task.AO)), Vector2.Normalize(Task.AO - this.findAveragePosition()));
                 using (List<Ship>.Enumerator enumerator = this.Ships.GetEnumerator())
                 {
                     while (enumerator.MoveNext())
                         enumerator.Current.GetAI().HasPriorityOrder = true;
                     break;
                 }
             case 2:
                 bool flag3 = false;
                 if ((double)Vector2.Distance(this.findAveragePosition(), Task.AO) < 15000.0)
                 {
                     foreach (Ship ship in (List<Ship>)this.Ships)
                     {
                         lock (ship)
                         {
                             if (ship.InCombat)
                             {
                                 flag3 = true;
                                 ship.HyperspaceReturn();
                                 ship.GetAI().OrderQueue.Clear();
                                 break;
                             }
                         }
                     }
                 }
                 if (!flag3 && (double)Vector2.Distance(this.findAveragePosition(), Task.AO) >= 5000.0)
                     break;
                 this.TaskStep = 3;
                 break;
             case 3:
                 this.EnemyClumpsDict.Clear();
                 List<Ship> list2 = new List<Ship>();
                 List<GameplayObject> nearby1 = UniverseScreen.ShipSpatialManager.GetNearby(this.Position);
                 for (int index1 = 0; index1 < nearby1.Count; ++index1)
                 {
                     Ship ship1 = nearby1[index1] as Ship;
                     if (ship1 != null && ship1.loyalty != this.Owner && (ship1.loyalty.isFaction || this.Owner.GetRelations()[ship1.loyalty].AtWar || this.Owner.isFaction) && (!list2.Contains(ship1) && (double)Vector2.Distance(ship1.Center, Task.AO) < (double)Task.AORadius && !this.EnemyClumpsDict.ContainsKey(ship1.Center)))
                     {
                         this.EnemyClumpsDict.Add(ship1.Center, new List<Ship>());
                         this.EnemyClumpsDict[ship1.Center].Add(ship1);
                         list2.Add(ship1);
                         List<GameplayObject> nearby2 = UniverseScreen.ShipSpatialManager.GetNearby(this.Position);
                         for (int index2 = 0; index2 < nearby2.Count; ++index2)
                         {
                             Ship ship2 = nearby2[index2] as Ship;
                             if (ship2 != null && ship2.loyalty != this.Owner && (ship2.loyalty == ship1.loyalty && (double)Vector2.Distance(ship1.Center, ship2.Center) < 10000.0) && !list2.Contains(ship2))
                                 this.EnemyClumpsDict[ship1.Center].Add(ship2);
                         }
                     }
                 }
                 if (this.EnemyClumpsDict.Count == 0)
                 {
                     if ((double)Vector2.Distance(this.findAveragePosition(), Task.AO) <= 10000.0)
                         break;
                     this.FormationWarpTo(Task.AO, 0.0f, new Vector2(0.0f, -1f));
                     break;
                 }
                 else
                 {
                     List<Vector2> list3 = new List<Vector2>();
                     foreach (KeyValuePair<Vector2, List<Ship>> keyValuePair in this.EnemyClumpsDict)
                         list3.Add(keyValuePair.Key);
                     IOrderedEnumerable<Vector2> orderedEnumerable2 = Enumerable.OrderBy<Vector2, float>((IEnumerable<Vector2>)list3, (Func<Vector2, float>)(clumpPos => Vector2.Distance(this.findAveragePosition(), clumpPos)));
                     List<Ship> list4 = new List<Ship>();
                     foreach (Ship toAttack in (IEnumerable<Ship>)Enumerable.OrderByDescending<Ship, int>((IEnumerable<Ship>)this.EnemyClumpsDict[Enumerable.First<Vector2>((IEnumerable<Vector2>)orderedEnumerable2)], (Func<Ship, int>)(ship => ship.Size)))
                     {
                         float num = 0.0f;
                         foreach (Ship ship in (IEnumerable<Ship>)Enumerable.OrderByDescending<Ship, int>((IEnumerable<Ship>)this.Ships, (Func<Ship, int>)(ship => ship.Size)))
                         {
                             if (!list4.Contains(ship) && ((double)num == 0.0 || (double)num < (double)toAttack.GetStrength()))
                             {
                                 ship.GetAI().OrderAttackSpecificTarget(toAttack);
                                 ship.GetAI().Intercepting = true;
                                 list4.Add(ship);
                                 num += ship.GetStrength();
                             }
                         }
                     }
                     List<Ship> list5 = new List<Ship>();
                     foreach (Ship ship in (List<Ship>)this.Ships)
                     {
                         if (!list4.Contains(ship))
                             list5.Add(ship);
                     }
                     foreach (Ship ship in list5)
                     {
                         ship.GetAI().OrderAttackSpecificTarget(list4[0].GetAI().Target as Ship);
                         ship.GetAI().Intercepting = true;
                     }
                     this.TaskStep = 4;
                     break;
                 }
             case 4:
                 float num1 = 0.0f;
                 float num2 = 0.0f;
                 float num3 = 0.0f;
                 float num4 = 0.0f;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     num1 += ship.Ordinance;
                     num2 += ship.OrdinanceMax;
                     foreach (Weapon weapon in ship.Weapons)
                     {
                         if (weapon.BombTroopDamage_Max <= 0)
                         {
                             if ((double)weapon.OrdinanceRequiredToFire > 0.0)
                                 num3 = weapon.DamageAmount / weapon.fireDelay;
                             if ((double)weapon.PowerRequiredToFire > 0.0)
                                 num4 = weapon.DamageAmount / weapon.fireDelay;
                         }
                     }
                 }
                 float num5 = num3 + num4;
                 if ((double)num3 >= 0.649999976158142 * (double)num5 && (double)num1 <= 0.100000001490116 * (double)num2)
                 {
                     this.TaskStep = 5;
                     break;
                 }
                 else
                 {
                     bool flag4 = false;
                     foreach (Ship ship in (List<Ship>)this.Ships)
                     {
                         if (!ship.InCombat)
                         {
                             flag4 = true;
                             break;
                         }
                     }
                     if (!flag4)
                         break;
                     this.TaskStep = 3;
                     break;
                 }
             case 5:
                 List<Planet> list6 = new List<Planet>();
                 foreach (Planet planet in this.Owner.GetPlanets())
                 {
                     if (planet.HasShipyard)
                         list6.Add(planet);
                 }
                 IOrderedEnumerable<Planet> orderedEnumerable3 = Enumerable.OrderBy<Planet, float>((IEnumerable<Planet>)list6, (Func<Planet, float>)(p => Vector2.Distance(this.Position, p.Position)));
                 if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable3) <= 0)
                     break;
                 this.Position = Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable3).Position;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                     ship.GetAI().OrderResupply(Enumerable.First<Planet>((IEnumerable<Planet>)orderedEnumerable3), true);
                 this.TaskStep = 6;
                 break;
             case 6:
                 float num6 = 0.0f;
                 float num7 = 0.0f;
                 foreach (Ship ship in (List<Ship>)this.Ships)
                 {
                     ship.GetAI().HasPriorityOrder = true;
                     num6 += ship.Ordinance;
                     num7 += ship.OrdinanceMax;
                 }
                 if ((double)num6 != (double)num7)
                     break;
                 this.TaskStep = 0;
                 break;
         }
     }
 }
 private void FightBrutalWar(KeyValuePair<Empire, Relationship> r)
 {
     List<Planet> InvasionTargets = new List<Planet>();
     foreach (Planet p in this.empire.GetPlanets())
     {
         foreach (Planet toCheck in p.system.PlanetList)
         {
             if (toCheck.Owner == null || toCheck.Owner == this.empire || !toCheck.Owner.isFaction && !this.empire.GetRelations()[toCheck.Owner].AtWar)
             {
                 continue;
             }
             InvasionTargets.Add(toCheck);
         }
     }
     if (InvasionTargets.Count > 0)
     {
         Planet target = InvasionTargets[0];
         bool OK = true;
         lock (GlobalStats.TaskLocker)
         {
             foreach (MilitaryTask task in this.TaskList)
             {
                 if (task.GetTargetPlanet() != target)
                 {
                     continue;
                 }
                 OK = false;
                 break;
             }
         }
         if (OK)
         {
             MilitaryTask InvadeTask = new MilitaryTask(target, this.empire);
             lock (GlobalStats.TaskLocker)
             {
                 this.TaskList.Add(InvadeTask);
             }
         }
     }
     List<Planet> PlanetsWeAreInvading = new List<Planet>();
     lock (GlobalStats.TaskLocker)
     {
         foreach (MilitaryTask task in this.TaskList)
         {
             if (task.type != MilitaryTask.TaskType.AssaultPlanet || task.GetTargetPlanet().Owner == null || task.GetTargetPlanet().Owner != r.Key)
             {
                 continue;
             }
             PlanetsWeAreInvading.Add(task.GetTargetPlanet());
         }
     }
     if (PlanetsWeAreInvading.Count < 3 && this.empire.GetPlanets().Count > 0)
     {
         Vector2 vector2 = this.FindAveragePosition(this.empire);
         this.FindAveragePosition(r.Key);
         IOrderedEnumerable<Planet> sortedList =
             from planet in r.Key.GetPlanets()
             orderby Vector2.Distance(vector2, planet.Position)
             select planet;
         foreach (Planet p in sortedList)
         {
             if (PlanetsWeAreInvading.Contains(p))
             {
                 continue;
             }
             if (PlanetsWeAreInvading.Count >= 3)
             {
                 break;
             }
             PlanetsWeAreInvading.Add(p);
             MilitaryTask invade = new MilitaryTask(p, this.empire);
             lock (GlobalStats.TaskLocker)
             {
                 this.TaskList.Add(invade);
             }
         }
     }
 }
        public void Reset()
        {
            this.Ships.thisLock.EnterWriteLock();
            foreach (Ship ship in (List<Ship>)this.Ships)
                ship.fleet = (Fleet)null;
            this.Ships.thisLock.ExitWriteLock();
            this.Ships.Clear();

            this.TaskStep = 0;
            this.Task = (MilitaryTask)null;
            this.GoalStack.Clear();
        }
        private void RequisitionAssaultForces()
        {
            List<Troop>.Enumerator enumerator;
            if (this.IsToughNut)
            {
                this.DoToughNutRequisition();
                return;
            }
            IOrderedEnumerable<Ship_Game.Gameplay.AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations
                //orderby ao.GetOffensiveForcePool().Sum(bombs => bombs.BombBays.Count) > 0 descending
                //orderby ao.GetOffensiveForcePool().Sum(strength => strength.GetStrength()) >= this.MinimumTaskForceStrength descending
                orderby Vector2.Distance(this.AO, ao.Position)
                select ao;
            //IOrderedEnumerable<Ship_Game.Gameplay.AO> sorted = this.empire.GetGSAI().AreasOfOperations
            //    .OrderByDescending(ao => ao.GetOffensiveForcePool().Sum(bombs => bombs.BombBays.Count) > 0)
            //    .ThenByDescending(ao => ao.GetOffensiveForcePool().Sum(strength => strength.GetStrength()) >= this.MinimumTaskForceStrength)
            //    .ThenBy(ao => Vector2.Distance(this.AO, ao.Position));
            if (sorted.Count<Ship_Game.Gameplay.AO>() == 0)
            {
                return;
            }
            Ship_Game.Gameplay.AO ClosestAO = sorted.First<Ship_Game.Gameplay.AO>();
            if (this.TargetPlanet.Owner == null || !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
            {
                this.EndTask();
                return;
            }
            if (this.empire.GetRelations()[this.TargetPlanet.Owner].Treaty_Peace)
            {
                this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar = false;
                this.EndTask();
                return;
            }
            float EnemyTroopStrength = 0f;
            int troopCount = 0;
            foreach (PlanetGridSquare pgs in this.TargetPlanet.TilesList)
            {
                if (troopCount > 25)
                    break;
                if (pgs.TroopsHere.Count <= 0)
                {
                    if (pgs.building == null || pgs.building.CombatStrength <= 0)
                    {
                        continue;
                    }
                    EnemyTroopStrength = EnemyTroopStrength + (float)(pgs.building.Strength + (float)(pgs.building.CombatStrength));
                    troopCount++;
                }
                else
                {
                    troopCount++;
                    EnemyTroopStrength = EnemyTroopStrength + (float)pgs.TroopsHere[0].Strength;
                    if (pgs.building == null || pgs.building.CombatStrength <= 0)
                    {
                        continue;
                    }
                    EnemyTroopStrength = EnemyTroopStrength + (float)(pgs.building.Strength + (float)(pgs.building.CombatStrength));
                }
            }

            if (EnemyTroopStrength < 80f)
            {
                EnemyTroopStrength = 80f;
            }
            EnemyTroopStrength *= (1.2f + (int)Ship.universeScreen.GameDifficulty * .1f);
            List<Ship> PotentialAssaultShips = new List<Ship>();
            List<Troop> PotentialTroops = new List<Troop>();
            List<Ship> PotentialBombers = new List<Ship>();
            foreach (Ship ship in this.empire.GetShips().OrderBy(troops => Vector2.Distance(this.AO, troops.Position)))
            {
                if ((ship.TroopList.Count <= 0 || ship.fleet != null) || (!ship.HasTroopBay && ship.Role != "troop" && !ship.hasTransporter))
                {
                    continue;
                }
                PotentialAssaultShips.Add(ship);
            }
            List<Planet> shipyards = new List<Planet>();
            foreach (Planet planet1 in ClosestAO.GetPlanets())
            {
                if (!planet1.HasShipyard)
                {
                    continue;
                }
                shipyards.Add(planet1);
            }
            IOrderedEnumerable<Planet> planets =
                from p in shipyards
                orderby Vector2.Distance(p.Position, this.TargetPlanet.Position)
                select p;
            if (planets.Count<Planet>() == 0)
            {
                return;
            }
            IOrderedEnumerable<Planet> sortedList =
                //from planet in ClosestAO.GetPlanets()
                from planet in empire.GetPlanets()
                //where planet.system.CombatInSystem ==false
                orderby empire.GetGSAI().DefensiveCoordinator.DefenseDict[planet.ParentSystem].ValueToUs *.1f
                orderby Vector2.Distance(planet.Position, planets.First<Planet>().Position)
                select planet;
            //        IOrderedEnumerable<SolarSystem> sortedSystems =
            //from system in systems
            //orderby this.DefenseDict[system].ValueToUs descending
            //orderby Vector2.Distance(system.Position, ship4.Center)
            //select system;

            //foreach(SolarSystem system in this.empire.GetOwnedSystems())
            //{

            //}
            foreach (Planet planet2 in sortedList)
            {
                foreach (Troop t in planet2.TroopsHere)
                {
                    if (t.GetOwner() != this.empire)
                    {
                        continue;
                    }
                    t.SetPlanet(planet2);
                    PotentialTroops.Add(t);
                }
            }
            float ourAvailableStrength = 0f;
            foreach (Ship ship in PotentialAssaultShips)
            {
                foreach (Troop t in ship.TroopList)
                {
                    ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
                }
            }
            bool GoodToGo = false;
            foreach (Troop t in PotentialTroops)
            {
                ourAvailableStrength = ourAvailableStrength + (float)t.Strength;
            }
            float MinimumEscortStrength = 0f;
            int count = 0;
            float OurPresentStrength = 0f;
            foreach (Ship ship in this.TargetPlanet.system.ShipList)
            {
                if (ship.loyalty == this.TargetPlanet.Owner)
                {
                    MinimumEscortStrength = MinimumEscortStrength + ship.GetStrength();
                    count++;
                }
                if (ship.loyalty != this.empire)
                {
                    continue;
                }
                OurPresentStrength = OurPresentStrength + ship.GetStrength();
            }
            MinimumEscortStrength *= (1.3f + (int)Ship.universeScreen.GameDifficulty * .1f);
            // I'm unsure on ball-park figures for ship strengths. Given it used to build up to 1500, sticking flat +300 on seems a good start
            //updated. Now it will use 1/10th of the current military strength escort strength needed is under 1000
            if (MinimumEscortStrength < 1000)
                MinimumEscortStrength = this.empire.currentMilitaryStrength * .10f;
            //if (MinimumEscortStrength + OurPresentStrength < this.empire.MilitaryScore *.1f) //+1500
            //{
            //    MinimumEscortStrength = this.empire.MilitaryScore * .15f - OurPresentStrength; //1500f - OurPresentStrength;
            //}
            //if (MinimumEscortStrength < this.empire.MilitaryScore * .15f)
            //{
            //    MinimumEscortStrength = this.empire.MilitaryScore * .15f;
            //}
            this.MinimumTaskForceStrength = MinimumEscortStrength;
            BatchRemovalCollection<Ship> elTaskForce = new BatchRemovalCollection<Ship>();
            float tfstrength = 0f;

            foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
            {
                if (ship.InCombat || ship.fleet != null || tfstrength >= MinimumEscortStrength
                    || ship.GetAI().State == AIState.Explore
                    || ship.GetStrength() <= 0f ||(ship.Role == "station" || ship.Role == "platform") )
                {
                    continue;
                }
                tfstrength = tfstrength + ship.GetStrength();
                elTaskForce.Add(ship);
            }
            if (!this.empire.isFaction
                && this.empire.data.DiplomaticPersonality.Name == "Aggressive"
                //|| empire.data.DiplomaticPersonality.Name == "Xenophobic"
                //|| empire.GetRelations().Where(war => war.Value.ActiveWar !=null).Count() <2
                )
            {
                if(!this.IsCoreFleetTask)
                foreach (KeyValuePair<SolarSystem, SystemCommander> entry in this.empire.GetGSAI().DefensiveCoordinator.DefenseDict
                    .OrderByDescending(system => system.Key.CombatInSystem)
                    .ThenByDescending(ship => (ship.Value.GetOurStrength() - ship.Value.IdealShipStrength) < 1000)
                    .ThenByDescending(system => Vector2.Distance(system.Key.Position, this.TargetPlanet.Position))

            )
                {
                    foreach (Ship ship in entry.Value.GetShipList())
                    {
                        if (ship.InCombat || ship.fleet != null || tfstrength >= MinimumEscortStrength || ship.GetStrength() <= 0f)
                        {
                            continue;
                        }
                        tfstrength = tfstrength + ship.GetStrength();
                        elTaskForce.Add(ship);
                    }

                }
            }

            //if (ourAvailableStrength > EnemyTroopStrength * 1.65f && tfstrength >= this.MinimumTaskForceStrength)
            if (this.TargetPlanet.GetGroundLandingSpots() >5 && tfstrength >= this.MinimumTaskForceStrength)
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                {
                    this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                }
                GoodToGo = true;
                Fleet newFleet = new Fleet()
                {
                    Owner = this.empire,
                    Name = "Invasion Fleet"
                };
                int i = 1;
                while (i < 10)
                {
                    if (this.empire.GetGSAI().UsedFleets.Contains(i))
                    {
                        i++;
                    }
                    else
                    {
                        float ForceStrength = 0f;
                        List<Ship>.Enumerator enumerator1 = PotentialAssaultShips.GetEnumerator();
                        try
                        {
                            do
                            {
                                if (!enumerator1.MoveNext())
                                {
                                    break;
                                }
                                Ship ship = enumerator1.Current;
                                newFleet.AddShip(ship);
                                foreach (Troop t in ship.TroopList)
                                {
                                    ForceStrength = ForceStrength + (float)t.Strength;
                                }
                                this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                            }
                            while (ForceStrength <= EnemyTroopStrength);//* 2f);
                        }
                        finally
                        {
                            ((IDisposable)enumerator1).Dispose();
                        }
                        List<Troop>.Enumerator enumerator2 = PotentialTroops.GetEnumerator();
                        try
                        {
                            do
                            {
                            Label1:
                                if (!enumerator2.MoveNext())
                                {
                                    break;
                                }
                                Troop t = enumerator2.Current;
                                if (t.GetPlanet() != null && t.GetPlanet().ParentSystem.combatTimer <= 0 && !t.GetPlanet().RecentCombat && t.GetPlanet().TroopsHere.Count > t.GetPlanet().developmentLevel)
                                {
                                    (new List<Troop>()).Add(t);
                                    if (t.GetOwner() != null)
                                    {
                                        newFleet.AddShip(t.Launch());
                                        ForceStrength = ForceStrength + (float)t.Strength;

                                    }
                                    else
                                    {
                                        goto Label1;
                                    }
                                }
                                else
                                {
                                    goto Label1;
                                }
                            }
                            while (ForceStrength <= EnemyTroopStrength || ForceStrength <50);//+ EnemyTroopStrength * 0.3f);
                        }
                        finally
                        {
                            ((IDisposable)enumerator2).Dispose();
                        }
                        this.empire.GetFleetsDict()[i] = newFleet;
                        this.empire.GetGSAI().UsedFleets.Add(i);
                        this.WhichFleet = i;
                        newFleet.Task = this;
                        foreach (Ship ship in elTaskForce)
                        {
                            newFleet.AddShip(ship);
                            ship.GetAI().OrderQueue.Clear();
                            ship.GetAI().State = AIState.AwaitingOrders;
                            ClosestAO.GetOffensiveForcePool().Remove(ship);
                            ClosestAO.GetWaitingShips().Remove(ship);
                            this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                        }
                        newFleet.AutoArrange();
                        break;
                    }
                }
                this.Step = 1;
            }
            else if (ourAvailableStrength >= EnemyTroopStrength && tfstrength >= this.MinimumTaskForceStrength)
            {
                foreach (Ship ship in ClosestAO.GetOffensiveForcePool())
                {
                    if (ship.BombBays.Count <= 0)
                    {
                        continue;
                    }
                    PotentialBombers.Add(ship);
                    if (elTaskForce.Contains(ship))
                    {
                        continue;
                    }
                    elTaskForce.Add(ship);
                }
                if (PotentialBombers.Count > 0)
                {
                    if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                    {
                        this.EndTask();
                        return;
                    }
                    if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                    {
                        this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                    }
                    GoodToGo = true;
                    Fleet newFleet = new Fleet()
                    {
                        Owner = this.empire,
                        Name = "Invasion Fleet"
                    };
                    int i = 1;
                    while (i < 10)
                    {
                        if (this.empire.GetGSAI().UsedFleets.Contains(i))
                        {
                            i++;
                        }
                        else
                        {
                            float ForceStrength = 0f;
                            List<Ship>.Enumerator enumerator3 = PotentialAssaultShips.GetEnumerator();
                            try
                            {
                                do
                                {
                                    if (!enumerator3.MoveNext())
                                    {
                                        break;
                                    }
                                    Ship ship = enumerator3.Current;
                                    newFleet.AddShip(ship);
                                    foreach (Troop t in ship.TroopList)
                                    {
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                    }
                                }
                                while (ForceStrength <= EnemyTroopStrength * 2f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator3).Dispose();
                            }
                            enumerator = PotentialTroops.GetEnumerator();
                            try
                            {
                                do
                                {
                                Label0:
                                    if (!enumerator.MoveNext())
                                    {
                                        break;
                                    }
                                    Troop t = enumerator.Current;
                                    if (t.GetPlanet() != null && t != null)
                                    {
                                        (new List<Troop>()).Add(t);
                                        Ship launched = t.Launch();
                                        ForceStrength = ForceStrength + (float)t.Strength;
                                        newFleet.AddShip(launched);
                                    }
                                    else
                                    {
                                        goto Label0;
                                    }
                                }
                                while (ForceStrength <= EnemyTroopStrength + EnemyTroopStrength * 0.3f);
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                            this.empire.GetFleetsDict()[i] = newFleet;
                            this.empire.GetGSAI().UsedFleets.Add(i);
                            this.WhichFleet = i;
                            newFleet.Task = this;
                            foreach (Ship ship in elTaskForce)
                            {
                                newFleet.AddShip(ship);
                                ship.GetAI().OrderQueue.Clear();
                                ship.GetAI().State = AIState.AwaitingOrders;
                                ClosestAO.GetOffensiveForcePool().Remove(ship);
                                ClosestAO.GetWaitingShips().Remove(ship);
                                this.empire.GetGSAI().DefensiveCoordinator.remove(ship);
                            }
                            newFleet.AutoArrange();
                            break;
                        }
                    }
                    this.Step = 1;
                }
            }
            else if (ourAvailableStrength > EnemyTroopStrength )
            {
                if (this.TargetPlanet.Owner == null || this.TargetPlanet.Owner != null && !this.empire.GetRelations().ContainsKey(this.TargetPlanet.Owner))
                {
                    this.EndTask();
                    return;
                }
                if (ClosestAO.GetCoreFleet().Task == null && ClosestAO.GetCoreFleet().GetStrength() > this.MinimumTaskForceStrength)
                {
                    MilitaryTask clearArea = new MilitaryTask(ClosestAO.GetCoreFleet().Owner)
                    {
                        AO = this.TargetPlanet.Position,
                        AORadius = 75000f,
                        type = MilitaryTask.TaskType.ClearAreaOfEnemies
                    };
                    ClosestAO.GetCoreFleet().Owner.GetGSAI().TasksToAdd.Add(clearArea);
                    clearArea.WhichFleet = ClosestAO.WhichFleet;
                    ClosestAO.GetCoreFleet().Task = clearArea;
                    clearArea.IsCoreFleetTask = true;
                    ClosestAO.GetCoreFleet().TaskStep = 1;
                    clearArea.Step = 1;
                    if (this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWar)
                    {
                        this.empire.GetGSAI().DeclareWarOn(this.TargetPlanet.Owner, this.empire.GetRelations()[this.TargetPlanet.Owner].PreparingForWarType);
                    }
                }
            }
            //else if (EnemyTroopStrength > 100f)
            else if (this.TargetPlanet.GetGroundLandingSpots()<10)
            {
                this.IsToughNut = true;
            }
            if (!GoodToGo)
            {
                this.NeededTroopStrength = (int)(EnemyTroopStrength  - ourAvailableStrength);
            }
        }