コード例 #1
0
 private void DoMarkedColonizeGoal()
 {
     switch (this.Step)
     {
         case 0:
             bool flag1 = false;
             foreach (Ship ship in (List<Ship>)this.empire.GetShips())
             {
                 if (ship.isColonyShip && !ship.isPlayerShip() && (ship.GetAI() != null && ship.GetAI().State != AIState.Colonize))
                 {
                     this.colonyShip = ship;
                     flag1 = true;
                 }
             }
             Planet planet1 = (Planet)null;
             if (!flag1)
             {
                 List<Planet> list = new List<Planet>();
                 foreach (Planet planet2 in this.empire.GetPlanets())
                 {
                     if (planet2.HasShipyard)
                         list.Add(planet2);
                 }
                 int num1 = 9999999;
                 foreach (Planet planet2 in list)
                 {
                     int num2 = 0;
                     foreach (QueueItem queueItem in (List<QueueItem>)planet2.ConstructionQueue)
                         num2 += (int)(((double)queueItem.Cost - (double)queueItem.productionTowards) / (double)planet2.NetProductionPerTurn);
                     if (num2 < num1)
                     {
                         num1 = num2;
                         planet1 = planet2;
                     }
                 }
                 if (planet1 == null)
                     break;
                 if (this.empire.isPlayer && ResourceManager.ShipsDict.ContainsKey(this.empire.data.CurrentAutoColony))
                 {
                     planet1.ConstructionQueue.Add(new QueueItem()
                     {
                         isShip = true,
                         QueueNumber = planet1.ConstructionQueue.Count,
                         sData = ResourceManager.ShipsDict[this.empire.data.CurrentAutoColony].GetShipData(),
                         Goal = this,
                         Cost = ResourceManager.ShipsDict[this.empire.data.CurrentAutoColony].GetCost(this.empire)
                     });
                     this.PlanetBuildingAt = planet1;
                     ++this.Step;
                     break;
                 }
                 else
                 {
                     QueueItem queueItem = new QueueItem();
                     queueItem.isShip = true;
                     queueItem.QueueNumber = planet1.ConstructionQueue.Count;
                     if (ResourceManager.ShipsDict.ContainsKey(this.empire.data.DefaultColonyShip))
                     {
                         queueItem.sData = ResourceManager.ShipsDict[this.empire.data.DefaultColonyShip].GetShipData();
                     }
                     else
                     {
                         queueItem.sData = ResourceManager.ShipsDict[ResourceManager.GetEmpireByName(this.empire.data.Traits.Name).DefaultColonyShip].GetShipData();
                         this.empire.data.DefaultColonyShip = ResourceManager.GetEmpireByName(this.empire.data.Traits.Name).DefaultColonyShip;
                     }
                     queueItem.Goal = this;
                     queueItem.NotifyOnEmpty = false;
                     queueItem.Cost = ResourceManager.ShipsDict[this.empire.data.DefaultColonyShip].GetCost(this.empire);
                     planet1.ConstructionQueue.Add(queueItem);
                     this.PlanetBuildingAt = planet1;
                     ++this.Step;
                     break;
                 }
             }
             else
             {
                 this.Step = 2;
                 this.DoMarkedColonizeGoal();
                 break;
             }
         case 1:
             bool flag2 = false;
             foreach (QueueItem queueItem in (List<QueueItem>)this.PlanetBuildingAt.ConstructionQueue)
             {
                 if (queueItem.isShip && ResourceManager.ShipsDict[queueItem.sData.Name].isColonyShip)
                     flag2 = true;
             }
             if (!flag2)
             {
                 this.PlanetBuildingAt = (Planet)null;
                 this.Step = 0;
             }
             if (this.markedPlanet.Owner == null)
                 break;
             foreach (KeyValuePair<Empire, Relationship> Them in this.empire.GetRelations())
                 this.empire.GetGSAI().CheckClaim(Them, this.markedPlanet);
             this.empire.GetGSAI().Goals.QueuePendingRemoval(this);
             break;
         case 2:
             if (this.markedPlanet.Owner != null)
             {
                 foreach (KeyValuePair<Empire, Relationship> Them in this.empire.GetRelations())
                     this.empire.GetGSAI().CheckClaim(Them, this.markedPlanet);
                 this.empire.GetGSAI().Goals.QueuePendingRemoval(this);
                 break;
             }
             else
             {
                 bool flag3;
                 if (this.colonyShip == null)
                 {
                     flag3 = false;
                     foreach (Ship ship in (List<Ship>)this.empire.GetShips())
                     {
                         if (ship.isColonyShip && !ship.isPlayerShip() && (ship.GetAI() != null && ship.GetAI().State != AIState.Colonize))
                         {
                             this.colonyShip = ship;
                             flag3 = true;
                         }
                     }
                 }
                 else
                     flag3 = true;
                 if (flag3)
                 {
                     this.colonyShip.DoColonize(this.markedPlanet, this);
                     this.Step = 3;
                     break;
                 }
                 else
                 {
                     this.Step = 0;
                     break;
                 }
             }
         case 3:
             if (this.colonyShip == null)
             {
                 this.Step = 0;
                 break;
             }
             else if (this.colonyShip != null && this.colonyShip.Active && this.colonyShip.GetAI().State != AIState.Colonize)
             {
                 this.Step = 0;
                 break;
             }
             else if (this.colonyShip != null && !this.colonyShip.Active && this.markedPlanet.Owner == null)
             {
                 this.Step = 0;
                 break;
             }
             else
             {
                 if (this.markedPlanet.Owner == null)
                     break;
                 foreach (KeyValuePair<Empire, Relationship> Them in this.empire.GetRelations())
                     this.empire.GetGSAI().CheckClaim(Them, this.markedPlanet);
                 this.empire.GetGSAI().Goals.QueuePendingRemoval(this);
                 this.colonyShip.GetAI().State = AIState.AwaitingOrders;
                 this.Step = 4;
                 break;
             }
     }
 }
コード例 #2
0
 public bool AssignBuildingToTile(Building b, QueueItem qi)
 {
     List<PlanetGridSquare> list = new List<PlanetGridSquare>();
     if (b.Name == "Biospheres")
         return false;
     foreach (PlanetGridSquare planetGridSquare in this.TilesList)
     {
         bool flag = true;
         foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
         {
             if (queueItem.pgs == planetGridSquare)
             {
                 flag = false;
                 break;
             }
         }
         if (flag && planetGridSquare.Habitable && planetGridSquare.building == null)
             list.Add(planetGridSquare);
     }
     if (list.Count > 0)
     {
         int index = (int)RandomMath.RandomBetween(0.0f, (float)list.Count);
         PlanetGridSquare planetGridSquare1 = list[index];
         foreach (PlanetGridSquare planetGridSquare2 in this.TilesList)
         {
             if (planetGridSquare2 == planetGridSquare1)
             {
                 planetGridSquare2.QItem = qi;
                 qi.pgs = planetGridSquare2;
                 return true;
             }
         }
     }
     else if (b.CanBuildAnywhere)
     {
         PlanetGridSquare planetGridSquare1 = this.TilesList[(int)RandomMath.RandomBetween(0.0f, (float)this.TilesList.Count)];
         foreach (PlanetGridSquare planetGridSquare2 in this.TilesList)
         {
             if (planetGridSquare2 == planetGridSquare1)
             {
                 planetGridSquare2.QItem = qi;
                 qi.pgs = planetGridSquare2;
                 return true;
             }
         }
     }
     return false;
 }
コード例 #3
0
 private void DoBuildConstructionShip()
 {
     switch (this.Step)
     {
         case 0:
             List<Planet> list = new List<Planet>();
             foreach (Planet planet in this.empire.GetPlanets())
             {
                 if (planet.HasShipyard)
                     list.Add(planet);
             }
             IOrderedEnumerable<Planet> orderedEnumerable = Enumerable.OrderByDescending<Planet, float>((IEnumerable<Planet>)list, (Func<Planet, float>)(planet => planet.ConstructionQueue.Count ));//Vector2.Distance(planet.Position, this.BuildPosition)));
             if (Enumerable.Count<Planet>((IEnumerable<Planet>)orderedEnumerable) <= 0)
                 break;
             this.PlanetBuildingAt = Enumerable.ElementAt<Planet>((IEnumerable<Planet>)orderedEnumerable, 0);
             QueueItem queueItem = new QueueItem();
             queueItem.isShip = true;
             queueItem.DisplayName = "Construction Ship";
             queueItem.QueueNumber = Enumerable.ElementAt<Planet>((IEnumerable<Planet>)orderedEnumerable, 0).ConstructionQueue.Count;
             queueItem.sData = ResourceManager.ShipsDict[EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty).data.CurrentConstructor].GetShipData();
             queueItem.Goal = this;
             queueItem.Cost = ResourceManager.ShipsDict[this.ToBuildUID].GetCost(this.empire);
             queueItem.NotifyOnEmpty = false;
             if (!string.IsNullOrEmpty(this.empire.data.CurrentConstructor) && ResourceManager.ShipsDict.ContainsKey(this.empire.data.CurrentConstructor))
             {
                 this.beingBuilt = ResourceManager.ShipsDict[this.empire.data.CurrentConstructor];
             }
             else
             {
                 this.beingBuilt = null;
                 string empiredefaultShip = this.empire.data.DefaultConstructor;
                 if (string.IsNullOrEmpty(empiredefaultShip))
                 {
                     empiredefaultShip = this.empire.data.DefaultSmallTransport;
                 }
                 ResourceManager.ShipsDict.TryGetValue(empiredefaultShip, out this.beingBuilt);
                 //if(this.beingBuilt == null)
                 //{
                 //    ResourceManager.ShipsDict.TryGetValue(ResourceManager.GetEmpireByName(this.empire.data.Traits.Name).DefaultSmallTransport, out this.beingBuilt);
                 //}
                 this.empire.data.DefaultConstructor = empiredefaultShip;
             }
             Enumerable.ElementAt<Planet>((IEnumerable<Planet>)orderedEnumerable, 0).ConstructionQueue.Add(queueItem);
             ++this.Step;
             break;
         case 4:
             this.empire.GetGSAI().Goals.QueuePendingRemoval(this);
             break;
     }
 }
コード例 #4
0
        public void AddBuildingToCQ(Building b)
        {
            int count = this.ConstructionQueue.Count;
            QueueItem qi = new QueueItem();
            qi.isBuilding = true;
            qi.Building = b;
            qi.Cost = ResourceManager.GetBuilding(b.Name).Cost;
            qi.productionTowards = 0.0f;
            qi.NotifyOnEmpty = false;
            Building terraformer =ResourceManager.GetBuilding("Terraformer");
            if (this.AssignBuildingToTile(b, qi))
                this.ConstructionQueue.Add(qi);

            else if (this.Owner.GetBDict()[terraformer.Name] && this.Fertility < 1.0 && this.WeCanAffordThis(terraformer, this.colonyType))
            {
                bool flag = true;
                foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                {
                    if (queueItem.isBuilding && queueItem.Building.Name == terraformer.Name)
                        flag = false;
                }
                foreach (Building building in this.BuildingList)
                {
                    if (building.Name == terraformer.Name)
                        flag = false;
                }
                if (!flag)
                    return;
                this.AddBuildingToCQ(terraformer);
            }
            else
            {
                if (!this.Owner.GetBDict()["Biospheres"])
                    return;
                this.TryBiosphereBuild(ResourceManager.GetBuilding("Biospheres"), qi);
            }
        }
コード例 #5
0
 public bool TryBiosphereBuild(Building b, QueueItem qi)
 {
     List<PlanetGridSquare> list = new List<PlanetGridSquare>();
     foreach (PlanetGridSquare planetGridSquare in this.TilesList)
     {
         if (!planetGridSquare.Habitable && planetGridSquare.building == null && (!planetGridSquare.Biosphere && planetGridSquare.QItem == null))
             list.Add(planetGridSquare);
     }
     if (b.Name == "Biospheres" && list.Count > 0)
     {
         int index = (int)RandomMath.RandomBetween(0.0f, (float)list.Count);
         PlanetGridSquare planetGridSquare1 = list[index];
         foreach (PlanetGridSquare planetGridSquare2 in this.TilesList)
         {
             if (planetGridSquare2 == planetGridSquare1)
             {
                 qi.Building = b;
                 qi.isBuilding = true;
                 qi.Cost = b.Cost;
                 qi.productionTowards = 0.0f;
                 planetGridSquare2.QItem = qi;
                 qi.pgs = planetGridSquare2;
                 qi.NotifyOnEmpty = false;
                 this.ConstructionQueue.Add(qi);
                 return true;
             }
         }
     }
     return false;
 }
