void ReverseConvertSigns(CommandArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                using (var reader = Database.QueryReader("SELECT COUNT(*) AS Count FROM Signs"))
                {
                    reader.Read();
                    if (reader.Get <int>("Count") > 1000)
                    {
                        e.Player.SendErrorMessage("The signs cannot be reverse-converted without losing data.");
                        return;
                    }
                }

                int i = 0;
                using (var reader = Database.QueryReader("SELECT Text, X, Y FROM Signs WHERE WorldID = @0", Main.worldID))
                {
                    while (reader.Read())
                    {
                        var sign  = (Main.sign[i++] = new Terraria.Sign());
                        sign.text = reader.Get <string>("Text");
                        sign.x    = reader.Get <int>("X");
                        sign.y    = reader.Get <int>("Y");
                    }
                }
                Database.Query("DELETE FROM Signs WHERE WorldID = @0", Main.worldID);
                e.Player.SendSuccessMessage("Reverse converted {0} signs.", i);
                if (i > 0)
                {
                    WorldFile.saveWorld();
                }
            });
        }
Esempio n. 2
0
        ////////////////

        public static void ExitToDesktop(bool save = true)
        {
            LogHelpers.Log("Exiting to desktop " + (save?"with save...":"..."));

            if (Main.netMode == 0)
            {
                if (save)
                {
                    Main.SaveSettings();
                }
                SocialAPI.Shutdown();
                Main.instance.Exit();
            }
            else
            {
                if (save)
                {
                    WorldFile.saveWorld();
                }
                Netplay.disconnect = true;
                if (Main.netMode == 1)
                {
                    SocialAPI.Shutdown();
                }
                Environment.Exit(0);
            }
        }
Esempio n. 3
0
        internal void generateDimension()
        {
            WorldFile.saveWorld(false, true);
            WorldGen.clearWorld();

            generator.GenerateDimension(Main.rand.Next());
            itemUseCooldown = 500;

            WorldGen.EveryTileFrame();
        }
Esempio n. 4
0
        private void generateDimension()
        {
            WorldFile.saveWorld(false, true);
            WorldGen.clearWorld();

            SolarWorldGen.GenerateSolarWorld(-1);
            itemUseCooldown = 500;

            //TUAWorld.solarWorldGen(mod);
            WorldGen.EveryTileFrame();
        }
Esempio n. 5
0
        public static List <GenPass> NormalGenPassList()
        {
            List <GenPass> list = new List <GenPass>
            {
                new SubworldGenPass(progress =>
                {
                    WorldGen.generateWorld(WorldGen._genRandSeed, progress);
                    WorldFile.saveWorld();
                })
            };

            return(list);
        }
Esempio n. 6
0
        private void TimerCallback(object state)
        {
            var shouldRestartServer = Check();

            TShockAPI.TShock.Log.ConsoleInfo("Deadlock: " + shouldRestartServer);
            if (!shouldRestartServer)
            {
                return;
            }

            TShockAPI.TShock.Log.ConsoleError("Server starts terminating...");
            WorldFile.saveWorld(false);
            Environment.Exit(1);
        }
Esempio n. 7
0
 private void Do_Save(object state)
 {
     try
     {
         CommandBoardcast.ConsoleSaveInfo();
         ServerSideCharacter2.PlayerDoc.SavePlayersData();
         ServerSideCharacter2.MailManager.Save();
         ConfigLoader.Save();
         WorldFile.saveWorld();
     }
     catch (Exception ex)
     {
         CommandBoardcast.ConsoleError(ex);
     }
 }
Esempio n. 8
0
        private void Quit(Action callback = null, bool saveWorld = false, bool savePlayer = false)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(QuitCallBack), callback);

            void QuitCallBack(object threadContext)
            {
                if (Main.netMode == NetmodeID.SinglePlayer)
                {
                    WorldFile.CacheSaveTime();
                }

                Main.invasionProgress            = 0;
                Main.invasionProgressDisplayLeft = 0;
                Main.invasionProgressAlpha       = 0f;
                Main.menuMode = 10;
                Main.gameMenu = true;
                Main.StopTrackedSounds();
                CaptureInterface.ResetFocus();
                Main.ActivePlayerFileData.StopPlayTimer();

                if (savePlayer)
                {
                    Player.SavePlayer(Main.ActivePlayerFileData, false);
                }

                if (Main.netMode == NetmodeID.SinglePlayer)
                {
                    if (saveWorld)
                    {
                        WorldFile.saveWorld();
                    }
                }
                else
                {
                    Netplay.disconnect = true;
                    Main.netMode       = NetmodeID.SinglePlayer;
                }

                Main.fastForwardTime = false;
                Main.UpdateSundial();
                Main.menuMode = 0;

                if (threadContext != null)
                {
                    ((Action)threadContext)();
                }
            }
        }
Esempio n. 9
0
 public override void Action(CommandCaller caller, string input, string[] args)
 {
     try
     {
         Console.WriteLine(GameLanguage.GetText("savingText"));
         ServerSideCharacter2.PlayerDoc.SavePlayersData();
         ServerSideCharacter2.MailManager.Save();
         ConfigLoader.Save();
         WorldFile.saveWorld();
         Console.WriteLine(GameLanguage.GetText("savedText"));
     }
     catch (Exception ex)
     {
         CommandBoardcast.ConsoleError(ex);
     }
 }
Esempio n. 10
0
 private void SaveWorker()
 {
     while (true)
     {
         lock (_saveLock)
         {
             // NOTE: lock for the entire process so wait works in SaveWorld
             if (_saveQueue.Count > 0)
             {
                 SaveTask task = _saveQueue.Dequeue();
                 if (null == task)
                 {
                     return;
                 }
                 else
                 {
                     // Ensure that save handler errors don't bubble up and cause a recursive call
                     // These can be caused by an unexpected error such as a bad or out of date plugin
                     try
                     {
                         if (task.direct)
                         {
                             OnSaveWorld(new WorldSaveEventArgs());
                             WorldFile.saveWorld(task.resetTime);
                         }
                         else
                         {
                             WorldFile.saveWorld(task.resetTime);
                         }
                         TShock.Log.ConsoleInfo("Mapa Salvo");
                         TShock.AllSendMessagev2("Mapa Salvo",
                                                 "World Saved", Color.SeaGreen);
                         TShock.Log.Info(string.Format("World saved at ({0})", Main.worldPathName));
                     }
                     catch (Exception e)
                     {
                         TShock.AllSendMessagev2("O salvamento do mapa falhou",
                                                 "World saved failed", Color.Red);
                         TShock.Log.Error("World saved failed");
                         TShock.Log.Error(e.ToString());
                     }
                 }
             }
         }
         _wh.WaitOne();
     }
 }
Esempio n. 11
0
 internal static void do_worldGenCallBack(ProjectDimensionHook.orig_do_worldGenCallBack orig, object threadContext)
 {
     Main.PlaySound(10, -1, -1, 1, 1f, 0f);
     foreach (ModDimension handler in Dimlibs.dimensionInstanceHandlers.Values)
     {
         Dimlibs.dimension = handler.URN;
         WorldGen.clearWorld();
         handler.GenerateDimension(Main.ActiveWorldFileData.Seed, threadContext as GenerationProgress);
         handler.handler.Save();
         WorldFile.saveWorld(Main.ActiveWorldFileData.IsCloudSave, true);
     }
     if (Main.menuMode == 10 || Main.menuMode == 888)
     {
         Main.menuMode = 6;
     }
     Main.PlaySound(10, -1, -1, 1, 1f, 0f);
 }
Esempio n. 12
0
        void OnPostInitialize(EventArgs e)
        {
            int converted = 0;

            foreach (Terraria.Sign s in Main.sign)
            {
                if (s != null)
                {
                    Database.Query("INSERT INTO Signs (X, Y, Text, WorldID) VALUES (@0, @1, @2, @3)",
                                   s.x, s.y, s.text, Main.worldID);
                    converted++;
                }
            }
            if (converted > 0)
            {
                TSPlayer.Server.SendSuccessMessage("[InfiniteSigns] Converted {0} sign{1}.", converted, converted == 1 ? "" : "s");
                WorldFile.saveWorld();
            }
        }
Esempio n. 13
0
 private void SaveWorker()
 {
     while (true)
     {
         lock (_saveLock)
         {
             // NOTE: lock for the entire process so wait works in SaveWorld
             if (_saveQueue.Count > 0)
             {
                 SaveTask task = _saveQueue.Dequeue();
                 if (null == task)
                 {
                     return;
                 }
                 else
                 {
                     // Ensure that save handler errors don't bubble up and cause a recursive call
                     // These can be caused by an unexpected error such as a bad or out of date plugin
                     try
                     {
                         if (task.direct)
                         {
                             OnSaveWorld(new WorldSaveEventArgs());
                             WorldFile.saveWorld(task.resetTime);
                         }
                         else
                         {
                             WorldFile.saveWorld(task.resetTime);
                         }
                         TShock.Utils.Broadcast("地图保存完毕。", Color.Yellow);
                         TShock.Log.Info(string.Format("World saved at ({0})", Main.worldPathName));
                     }
                     catch (Exception e)
                     {
                         TShock.Log.Error("地图保存失败。");
                         TShock.Log.Error(e.ToString());
                     }
                 }
             }
         }
         _wh.WaitOne();
     }
 }
