public bool PSystemsLoaded;//Signals that all PSystems have been loaded and the server is ready
        //TODO: Implement pause to object updating when additional systems need to be loaded while server is up

        public MasterServerMessageHandler(
            int mySlaveID,
            RedisServer redisServer,
            ConnectionManager connectionManager,
            LocatorService ls,
            AccountManager accountManager,
            LocalIDManager accountIdManager,
            IDatabaseManager databaseManager,
            GalaxyManager galaxyManager,
            LocalIDManager galaxyIDManager,
            PlayerManager playerManager,
            ShipManager shipManager,
            GalaxyRegistrationManager rm,
            LocalIDManager teamIDManager,
            MessageManager messageManager,
            GlobalTeamManager teamManager,
            WarpManager warpManager,
            LocalIDManager transactionIdManager,
            EventHandler <NetworkMessageContainer> routedMessageProcessor
            )
        {
            _connectionManager    = connectionManager;
            _accountManager       = accountManager;
            _accountIdManager     = accountIdManager;
            _databaseManager      = databaseManager;
            _galaxyIDManager      = galaxyIDManager;
            _galaxyManager        = galaxyManager;
            _teamIDManager        = teamIDManager;
            _playerManager        = playerManager;
            _shipManager          = shipManager;
            _registrationManager  = rm;
            _locatorService       = ls;
            _messageManager       = messageManager;
            _teamManager          = teamManager;
            _redisServer          = redisServer;
            _warpManager          = warpManager;
            _transactionIdManager = transactionIdManager;

            _mySlaveID = mySlaveID;

            _routedMessageProcessor = routedMessageProcessor;

            _redisServer.Subscribe(MessageTypes.Redis_LoginDataRequest, _handleLoginDataRequest);
            _redisServer.Subscribe(MessageTypes.Redis_ColonyDataPush, _handleColonyDataPush);
            _redisServer.Subscribe(MessageTypes.Redis_ClientHandoff, _handleHandoff);
            _redisServer.Subscribe(MessageTypes.Redis_StartUpdatingSystems, _handleMessageStartUpdatingSystems);
            _redisServer.Subscribe(MessageTypes.Redis_IDResponse, _handleMessageIDResponse);
            _redisServer.Subscribe(MessageTypes.Redis_AdminWarpPlayer, _handleAdminWarpPlayer);
        }
예제 #2
0
        public MinimalMockServer(GalacticProperties gp, IDatabaseManager databaseManager, IDbIdIoService dbIdIoService)
        {
            Logger.Initialize();

            DatabaseManager = databaseManager;
            DbIdIoService   = dbIdIoService;

            //Minimal initializations
            GalaxyIDManager  = new LocalIDManager(null, IDTypes.GalaxyID);
            TeamIDManager    = new LocalIDManager(null, IDTypes.TeamID);
            accountIDManager = new LocalIDManager(null, IDTypes.AccountID);

            InitializeIdData(gp);

            globalGalaxyIDManager = new GlobalGalaxyIDManager(dbIdIoService, gp);
            GenerateIDsForLocalIDManager(globalGalaxyIDManager, GalaxyIDManager, gp.IdProperties[IDTypes.GalaxyID].LastIDAdded);

            globalTeamIDManager = new GlobalTeamIDManager(dbIdIoService, gp);
            GenerateIDsForLocalIDManager(globalTeamIDManager, TeamIDManager, gp.IdProperties[IDTypes.TeamID].LastIDAdded);

            globalAccountIDManager = new GlobalAccountIDManager(dbIdIoService, gp);
            GenerateIDsForLocalIDManager(globalAccountIDManager, accountIDManager, gp.IdProperties[IDTypes.AccountID].LastIDAdded);

            _redisServer = new RedisServer(Logger.LogRedisError, Logger.LogRedisInfo, new RedisConfig().Address);


            TeamManager        = new GlobalTeamManager(TeamIDManager, null, null, null, DatabaseManager);
            PlayerManager      = new PlayerManager(DatabaseManager, null, _redisServer, GalaxyIDManager, null);
            GalaxyManager      = new GalaxyManager(gp.SolID, TeamManager);
            shipManager        = new ShipManager(null, GalaxyManager, null, null, DatabaseManager);
            CollisionManager   = new CollisionManager(GalaxyManager, null, null, null);
            GalaxyGenerator    = new DebugGalaxyGenerator(PlayerManager, GalaxyManager, shipManager);
            AccountManager     = new AccountManager_MasterServer(accountIDManager, DatabaseManager, false);
            CargoSynchronizer  = new Server.Managers.CargoSynchronizer();
            StructureManager   = new StructureManager(DatabaseManager, GalaxyManager, GalaxyIDManager, CargoSynchronizer);
            RegistrationManger = new GalaxyRegistrationManager(GalaxyManager, shipManager, CollisionManager, GalaxyIDManager, PlayerManager, null, CargoSynchronizer, StructureManager);
            ColonyFactory.Initialize(GalaxyIDManager, RegistrationManger);
            StructureFactory.Initialize(GalaxyIDManager, RegistrationManger);
            LocatorService = new LocatorService(RegistrationManger, PlayerManager, GalaxyManager, shipManager, AccountManager, TeamManager, TeamManager, null, StructureManager, null);

            WarpManager = new WarpManager(GalaxyManager, null, null, _redisServer, AccountManager, null);

            CargoSynchronizer.Start(10, 4);
        }
