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 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();
            }
        }
        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();

                }
            }
        }