Esempio n. 14
0
        public override bool UseItem(Player player)
        {
            DimPlayer p = player.GetModPlayer <DimPlayer>();

            FieldInfo info = typeof(FileData).GetField("_path", BindingFlags.Instance | BindingFlags.NonPublic);
            string    get  = (string)info.GetValue(Main.ActiveWorldFileData);

            if (itemUseCooldown == 0)
            {
                WorldFile.saveWorld(false, true);
                if (p.getCurrentDimension() != dimensionName)
                {
                    p.setCurrentDimension(dimensionName);
                    if (dimensionMessage != null)
                    {
                        Main.NewText("Get dunked m8", Color.Orange);
                    }
                    else
                    {
                        Main.NewText("You are entering into a custom dimension...", Color.Orange);
                    }
                    if (!File.Exists(Main.SavePath + "/World/" + (dimensionName + "/" + Main.worldName + ".wld").Replace(' ', '_')))
                    {
                        info.SetValue(Main.ActiveWorldFileData, Main.SavePath + "/World/" + (dimensionName + "/" + Main.worldName + ".wld").Replace(' ', '_'));
                        generateDimension();
                        p.player.Spawn();
                        return(true);
                    }

                    info.SetValue(Main.ActiveWorldFileData, Main.SavePath + "/World/" + (dimensionName + "/" + Main.worldName + ".wld").Replace(' ', '_'));
                    itemUseCooldown = 500;
                    WorldGen.EveryTileFrame();
                    WorldGen.playWorld();
                    return(true);
                }
                info.SetValue(Main.ActiveWorldFileData, Main.SavePath + "/World/" + (Main.worldName + ".wld").Replace(' ', '_'));
                p.setCurrentDimension("overworld");
                itemUseCooldown = 500;
                WorldGen.playWorld();
                return(true);
            }
            return(false);
        }
Esempio n. 15
0
 void ConvertSigns(CommandArgs e)
 {
     Task.Factory.StartNew(() =>
     {
         int converted = 0;
         foreach (Terraria.Sign s in Main.sign)
         {
             if (s != null)
             {
                 Database.Query("INSERT INTO Signs (X, Y, Text, WorldID) VALUES (@0, @1, @2, @3)", s.x, s.y, s.text, Main.worldID);
                 converted++;
             }
         }
         e.Player.SendSuccessMessage("Converted {0} sign{1}.", converted, converted == 1 ? "" : "s");
         if (converted > 0)
         {
             WorldFile.saveWorld();
         }
     });
 }
Esempio n. 16
0
        public override bool UseItem(Player player)
        {
            TUAPlayer p = player.GetModPlayer <TUAPlayer>(mod);

            FieldInfo info = typeof(FileData).GetField("_path", BindingFlags.Instance | BindingFlags.NonPublic);
            string    get  = (string)info.GetValue(Main.ActiveWorldFileData);

            if (itemUseCooldown == 0)
            {
                WorldFile.saveWorld(false, true);
                if (p.currentDimension != "solar")
                {
                    p.currentDimension = "solar";
                    Main.NewText("You are entering into the solar dimension...", Color.Orange);



                    if (!File.Exists(Main.SavePath + "/World/Solar/" + Main.worldName + ".wld"))
                    {
                        info.SetValue(Main.ActiveWorldFileData, Main.SavePath + "/World/Solar/" + Main.worldName + ".wld");
                        generateDimension();
                        p.player.Spawn();
                        return(true);
                    }

                    info.SetValue(Main.ActiveWorldFileData, Main.SavePath + "/World/Solar/" + Main.worldName + ".wld");
                    itemUseCooldown = 500;
                    WorldGen.EveryTileFrame();
                    WorldGen.playWorld();
                    return(true);
                }
                info.SetValue(Main.ActiveWorldFileData, Main.SavePath + "/World/" + Main.worldName + ".wld");
                p.currentDimension = "overworld";
                itemUseCooldown    = 500;
                WorldGen.playWorld();
                return(true);
            }
            return(false);
        }
Esempio n. 17
0
        private static void EnsureLocalPlayerIsPresent()
        {
            if (!Main.autoShutdown)
            {
                return;
            }
            var flag = false;

            for (var i = 0; i < 255; i++)
            {
                if (Netplay.Clients[i].State == 10 && Netplay.Clients[i].Socket.GetRemoteAddress().IsLocalHost())
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                Console.WriteLine(Language.GetTextValue("Net.ServerAutoShutdown"));
                WorldFile.saveWorld();
                Netplay.disconnect = true;
            }
        }
        public override void PostUpdateEverything()
        {
            // ModContent.GetInstance<AmbienceHelper>().HandleAmbiences();
            Main.raining  = false;
            Main.rainTime = 0;
            Main.maxRain  = 0;
            musicType     = ModContent.GetInstance <SpookyConfigClient>().musicType;
            playMusicTimer_UseOnce++;
            // Main.NewText($"X: {(int)Main.MouseWorld.X / 16} | Y: {(int)Main.MouseWorld.Y / 16}");
            updateGameZoomTargetValue = Main.GameZoomTarget;
            var player = Main.player[Main.myPlayer];

            if (Main.hasFocus)
            {
                player.GetModPlayer <SpookyPlayer>().deathTextTimer--;
                if (player.GetModPlayer <SpookyPlayer>().deathTextTimer < 0)
                {
                    player.GetModPlayer <SpookyPlayer>().deathTextTimer = 0;
                }
            }

            if (player.respawnTimer == 25)
            {
                if (Main.worldName == SpookyTerrariaUtils.slenderWorldName)
                {
                    SpookyPlayer.Pages = 0;
                    SpookyTerrariaUtils.RemoveAllPossiblePagePositions();
                    Main.SaveSettings();

                    if (Main.netMode == NetmodeID.SinglePlayer)
                    {
                        WorldFile.CacheSaveTime();
                    }

                    Main.invasionProgress            = 0;
                    Main.invasionProgressDisplayLeft = 0;
                    Main.invasionProgressAlpha       = 0f;
                    Main.menuMode = 10;
                    Main.StopTrackedSounds();
                    CaptureInterface.ResetFocus();
                    Main.ActivePlayerFileData.StopPlayTimer();

                    Player.SavePlayer(Main.ActivePlayerFileData);

                    if (Main.netMode == NetmodeID.SinglePlayer)
                    {
                        WorldFile.saveWorld();
                    }
                    else
                    {
                        Netplay.disconnect = true;
                        Main.netMode       = NetmodeID.SinglePlayer;
                    }

                    Main.fastForwardTime = false;
                    Main.UpdateSundial();
                    Main.menuMode = MenuModeID.MainMenu;
                }
            }

            Main.soundInstanceMenuTick.Volume  = 0f;
            Main.soundInstanceMenuOpen.Volume  = 0f;
            Main.soundInstanceMenuClose.Volume = 0f;
            if (Main.netMode != NetmodeID.Server)
            {
                for (var i = 0; i < Main.maxNPCs; i++)
                {
                    var npc = Main.npc[i];
                    if (npc.type == ModContent.NPCType <Stalker>())
                    {
                        Filters.Scene["Darkness"].GetShader().UseIntensity(player.Distance(npc.Center) / 8);
                    }
                }
            }

            Main.slimeRain        = false;
            Main.invasionSize     = 0;
            Main.invasionProgress = 0;
            if (!beatGame)
            {
                Main.dayTime = false;
                Main.time    = 1800;
            }
            else
            {
                Main.dayTime = true;
                Main.time    = 18000;
            }
        }
