public UniverseScreen(UniverseData data, string loyalty)
 {
     //this.perfavg2   = new List<float>();
     //this.perfavg3 = new List<float>();
     //this.perfavg4 = new List<float>();
     //this.perfavg5 = new List<float>();
     //this.perfavg = new List<float>();
     this.Size = data.Size;
     this.FTLModifier = data.FTLSpeedModifier;
     this.EnemyFTLModifier = data.EnemyFTLSpeedModifier;
     this.GravityWells = data.GravityWells;
     UniverseScreen.SolarSystemList = data.SolarSystemsList;
     this.MasterShipList = data.MasterShipList;
     this.loadFogPath = data.loadFogPath;
     this.PlayerLoyalty = loyalty;
     this.playerShip = data.playerShip;
     EmpireManager.GetEmpireByName(loyalty).isPlayer = true;
     this.ShipToView = this.playerShip;
     this.loading = true;
 }
 public void InitialzeAOsFromSave(UniverseData data)
 {
     foreach (AO area in this.AreasOfOperations)
     {
         foreach (SolarSystem sys in data.SolarSystemsList)
         {
             foreach (Planet p in sys.PlanetList)
             {
                 if (p.guid != area.CoreWorldGuid)
                 {
                     continue;
                 }
                 area.SetPlanet(p);
             }
         }
         foreach (SolarSystem sys in data.SolarSystemsList)
         {
             foreach (Planet p in sys.PlanetList)
             {
                 if (Vector2.Distance(p.Position, area.Position) >= area.Radius)
                 {
                     continue;
                 }
                 area.GetPlanets().Add(p);
             }
         }
         foreach (Guid guid in area.OffensiveForceGuids)
         {
             foreach (Ship ship in data.MasterShipList)
             {
                 if (ship.guid != guid)//||ship.GetStrength() <=0)
                 {
                     continue;
                 }
                 area.GetOffensiveForcePool().Add(ship);
                 ship.AddedOnLoad = true;
             }
         }
         foreach (Guid guid in area.ShipsWaitingGuids)
         {
             foreach (Ship ship in data.MasterShipList)
             {
                 if (ship.guid != guid)
                 {
                     continue;
                 }
                 area.GetWaitingShips().Add(ship);
                 ship.AddedOnLoad = true;
             }
         }
         foreach (KeyValuePair<int, Fleet> fleet in this.empire.GetFleetsDict())
         {
             if (fleet.Value.guid != area.fleetGuid)
             {
                 continue;
             }
             area.SetFleet(fleet.Value);
         }
     }
 }
        //private float Zrotate;
        public CreatingNewGameScreen(Empire empire, string size, float StarNumModifier, string EmpireToRemoveName, int numOpponents, RaceDesignScreen.GameMode gamemode, int GameScale, UniverseData.GameDifficulty difficulty, MainMenuScreen mmscreen)
        {
            {
                GlobalStats.RemnantArmageddon = false;
                GlobalStats.RemnantKills = 0;
                this.mmscreen = mmscreen;
                foreach (KeyValuePair<string, Ship_Game.Artifact> Artifact in Ship_Game.ResourceManager.ArtifactsDict)
                {
                    Artifact.Value.Discovered = false;
                }
                RandomEventManager.ActiveEvent = null;
                this.difficulty = difficulty;
                this.scale = (float)GameScale;
                if (this.scale == 5) this.scale = 8;
                if (this.scale == 6) this.scale = 16;
                this.mode = gamemode;
                this.numOpponents = numOpponents;
                this.EmpireToRemoveName = EmpireToRemoveName;
                EmpireManager.EmpireList.Clear();
                XmlSerializer serializer2 = new XmlSerializer(typeof(DiplomaticTraits));
                //Added by McShooterz: mod folder support
                this.dtraits = (DiplomaticTraits)serializer2.Deserialize((new FileInfo(File.Exists(string.Concat(Ship_Game.ResourceManager.WhichModPath, "/Diplomacy/DiplomaticTraits.xml")) ? string.Concat(Ship_Game.ResourceManager.WhichModPath, "/Diplomacy/DiplomaticTraits.xml") : "Content/Diplomacy/DiplomaticTraits.xml")).OpenRead());
                Ship_Game.ResourceManager.LoadEncounters();
                this.playerEmpire = empire;
                empire.Initialize();
                empire.data.CurrentAutoColony = empire.data.DefaultColonyShip;
                empire.data.CurrentAutoFreighter = empire.data.DefaultSmallTransport;
                empire.data.CurrentAutoScout = empire.data.StartingScout;
                empire.data.CurrentConstructor = empire.data.DefaultConstructor;
                this.data = new UniverseData()
                {
                    FTLSpeedModifier = GlobalStats.FTLInSystemModifier,
                    EnemyFTLSpeedModifier = GlobalStats.EnemyFTLInSystemModifier,
                    GravityWells = GlobalStats.PlanetaryGravityWells,
                    FTLinNeutralSystem = GlobalStats.WarpInSystem
                };
                string str = size;
                string str1 = str;
                if (str != null)
                {
                    if (str1 == "Tiny")
                    {
                        //if (mode == RaceDesignScreen.GameMode.Warlords)
                        //{
                        //    this.numSystems = (int)(12 * StarNumModifier);
                        //}
                        //else
                            this.numSystems = (int)(16f * StarNumModifier);
                        this.data.Size = new Vector2(3500000f, 3500000f);
                    }
                    else if (str1 == "Small")
                    {
                        //if (mode == RaceDesignScreen.GameMode.Warlords)
                        //{
                        //    this.numSystems = (int)(12 * StarNumModifier);
                        //}
                        //else
                            this.numSystems = (int)(30f * StarNumModifier);
                        this.data.Size = new Vector2(7300000f, 7300000f);
                    }
                    else if (str1 == "Medium")
                    {
                        //if (mode == RaceDesignScreen.GameMode.Warlords)
                        //{
                        //    this.numSystems = (int)(12 * StarNumModifier);
                        //}
                        //else
                            this.numSystems = (int)(50f * StarNumModifier);
                        this.data.Size = new Vector2(9350000f, 9350000f);
                        Empire.ProjectorRadius = (this.data.Size.X / 70);
                    }
                    else if (str1 == "Large")
                    {
                        //if (mode == RaceDesignScreen.GameMode.Warlords)
                        //{
                        //    this.numSystems = (int)(12 * StarNumModifier);
                        //}
                        //else
                            this.numSystems = (int)(50f * StarNumModifier);
                            Empire.ProjectorRadius = (this.data.Size.X / 70);
                    }
                    else if (str1 == "Huge")
                    {
                        //if (mode == RaceDesignScreen.GameMode.Warlords)
                        //{
                        //    this.numSystems = (int)(12 * StarNumModifier);
                        //}
                        //else
                            this.numSystems = (int)(50f * StarNumModifier);
                            this.data.Size = new Vector2(18000000f, 18000000f);
                            Empire.ProjectorRadius = (this.data.Size.X / 70);
                    }
                    else if (str1 == "Epic")
                    {
                        //if (mode == RaceDesignScreen.GameMode.Warlords)
                        //{
                        //    this.numSystems = (int)(12 * StarNumModifier);
                        //}
                        //else
                            this.numSystems = (int)(50f * StarNumModifier);
                            this.data.Size = new Vector2(54000000, 54000000);
                            Empire.ProjectorRadius = (this.data.Size.X / 70);
                            //this.data.Size = new Vector2(36000000, 36000000);
                        //this.scale = 2;

                        //this.numSystems = (int)(125f * StarNumModifier);
                        //this.data.Size = new Vector2(3.6E+07f, 3.6E+07f);

                    }
                    else if (str1 == "TrulyEpic")
                    {
                        //if (mode == RaceDesignScreen.GameMode.Warlords)
                        //{
                        //    this.numSystems = (int)(12 * StarNumModifier);
                        //}
                        //else
                            this.numSystems = (int)(50f * StarNumModifier);
                        //this.numSystems = (int)(100f * StarNumModifier);
                            this.data.Size = new Vector2(54000000, 54000000);
                        //this.data.Size = new Vector2(7.2E+07f, 7.2E+07f);
                        //this.scale = 4;
                            Empire.ProjectorRadius = (this.data.Size.X / 70);

                    }
                    //if (this.numSystems <= this.numOpponents+2)
                    //{
                    //    this.numSystems = this.numOpponents + 2;
                    //}
                }
                UniverseData universeDatum = this.data;
                universeDatum.Size = universeDatum.Size * this.scale;
                this.data.EmpireList.Add(empire);
                EmpireManager.EmpireList.Add(empire);
                this.GalacticCenter = new Vector2(this.data.Size.X / 2f, this.data.Size.Y / 2f);
                StatTracker.SnapshotsDict.Clear();

            }
        }
 public UniverseScreen(UniverseData data)
 {
     this.Size = data.Size;
     this.FTLModifier = data.FTLSpeedModifier;
     this.EnemyFTLModifier = data.EnemyFTLSpeedModifier;
     this.GravityWells = data.GravityWells;
     UniverseScreen.SolarSystemList = data.SolarSystemsList;
     this.MasterShipList = data.MasterShipList;
     this.playerShip = data.playerShip;
     this.PlayerLoyalty = this.playerShip.loyalty.data.Traits.Name;
     this.playerShip.loyalty.isPlayer = true;
     this.ShipToView = this.playerShip;
 }
 private void AddRemnantPatrol(Planet newOrbital, UniverseData data)
 {
     newOrbital.PlanetFleets.Add("Remnant Patrol");
 }
 private void AddRemnantGarrison(Planet newOrbital, UniverseData data)
 {
     newOrbital.PlanetFleets.Add("Remnant Garrison");
 }
        public void GenerateRandomSystem(string name, UniverseData data, float systemScale)
        {
            int WhichSun = (int)RandomMath.RandomBetween(1f, 6f);
            // CHANGED BY SHAHMATT
            if (WhichSun > 5)
            {
                if ((int)RandomMath.RandomBetween(0f, 100f) < 10)   // 10% for binary star (so 1/6 * 10% = 1/60 for binary star in system)
                {
                    WhichSun = 6;
                }
                else
                {
                    WhichSun = 5;
                }

            }
            // END OF CHANGED BY SHAHMATT

            //int WhichSun = (int)RandomMath.RandomBetween(1f, 6f);
            //if (WhichSun > 5)
            //{
            //    WhichSun = 5;
            //}
            if (WhichSun == 1)
            {
                this.SunPath = "star_red";
            }
            else if (WhichSun == 2)
            {
                this.SunPath = "star_yellow";
            }
            else if (WhichSun == 3)
            {
                this.SunPath = "star_green";
            }
            else if (WhichSun == 4)
            {
                this.SunPath = "star_blue";
            }
            else if (WhichSun == 5)
            {
                this.SunPath = "star_yellow2";
            }
            else if (WhichSun == 6)
            {
                this.SunPath = "star_binary";
            }
            this.Name = name;
            this.numberOfRings = (int)RandomMath.RandomBetween(1f, 6f);
            // ADDED BY SHAHMATT (more planets in system)
            if (GlobalStats.ExtraPlanets >0)
            {
                this.numberOfRings = this.numberOfRings + (int)RandomMath.RandomBetween(0f, (float)GlobalStats.ExtraPlanets);
            }
            // END OF ADDED BY SHAHMATT
            this.RingsCount = this.numberOfRings;
            this.StarRadius = (int)RandomMath.RandomBetween(250f, 500f);
            float ringbase = 10500f;
            float ringmax = 0;
            if (this.RingsCount > 0)
            {
                ringmax = (95000 - this.StarRadius) / this.numberOfRings;
                //ringbase = (10000 - this.StarRadius) / this.numberOfRings;
            }

            for (int i = 1; i < this.numberOfRings + 1; i++)
            {
                if (this.RingList.Count > 1)
                {
                    ringbase = this.RingList[this.RingList.Count - 1].Distance + 5000;// / this.numberOfRings;
                    Planet p = this.RingList[this.RingList.Count - 1].planet;
                    if (p != null)
                        ringbase += p.ObjectRadius;

                }

                //float ringRadius = (float)i * ((float)this.StarRadius + RandomMath.RandomBetween(10500f, 12000f) + 10000f);
                float ringRadius = ringbase + RandomMath.RandomBetween(0, ringmax);// + 20000f / this.numberOfRings);
                ringRadius = ringRadius * systemScale;
                if ((int)RandomMath.RandomBetween(1f, 100f) > 80)
                {
                    float numberOfAsteroids = RandomMath.RandomBetween(150f, 250f);
                    for (int k = 0; (float)k < numberOfAsteroids; k++)
                    {
                        Vector3 asteroidCenter = new Vector3(this.GenerateRandomPointOnCircle(ringRadius + RandomMath.RandomBetween(-3500f * systemScale, 3500f * systemScale), Vector2.Zero), 0f);
                        while (!this.RoidPosOK(asteroidCenter))
                        {
                            asteroidCenter = new Vector3(this.GenerateRandomPointOnCircle(ringRadius + RandomMath.RandomBetween(-3500f * systemScale, 3500f * systemScale), Vector2.Zero), 0f);
                        }
                        Asteroid newRoid = new Asteroid()
                        {
                            scale = RandomMath.RandomBetween(0.75f, 1.6f),
                            Position3D = asteroidCenter
                        };
                        int whichRoid = 0;
                        while (whichRoid == 0 || whichRoid == 3)
                        {
                            whichRoid = (int)RandomMath.RandomBetween(1f, 9f);
                        }
                        newRoid.whichRoid = whichRoid;
                        newRoid.Radius = RandomMath.RandomBetween(30f, 90f);
                        this.AsteroidsList.Add(newRoid);
                    }
                    SolarSystem.Ring ring = new SolarSystem.Ring()
                    {
                        Distance = ringRadius,
                        Asteroids = true
                    };
                    this.RingList.Add(ring);
                }
                else
                {

                    float RandomAngle = RandomMath.RandomBetween(0f, 360f);
                    Vector2 planetCenter = this.findPointFromAngleAndDistance(Vector2.Zero, RandomAngle, ringRadius);
                    Planet newOrbital = new Planet()
                    {
                        Name = string.Concat(this.Name, " ", NumberToRomanConvertor.NumberToRoman(i)),
                        OrbitalAngle = RandomAngle,
                        ParentSystem = this,
                        planetType = (int)RandomMath.RandomBetween(1f, 24f)
                    };
                    if ((newOrbital.planetType == 22 || newOrbital.planetType == 13) && RandomMath.RandomBetween(0f, 100f) > 50f)
                    {
                        newOrbital.planetType = (int)RandomMath.RandomBetween(1f, 24f);
                    }

                    float scale = RandomMath.RandomBetween(0.9f, 1.8f);
                    if (newOrbital.planetType == 2 || newOrbital.planetType == 6 || newOrbital.planetType == 10 || newOrbital.planetType == 12 || newOrbital.planetType == 15 || newOrbital.planetType == 20 || newOrbital.planetType == 26)
                    {
                        scale += 2.5f;
                    }
                    float planetRadius = 100f * scale;
                    newOrbital.SetPlanetAttributes();
                    newOrbital.Position = planetCenter;
                    newOrbital.scale = scale;
                    newOrbital.ObjectRadius = planetRadius;
                    newOrbital.OrbitalRadius = ringRadius;
                    newOrbital.planetTilt = RandomMath.RandomBetween(45f, 135f);
                    if (RandomMath.RandomBetween(1f, 100f) < 15f)
                    {
                        newOrbital.hasRings = true;
                        newOrbital.ringTilt = RandomMath.RandomBetween(-80f, -45f);
                    }
                    float quality = newOrbital.Fertility + newOrbital.MineralRichness + newOrbital.MaxPopulation / 1000f;
                    if (GlobalStats.ActiveModInfo != null && GlobalStats.ActiveModInfo.customRemnantElements)
                    {
                        if (quality > 6f && quality < 10f)
                        {
                            int iRandom = (int)RandomMath.RandomBetween(0f, 100f);
                            if (iRandom > 20 && iRandom < 50)
                            {
                                this.AddRemnantPatrol(newOrbital, data);
                            }
                            else if (iRandom >= 50)
                            {
                                this.AddRemnantGarrison(newOrbital, data);
                            }
                        }
                        else if (quality > 10f)
                        {
                            int iRandom = (int)RandomMath.RandomBetween(0f, 100f);
                            if (iRandom > 50 && iRandom < 85)
                            {
                                this.AddMinorRemnantPresence(newOrbital);
                            }
                            else if (iRandom >= 85)
                            {
                                this.AddMajorRemnantPresence(newOrbital);
                            }
                        }
                    }
                    else
                    {
                        if (quality > 6f && quality < 10f)
                        {
                            if ((int)RandomMath.RandomBetween(0f, 100f) > 50)
                            {
                                this.AddMinorRemnantPresence(newOrbital);
                            }
                        }
                        else if (quality > 10f && (int)RandomMath.RandomBetween(0f, 100f) < 50)
                        {
                            this.AddMajorRemnantPresence(newOrbital);
                        }
                    }
                    this.PlanetList.Add(newOrbital);
                    RandomMath.RandomBetween(0f, 3f);
                    SolarSystem.Ring ring = new SolarSystem.Ring()
                    {
                        Distance = ringRadius,
                        Asteroids = false,
                        planet = newOrbital
                    };
                    this.RingList.Add(ring);
                }
            }
        }
        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;
        }
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         lock (this)
         {
             if (this.GateKeeper != null)
                 this.GateKeeper.Dispose();
             if (this.data != null)
                 this.data.Dispose();
         }
         this.GateKeeper = null;
         this.data = null;
     }
 }