예제 #3
0
        /// <summary>
        /// Returns created NPCPlayers
        /// </summary>
        /// <param name="galaxyManager"></param>
        /// <param name="IDManager"></param>
        /// <param name="rm"></param>
        /// <param name="pm"></param>
        /// <param name="npcShips"></param>
        /// <returns></returns>
        async Task <IEnumerable <NPCPlayer> > CreateNPCs(GalaxyManager galaxyManager, LocalIDManager IDManager, GalaxyRegistrationManager rm, PlayerManager pm, LocatorService locatorService, CargoSynchronizer cargoSynchronizer, GlobalTeamManager teamManager, LocalIDManager galaxyIDManager)
        {
            Random r = new Random(666);


            var players = new List <NPCPlayer>();


            var systems  = galaxyManager.Systems;
            int npcCount = 0;

            foreach (PSystem s in systems)
            {
                List <Player> team1 = new List <Player>();
                List <Player> team2 = new List <Player>();
                List <Player> team3 = new List <Player>();
                for (int i = 0; i < _config.NumNPCsPerSystem; i++)
                {
                    List <WeaponTypes> weapons = new List <WeaponTypes>();

                    ShipTypes shipType = ShipTypes.Barge;
                    switch (npcCount % 3)
                    {
                    case 0:
                        shipType = ShipTypes.Penguin;
                        break;

                    case 1:
                        shipType = ShipTypes.Barge;
                        break;

                    case 2:
                        shipType = ShipTypes.Reaper;
                        break;
                    }

                    if (shipType == ShipTypes.Reaper)
                    {
                        weapons.Add(WeaponTypes.LaserWave);
                        weapons.Add(WeaponTypes.PlasmaCannon);
                    }
                    else
                    {
                        weapons.Add(WeaponTypes.AltLaser);
                        weapons.Add(WeaponTypes.LaserWave);
                    }

                    ShipCreationProperties props = new ShipCreationProperties(r.Next(-20, 20), r.Next(-20, 20), (int)galaxyManager.SolAreaID, PilotTypes.NPC, shipType, weapons);
                    IShip tempShip = _dbFillerUtils.ShipFactory.CreateShip(props);
                    tempShip.ShipStats.ShieldType = ShieldTypes.QuickRegen;

                    NPCPlayer p = pm.CreateNPCPlayer(locatorService);
                    pm.RegisterPlayer(p);
                    players.Add(p);

                    tempShip.SetPlayer(p);
                    p.SetActiveShip(tempShip, MockServer.WarpManager);


                    TransactionAddStatelessCargo tr = new TransactionAddStatelessCargo(tempShip,
                                                                                       StatelessCargoTypes.AmbassadorMissile, 666666, true);
                    cargoSynchronizer.RequestTransaction(tr);
                    await tr.ResultTask;

                    tr = new TransactionAddStatelessCargo(tempShip, StatelessCargoTypes.Biodome, 666666, true);
                    cargoSynchronizer.RequestTransaction(tr);
                    await tr.ResultTask;

                    Helpers.DebugWarp(s, p, tempShip);

                    ships.Add(tempShip);

                    //Random team assignment
                    switch (npcCount % 2)
                    {
                    case 0:
                        team1.Add(p);
                        break;

                    case 1:
                        team2.Add(p);
                        break;

                    case 2:
                        team3.Add(p);
                        break;
                    }


                    //Give the guy some turrets
                    for (int j = 0; j < _config.NumTurretsPerNPC; j++)
                    {
                        var t = StructureFactory.CreateStructure(StructureTypes.LaserTurret, r.Next(-20, 20),
                                                                 r.Next(-20, 20), p, null, (int)p.CurrentAreaID, locatorService.PlayerLocator, true, dbm);

                        p.GetArea().AddStructure(t);
                    }

                    AddModulesToShip(tempShip, 5, cargoSynchronizer, galaxyIDManager);

                    npcCount++;
                }

                foreach (Planet pl in s.GetPlanets())
                {
                    npcCount = 0;
                    for (int i = 0; i < _config.NumNpcsPerPlanet; i++)
                    {
                        ShipTypes shipType = ShipTypes.Barge;
                        switch (npcCount % 3)
                        {
                        case 0:
                            shipType = ShipTypes.Penguin;
                            break;

                        case 1:
                            shipType = ShipTypes.Barge;
                            break;

                        case 2:
                            shipType = ShipTypes.Reaper;
                            break;
                        }

                        NPCPlayer p = pm.CreateNPCPlayer(locatorService);
                        pm.RegisterPlayer(p);
                        players.Add(p);
                        IShip tempShip = new NPCShip(ShipStatManager.TypeToStats[shipType], locatorService);
                        tempShip.ShipStats.ShieldType = ShieldTypes.QuickRegen;
                        tempShip.Id = IDManager.PopFreeID();
                        rm.RegisterObject(tempShip);
                        p.SetActiveShip(tempShip, MockServer.WarpManager);


                        tempShip.SetWeapon(WeaponManager.GetNewWeapon(WeaponTypes.MissileLauncher));


                        if (shipType == ShipTypes.Reaper)
                        {
                            tempShip.SetWeapon(WeaponManager.GetNewWeapon(WeaponTypes.LaserWave));
                            tempShip.SetWeapon(WeaponManager.GetNewWeapon(WeaponTypes.PlasmaCannon));
                        }
                        else
                        {
                            tempShip.SetWeapon(WeaponManager.GetNewWeapon(WeaponTypes.AltLaser));
                            tempShip.SetWeapon(WeaponManager.GetNewWeapon(WeaponTypes.LaserWave));
                        }



                        TransactionAddStatelessCargo tr = new TransactionAddStatelessCargo(tempShip,
                                                                                           StatelessCargoTypes.AmbassadorMissile, 666666, true);
                        cargoSynchronizer.RequestTransaction(tr);
                        await tr.ResultTask;

                        tr = new TransactionAddStatelessCargo(tempShip, StatelessCargoTypes.Biodome, 666666, true);
                        cargoSynchronizer.RequestTransaction(tr);
                        await tr.ResultTask;

                        tempShip.PosX = r.Next(-20, 20);
                        tempShip.PosY = r.Next(-20, 20);

                        Helpers.DebugWarp(pl, p, tempShip);


                        ships.Add(tempShip);

                        //Random team assignment
                        switch (npcCount % 2)
                        {
                        case 0:
                            team1.Add(p);
                            break;

                        case 1:
                            team2.Add(p);
                            break;

                        case 2:
                            team3.Add(p);
                            break;
                        }



                        AddModulesToShip(tempShip, 5, cargoSynchronizer, galaxyIDManager);

                        npcCount++;
                    }


                    teamManager.DebugCreateNewTeam(team1);
                    teamManager.DebugCreateNewTeam(team2);
                    teamManager.DebugCreateNewTeam(team3);
                }
            }

            return(players);
        }