Esempio n. 19
0
        public static void ServerLoop(object threadContext)
        {
            Netplay.ResetNetDiag();
            if (Main.rand == null)
            {
                Main.rand = new UnifiedRandom((int)DateTime.Now.Ticks);
            }
            Main.myPlayer      = (int)byte.MaxValue;
            Netplay.ServerIP   = IPAddress.Any;
            Main.menuMode      = 14;
            Main.statusText    = Lang.menu[8].Value;
            Main.netMode       = 2;
            Netplay.disconnect = false;
            for (int index = 0; index < 256; ++index)
            {
                Netplay.Clients[index] = new RemoteClient();
                Netplay.Clients[index].Reset();
                Netplay.Clients[index].Id         = index;
                Netplay.Clients[index].ReadBuffer = new byte[1024];
            }
            Netplay.TcpListener = (ISocket) new TcpSocket();
            if (!Netplay.disconnect)
            {
                if (!Netplay.StartListening())
                {
                    Main.menuMode      = 15;
                    Main.statusText    = Language.GetTextValue("Error.TriedToRunServerTwice");
                    Netplay.disconnect = true;
                }
                Main.statusText = Language.GetTextValue("CLI.ServerStarted");
            }
            if (Netplay.UseUPNP)
            {
                try
                {
                    Netplay.OpenPort();
                }
                catch
                {
                }
            }
            int num1 = 0;

            while (!Netplay.disconnect)
            {
                if (!Netplay.IsListening)
                {
                    int num2 = -1;
                    for (int index = 0; index < Main.maxNetPlayers; ++index)
                    {
                        if (!Netplay.Clients[index].IsConnected())
                        {
                            num2 = index;
                            break;
                        }
                    }
                    if (num2 >= 0)
                    {
                        if (Main.ignoreErrors)
                        {
                            try
                            {
                                Netplay.StartListening();
                                Netplay.IsListening = true;
                            }
                            catch
                            {
                            }
                        }
                        else
                        {
                            Netplay.StartListening();
                            Netplay.IsListening = true;
                        }
                    }
                }
                int num3 = 0;
                for (int index = 0; index < 256; ++index)
                {
                    if (NetMessage.buffer[index].checkBytes)
                    {
                        NetMessage.CheckBytes(index);
                    }
                    if (Netplay.Clients[index].PendingTermination)
                    {
                        Netplay.Clients[index].Reset();
                        NetMessage.SyncDisconnectedPlayer(index);
                    }
                    else if (Netplay.Clients[index].IsConnected())
                    {
                        if (!Netplay.Clients[index].IsActive)
                        {
                            Netplay.Clients[index].State = 0;
                        }
                        Netplay.Clients[index].IsActive = true;
                        ++num3;
                        if (!Netplay.Clients[index].IsReading)
                        {
                            try
                            {
                                if (Netplay.Clients[index].Socket.IsDataAvailable())
                                {
                                    Netplay.Clients[index].IsReading = true;
                                    Netplay.Clients[index].Socket.AsyncReceive(Netplay.Clients[index].ReadBuffer, 0, Netplay.Clients[index].ReadBuffer.Length, new SocketReceiveCallback(Netplay.Clients[index].ServerReadCallBack), (object)null);
                                }
                            }
                            catch
                            {
                                Netplay.Clients[index].PendingTermination = true;
                            }
                        }
                        if (Netplay.Clients[index].StatusMax > 0 && Netplay.Clients[index].StatusText2 != "")
                        {
                            if (Netplay.Clients[index].StatusCount >= Netplay.Clients[index].StatusMax)
                            {
                                Netplay.Clients[index].StatusText  = Language.GetTextValue("Net.ClientStatusComplete", (object)Netplay.Clients[index].Socket.GetRemoteAddress(), (object)Netplay.Clients[index].Name, (object)Netplay.Clients[index].StatusText2);
                                Netplay.Clients[index].StatusText2 = "";
                                Netplay.Clients[index].StatusMax   = 0;
                                Netplay.Clients[index].StatusCount = 0;
                            }
                            else
                            {
                                Netplay.Clients[index].StatusText = "(" + (object)Netplay.Clients[index].Socket.GetRemoteAddress() + ") " + Netplay.Clients[index].Name + " " + Netplay.Clients[index].StatusText2 + ": " + (object)(int)((double)Netplay.Clients[index].StatusCount / (double)Netplay.Clients[index].StatusMax * 100.0) + "%";
                            }
                        }
                        else if (Netplay.Clients[index].State == 0)
                        {
                            Netplay.Clients[index].StatusText = Language.GetTextValue("Net.ClientConnecting", (object)string.Format("({0}) {1}", (object)Netplay.Clients[index].Socket.GetRemoteAddress(), (object)Netplay.Clients[index].Name));
                        }
                        else if (Netplay.Clients[index].State == 1)
                        {
                            Netplay.Clients[index].StatusText = Language.GetTextValue("Net.ClientSendingData", (object)Netplay.Clients[index].Socket.GetRemoteAddress(), (object)Netplay.Clients[index].Name);
                        }
                        else if (Netplay.Clients[index].State == 2)
                        {
                            Netplay.Clients[index].StatusText = Language.GetTextValue("Net.ClientRequestedWorldInfo", (object)Netplay.Clients[index].Socket.GetRemoteAddress(), (object)Netplay.Clients[index].Name);
                        }
                        else if (Netplay.Clients[index].State != 3)
                        {
                            if (Netplay.Clients[index].State == 10)
                            {
                                try
                                {
                                    Netplay.Clients[index].StatusText = Language.GetTextValue("Net.ClientPlaying", (object)Netplay.Clients[index].Socket.GetRemoteAddress(), (object)Netplay.Clients[index].Name);
                                }
                                catch (Exception ex)
                                {
                                    Netplay.Clients[index].PendingTermination = true;
                                }
                            }
                        }
                    }
                    else if (Netplay.Clients[index].IsActive)
                    {
                        Netplay.Clients[index].PendingTermination = true;
                    }
                    else
                    {
                        Netplay.Clients[index].StatusText2 = "";
                        if (index < (int)byte.MaxValue)
                        {
                            bool active = Main.player[index].active;
                            Main.player[index].active = false;
                            if (active)
                            {
                                Player.Hooks.PlayerDisconnect(index);
                            }
                        }
                    }
                }
                ++num1;
                if (num1 > 10)
                {
                    Thread.Sleep(1);
                    num1 = 0;
                }
                else
                {
                    Thread.Sleep(0);
                }
                if (!WorldGen.saveLock && !Main.dedServ)
                {
                    Main.statusText = num3 != 0 ? Language.GetTextValue("Net.ClientsConnected", (object)num3) : Language.GetTextValue("Net.WaitingForClients");
                }
                Netplay.anyClients      = num3 != 0;
                Netplay.IsServerRunning = true;
            }
            Netplay.StopListening();
            try
            {
                Netplay.closePort();
            }
            catch
            {
            }
            for (int index = 0; index < 256; ++index)
            {
                Netplay.Clients[index].Reset();
            }
            if (Main.menuMode != 15)
            {
                Main.netMode  = 0;
                Main.menuMode = 10;
                WorldFile.saveWorld();
                do
                {
                    ;
                }while (WorldGen.saveLock);
                Main.menuMode = 0;
            }
            else
            {
                Main.netMode = 0;
            }
            Main.myPlayer = 0;
        }
