Exemplo n.º 1
0
        /// <summary>
        /// Handle the given packet
        /// </summary>
        /// <param name="packetID">Packet ID</param>
        /// <param name="packetData">Packet contents</param>
        /// <returns>TRUE if the packet was processed, FALSE if ignored or unknown</returns>
        internal bool HandlePacket(Packet packet)
        {
            int         packetID   = packet.id;
            List <byte> packetData = packet.data;

            try
            {
                if (login_phase)
                {
                    switch (packetID) //Packet IDs are different while logging in
                    {
                    case 0x03:
                        if (protocolversion >= (int)McVersion.V18)
                        {
                            connectionInfo.compressionThreshold = dataTypes.ReadNextVarInt(packetData);
                        }
                        break;

                    default:
                        return(false);    //Ignored packet
                    }
                }
                return(packetHandler.HandlePacket(Protocol18PacketTypes.GetPacketIncomingType(packetID, protocolversion), packet.data));
            }
            catch (Exception innerException)
            {
                throw new System.IO.InvalidDataException(
                          String.Format("Failed to process incoming packet of type {0}. (PacketID: {1}, Protocol: {2}, LoginPhase: {3}, InnerException: {4}).",
                                        Protocol18PacketTypes.GetPacketIncomingType(packetID, protocolversion),
                                        packetID,
                                        protocolversion,
                                        login_phase,
                                        innerException.GetType()),
                          innerException);
            }
        }
        /// <summary>
        /// Handle Forge plugin messages
        /// </summary>
        /// <param name="channel">Plugin message channel</param>
        /// <param name="packetData">Plugin message data</param>
        /// <param name="currentDimension">Current world dimension</param>
        /// <returns>TRUE if the plugin message was recognized and handled</returns>
        public bool HandlePluginMessage(string channel, List <byte> packetData, ref int currentDimension)
        {
            if (ForgeEnabled() && fmlHandshakeState != FMLHandshakeClientState.DONE)
            {
                if (channel == "FML|HS")
                {
                    FMLHandshakeDiscriminator discriminator = (FMLHandshakeDiscriminator)dataTypes.ReadNextByte(packetData);

                    if (discriminator == FMLHandshakeDiscriminator.HandshakeReset)
                    {
                        fmlHandshakeState = FMLHandshakeClientState.START;
                        return(true);
                    }

                    switch (fmlHandshakeState)
                    {
                    case FMLHandshakeClientState.START:
                        if (discriminator != FMLHandshakeDiscriminator.ServerHello)
                        {
                            return(false);
                        }

                        // Send the plugin channel registration.
                        // REGISTER is somewhat special in that it doesn't actually include length information,
                        // and is also \0-separated.
                        // Also, yes, "FML" is there twice.  Don't ask me why, but that's the way forge does it.
                        string[] channels = { "FML|HS", "FML", "FML|MP", "FML", "FORGE" };
                        protocol18.SendPluginChannelPacket("REGISTER", Encoding.UTF8.GetBytes(string.Join("\0", channels)));

                        byte fmlProtocolVersion = dataTypes.ReadNextByte(packetData);

                        if (Settings.DebugMessages)
                        {
                            ConsoleIO.WriteLineFormatted("§8Forge protocol version : " + fmlProtocolVersion);
                        }

                        if (fmlProtocolVersion >= 1)
                        {
                            currentDimension = dataTypes.ReadNextInt(packetData);
                        }

                        // Tell the server we're running the same version.
                        SendForgeHandshakePacket(FMLHandshakeDiscriminator.ClientHello, new byte[] { fmlProtocolVersion });

                        // Then tell the server that we're running the same mods.
                        if (Settings.DebugMessages)
                        {
                            ConsoleIO.WriteLineFormatted("§8Sending falsified mod list to server...");
                        }
                        byte[][] mods = new byte[forgeInfo.Mods.Count][];
                        for (int i = 0; i < forgeInfo.Mods.Count; i++)
                        {
                            ForgeInfo.ForgeMod mod = forgeInfo.Mods[i];
                            mods[i] = dataTypes.ConcatBytes(dataTypes.GetString(mod.ModID), dataTypes.GetString(mod.Version));
                        }
                        SendForgeHandshakePacket(FMLHandshakeDiscriminator.ModList,
                                                 dataTypes.ConcatBytes(dataTypes.GetVarInt(forgeInfo.Mods.Count), dataTypes.ConcatBytes(mods)));

                        fmlHandshakeState = FMLHandshakeClientState.WAITINGSERVERDATA;

                        return(true);

                    case FMLHandshakeClientState.WAITINGSERVERDATA:
                        if (discriminator != FMLHandshakeDiscriminator.ModList)
                        {
                            return(false);
                        }

                        Thread.Sleep(2000);

                        if (Settings.DebugMessages)
                        {
                            ConsoleIO.WriteLineFormatted("§8Accepting server mod list...");
                        }
                        // Tell the server that yes, we are OK with the mods it has
                        // even though we don't actually care what mods it has.

                        SendForgeHandshakePacket(FMLHandshakeDiscriminator.HandshakeAck,
                                                 new byte[] { (byte)FMLHandshakeClientState.WAITINGSERVERDATA });

                        fmlHandshakeState = FMLHandshakeClientState.WAITINGSERVERCOMPLETE;
                        return(false);

                    case FMLHandshakeClientState.WAITINGSERVERCOMPLETE:
                        // The server now will tell us a bunch of registry information.
                        // We need to read it all, though, until it says that there is no more.
                        if (discriminator != FMLHandshakeDiscriminator.RegistryData)
                        {
                            return(false);
                        }

                        if (protocolversion < Protocol18Handler.MC18Version)
                        {
                            // 1.7.10 and below have one registry
                            // with blocks and items.
                            int registrySize = dataTypes.ReadNextVarInt(packetData);

                            if (Settings.DebugMessages)
                            {
                                ConsoleIO.WriteLineFormatted("§8Received registry with " + registrySize + " entries");
                            }

                            fmlHandshakeState = FMLHandshakeClientState.PENDINGCOMPLETE;
                        }
                        else
                        {
                            // 1.8+ has more than one registry.

                            bool   hasNextRegistry = dataTypes.ReadNextBool(packetData);
                            string registryName    = dataTypes.ReadNextString(packetData);
                            int    registrySize    = dataTypes.ReadNextVarInt(packetData);
                            if (Settings.DebugMessages)
                            {
                                ConsoleIO.WriteLineFormatted("§8Received registry " + registryName + " with " + registrySize + " entries");
                            }
                            if (!hasNextRegistry)
                            {
                                fmlHandshakeState = FMLHandshakeClientState.PENDINGCOMPLETE;
                            }
                        }

                        return(false);

                    case FMLHandshakeClientState.PENDINGCOMPLETE:
                        // The server will ask us to accept the registries.
                        // Just say yes.
                        if (discriminator != FMLHandshakeDiscriminator.HandshakeAck)
                        {
                            return(false);
                        }
                        if (Settings.DebugMessages)
                        {
                            ConsoleIO.WriteLineFormatted("§8Accepting server registries...");
                        }
                        SendForgeHandshakePacket(FMLHandshakeDiscriminator.HandshakeAck,
                                                 new byte[] { (byte)FMLHandshakeClientState.PENDINGCOMPLETE });
                        fmlHandshakeState = FMLHandshakeClientState.COMPLETE;

                        return(true);

                    case FMLHandshakeClientState.COMPLETE:
                        // One final "OK".  On the actual forge source, a packet is sent from
                        // the client to the client saying that the connection was complete, but
                        // we don't need to do that.

                        SendForgeHandshakePacket(FMLHandshakeDiscriminator.HandshakeAck,
                                                 new byte[] { (byte)FMLHandshakeClientState.COMPLETE });
                        if (Settings.DebugMessages)
                        {
                            ConsoleIO.WriteLine("Forge server connection complete!");
                        }
                        fmlHandshakeState = FMLHandshakeClientState.DONE;
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Read the next packet from the network
        /// </summary>
        /// <param name="packetID">will contain packet ID</param>
        /// <param name="packetData">will contain raw packet Data</param>
        internal void ReadNextPacket(ref int packetID, List <byte> packetData)
        {
            packetData.Clear();
            int size = dataTypes.ReadNextVarIntRAW(socketWrapper); //Packet size

            packetData.AddRange(socketWrapper.ReadDataRAW(size));  //Packet contents

            //Handle packet decompression
            if (protocolversion >= MC18Version &&
                compression_treshold > 0)
            {
                int sizeUncompressed = dataTypes.ReadNextVarInt(packetData);
                if (sizeUncompressed != 0) // != 0 means compressed, let's decompress
                {
                    byte[] toDecompress = packetData.ToArray();
                    byte[] uncompressed = ZlibUtils.Decompress(toDecompress, sizeUncompressed);
                    packetData.Clear();
                    packetData.AddRange(uncompressed);
                }
            }

            packetID = dataTypes.ReadNextVarInt(packetData); //Packet ID
        }
Exemplo n.º 4
0
        /// <summary>
        /// Ping a Minecraft server to get information about the server
        /// </summary>
        /// <returns>True if ping was successful</returns>
        public static bool doPing(string host, int port, ref int protocolversion, ref ForgeInfo forgeInfo)
        {
            string    version = "";
            TcpClient tcp     = ProxyHandler.newTcpClient(host, port);

            tcp.ReceiveBufferSize = 1024 * 1024;
            SocketWrapper socketWrapper = new SocketWrapper(tcp);
            DataTypes     dataTypes     = new DataTypes(MC18Version);

            byte[] packet_id        = dataTypes.GetVarInt(0);
            byte[] protocol_version = dataTypes.GetVarInt(-1);
            byte[] server_port      = BitConverter.GetBytes((ushort)port); Array.Reverse(server_port);
            byte[] next_state       = dataTypes.GetVarInt(1);
            byte[] packet           = dataTypes.ConcatBytes(packet_id, protocol_version, dataTypes.GetString(host), server_port, next_state);
            byte[] tosend           = dataTypes.ConcatBytes(dataTypes.GetVarInt(packet.Length), packet);

            socketWrapper.SendDataRAW(tosend);

            byte[] status_request = dataTypes.GetVarInt(0);
            byte[] request_packet = dataTypes.ConcatBytes(dataTypes.GetVarInt(status_request.Length), status_request);

            socketWrapper.SendDataRAW(request_packet);

            int packetLength = dataTypes.ReadNextVarIntRAW(socketWrapper);

            if (packetLength > 0) //Read Response length
            {
                List <byte> packetData = new List <byte>(socketWrapper.ReadDataRAW(packetLength));
                if (dataTypes.ReadNextVarInt(packetData) == 0x00)         //Read Packet ID
                {
                    string result = dataTypes.ReadNextString(packetData); //Get the Json data

                    if (!String.IsNullOrEmpty(result) && result.StartsWith("{") && result.EndsWith("}"))
                    {
                        Json.JSONData jsonData = Json.ParseJson(result);
                        if (jsonData.Type == Json.JSONData.DataType.Object && jsonData.Properties.ContainsKey("version"))
                        {
                            Json.JSONData versionData = jsonData.Properties["version"];

                            //Retrieve display name of the Minecraft version
                            if (versionData.Properties.ContainsKey("name"))
                            {
                                version = versionData.Properties["name"].StringValue;
                            }

                            //Retrieve protocol version number for handling this server
                            if (versionData.Properties.ContainsKey("protocol"))
                            {
                                protocolversion = dataTypes.Atoi(versionData.Properties["protocol"].StringValue);
                            }

                            // Check for forge on the server.
                            Protocol18Forge.ServerInfoCheckForge(jsonData, ref forgeInfo);

                            ConsoleIO.WriteLineFormatted("§8Server version : " + version + " (protocol v" + protocolversion + (forgeInfo != null ? ", with Forge)." : ")."));

                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Process chunk column data from the server and (un)load the chunk from the Minecraft world
        /// </summary>
        /// <param name="chunkX">Chunk X location</param>
        /// <param name="chunkZ">Chunk Z location</param>
        /// <param name="chunkMask">Chunk mask for reading data</param>
        /// <param name="chunkMask2">Chunk mask for some additional 1.7 metadata</param>
        /// <param name="hasSkyLight">Contains skylight info</param>
        /// <param name="chunksContinuous">Are the chunk continuous</param>
        /// <param name="currentDimension">Current dimension type (0 = overworld)</param>
        /// <param name="cache">Cache for reading chunk data</param>
        public void ProcessChunkColumnData(int chunkX, int chunkZ, ushort chunkMask, ushort chunkMask2, bool hasSkyLight, bool chunksContinuous, int currentDimension, Queue <byte> cache)
        {
            if (protocolversion >= Protocol18Handler.MC19Version)
            {
                // 1.9 and above chunk format
                // Unloading chunks is handled by a separate packet
                for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                {
                    if ((chunkMask & (1 << chunkY)) != 0)
                    {
                        // 1.14 and above Non-air block count inside chunk section, for lighting purposes
                        if (protocolversion >= Protocol18Handler.MC114Version)
                        {
                            dataTypes.ReadNextShort(cache);
                        }

                        byte bitsPerBlock = dataTypes.ReadNextByte(cache);
                        bool usePalette   = (bitsPerBlock <= 8);

                        // Vanilla Minecraft will use at least 4 bits per block
                        if (bitsPerBlock < 4)
                        {
                            bitsPerBlock = 4;
                        }

                        // MC 1.9 to 1.12 will set palette length field to 0 when palette
                        // is not used, MC 1.13+ does not send the field at all in this case
                        int paletteLength = 0; // Assume zero when length is absent
                        if (usePalette || protocolversion < Protocol18Handler.MC113Version)
                        {
                            paletteLength = dataTypes.ReadNextVarInt(cache);
                        }

                        int[] palette = new int[paletteLength];
                        for (int i = 0; i < paletteLength; i++)
                        {
                            palette[i] = dataTypes.ReadNextVarInt(cache);
                        }

                        // Bit mask covering bitsPerBlock bits
                        // EG, if bitsPerBlock = 5, valueMask = 00011111 in binary
                        uint valueMask = (uint)((1 << bitsPerBlock) - 1);

                        ulong[] dataArray = dataTypes.ReadNextULongArray(cache);

                        Chunk chunk = new Chunk();

                        if (dataArray.Length > 0)
                        {
                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        int blockNumber = (blockY * Chunk.SizeZ + blockZ) * Chunk.SizeX + blockX;

                                        int startLong   = (blockNumber * bitsPerBlock) / 64;
                                        int startOffset = (blockNumber * bitsPerBlock) % 64;
                                        int endLong     = ((blockNumber + 1) * bitsPerBlock - 1) / 64;

                                        // TODO: In the future a single ushort may not store the entire block id;
                                        // the Block code may need to change if block state IDs go beyond 65535
                                        ushort blockId;
                                        if (startLong == endLong)
                                        {
                                            blockId = (ushort)((dataArray[startLong] >> startOffset) & valueMask);
                                        }
                                        else
                                        {
                                            int endOffset = 64 - startOffset;
                                            blockId = (ushort)((dataArray[startLong] >> startOffset | dataArray[endLong] << endOffset) & valueMask);
                                        }

                                        if (usePalette)
                                        {
                                            // Get the real block ID out of the palette
                                            blockId = (ushort)palette[blockId];
                                        }

                                        chunk[blockX, blockY, blockZ] = new Block(blockId);
                                    }
                                }
                            }
                        }

                        //We have our chunk, save the chunk into the world
                        if (handler.GetWorld()[chunkX, chunkZ] == null)
                        {
                            handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                        }
                        handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;

                        //Pre-1.14 Lighting data
                        if (protocolversion < Protocol18Handler.MC114Version)
                        {
                            //Skip block light
                            dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

                            //Skip sky light
                            if (currentDimension == 0)
                            {
                                // Sky light is not sent in the nether or the end
                                dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);
                            }
                        }
                    }
                }

                // Don't worry about skipping remaining data since there is no useful data afterwards in 1.9
                // (plus, it would require parsing the tile entity lists' NBT)
            }
            else if (protocolversion >= Protocol18Handler.MC18Version)
            {
                // 1.8 chunk format
                if (chunksContinuous && chunkMask == 0)
                {
                    //Unload the entire chunk column
                    handler.GetWorld()[chunkX, chunkZ] = null;
                }
                else
                {
                    //Load chunk data from the server
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            Chunk chunk = new Chunk();

                            //Read chunk data, all at once for performance reasons, and build the chunk object
                            Queue <ushort> queue = new Queue <ushort>(dataTypes.ReadNextUShortsLittleEndian(Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ, cache));
                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        chunk[blockX, blockY, blockZ] = new Block(queue.Dequeue());
                                    }
                                }
                            }

                            //We have our chunk, save the chunk into the world
                            if (handler.GetWorld()[chunkX, chunkZ] == null)
                            {
                                handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                            }
                            handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
                        }
                    }

                    //Skip light information
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            //Skip block light
                            dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

                            //Skip sky light
                            if (hasSkyLight)
                            {
                                dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);
                            }
                        }
                    }

                    //Skip biome metadata
                    if (chunksContinuous)
                    {
                        dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache);
                    }
                }
            }
            else
            {
                // 1.7 chunk format
                if (chunksContinuous && chunkMask == 0)
                {
                    //Unload the entire chunk column
                    handler.GetWorld()[chunkX, chunkZ] = null;
                }
                else
                {
                    //Count chunk sections
                    int sectionCount        = 0;
                    int addDataSectionCount = 0;
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            sectionCount++;
                        }
                        if ((chunkMask2 & (1 << chunkY)) != 0)
                        {
                            addDataSectionCount++;
                        }
                    }

                    //Read chunk data, unpacking 4-bit values into 8-bit values for block metadata
                    Queue <byte> blockTypes = new Queue <byte>(dataTypes.ReadData(Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount, cache));
                    Queue <byte> blockMeta  = new Queue <byte>();
                    foreach (byte packed in dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache))
                    {
                        byte hig = (byte)(packed >> 4);
                        byte low = (byte)(packed & (byte)0x0F);
                        blockMeta.Enqueue(hig);
                        blockMeta.Enqueue(low);
                    }

                    //Skip data we don't need
                    dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache);          //Block light
                    if (hasSkyLight)
                    {
                        dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache);      //Sky light
                    }
                    dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * addDataSectionCount) / 2, cache);   //BlockAdd
                    if (chunksContinuous)
                    {
                        dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache);                                         //Biomes
                    }
                    //Load chunk data
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            Chunk chunk = new Chunk();

                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        chunk[blockX, blockY, blockZ] = new Block(blockTypes.Dequeue(), blockMeta.Dequeue());
                                    }
                                }
                            }

                            if (handler.GetWorld()[chunkX, chunkZ] == null)
                            {
                                handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                            }
                            handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Process chunk column data from the server and (un)load the chunk from the Minecraft world
        /// </summary>
        /// <param name="chunkX">Chunk X location</param>
        /// <param name="chunkZ">Chunk Z location</param>
        /// <param name="chunkMask">Chunk mask for reading data</param>
        /// <param name="chunkMask2">Chunk mask for some additional 1.7 metadata</param>
        /// <param name="hasSkyLight">Contains skylight info</param>
        /// <param name="chunksContinuous">Are the chunk continuous</param>
        /// <param name="currentDimension">Current dimension type (0 = overworld)</param>
        /// <param name="cache">Cache for reading chunk data</param>
        public void ProcessChunkColumnData(int chunkX, int chunkZ, ushort chunkMask, ushort chunkMask2, bool hasSkyLight, bool chunksContinuous, int currentDimension, Queue <byte> cache)
        {
            if (protocolversion >= Protocol18Handler.MC19Version)
            {
                // 1.9 and above chunk format
                // Unloading chunks is handled by a separate packet
                for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                {
                    if ((chunkMask & (1 << chunkY)) != 0)
                    {
                        // 1.14 and above Non-air block count inside chunk section, for lighting purposes
                        if (protocolversion >= Protocol18Handler.MC114Version)
                        {
                            dataTypes.ReadNextShort(cache);
                        }

                        byte bitsPerBlock = dataTypes.ReadNextByte(cache);
                        bool usePalette   = (bitsPerBlock <= 8);

                        // Vanilla Minecraft will use at least 4 bits per block
                        if (bitsPerBlock < 4)
                        {
                            bitsPerBlock = 4;
                        }

                        // MC 1.9 to 1.12 will set palette length field to 0 when palette
                        // is not used, MC 1.13+ does not send the field at all in this case
                        int paletteLength = 0; // Assume zero when length is absent
                        if (usePalette || protocolversion < Protocol18Handler.MC113Version)
                        {
                            paletteLength = dataTypes.ReadNextVarInt(cache);
                        }

                        int[] palette = new int[paletteLength];
                        for (int i = 0; i < paletteLength; i++)
                        {
                            palette[i] = dataTypes.ReadNextVarInt(cache);
                        }

                        // Bit mask covering bitsPerBlock bits
                        // EG, if bitsPerBlock = 5, valueMask = 00011111 in binary
                        uint valueMask = (uint)((1 << bitsPerBlock) - 1);

                        // Block IDs are packed in the array of 64-bits integers
                        ulong[] dataArray = dataTypes.ReadNextULongArray(cache);

                        Chunk chunk = new Chunk();

                        if (dataArray.Length > 0)
                        {
                            int longIndex   = 0;
                            int startOffset = 0 - bitsPerBlock;

                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        // NOTICE: In the future a single ushort may not store the entire block id;
                                        // the Block class may need to change if block state IDs go beyond 65535
                                        ushort blockId;

                                        // Calculate location of next block ID inside the array of Longs
                                        startOffset += bitsPerBlock;
                                        bool overlap = false;

                                        if ((startOffset + bitsPerBlock) > 64)
                                        {
                                            if (protocolversion >= Protocol18Handler.MC116Version)
                                            {
                                                // In MC 1.16+, padding is applied to prevent overlapping between Longs:
                                                // [      LONG INTEGER      ][      LONG INTEGER      ]
                                                // [Block][Block][Block]XXXXX[Block][Block][Block]XXXXX

                                                // When overlapping, move forward to the beginning of the next Long
                                                startOffset = 0;
                                                longIndex++;
                                            }
                                            else
                                            {
                                                // In MC 1.15 and lower, block IDs can overlap between Longs:
                                                // [      LONG INTEGER      ][      LONG INTEGER      ]
                                                // [Block][Block][Block][Blo  ck][Block][Block][Block][

                                                // Detect when we reached the next Long or switch to overlap mode
                                                if (startOffset >= 64)
                                                {
                                                    startOffset -= 64;
                                                    longIndex++;
                                                }
                                                else
                                                {
                                                    overlap = true;
                                                }
                                            }
                                        }

                                        // Extract Block ID
                                        if (overlap)
                                        {
                                            int endOffset = 64 - startOffset;
                                            blockId = (ushort)((dataArray[longIndex] >> startOffset | dataArray[longIndex + 1] << endOffset) & valueMask);
                                        }
                                        else
                                        {
                                            blockId = (ushort)((dataArray[longIndex] >> startOffset) & valueMask);
                                        }

                                        // Map small IDs to actual larger block IDs
                                        if (usePalette)
                                        {
                                            if (paletteLength <= blockId)
                                            {
                                                int blockNumber = (blockY * Chunk.SizeZ + blockZ) * Chunk.SizeX + blockX;
                                                throw new IndexOutOfRangeException(String.Format("Block ID {0} is outside Palette range 0-{1}! (bitsPerBlock: {2}, blockNumber: {3})",
                                                                                                 blockId,
                                                                                                 paletteLength - 1,
                                                                                                 bitsPerBlock,
                                                                                                 blockNumber));
                                            }

                                            blockId = (ushort)palette[blockId];
                                        }

                                        // We have our block, save the block into the chunk
                                        chunk[blockX, blockY, blockZ] = new Block(blockId);
                                    }
                                }
                            }
                        }

                        //We have our chunk, save the chunk into the world
                        if (handler.GetWorld()[chunkX, chunkZ] == null)
                        {
                            handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                        }
                        handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;

                        //Pre-1.14 Lighting data
                        if (protocolversion < Protocol18Handler.MC114Version)
                        {
                            //Skip block light
                            dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

                            //Skip sky light
                            if (currentDimension == 0)
                            {
                                // Sky light is not sent in the nether or the end
                                dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);
                            }
                        }
                    }
                }

                // Don't worry about skipping remaining data since there is no useful data afterwards in 1.9
                // (plus, it would require parsing the tile entity lists' NBT)
            }
            else if (protocolversion >= Protocol18Handler.MC18Version)
            {
                // 1.8 chunk format
                if (chunksContinuous && chunkMask == 0)
                {
                    //Unload the entire chunk column
                    handler.GetWorld()[chunkX, chunkZ] = null;
                }
                else
                {
                    //Load chunk data from the server
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            Chunk chunk = new Chunk();

                            //Read chunk data, all at once for performance reasons, and build the chunk object
                            Queue <ushort> queue = new Queue <ushort>(dataTypes.ReadNextUShortsLittleEndian(Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ, cache));
                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        chunk[blockX, blockY, blockZ] = new Block(queue.Dequeue());
                                    }
                                }
                            }

                            //We have our chunk, save the chunk into the world
                            if (handler.GetWorld()[chunkX, chunkZ] == null)
                            {
                                handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                            }
                            handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
                        }
                    }

                    //Skip light information
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            //Skip block light
                            dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);

                            //Skip sky light
                            if (hasSkyLight)
                            {
                                dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ) / 2, cache);
                            }
                        }
                    }

                    //Skip biome metadata
                    if (chunksContinuous)
                    {
                        dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache);
                    }
                }
            }
            else
            {
                // 1.7 chunk format
                if (chunksContinuous && chunkMask == 0)
                {
                    //Unload the entire chunk column
                    handler.GetWorld()[chunkX, chunkZ] = null;
                }
                else
                {
                    //Count chunk sections
                    int sectionCount        = 0;
                    int addDataSectionCount = 0;
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            sectionCount++;
                        }
                        if ((chunkMask2 & (1 << chunkY)) != 0)
                        {
                            addDataSectionCount++;
                        }
                    }

                    //Read chunk data, unpacking 4-bit values into 8-bit values for block metadata
                    Queue <byte> blockTypes = new Queue <byte>(dataTypes.ReadData(Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount, cache));
                    Queue <byte> blockMeta  = new Queue <byte>();
                    foreach (byte packed in dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache))
                    {
                        byte hig = (byte)(packed >> 4);
                        byte low = (byte)(packed & (byte)0x0F);
                        blockMeta.Enqueue(hig);
                        blockMeta.Enqueue(low);
                    }

                    //Skip data we don't need
                    dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache);          //Block light
                    if (hasSkyLight)
                    {
                        dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * sectionCount) / 2, cache);      //Sky light
                    }
                    dataTypes.ReadData((Chunk.SizeX * Chunk.SizeY * Chunk.SizeZ * addDataSectionCount) / 2, cache);   //BlockAdd
                    if (chunksContinuous)
                    {
                        dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache);                                         //Biomes
                    }
                    //Load chunk data
                    for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
                    {
                        if ((chunkMask & (1 << chunkY)) != 0)
                        {
                            Chunk chunk = new Chunk();

                            for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
                            {
                                for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
                                {
                                    for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
                                    {
                                        chunk[blockX, blockY, blockZ] = new Block(blockTypes.Dequeue(), blockMeta.Dequeue());
                                    }
                                }
                            }

                            if (handler.GetWorld()[chunkX, chunkZ] == null)
                            {
                                handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn();
                            }
                            handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
                        }
                    }
                }
            }
        }