示例#1
0
        public MinecraftServer()
        {
            Log.Info("Initializing...");
            MCPacketFactory.Load();

            Server = new NetServer(new NetConfiguration()
            {
                Host     = IPAddress.Any,
                Port     = 25565,
                Protocol = ProtocolType.Tcp
            });

            Server.NetConnectionFactory = new ConnectionFactory(this);

            PlayerFactory = new DefaultPlayerFactory(this);

            LevelManager = new LevelManager();

            //Cache the level
            LevelManager.GetLevel(null, "default");

            Info = new ServerInfo(this);

            Log.Info("Generating RSA keypair...");
            //RsaEncryption = null;
            RsaEncryption = new EncryptionHolder();
        }
示例#2
0
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");
            API.Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();
            //ConfigureServices();

            var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                eventDispatcher.LoadFrom(assembly);
            }

            //var options = Services.GetService<IOptionsProvider>();

            //	Log.Info($"Loading resources...");
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver,
                                          OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();
                return;
            }

            var profileManager = Services.GetService <ProfileManager>();

            profileManager.LoadProfiles(progressReceiver);

            //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null);
            AnvilWorldProvider.LoadBlockConverter();

            PluginManager.EnablePlugins();

            var storage = Services.GetRequiredService <IStorageSystem>();

            if (storage.TryReadJson("skin.json", out EntityModel model))
            {
                PlayerModel = model;
            }

            if (storage.TryReadBytes("skin.png", out byte[] skinBytes))
示例#3
0
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");
            API.Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();

            //ConfigureServices();

            var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                eventDispatcher.LoadFrom(assembly);
            }

            var options = Services.GetService <IOptionsProvider>();

            string pluginDirectoryPaths = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            var pluginDir = options.AlexOptions.ResourceOptions.PluginDirectory;

            if (!string.IsNullOrWhiteSpace(pluginDir))
            {
                pluginDirectoryPaths = pluginDir;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(LaunchSettings.WorkDir) && Directory.Exists(LaunchSettings.WorkDir))
                {
                    pluginDirectoryPaths = LaunchSettings.WorkDir;
                }
            }

            foreach (string dirPath in pluginDirectoryPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                string directory = dirPath;
                if (!Path.IsPathRooted(directory))
                {
                    directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dirPath);
                }

                PluginManager.DiscoverPlugins(directory);
            }


            var profileManager = Services.GetService <ProfileManager>();

            //	Log.Info($"Loading resources...");
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver,
                                          OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();
                return;
            }

            profileManager.LoadProfiles(progressReceiver);

            //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null);
            AnvilWorldProvider.LoadBlockConverter();

            PluginManager.EnablePlugins();

            if (LaunchSettings.ModelDebugging)
            {
                GameStateManager.SetActiveState <ModelDebugState>();
            }
            else
            {
                GameStateManager.SetActiveState <TitleState>("title");
                //	var player = new Player(GraphicsDevice, InputManager, null, null, new Skin(),  null, PlayerIndex.One, null);
                //	player.Inventory.IsPeInventory = true;

                /*Random rnd = new Random();
                 * for (int i = 0; i < player.Inventory.SlotCount; i++)
                 * {
                 *      player.Inventory[i] = new ItemBlock(BlockFactory.AllBlockstates.ElementAt(rnd.Next() % BlockFactory.AllBlockstates.Count).Value)
                 *      {
                 *              Count = rnd.Next(1, 64)
                 *      };
                 * }*/
                //GuiManager.ShowDialog(new GuiPlayerInventoryDialog(player, player.Inventory));
            }

            GameStateManager.RemoveState("splash");
        }
示例#4
0
 public ServerQueryProvider(Alex alex)
 {
     Alex = alex;
     MCPacketFactory.Load();
 }