예제 #4
0
        async Task AddCargoToPlayerShips(IEnumerable <IShip> ships, ILocalIDManager galaxyIDManager, GalaxyRegistrationManager registrationManager, CargoSynchronizer cargoSynchronizer)
        {
            //Making this into a grand test of transaction sequences, there's really no reason to put this all into one sequence
            CargoTransactionSequence cs = new CargoTransactionSequence();

            foreach (var s in ships)
            {
                for (int i = 0; i < _config.CARGO_NumTurrets; i++)//Sending ship state over a network might be painful while this is here...
                {
                    CargoLaserTurret            c = new CargoLaserTurret(galaxyIDManager.PopFreeID(), 666, new LaserWeaponStats());
                    TransactionAddStatefulCargo t = new TransactionAddStatefulCargo(s, c, true);
                    cs.Add(t);

                    registrationManager.RegisterObject(c);
                }

                TransactionAddStatelessCargo tr = new TransactionAddStatelessCargo(s, StatelessCargoTypes.AmbassadorMissile, _config.CARGO_NumMissiles, true);
                cs.Add(tr);

                tr = new TransactionAddStatelessCargo(s, StatelessCargoTypes.HellHoundMissile, _config.CARGO_NumMissiles, true);
                cs.Add(tr);
                tr = new TransactionAddStatelessCargo(s, StatelessCargoTypes.MissileType1, _config.CARGO_NumMissiles, true);
                cs.Add(tr);
                tr = new TransactionAddStatelessCargo(s, StatelessCargoTypes.MissileType2, _config.CARGO_NumMissiles, true);
                cs.Add(tr);
                tr = new TransactionAddStatelessCargo(s, StatelessCargoTypes.MissileType3, _config.CARGO_NumMissiles, true);
                cs.Add(tr);
                tr = new TransactionAddStatelessCargo(s, StatelessCargoTypes.MissileType4, _config.CARGO_NumMissiles, true);
                cs.Add(tr);

                tr = new TransactionAddStatelessCargo(s, StatelessCargoTypes.Biodome, _config.CARGO_NumBiodomes, true);
                cs.Add(tr);
            }
            cargoSynchronizer.RequestAtomicTransactionSequence(cs);
            await cs.ResultTask;

            if (cs.ResultTask.Result != CargoResult.Success)
            {
                ConsoleManager.WriteLine(cs.ResultTask.Result.ToString());
            }
            return;
        }