Esempio n. 20
0
        public static void ServerLoop(object threadContext)
        {
            Netplay.ResetNetDiag();
            if (Main.rand == null)
            {
                Main.rand = new Random((int)DateTime.Now.Ticks);
            }
            if (WorldGen.genRand == null)
            {
                WorldGen.genRand = new Random((int)DateTime.Now.Ticks);
            }
            Main.myPlayer      = (int)byte.MaxValue;
            Netplay.ServerIP   = IPAddress.Any;
            Main.menuMode      = 14;
            Main.statusText    = "Starting server...";
            Main.netMode       = 2;
            Netplay.disconnect = false;
            for (int index = 0; index < 256; ++index)
            {
                Netplay.Clients[index] = new RemoteClient();
                Netplay.Clients[index].Reset();
                Netplay.Clients[index].Id         = index;
                Netplay.Clients[index].ReadBuffer = new byte[1024];
            }
            Netplay.TcpListener = (ISocket) new TcpSocket();
            if (!Netplay.disconnect)
            {
                if (!Netplay.StartListening())
                {
                    Main.menuMode      = 15;
                    Main.statusText    = "Tried to run two servers on the same PC";
                    Netplay.disconnect = true;
                }
                Main.statusText = "Server started";
            }
            if (Netplay.UseUPNP)
            {
                try
                {
                    Netplay.OpenPort();
                }
                catch
                {
                }
            }
            int num1 = 0;

            while (!Netplay.disconnect)
            {
                if (!Netplay.IsListening)
                {
                    int num2 = -1;
                    for (int index = 0; index < Main.maxNetPlayers; ++index)
                    {
                        if (!Netplay.Clients[index].Socket.IsConnected())
                        {
                            num2 = index;
                            break;
                        }
                    }
                    if (num2 >= 0)
                    {
                        if (Main.ignoreErrors)
                        {
                            try
                            {
                                Netplay.StartListening();
                                Netplay.IsListening = true;
                            }
                            catch
                            {
                            }
                        }
                        else
                        {
                            Netplay.StartListening();
                            Netplay.IsListening = true;
                        }
                    }
                }
                int num3 = 0;
                for (int bufferIndex = 0; bufferIndex < 256; ++bufferIndex)
                {
                    if (NetMessage.buffer[bufferIndex].checkBytes)
                    {
                        NetMessage.CheckBytes(bufferIndex);
                    }
                    if (Netplay.Clients[bufferIndex].PendingTermination)
                    {
                        Netplay.Clients[bufferIndex].Reset();
                        NetMessage.syncPlayers();
                    }
                    else if (Netplay.Clients[bufferIndex].Socket.IsConnected())
                    {
                        if (!Netplay.Clients[bufferIndex].IsActive)
                        {
                            Netplay.Clients[bufferIndex].State = 0;
                        }
                        Netplay.Clients[bufferIndex].IsActive = true;
                        ++num3;
                        if (!Netplay.Clients[bufferIndex].IsReading)
                        {
                            try
                            {
                                if (Netplay.Clients[bufferIndex].Socket.IsDataAvailable())
                                {
                                    Netplay.Clients[bufferIndex].IsReading = true;
                                    Netplay.Clients[bufferIndex].Socket.AsyncReceive(Netplay.Clients[bufferIndex].ReadBuffer, 0, Netplay.Clients[bufferIndex].ReadBuffer.Length, new SocketReceiveCallback(Netplay.Clients[bufferIndex].ServerReadCallBack), (object)null);
                                }
                            }
                            catch
                            {
                                Netplay.Clients[bufferIndex].PendingTermination = true;
                            }
                        }
                        if (Netplay.Clients[bufferIndex].StatusMax > 0 && Netplay.Clients[bufferIndex].StatusText2 != "")
                        {
                            if (Netplay.Clients[bufferIndex].StatusCount >= Netplay.Clients[bufferIndex].StatusMax)
                            {
                                Netplay.Clients[bufferIndex].StatusText  = "(" + (object)Netplay.Clients[bufferIndex].Socket.GetRemoteAddress() + ") " + Netplay.Clients[bufferIndex].Name + " " + Netplay.Clients[bufferIndex].StatusText2 + ": Complete!";
                                Netplay.Clients[bufferIndex].StatusText2 = "";
                                Netplay.Clients[bufferIndex].StatusMax   = 0;
                                Netplay.Clients[bufferIndex].StatusCount = 0;
                            }
                            else
                            {
                                Netplay.Clients[bufferIndex].StatusText = "(" + (object)Netplay.Clients[bufferIndex].Socket.GetRemoteAddress() + ") " + Netplay.Clients[bufferIndex].Name + " " + Netplay.Clients[bufferIndex].StatusText2 + ": " + (string)(object)(int)((double)Netplay.Clients[bufferIndex].StatusCount / (double)Netplay.Clients[bufferIndex].StatusMax * 100.0) + "%";
                            }
                        }
                        else if (Netplay.Clients[bufferIndex].State == 0)
                        {
                            Netplay.Clients[bufferIndex].StatusText = "(" + (object)Netplay.Clients[bufferIndex].Socket.GetRemoteAddress() + ") " + Netplay.Clients[bufferIndex].Name + " is connecting...";
                        }
                        else if (Netplay.Clients[bufferIndex].State == 1)
                        {
                            Netplay.Clients[bufferIndex].StatusText = "(" + (object)Netplay.Clients[bufferIndex].Socket.GetRemoteAddress() + ") " + Netplay.Clients[bufferIndex].Name + " is sending player data...";
                        }
                        else if (Netplay.Clients[bufferIndex].State == 2)
                        {
                            Netplay.Clients[bufferIndex].StatusText = "(" + (object)Netplay.Clients[bufferIndex].Socket.GetRemoteAddress() + ") " + Netplay.Clients[bufferIndex].Name + " requested world information";
                        }
                        else if (Netplay.Clients[bufferIndex].State != 3)
                        {
                            if (Netplay.Clients[bufferIndex].State == 10)
                            {
                                try
                                {
                                    Netplay.Clients[bufferIndex].StatusText = "(" + (object)Netplay.Clients[bufferIndex].Socket.GetRemoteAddress() + ") " + Netplay.Clients[bufferIndex].Name + " is playing";
                                }
                                catch
                                {
                                    Netplay.Clients[bufferIndex].PendingTermination = true;
                                }
                            }
                        }
                    }
                    else if (Netplay.Clients[bufferIndex].IsActive)
                    {
                        Netplay.Clients[bufferIndex].PendingTermination = true;
                    }
                    else
                    {
                        Netplay.Clients[bufferIndex].StatusText2 = "";
                        if (bufferIndex < (int)byte.MaxValue)
                        {
                            Main.player[bufferIndex].active = false;
                        }
                    }
                }
                ++num1;
                if (num1 > 10)
                {
                    Thread.Sleep(1);
                    num1 = 0;
                }
                else
                {
                    Thread.Sleep(0);
                }
                if (!WorldGen.saveLock && !Main.dedServ)
                {
                    Main.statusText = num3 != 0 ? (string)(object)num3 + (object)" clients connected" : "Waiting for clients...";
                }
                Netplay.anyClients      = num3 != 0;
                Netplay.IsServerRunning = true;
            }
            Netplay.StopListening();
            try
            {
                Netplay.closePort();
            }
            catch
            {
            }
            for (int index = 0; index < 256; ++index)
            {
                Netplay.Clients[index].Reset();
            }
            if (Main.menuMode != 15)
            {
                Main.netMode  = 0;
                Main.menuMode = 10;
                WorldFile.saveWorld();
                while (WorldGen.saveLock)
                {
                    ;
                }
                Main.menuMode = 0;
            }
            else
            {
                Main.netMode = 0;
            }
            Main.myPlayer = 0;
        }
Esempio n. 21
0
        public static void SaveWorld()
        {
            void SaveWorld(object threadContext) => WorldFile.saveWorld();

            ThreadPool.QueueUserWorkItem(new WaitCallback(SaveWorld), 1);
        }
Esempio n. 22
0
        public static void ServerLoop(object threadContext)
        {
            Netplay.ResetNetDiag();
            if (Main.rand == null)
            {
                Main.rand = new Random((int)DateTime.Now.Ticks);
            }
            if (WorldGen.genRand == null)
            {
                WorldGen.genRand = new Random((int)DateTime.Now.Ticks);
            }
            Main.myPlayer      = 255;
            Main.menuMode      = 14;
            Main.statusText    = "Starting server...";
            Main.netMode       = 2;
            Netplay.disconnect = false;
            for (int i = 0; i < 256; i++)
            {
                Netplay.Clients[i] = new RemoteClient();
                Netplay.Clients[i].Reset();
                Netplay.Clients[i].Id         = i;
                Netplay.Clients[i].ReadBuffer = new byte[1024];
            }
            Netplay.TcpListener = new TcpSocket();
            if (!Netplay.disconnect)
            {
                if (!Netplay.StartListening())
                {
                    Main.menuMode      = 15;
                    Main.statusText    = "Tried to run two servers on the same PC";
                    Netplay.disconnect = true;
                }
                Main.statusText = "Server started";
            }
            int num = 0;

            while (!Netplay.disconnect)
            {
                if (!Netplay.IsListening)
                {
                    int num2 = -1;
                    for (int j = 0; j < Main.maxNetPlayers; j++)
                    {
                        if (!Netplay.Clients[j].Socket.IsConnected())
                        {
                            num2 = j;
                            break;
                        }
                    }
                    if (num2 >= 0)
                    {
                        if (Main.ignoreErrors)
                        {
                            try
                            {
                                Netplay.StartListening();
                                Netplay.IsListening = true;
                                goto IL_16A;
                            }
                            catch
                            {
                                goto IL_16A;
                            }
                        }
                        Netplay.StartListening();
                        Netplay.IsListening = true;
                    }
                }
IL_16A:
                int num3 = 0;
                for (int k = 0; k < 256; k++)
                {
                    if (NetMessage.buffer[k].checkBytes)
                    {
                        NetMessage.CheckBytes(k);
                    }
                    if (Netplay.Clients[k].PendingTermination)
                    {
                        ServerApi.Hooks.InvokeServerLeave(Netplay.Clients[k].Id);
                        Netplay.Clients[k].Reset();
                        NetMessage.syncPlayers(sendInventory: false, sendPlayerInfo: false);
                    }
                    else
                    {
                        if (Netplay.Clients[k].Socket.IsConnected())
                        {
                            if (!Netplay.Clients[k].IsActive)
                            {
                                Netplay.Clients[k].State = 0;
                            }
                            Netplay.Clients[k].IsActive = true;
                            num3++;
                            if (!Netplay.Clients[k].IsReading)
                            {
                                try
                                {
                                    if (Netplay.Clients[k].Socket.IsDataAvailable())
                                    {
                                        Netplay.Clients[k].IsReading = true;
                                        Netplay.Clients[k].Socket.AsyncReceive(Netplay.Clients[k].ReadBuffer, 0, Netplay.Clients[k].ReadBuffer.Length, new SocketReceiveCallback(Netplay.Clients[k].ServerReadCallBack), null);
                                    }
                                }
                                catch
                                {
                                    Netplay.Clients[k].PendingTermination = true;
                                }
                            }
                            if (Netplay.Clients[k].StatusMax > 0 && Netplay.Clients[k].StatusText2 != "")
                            {
                                if (Netplay.Clients[k].StatusCount >= Netplay.Clients[k].StatusMax)
                                {
                                    Netplay.Clients[k].StatusText = string.Concat(new object[]
                                    {
                                        "(",
                                        Netplay.Clients[k].Socket.GetRemoteAddress(),
                                        ") ",
                                        Netplay.Clients[k].Name,
                                        " ",
                                        Netplay.Clients[k].StatusText2,
                                        ": Complete!"
                                    });
                                    Netplay.Clients[k].StatusText2 = "";
                                    Netplay.Clients[k].StatusMax   = 0;
                                    Netplay.Clients[k].StatusCount = 0;
                                    continue;
                                }
                                Netplay.Clients[k].StatusText = string.Concat(new object[]
                                {
                                    "(",
                                    Netplay.Clients[k].Socket.GetRemoteAddress(),
                                    ") ",
                                    Netplay.Clients[k].Name,
                                    " ",
                                    Netplay.Clients[k].StatusText2,
                                    ": ",
                                    (int)((float)Netplay.Clients[k].StatusCount / (float)Netplay.Clients[k].StatusMax * 100f),
                                    "%"
                                });
                                continue;
                            }
                            else
                            {
                                if (Netplay.Clients[k].State == 0)
                                {
                                    Netplay.Clients[k].StatusText = string.Concat(new object[]
                                    {
                                        "(",
                                        Netplay.Clients[k].Socket.GetRemoteAddress(),
                                        ") ",
                                        Netplay.Clients[k].Name,
                                        " is connecting..."
                                    });
                                    continue;
                                }
                                if (Netplay.Clients[k].State == 1)
                                {
                                    Netplay.Clients[k].StatusText = string.Concat(new object[]
                                    {
                                        "(",
                                        Netplay.Clients[k].Socket.GetRemoteAddress(),
                                        ") ",
                                        Netplay.Clients[k].Name,
                                        " is sending player data..."
                                    });
                                    continue;
                                }
                                if (Netplay.Clients[k].State == 2)
                                {
                                    Netplay.Clients[k].StatusText = string.Concat(new object[]
                                    {
                                        "(",
                                        Netplay.Clients[k].Socket.GetRemoteAddress(),
                                        ") ",
                                        Netplay.Clients[k].Name,
                                        " requested world information"
                                    });
                                    continue;
                                }
                                if (Netplay.Clients[k].State == 3 || Netplay.Clients[k].State != 10)
                                {
                                    continue;
                                }
                                try
                                {
                                    Netplay.Clients[k].StatusText = string.Concat(new object[]
                                    {
                                        "(",
                                        Netplay.Clients[k].Socket.GetRemoteAddress(),
                                        ") ",
                                        Netplay.Clients[k].Name,
                                        " is playing"
                                    });
                                    continue;
                                }
                                catch
                                {
                                    Netplay.Clients[k].PendingTermination = true;
                                    continue;
                                }
                            }
                        }
                        if (Netplay.Clients[k].IsActive)
                        {
                            Netplay.Clients[k].PendingTermination = true;
                        }
                        else
                        {
                            Netplay.Clients[k].StatusText2 = "";
                            if (k < 255)
                            {
                                Main.player[k].active = false;
                            }
                        }
                    }
                }
                num++;
                if (num > 10)
                {
                    Thread.Sleep(1);
                    num = 0;
                }
                else
                {
                    Thread.Sleep(0);
                }
                if (!WorldGen.saveLock && !Main.dedServ)
                {
                    if (num3 == 0)
                    {
                        Main.statusText = "Waiting for clients...";
                    }
                    else
                    {
                        Main.statusText = num3 + " clients connected";
                    }
                }
                if (num3 == 0)
                {
                    Netplay.anyClients = false;
                }
                else
                {
                    Netplay.anyClients = true;
                }
                Netplay.IsServerRunning = true;
            }
            Netplay.StopListening();
            for (int l = 0; l < 256; l++)
            {
                Netplay.Clients[l].Reset();
            }
            if (Main.menuMode != 15)
            {
                Main.netMode  = 0;
                Main.menuMode = 10;
                WorldFile.saveWorld();
                //blocks until world saves?
                while (WorldGen.saveLock)
                {
                }
                Main.menuMode = 0;
            }
            else
            {
                Main.netMode = 0;
            }
            Main.myPlayer = 0;
        }