示例#5
0
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");

            API.Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();
            //ConfigureServices();

            //var options = Services.GetService<IOptionsProvider>();

            //	Log.Info($"Loading resources...");
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver, OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();

                return;
            }

            var profileManager = Services.GetService <ProfileManager>();

            profileManager.LoadProfiles(progressReceiver);

            //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null);
            AnvilWorldProvider.LoadBlockConverter();

            PluginManager.EnablePlugins();

            var storage = Services.GetRequiredService <IStorageSystem>();

            if (storage.TryReadString("skin.json", out var str, Encoding.UTF8))
            {
                Dictionary <string, EntityModel> models = new Dictionary <string, EntityModel>();
                BedrockResourcePack.LoadEntityModel(str, models);
                models = BedrockResourcePack.ProcessEntityModels(models);

                if (models.Count > 0)
                {
                    if (models.TryGetValue("geometry.humanoid.custom", out var entityModel) || models.TryGetValue(
                            "geometry.humanoid.customSlim", out entityModel))
                    {
                        PlayerModel = entityModel;
                        Log.Info($"Player model loaded...");
                    }
                }
            }

            if (PlayerModel == null)
            {
                if (ModelFactory.TryGetModel("geometry.humanoid.customSlim", out var model))
                {
                    //model.Name = "geometry.humanoid.customSlim";
                    PlayerModel = model;
                }
            }

            if (PlayerModel != null)
            {
                //Log.Info($"Player model loaded...");
            }

            if (storage.TryReadBytes("skin.png", out byte[] skinBytes))
示例#6
0
 public JavaClient(JavaWorldProvider javaWorldProvider, Socket socket, DedicatedThreadPool networkPool) : base(PacketDirection.ClientBound, socket, null, networkPool)
 {
     MCPacketFactory.Load();
     JavaWorld     = javaWorldProvider;
     WorldReceiver = javaWorldProvider;
 }
示例#7
0
        public void Dispose()
        {
            Stop();

            // NetworkProcessing?.Wait();
            //NetworkProcessing?.Dispose();
            NetworkProcessing = null;
            ClearOutQueue(PacketWriteQueue);

            //NetworkWriting?.Wait();
            //NetworkWriting?.Dispose();
            NetworkWriting = null;
            //PacketWriteQueue?.Dispose();

            ClearOutQueue(HandlePacketQueue);

            //PacketHandling?.Wait();
            //PacketHandling?.Dispose();
            PacketHandling = null;

            //HandlePacketQueue?.Dispose();

            CancellationToken?.Dispose();

            _readerStream?.Dispose();
            _sendStream?.Dispose();
            Socket?.Dispose();

            foreach (var state in UnhandledPacketsFilter.ToArray())
            {
                foreach (var p in state.Value)
                {
                    Log.Warn($"({state.Key}) unhandled: 0x{p.Key:X2} ({(state.Key == ConnectionState.Play ? MCPacketFactory.GetPlayPacketName(p.Key) : "Unknown")}) * {p.Value}");
                }
            }

            UnhandledPacketsFilter.Clear();
        }