예제 #5
0
        /// <summary>
        /// Gives each player a ship
        /// Galaxy must already have been generated
        /// </summary>
        async Task CreateShips(IEnumerable <Player> players, GalaxyManager galaxyManager, LocalIDManager IDManager, GalaxyRegistrationManager rm, PlayerManager pm, LocatorService locatorService)
        {
            ships = new List <IShip>();
            int counter = 0;

            foreach (Player p in players)
            {
                List <WeaponTypes> weapons = new List <WeaponTypes>
                {
                    WeaponTypes.PlasmaCannon,
                    WeaponTypes.BC_Laser,
                    WeaponTypes.LaserWave,
                    WeaponTypes.GravBomber,
                    WeaponTypes.HurrDurr
                };

                ShipCreationProperties props = new ShipCreationProperties(counter + 10, counter + 10, (int)galaxyManager.SolAreaID, PilotTypes.Player, ShipTypes.BattleCruiser, weapons);
                var tempShip = _dbFillerUtils.ShipFactory.CreateShip(props);
                tempShip.SetPlayer(p);
                p.SetActiveShip(tempShip, MockServer.WarpManager);
                tempShip.CurrentEnergy = tempShip.ShipStats.Energy;


                ships.Add(tempShip);
                counter++;
            }
        }
예제 #6
0
 public static void Initialize(LocalIDManager idm, GalaxyRegistrationManager rm)
 {
     _localIDManager            = idm;
     _galaxyRegistrationManager = rm;
 }