Esempio n. 23
0
        public static void ServerLoop(object threadContext)
        {
            ResetNetDiag();
            if (Main.rand == null)
            {
                Main.rand = new Random((int)DateTime.Now.Ticks);
            }
            if (WorldGen.genRand == null)
            {
                WorldGen.genRand = new Random((int)DateTime.Now.Ticks);
            }
            Main.myPlayer   = 16;
            ServerIP        = IPAddress.Any;
            Main.menuMode   = 14;
            Main.statusText = Lang.menu[8].Value;
            Main.netMode    = 2;
            disconnect      = false;
            for (int i = 0; i < 17; i++)
            {
                Clients[i] = new RemoteClient();
                Clients[i].Reset();
                Clients[i].Id         = i;
                Clients[i].ReadBuffer = new byte[1024];
            }
            TcpListener = new TcpSocket();
            if (!disconnect)
            {
                if (!StartListening())
                {
                    Main.menuMode   = 15;
                    Main.statusText = Language.GetTextValue("Net.TriedToRunServerTwice");
                    disconnect      = true;
                }
                Main.statusText = Language.GetTextValue("CLI.ServerStarted");
            }
            if (UseUPNP)
            {
                try
                {
                    OpenPort();
                }
                catch
                {
                }
            }
            StartBroadCasting();
            int num = 0;

            while (!disconnect)
            {
                if (!IsListening)
                {
                    int num2 = -1;
                    for (int j = 0; j < Main.maxNetPlayers; j++)
                    {
                        if (!Clients[j].IsConnected())
                        {
                            num2 = j;
                            break;
                        }
                    }
                    if (num2 >= 0)
                    {
                        if (Main.ignoreErrors)
                        {
                            try
                            {
                                StartListening();
                                IsListening = true;
                            }
                            catch
                            {
                            }
                        }
                        else
                        {
                            StartListening();
                            IsListening = true;
                        }
                    }
                }
                int num3 = 0;
                for (int k = 0; k < 17; k++)
                {
                    if (NetMessage.buffer[k].checkBytes)
                    {
                        NetMessage.CheckBytes(k);
                    }
                    if (Clients[k].PendingTermination)
                    {
                        Clients[k].Reset();
                        NetMessage.syncPlayers();
                    }
                    else if (Clients[k].IsConnected())
                    {
                        if (!Clients[k].IsActive)
                        {
                            Clients[k].State = 0;
                        }
                        Clients[k].IsActive = true;
                        num3++;
                        if (!Clients[k].IsReading)
                        {
                            try
                            {
                                if (Clients[k].Socket.IsDataAvailable())
                                {
                                    Clients[k].IsReading = true;
                                    Clients[k].Socket.AsyncReceive(Clients[k].ReadBuffer, 0, Clients[k].ReadBuffer.Length, Clients[k].ServerReadCallBack);
                                }
                            }
                            catch
                            {
                                Clients[k].PendingTermination = true;
                            }
                        }
                        if (Clients[k].StatusMax > 0 && Clients[k].StatusText2 != "")
                        {
                            if (Clients[k].StatusCount >= Clients[k].StatusMax)
                            {
                                Clients[k].StatusText  = string.Concat("(", Clients[k].Socket.GetRemoteAddress(), ") ", Clients[k].Name, " ", Clients[k].StatusText2, ": Complete!");
                                Clients[k].StatusText2 = "";
                                Clients[k].StatusMax   = 0;
                                Clients[k].StatusCount = 0;
                            }
                            else
                            {
                                Clients[k].StatusText = string.Concat("(", Clients[k].Socket.GetRemoteAddress(), ") ", Clients[k].Name, " ", Clients[k].StatusText2, ": ", (int)((float)Clients[k].StatusCount / (float)Clients[k].StatusMax * 100f), "%");
                            }
                        }
                        else if (Clients[k].State == 0)
                        {
                            Clients[k].StatusText = string.Concat("(", Clients[k].Socket.GetRemoteAddress(), ") ", Clients[k].Name, " is connecting...");
                        }
                        else if (Clients[k].State == 1)
                        {
                            Clients[k].StatusText = string.Concat("(", Clients[k].Socket.GetRemoteAddress(), ") ", Clients[k].Name, " is sending player data...");
                        }
                        else if (Clients[k].State == 2)
                        {
                            Clients[k].StatusText = string.Concat("(", Clients[k].Socket.GetRemoteAddress(), ") ", Clients[k].Name, " requested world information");
                        }
                        else if (Clients[k].State != 3 && Clients[k].State == 10)
                        {
                            try
                            {
                                Clients[k].StatusText = string.Concat("(", Clients[k].Socket.GetRemoteAddress(), ") ", Clients[k].Name, " is playing");
                            }
                            catch (Exception)
                            {
                                Clients[k].PendingTermination = true;
                            }
                        }
                    }
                    else if (Clients[k].IsActive)
                    {
                        Clients[k].PendingTermination = true;
                    }
                    else
                    {
                        Clients[k].StatusText2 = "";
                        if (k < 16)
                        {
                            Main.player[k].active = false;
                        }
                    }
                }
                num++;
                if (num > 10)
                {
                    Thread.Sleep(1);
                    num = 0;
                }
                else
                {
                    Thread.Sleep(0);
                }
                if (!WorldGen.saveLock && !Main.dedServ)
                {
                    if (num3 == 0)
                    {
                        Main.statusText = "Waiting for clients...";
                    }
                    else
                    {
                        Main.statusText = num3 + " clients connected";
                    }
                }
                if (num3 == 0)
                {
                    anyClients = false;
                }
                else
                {
                    anyClients = true;
                }
                IsServerRunning = true;
            }
            StopBroadCasting();
            StopListening();
            try
            {
                closePort();
            }
            catch
            {
            }
            for (int l = 0; l < 17; l++)
            {
                Clients[l].Reset();
            }
            if (Main.menuMode != 15)
            {
                Main.netMode  = 0;
                Main.menuMode = 10;
                WorldFile.saveWorld();
                while (WorldGen.saveLock)
                {
                }
                Main.menuMode = 0;
            }
            else
            {
                Main.netMode = 0;
            }
            Main.myPlayer = 0;
        }
        public static void loadWorld(bool loadFromCloud)
        {
            MainCallback.WorldLoadBegin();
            WorldFile.IsWorldOnCloud = loadFromCloud;
            Main.checkXMas();
            Main.checkHalloween();
            bool flag = loadFromCloud && SocialAPI.Cloud != null;

            if (!FileUtilities.Exists(Main.worldPathName, flag) && Main.autoGen)
            {
                if (!flag)
                {
                    for (int i = Main.worldPathName.Length - 1; i >= 0; i--)
                    {
                        if (Main.worldPathName.Substring(i, 1) == string.Concat(Path.DirectorySeparatorChar))
                        {
                            string path = Main.worldPathName.Substring(0, i);
                            Directory.CreateDirectory(path);
                            break;
                        }
                    }
                }
                WorldGen.clearWorld();
                WorldGen.generateWorld(-1, Main.AutogenProgress);
                WorldFile.saveWorld();
            }
            if (WorldGen.genRand == null)
            {
                WorldGen.genRand = new Random((int)DateTime.Now.Ticks);
            }
            byte[] buffer = FileUtilities.ReadAllBytes(Main.worldPathName, flag);
            using (MemoryStream memoryStream = new MemoryStream(buffer))
            {
                using (BinaryReader binaryReader = new BinaryReader(memoryStream))
                {
                    try
                    {
                        WorldGen.loadFailed  = false;
                        WorldGen.loadSuccess = false;
                        int num = binaryReader.ReadInt32();
                        WorldFile.versionNumber = num;
                        int num2;
                        if (num <= 87)
                        {
                            num2 = WorldFile.LoadWorld_Version1(binaryReader);
                        }
                        else
                        {
                            num2 = WorldFile.LoadWorld_Version2(binaryReader);
                        }
                        if (num < 141)
                        {
                            if (!loadFromCloud)
                            {
                                Main.ActiveWorldFileData.CreationTime = File.GetCreationTime(Main.worldPathName);
                            }
                            else
                            {
                                Main.ActiveWorldFileData.CreationTime = DateTime.Now;
                            }
                        }
                        binaryReader.Close();
                        memoryStream.Close();
                        if (num2 != 0)
                        {
                            WorldGen.loadFailed = true;
                        }
                        else
                        {
                            WorldGen.loadSuccess = true;
                        }
                        if (WorldGen.loadFailed || !WorldGen.loadSuccess)
                        {
                            return;
                        }
                        WorldGen.gen       = true;
                        WorldGen.waterLine = Main.maxTilesY;
                        Liquid.QuickWater(2, -1, -1);
                        WorldGen.WaterCheck();
                        int num3 = 0;
                        Liquid.quickSettle = true;
                        int   num4 = Liquid.numLiquid + LiquidBuffer.numLiquidBuffer;
                        float num5 = 0;
                        while (Liquid.numLiquid > 0 && num3 < 100000)
                        {
                            num3++;
                            float num6 = (float)(num4 - (Liquid.numLiquid + LiquidBuffer.numLiquidBuffer)) / (float)num4;
                            if (Liquid.numLiquid + LiquidBuffer.numLiquidBuffer > num4)
                            {
                                num4 = Liquid.numLiquid + LiquidBuffer.numLiquidBuffer;
                            }
                            if (num6 > num5)
                            {
                                num5 = num6;
                            }
                            else
                            {
                                num6 = num5;
                            }
                            Main.statusText = string.Concat(new object[]
                            {
                                Lang.gen[27],
                                " ",
                                (int)(num6 * 100 / 2 + 50),
                                "%"
                            });
                            Liquid.UpdateLiquid();
                        }
                        Liquid.quickSettle  = false;
                        Main.weatherCounter = WorldGen.genRand.Next(3600, 18000);
                        Cloud.resetClouds();
                        WorldGen.WaterCheck();
                        WorldGen.gen = false;
                        NPC.setFireFlyChance();
                        MainCallback.WorldLoadEnd();
                        Main.InitLifeBytes();
                        if (Main.slimeRainTime > 0)
                        {
                            Main.StartSlimeRain(false);
                        }
                        NPC.setWorldMonsters();
                    }
                    catch (Exception e)
                    {
                        WorldGen.loadFailed  = true;
                        WorldGen.loadSuccess = false;
                        try
                        {
                            binaryReader.Close();
                            memoryStream.Close();
                        }
                        catch
                        {
                        }
                        Console.WriteLine(e);
                        return;
                    }
                }
            }
//            if (WorldFile.OnWorldLoad != null)
//            {
//                WorldFile.OnWorldLoad.Invoke();
//            }
        }