示例#8
0
        private void ProcessNetwork()
        {
            int lastPacketId = 0;

            try
            {
                using (NetworkStream ns = new NetworkStream(Socket))
                {
                    using (MinecraftStream ms = new MinecraftStream(ns))
                    {
                        _readerStream = ms;

                        while (!CancellationToken.IsCancellationRequested)
                        {
                            Packets.Packet packet = null;
                            int            packetId;
                            byte[]         packetData;

                            if (!CompressionEnabled)
                            {
                                int length = ms.ReadVarInt();

                                int packetIdLength;
                                packetId     = ms.ReadVarInt(out packetIdLength);
                                lastPacketId = packetId;
                                if (length - packetIdLength > 0)
                                {
                                    /*packetData = new byte[length - packetIdLength];
                                     * int read = 0;
                                     * while (read < packetData.Length)
                                     * {
                                     *      read += ms.Read(packetData, read, packetData.Length - read);
                                     *
                                     *      if (CancellationToken.IsCancellationRequested) throw new OperationCanceledException();
                                     * }*/
                                    packetData = ms.Read(length - packetIdLength);
                                }
                                else
                                {
                                    packetData = new byte[0];
                                }
                            }
                            else
                            {
                                int packetLength = ms.ReadVarInt();

                                int br;
                                int dataLength = ms.ReadVarInt(out br);

                                int readMore;
                                if (dataLength == 0)
                                {
                                    packetId     = ms.ReadVarInt(out readMore);
                                    lastPacketId = packetId;
                                    packetData   = ms.Read(packetLength - (br + readMore));
                                }
                                else
                                {
                                    byte[] data = ms.Read(packetLength - br);
                                    byte[] decompressed;
                                    DecompressData(data, out decompressed);

                                    using (MemoryStream b = new MemoryStream(decompressed))
                                    {
                                        using (MinecraftStream a = new MinecraftStream(b))
                                        {
                                            int l;
                                            packetId     = a.ReadVarInt(out l);
                                            lastPacketId = packetId;
                                            packetData   = a.Read(dataLength - l);
                                        }
                                    }
                                }
                            }

                            packet = MCPacketFactory.GetPacket(Direction, ConnectionState, packetId);
                            if (packet == null)
                            {
                                if (UnhandledPacketsFilter[ConnectionState]
                                    .TryAdd(packetId, 1))
                                {
                                    Log.Debug($"Unhandled packet in {ConnectionState}! 0x{packetId.ToString("x2")} = {(ConnectionState == ConnectionState.Play ? MCPacketFactory.GetPlayPacketName(packetId) : "Unknown")}");
                                }
                                else
                                {
                                    UnhandledPacketsFilter[ConnectionState][packetId] = UnhandledPacketsFilter[ConnectionState][packetId] + 1;
                                }

                                continue;
                            }

                            if (ConnectionState == ConnectionState.Play)
                            {
                                HandlePacketQueue.Add(new TemporaryPacketData(packet, packetData));
                            }
                            else
                            {
                                packet.Decode(new MinecraftStream(new MemoryStream(packetData)));
                                HandlePacket(packet);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException)
                {
                    return;
                }
                if (ex is EndOfStreamException)
                {
                    return;
                }
                if (ex is IOException)
                {
                    return;
                }

                if (LogExceptions)
                {
                    Log.Warn($"Failed to process network (Last packet: 0x{lastPacketId:X2} State: {ConnectionState}): " + ex);
                }
            }
            finally
            {
                Disconnected(false);
            }
        }
示例#9
0
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");
            API.Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();
            //ConfigureServices();

            var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                eventDispatcher.LoadFrom(assembly);
            }

            //var options = Services.GetService<IOptionsProvider>();

            //	Log.Info($"Loading resources...");
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver,
                                          OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();
                return;
            }

            var profileManager = Services.GetService <ProfileManager>();

            profileManager.LoadProfiles(progressReceiver);

            //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null);
            AnvilWorldProvider.LoadBlockConverter();

            PluginManager.EnablePlugins();

            var storage = Services.GetRequiredService <IStorageSystem>();

            if (storage.TryReadString("skin.json", out var str, Encoding.UTF8))
            {
                //var entries = new Dictionary<string, EntityModel>();
                //EntityModel.GetEntries(str, entries);
                var geometryModel =
                    MCJsonConvert.DeserializeObject <GeometryModel>(str);

                var model = geometryModel.FindGeometry("geometry.humanoid.custom");

                if (model == null)
                {
                    model = geometryModel.FindGeometry("geometry.humanoid.customSlim");
                }

                if (model != null)
                {
                    PlayerModel = model;
                }
            }

            if (PlayerModel == null)
            {
                if (ModelFactory.TryGetModel("geometry.humanoid.customSlim", out var model))
                {
                    model.Name  = "geometry.humanoid.customSlim";
                    PlayerModel = model;
                }
            }

            if (PlayerModel != null)
            {
                Log.Info($"Player model loaded...");
            }

            if (storage.TryReadBytes("skin.png", out byte[] skinBytes))
示例#10
0
        private bool TryReadPacket(MinecraftStream stream, out int lastPacketId)
        {
            Packets.Packet packet = null;
            int            packetId;

            byte[] packetData;

            if (!CompressionEnabled)
            {
                int length = stream.ReadVarInt();

                int packetIdLength;
                packetId     = stream.ReadVarInt(out packetIdLength);
                lastPacketId = packetId;

                if (length - packetIdLength > 0)
                {
                    packetData = stream.Read(length - packetIdLength);
                }
                else
                {
                    packetData = new byte[0];
                }
            }
            else
            {
                int packetLength = stream.ReadVarInt();

                int br;
                int dataLength = stream.ReadVarInt(out br);

                int readMore;

                if (dataLength == 0)
                {
                    packetId     = stream.ReadVarInt(out readMore);
                    lastPacketId = packetId;
                    packetData   = stream.Read(packetLength - (br + readMore));
                }
                else
                {
                    var data = stream.ReadToSpan(packetLength - br);

                    using (MinecraftStream a = new MinecraftStream())
                    {
                        using (ZlibStream outZStream = new ZlibStream(
                                   a, CompressionMode.Decompress, CompressionLevel.Default, true))
                        {
                            outZStream.Write(data);
                            //  outZStream.Write(data, 0, data.Length);
                        }

                        a.Seek(0, SeekOrigin.Begin);

                        int l;
                        packetId     = a.ReadVarInt(out l);
                        lastPacketId = packetId;
                        packetData   = a.Read(dataLength - l);
                    }
                }
            }

            packet = MCPacketFactory.GetPacket(PacketDirection, ConnectionState, packetId);

            Interlocked.Increment(ref PacketsIn);
            Interlocked.Add(ref PacketSizeIn, packetData.Length);

            if (packet == null)
            {
                if (UnhandledPacketsFilter[ConnectionState].TryAdd(packetId, 1))
                {
                    Log.Debug(
                        $"Unhandled packet in {ConnectionState}! 0x{packetId.ToString("x2")} = {(ConnectionState == ConnectionState.Play ? MCPacketFactory.GetPlayPacketName(packetId) : "Unknown")}");
                }
                else
                {
                    UnhandledPacketsFilter[ConnectionState][packetId] =
                        UnhandledPacketsFilter[ConnectionState][packetId] + 1;
                }

                return(false);
            }

            //    Log.Info($"Received: {packet}");

            if (ConnectionState == ConnectionState.Play)
            {
                if (ShouldAddToProcessing(packet))
                {
                    // Interlocked.Increment(ref _queued);

                    // ThreadPool.QueueUserWorkItem(
                    //	    () =>
                    //	    {
                    ProcessPacket(packet, packetData);
                    //   Interlocked.Decrement(ref _queued);
                    //	    });

                    return(true);
                }
            }
            else
            {
                ProcessPacket(packet, packetData);

                return(true);
            }

            return(false);
        }
示例#11
0
        public JavaClient(JavaWorldProvider javaWorldProvider, Socket socket) : base(Direction.ClientBound, socket, null, null)
        {
            MCPacketFactory.Load();

            WorldReceiver = javaWorldProvider;
        }
示例#12
0
        private void ProcessNetwork()
        {
            try
            {
                using (NetworkStream ns = new NetworkStream(Socket))
                {
                    using (MinecraftStream ms = new MinecraftStream(ns))
                    {
                        _readerStream = ms;

                        while (!CancellationToken.IsCancellationRequested)
                        {
                            Packets.Packet packet = null;
                            int            packetId;
                            byte[]         packetData;

                            if (!CompressionEnabled)
                            {
                                int length = ms.ReadVarInt();

                                int packetIdLength;
                                packetId = ms.ReadVarInt(out packetIdLength);

                                if (length - packetIdLength > 0)
                                {
                                    /*packetData = new byte[length - packetIdLength];
                                     * int read = 0;
                                     * while (read < packetData.Length)
                                     * {
                                     *      read += ms.Read(packetData, read, packetData.Length - read);
                                     *
                                     *      if (CancellationToken.IsCancellationRequested) throw new OperationCanceledException();
                                     * }*/
                                    packetData = ms.Read(length - packetIdLength);
                                }
                                else
                                {
                                    packetData = new byte[0];
                                }
                            }
                            else
                            {
                                int packetLength = ms.ReadVarInt();

                                int br;
                                int dataLength = ms.ReadVarInt(out br);

                                int readMore;
                                if (dataLength == 0)
                                {
                                    packetId   = ms.ReadVarInt(out readMore);
                                    packetData = ms.Read(packetLength - (br + readMore));
                                }
                                else
                                {
                                    byte[] data = ms.Read(packetLength - br);
                                    byte[] decompressed;
                                    DecompressData(data, out decompressed);

                                    using (MemoryStream b = new MemoryStream(decompressed))
                                    {
                                        using (MinecraftStream a = new MinecraftStream(b))
                                        {
                                            int l;
                                            packetId   = a.ReadVarInt(out l);
                                            packetData = a.Read(dataLength - l);
                                        }
                                    }
                                }
                            }

                            packet = MCPacketFactory.GetPacket(ConnectionState, packetId);
                            if (packet == null)
                            {
                                Log.Warn($"Unhandled package! 0x{packetId.ToString("x2")}");
                                continue;
                            }
                            packet.Decode(new MinecraftStream(new MemoryStream(packetData)));
                            HandlePacket(packet);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn("OH NO", ex);
                if (ex is OperationCanceledException)
                {
                    return;
                }
                if (ex is EndOfStreamException)
                {
                    return;
                }
                if (ex is IOException)
                {
                    return;
                }

                Log.Error("An unhandled exception occured while processing network!", ex);
            }
            finally
            {
                Disconnected(false);
            }
        }
示例#13
0
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");
            API.Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();

            //ConfigureServices();

            var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                eventDispatcher.LoadFrom(assembly);
            }

            var options = Services.GetService <IOptionsProvider>();

            string pluginDirectoryPaths = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            var pluginDir = options.AlexOptions.ResourceOptions.PluginDirectory;

            if (!string.IsNullOrWhiteSpace(pluginDir))
            {
                pluginDirectoryPaths = pluginDir;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(LaunchSettings.WorkDir) && Directory.Exists(LaunchSettings.WorkDir))
                {
                    pluginDirectoryPaths = LaunchSettings.WorkDir;
                }
            }

            foreach (string dirPath in pluginDirectoryPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                string directory = dirPath;
                if (!Path.IsPathRooted(directory))
                {
                    directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dirPath);
                }

                PluginManager.DiscoverPlugins(directory);
            }


            var profileManager = Services.GetService <ProfileManager>();

            //	Log.Info($"Loading resources...");
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver,
                                          OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();
                return;
            }

            profileManager.LoadProfiles(progressReceiver);

            //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null);
            AnvilWorldProvider.LoadBlockConverter();

            PluginManager.EnablePlugins();

            var storage = Services.GetRequiredService <IStorageSystem>();

            if (storage.TryReadJson("skin.json", out EntityModel model))
            {
                PlayerModel = model;
            }

            if (storage.TryReadBytes("skin.png", out byte[] skinBytes))