예제 #7
0
        /// <summary>
        /// Initializes the entire server
        /// </summary>
        private void Initialize()
        {
            for (int i = 0; i < 20; i++)
            {
                msgAvgQue.Enqueue(0);
            }

            var rand = new Random(3);

            // Logging Enabled
            Logger.Initialize();

            _synchronizers = new List <ISynchronizer>();


            //Load configs
            ConnectionManagerConfig connectionManagerConfig = new ConnectionManagerConfig(new CoreNetworkConfig());
            GalacticProperties      galacticProperties      = new GalacticProperties();

            _consoleManager = new ConsoleManager();

            _projectileManager = new ProjectileManager();

            ConsoleManager.WriteLine("Starting database...", ConsoleMessageType.Startup);
            _databaseManager = new MongoDatabaseManager();

            ShipStatManager.ReadShipsFromDBSList(_databaseManager.GetStatsFromDBAsync().Result);
            ConsoleManager.WriteLine("Ship types loaded.", ConsoleMessageType.Startup);

            RedisConfig rc = new RedisConfig();

            _redisServer = new RedisServer(LogRedisError, LogRedisInfo, rc.Address);

            var slaveId = SlaveServerConfigService.GetFreeSlaveID(_redisServer).Result;

            _slaveServerConfigService = new SlaveServerConfigService(_redisServer, slaveId);

            _masterServerManager = new MasterServerManager(new MasterServerConfig(), new GalacticProperties(), _databaseManager, _databaseManager, _redisServer, _slaveServerConfigService);

            _cargoSynchronizer = new CargoSynchronizer();
            _synchronizers.Add(_cargoSynchronizer);

            connectionManagerConfig.MyConfig.Port = ConnectionManager.GetFreePort(28002, 28010);
            _connectionManager = new ConnectionManager();
            _connectionManager.Initialize(connectionManagerConfig);

            //Poll to listen to Lidgren until it is ready
            //LidgrenMessagePoller_Init initializationPoller = new LidgrenMessagePoller_Init(_connectionManager.Server, this);
            //initializationPoller.Poll();

            _galaxyIDManager      = new LocalIDManager(_masterServerManager, IDTypes.GalaxyID);
            _teamIDManager        = new LocalIDManager(_masterServerManager, IDTypes.TeamID);
            _accountIDManager     = new LocalIDManager(_masterServerManager, IDTypes.AccountID);
            _transactionIDManager = new LocalIDManager(_masterServerManager, IDTypes.TransactionID);

            _accountManager = new AccountManager(_accountIDManager, _databaseManager);

            _messageManager = new MessageManager(_connectionManager);

            _clientUpdateManager = new ClientUpdateManager(_playerManager);

            _playerManager = new PlayerManager(_databaseManager, _connectionManager, _redisServer, _galaxyIDManager, _clientUpdateManager);

            var chatCommands = new List <IChatCommand>()
            {
                new HelpCommand(),
                new ShoutCommand(_redisServer),
                new RadioCommand(),
                new TellCommand(_playerManager)
            };

            var asyncChatCommands = new List <IAsyncChatCommand>()
            {
                new AdminWarpCommand(_databaseManager, _redisServer, new Random())
            };

            _teamManager = new GlobalTeamManager(_teamIDManager, _connectionManager, _redisServer, _playerManager, _databaseManager);

            _galaxyManager = new GalaxyManager(galacticProperties.SolID, _teamManager);

            _chatManager = new ChatManager(chatCommands, asyncChatCommands, _playerManager, _messageManager, _redisServer);

            _warpManager = new WarpManager(_galaxyManager, _messageManager, _chatManager, _redisServer, _accountManager, _databaseManager);

            _shipManager = new ShipManager(_messageManager, _galaxyManager, _warpManager, _connectionManager, _databaseManager);

            _structureManager = new StructureManager(_databaseManager, _galaxyManager, _galaxyIDManager, _cargoSynchronizer);

            loginManager = new LoginManager(_accountManager, _playerManager, _connectionManager, _redisServer);

            // Todo: Convert everything over to ServerNetworkMessage to propogate full request context.
            _simulatorManager = new SimulatorManager(new SimulatorConfig(), _redisServer, (sender, container) => ProcessMessage(sender, new ServerNetworkMessage(container, null)));

            StructureStatManager.Initialize();

            ConsoleManager.WriteLine("Completed Initialization", ConsoleMessageType.Startup);

            _economyManager      = new EconomyManager(_transactionIDManager, _playerManager, _galaxyManager, _cargoSynchronizer, _shipManager, _databaseManager, _masterServerManager);
            _killManager         = new KillManager(_cargoSynchronizer, _playerManager, _galaxyManager, _messageManager, _connectionManager, _warpManager, _chatManager, _economyManager);
            _collisionManager    = new CollisionManager(_galaxyManager, _messageManager, _killManager, _projectileManager);
            _registrationManager = new GalaxyRegistrationManager(_galaxyManager, _shipManager, _collisionManager, _galaxyIDManager, _playerManager, _accountManager, _cargoSynchronizer, _structureManager);
            _warpManager.SetRegistrationManager(_registrationManager);//Gross, I know.
            _locatorService   = new LocatorService(_registrationManager, _playerManager, _galaxyManager, _shipManager, _accountManager, _teamManager, _teamManager, _messageManager, _structureManager, _masterServerManager);
            _msMessageHandler = new MasterServerMessageHandler((int)_masterServerManager.SlaveID, _redisServer, _connectionManager, _locatorService, _accountManager, _accountIDManager, _databaseManager, _galaxyManager, _galaxyIDManager, _playerManager, _shipManager, _registrationManager, _teamIDManager, _messageManager, _teamManager, _warpManager, _transactionIDManager, ProcessRoutedMessage);

            StructureFactory.Initialize(_galaxyIDManager, _registrationManager);
            ColonyFactory.Initialize(_galaxyIDManager, _registrationManager);

            dbSyncer = new DBSyncer(_databaseManager, _galaxyManager, _shipManager, _playerManager, _accountManager, _structureManager);

#if DEBUG
            _typesToExcludeIgnore.Add(MessageTypes.PositionUpdateData);
            _typesToExcludeIgnore.Add(MessageTypes.ShipFireRequest);
            _typesToExcludeIgnore.Add(MessageTypes.ProjectileCollisionReport);
            _typesToExcludeIgnore.Add(MessageTypes.StructureFireRequest);
            _typesToExcludeIgnore.Add(MessageTypes.ObjectPickupRequest);
#endif
        }