Esempio n. 25
0
        public static void ServerLoop(object threadContext)
        {
            Netplay.ResetNetDiag();
            if (Main.rand == null)
            {
                Main.rand = new Random((int)DateTime.Now.Ticks);
            }
            if (WorldGen.genRand == null)
            {
                WorldGen.genRand = new Random((int)DateTime.Now.Ticks);
            }
            Main.myPlayer          = 255;
            Netplay.serverIP       = IPAddress.Any;
            Netplay.serverListenIP = Netplay.serverIP;
            Main.menuMode          = 14;
            Main.statusText        = "Starting server...";
            Main.netMode           = 2;
            Netplay.disconnect     = false;
            for (int i = 0; i < 256; i++)
            {
                Netplay.serverSock[i] = new ServerSock();
                Netplay.serverSock[i].Reset();
                Netplay.serverSock[i].whoAmI            = i;
                Netplay.serverSock[i].tcpClient         = new TcpClient();
                Netplay.serverSock[i].tcpClient.NoDelay = true;
                Netplay.serverSock[i].readBuffer        = new byte[1024];
                Netplay.serverSock[i].writeBuffer       = new byte[1024];
            }
            Netplay.tcpListener = new TcpListener(Netplay.serverListenIP, Netplay.serverPort);
            try
            {
                Netplay.tcpListener.Start();
            }
            catch (Exception ex)
            {
                Main.menuMode      = 15;
                Main.statusText    = ex.ToString();
                Netplay.disconnect = true;
            }
            if (!Netplay.disconnect)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(Netplay.ListenForClients), 1);
                Main.statusText = "Server started";
            }
            if (Netplay.uPNP)
            {
                try
                {
                    Netplay.openPort();
                }
                catch
                {
                }
            }
            int num = 0;

            while (!Netplay.disconnect)
            {
                if (Netplay.stopListen)
                {
                    int num2 = -1;
                    for (int j = 0; j < Main.maxNetPlayers; j++)
                    {
                        if (!Netplay.serverSock[j].tcpClient.Connected)
                        {
                            num2 = j;
                            break;
                        }
                    }
                    if (num2 >= 0)
                    {
                        if (Main.ignoreErrors)
                        {
                            try
                            {
                                Netplay.tcpListener.Start();
                                Netplay.stopListen = false;
                                ThreadPool.QueueUserWorkItem(new WaitCallback(Netplay.ListenForClients), 1);
                                goto IL_219;
                            }
                            catch
                            {
                                goto IL_219;
                            }
                        }
                        Netplay.tcpListener.Start();
                        Netplay.stopListen = false;
                        ThreadPool.QueueUserWorkItem(new WaitCallback(Netplay.ListenForClients), 1);
                    }
                }
IL_219:
                int num3 = 0;
                for (int k = 0; k < 256; k++)
                {
                    if (NetMessage.buffer[k].checkBytes)
                    {
                        NetMessage.CheckBytes(k);
                    }
                    if (Netplay.serverSock[k].kill)
                    {
                        Netplay.serverSock[k].Reset();
                        NetMessage.syncPlayers();
                    }
                    else
                    {
                        if (Netplay.serverSock[k].tcpClient.Connected)
                        {
                            if (!Netplay.serverSock[k].active)
                            {
                                Netplay.serverSock[k].state = 0;
                            }
                            Netplay.serverSock[k].active = true;
                            num3++;
                            if (!Netplay.serverSock[k].locked)
                            {
                                try
                                {
                                    Netplay.serverSock[k].networkStream = Netplay.serverSock[k].tcpClient.GetStream();
                                    if (Netplay.serverSock[k].networkStream.DataAvailable)
                                    {
                                        Netplay.serverSock[k].locked = true;
                                        Netplay.serverSock[k].networkStream.BeginRead(Netplay.serverSock[k].readBuffer, 0, Netplay.serverSock[k].readBuffer.Length, new AsyncCallback(Netplay.serverSock[k].ServerReadCallBack), Netplay.serverSock[k].networkStream);
                                    }
                                }
                                catch
                                {
                                    Netplay.serverSock[k].kill = true;
                                }
                            }
                            if (Netplay.serverSock[k].statusMax > 0 && Netplay.serverSock[k].statusText2 != "")
                            {
                                if (Netplay.serverSock[k].statusCount >= Netplay.serverSock[k].statusMax)
                                {
                                    Netplay.serverSock[k].statusText = string.Concat(new object[]
                                    {
                                        "(",
                                        Netplay.serverSock[k].tcpClient.Client.RemoteEndPoint,
                                        ") ",
                                        Netplay.serverSock[k].name,
                                        " ",
                                        Netplay.serverSock[k].statusText2,
                                        ": Complete!"
                                    });
                                    Netplay.serverSock[k].statusText2 = "";
                                    Netplay.serverSock[k].statusMax   = 0;
                                    Netplay.serverSock[k].statusCount = 0;
                                }
                                else
                                {
                                    Netplay.serverSock[k].statusText = string.Concat(new object[]
                                    {
                                        "(",
                                        Netplay.serverSock[k].tcpClient.Client.RemoteEndPoint,
                                        ") ",
                                        Netplay.serverSock[k].name,
                                        " ",
                                        Netplay.serverSock[k].statusText2,
                                        ": ",
                                        (int)((float)Netplay.serverSock[k].statusCount / (float)Netplay.serverSock[k].statusMax * 100f),
                                        "%"
                                    });
                                }
                            }
                            else
                            {
                                if (Netplay.serverSock[k].state == 0)
                                {
                                    Netplay.serverSock[k].statusText = string.Concat(new object[]
                                    {
                                        "(",
                                        Netplay.serverSock[k].tcpClient.Client.RemoteEndPoint,
                                        ") ",
                                        Netplay.serverSock[k].name,
                                        " is connecting..."
                                    });
                                }
                                else
                                {
                                    if (Netplay.serverSock[k].state == 1)
                                    {
                                        Netplay.serverSock[k].statusText = string.Concat(new object[]
                                        {
                                            "(",
                                            Netplay.serverSock[k].tcpClient.Client.RemoteEndPoint,
                                            ") ",
                                            Netplay.serverSock[k].name,
                                            " is sending player data..."
                                        });
                                    }
                                    else
                                    {
                                        if (Netplay.serverSock[k].state == 2)
                                        {
                                            Netplay.serverSock[k].statusText = string.Concat(new object[]
                                            {
                                                "(",
                                                Netplay.serverSock[k].tcpClient.Client.RemoteEndPoint,
                                                ") ",
                                                Netplay.serverSock[k].name,
                                                " requested world information"
                                            });
                                        }
                                        else
                                        {
                                            if (Netplay.serverSock[k].state != 3 && Netplay.serverSock[k].state == 10)
                                            {
                                                Netplay.serverSock[k].statusText = string.Concat(new object[]
                                                {
                                                    "(",
                                                    Netplay.serverSock[k].tcpClient.Client.RemoteEndPoint,
                                                    ") ",
                                                    Netplay.serverSock[k].name,
                                                    " is playing"
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (Netplay.serverSock[k].active)
                            {
                                Netplay.serverSock[k].kill = true;
                            }
                            else
                            {
                                Netplay.serverSock[k].statusText2 = "";
                                if (k < 255)
                                {
                                    Main.player[k].active = false;
                                }
                            }
                        }
                    }
                }
                num++;
                if (num > 10)
                {
                    Thread.Sleep(1);
                    num = 0;
                }
                else
                {
                    Thread.Sleep(0);
                }
                if (!WorldGen.saveLock && !Main.dedServ)
                {
                    if (num3 == 0)
                    {
                        Main.statusText = "Waiting for clients...";
                    }
                    else
                    {
                        Main.statusText = num3 + " clients connected";
                    }
                }
                if (num3 == 0)
                {
                    Netplay.anyClients = false;
                }
                else
                {
                    Netplay.anyClients = true;
                }
                Netplay.ServerUp = true;
            }
            Netplay.tcpListener.Stop();
            try
            {
                Netplay.closePort();
            }
            catch
            {
            }
            for (int l = 0; l < 256; l++)
            {
                Netplay.serverSock[l].Reset();
            }
            if (Main.menuMode != 15)
            {
                Main.netMode  = 0;
                Main.menuMode = 10;
                WorldFile.saveWorld(false);
                while (WorldGen.saveLock)
                {
                }
                Main.menuMode = 0;
            }
            else
            {
                Main.netMode = 0;
            }
            Main.myPlayer = 0;
        }
Esempio n. 26
0
        void Prune(CommandArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                int corrupted = 0;
                int empty     = 0;
                var pruneID   = new List <int>();
                for (int i = 0; i < Main.maxTilesX; i++)
                {
                    for (int j = 0; j < Main.maxTilesY; j++)
                    {
                        if (Main.tile[i, j].type == TileID.Signs)
                        {
                            int x = i;
                            int y = j;
                            if (Main.tile[x, y].frameY % 36 != 0)
                            {
                                y--;
                            }
                            if (Main.tile[x, y].frameX % 36 != 0)
                            {
                                x--;
                            }

                            using (var reader = Database.QueryReader("SELECT ID, Text FROM Signs WHERE X = @0 AND Y = @1 AND WorldID = @2", x, y, Main.worldID))
                            {
                                if (reader.Read())
                                {
                                    if (String.IsNullOrWhiteSpace(reader.Get <string>("Text")))
                                    {
                                        empty++;
                                        WorldGen.KillTile(x, y);
                                        TSPlayer.All.SendTileSquare(x, y, 3);
                                        pruneID.Add(reader.Get <int>("ID"));
                                    }
                                }
                                else
                                {
                                    corrupted++;
                                    WorldGen.KillTile(x, y);
                                    TSPlayer.All.SendTileSquare(x, y, 3);
                                }
                            }
                        }
                    }
                }

                e.Player.SendSuccessMessage("Pruned {0} empty sign{1}.", empty, empty == 1 ? "" : "s");

                using (var reader = Database.QueryReader("SELECT ID, X, Y FROM Signs WHERE WorldID = @0", Main.worldID))
                {
                    while (reader.Read())
                    {
                        int x = reader.Get <int>("X");
                        int y = reader.Get <int>("Y");
                        if (Main.tile[x, y].type != TileID.Signs)
                        {
                            corrupted++;
                            WorldGen.KillTile(x, y);
                            TSPlayer.All.SendTileSquare(x, y, 3);
                            pruneID.Add(reader.Get <int>("ID"));
                        }
                    }
                }

                for (int i = 0; i < pruneID.Count; i++)
                {
                    Database.Query("DELETE FROM Signs WHERE ID = @0", pruneID[i]);
                }

                e.Player.SendSuccessMessage("Pruned {0} corrupted sign{1}.", corrupted, corrupted == 1 ? "" : "s");
                if (corrupted + empty > 0)
                {
                    WorldFile.saveWorld();
                }
            });
        }
Esempio n. 27
0
        public override void PreUpdate()
        {
            if (Main.netMode != 2)
            {
                return;
            }
            try
            {
                _timer++;
                if (_timer > 10000000)
                {
                    _timer = 0;
                }
                ServerStarted = true;
                foreach (var player in ServerSideCharacter2.PlayerCollection)
                {
                    if (player.Value.PrototypePlayer == null || !player.Value.PrototypePlayer.active)
                    {
                        player.Value.IsLogin = false;
                        player.Value.SetID(-1);
                    }
                }

                for (var i = 0; i < Main.maxPlayers; i++)
                {
                    if (TileMessageCD[i] > 0)
                    {
                        TileMessageCD[i]--;
                    }
                }
                if (_timer % 300 < 1)
                {
                    foreach (var player in Main.player)
                    {
                        if (!player.active)
                        {
                            continue;
                        }
                        var serverPlayer = player.GetServerPlayer();
                        var playerID     = player.whoAmI;
                        if (serverPlayer == null)
                        {
                            continue;
                        }
                        if (!serverPlayer.HasPassword)
                        {
                            serverPlayer.ApplyLockBuffs();
                            NetMessage.SendChatMessageToClient(NetworkText.FromLiteral("您还没有注册,请使用登录窗口注册哦~"), new Color(255, 255, 30, 30), playerID);
                        }
                        else if (serverPlayer.HasPassword && !serverPlayer.IsLogin)
                        {
                            serverPlayer.ApplyLockBuffs();
                            NetMessage.SendChatMessageToClient(NetworkText.FromLiteral("您已注册,输入密码就可以登录了!"), new Color(255, 255, 30, 30), playerID);
                        }
                    }
                }
                foreach (var p in Main.player)
                {
                    if (p.whoAmI == 255)
                    {
                        continue;
                    }
                    if (!p.active)
                    {
                        continue;
                    }
                    var player = p.GetServerPlayer();
                    if (player == null)
                    {
                        continue;
                    }
                    if (player.IsLogin)
                    {
                        player.SyncPlayerToInfo();
                    }
                    UpdateRegion(p);
                    // CommandBoardcast.ConsoleMessage($"玩家 {player.Name} 物品栏第一 {player.inventory[0].type}");
                }
                ServerSideCharacter2.MatchingSystem.Run();
                OnPostUpdate?.Invoke(this, new EventArgs());
                Ranking.CheckRankBoard();
                if (ServerSideCharacter2.Config.AutoSave && _timer % ServerSideCharacter2.Config.SaveInterval < 1)
                {
                    ThreadPool.QueueUserWorkItem(Do_Save);
                }
            }
            catch (Exception ex)
            {
                CommandBoardcast.ConsoleError(ex);
                WorldFile.saveWorld();
                Netplay.disconnect = true;
                Terraria.Social.SocialAPI.Shutdown();
            }
        }
Esempio n. 28
0
        public override void AI()
        {
            if (npc.life < npc.lifeMax / 2)
            {
                PhaseValueOrSomethingIDK = 1;
            }

            npc.TargetClosest(true);
            npc.spriteDirection = npc.direction;

            Player player = Main.player[npc.target];

            SpeeeeedValue = SpeeeenBool ? 5 : 7;

            Vector2 moveTo = player.Center - npc.Center;

            moveTo.Normalize();
            moveTo = moveTo * SpeeeeedValue;

            npc.velocity = moveTo;

            if (++SpeeeeenTimer % 180 == 0)
            {
                if (SpeeeenBool)
                {
                    SpeeeenBool = true;
                }
                else
                {
                    SpeeeenBool = false;
                }
            }

            if (SpeeeenBool)
            {
                npc.rotation += npc.velocity.X * 0.1f;
            }

            if (PhaseValueOrSomethingIDK == 0)
            {
                if (++AtttaackTimer >= 250)
                {
                    for (int i = 0; i < Main.rand.Next(10, 20); i++)
                    {
                        Projectile.NewProjectile(npc.Center.X - Main.rand.Next(-600, 600), npc.Center.Y - Main.screenHeight / 2 - 60, moveTo.X * 1.5f, moveTo.Y * 1.5f, ModContent.ProjectileType <Projectiles.rum>(), 35, 2);
                    }

                    AtttaackTimer = 0;
                }
            }
            else if (PhaseValueOrSomethingIDK == 1)
            {
                GameCrashCounter++;

                if (GameCrashCounter == 1)
                {
                    CombatText.NewText(npc.Hitbox, Color.DarkRed, "Kill me in 2 minute or you get booted", dramatic: true);
                }

                if (GameCrashCounter == 3600)
                {
                    CombatText.NewText(npc.Hitbox, Color.DarkRed, "One minute kill me or terraria go back to menu", dramatic: true);
                }

                if (GameCrashCounter == 7140)
                {
                    CombatText.NewText(npc.Hitbox, Color.DarkRed, "You are going to brazil", dramatic: true);
                }

                if (GameCrashCounter == 7200)
                {
                    CombatText.NewText(npc.Hitbox, Color.DarkRed, "Whoops gotta save your stuff first", dramatic: true);
                }

                if (GameCrashCounter == 7300)
                {
                    CombatText.NewText(npc.Hitbox, Color.DarkRed, "PASTA LA VISTA!!!!!", dramatic: true);
                }

                if (GameCrashCounter >= 7320)
                {
                    Main.SaveSettings();

                    if (Main.netMode == NetmodeID.SinglePlayer)
                    {
                        WorldFile.CacheSaveTime();
                    }

                    Main.invasionProgress            = 0;
                    Main.invasionProgressDisplayLeft = 0;
                    Main.invasionProgressAlpha       = 0f;
                    Main.menuMode = 10;
                    Main.gameMenu = true;
                    Main.StopTrackedSounds();
                    CaptureInterface.ResetFocus();
                    Main.ActivePlayerFileData.StopPlayTimer();

                    Player.SavePlayer(Main.ActivePlayerFileData, false);

                    if (Main.netMode == NetmodeID.SinglePlayer)
                    {
                        WorldFile.saveWorld();
                    }
                    else
                    {
                        Netplay.disconnect = true;
                        Main.netMode       = NetmodeID.SinglePlayer;
                    }

                    Main.fastForwardTime = false;
                    Main.UpdateSundial();
                    Main.menuMode = 0;
                }

                if (++AtttaackTimer >= 40)
                {
                    Projectile.NewProjectile(npc.Center, moveTo * 4, ModContent.ProjectileType <Projectiles.beer>(), 50, 3);

                    AtttaackTimer = 0;
                }
            }
        }
Esempio n. 29
0
 public override void PostUpdate()
 {
     if (Main.netMode == 2)
     {
         try
         {
             ServerStarted = true;
             for (int i = 0; i < 255; i++)
             {
                 if (Main.player[i].active)
                 {
                     ServerPlayer player = ServerSideCharacter.XmlData.Data[Main.player[i].name];
                     player.CopyFrom(Main.player[i]);
                 }
             }
             if (Main.time % 180 < 1)
             {
                 lock (ServerSideCharacter.XmlData)
                 {
                     foreach (var player in ServerSideCharacter.XmlData.Data)
                     {
                         if (player.Value.PrototypePlayer != null)
                         {
                             int playerID = player.Value.PrototypePlayer.whoAmI;
                             if (!player.Value.HasPassword)
                             {
                                 player.Value.ApplyLockBuffs();
                                 NetMessage.SendChatMessageToClient(NetworkText.FromLiteral("Welcome! You are new to here. Please use /register <password> to register an account!"), new Color(255, 255, 30, 30), playerID);
                             }
                             if (player.Value.HasPassword && !player.Value.IsLogin)
                             {
                                 player.Value.ApplyLockBuffs();
                                 NetMessage.SendChatMessageToClient(NetworkText.FromLiteral("Welcome! You have already created an account. Please type /login <password> to login!"), new Color(255, 255, 30, 30), playerID);
                             }
                         }
                     }
                 }
             }
             if (Main.time % 3600 < 1)
             {
                 ThreadPool.QueueUserWorkItem(Do_Save);
             }
             foreach (var player in Main.player.Where(p => p.active))
             {
                 if (player.GetServerPlayer().EnteredRegion == null)
                 {
                     var        serverPlayer = player.GetServerPlayer();
                     RegionInfo region;
                     if (serverPlayer.InAnyRegion(out region))
                     {
                         serverPlayer.EnteredRegion = region;
                         serverPlayer.SendInfo(region.WelcomeInfo());
                     }
                 }
                 else if (player.GetServerPlayer().EnteredRegion != null)
                 {
                     var        serverPlayer = player.GetServerPlayer();
                     RegionInfo region;
                     if (!serverPlayer.InAnyRegion(out region))
                     {
                         serverPlayer.SendInfo(serverPlayer.EnteredRegion.LeaveInfo());
                         serverPlayer.EnteredRegion = null;
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             CommandBoardcast.ConsoleError(ex);
             WorldFile.saveWorld();
             Netplay.disconnect = true;
             Terraria.Social.SocialAPI.Shutdown();
         }
     }
 }
Esempio n. 30
0
        public override void PostUpdateEverything()
        {
            playMusicTimer_UseOnce++;
            // Main.NewText($"X: {(int)Main.MouseWorld.X / 16} | Y: {(int)Main.MouseWorld.Y / 16}");
            updateGameZoomTargetValue = Main.GameZoomTarget;
            Player player = Main.player[Main.myPlayer];

            if (Main.hasFocus)
            {
                player.GetModPlayer <SpookyPlayer>().deathTextTimer--;
                if (player.GetModPlayer <SpookyPlayer>().deathTextTimer < 0)
                {
                    player.GetModPlayer <SpookyPlayer>().deathTextTimer = 0;
                }
            }
            if (player.respawnTimer == 25)
            {
                if (Main.worldName == SpookyTerrariaUtils.slenderWorldName)
                {
                    SpookyPlayer.pages = 0;
                    SpookyTerrariaUtils.RemoveAllPossiblePagePositions();
                    Main.SaveSettings();

                    if (Main.netMode == NetmodeID.SinglePlayer)
                    {
                        WorldFile.CacheSaveTime();
                    }
                    Main.invasionProgress            = 0;
                    Main.invasionProgressDisplayLeft = 0;
                    Main.invasionProgressAlpha       = 0f;
                    Main.menuMode = 10;
                    Main.StopTrackedSounds();
                    CaptureInterface.ResetFocus();
                    Main.ActivePlayerFileData.StopPlayTimer();

                    Player.SavePlayer(Main.ActivePlayerFileData, false);

                    if (Main.netMode == NetmodeID.SinglePlayer)
                    {
                        WorldFile.saveWorld();
                    }
                    else
                    {
                        Netplay.disconnect = true;
                        Main.netMode       = NetmodeID.SinglePlayer;
                    }

                    Main.fastForwardTime = false;
                    Main.UpdateSundial();
                    Main.menuMode = 0;
                }
            }

            /*
             * if (Main.worldName == SpookyTerrariaUtils.slenderWorldName)
             * {
             *  Rectangle insideBathrooms = new Rectangle(2091 * SpookyTerrariaUtils.tileScaling, 367 * SpookyTerrariaUtils.tileScaling, 85 * SpookyTerrariaUtils.tileScaling, 26 * SpookyTerrariaUtils.tileScaling);
             *  if (player.Hitbox.Intersects(insideBathrooms))
             *  {
             *      Main.NewText(updateGameZoomTargetValue + ", " + Main.GameZoomTarget);
             *      updateGameZoomTargetValue += 0.05f;
             *      if (updateGameZoomTargetValue > 8.75f)
             *      {
             *          updateGameZoomTargetValue = 8.75f;
             *      }
             *  }
             * }
             */
            // Fix for lerping
            Main.soundInstanceMenuTick.Volume  = 0f;
            Main.soundInstanceMenuOpen.Volume  = 0f;
            Main.soundInstanceMenuClose.Volume = 0f;
            if (Main.netMode != NetmodeID.Server)
            {
                for (int i = 0; i < Main.maxNPCs; i++)
                {
                    NPC npc = Main.npc[i];
                    if (npc.type == ModContent.NPCType <Stalker>())
                    {
                        Filters.Scene["Darkness"].GetShader().UseIntensity(player.Distance(npc.Center) / 8);
                    }
                }
            }
            Main.slimeRain        = false;
            Main.invasionSize     = 0;
            Main.invasionProgress = 0;
            if (!beatGame)
            {
                Main.dayTime = false;
                Main.time    = 1800;
            }
            else
            {
                Main.dayTime = true;
                Main.time    = 18000;
            }
        }