示例#14
0
文件: Alex.cs 项目: wqd1019dqw/Alex
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");
            Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();

            ConfigureServices();

            var options = Services.GetService <IOptionsProvider>();

            string pluginDirectoryPaths = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            var pluginDir = options.AlexOptions.ResourceOptions.PluginDirectory;

            if (!string.IsNullOrWhiteSpace(pluginDir))
            {
                pluginDirectoryPaths = pluginDir;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(LaunchSettings.WorkDir) && Directory.Exists(LaunchSettings.WorkDir))
                {
                    pluginDirectoryPaths = LaunchSettings.WorkDir;
                }
            }

            foreach (string dirPath in pluginDirectoryPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                string directory = dirPath;
                if (!Path.IsPathRooted(directory))
                {
                    directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dirPath);
                }

                PluginManager.DiscoverPlugins(directory);
            }


            ProfileManager.LoadProfiles(progressReceiver);

            //	Log.Info($"Loading resources...");
            Resources = new ResourceManager(GraphicsDevice, Storage, options);
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver,
                                          OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();
                return;
            }

            GuiRenderer.LoadResourcePack(Resources.ResourcePack);
            AnvilWorldProvider.LoadBlockConverter();

            GameStateManager.AddState <TitleState>("title");

            if (LaunchSettings.ConnectOnLaunch && ProfileService.CurrentProfile != null)
            {
                ConnectToServer(LaunchSettings.Server, ProfileService.CurrentProfile, LaunchSettings.ConnectToBedrock);
            }
            else
            {
                GameStateManager.SetActiveState <TitleState>("title");
                var player = new Player(GraphicsDevice, this, null, null, new Skin(), null, PlayerIndex.One);
                player.Inventory.IsPeInventory = true;
                Random rnd = new Random();
                for (int i = 0; i < player.Inventory.SlotCount; i++)
                {
                    player.Inventory[i] = new ItemBlock(BlockFactory.AllBlockstates.ElementAt(rnd.Next() % BlockFactory.AllBlockstates.Count).Value)
                    {
                        Count = rnd.Next(1, 64)
                    };
                }
                //GuiManager.ShowDialog(new GuiPlayerInventoryDialog(player, player.Inventory));
            }

            GameStateManager.RemoveState("splash");
        }