コード例 #6
0
        public void DoGoverning()
        {
            float income = this.GrossMoneyPT - this.TotalMaintenanceCostsPerTurn;
            if (this.colonyType == Planet.ColonyType.Colony)
                return;
            this.GetBuildingsWeCanBuildHere();
            Building cheapestFlatfood =
                this.BuildingsCanBuild.Where(flatfood => flatfood.PlusFlatFoodAmount > 0).OrderByDescending(cost => cost.Cost).FirstOrDefault();
            if(this.Owner.data.Traits.Cybernetic>0)
            {
                cheapestFlatfood = this.BuildingsCanBuild.Where(flat => flat.PlusProdPerColonist > 0).OrderByDescending(cost => cost.Cost).FirstOrDefault();
            }
            Building cheapestFlatprod = this.BuildingsCanBuild.Where(flat => flat.PlusFlatProductionAmount > 0).OrderByDescending(cost => cost.Cost).FirstOrDefault();
            Building cheapestFlatResearch = this.BuildingsCanBuild.Where(flat => flat.PlusFlatResearchAmount > 0).OrderByDescending(cost => cost.Cost).FirstOrDefault();
            Building pro = cheapestFlatprod;
            Building food = cheapestFlatfood;
            Building res = cheapestFlatResearch;

            int buildingsinQueue = this.ConstructionQueue.Where(isbuilding => isbuilding.isBuilding).Count();
            bool needsBiospheres = this.ConstructionQueue.Where(isbuilding => isbuilding.isBuilding && isbuilding.Building.Name == "Biospheres").Count() != buildingsinQueue;
            bool StuffInQueueToBuild = this.ConstructionQueue.Where(building => building.isBuilding || (building.Cost - building.productionTowards > this.ProductionHere)).Count() > 0;
            bool ForgetReseachAndBuild =
             string.IsNullOrEmpty(this.Owner.ResearchTopic) || StuffInQueueToBuild || (this.developmentLevel < 3 && (this.ProductionHere + 1) / (this.MAX_STORAGE + 1) < .9f);
            if (this.Owner.data.Traits.Cybernetic < 0)
            #region cybernetic
            {

                this.FarmerPercentage = 0.0f;

                float surplus = this.GrossProductionPerTurn - this.consumption;
                surplus = surplus * (1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1));
                this.WorkerPercentage = this.CalculateCyberneticPercentForSurplus(surplus);
                if ((double)this.WorkerPercentage > 1.0)
                    this.WorkerPercentage = 1f;
                this.ResearcherPercentage = 1f - this.WorkerPercentage;
                if (this.ResearcherPercentage < 0f)
                    ResearcherPercentage = 0f;
                //if (this.ProductionHere > this.MAX_STORAGE * 0.25f && (double)this.GetNetProductionPerTurn() > 1.0)// &&
                //    this.ps = Planet.GoodState.EXPORT;
                //else
                //    this.ps = Planet.GoodState.IMPORT;
                float buildingCount = 0.0f;
                foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                {
                    if (queueItem.isBuilding)
                        ++buildingCount;
                    if (queueItem.isBuilding && queueItem.Building.Name == "Biospheres")
                        ++buildingCount;
                }
                bool flag1 = true;
                foreach (Building building in this.BuildingList)
                {
                    if (building.Name == "Outpost" || building.Name == "Capital City")
                        flag1 = false;
                }
                if (flag1)
                {
                    bool flag2 = false;
                    foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                    {
                        if (queueItem.isBuilding && queueItem.Building.Name == "Outpost")
                        {
                            flag2 = true;
                            break;
                        }
                    }
                    if (!flag2)
                        this.AddBuildingToCQ(ResourceManager.GetBuilding("Outpost"));
                }
                bool flag3 = false;
                foreach (Building building1 in this.BuildingsCanBuild)
                {
                    if ((double)building1.PlusFlatProductionAmount > 0.0
                        || (double)building1.PlusProdPerColonist > 0.0
                        || (building1.Name == "Space Port" || (double)building1.PlusProdPerRichness > 0.0) || building1.Name == "Outpost")
                    {
                        int num2 = 0;
                        foreach (Building building2 in this.BuildingList)
                        {
                            if (building2 == building1)
                                ++num2;
                        }
                        flag3 = num2 <= 9;
                        break;
                    }
                }
                bool flag4 = true;
                if (flag3)
                {
                    foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                    {
                        if (queueItem.isBuilding
                            && ((double)queueItem.Building.PlusFlatProductionAmount > 0.0
                            || (double)queueItem.Building.PlusProdPerColonist > 0.0
                            || (double)queueItem.Building.PlusProdPerRichness > 0.0))
                        {
                            flag4 = false;
                            break;
                        }
                    }
                }
                if (this.Owner != EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty)
                    && this.Shipyards.Where(ship => ship.Value.GetShipData().IsShipyard).Count() == 0
                    && this.Owner.ShipsWeCanBuild.Contains(this.Owner.data.DefaultShipyard) && (double)this.GrossMoneyPT > 5.0
                    && (double)this.NetProductionPerTurn > 6.0)
                {
                    bool hasShipyard = false;
                    foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                    {
                        if (queueItem.isShip && queueItem.sData.IsShipyard)
                        {
                            hasShipyard = true;
                            break;
                        }
                    }
                    if (!hasShipyard)
                        this.ConstructionQueue.Add(new QueueItem()
                        {
                            isShip = true,
                            sData = ResourceManager.ShipsDict[this.Owner.data.DefaultShipyard].GetShipData(),
                            Cost = ResourceManager.ShipsDict[this.Owner.data.DefaultShipyard].GetCost(this.Owner)
                        });
                }
                if ((double)buildingCount < 2.0 && flag4)
                {
                    this.GetBuildingsWeCanBuildHere();
                    Building b = (Building)null;
                    float num2 = 99999f;
                    foreach (Building building in this.BuildingsCanBuild)
                    {
                        if ((building.PlusTerraformPoints <= 0.0) //(building.Name == "Terraformer")
                            && (double)building.PlusFlatFoodAmount <= 0.0
                            && ((double)building.PlusFoodPerColonist <= 0.0 && !(building.Name == "Biospheres"))
                            && ((double)building.PlusFlatPopulation <= 0.0 || (double)this.Population / (double)this.MaxPopulation <= 0.25))
                        {
                            if ((double)building.PlusFlatProductionAmount > 0.0
                                || (double)building.PlusProdPerColonist > 0.0
                                || (double)building.PlusTaxPercentage > 0.0
                                || (double)building.PlusProdPerRichness > 0.0
                                || (double)building.CreditsPerColonist > 0.0
                                || (building.Name == "Space Port" || building.Name == "Outpost"))
                            {
                                if ((building.Cost + 1) / ((double)this.GetNetProductionPerTurn() + 1) < 150 || this.ProductionHere > building.Cost * .5) //(building.Name == "Space Port") &&
                                {
                                    float num3 = building.Cost;
                                    b = building;
                                    break;
                                }
                            }
                            else if ((double)building.Cost < (double)num2 && (!(building.Name == "Space Port") || this.BuildingList.Count >= 2) || ((building.Cost + 1) / ((double)this.GetNetProductionPerTurn() + 1) < 150 || this.ProductionHere > building.Cost * .5))
                            {
                                num2 = building.Cost;
                                b = building;
                            }
                        }
                    }
                    if (b != null && (this.GrossMoneyPT - this.TotalMaintenanceCostsPerTurn > 0.0 || (b.CreditsPerColonist > 0 || this.PlusTaxPercentage > 0)))//((double)this.Owner.EstimateIncomeAtTaxRate(0.4f) - (double)b.Maintenance > 0.0 ))
                    {
                        bool flag2 = true;
                        if (b.BuildOnlyOnce)
                        {
                            for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                            {
                                if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                {
                                    flag2 = false;
                                    break;
                                }
                            }
                        }
                        if (flag2)
                            this.AddBuildingToCQ(b);
                    }
                    else if ((double)buildingCount < 2.0 && this.Owner.GetBDict()["Biospheres"] && (double)this.MineralRichness >= .5f)
                    {
                        if (this.Owner == EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty))
                        {
                            if (this.Population / (this.MaxPopulation + (double)this.MaxPopBonus) > 0.949999988079071 && (this.Owner.EstimateIncomeAtTaxRate(this.Owner.data.TaxRate) - (double)ResourceManager.BuildingsDict["Biospheres"].Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes * 3))
                                this.TryBiosphereBuild(ResourceManager.BuildingsDict["Biospheres"], new QueueItem());
                        }
                        else if (this.Population / (this.MaxPopulation + this.MaxPopBonus) > 0.949999988079071 && ((double)this.Owner.EstimateIncomeAtTaxRate(0.5f) - (double)ResourceManager.BuildingsDict["Biospheres"].Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes * 3))
                            this.TryBiosphereBuild(ResourceManager.BuildingsDict["Biospheres"], new QueueItem());
                    }
                }
                for (int index = 0; index < this.ConstructionQueue.Count; ++index)
                {
                    QueueItem queueItem1 = this.ConstructionQueue[index];
                    if (index == 0 && queueItem1.isBuilding && this.ProductionHere > this.MAX_STORAGE * .5)
                    {
                        if (queueItem1.Building.Name == "Outpost"
                            || (double)queueItem1.Building.PlusFlatProductionAmount > 0.0
                            || (double)queueItem1.Building.PlusProdPerRichness > 0.0
                            || (double)queueItem1.Building.PlusProdPerColonist > 0.0
                            //|| (double)queueItem1.Building.PlusTaxPercentage > 0.0
                            //|| (double)queueItem1.Building.CreditsPerColonist > 0.0
                            )
                        {
                            this.ApplyAllStoredProduction(0);
                        }
                        break;
                    }
                    else if (queueItem1.isBuilding
                        && ((double)queueItem1.Building.PlusFlatProductionAmount > 0.0
                        || (double)queueItem1.Building.PlusProdPerColonist > 0.0
                        || (queueItem1.Building.Name == "Outpost"
                        || (double)queueItem1.Building.PlusProdPerRichness > 0.0
                        //|| queueItem1.Building.PlusFlatFoodAmount >0f
                        )))
                    {
                        LinkedList<QueueItem> linkedList = new LinkedList<QueueItem>();
                        foreach (QueueItem queueItem2 in (List<QueueItem>)this.ConstructionQueue)
                            linkedList.AddLast(queueItem2);
                        linkedList.Remove(queueItem1);
                        linkedList.AddFirst(queueItem1);
                        this.ConstructionQueue.Clear();
                        foreach (QueueItem queueItem2 in linkedList)
                            this.ConstructionQueue.Add(queueItem2);
                    }
                }
            }
            #endregion
            else
            {

                switch (this.colonyType)
                {
                    case Planet.ColonyType.Core:
                        #region MyRegion
                        {
                            #region Resource control
                            //Determine Food needs first
                            //if (this.DetermineIfSelfSufficient())
                            #region MyRegion
                            {
                                //this.fs = GoodState.EXPORT;
                                //Determine if excess food

                                float surplus = (this.NetFoodPerTurn * (string.IsNullOrEmpty(this.Owner.ResearchTopic) ? 1 : .5f)) * (1 - (this.FoodHere + 1) / (this.MAX_STORAGE + 1));
                                if(this.Owner.data.Traits.Cybernetic >0)
                                {
                                    surplus = this.GrossProductionPerTurn - this.consumption;
                                    surplus = surplus * ((string.IsNullOrEmpty(this.Owner.ResearchTopic) ? 1 : .5f)) * (1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1));
                                        //(1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1));
                                }
                                this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(surplus);
                                if ( FarmerPercentage == 1 && StuffInQueueToBuild)
                                    this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(0);
                                if (this.FarmerPercentage == 1 && StuffInQueueToBuild)
                                    this.FarmerPercentage = .9f;
                                this.WorkerPercentage =
                                (1f - this.FarmerPercentage) *
                                (ForgetReseachAndBuild ? 1 : (1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1)));

                                float Remainder = 1f - FarmerPercentage;
                                //Research is happening
                                this.WorkerPercentage = (Remainder * (string.IsNullOrEmpty(this.Owner.ResearchTopic) ? 1 : (1 - (this.ProductionHere ) / (this.MAX_STORAGE ))));
                                if (this.ProductionHere / this.MAX_STORAGE > .9 && !StuffInQueueToBuild)
                                    this.WorkerPercentage = 0;
                                this.ResearcherPercentage = Remainder - this.WorkerPercentage;
                                if (this.Owner.data.Traits.Cybernetic > 0)
                                {
                                    this.WorkerPercentage += this.FarmerPercentage;
                                    this.FarmerPercentage = 0;
                                }
                            }
                            #endregion
                            this.SetExportState(this.colonyType);
                            //if (this.NetProductionPerTurn > 3f || this.developmentLevel > 2)
                            //{
                            //    if (this.ProductionHere > this.MAX_STORAGE * 0.33f)
                            //        this.ps = Planet.GoodState.EXPORT;
                            //    else if (this.ConstructionQueue.Count == 0)
                            //        this.ps = Planet.GoodState.STORE;
                            //    else
                            //        this.ps = Planet.GoodState.IMPORT;
                            //}
                            ////Not enough production or development
                            //else if (MAX_STORAGE * .75f > this.ProductionHere)
                            //{
                            //    this.ps = Planet.GoodState.IMPORT;
                            //}
                            //else if (MAX_STORAGE == this.ProductionHere)
                            //{
                            //    this.ps = GoodState.EXPORT;
                            //}
                            //else
                            //    this.ps = GoodState.STORE;
                            if (this.Owner != EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty)
                                && this.Shipyards.Where(ship => ship.Value.GetShipData().IsShipyard).Count() == 0
                                && this.Owner.ShipsWeCanBuild.Contains(this.Owner.data.DefaultShipyard)

                                )
                            // && (double)this.Owner.MoneyLastTurn > 5.0 && (double)this.NetProductionPerTurn > 4.0)
                            {
                                bool hasShipyard = false;
                                foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                                {
                                    if (queueItem.isShip && queueItem.sData.IsShipyard)
                                    {
                                        hasShipyard = true;
                                        break;
                                    }
                                }
                                if (!hasShipyard && this.developmentLevel > 2)
                                    this.ConstructionQueue.Add(new QueueItem()
                                    {
                                        isShip = true,
                                        sData = ResourceManager.ShipsDict[this.Owner.data.DefaultShipyard].GetShipData(),
                                        Cost = ResourceManager.ShipsDict[this.Owner.data.DefaultShipyard].GetCost(this.Owner) * UniverseScreen.GamePaceStatic
                                    });
                            }
                            #endregion
                            byte num5 = 0;
                            bool flag5 = false;
                            foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                            {
                                if (queueItem.isBuilding && queueItem.Building.Name != "Biospheres")
                                    ++num5;
                                if (queueItem.isBuilding && queueItem.Building.Name == "Biospheres")
                                    ++num5;
                                if (queueItem.isBuilding && queueItem.Building.Name == "Biospheres")
                                    flag5 = true;
                            }
                            bool flag6 = true;
                            foreach (Building building in this.BuildingList)
                            {
                                if (building.Name == "Outpost" || building.Name == "Capital City")
                                    flag6 = false;
                                if (building.Name == "Terraformer")
                                    flag5 = true;
                            }
                            if (flag6)
                            {
                                bool flag1 = false;
                                foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                                {
                                    if (queueItem.isBuilding && queueItem.Building.Name == "Outpost")
                                    {
                                        flag1 = true;
                                        break;
                                    }
                                }
                                if (!flag1)
                                    this.AddBuildingToCQ(ResourceManager.GetBuilding("Outpost"));
                            }
                            if (num5 < 2)
                            {
                                this.GetBuildingsWeCanBuildHere();

                                foreach (PlanetGridSquare PGS in this.TilesList)
                                {
                                    bool qitemTest = PGS.QItem != null;
                                    if (PGS.building == cheapestFlatprod || qitemTest && PGS.QItem.Building == cheapestFlatprod)
                                        pro = null;
                                    if (PGS.building != cheapestFlatfood && !(qitemTest && PGS.QItem.Building == cheapestFlatfood))
                                        food = cheapestFlatfood;

                                    if (PGS.building != cheapestFlatResearch && !(qitemTest && PGS.QItem.Building == cheapestFlatResearch))
                                        res = cheapestFlatResearch;

                                }

                                Building buildthis = null;
                                buildthis = pro;
                                buildthis = pro ?? food ?? res;

                                if (buildthis != null)
                                {
                                    num5++;
                                    this.AddBuildingToCQ(buildthis);
                                }

                            }
                            if (num5 < 2)
                            {
                                float coreCost = 99999f;
                                this.GetBuildingsWeCanBuildHere();
                                Building b = (Building)null;
                                foreach (Building building in this.BuildingsCanBuild)
                                {
                                    if (!WeCanAffordThis(building, this.colonyType))
                                        continue;

                                    if (cheapestFlatfood == null && cheapestFlatprod == null &&
                                        (building.PlusFlatPopulation <= 0.0 || this.Population <= 1000.0)
                                        && (this.Owner.data.Traits.Cybernetic <=0 && building.MinusFertilityOnBuild <= 0.0 && !(building.Name == "Biospheres"))
                                        //&& (!(building.Name == "Terraformer") || !flag5 && this.Fertility < 1.0)
                                        && (building.PlusTerraformPoints < 0 || !flag5 && this.Fertility < 1.0)
                                        //&& (building.Name != "Deep Core Mine")
                                        && (building.PlusFlatPopulation <= 0.0
                                        || this.Population / this.MaxPopulation <= 0.25)
                                        ||(this.Owner.data.Traits.Cybernetic >=0 && building.PlusProdPerRichness >0)
                                        )
                                    {

                                        b = building;
                                        coreCost = b.Cost;
                                        break;
                                    }
                                    else if (building.Cost < coreCost)
                                    {
                                        b = building;
                                        coreCost = b.Cost;
                                    }
                                }

                                if (b != null && cheapestFlatfood == null && cheapestFlatprod == null &&
                                   (b.CreditsPerColonist > 0 || b.PlusTaxPercentage > 0
                                   || b.PlusFlatProductionAmount > 0 || b.PlusProdPerRichness > 0 || b.PlusProdPerColonist > 0
                                   || b.PlusFoodPerColonist > 0 || b.PlusFlatFoodAmount > 0
                                   || b.PlusFlatResearchAmount > 0 || b.PlusResearchPerColonist > 0
                                   || b.StorageAdded > 0
                                   ))//&& !b.AllowShipBuilding)))//  ((double)this.Owner.EstimateIncomeAtTaxRate(0.25f) - (double)b.Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes * 3)) //this.WeCanAffordThis(b,this.colonyType)) //
                                {
                                    bool flag1 = true;
                                    if (b.BuildOnlyOnce)
                                    {
                                        for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                        {
                                            if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                            {
                                                flag1 = false;
                                                break;
                                            }
                                        }
                                    }
                                    if (flag1)
                                        this.AddBuildingToCQ(b);
                                }
                                else if (b != null
                                    //&& ((double)b.PlusFlatProductionAmount > 0.0 || (double)b.PlusProdPerColonist > 0.0)
                                    // && WeCanAffordThis(b,this.colonyType)
                                    )
                                {
                                    bool flag1 = true;
                                    if (b.BuildOnlyOnce)
                                    {
                                        for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                        {
                                            if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                            {
                                                flag1 = false;
                                                break;
                                            }
                                        }
                                    }
                                    if (flag1)
                                        this.AddBuildingToCQ(b);
                                }
                                else if (this.Owner.GetBDict()["Biospheres"] && (double)this.MineralRichness >= 1.0 && (double)this.Fertility >= 1.0)
                                {
                                    if (this.Owner == EmpireManager.GetEmpireByName(Planet.universeScreen.PlayerLoyalty))
                                    {
                                        if ((double)this.Population / ((double)this.MaxPopulation + (double)this.MaxPopBonus) > 0.949999988079071 && ((double)this.Owner.EstimateIncomeAtTaxRate(this.Owner.data.TaxRate) - (double)ResourceManager.BuildingsDict["Biospheres"].Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes * 3))
                                            this.TryBiosphereBuild(ResourceManager.BuildingsDict["Biospheres"], new QueueItem());
                                    }
                                    else if ((double)this.Population / ((double)this.MaxPopulation + (double)this.MaxPopBonus) > 0.949999988079071 && ((double)this.Owner.EstimateIncomeAtTaxRate(0.5f) - (double)ResourceManager.BuildingsDict["Biospheres"].Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes * 3))
                                        this.TryBiosphereBuild(ResourceManager.BuildingsDict["Biospheres"], new QueueItem());
                                }
                            }

                            for (int index = 0; index < this.ConstructionQueue.Count; ++index)
                            {
                                QueueItem queueItem1 = this.ConstructionQueue[index];
                                if (index == 0 && queueItem1.isBuilding)
                                {
                                    if (queueItem1.Building.Name == "Outpost" ) //|| (double)queueItem1.Building.PlusFlatProductionAmount > 0.0 || (double)queueItem1.Building.PlusProdPerRichness > 0.0 || (double)queueItem1.Building.PlusProdPerColonist > 0.0)
                                    {
                                        this.ApplyAllStoredProduction(0);
                                    }
                                    break;
                                }
                                else if (queueItem1.isBuilding && ((double)queueItem1.Building.PlusFlatProductionAmount > 0.0 || (double)queueItem1.Building.PlusProdPerColonist > 0.0 || queueItem1.Building.Name == "Outpost"))
                                {
                                    LinkedList<QueueItem> linkedList = new LinkedList<QueueItem>();
                                    foreach (QueueItem queueItem2 in (List<QueueItem>)this.ConstructionQueue)
                                        linkedList.AddLast(queueItem2);
                                    linkedList.Remove(queueItem1);
                                    linkedList.AddFirst(queueItem1);
                                    this.ConstructionQueue.Clear();
                                    foreach (QueueItem queueItem2 in linkedList)
                                        this.ConstructionQueue.Add(queueItem2);
                                }
                            }

                            break;
                        }
                        #endregion
                    case Planet.ColonyType.Industrial:
                        #region MyRegion
                        //this.fs = Planet.GoodState.IMPORT;

                        this.FarmerPercentage = 0.0f;
                        this.WorkerPercentage = 1f;
                        this.ResearcherPercentage = 0.0f;

                        //? true : .75f;
                        //this.ps = (double)this.ProductionHere >= 20.0 ? Planet.GoodState.EXPORT : Planet.GoodState.IMPORT;
                        float IndySurplus = (this.NetFoodPerTurn) *//(string.IsNullOrEmpty(this.Owner.ResearchTopic) ? .5f : .25f)) *
                            (1 - (this.FoodHere + 1) / (this.MAX_STORAGE + 1));
                        if (this.Owner.data.Traits.Cybernetic > 0)
                        {
                            IndySurplus = this.GrossProductionPerTurn - this.consumption;
                            IndySurplus = IndySurplus * (1 - (this.FoodHere + 1) / (this.MAX_STORAGE + 1));
                            //(1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1));
                        }
                        //if ((double)this.FoodHere <= (double)this.consumption)
                        {

                            this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(IndySurplus);
                            this.FarmerPercentage *= (this.FoodHere / MAX_STORAGE) > .25 ? .5f : 1;
                            if ( FarmerPercentage == 1 && StuffInQueueToBuild)
                                this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(0);
                            this.WorkerPercentage =
                                (1f - this.FarmerPercentage)   //(string.IsNullOrEmpty(this.Owner.ResearchTopic) ? 1f :
                                * (ForgetReseachAndBuild ? 1 :
                             (1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1)));
                            if (this.ProductionHere / this.MAX_STORAGE >.75 && !StuffInQueueToBuild)
                                this.WorkerPercentage = 0;

                            this.ResearcherPercentage = 1 - this.FarmerPercentage - this.WorkerPercentage;// 0.0f;
                            if (this.Owner.data.Traits.Cybernetic > 0)
                            {
                                this.WorkerPercentage += this.FarmerPercentage;
                                this.FarmerPercentage = 0;
                            }
                        }
                        this.SetExportState(this.colonyType);

                        float num6 = 0.0f;
                        foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                        {
                            if (queueItem.isBuilding)
                                ++num6;
                            if (queueItem.isBuilding && queueItem.Building.Name == "Biospheres")
                                ++num6;
                        }
                        bool flag7 = true;
                        foreach (Building building in this.BuildingList)
                        {
                            if (building.Name == "Outpost" || building.Name == "Capital City")
                                flag7 = false;
                        }
                        if (flag7)
                        {
                            bool flag1 = false;
                            foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                            {
                                if (queueItem.isBuilding && queueItem.Building.Name == "Outpost")
                                {
                                    flag1 = true;
                                    break;
                                }
                            }
                            if (!flag1)
                                this.AddBuildingToCQ(ResourceManager.GetBuilding("Outpost"));
                        }

                        bool flag8 = false;
                        this.GetBuildingsWeCanBuildHere();
                        if (num6 < 2)
                        {

                            this.GetBuildingsWeCanBuildHere();

                            foreach (PlanetGridSquare PGS in this.TilesList)
                            {
                                bool qitemTest = PGS.QItem != null;
                                if (PGS.building == cheapestFlatprod || qitemTest && PGS.QItem.Building == cheapestFlatprod)
                                    pro = null;
                                if (PGS.building != cheapestFlatfood && !(qitemTest && PGS.QItem.Building == cheapestFlatfood))
                                    food = cheapestFlatfood;

                                if (PGS.building != cheapestFlatResearch && !(qitemTest && PGS.QItem.Building == cheapestFlatResearch))
                                    res = cheapestFlatResearch;

                            }
                            Building buildthis = null;
                            buildthis = pro;
                            buildthis = pro ?? food ?? res;

                            if (buildthis != null)
                            {
                                num6++;
                                this.AddBuildingToCQ(buildthis);
                            }

                        }
                        {

                            double num1 = 0;
                            foreach (Building building1 in this.BuildingsCanBuild)
                            {
                                if ((double)building1.PlusFlatProductionAmount > 0.0
                                    || (double)building1.PlusProdPerColonist > 0.0
                                    || (double)building1.PlusProdPerRichness > 0.0
                                    )
                                {

                                    foreach (Building building2 in this.BuildingList)
                                    {
                                        if (building2 == building1)
                                            ++num1;
                                    }
                                    flag8 = num1 <= 9;
                                    break;
                                }
                            }
                        }
                        bool flag9 = true;
                        if (flag8)
                        {
                            this.ConstructionQueue.thisLock.EnterReadLock();
                            foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                            {
                                if (queueItem.isBuilding
                                    && ((double)queueItem.Building.PlusFlatProductionAmount > 0.0
                                    || (double)queueItem.Building.PlusProdPerColonist > 0.0
                                    || (double)queueItem.Building.PlusProdPerRichness > 0.0)
                                    )
                                {
                                    flag9 = false;
                                    break;
                                }
                            }
                            this.ConstructionQueue.thisLock.ExitReadLock();
                        }
                        if (flag9 && (double)num6 < 2.0)
                        {
                            float indycost = 99999f;
                            Building b = (Building)null;
                            foreach (Building building in this.BuildingsCanBuild)//.OrderBy(cost=> cost.Cost))
                            {
                                if (!this.WeCanAffordThis(b, this.colonyType))
                                    continue;
                                if ((double)building.PlusFlatProductionAmount > 0.0
                                    || (double)building.PlusProdPerColonist > 0.0
                                    || ((double)building.PlusProdPerRichness > 0.0
                                    || building.StorageAdded > 0

                                    )
                                    )//this.WeCanAffordThis(b,this.colonyType) )//
                                {
                                    indycost = building.Cost;
                                    b = building;
                                    break;
                                }
                            }
                            if (b != null) //(this.GrossMoneyPT - this.TotalMaintenanceCostsPerTurn > 0.0 || (b.CreditsPerColonist > 0 || this.PlusTaxPercentage > 0))) // ((double)this.Owner.EstimateIncomeAtTaxRate(0.25f) - (double)b.Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes * 3)) //this.WeCanAffordThis(b, this.colonyType)) //
                            {
                                bool flag1 = true;
                                if (b.BuildOnlyOnce)
                                {
                                    for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                    {
                                        if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                        {
                                            flag1 = false;
                                            break;
                                        }
                                    }
                                }
                                if (flag1)
                                {
                                    this.AddBuildingToCQ(b);
                                    ++num6;
                                }
                            }
                            else if (b != null && ((double)b.PlusFlatProductionAmount > 0.0
                                || (double)b.PlusProdPerColonist > 0.0
                                || (double)b.PlusProdPerRichness > 0.0 && (double)this.MineralRichness > 1.5)) //this.WeCanAffordThis(b, this.colonyType))//
                            {
                                bool flag1 = true;
                                if (b.BuildOnlyOnce)
                                {
                                    for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                    {
                                        if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                        {
                                            flag1 = false;
                                            break;
                                        }
                                    }
                                }
                                if (flag1)
                                    this.AddBuildingToCQ(b);
                            }
                        }
                        if ((double)num6 < 2)
                        {
                            Building b = (Building)null;

                            float num1 = 99999f;
                            foreach (Building building in this.GetBuildingsWeCanBuildHere().OrderByDescending(industry => this.MaxPopulation < 4 ? industry.PlusFlatFoodAmount : industry.PlusFoodPerColonist).ThenBy(maintenance => maintenance.Maintenance))
                            {
                                if (this.WeCanAffordThis(building, this.colonyType) && (int)(building.Cost * .05f) < num1)   //
                                {
                                    b = building;
                                    num1 = (int)(building.Cost * .05f);

                                }

                            }
                            if (b != null)
                            {
                                bool flag1 = true;
                                if (b.BuildOnlyOnce)
                                {
                                    for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                    {
                                        if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                        {
                                            flag1 = false;
                                            break;
                                        }
                                    }
                                }
                                if (flag1)
                                    this.AddBuildingToCQ(b);
                            }
                        }
                        break;
                        #endregion
                    case Planet.ColonyType.Research:
                        #region MyRegion
                        //this.fs = Planet.GoodState.IMPORT;
                        //this.ps = Planet.GoodState.IMPORT;
                        this.FarmerPercentage = 0.0f;
                        this.WorkerPercentage = 0.0f;
                        this.ResearcherPercentage = 1f;
                        StuffInQueueToBuild =
                            this.ConstructionQueue.Where(building => building.isBuilding
                                && (building.Building.PlusFlatFoodAmount > 0
                                || building.Building.PlusFlatProductionAmount > 0
                                || building.Building.PlusFlatResearchAmount > 0
                                || building.Building.PlusResearchPerColonist > 0
                                || building.Building.Name == "Biospheres"
                                )).Count() > 0;  //(building.Cost > this.NetProductionPerTurn * 10)).Count() > 0;
                        ForgetReseachAndBuild =
                            string.IsNullOrEmpty(this.Owner.ResearchTopic) || StuffInQueueToBuild; //? 1 : .5f;
                        IndySurplus = 0;
                        this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(IndySurplus);
                        if (this.Owner.data.Traits.Cybernetic <= 0 && FarmerPercentage == 1 & StuffInQueueToBuild)
                            this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(0);
                        if (this.FarmerPercentage == 1 && StuffInQueueToBuild)
                            this.FarmerPercentage = .9f;
                        this.WorkerPercentage =
                        (1f - this.FarmerPercentage) *
                        (ForgetReseachAndBuild ? 1 : ((1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1)) * .25f));
                        if (this.ProductionHere / this.MAX_STORAGE > .9 && !StuffInQueueToBuild)
                            this.WorkerPercentage = 0;
                        this.ResearcherPercentage = 1f - this.FarmerPercentage - this.WorkerPercentage;
                        if (this.Owner.data.Traits.Cybernetic > 0)
                        {
                            this.WorkerPercentage += this.FarmerPercentage;
                            this.FarmerPercentage = 0;
                        }
                        this.SetExportState(this.colonyType);
                        //    if ((double)this.FoodHere <= (double)this.consumption)
                        //{
                        //    this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(0.0f);
                        //    this.ResearcherPercentage = 1f - this.FarmerPercentage;
                        //}
                        float num8 = 0.0f;
                        foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                        {
                            if (queueItem.isBuilding)
                                ++num8;
                            if (queueItem.isBuilding && queueItem.Building.Name == "Biospheres")
                                ++num8;
                        }
                        bool flag10 = true;
                        foreach (Building building in this.BuildingList)
                        {
                            if (building.Name == "Outpost" || building.Name == "Capital City")
                                flag10 = false;
                        }
                        if (flag10)
                        {
                            bool flag1 = false;
                            foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                            {
                                if (queueItem.isBuilding && queueItem.Building.Name == "Outpost")
                                {
                                    flag1 = true;
                                    break;
                                }
                            }
                            if (!flag1)
                                this.AddBuildingToCQ(ResourceManager.GetBuilding("Outpost"));
                        }
                        if (num8 < 2.0)
                        {
                            this.GetBuildingsWeCanBuildHere();

                            foreach (PlanetGridSquare PGS in this.TilesList)
                            {
                                bool qitemTest = PGS.QItem != null;
                                if (PGS.building == cheapestFlatprod || qitemTest && PGS.QItem.Building == cheapestFlatprod)
                                    pro = null;
                                if (PGS.building != cheapestFlatfood && !(qitemTest && PGS.QItem.Building == cheapestFlatfood))
                                    food = cheapestFlatfood;

                                if (PGS.building != cheapestFlatResearch && !(qitemTest && PGS.QItem.Building == cheapestFlatResearch))
                                    res = cheapestFlatResearch;

                            }
                            Building buildthis = null;
                            buildthis = pro;
                            buildthis = pro ?? food ?? res;

                            if (buildthis != null)
                            {
                                num8++;
                                this.AddBuildingToCQ(buildthis);
                            }
                        }
                        if (num8 < 2.0)
                        {
                            this.GetBuildingsWeCanBuildHere();
                            Building b = (Building)null;
                            float num1 = 99999f;
                            foreach (Building building in this.BuildingsCanBuild)
                            {
                                if (!WeCanAffordThis(building, this.colonyType))
                                    continue;
                                if (building.PlusFlatProductionAmount > 0.0 || building.Name == "Outpost") //this.WeCanAffordThis(building,this.colonyType)) //
                                {
                                    //float num2 = building.Cost;
                                    b = building;
                                    break;
                                }
                                else if (building.Cost < num1)
                                //&&
                                //( (double)building.PlusResearchPerColonist > 0.0
                                //|| (double)building.PlusFlatResearchAmount > 0.0
                                //|| (double)building.CreditsPerColonist > 0.0
                                //|| building.StorageAdded > 0
                                ////|| (building.PlusTaxPercentage > 0 && !building.AllowShipBuilding)))
                                //))
                                {
                                    num1 = building.Cost;
                                    b = building;
                                }
                            }
                            if (b != null) // (this.GrossMoneyPT - this.TotalMaintenanceCostsPerTurn > 0.0
                            //|| (b.CreditsPerColonist > 0 || this.PlusTaxPercentage > 0))) //((double)this.Owner.EstimateIncomeAtTaxRate(0.25f) - (double)b.Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes *3))
                            {
                                bool flag1 = true;
                                if (b.StorageAdded > 0 && !(this.ps == GoodState.EXPORT && this.fs == GoodState.EXPORT))
                                    flag1 = false;

                                if (b.BuildOnlyOnce)
                                {
                                    for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                    {
                                        if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                        {
                                            flag1 = false;
                                            break;
                                        }
                                    }
                                }
                                if (flag1)
                                    this.AddBuildingToCQ(b);
                            }
                        }
                        break;
                        #endregion
                    case Planet.ColonyType.Agricultural:
                        #region MyRegion
                        //this.fs = Planet.GoodState.EXPORT;
                        //this.ps = Planet.GoodState.IMPORT;
                        this.FarmerPercentage = 1f;
                        this.WorkerPercentage = 0.0f;
                        this.ResearcherPercentage = 0.0f;
                        if ((this.Owner.data.Traits.Cybernetic <= 0 ? this.FoodHere:this.ProductionHere) == this.MAX_STORAGE)
                        {
                            this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(0.0f);
                            float num1 = 1f - this.FarmerPercentage;
                            //Added by McShooterz: No research percentage if not researching
                            if (!string.IsNullOrEmpty(this.Owner.ResearchTopic))
                            {
                                this.WorkerPercentage = num1 / 2f;
                                this.ResearcherPercentage = num1 / 2f;
                            }
                            else
                            {
                                this.WorkerPercentage = num1;
                                this.ResearcherPercentage = 0.0f;
                            }
                        }
                        if ((double)this.ProductionHere / (double)this.MAX_STORAGE > 0.850000023841858)
                        {
                            float num1 = 1f - this.FarmerPercentage;
                            this.WorkerPercentage = 0.0f;
                            //Added by McShooterz: No research percentage if not researching
                            if (!string.IsNullOrEmpty(this.Owner.ResearchTopic))
                            {
                                this.ResearcherPercentage = num1;
                            }
                            else
                            {
                                this.FarmerPercentage = 1f;
                                this.ResearcherPercentage = 0.0f;
                            }
                        }
                        if (this.Owner.data.Traits.Cybernetic > 0)
                        {
                            this.WorkerPercentage += this.FarmerPercentage;
                            this.FarmerPercentage = 0;
                        }
                        this.SetExportState(this.colonyType);
                        StuffInQueueToBuild = this.ConstructionQueue.Where(building => building.isBuilding || (building.Cost > this.NetProductionPerTurn * 10)).Count() > 0;
                        ForgetReseachAndBuild =
                            string.IsNullOrEmpty(this.Owner.ResearchTopic) || StuffInQueueToBuild; //? 1 : .5f;
                        IndySurplus = (this.NetFoodPerTurn) *//(string.IsNullOrEmpty(this.Owner.ResearchTopic) ? .5f : .25f)) * * (ForgetReseachAndBuild * .1f)
            (1 - (this.FoodHere + 1) / (this.MAX_STORAGE + 1));
                        this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(IndySurplus);
                        if (FarmerPercentage == 1 & StuffInQueueToBuild)
                            this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(0);
                        if (this.FarmerPercentage == 1 && StuffInQueueToBuild)
                            this.FarmerPercentage = .9f;
                        this.WorkerPercentage =
                        (1f - this.FarmerPercentage) *
                        (ForgetReseachAndBuild ? 1 : (1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1)));
                        if (this.ProductionHere / this.MAX_STORAGE > .75 && !StuffInQueueToBuild)
                            this.WorkerPercentage = 0;

                        this.ResearcherPercentage = 1f - this.FarmerPercentage - this.WorkerPercentage;

                        float num9 = 0.0f;
                        bool flag11 = false;
                        foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                        {
                            if (queueItem.isBuilding)
                                ++num9;
                            if (queueItem.isBuilding && queueItem.Building.Name == "Biospheres")
                                ++num9;
                            if (queueItem.isBuilding && queueItem.Building.Name == "Terraformer")
                                flag11 = true;
                        }
                        bool flag12 = true;
                        foreach (Building building in this.BuildingList)
                        {
                            if (building.Name == "Outpost" || building.Name == "Capital City")
                                flag12 = false;
                            if (building.Name == "Terraformer" && this.Fertility >= 1.0)
                                flag11 = true;
                        }
                        if (flag12)
                        {
                            bool flag1 = false;
                            foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                            {
                                if (queueItem.isBuilding && queueItem.Building.Name == "Outpost")
                                {
                                    flag1 = true;
                                    break;
                                }
                            }
                            if (!flag1)
                                this.AddBuildingToCQ(ResourceManager.GetBuilding("Outpost"));
                        }
                        if ((double)num9 < 2.0)
                        {
                            this.GetBuildingsWeCanBuildHere();

                            foreach (PlanetGridSquare PGS in this.TilesList)
                            {
                                bool qitemTest = PGS.QItem != null;
                                if (PGS.building == cheapestFlatprod || qitemTest && PGS.QItem.Building == cheapestFlatprod)
                                    pro = null;
                                if (PGS.building != cheapestFlatfood && !(qitemTest && PGS.QItem.Building == cheapestFlatfood))
                                    food = cheapestFlatfood;

                                if (PGS.building != cheapestFlatResearch && !(qitemTest && PGS.QItem.Building == cheapestFlatResearch))
                                    res = cheapestFlatResearch;

                            }
                            Building buildthis = null;
                            buildthis = pro;
                            buildthis = pro ?? food ?? res;

                            if (buildthis != null)
                            {
                                num9++;
                                this.AddBuildingToCQ(buildthis);
                            }
                        }

                        if ((double)num9 < 2.0)
                        {
                            this.GetBuildingsWeCanBuildHere();
                            Building b = (Building)null;
                            float num1 = 99999f;
                            bool highPri = false;
                            foreach (Building building in this.BuildingsCanBuild.OrderBy(cost => cost.Cost))
                            {
                                if (!WeCanAffordThis(building, this.colonyType))
                                    continue;
                                if (building.Name == "Outpost") //this.WeCanAffordThis(building,this.colonyType)) //
                                {//(double)building.PlusFlatProductionAmount > 0.0 ||
                                    float num2 = building.Cost;
                                    b = building;
                                    break;
                                }
                                else if ((double)building.Cost < (double)num1
                                    && (
                                     (double)building.PlusFoodPerColonist > 0.0
                                    || (double)building.PlusFlatFoodAmount > 0.0
                                    || (building.PlusTerraformPoints > 0f && this.Fertility < 1)
                                    || building.StorageAdded > 0f
                                    ))
                                //||
                                //(double)building.PlusFlatResearchAmount > 0.0 || building.StorageAdded > 0 || (building.Name == "Outpost" || (double)building.CreditsPerColonist > 0.0))
                                //|| (building.StorageAdded > 0 || !flag11 && building.Name == "Terraformer"
                                //&& (double)this.Fertility < 1.0) || (double)building.PlusTaxPercentage > 0.0))
                                {
                                    highPri = true;
                                    num1 = building.Cost;
                                    b = building;
                                }
                                else if (!highPri && (double)building.Cost < (double)num1 && cheapestFlatfood == null && cheapestFlatprod == null && cheapestFlatResearch == null)
                                {
                                    num1 = building.Cost;
                                    b = building;
                                }
                            }
                            if (b != null)//&& (this.GrossMoneyPT - this.TotalMaintenanceCostsPerTurn > 0.0 || (b.CreditsPerColonist > 0 || this.PlusTaxPercentage > 0))) //((double)this.Owner.EstimateIncomeAtTaxRate(0.25f) - (double)b.Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes *3))
                            {
                                bool flag1 = true;
                                if (b.BuildOnlyOnce)
                                {
                                    for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                    {
                                        if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                        {
                                            flag1 = false;
                                            break;
                                        }
                                    }
                                }
                                if (flag1)
                                    this.AddBuildingToCQ(b);
                            }
                        }
                        break;
                        #endregion
                    case Planet.ColonyType.Military:
                        #region MyRegion
                        //this.fs = Planet.GoodState.IMPORT;
                        //if ((double)this.MAX_STORAGE - (double)this.FoodHere < 25.0)
                        //    this.fs = Planet.GoodState.EXPORT;
                        this.FarmerPercentage = 0.0f;
                        this.WorkerPercentage = 1f;
                        this.ResearcherPercentage = 0.0f;
                        if ((double)this.FoodHere <= (double)this.consumption)
                        {
                            this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(0.01f);
                            this.WorkerPercentage = 1f - this.FarmerPercentage;
                            this.ResearcherPercentage = 0.0f;
                        }
                        if (this.Owner.data.Traits.Cybernetic > 0)
                        {
                            this.WorkerPercentage += this.FarmerPercentage;
                            this.FarmerPercentage = 0;
                        }
                        this.SetExportState(this.colonyType);
                        //this.ps = (double)this.ProductionHere >= 20.0 ? Planet.GoodState.EXPORT : Planet.GoodState.IMPORT;
                        float buildingCount = 0.0f;
                        foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                        {
                            if (queueItem.isBuilding)
                                ++buildingCount;
                            if (queueItem.isBuilding && queueItem.Building.Name == "Biospheres")
                                ++buildingCount;
                        }
                        bool missingOutpost = true;
                        foreach (Building building in this.BuildingList)
                        {
                            if (building.Name == "Outpost" || building.Name == "Capital City")
                                missingOutpost = false;
                        }
                        if (missingOutpost)
                        {
                            bool hasOutpost = false;
                            foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                            {
                                if (queueItem.isBuilding && queueItem.Building.Name == "Outpost")
                                {
                                    hasOutpost = true;
                                    break;
                                }
                            }
                            if (!hasOutpost)
                                this.AddBuildingToCQ(ResourceManager.GetBuilding("Outpost"));
                        }
                        if (this.Owner != EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty)
                            && this.Shipyards.Where(ship => ship.Value.GetShipData().IsShipyard).Count() == 0
                            && this.Owner.ShipsWeCanBuild.Contains(this.Owner.data.DefaultShipyard) && (double)this.GrossMoneyPT > 3.0)
                        {
                            bool hasShipyard = false;
                            foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                            {
                                if (queueItem.isShip && queueItem.sData.IsShipyard)
                                {
                                    hasShipyard = true;
                                    break;
                                }
                            }
                            if (!hasShipyard)
                                this.ConstructionQueue.Add(new QueueItem()
                                {
                                    isShip = true,
                                    sData = ResourceManager.ShipsDict[this.Owner.data.DefaultShipyard].GetShipData(),
                                    Cost = ResourceManager.ShipsDict[this.Owner.data.DefaultShipyard].GetCost(this.Owner)
                                });
                        }
                        if ((double)buildingCount < 2.0)
                        {
                            this.GetBuildingsWeCanBuildHere();
                            Building b = (Building)null;
                            float num1 = 99999f;
                            foreach (Building building in this.BuildingsCanBuild)
                            {
                                if ((double)building.PlusFlatProductionAmount > 0.0 || (double)building.PlusFlatResearchAmount > 0.0 || ((double)building.PlusFlatFoodAmount > 0.0 || building.Name == "Space Port") || ((double)building.PlusProdPerColonist > 0.0 || building.Name == "Outpost" || ((double)building.CreditsPerColonist > 0.0 || building.CombatStrength > 0))) //this.WeCanAffordThis(building,this.colonyType)) //
                                {
                                    if (!(building.Name == "Space Port") || (double)this.GetNetProductionPerTurn() >= 2.0) //this.WeCanAffordThis(building,this.colonyType)) //
                                    {
                                        float num2 = building.Cost;
                                        b = building;
                                        break;
                                    }
                                }
                                else if ((double)building.Cost < (double)num1
                                    && ((double)building.PlusFlatProductionAmount > 0.0
                                    || (double)building.PlusFlatResearchAmount > 0.0
                                    || ((double)building.PlusFlatFoodAmount > 0.0 || building.Name == "Space Port")
                                    || ((double)building.PlusProdPerColonist > 0.0 || building.Name == "Outpost" || ((double)building.CreditsPerColonist > 0.0 || building.CombatStrength > 0))
                                    || ((building.PlusTaxPercentage > 0 && !building.AllowShipBuilding) || building.StorageAdded > 0))
                                    && (building.CombatStrength <= 0 && (!(building.Name == "Space Port" || building.AllowShipBuilding) || this.BuildingList.Count >= 2)))
                                {
                                    num1 = building.Cost;
                                    b = building;
                                }
                            }
                            if (b != null && (this.GrossMoneyPT - this.TotalMaintenanceCostsPerTurn > 0.0 || (b.CreditsPerColonist > 0 || (b.PlusTaxPercentage > 0 && !b.AllowShipBuilding)))) // ((double)this.Owner.EstimateIncomeAtTaxRate(0.25f) - (double)b.Maintenance > 0.0 || this.Owner.Money > this.Owner.GrossTaxes * 3)) //this.WeCanAffordThis(b,this.colonyType))  //
                            {
                                bool flag1 = true;
                                if (b.BuildOnlyOnce)
                                {
                                    for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                    {
                                        if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                        {
                                            flag1 = false;
                                            break;
                                        }
                                    }
                                }
                                if (flag1)
                                    this.AddBuildingToCQ(b);
                            }
                            else if (b != null && ((double)b.PlusFlatProductionAmount > 0.0 || (double)b.PlusProdPerColonist > 0.0))
                            {
                                bool flag1 = true;
                                if (b.BuildOnlyOnce)
                                {
                                    for (int index = 0; index < this.Owner.GetPlanets().Count; ++index)
                                    {
                                        if (this.Owner.GetPlanets()[index].BuildingInQueue(b.Name))
                                        {
                                            flag1 = false;
                                            break;
                                        }
                                    }
                                }
                                if (flag1)
                                    this.AddBuildingToCQ(b);
                            }
                        }
                        break;
                        #endregion

                    case Planet.ColonyType.TradeHub:
                        #region MyRegion
                        {

                            //this.fs = Planet.GoodState.IMPORT;

                            this.FarmerPercentage = 0.0f;
                            this.WorkerPercentage = 1f;
                            this.ResearcherPercentage = 0.0f;

                            //? true : .75f;
                            this.ps = (double)this.ProductionHere >= 20.0 ? Planet.GoodState.EXPORT : Planet.GoodState.IMPORT;
                            float IndySurplus2 = (this.NetFoodPerTurn) *//(string.IsNullOrEmpty(this.Owner.ResearchTopic) ? .5f : .25f)) *
                                (1 - (this.FoodHere + 1) / (this.MAX_STORAGE + 1));
                            if (this.Owner.data.Traits.Cybernetic > 0)
                            {
                                IndySurplus = this.GrossProductionPerTurn - this.consumption;
                                IndySurplus = IndySurplus * (1 - (this.FoodHere + 1) / (this.MAX_STORAGE + 1));
                                //(1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1));
                            }
                            //if ((double)this.FoodHere <= (double)this.consumption)
                            {

                                this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(IndySurplus2);
                                if (FarmerPercentage == 1 && StuffInQueueToBuild)
                                    this.FarmerPercentage = this.CalculateFarmerPercentForSurplus(0);
                                this.WorkerPercentage =
                                    (1f - this.FarmerPercentage)   //(string.IsNullOrEmpty(this.Owner.ResearchTopic) ? 1f :
                                    * (ForgetReseachAndBuild ? 1 :
                                 (1 - (this.ProductionHere + 1) / (this.MAX_STORAGE + 1)));
                                if (this.ProductionHere / this.MAX_STORAGE > .75 && !StuffInQueueToBuild)
                                    this.WorkerPercentage = 0;
                                this.ResearcherPercentage = 1 - this.FarmerPercentage - this.WorkerPercentage;// 0.0f;
                                if (this.Owner.data.Traits.Cybernetic > 0)
                                {
                                    this.WorkerPercentage += this.FarmerPercentage;
                                    this.FarmerPercentage = 0;
                                }
                                this.SetExportState(this.colonyType);

                            }
                            break;
                        }
                        #endregion
                }
            }

            if (this.ConstructionQueue.Count < 5 && !this.system.CombatInSystem) //  this.ProductionHere > this.MAX_STORAGE * .75f)
            #region Troops and platforms
            {
                //Added by McShooterz: Colony build troops
                #region MyRegion
                if (this.Owner.isPlayer && this.colonyType == ColonyType.Military)
                {
                    bool addTroop = false;
                    foreach (PlanetGridSquare planetGridSquare in this.TilesList)
                    {
                        if (planetGridSquare.TroopsHere.Count < planetGridSquare.number_allowed_troops)
                        {
                            addTroop = true;
                            break;
                        }
                    }
                    if (addTroop)
                    {
                        foreach (KeyValuePair<string, Troop> troop in ResourceManager.TroopsDict)
                        {
                            if (this.Owner.WeCanBuildTroop(troop.Key))
                            {

                                QueueItem qi = new QueueItem();
                                qi.isTroop = true;
                                qi.troop = troop.Value;
                                qi.Cost = troop.Value.GetCost();
                                qi.productionTowards = 0f;
                                qi.NotifyOnEmpty = false;
                                this.ConstructionQueue.Add(qi);
                                break;
                            }
                        }
                    }

                }
                #endregion
                //Added by McShooterz: build defense platforms

                if (this.HasShipyard && !this.system.CombatInSystem && (!this.Owner.isPlayer || this.colonyType == ColonyType.Military))
                {

                    SystemCommander SCom;
                    if (this.Owner.GetGSAI().DefensiveCoordinator.DefenseDict.TryGetValue(this.system, out SCom))
                    {
                        float DefBudget;
                        DefBudget = this.Owner.data.DefenseBudget * SCom.PercentageOfValue;

                        float maxProd = this.GetMaxProductionPotential();
                        //bool buildStation =false;
                        float platformUpkeep = ResourceManager.ShipRoles["platform"].Upkeep;
                        float stationUpkeep = ResourceManager.ShipRoles["station"].Upkeep;
                        string station = this.Owner.GetGSAI().GetStarBase();
                        //if (DefBudget >= 1 && !string.IsNullOrEmpty(station))
                        //    buildStation = true;
                        int PlatformCount = 0;
                        int stationCount = 0;
                        foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                        {
                            if (!queueItem.isShip)
                                continue;
                            if (queueItem.sData.Role == "platform")
                            {
                                if (DefBudget - platformUpkeep < -platformUpkeep * .5) //|| (buildStation && DefBudget > stationUpkeep))
                                {
                                    this.ConstructionQueue.QueuePendingRemoval(queueItem);
                                    continue;
                                }
                                DefBudget -= platformUpkeep;
                                PlatformCount++;
                            }
                            if (queueItem.sData.Role == "station")
                            {
                                if (DefBudget - stationUpkeep < -stationUpkeep)
                                {
                                    this.ConstructionQueue.QueuePendingRemoval(queueItem);
                                    continue;
                                }
                                DefBudget -= stationUpkeep;
                                stationCount++;
                            }
                        }
                        foreach (Ship platform in this.Shipyards.Values)
                        {
                            if (platform.BaseStrength <= 0)
                                continue;
                            if (platform.GetAI().State == AIState.Scrap)
                                continue;
                            if (platform.Role == "station")
                            {
                                stationUpkeep = platform.GetMaintCost();
                                if (DefBudget - stationUpkeep < -stationUpkeep)
                                {

                                    platform.GetAI().OrderScrapShip();
                                    continue;
                                }
                                DefBudget -= stationUpkeep;
                                stationCount++;
                            }
                            if (platform.Role == "platform")//|| (buildStation && DefBudget < 5))
                            {
                                platformUpkeep = platform.GetMaintCost();
                                if (DefBudget - platformUpkeep < -platformUpkeep)
                                {
                                    platform.GetAI().OrderScrapShip();

                                    continue;
                                }
                                DefBudget -= platformUpkeep;
                                PlatformCount++;
                            }

                        }
                        //this.Shipyards.Where(ship => ship.Value.Weapons.Count() > 0 && ship.Value.Role=="platform").Count();

                        if (DefBudget > stationUpkeep && maxProd > 10.0
            && stationCount < (int)(SCom.RankImportance * .5f) //(int)(SCom.PercentageOfValue * this.developmentLevel)
            && stationCount < GlobalStats.ShipCountLimit * GlobalStats.DefensePlatformLimit)
                        {
                            // string platform = this.Owner.GetGSAI().GetStarBase();
                            if (!string.IsNullOrEmpty(station))
                            {
                                Ship ship = ResourceManager.ShipsDict[station];
                                this.ConstructionQueue.Add(new QueueItem()
                                   {
                                       isShip = true,
                                       sData = ship.GetShipData(),
                                       Cost = ship.GetCost(this.Owner)
                                   });
                            }
                            DefBudget -= stationUpkeep;
                        }
                        if (DefBudget > platformUpkeep && maxProd > 1.0
                            && PlatformCount < SCom.RankImportance //(int)(SCom.PercentageOfValue * this.developmentLevel)
                            && PlatformCount < GlobalStats.ShipCountLimit * GlobalStats.DefensePlatformLimit)
                        {
                            string platform = this.Owner.GetGSAI().GetDefenceSatellite();
                            if (!string.IsNullOrEmpty(platform))
                            {
                                Ship ship = ResourceManager.ShipsDict[platform];
                                this.ConstructionQueue.Add(new QueueItem()
                                {
                                    isShip = true,
                                    sData = ship.GetShipData(),
                                    Cost = ship.GetCost(this.Owner)
                                });
                            }

                        }

                    }
                }

            }
            #endregion
            //if (this.Population > 3000.0 || this.Population / (this.MaxPopulation + this.MaxPopBonus) > 0.75)
            #region Scrap
            //if (this.colonyType!= ColonyType.TradeHub)
            {
                //List<Building> list = new List<Building>();
                //foreach (Building building in this.BuildingList)
                //{
                //    if ((double)building.PlusFlatPopulation > 0.0 && (double)building.Maintenance > 0.0 && building.Name != "Biospheres")
                //    //
                //        list.Add(building);
                //}
                //foreach (Building b in list)
                //    this.ScrapBuilding(b);

                List<Building> list1 = new List<Building>();
                if ((double)this.Fertility >= 1.0)
                {

                    foreach (Building building in this.BuildingList)
                    {
                        if (building.PlusTerraformPoints > 0.0 && (double)building.Maintenance > 0.0)
                            list1.Add(building);
                    }
                }

                //finances
                //if (this.Owner.Money*.5f < this.Owner.GrossTaxes*(1-this.Owner.data.TaxRate) && this.GrossMoneyPT - this.TotalMaintenanceCostsPerTurn < 0)
                {
                    this.ConstructionQueue.thisLock.EnterReadLock();
                    foreach (PlanetGridSquare PGS in this.TilesList)
                    {
                        bool qitemTest = PGS.QItem != null;
                        if ((qitemTest && PGS.QItem.Building.Name == "Biospheres") || (PGS.building != null && PGS.building.Name == "Biospheres"))
                            continue;
                        if ((PGS.building != null && PGS.building.PlusFlatProductionAmount > 0) || (PGS.building != null && PGS.building.PlusFlatProductionAmount > 0))
                            continue;
                        if ((PGS.building != null && PGS.building.PlusFlatFoodAmount > 0) || (PGS.building != null && PGS.building.PlusFlatFoodAmount > 0))
                            continue;
                        if ((PGS.building != null && PGS.building.PlusFlatResearchAmount > 0) || (PGS.building != null && PGS.building.PlusFlatResearchAmount > 0))
                            continue;
                        if (PGS.building != null && !qitemTest && PGS.building.Scrappable && !WeCanAffordThis(PGS.building, this.colonyType)) // queueItem.isBuilding && !WeCanAffordThis(queueItem.Building, this.colonyType))
                        {
                            this.ScrapBuilding(PGS.building);

                        }
                        if (qitemTest && !WeCanAffordThis(PGS.QItem.Building, this.colonyType))
                        {
                            this.ProductionHere += PGS.QItem.productionTowards;
                            this.ConstructionQueue.QueuePendingRemoval(PGS.QItem);
                            PGS.QItem = null;

                        }
                    }
                    //foreach (QueueItem queueItem in (List<QueueItem>)this.ConstructionQueue)
                    //{
                    //    if(queueItem.Building == cheapestFlatfood || queueItem.Building == cheapestFlatprod || queueItem.Building == cheapestFlatResearch)
                    //        continue;
                    //    if (queueItem.isBuilding &&  !WeCanAffordThis(queueItem.Building, this.colonyType))
                    //    {
                    //        this.ProductionHere += queueItem.productionTowards;
                    //        this.ConstructionQueue.QueuePendingRemoval(queueItem);
                    //    }
                    //}
                    this.ConstructionQueue.thisLock.ExitReadLock();
                    this.ConstructionQueue.ApplyPendingRemovals();
                    //foreach (Building building in this.BuildingList)
                    //{
                    //    if (building.Name != "Biospheres" && !WeCanAffordThis(building, this.colonyType))
                    //        //
                    //        list1.Add(building);
                    //}

                }

                //foreach (Building b in list1.OrderBy(maintenance=> maintenance.Maintenance))
                //{

                //    if (b == cheapestFlatprod || b == cheapestFlatfood || b == cheapestFlatResearch)
                //        continue;
                //    this.ScrapBuilding(b);
                //}
            #endregion
            }
        }