예제 #8
0
        public static PSystem GenerateStarsystem(int numberOfPlanets, int ID, GalaxyManager galaxyManager, LocalIDManager idManager, GalaxyRegistrationManager rm, LocatorService ls)
        {
            bool hasPort = false;

            // Add sun

            float size         = r.Next(100, 255) / 100f;
            float mass         = r.Next(50, 255) / 10f;
            float innerGravity = mass / 1875f;
            float outerGravity = innerGravity / 6f;

            var s    = (SunTypes[])Enum.GetValues(typeof(SunTypes));
            int type = r.Next(0, s.Length);

            var star = new Star(size, mass, innerGravity, outerGravity, s[type]);

            var system = new PSystem(star, ID, ls);

            system.AreaSize = baseBorder + r.Next(0, borderVariation);


            // Add Name
            system.AreaName = NameProvider.GetRandomName();


            rm.RegisterObject(system);


            for (int i = 0; i < numberOfPlanets; i++)
            {
                Planet planet;
                bool   SatisfiedWithResults = false;
                int    numAttempts          = MaxAttempts;
                system.IsCluster = false;
                int clusterType = 0;



                planet = new Planet(system, 0, ls);

                planet.AreaName = system.AreaName + " " + ToRoman(i + 1);

                if (r.Next(0, 101) > (100 - chanceOfCluster)) // Chance for planets to cluster
                {
                    system.IsCluster = true;
                    clusterType      = r.Next(0, clusterRadii.Count()); // Get which type of cluster
                }

                planet.Init(i, moonChance, minDistance, incrementOfOrbit, variationOfOrbit, 0,
                            r.Next());
                SatisfiedWithResults = !CheckForCollisions(system, planet); // True if we find any collisions.



                while (!SatisfiedWithResults)// While we're not content with the generation
                {
                    planet.Init(i, moonChance, minDistance, incrementOfOrbit, variationOfOrbit, 0,
                                r.Next());

                    SatisfiedWithResults = !CheckForCollisions(system, planet); // True if we find any collisions.

                    if (SatisfiedWithResults && system.IsCluster && i > 0)
                    {
                        SatisfiedWithResults = CheckForCollisions(system, planet, clusterRadii[clusterType]); // Cluster planets
                    }

                    numAttempts++;

                    if (numAttempts >= MaxAttempts && !system.IsCluster)
                    {
                        break; // Breaks out of infinite pass if it ever occurs
                    }
                    else if (numAttempts >= MaxAttempts && system.IsCluster)
                    {
                        i = 0; // Reset the whole operation because there's a bad system being generated.
                        foreach (Planet pll in system.GetPlanets())
                        {
                            system.RemovePlanet(pll);
                            rm.DeRegisterObject(pll);
                        }
                        break;
                    }
                }

                if (SatisfiedWithResults == false) // Don't add a colliding planet!
                {
                    //Logger.log(Log_Type.WARNING, "Skipped adding a planet due to MaxAttempts being too much");
                    continue;
                }
                planet.Id = idManager.PopFreeID();
                system.AddPlanet(planet);
                planet.ParentAreaID = system.Id;
                rm.RegisterObject(planet);

                if (system.AreaSize < planet.Distance - baseBorder) // If we're skinny, throw in a little extra space
                {
                    system.AreaSize = planet.Distance + baseBorder + r.Next(0, borderVariation);
                }
            }


            foreach (Planet p in system.GetPlanets())
            {
                _generateMoons(system, p, galaxyManager, idManager, rm, ls);
            }

            foreach (Planet m in system.GetMoons())
            {
                if (system.AreaSize < ls.AreaLocator.GetArea(m.IDToOrbit).Distance + m.Distance + baseBorder)
                {
                    // If we're skinny, throw in a little extra space
                    system.AreaSize = ls.AreaLocator.GetArea(m.IDToOrbit).Distance + m.Distance + baseBorder + r.Next(0, borderVariation);
                }
            }

            // Port Generation
            if (r.Next(0, 100) > 100 - portChance && !hasPort)
            {
                if (system.MoonCount > 0)
                {
                    for (int i = 0; i < system.MoonCount; i++)
                    {
                    }
                    int cr          = r.Next(0, system.MoonCount + 1); // Finds moon to turn into port.
                    int currentMoon = 0;                               // Used to get the moon

                    foreach (Planet m in system.GetMoons())
                    {
                        if (currentMoon == cr)
                        {
                            Planet moonToPort = m;
                            moonToPort.ParentAreaID = system.Id;
                            system.RemoveMoon(m);
                            rm.DeRegisterObject(m);

                            Port por = new Port(idManager.PopFreeID(), moonToPort, system.AreaName, ShipStatManager.StatShipList.ToList <ShipStats>(), ls); // Converts a moon into a port.
                            system.AddPort(por);
                            rm.RegisterObject(por);

                            hasPort = true;
                            break;
                        }
                        currentMoon++;
                    }
                }
            }


            return(system);
        }