示例#15
0
        private void ProcessNetwork()
        {
            int lastPacketId = 0;

            try
            {
                using (NetworkStream ns = new NetworkStream(Socket))
                {
                    using (MinecraftStream ms = new MinecraftStream(ns))
                    {
                        _readerStream = ms;

                        while (!CancellationToken.IsCancellationRequested)
                        {
                            Packets.Packet packet = null;
                            int            packetId;
                            byte[]         packetData;

                            if (!CompressionEnabled)
                            {
                                int length = ms.ReadVarInt();

                                int packetIdLength;
                                packetId     = ms.ReadVarInt(out packetIdLength);
                                lastPacketId = packetId;
                                if (length - packetIdLength > 0)
                                {
                                    packetData = ms.Read(length - packetIdLength);
                                }
                                else
                                {
                                    packetData = new byte[0];
                                }
                            }
                            else
                            {
                                int packetLength = ms.ReadVarInt();

                                int br;
                                int dataLength = ms.ReadVarInt(out br);

                                int readMore;
                                if (dataLength == 0)
                                {
                                    packetId     = ms.ReadVarInt(out readMore);
                                    lastPacketId = packetId;
                                    packetData   = ms.Read(packetLength - (br + readMore));
                                }
                                else
                                {
                                    byte[] data = ms.Read(packetLength - br);
                                    using (MinecraftStream a = new MinecraftStream())
                                    {
                                        using (ZlibStream outZStream = new ZlibStream(a,
                                                                                      CompressionMode.Decompress, CompressionLevel.Default, true))
                                        {
                                            outZStream.Write(data, 0, data.Length);
                                        }

                                        a.Seek(0, SeekOrigin.Begin);

                                        int l;
                                        packetId     = a.ReadVarInt(out l);
                                        lastPacketId = packetId;
                                        packetData   = a.Read(dataLength - l);
                                    }
                                }
                            }

                            packet = MCPacketFactory.GetPacket(Direction, ConnectionState, packetId);
                            if (packet == null)
                            {
                                if (UnhandledPacketsFilter[ConnectionState]
                                    .TryAdd(packetId, 1))
                                {
                                    Log.Debug(
                                        $"Unhandled packet in {ConnectionState}! 0x{packetId.ToString("x2")} = {(ConnectionState == ConnectionState.Play ? MCPacketFactory.GetPlayPacketName(packetId) : "Unknown")}");
                                }
                                else
                                {
                                    UnhandledPacketsFilter[ConnectionState][packetId] =
                                        UnhandledPacketsFilter[ConnectionState][packetId] + 1;
                                }

                                continue;
                            }

                            if (ConnectionState == ConnectionState.Play)
                            {
                                if (ShouldAddToProcessing(packet))
                                {
                                    Interlocked.Increment(ref _queued);
                                    ThreadPool.QueueUserWorkItem(() =>
                                    {
                                        ProcessPacket(packet, packetData);
                                        Interlocked.Decrement(ref _queued);
                                    });
                                }
                            }
                            else
                            {
                                ProcessPacket(packet, packetData);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException)
                {
                    return;
                }
                if (ex is EndOfStreamException)
                {
                    return;
                }
                if (ex is IOException)
                {
                    return;
                }

                if (LogExceptions)
                {
                    Log.Warn(
                        $"Failed to process network (Last packet: 0x{lastPacketId:X2} State: {ConnectionState}): " +
                        ex);
                }
            }
            finally
            {
                Disconnected(false);
            }
        }