コード例 #7
0
 public int EstimatedTurnsTillComplete(QueueItem qItem)
 {
     int num = (int)Math.Ceiling((double)(int)((qItem.Cost - qItem.productionTowards) / this.NetProductionPerTurn));
     if (this.NetProductionPerTurn > 0.0)
         return num;
     else
         return 999;
 }
 private void DoRefitORIG(float elapsedTime, ArtificialIntelligence.ShipGoal goal)
 {
     QueueItem qi = new QueueItem()
     {
         isShip = true,
         productionTowards = 0f,
         sData = ResourceManager.ShipsDict[goal.VariableString].GetShipData()
     };
     if (qi.sData == null)
     {
         this.OrderQueue.Clear();
         this.State = AIState.AwaitingOrders;
     }
     int cost = (int)(ResourceManager.ShipsDict[goal.VariableString].GetCost(this.Owner.loyalty) - this.Owner.GetCost(this.Owner.loyalty));
     if (cost < 0)
     {
         cost = 0;
     }
     cost = cost + 10 * (int)UniverseScreen.GamePaceStatic;
     qi.Cost = (float)cost;
     qi.isRefit = true;
     this.OrbitTarget.ConstructionQueue.Add(qi);
     this.Owner.QueueTotalRemoval();
 }
        //added by gremlin refit while in fleet
        private void DoRefit(float elapsedTime, ArtificialIntelligence.ShipGoal goal)
        {
            QueueItem qi = new QueueItem()
            {
                isShip = true,
                productionTowards = 0f,
                sData = ResourceManager.ShipsDict[goal.VariableString].GetShipData()
            };

            if (qi.sData == null)
            {
                this.OrderQueue.Clear();
                this.State = AIState.AwaitingOrders;
            }
            int cost = (int)(ResourceManager.ShipsDict[goal.VariableString].GetCost(this.Owner.loyalty) - this.Owner.GetCost(this.Owner.loyalty));
            if (cost < 0)
            {
                cost = 0;
            }
            cost = cost + 10 * (int)UniverseScreen.GamePaceStatic;
            qi.Cost = (float)cost;
            qi.isRefit = true;
            //Added by McShooterz: refit keeps name and level
            if(this.Owner.VanityName != this.Owner.Name)
                qi.RefitName = this.Owner.VanityName;
            qi.sData.Level = (byte)this.Owner.Level;
            if (this.Owner.fleet != null)
            {

                FleetDataNode node = this.Owner.fleet.DataNodes.Where(thenode => thenode.GetShip() == this.Owner).First();

                Goal refitgoal = new Goal
                {
                    beingBuilt = ResourceManager.ShipsDict[goal.VariableString],

                    GoalName = "FleetRequisition",

                };
                refitgoal.Step = 1;
                refitgoal.beingBuilt.fleet = this.Owner.fleet;
                refitgoal.beingBuilt.RelativeFleetOffset = node.FleetOffset;
                node.GoalGUID = refitgoal.guid;
                refitgoal.SetFleet(this.Owner.fleet);
                refitgoal.SetPlanetWhereBuilding(this.OrbitTarget);

                this.Owner.loyalty.GetGSAI().Goals.Add(refitgoal);

                qi.Goal = refitgoal;
            }
            this.OrbitTarget.ConstructionQueue.Add(qi);
            this.Owner.QueueTotalRemoval();
        }