예제 #9
0
        /// <summary>
        /// Generates n moons for a single planet, where n is divined from some mystical voodoo black magic related to planet.Scale
        /// </summary>
        /// <param name="system"></param>
        /// <param name="planet"></param>
        /// <param name="galaxyManager"></param>
        /// <param name="idManager"></param>
        /// <param name="rm"></param>
        /// <param name="pl"></param>
        /// <param name="al"></param>
        /// <param name="sl"></param>
        /// <param name="tl"></param>
        /// <param name="mem"></param>
        static void _generateMoons(PSystem system, Planet planet, GalaxyManager galaxyManager, LocalIDManager idManager, GalaxyRegistrationManager rm, LocatorService ls)
        {
            // If any moons, add them
            if (planet.HasMoons)
            {
                int parentID = planet.Id;

                int numMoons = 0;

                // Creates moon based on scale of size
                switch (planet.Scale)
                {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    planet.PlanetType = (PlanetTypes)r.Next(0, (int)PlanetTypes.OceanicSmall + 1);
                    planet.Scale     += 3; // Makes the small sprites scale better
                    break;

                case 6:
                case 7:
                    planet.PlanetType = (PlanetTypes)r.Next(0, (int)PlanetTypes.OceanicSmall + 1);
                    if (planet.PlanetType >= PlanetTypes.Crystalline &&
                        planet.PlanetType < PlanetTypes.Port)
                    {
                        planet.Scale += 3;     // Makes the small sprites scale better
                    }
                    numMoons = r.Next(3) + 2;
                    break;

                case 8:
                case 9:
                    numMoons = r.Next(2) + 3;
                    break;

                case 10:
                case 11:
                case 12:
                    numMoons = r.Next(3) + 3;
                    break;
                }

                for (int m = 0; m < numMoons; m++)
                {
                    Planet moon;

                    moon = new Planet(planet, idManager.PopFreeID(), ls);
                    InitializeMoon(moon, m, moonMinimumDistance, moonIncrementOfOrbit * m, moonVariationOfOrbit, planet, planet.Id,
                                   r.Next());


                    if (moon.PlanetType >= PlanetTypes.Crystalline &&
                        moon.PlanetType < PlanetTypes.Port)
                    {
                        moon.Scale += 3; // Makes the small sprites scale better
                    }
                    // #Yolo
                    moon.AreaName = planet.AreaName + "abcdefghijklmnopqrstuvwxyz"[m];

                    bool SatisfiedWithResults = false;
                    int  maxAttempts          = 200;
                    int  numAttempts          = 0;

                    while (!SatisfiedWithResults)// While we're not content with the generation
                    {
                        // Add moons
                        moon = new Planet(planet, moon.Id, ls);
                        InitializeMoon(moon, m, moonMinimumDistance, moonIncrementOfOrbit * m, moonVariationOfOrbit, planet, planet.Id,
                                       r.Next());
                        // Add another while here to check for maxDistance, as well as an If for if the system should follow that path of generation

                        SatisfiedWithResults = !CheckForCollisions(system, planet, moon, galaxyManager); // True if we find any collisions.
                        numAttempts++;

                        if (numAttempts >= maxAttempts)
                        {
                            break; // Breaks out of infinite pass if it ever occurs
                        }
                    }

                    if (!SatisfiedWithResults) // Don't add a colliding planet!
                    {
                        //Logger.log(Log_Type.ERROR, "Skipped adding a moon due to MaxAttempts being too much");
                        idManager.PushFreeID(moon.Id);

                        continue;
                    }


                    moon.IsMoon = true;
                    rm.RegisterObject(moon);
                    system.AddMoon(moon);
                    moon.ParentAreaID = system.Id;
                }
            }
        }
예제 #10
0
        public List <PSystem> generateAndFillGalaxy(int numPlanetsPerSystem, int solID, int numSystems, IEnumerable <PlanetLayout> layouts, GalaxyManager galaxyManager, LocalIDManager IDManager, GalaxyRegistrationManager rm, LocatorService ls)
        {
            float warpXPos = 0;
            float warpYPos = 0;
            int   amount   = 0;

            List <PSystem> generatedSystems = new List <PSystem>();

            PSystem sol = GenerateStarsystem(numPlanetsPerSystem, solID, galaxyManager, IDManager, rm, ls);

            sol.AreaName = "Sol";
            amount      += sol.PlanetCount;
            generatedSystems.Add(sol);

            for (int i = 0; i < numSystems - 1; i++)
            {
                tempsys = GenerateStarsystem(numPlanetsPerSystem, IDManager.PopFreeID(), galaxyManager, IDManager, rm, ls);

                amount += tempsys.PlanetCount;
                generatedSystems.Add(tempsys);

                //GalaxyManager.idToSystem.TryAdd(tempsys.ID, tempsys);
            }


            //ConsoleManager.WriteToFreeLine("Average of " + amount / numSystems + " planets per system");

            //Randomly link the systems
            //Take each system, iterate through the systems list and randomly connect them, or don't
            for (int i = 0; i < generatedSystems.Count; i++)
            {
                for (int j = i + 1; j < generatedSystems.Count; j++)
                {
                    if (r.Next(0, 100) <= 30) //30% probability of having the systems link
                    {
                        warpXPos = r.Next(-(generatedSystems[i].AreaSize - 200),
                                          (generatedSystems[i].AreaSize - 200));
                        warpYPos = -(int)Math.Sqrt(Math.Pow((generatedSystems[i].AreaSize - 200f), 2) - Math.Pow(warpXPos, 2));



                        tempWarp = new Warphole(warpXPos / 100, warpYPos / 100, generatedSystems[i].Id, generatedSystems[j].Id,
                                                (byte)generatedSystems[i].Warpholes.Count);
                        tempWarp.DestinationAreaID = generatedSystems[j].Id;
                        generatedSystems[i].Warpholes.Add(tempWarp);

                        //Normalizing the vector
                        warpXPos = warpXPos / (generatedSystems[i].AreaSize - 200f);
                        warpYPos = warpYPos / (generatedSystems[i].AreaSize - 200f);

                        //Converting it to the length for the other system, flipping to other side of system
                        warpXPos = -warpXPos * (generatedSystems[j].AreaSize - 200f);
                        warpYPos = -warpYPos * (generatedSystems[j].AreaSize - 200f);
                        tempWarp = new Warphole(warpXPos / 100, warpYPos / 100, generatedSystems[j].Id, generatedSystems[i].Id,
                                                (byte)generatedSystems[j].Warpholes.Count);
                        tempWarp.DestinationAreaID = generatedSystems[i].Id;
                        generatedSystems[j].Warpholes.Add(tempWarp);
                    }
                }
            }

            AssignPlanetLayouts(layouts, generatedSystems);

            return(generatedSystems);
        }