コード例 #10
0
 private void AddTroopToQ()
 {
     int count = this.p.ConstructionQueue.Count;
     QueueItem qItem = new QueueItem()
     {
         isTroop = true,
         troop = ResourceManager.TroopsDict["Terran/Space Marine"],
         Cost = ResourceManager.TroopsDict["Terran/Space Marine"].GetCost(),
         productionTowards = 0f
     };
     this.p.ConstructionQueue.Add(qItem);
 }
コード例 #11
0
        public override void HandleInput(InputState input)
        {
            this.pFacilities.HandleInputNoReset(this);
            if (HelperFunctions.CheckIntersection(this.RightColony.r, input.CursorPosition))
            {
                ToolTip.CreateTooltip(Localizer.Token(2279), this.ScreenManager);
            }
            if (HelperFunctions.CheckIntersection(this.LeftColony.r, input.CursorPosition))
            {
                ToolTip.CreateTooltip(Localizer.Token(2280), this.ScreenManager);
            }
            if ((input.Right || this.RightColony.HandleInput(input)) && (PlanetScreen.screen.Debug || this.p.Owner == EmpireManager.GetEmpireByName(PlanetScreen.screen.PlayerLoyalty)))
            {

                try
                {
                    this.p.Owner.GetPlanets().thisLock.EnterReadLock();
                    int thisindex = this.p.Owner.GetPlanets().IndexOf(this.p);
                    thisindex = (thisindex >= this.p.Owner.GetPlanets().Count - 1 ? 0 : thisindex + 1);
                    if (this.p.Owner.GetPlanets()[thisindex] != this.p)
                    {
                        this.p = this.p.Owner.GetPlanets()[thisindex];
                        PlanetScreen.screen.workersPanel = new ColonyScreen(this.p, this.ScreenManager, this.eui);
                    }
                    this.p.Owner.GetPlanets().thisLock.ExitReadLock();
                }
                catch
                {

                    System.Diagnostics.Debug.WriteLine("Colony Screen Handle Inpu. Likely null reference.");
                }
                if (input.CurrentMouseState.RightButton != ButtonState.Released || this.previousMouse.RightButton != ButtonState.Released)
                {
                    this.eui.screen.ShipsInCombat.Active = true;
                    this.eui.screen.PlanetsInCombat.Active = true;
                }
                return;
            }
            if ((input.Left || this.LeftColony.HandleInput(input)) && (PlanetScreen.screen.Debug || this.p.Owner == EmpireManager.GetEmpireByName(PlanetScreen.screen.PlayerLoyalty)))
            {
                int thisindex = this.p.Owner.GetPlanets().IndexOf(this.p);
                thisindex = (thisindex <= 0 ? this.p.Owner.GetPlanets().Count - 1 : thisindex - 1);
                if (this.p.Owner.GetPlanets()[thisindex] != this.p)
                {
                    this.p = this.p.Owner.GetPlanets()[thisindex];
                    PlanetScreen.screen.workersPanel = new ColonyScreen(this.p, this.ScreenManager, this.eui);
                }
                if (input.CurrentMouseState.RightButton != ButtonState.Released || this.previousMouse.RightButton != ButtonState.Released)
                {
                    this.eui.screen.ShipsInCombat.Active = true;
                    this.eui.screen.PlanetsInCombat.Active = true;
                }
                return;
            }
            this.p.UpdateIncomes();
            this.HandleDetailInfo(input);
            this.currentMouse = Mouse.GetState();
            Vector2 MousePos = new Vector2((float)this.currentMouse.X, (float)this.currentMouse.Y);
            this.buildSL.HandleInput(input);
            this.buildSL.Update();
            this.build.HandleInput(this);
            if (this.p.Owner != EmpireManager.GetEmpireByName(PlanetScreen.screen.PlayerLoyalty))
            {
                this.HandleDetailInfo(input);
                if (input.CurrentMouseState.RightButton != ButtonState.Released || this.previousMouse.RightButton != ButtonState.Released)
                {
                    this.eui.screen.ShipsInCombat.Active = true;
                    this.eui.screen.PlanetsInCombat.Active = true;
                }
                return;
            }
            if (!HelperFunctions.CheckIntersection(this.launchTroops.Rect, input.CursorPosition))
            {
                this.launchTroops.State = UIButton.PressState.Normal;
            }
            else
            {
                this.launchTroops.State = UIButton.PressState.Hover;
                if (input.InGameSelect)
                {
                    bool play = false;
                    foreach (PlanetGridSquare pgs in this.p.TilesList)
                    {
                        if (pgs.TroopsHere.Count <= 0 || pgs.TroopsHere[0].GetOwner() != EmpireManager.GetEmpireByName(PlanetScreen.screen.PlayerLoyalty))
                        {
                            continue;
                        }

                        play = true;

                        ResourceManager.CreateTroopShipAtPoint((this.p.Owner.data.DefaultTroopShip != null) ? this.p.Owner.data.DefaultTroopShip : this.p.Owner.data.DefaultSmallTransport, this.p.Owner, this.p.Position, pgs.TroopsHere[0]);
                        this.p.TroopsHere.Remove(pgs.TroopsHere[0]);
                        pgs.TroopsHere[0].SetPlanet(null);
                        pgs.TroopsHere.Clear();
                        this.ClickedTroop = true;
                        this.detailInfo = null;
                    }
                    if (play)
                    {

                        AudioManager.PlayCue("sd_troop_takeoff");
                    }
                }
            }
            //fbedard: Click button to send troops
            if (!HelperFunctions.CheckIntersection(this.SendTroops.Rect, input.CursorPosition))
            {
                this.SendTroops.State = UIButton.PressState.Normal;
            }
            else
            {
                this.SendTroops.State = UIButton.PressState.Hover;
                if (input.InGameSelect)
                {
                    this.eui.empire.GetShips().thisLock.EnterReadLock();
                    List<Ship> troopShips = new List<Ship>(this.eui.empire.GetShips()
                        .Where(troop => troop.TroopList.Count > 0
                            && troop.GetAI().State == AIState.AwaitingOrders
                            && troop.fleet == null && !troop.InCombat).OrderBy(distance => Vector2.Distance(distance.Center, this.p.Position)));
                    this.eui.empire.GetShips().thisLock.ExitReadLock();
                    this.eui.empire.GetPlanets().thisLock.EnterReadLock();
                    List<Planet> planetTroops = new List<Planet>(this.eui.empire.GetPlanets()
                        .Where(troops => troops.TroopsHere.Count > 1).OrderBy(distance => Vector2.Distance(distance.Position, this.p.Position))
                        .Where(Name => Name.Name != this.p.Name));
                    this.eui.empire.GetPlanets().thisLock.ExitReadLock();
                    if (troopShips.Count > 0)
                    {
                        AudioManager.PlayCue("echo_affirm");
                        troopShips.First().GetAI().OrderRebase(this.p,true);
                    }
                    else
                        if (planetTroops.Count > 0)
                        {
                            {
                                planetTroops.First().TroopsHere.thisLock.EnterWriteLock();
                                Ship troop = planetTroops.First().TroopsHere.First().Launch();
                                if (troop != null)
                                {
                                    AudioManager.PlayCue("echo_affirm");
                                    troop.GetAI().OrderRebase(this.p,true);
                                }
                                planetTroops.First().TroopsHere.thisLock.ExitWriteLock();
                            }
                        }
                        else
                        {
                            AudioManager.PlayCue("blip_click");
                        }
                }
            }
            if (!HelperFunctions.CheckIntersection(this.edit_name_button, MousePos))
            {
                this.editHoverState = 0;
            }
            else
            {
                this.editHoverState = 1;
                if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                {
                    this.PlanetName.HandlingInput = true;
                }
            }
            if (!this.PlanetName.HandlingInput)
            {
                GlobalStats.TakingInput = false;
                bool empty = true;
                string text = this.PlanetName.Text;
                int num = 0;
                while (num < text.Length)
                {
                    if (text[num] == ' ')
                    {
                        num++;
                    }
                    else
                    {
                        empty = false;
                        break;
                    }
                }
                if (empty)
                {
                    int ringnum = 1;
                    foreach (SolarSystem.Ring ring in this.p.system.RingList)
                    {
                        if (ring.planet == this.p)
                        {
                            this.PlanetName.Text = string.Concat(this.p.system.Name, " ", NumberToRomanConvertor.NumberToRoman(ringnum));
                        }
                        ringnum++;
                    }
                }
            }
            else
            {
                GlobalStats.TakingInput = true;
                this.PlanetName.HandleTextInput(ref this.PlanetName.Text, input);
            }
            this.GovernorDropdown.HandleInput(input);
            if (this.GovernorDropdown.Options[this.GovernorDropdown.ActiveIndex].@value != (int)this.p.colonyType)
            {
                this.p.colonyType = (Planet.ColonyType)this.GovernorDropdown.Options[this.GovernorDropdown.ActiveIndex].@value;
                if (this.p.colonyType != Planet.ColonyType.Colony)
                {
                    this.p.FoodLocked = true;
                    this.p.ProdLocked = true;
                    this.p.ResLocked = true;
                    this.p.GovernorOn = true;
                }
                else
                {
                    this.p.GovernorOn = false;
                    this.p.FoodLocked = false;
                    this.p.ProdLocked = false;
                    this.p.ResLocked = false;
                }
            }
            this.HandleSlider();
            if (this.p.HasShipyard && this.build.Tabs.Count > 1 && this.build.Tabs[1].Selected)
            {
                if (HelperFunctions.CheckIntersection(this.playerDesignsToggle.r, input.CursorPosition))
                {
                    ToolTip.CreateTooltip(Localizer.Token(2225), this.ScreenManager);
                }
                if (this.playerDesignsToggle.HandleInput(input))
                {
                    AudioManager.PlayCue("sd_ui_accept_alt3");
                    GlobalStats.ShowAllDesigns = !GlobalStats.ShowAllDesigns;
                    if (GlobalStats.ShowAllDesigns)
                    {
                        this.playerDesignsToggle.Active = true;
                    }
                    else
                    {
                        this.playerDesignsToggle.Active = false;
                    }
                    this.Reset = true;
                }
            }
            if (this.p.colonyType != Planet.ColonyType.Colony)
            {
                this.FoodLock.Locked = true;
                this.ProdLock.Locked = true;
                this.ResLock.Locked = true;
            }
            else
            {
                if (!HelperFunctions.CheckIntersection(this.FoodLock.LockRect, MousePos) || this.p.Owner == null || this.p.Owner.data.Traits.Cybernetic != 0)
                {
                    this.FoodLock.Hover = false;
                }
                else
                {
                    if (this.FoodLock.Locked)
                    {
                        this.FoodLock.Hover = false;
                        if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                        {
                            this.p.FoodLocked = false;
                            this.FoodLock.Locked = false;
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                        }
                    }
                    else
                    {
                        this.FoodLock.Hover = true;
                        if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                        {
                            this.p.FoodLocked = true;
                            this.FoodLock.Locked = true;
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                        }
                    }
                    ToolTip.CreateTooltip(69, this.ScreenManager);
                }
                if (!HelperFunctions.CheckIntersection(this.ProdLock.LockRect, MousePos))
                {
                    this.ProdLock.Hover = false;
                }
                else
                {
                    if (this.ProdLock.Locked)
                    {
                        this.ProdLock.Hover = false;
                        if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                        {
                            this.p.ProdLocked = false;
                            this.ProdLock.Locked = false;
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                        }
                    }
                    else
                    {
                        this.ProdLock.Hover = true;
                        if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                        {
                            this.p.ProdLocked = true;
                            this.ProdLock.Locked = true;
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                        }
                    }
                    ToolTip.CreateTooltip(69, this.ScreenManager);
                }
                if (!HelperFunctions.CheckIntersection(this.ResLock.LockRect, MousePos))
                {
                    this.ResLock.Hover = false;
                }
                else
                {
                    if (this.ResLock.Locked)
                    {
                        this.ResLock.Hover = false;
                        if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                        {
                            this.p.ResLocked = false;
                            this.ResLock.Locked = false;
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                        }
                    }
                    else
                    {
                        this.ResLock.Hover = true;
                        if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                        {
                            this.p.ResLocked = true;
                            this.ResLock.Locked = true;
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                        }
                    }
                    ToolTip.CreateTooltip(69, this.ScreenManager);
                }
            }
            this.selector = null;
            this.ClickedTroop = false;
            foreach (PlanetGridSquare pgs in this.p.TilesList)
            {
                if (!HelperFunctions.CheckIntersection(pgs.ClickRect, MousePos))
                {
                    pgs.highlighted = false;
                }
                else
                {
                    if (!pgs.highlighted)
                    {
                        AudioManager.PlayCue("sd_ui_mouseover");
                    }
                    pgs.highlighted = true;
                }
                if (pgs.TroopsHere.Count <= 0 || !HelperFunctions.CheckIntersection(pgs.TroopClickRect, MousePos))
                {
                    continue;
                }
                this.detailInfo = pgs.TroopsHere[0];
                if (input.RightMouseClick && pgs.TroopsHere[0].GetOwner() == EmpireManager.GetEmpireByName(PlanetScreen.screen.PlayerLoyalty))
                {
                    AudioManager.PlayCue("sd_troop_takeoff");
                    ResourceManager.CreateTroopShipAtPoint((this.p.Owner.data.DefaultTroopShip != null) ? this.p.Owner.data.DefaultTroopShip : this.p.Owner.data.DefaultSmallTransport, this.p.Owner, this.p.Position, pgs.TroopsHere[0]);
                    this.p.TroopsHere.Remove(pgs.TroopsHere[0]);
                    pgs.TroopsHere[0].SetPlanet(null);
                    pgs.TroopsHere.Clear();
                    this.ClickedTroop = true;
                    this.detailInfo = null;
                    rmouse = true;
                }
                return;
            }
            if (!this.ClickedTroop)
            {
                foreach (PlanetGridSquare pgs in this.p.TilesList)
                {
                    if (HelperFunctions.CheckIntersection(pgs.ClickRect, input.CursorPosition))
                    {
                        this.detailInfo = pgs;
                        Rectangle bRect = new Rectangle(pgs.ClickRect.X + pgs.ClickRect.Width / 2 - 32, pgs.ClickRect.Y + pgs.ClickRect.Height / 2 - 32, 64, 64);
                        if (pgs.building != null && pgs.building.Scrappable && HelperFunctions.CheckIntersection(bRect, input.CursorPosition) && input.RightMouseClick)
                        {
                            this.toScrap = pgs.building;
                            string message = string.Concat("Do you wish to scrap ", Localizer.Token(pgs.building.NameTranslationIndex), "? Half of the building's construction cost will be recovered to your storage.");
                            MessageBoxScreen messageBox = new MessageBoxScreen(message);
                            messageBox.Accepted += new EventHandler<EventArgs>(this.ScrapAccepted);
                            this.ScreenManager.AddScreen(messageBox);
                            this.ClickedTroop = true;
                            rmouse = true;
                            return;
                        }
                    }
                    if (pgs.TroopsHere.Count <= 0 || !HelperFunctions.CheckIntersection(pgs.TroopClickRect, input.CursorPosition))
                    {
                        continue;
                    }
                    this.detailInfo = pgs.TroopsHere;
                }
            }
            if (!GlobalStats.HardcoreRuleset)
            {
                if (HelperFunctions.CheckIntersection(this.foodDropDown.r, MousePos) && this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                {
                    this.foodDropDown.Toggle();
                    Planet planet = this.p;
                    planet.fs = (Planet.GoodState)((int)planet.fs + (int)Planet.GoodState.IMPORT);
                    if (this.p.fs > Planet.GoodState.EXPORT)
                    {
                        this.p.fs = Planet.GoodState.STORE;
                    }
                    AudioManager.PlayCue("sd_ui_accept_alt3");
                }
                if (HelperFunctions.CheckIntersection(this.prodDropDown.r, MousePos) && this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                {
                    this.prodDropDown.Toggle();
                    AudioManager.PlayCue("sd_ui_accept_alt3");
                    Planet planet1 = this.p;
                    planet1.ps = (Planet.GoodState)((int)planet1.ps + (int)Planet.GoodState.IMPORT);
                    if (this.p.ps > Planet.GoodState.EXPORT)
                    {
                        this.p.ps = Planet.GoodState.STORE;
                    }
                }
            }
            else
            {
                foreach (ThreeStateButton b in this.ResourceButtons)
                {
                    b.HandleInput(input, this.ScreenManager);
                }
            }
            for (int i = this.QSL.indexAtTop; i < this.QSL.Copied.Count && i < this.QSL.indexAtTop + this.QSL.entriesToDisplay; i++)
            {
                try
                {
                    ScrollList.Entry e = this.QSL.Copied[i];
                    if (!HelperFunctions.CheckIntersection(e.clickRect, MousePos))
                    {
                        e.clickRectHover = 0;
                    }
                    else
                    {
                        this.selector = new Selector(this.ScreenManager, e.clickRect);
                        if (e.clickRectHover == 0)
                        {
                            AudioManager.PlayCue("sd_ui_mouseover");
                        }
                        e.clickRectHover = 1;
                    }
                    if (HelperFunctions.CheckIntersection(e.up, MousePos))
                    {
                        ToolTip.CreateTooltip(63, PlanetScreen.screen.ScreenManager);
                        if (!input.CurrentKeyboardState.IsKeyDown(Keys.RightControl) && !input.CurrentKeyboardState.IsKeyDown(Keys.LeftControl) || this.currentMouse.LeftButton != ButtonState.Pressed || this.previousMouse.LeftButton != ButtonState.Released)
                        {
                            if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released && i > 0)
                            {
                                object tmp = this.p.ConstructionQueue[i - 1];
                                this.p.ConstructionQueue[i - 1] = this.p.ConstructionQueue[i];
                                this.p.ConstructionQueue[i] = tmp as QueueItem;
                                AudioManager.PlayCue("sd_ui_accept_alt3");
                            }
                        }
                        else if (i > 0)
                        {
                            LinkedList<QueueItem> copied = new LinkedList<QueueItem>();
                            foreach (QueueItem qi in this.p.ConstructionQueue)
                            {
                                copied.AddLast(qi);
                            }
                            copied.Remove(this.p.ConstructionQueue[i]);
                            copied.AddFirst(this.p.ConstructionQueue[i]);
                            this.p.ConstructionQueue.Clear();
                            foreach (QueueItem qi in copied)
                            {
                                this.p.ConstructionQueue.Add(qi);
                            }
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                            break;
                        }
                    }
                    if (HelperFunctions.CheckIntersection(e.down, MousePos))
                    {
                        ToolTip.CreateTooltip(64, PlanetScreen.screen.ScreenManager);
                        if (!input.CurrentKeyboardState.IsKeyDown(Keys.RightControl) && !input.CurrentKeyboardState.IsKeyDown(Keys.LeftControl) || this.currentMouse.LeftButton != ButtonState.Pressed || this.previousMouse.LeftButton != ButtonState.Released)
                        {
                            if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released && i + 1 < this.QSL.Copied.Count)
                            {
                                object tmp = this.p.ConstructionQueue[i + 1];
                                this.p.ConstructionQueue[i + 1] = this.p.ConstructionQueue[i];
                                this.p.ConstructionQueue[i] = tmp as QueueItem;
                                AudioManager.PlayCue("sd_ui_accept_alt3");
                            }
                        }
                        else if (i + 1 < this.QSL.Copied.Count)
                        {
                            LinkedList<QueueItem> copied = new LinkedList<QueueItem>();
                            foreach (QueueItem qi in this.p.ConstructionQueue)
                            {
                                copied.AddLast(qi);
                            }
                            copied.Remove(this.p.ConstructionQueue[i]);
                            copied.AddLast(this.p.ConstructionQueue[i]);
                            this.p.ConstructionQueue.Clear();
                            foreach (QueueItem qi in copied)
                            {
                                this.p.ConstructionQueue.Add(qi);
                            }
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                            break;
                        }
                    }
                    if (HelperFunctions.CheckIntersection(e.apply, MousePos) && !this.p.RecentCombat && this.p.Crippled_Turns <= 0)
                    {
                        if (!input.CurrentKeyboardState.IsKeyDown(Keys.RightControl) && !input.CurrentKeyboardState.IsKeyDown(Keys.LeftControl) || this.currentMouse.LeftButton != ButtonState.Pressed || this.previousMouse.LeftButton != ButtonState.Released)
                        {
                            if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                            {

                                if (this.p.ApplyStoredProduction(i))
                                {
                                    AudioManager.PlayCue("sd_ui_accept_alt3");
                                }
                                else
                                {
                                    AudioManager.PlayCue("UI_Misc20");
                                }
                            }
                        }
                        //else if (PlanetScreen.screen.Debug)
                        //{
                        //    this.p.ApplyProductiontoQueue(this.p.ConstructionQueue[i].Cost - this.p.ConstructionQueue[i].productionTowards, i);
                        //}
                        else if (this.p.ProductionHere == 0f)
                        {
                            AudioManager.PlayCue("UI_Misc20");
                        }
                        else
                        {
                            this.p.ApplyAllStoredProduction(i);
                            AudioManager.PlayCue("sd_ui_accept_alt3");
                        }
                    }
                    if (HelperFunctions.CheckIntersection(e.cancel, MousePos) && this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                    {
                        Planet productionHere2 = this.p;
                        productionHere2.ProductionHere = productionHere2.ProductionHere + (e.item as QueueItem).productionTowards;
                        if (this.p.ProductionHere > this.p.MAX_STORAGE)
                        {
                            this.p.ProductionHere = this.p.MAX_STORAGE;
                        }
                        QueueItem item = (e.item as QueueItem);
                        if (item.pgs != null)
                        {
                            (e.item as QueueItem).pgs.QItem = null;
                        }
                        if(item.Goal !=null)
                        {
                            if(item.Goal.GoalName=="BuildConstructionShip")
                            {
                                p.Owner.GetGSAI().Goals.Remove(item.Goal);

                            }
                            if(item.Goal.GetFleet() !=null)
                                p.Owner.GetGSAI().Goals.Remove(item.Goal);

                        }
                        this.p.ConstructionQueue.Remove(e.item as QueueItem);
                        AudioManager.PlayCue("sd_ui_accept_alt3");
                    }
                }
                catch
                {
                }
            }
            this.QSL.HandleInput(input, this.p);
            if (this.ActiveBuildingEntry != null)
            {
                foreach (PlanetGridSquare pgs in this.p.TilesList)
                {
                    if (!HelperFunctions.CheckIntersection(pgs.ClickRect, MousePos) || this.currentMouse.LeftButton != ButtonState.Released || this.previousMouse.LeftButton != ButtonState.Pressed)
                    {
                        continue;
                    }
                    if (pgs.Habitable && pgs.building == null && pgs.QItem == null && (this.ActiveBuildingEntry.item as Building).Name != "Biospheres")
                    {
                        QueueItem qi = new QueueItem();
                        //{
                        qi.isBuilding = true;
                        qi.Building = this.ActiveBuildingEntry.item as Building;
                        qi.Cost = ResourceManager.BuildingsDict[qi.Building.Name].Cost * UniverseScreen.GamePaceStatic;
                        qi.productionTowards = 0f;
                        qi.pgs = pgs;
                        //};
                        pgs.QItem = qi;
                        this.p.ConstructionQueue.Add(qi);
                        this.ActiveBuildingEntry = null;
                        break;
                    }
                    else if (pgs.Habitable || pgs.Biosphere || pgs.QItem != null || !(this.ActiveBuildingEntry.item as Building).CanBuildAnywhere)
                    {
                        AudioManager.PlayCue("UI_Misc20");
                        this.ActiveBuildingEntry = null;
                        break;
                    }
                    else
                    {
                        QueueItem qi = new QueueItem();
                        //{
                        qi.isBuilding = true;
                        qi.Building = this.ActiveBuildingEntry.item as Building;
                        qi.Cost = ResourceManager.BuildingsDict[qi.Building.Name].Cost * UniverseScreen.GamePaceStatic;
                        qi.productionTowards = 0f;
                        qi.pgs = pgs;
                        //};
                        pgs.QItem = qi;
                        this.p.ConstructionQueue.Add(qi);
                        this.ActiveBuildingEntry = null;
                        break;
                    }
                }
                if (this.ActiveBuildingEntry != null)
                {
                    foreach (QueueItem qi in this.p.ConstructionQueue)
                    {
                        if (!qi.isBuilding || !(qi.Building.Name == (this.ActiveBuildingEntry.item as Building).Name) || !(this.ActiveBuildingEntry.item as Building).Unique)
                        {
                            continue;
                        }
                        this.ActiveBuildingEntry = null;
                        break;
                    }
                }
                if (this.currentMouse.RightButton == ButtonState.Pressed && this.previousMouse.RightButton == ButtonState.Released)
                {
                    this.ClickedTroop = true;
                    this.ActiveBuildingEntry = null;
                }
                if (this.currentMouse.LeftButton == ButtonState.Released && this.previousMouse.LeftButton == ButtonState.Pressed)
                {
                    this.ClickedTroop = true;
                    this.ActiveBuildingEntry = null;
                }
            }
            for (int i = this.buildSL.indexAtTop; i < this.buildSL.Copied.Count && i < this.buildSL.indexAtTop + this.buildSL.entriesToDisplay; i++)
            {
                ScrollList.Entry e = this.buildSL.Copied[i];
                if (e.item is ModuleHeader)
                {
                    (e.item as ModuleHeader).HandleInput(input, e);
                }
                else if (!HelperFunctions.CheckIntersection(e.clickRect, MousePos))
                {
                    e.clickRectHover = 0;
                }
                else
                {
                    this.selector = new Selector(this.ScreenManager, e.clickRect);
                    if (e.clickRectHover == 0)
                    {
                        AudioManager.PlayCue("sd_ui_mouseover");
                    }
                    e.clickRectHover = 1;
                    if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Pressed && e.item is Building && this.ActiveBuildingEntry == null)
                    {
                        this.ActiveBuildingEntry = e;
                    }
                    if (this.currentMouse.LeftButton == ButtonState.Released && this.previousMouse.LeftButton == ButtonState.Pressed)
                    {
                        if (this.ClickTimer >= this.TimerDelay)
                        {
                            this.ClickTimer = 0f;
                        }
                        else
                        {
                            Rectangle rectangle = e.addRect;
                            if (!HelperFunctions.CheckIntersection(e.addRect, input.CursorPosition))
                            {
                                QueueItem qi = new QueueItem();
                                if (e.item is Ship)
                                {
                                    qi.isShip = true;
                                    qi.sData = (e.item as Ship).GetShipData();
                                    qi.Cost = (e.item as Ship).GetCost(this.p.Owner);
                                    qi.productionTowards = 0f;
                                    this.p.ConstructionQueue.Add(qi);
                                    AudioManager.PlayCue("sd_ui_mouseover");
                                }
                                else if (e.item is Troop)
                                {
                                    qi.isTroop = true;
                                    qi.troop = e.item as Troop;
                                    qi.Cost = (e.item as Troop).GetCost();
                                    qi.productionTowards = 0f;
                                    this.p.ConstructionQueue.Add(qi);
                                    AudioManager.PlayCue("sd_ui_mouseover");
                                }
                                else if (e.item is Building)
                                {
                                    this.p.AddBuildingToCQ(ResourceManager.GetBuilding((e.item as Building).Name));
                                    AudioManager.PlayCue("sd_ui_mouseover");
                                }
                            }
                        }
                    }
                }
                Rectangle rectangle1 = e.addRect;
                if (!HelperFunctions.CheckIntersection(e.addRect, MousePos))
                {
                    e.PlusHover = 0;
                }
                else
                {
                    e.PlusHover = 1;
                    ToolTip.CreateTooltip(51, this.ScreenManager);
                    if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                    {
                        QueueItem qi = new QueueItem();
                        if (e.item is Building)
                        {
                            this.p.AddBuildingToCQ(ResourceManager.GetBuilding((e.item as Building).Name));
                        }
                        else if (e.item is Ship)
                        {
                            qi.isShip = true;
                            qi.sData = (e.item as Ship).GetShipData();
                            qi.Cost = (e.item as Ship).GetCost(this.p.Owner);
                            qi.productionTowards = 0f;
                            this.p.ConstructionQueue.Add(qi);
                        }
                        else if (e.item is Troop)
                        {
                            qi.isTroop = true;
                            qi.troop = e.item as Troop;
                            qi.Cost = (e.item as Troop).GetCost();
                            qi.productionTowards = 0f;
                            this.p.ConstructionQueue.Add(qi);
                        }
                    }
                }
                Rectangle rectangle2 = e.editRect;
                if (!HelperFunctions.CheckIntersection(e.editRect, MousePos))
                {
                    e.EditHover = 0;
                }
                else
                {
                    e.EditHover = 1;
                    ToolTip.CreateTooltip(52, this.ScreenManager);
                    if (this.currentMouse.LeftButton == ButtonState.Pressed && this.previousMouse.LeftButton == ButtonState.Released)
                    {
                        ShipDesignScreen sdScreen = new ShipDesignScreen(this.eui);
                        this.ScreenManager.AddScreen(sdScreen);
                        sdScreen.ChangeHull((e.item as Ship).GetShipData());
                    }
                }
            }
            this.shipsCanBuildLast = this.p.Owner.ShipsWeCanBuild.Count;
            this.buildingsHereLast = this.p.BuildingList.Count;
            this.buildingsCanBuildLast = this.BuildingsCanBuild.Count;
            if (input.RightMouseClick && !this.ClickedTroop) rmouse = false;
            if (!rmouse && (input.CurrentMouseState.RightButton != ButtonState.Released || this.previousMouse.RightButton != ButtonState.Released))
            {
                this.eui.screen.ShipsInCombat.Active = true;
                this.eui.screen.PlanetsInCombat.Active = true;
            }
            this.previousMouse = this.currentMouse;
        }
        private void LoadEverything(object sender, RunWorkerCompletedEventArgs ev)
        {
            bool stop;
            List<SolarSystem>.Enumerator enumerator;
            base.ScreenManager.inter.ObjectManager.Clear();
            this.data = new UniverseData();
            RandomEventManager.ActiveEvent = this.savedData.RandomEvent;
            UniverseScreen.DeepSpaceManager = new SpatialManager();
            this.ThrusterEffect = base.ScreenManager.Content.Load<Effect>("Effects/Thrust");
            int count = this.data.SolarSystemsList.Count;
            this.data.loadFogPath = this.savedData.FogMapName;
            this.data.difficulty = UniverseData.GameDifficulty.Normal;
            this.data.difficulty = this.savedData.gameDifficulty;
            this.data.Size = this.savedData.Size;
            this.data.FTLSpeedModifier = this.savedData.FTLModifier;
            this.data.EnemyFTLSpeedModifier = this.savedData.EnemyFTLModifier;
            this.data.GravityWells = this.savedData.GravityWells;
            //added by gremlin: adjuse projector radius to map size. but only normal or higher.
            //this is pretty bad as its not connected to the creating game screen code that sets the map sizes. If someone changes the map size they wont know to change this as well.
            if (this.data.Size.X > 7300000f)
            Empire.ProjectorRadius = this.data.Size.X / 70f;
            EmpireManager.EmpireList.Clear();
            if (Empire.universeScreen!=null && Empire.universeScreen.MasterShipList != null)
                Empire.universeScreen.MasterShipList.Clear();

            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e =new Empire();
                e.data = new EmpireData();
                    e= this.CreateEmpireFromEmpireSaveData(d);
                this.data.EmpireList.Add(e);
                if (e.data.Traits.Name == this.PlayerLoyalty)
                {
                    e.AutoColonize = this.savedData.AutoColonize;
                    e.AutoExplore = this.savedData.AutoExplore;
                    e.AutoFreighters = this.savedData.AutoFreighters;
                    e.AutoBuild = this.savedData.AutoProjectors;
                }
                EmpireManager.EmpireList.Add(e);
            }
            foreach (Empire e in this.data.EmpireList)
            {
                if (e.data.AbsorbedBy == null)
                {
                    continue;
                }
                foreach (KeyValuePair<string, TechEntry> tech in EmpireManager.GetEmpireByName(e.data.AbsorbedBy).GetTDict())
                {
                    if (!tech.Value.Unlocked)
                    {
                        continue;
                    }
                    EmpireManager.GetEmpireByName(e.data.AbsorbedBy).UnlockHullsSave(tech.Key, e.data.Traits.ShipType);
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                foreach (Relationship r in d.Relations)
                {
                    e.GetRelations().Add(EmpireManager.GetEmpireByName(r.Name), r);
                    if (r.ActiveWar == null)
                    {
                        continue;
                    }
                    r.ActiveWar.SetCombatants(e, EmpireManager.GetEmpireByName(r.Name));
                }
            }
            this.data.SolarSystemsList = new List<SolarSystem>();
            foreach (SavedGame.SolarSystemSaveData sdata in this.savedData.SolarSystemDataList)
            {
                SolarSystem system = this.CreateSystemFromData(sdata);
                system.guid = sdata.guid;
                this.data.SolarSystemsList.Add(system);
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.empireData.Traits.Name);
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    Ship ship = Ship.LoadSavedShip(shipData.data);
                    ship.guid = shipData.guid;
                    ship.Name = shipData.Name;
                    if (!string.IsNullOrEmpty(shipData.VanityName))
                        ship.VanityName = shipData.VanityName;
                    else
                    {
                        if (ship.Role == "troop")
                        {
                            if (shipData.TroopList.Count > 0)
                            {
                                ship.VanityName = shipData.TroopList[0].Name;
                            }
                            else
                                ship.VanityName = shipData.Name;
                        }
                        else
                            ship.VanityName = shipData.Name;
                    }
                    ship.Position = shipData.Position;
                    if (shipData.IsPlayerShip)
                    {
                        this.playerShip = ship;
                        this.playerShip.PlayerShip = true;
                        this.data.playerShip = this.playerShip;
                    }
                    ship.experience = shipData.experience;
                    ship.kills = shipData.kills;
                    if (!Ship_Game.ResourceManager.ShipsDict.ContainsKey(shipData.Name))
                    {
                        shipData.data.Hull = shipData.Hull;
                        Ship newShip = Ship.CreateShipFromShipData(shipData.data);
                        newShip.SetShipData(shipData.data);
                        if (!newShip.InitForLoad())
                        {
                            continue;
                        }
                        newShip.InitializeStatus();
                        newShip.IsPlayerDesign = false;
                        newShip.FromSave = true;
                        Ship_Game.ResourceManager.ShipsDict.Add(shipData.Name, newShip);
                    }
                    else if (Ship_Game.ResourceManager.ShipsDict[shipData.Name].FromSave)
                    {
                        ship.IsPlayerDesign = false;
                        ship.FromSave = true;
                    }
                    float oldbasestr = ship.BaseStrength;
                    float newbasestr = ResourceManager.CalculateBaseStrength(ship);
                    ship.BaseStrength = newbasestr;

                    foreach(ModuleSlotData moduleSD in shipData.data.ModuleSlotList)
                    {
                        ShipModule mismatch =null;
                        bool exists =ResourceManager.ShipModulesDict.TryGetValue(moduleSD.InstalledModuleUID,out mismatch);
                        if (exists)
                            continue;
                        System.Diagnostics.Debug.WriteLine(string.Concat("mismatch =", moduleSD.InstalledModuleUID));
                    }

                    ship.PowerCurrent = shipData.Power;
                    ship.yRotation = shipData.yRotation;
                    ship.Ordinance = shipData.Ordnance;
                    ship.Rotation = shipData.Rotation;
                    ship.Velocity = shipData.Velocity;
                    ship.isSpooling = shipData.AfterBurnerOn;
                    ship.InCombatTimer = shipData.InCombatTimer;
                    foreach (Troop t in shipData.TroopList)
                    {
                        t.SetOwner(EmpireManager.GetEmpireByName(t.OwnerString));
                        ship.TroopList.Add(t);
                    }

                    foreach (Rectangle AOO in shipData.AreaOfOperation)
                    {
                        ship.AreaOfOperation.Add(AOO);
                    }
                    ship.TetherGuid = shipData.TetheredTo;
                    ship.TetherOffset = shipData.TetherOffset;
                    if (ship.InCombatTimer > 0f)
                    {
                        ship.InCombat = true;
                    }
                    ship.loyalty = e;
                    ship.InitializeAI();
                    ship.GetAI().CombatState = shipData.data.CombatState;
                    ship.GetAI().FoodOrProd = shipData.AISave.FoodOrProd;
                    ship.GetAI().State = shipData.AISave.state;
                    ship.GetAI().DefaultAIState = shipData.AISave.defaultstate;
                    ship.GetAI().GotoStep = shipData.AISave.GoToStep;
                    ship.GetAI().MovePosition = shipData.AISave.MovePosition;
                    ship.GetAI().OrbitTargetGuid = shipData.AISave.OrbitTarget;
                    ship.GetAI().ColonizeTargetGuid = shipData.AISave.ColonizeTarget;
                    ship.GetAI().TargetGuid = shipData.AISave.AttackTarget;
                    ship.GetAI().SystemToDefendGuid = shipData.AISave.SystemToDefend;
                    ship.GetAI().EscortTargetGuid = shipData.AISave.EscortTarget;
                    bool hasCargo = false;
                    if (shipData.FoodCount > 0f)
                    {
                        ship.AddGood("Food", (int)shipData.FoodCount);
                        ship.GetAI().FoodOrProd = "Food";
                        hasCargo = true;
                    }
                    if (shipData.ProdCount > 0f)
                    {
                        ship.AddGood("Production", (int)shipData.ProdCount);
                        ship.GetAI().FoodOrProd = "Prod";
                        hasCargo = true;
                    }
                    if (shipData.PopCount > 0f)
                    {
                        ship.AddGood("Colonists_1000", (int)shipData.PopCount);
                    }
                    AIState state = ship.GetAI().State;
                    if (state == AIState.SystemTrader)
                    {
                        ship.GetAI().OrderTradeFromSave(hasCargo, shipData.AISave.startGuid, shipData.AISave.endGuid);
                    }
                    else if (state == AIState.PassengerTransport)
                    {
                        ship.GetAI().OrderTransportPassengersFromSave();
                    }
                    e.AddShip(ship);
                    foreach (SavedGame.ProjectileSaveData pdata in shipData.Projectiles)
                    {
                        Weapon w = Ship_Game.ResourceManager.GetWeapon(pdata.Weapon);
                        Projectile p = w.LoadProjectiles(pdata.Velocity, ship);
                        p.Velocity = pdata.Velocity;
                        p.Position = pdata.Position;
                        p.Center = pdata.Position;
                        p.duration = pdata.Duration;
                        ship.Projectiles.Add(p);
                    }
                    this.data.MasterShipList.Add(ship);
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                foreach (SavedGame.FleetSave fleetsave in d.FleetsList)
                {
                    Ship_Game.Gameplay.Fleet fleet = new Ship_Game.Gameplay.Fleet()
                    {
                        guid = fleetsave.FleetGuid,
                        IsCoreFleet = fleetsave.IsCoreFleet,
                        facing = fleetsave.facing
                    };
                    foreach (SavedGame.FleetShipSave ssave in fleetsave.ShipsInFleet)
                    {
                        foreach (Ship ship in this.data.MasterShipList)
                        {
                            if (ship.guid != ssave.shipGuid)
                            {
                                continue;
                            }
                            ship.RelativeFleetOffset = ssave.fleetOffset;
                            fleet.AddShip(ship);
                        }
                    }
                    foreach (FleetDataNode node in fleetsave.DataNodes)
                    {
                        fleet.DataNodes.Add(node);
                    }
                    foreach (FleetDataNode node in fleet.DataNodes)
                    {
                        foreach (Ship ship in fleet.Ships)
                        {
                            if (!(node.ShipGuid != Guid.Empty) || !(ship.guid == node.ShipGuid))
                            {
                                continue;
                            }
                            node.SetShip(ship);
                            node.ShipName = ship.Name;
                            break;
                        }
                    }
                    fleet.AssignPositions(fleet.facing);
                    fleet.Name = fleetsave.Name;
                    fleet.TaskStep = fleetsave.TaskStep;
                    fleet.Owner = e;
                    fleet.Position = fleetsave.Position;

                    if (e.GetFleetsDict().ContainsKey(fleetsave.Key))
                    {
                        e.GetFleetsDict()[fleetsave.Key] = fleet;
                    }
                    else
                    {
                        e.GetFleetsDict().TryAdd(fleetsave.Key, fleet);
                    }
                    e.GetFleetsDict()[fleetsave.Key].SetSpeed();
                    fleet.findAveragePositionset();
                    fleet.Setavgtodestination();

                }
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    foreach (Ship ship in e.GetShips())
                    {
                        if (ship.Position != shipData.Position)
                        {
                            continue;
                        }
                    }
                }
            }
            foreach (SavedGame.EmpireSaveData d in this.savedData.EmpireDataList)
            {
                Empire e = EmpireManager.GetEmpireByName(d.Name);
                e.SpaceRoadsList = new List<SpaceRoad>();
                foreach (SavedGame.SpaceRoadSave roadsave in d.SpaceRoadData)
                {
                    SpaceRoad road = new SpaceRoad();
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        if (roadsave.OriginGUID == s.guid)
                        {
                            road.SetOrigin(s);
                        }
                        if (roadsave.DestGUID != s.guid)
                        {
                            continue;
                        }
                        road.SetDestination(s);
                    }
                    foreach (SavedGame.RoadNodeSave nodesave in roadsave.RoadNodes)
                    {
                        RoadNode node = new RoadNode();
                        foreach (Ship s in this.data.MasterShipList)
                        {
                            if (nodesave.Guid_Platform != s.guid)
                            {
                                continue;
                            }
                            node.Platform = s;
                        }
                        node.Position = nodesave.Position;
                        road.RoadNodesList.Add(node);
                    }
                    e.SpaceRoadsList.Add(road);
                }
                foreach (SavedGame.GoalSave gsave in d.GSAIData.Goals)
                {
                    Goal g = new Goal()
                    {
                        empire = e,
                        type = gsave.type
                    };
                    if (g.type == GoalType.BuildShips && gsave.ToBuildUID != null && !Ship_Game.ResourceManager.ShipsDict.ContainsKey(gsave.ToBuildUID))
                    {
                        continue;
                    }
                    g.ToBuildUID = gsave.ToBuildUID;
                    g.Step = gsave.GoalStep;
                    g.guid = gsave.GoalGuid;
                    g.GoalName = gsave.GoalName;
                    g.BuildPosition = gsave.BuildPosition;
                    if (gsave.fleetGuid != Guid.Empty)
                    {
                        foreach (KeyValuePair<int, Ship_Game.Gameplay.Fleet> Fleet in e.GetFleetsDict())
                        {
                            if (Fleet.Value.guid != gsave.fleetGuid)
                            {
                                continue;
                            }
                            g.SetFleet(Fleet.Value);
                        }
                    }
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        foreach (Planet p in s.PlanetList)
                        {
                            if (p.guid == gsave.planetWhereBuildingAtGuid)
                            {
                                g.SetPlanetWhereBuilding(p);
                            }
                            if (p.guid != gsave.markedPlanetGuid)
                            {
                                continue;
                            }
                            g.SetMarkedPlanet(p);
                        }
                    }
                    foreach (Ship s in this.data.MasterShipList)
                    {
                        if (gsave.colonyShipGuid == s.guid)
                        {
                            g.SetColonyShip(s);
                        }
                        if (gsave.beingBuiltGUID != s.guid)
                        {
                            continue;
                        }
                        g.SetBeingBuilt(s);
                    }
                    e.GetGSAI().Goals.Add(g);
                }
                for (int i = 0; i < d.GSAIData.PinGuids.Count; i++)
                {
                    e.GetGSAI().ThreatMatrix.Pins.TryAdd(d.GSAIData.PinGuids[i], d.GSAIData.PinList[i]);
                }
                e.GetGSAI().UsedFleets = d.GSAIData.UsedFleets;
                lock (GlobalStats.TaskLocker)
                {
                    foreach (MilitaryTask task in d.GSAIData.MilitaryTaskList)
                    {
                        task.SetEmpire(e);
                        e.GetGSAI().TaskList.Add(task);
                        if (task.TargetPlanetGuid != Guid.Empty)
                        {
                            enumerator = this.data.SolarSystemsList.GetEnumerator();
                            try
                            {
                                do
                                {
                                    if (!enumerator.MoveNext())
                                    {
                                        break;
                                    }
                                    SolarSystem s = enumerator.Current;
                                    stop = false;
                                    foreach (Planet p in s.PlanetList)
                                    {
                                        if (p.guid != task.TargetPlanetGuid)
                                        {
                                            continue;
                                        }
                                        task.SetTargetPlanet(p);
                                        stop = true;
                                        break;
                                    }
                                }
                                while (!stop);
                            }
                            finally
                            {
                                ((IDisposable)enumerator).Dispose();
                            }
                        }
                        foreach (Guid guid in task.HeldGoals)
                        {
                            foreach (Goal g in e.GetGSAI().Goals)
                            {
                                if (g.guid != guid)
                                {
                                    continue;
                                }
                                g.Held = true;
                            }
                        }
                        try
                        {
                            if (task.WhichFleet != -1)
                            {
                                e.GetFleetsDict()[task.WhichFleet].Task = task;
                            }
                        }
                        catch
                        {
                            task.WhichFleet = 0;
                        }
                    }
                }
                foreach (SavedGame.ShipSaveData shipData in d.OwnedShips)
                {
                    foreach (Ship ship in this.data.MasterShipList)
                    {
                        if (ship.guid != shipData.guid)
                        {
                            continue;
                        }
                        foreach (Vector2 waypoint in shipData.AISave.ActiveWayPoints)
                        {
                            ship.GetAI().ActiveWayPoints.Enqueue(waypoint);
                        }
                        foreach (SavedGame.ShipGoalSave sg in shipData.AISave.ShipGoalsList)
                        {
                            ArtificialIntelligence.ShipGoal g = new ArtificialIntelligence.ShipGoal(sg.Plan, sg.MovePosition, sg.FacingVector);
                            foreach (SolarSystem s in this.data.SolarSystemsList)
                            {
                                foreach (Planet p in s.PlanetList)
                                {
                                    if (sg.TargetPlanetGuid == p.guid)
                                    {
                                        g.TargetPlanet = p;
                                        ship.GetAI().ColonizeTarget = p;
                                    }
                                    if (p.guid == shipData.AISave.startGuid)
                                    {
                                        ship.GetAI().start = p;
                                    }
                                    if (p.guid != shipData.AISave.endGuid)
                                    {
                                        continue;
                                    }
                                    ship.GetAI().end = p;
                                }
                            }
                            if (sg.fleetGuid != Guid.Empty)
                            {
                                foreach (KeyValuePair<int, Ship_Game.Gameplay.Fleet> fleet in e.GetFleetsDict())
                                {
                                    if (fleet.Value.guid != sg.fleetGuid)
                                    {
                                        continue;
                                    }
                                    g.fleet = fleet.Value;
                                }
                            }
                            g.VariableString = sg.VariableString;
                            g.DesiredFacing = sg.DesiredFacing;
                            g.SpeedLimit = sg.SpeedLimit;
                            foreach (Goal goal in ship.loyalty.GetGSAI().Goals)
                            {
                                if (sg.goalGuid != goal.guid)
                                {
                                    continue;
                                }
                                g.goal = goal;
                            }
                            ship.GetAI().OrderQueue.AddLast(g);
                        }
                    }
                }
            }
            foreach (SavedGame.SolarSystemSaveData sdata in this.savedData.SolarSystemDataList)
            {
                foreach (SavedGame.RingSave rsave in sdata.RingList)
                {
                    Planet p = new Planet();
                    foreach (SolarSystem s in this.data.SolarSystemsList)
                    {
                        foreach (Planet p1 in s.PlanetList)
                        {
                            if (p1.guid != rsave.Planet.guid)
                            {
                                continue;
                            }
                            p = p1;
                            break;
                        }
                    }
                    if (p.Owner == null)
                    {
                        continue;
                    }
                    foreach (SavedGame.QueueItemSave qisave in rsave.Planet.QISaveList)
                    {
                        QueueItem qi = new QueueItem();
                        if (qisave.isBuilding)
                        {
                            qi.isBuilding = true;
                            qi.Building = Ship_Game.ResourceManager.BuildingsDict[qisave.UID];
                            qi.Cost = qi.Building.Cost * this.savedData.GamePacing;
                            qi.NotifyOnEmpty = false;
                            foreach (PlanetGridSquare pgs in p.TilesList)
                            {
                                if ((float)pgs.x != qisave.pgsVector.X || (float)pgs.y != qisave.pgsVector.Y)
                                {
                                    continue;
                                }
                                pgs.QItem = qi;
                                qi.pgs = pgs;
                                break;
                            }
                        }
                        if (qisave.isTroop)
                        {
                            qi.isTroop = true;
                            qi.troop = Ship_Game.ResourceManager.TroopsDict[qisave.UID];
                            qi.Cost = qi.troop.GetCost();
                            qi.NotifyOnEmpty = false;
                        }
                        if (qisave.isShip)
                        {
                            qi.isShip = true;
                            if (!Ship_Game.ResourceManager.ShipsDict.ContainsKey(qisave.UID))
                            {
                                continue;
                            }
                            qi.sData = Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData();
                            qi.DisplayName = qisave.DisplayName;
                            qi.Cost = 0f;
                            foreach (ModuleSlot slot in Ship_Game.ResourceManager.GetShip(qisave.UID).ModuleSlotList)
                            {
                                if (slot.InstalledModuleUID == null)
                                {
                                    continue;
                                }
                                QueueItem cost = qi;
                                cost.Cost = cost.Cost + Ship_Game.ResourceManager.GetModule(slot.InstalledModuleUID).Cost * this.savedData.GamePacing;
                            }
                            QueueItem queueItem = qi;
                            queueItem.Cost += qi.Cost * p.Owner.data.Traits.ShipCostMod;
                            queueItem.Cost *= (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.useHullBonuses && ResourceManager.HullBonuses.ContainsKey(Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData().Hull) ? 1f - ResourceManager.HullBonuses[Ship_Game.ResourceManager.GetShip(qisave.UID).GetShipData().Hull].CostBonus : 1);
                            if (qi.sData.HasFixedCost)
                            {
                                qi.Cost = (float)qi.sData.FixedCost;
                            }
                            if (qisave.IsRefit)
                            {
                                qi.isRefit = true;
                                qi.Cost = qisave.RefitCost;
                            }
                        }
                        foreach (Goal g in p.Owner.GetGSAI().Goals)
                        {
                            if (g.guid != qisave.GoalGUID)
                            {
                                continue;
                            }
                            qi.Goal = g;
                            qi.NotifyOnEmpty = false;
                        }
                        if (qisave.isShip && qi.Goal != null)
                        {
                            qi.Goal.beingBuilt = Ship_Game.ResourceManager.GetShip(qisave.UID);
                        }
                        qi.productionTowards = qisave.ProgressTowards;
                        p.ConstructionQueue.Add(qi);
                    }
                }
            }
            this.Loaded = true;
        }