Exemplo n.º 1
0
        private void ReadHeader()
        {
            if (FileStream.CanWrite && FileStream.Length < 1)
            {
                byte[] zbuf        = ZlibStream.CompressBuffer(new byte[0]);
                byte[] zero        = new byte[4];
                int    zlen_le     = EndianConverter.LittleEndian(zbuf.Length),
                       zero_fcount = EndianConverter.LittleEndian(7),
                       create_ver  = EndianConverter.LittleEndian(m_IntVersion);

                FileStream.Write(Encoding.ASCII.GetBytes(GRF_HEADER), 0, GRF_HEADER_LEN);
                FileStream.Write(CryptWatermark, 0, CryptWatermark.Length);
                FileStream.Write(zero, 0, 4);
                FileStream.Write(zero, 0, 4);
                FileStream.Write(BitConverter.GetBytes(zero_fcount), 0, 4);
                FileStream.Write(BitConverter.GetBytes(create_ver), 0, 4);
                FileStream.Write(BitConverter.GetBytes(zlen_le), 0, 4);
                FileStream.Write(zero, 0, 4);
                FileStream.Write(zbuf, 0, zbuf.Length);

                FileStream.Seek(0, SeekOrigin.Begin);
            }

            byte[] buf = new byte[GRF_HEADER_FULL_LEN];
            FileStream.Read(buf, 0, buf.Length);

            if (buf[GRF_HEADER_LEN + 1] == 1)
            {
                m_AllowCrypt = true;
                // 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E
                for (byte i = 0; i < 0xF; i++)
                {
                    if (buf[GRF_HEADER_LEN + i] != i)
                    {
                        throw new GrfException();
                    }
                }
            }
            else if (buf[GRF_HEADER_LEN] == 0)
            {
                m_AllowCrypt = false;
                // 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
                for (byte i = 0; i < 0xF; i++)
                {
                    if (buf[GRF_HEADER_LEN + i] != 0)
                    {
                        throw new GrfException();
                    }
                }
            }
            else
            {
                throw new GrfException();
            }

            using (IntPtrEx pBuffer = new IntPtrEx(buf))
            {
                m_Items = new GrfItemCollection(this);

                m_IntVersion     = EndianConverter.LittleEndian(pBuffer.Read <int>(GRF_HEADER_MID_LEN + 0xC));
                m_Items.Capacity = EndianConverter.LittleEndian(pBuffer.Read <int>(GRF_HEADER_MID_LEN + 8))
                                   - EndianConverter.LittleEndian(pBuffer.Read <int>(GRF_HEADER_MID_LEN + 4))
                                   - 7;

                FileStream.Seek(EndianConverter.LittleEndian(pBuffer.Read <int>(GRF_HEADER_MID_LEN) + GRF_HEADER_FULL_LEN), SeekOrigin.Begin);
            }

            switch (m_IntVersion & 0xFF00)
            {
            case 0x0200: ReadVer2Info(); break;

            case 0x0100: ReadVer1Info(); break;

            default: throw new GrfException();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// This this grf in the specified path.
        /// </summary>
        /// <param name="filepath">The path where to save the grf.</param>
        public void SaveAs(string filepath)
        {
            // Write to temporary file
            string       tempfile = Path.GetTempFileName();
            FileStream   fs       = new FileStream(tempfile, FileMode.Create);
            BinaryWriter bw       = new BinaryWriter(fs);

            byte[] signatureByte = new byte[Math.Max(_signature.Length, 15)];
            Encoding.ASCII.GetBytes(_signature).CopyTo(signatureByte, 0);
            bw.Write(signatureByte, 0, 15);
            bw.Write((byte)0);
            bw.Write(_encryptionKey, 0, 14);

            bw.Write((int)0); // will be updated later
            bw.Write((int)_m1);
            bw.Write((int)_GRFFiles.Count + _m1 + 7);
            bw.Write((int)0x200); // We always save as 2.0
            OnGRFMetaWriteComplete();
            foreach (GRFFile file in _GRFFiles)
            {
                file.SaveBody(bw);
                OnFileBodyWriteComplete(new GRFEventArg(file));
            }

            bw.Flush();

            int fileTablePos = (int)fs.Position;

            MemoryStream bodyStream = new MemoryStream();
            BinaryWriter bw2        = new BinaryWriter(bodyStream);

            foreach (GRFFile file in _GRFFiles)
            {
                file.Save(bw2);
                OnFileTableWriteComplete(new GRFEventArg(file));
            }

            bw2.Flush();
            //byte[] compressedBody = new byte[_uncompressedLength + 100];
            //int size = compressedBody.Length;
            //ZLib.compress(compressedBody, ref size, bodyStream.GetBuffer(), (int)bodyStream.Length);
            byte[] compressedBody = ZlibStream.CompressBuffer(bodyStream.GetBuffer());

            bw.Write((int)compressedBody.Length);
            bw.Write((int)bodyStream.Length);
            bw.Write(compressedBody, 0, compressedBody.Length);
            bw2.Close();

            // Update file table offset
            bw.BaseStream.Seek(30, SeekOrigin.Begin);
            bw.Write((int)fileTablePos - 46);

            bw.Close();

            if (_grfStream != null)
            {
                _grfStream.Close();
            }

            File.Copy(tempfile, filepath, true);
            OnGRFSaveComplete();

            _filePathToGRF = filepath;
            Close();
            Open();
        }
Exemplo n.º 3
0
        public static void Process(string filename, string paramfile)
        {
            var firmware = File.ReadAllText(filename);
            var param    = File.ReadAllText(paramfile).Replace("\r", "");

            var fw_json   = JsonConvert.DeserializeObject <Hashtable>(firmware);
            var fw_base64 = fw_json["image"].ToString();
            var fw_binary = new MemoryStream();

            ZlibStream decompressionStream = new ZlibStream(new MemoryStream(Convert.FromBase64String(fw_base64)),
                                                            CompressionMode.Decompress);

            decompressionStream.CopyTo(fw_binary);

            var magic_str   = "PARMDEF";
            var param_magic = new byte[] { 0x55, 0x37, 0xf4, 0xa0, 0x38, 0x5d, 0x48, 0x5b };

            fw_binary.Position = 0;
            var offset = ReadOneSrch(fw_binary, magic_str.Select(a => (byte)a).ToArray());

            if (offset == -1)
            {
                throw new Exception("No param area found");
            }

            var magicoffset = ReadOneSrch(fw_binary, param_magic);

            if (magicoffset != -1)
            {
                var foffset = fw_binary.Position;
                var br      = new BinaryReader(fw_binary);

                var max_len = br.ReadInt16();
                var length  = br.ReadInt16();
                Console.WriteLine("Found param defaults max_length={0} length={1}", max_len, length);

                if (param.Length > max_len)
                {
                    throw new Exception(String.Format("Error: Length {0} larger than maximum {1}", length, max_len));
                }

                var paramdata = new byte[length];
                br.Read(paramdata, 0, length);

                var paramstring = ASCIIEncoding.ASCII.GetString(paramdata);

                var new_fwms = new MemoryStream(fw_binary.GetBuffer());
                var new_fw   = new BinaryWriter(new_fwms);

                new_fw.Seek((int)foffset + 2, SeekOrigin.Begin);
                new_fw.Write((short)param.Length);
                new_fw.Write(ASCIIEncoding.ASCII.GetBytes(param), 0, param.Length);

                fw_json["image"] = Convert.ToBase64String(ZlibStream.CompressBuffer(new_fwms.GetBuffer()));

                //File.WriteAllBytes(filename + "orig.bin", fw_binary.ToArray());
                //File.WriteAllBytes(filename + "new.bin", new_fwms.ToArray());
                File.WriteAllText(filename + "new.apj", JsonConvert.SerializeObject(fw_json, Formatting.Indented));

                return;
            }

            throw new Exception("Error: Param defaults support not found in firmware");
        }
Exemplo n.º 4
0
 public void ReCompress()
 {
     this.Compressed = ZlibStream.CompressBuffer(this.Content);
 }
 public override void WriteJson(JsonWriter writer, object?value, JsonSerializer serializer)
 {
     if (value is byte[] data)
     {
         writer.WriteValue(Convert.ToBase64String(data.Length > Treshold ? ZlibStream.CompressBuffer(data) : data));
     }
     else
     {
         writer.WriteNull();
     }
 }
Exemplo n.º 6
0
        public void SaveCharacter(Account acc, Char chr)
        {
            MySqlCommand cmd = CreateQuery();

            cmd.CommandText = @"UPDATE characters SET 
level=@level, 
exp=@exp, 
fame=@fame, 
items=@items, 
stats=@stats, 
hp=@hp, 
mp=@mp, 
tex1=@tex1, 
tex2=@tex2, 
pet=@pet, 
fameStats=@fameStats 
WHERE accId=@accId AND charId=@charId;";
            cmd.Parameters.AddWithValue("@accId", acc.AccountId);
            cmd.Parameters.AddWithValue("@charId", chr.CharacterId);

            cmd.Parameters.AddWithValue("@level", chr.Level);
            cmd.Parameters.AddWithValue("@exp", chr.Exp);
            cmd.Parameters.AddWithValue("@fame", chr.CurrentFame);
            cmd.Parameters.AddWithValue("@items", Utils.GetCommaSepString(chr.EquipSlots()));
            cmd.Parameters.AddWithValue("@stats", Utils.GetCommaSepString(new[]
            {
                chr.MaxHitPoints,
                chr.MaxMagicPoints,
                chr.Attack,
                chr.Defense,
                chr.Speed,
                chr.HpRegen,
                chr.MpRegen,
                chr.Dexterity
            }));
            cmd.Parameters.AddWithValue("@hp", chr.HitPoints);
            cmd.Parameters.AddWithValue("@mp", chr.MagicPoints);
            cmd.Parameters.AddWithValue("@tex1", chr.Tex1);
            cmd.Parameters.AddWithValue("@tex2", chr.Tex2);
            cmd.Parameters.AddWithValue("@pet", chr.Pet);
            chr.PCStats =
                Convert.ToBase64String(ZlibStream.CompressBuffer(chr.FameStats.Write()))
                .Replace('+', '-')
                .Replace('/', '_');
            cmd.Parameters.AddWithValue("@fameStats", chr.PCStats);
            cmd.ExecuteNonQuery();

            cmd             = CreateQuery();
            cmd.CommandText = @"INSERT INTO classstats(accId, objType, bestLv, bestFame) 
VALUES(@accId, @objType, @bestLv, @bestFame) 
ON DUPLICATE KEY UPDATE 
bestLv = GREATEST(bestLv, @bestLv), 
bestFame = GREATEST(bestFame, @bestFame);";
            cmd.Parameters.AddWithValue("@accId", acc.AccountId);
            cmd.Parameters.AddWithValue("@objType", chr.ObjectType);
            cmd.Parameters.AddWithValue("@bestLv", chr.Level);
            cmd.Parameters.AddWithValue("@bestFame", chr.CurrentFame);
            cmd.ExecuteNonQuery();

            SaveBackpacks(chr, acc);
        }
Exemplo n.º 7
0
        /// <summary>
        ///     Flush all data to the TCPClient NetworkStream.
        /// </summary>
        public void FlushData(bool quee = false)
        {
            try
            {
                var allData = _bffr.ToArray();
                _bffr.Clear();

                if (ServerSettings.UseCompression && _client.PacketMode == PacketMode.Play && _client.SetCompressionSend)
                {
                    bool isOver     = (allData.Length >= ServerSettings.CompressionThreshold);
                    int  dataLength = isOver ? allData.Length : 0;

                    //Calculate length of 'Data Length'
                    byte[] dLength = GetVarIntBytes(dataLength);

                    //Create all data
                    var compressedBytes = ZlibStream.CompressBuffer(allData);
                    int packetlength    = compressedBytes.Length + dLength.Length;
                    var dataToSend      = isOver ? compressedBytes : allData;

                    var compressed = new DataBuffer(_client);
                    compressed.WriteVarInt(packetlength);
                    compressed.WriteVarInt(dataLength);
                    compressed.Write(dataToSend);

                    Console.WriteLine();

                    Console.WriteLine("Packet bigger than Threshold: " + isOver);
                    Console.WriteLine("Packet info: ");

                    Console.WriteLine("(Header) Packet Length: " + packetlength);
                    Console.WriteLine("(Header) Data Length: " + dataLength);
                    Console.WriteLine("Data Length " + dataToSend.Length);
                    Console.WriteLine("Length difference: " + (packetlength - dataToSend.Length));

                    Console.WriteLine();

                    _client.AddToQuee(compressed.ExportWriter, quee);
                }
                else
                {
                    WriteVarInt(allData.Length);
                    var buffer = _bffr.ToArray();

                    var data = new List <byte>();
                    foreach (var i in buffer)
                    {
                        data.Add(i);
                    }
                    foreach (var i in allData)
                    {
                        data.Add(i);
                    }
                    _client.AddToQuee(data.ToArray(), quee);
                }
                _bffr.Clear();
            }
            catch (Exception ex)
            {
                //	ConsoleFunctions.WriteErrorLine("Failed to send a packet!\n" + ex);
                Globals.ClientManager.PacketError(_client, ex);
            }
        }
Exemplo n.º 8
0
 public static byte[] Compress(this byte[] value)
 {
     // compress
     return(ZlibStream.CompressBuffer(value));
 }
Exemplo n.º 9
0
 /// <summary>ZLib encoder.</summary>
 /// <param name="input">The input.</param>
 /// <returns>Compressed data.</returns>
 public static byte[] ZLibEncoder(byte[] input)
 {
     return(ZlibStream.CompressBuffer(input));
 }
Exemplo n.º 10
0
        /// <summary>
        /// Convert the ushort array to a byte arraay, compressing with the requested algorithm if required
        /// </summary>
        /// <param name="data"></param>
        /// <returns>Uncompressed or compressed byte array</returns>
        private byte[] PrepareArray(ushort[] data)
        {
            byte[] outArray;

            /*
             * Convert the ushort[] into a byte[]
             * From here onwards we deal in byte arrays only
             */
            byte[] byteArray = new byte[data.Length * ShuffleItemSize];
            Buffer.BlockCopy(data, 0, byteArray, 0, data.Length * ShuffleItemSize);

            /*
             * Compress the data block as configured.
             */
            using (MyStopWatch.Measure($"XISF Compression = {CompressionType}")) {
                if (CompressionType == XISFCompressionTypeEnum.LZ4)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "lz4+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "lz4";
                    }

                    byte[] tmpArray       = new byte[LZ4Codec.MaximumOutputSize(byteArray.Length)];
                    int    compressedSize = LZ4Codec.Encode(byteArray, 0, byteArray.Length, tmpArray, 0, tmpArray.Length, LZ4Level.L00_FAST);

                    outArray = new byte[compressedSize];
                    Array.Copy(tmpArray, outArray, outArray.Length);
                    tmpArray = null;
                }
                else if (CompressionType == XISFCompressionTypeEnum.LZ4HC)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "lz4hc+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "lz4hc";
                    }

                    byte[] tmpArray       = new byte[LZ4Codec.MaximumOutputSize(byteArray.Length)];
                    int    compressedSize = LZ4Codec.Encode(byteArray, 0, byteArray.Length, tmpArray, 0, tmpArray.Length, LZ4Level.L06_HC);

                    outArray = new byte[compressedSize];
                    Array.Copy(tmpArray, outArray, outArray.Length);
                    tmpArray = null;
                }
                else if (CompressionType == XISFCompressionTypeEnum.ZLIB)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "zlib+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "zlib";
                    }

                    outArray = ZlibStream.CompressBuffer(byteArray);
                }
                else
                {
                    outArray = new byte[byteArray.Length];
                    Array.Copy(byteArray, outArray, outArray.Length);
                    CompressionName = null;
                }
            }

            // Revert to the original data array in case the compression is bigger than uncompressed
            if (outArray.Length > byteArray.Length)
            {
                if (ByteShuffling)
                {
                    //As the original array is shuffled it needs to be unshuffled again - this scenario should be highly unlikely anyways
                    outArray = Unshuffle(byteArray, ShuffleItemSize);
                }
                else
                {
                    outArray = byteArray;
                }
                CompressionType = XISFCompressionTypeEnum.NONE;

                Logger.Debug("XISF output array is larger after compression. Image will be prepared uncompressed instead.");
            }

            if (CompressionType != XISFCompressionTypeEnum.NONE)
            {
                double percentChanged = (1 - ((double)outArray.Length / (double)byteArray.Length)) * 100;
                Logger.Debug($"XISF: {CompressionType} compressed {byteArray.Length} bytes to {outArray.Length} bytes ({percentChanged.ToString("#.##")}%)");
            }

            /*
             * Checksum the data block as configured.
             * If the data block is compressed, we always checksum the compressed form, not the uncompressed form.
             */
            using (MyStopWatch.Measure($"XISF Checksum = {ChecksumType}")) {
                SHA3Managed sha3;

                switch (ChecksumType)
                {
                case XISFChecksumTypeEnum.SHA1:
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha1.ComputeHash(outArray));
                    ChecksumName = "sha-1";
                    sha1.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA256:
                    SHA256 sha256 = new SHA256CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha256.ComputeHash(outArray));
                    ChecksumName = "sha-256";
                    sha256.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA512:
                    SHA512 sha512 = new SHA512CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha512.ComputeHash(outArray));
                    ChecksumName = "sha-512";
                    sha512.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA3_256:
                    sha3         = new SHA3Managed(256);
                    Checksum     = GetStringFromHash(sha3.ComputeHash(outArray));
                    ChecksumName = "sha3-256";
                    sha3.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA3_512:
                    sha3         = new SHA3Managed(512);
                    Checksum     = GetStringFromHash(sha3.ComputeHash(outArray));
                    ChecksumName = "sha3-512";
                    sha3.Dispose();
                    break;

                case XISFChecksumTypeEnum.NONE:
                default:
                    Checksum     = null;
                    ChecksumName = null;
                    break;
                }
            }

            return(outArray);
        }
Exemplo n.º 11
0
        internal override void Encode()
        {
            int Count = 6;

            this.Data.AddBool(false);

            this.Data.AddVInt(0);

            this.Data.AddVInt(21);

            this.Data.AddVInt((int)TimeUtils.ToUnixTimestamp(DateTime.Now));  // Timestamp

            this.Data.AddVInt(11);
            this.Data.AddVInt(0);

            this.Data.AddRange("D0B5AFB4E6A8D9EF".HexaToBytes()); // Checksum?

            this.Data.AddVInt(6);
            this.Data.AddVInt(1);

            this.Data.AddRange("7F7F7F7F0000".HexaToBytes()); // Enemy ID

            this.Data.AddString(string.Empty);

            this.Data.AddVInt(21);
            this.Data.AddVInt(9999);

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(7);

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(11);

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(4);

            this.Data.AddRange(this.Device.Player.Battle.ToBytes);

            this.Data.AddVInt(1);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(2);
            this.Data.AddVInt(2); //Player amount

            this.Data.AddVInt(44);

            this.Data.AddVInt(1);

            this.Data.AddHexa("7F7F");

            this.Data.AddVInt(0);

            this.Data.AddVInt(this.Device.Player.UserHighId);
            this.Data.AddVInt(this.Device.Player.UserLowId);

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            // IsTrainer
            // True = NPC
            // False = PVP

            this.Data.AddBool(true);

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(142);
            this.Data.AddVInt(62077);

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(Count);
            this.Data.AddVInt(Count);

            this.Data.AddVInt(35);
            this.Data.AddVInt(1);

            this.Data.AddVInt(35);
            this.Data.AddVInt(1);

            this.Data.AddVInt(35);
            this.Data.AddVInt(1);

            this.Data.AddVInt(35);
            this.Data.AddVInt(1);

            this.Data.AddVInt(35);
            this.Data.AddVInt(0);

            this.Data.AddVInt(35);
            this.Data.AddVInt(0);

            this.Data.AddVInt(1);
            this.Data.AddVInt(0);
            this.Data.AddVInt(1);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(1);

            for (int Index = 0; Index < Count; Index++)
            {
                this.Data.AddVInt(5);
                this.Data.AddVInt(Index);
            }

            this.Data.AddVInt(12);    //Level Tower R
            this.Data.AddVInt(13);    //Prefixed
            this.Data.AddVInt(14500); //Tower R Z
            this.Data.AddVInt(25500); //Tower R Y
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(49276);
            this.Data.AddVInt(0);
            this.Data.AddVInt(41985);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(2);

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(12);   //Level Tower R Enemy
            this.Data.AddVInt(13);   //Prefixed
            this.Data.AddVInt(3500); //Tower R Enemy X
            this.Data.AddVInt(6500); //Tower R Enemy Y
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(32772);
            this.Data.AddVInt(0);
            this.Data.AddVInt(41985);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(1);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(12);    //Level Tower L
            this.Data.AddVInt(13);    //Prefixed
            this.Data.AddVInt(3500);  //Tower L X
            this.Data.AddVInt(25500); //Tower L Y
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(49276);
            this.Data.AddVInt(0);
            this.Data.AddVInt(41985);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(1);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(12);    //Level Tower L Enemy
            this.Data.AddVInt(13);    //Prefixed
            this.Data.AddVInt(14500); //Tower L Enemy X
            this.Data.AddVInt(6500);  //Tower L Enemy Y
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(32772);
            this.Data.AddVInt(0);
            this.Data.AddVInt(41985);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(1);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(12);   //Enemy Crown Tower Level
            this.Data.AddVInt(13);   //Prefixed
            this.Data.AddVInt(9000); //Crown Tower Enemy X
            this.Data.AddVInt(3000); //Tower Tower Enemy Y
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(32772);
            this.Data.AddVInt(0);
            this.Data.AddVInt(41985);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(5);
            this.Data.AddVInt(4);
            this.Data.AddVInt(5);
            this.Data.AddRange("027D020401030200007F7F000000".HexaToBytes());
            this.Data.AddVInt(5); // Elixir Start
            this.Data.AddHexa("00000000007F7F7F7F7F7F7F7F");

            this.Data.AddVInt(12);    //Crown Tower Level
            this.Data.AddVInt(13);    //Prefixed
            this.Data.AddVInt(9000);  //Crown Tower  X
            this.Data.AddVInt(29000); //Crown Tower Tower  Y
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(49276);
            this.Data.AddVInt(0);
            this.Data.AddVInt(41985);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(5);
            this.Data.AddVInt(4);
            this.Data.AddVInt(6);
            this.Data.AddRange("7B067E0403000204007F7F000000".HexaToBytes());
            this.Data.AddVInt(5); // Elixir Start
            this.Data.AddRange("00000000007F7F7F7F7F7F7F7F".HexaToBytes());

            for (int Index = 0; Index < 48; Index++)
            {
                this.Data.AddVInt(0);
            }

            this.Data.AddVInt(3668); // Player R
            this.Data.AddVInt(3668); // Enemy R
            this.Data.AddVInt(3668); // Player L
            this.Data.AddVInt(3668); // Enemy L
            this.Data.AddVInt(5832); // Enemy Crown
            this.Data.AddVInt(5832); // Player Crown

            for (int Index = 0; Index < Count; Index++)
            {
                this.Data.AddVInt(0);
                this.Data.AddVInt(0);
                this.Data.AddVInt(0);
                this.Data.AddVInt(0);
                this.Data.AddVInt(0);
                this.Data.AddVInt(0);
                this.Data.AddVInt(0);

                this.Data.AddVInt(41985);
                this.Data.AddVInt(41985);
            }

            this.Data.AddRange("FF0184010A2A0B1F0B190B2509020B0707060B00".HexaToBytes()); //Deck - Card Type-ID-Level
            this.Data.AddHexa("FE03");
            this.Data.AddRange(this.Device.Player.Decks.Hand());
            this.Data.AddRange("0000050602020402010300000000000000060901010000000000000000000000010000000000000000000000000C00000080A1B0A80F002A002B".HexaToBytes());

            ZlibStream.CompressBuffer(this.Data.ToArray());
        }
Exemplo n.º 12
0
        /// <summary>
        /// 圧縮
        /// </summary>
        public byte[] Deflate()
        {
            //データ部圧縮
            //compress datas
            List <int>    originalContentDataSizeTable   = new List <int>();
            List <byte[]> compressedContentDataTable     = new List <byte[]>(_contentFileInfoTable.Count);
            int           compressedContentDataTableSize = 0;

            for (int contentIndex = 0; contentIndex < _contentFileInfoTable.Count; contentIndex++)
            {
                var fileInfo = _contentFileInfoTable[contentIndex];
                var data     = System.IO.File.ReadAllBytes(fileInfo.FullName);
                originalContentDataSizeTable.Add(data.Length);
                var compressed = ZlibStream.CompressBuffer(data);
                compressedContentDataTableSize += compressed.Length;
                compressedContentDataTable.Add(compressed);
            }

            //ファイル名部圧縮
            //compress name table
            byte[] compressedContentNameTable     = null;
            int    compressedContentNameTableSize = 0;

            {
                //全ファイル名結合
                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                foreach (var s in _contentNameTable)
                {
                    builder.Append(s);
                    compressedContentNameTableSize += System.Text.Encoding.UTF8.GetByteCount(s);
                }

                compressedContentNameTable = ZlibStream.CompressString(builder.ToString());
            }

            //コンテンツ情報部圧縮
            //compress contents
            byte[] compressedContentTable = null;
            {
                byte[] headerTable = new byte[SZipContent.Size * _contentFileInfoTable.Count];
                using (MemoryStream stream = new MemoryStream(headerTable))
                {
                    using (BinaryWriter writer = new BinaryWriter(stream))
                    {
                        for (int contentIndex = 0; contentIndex < _contentFileInfoTable.Count; contentIndex++)
                        {
                            var           content = new SZipContent();
                            System.UInt32 crc     = SZipUtility.FNVHash(compressedContentDataTable[contentIndex]);
                            content.Set(_contentNameTable[contentIndex].Length,
                                        originalContentDataSizeTable[contentIndex],
                                        compressedContentDataTable[contentIndex].Length,
                                        crc);
                            content.Write(writer);
                        }
                    }
                }
                compressedContentTable = ZlibStream.CompressBuffer(headerTable);
            }

            //ヘッダ生成
            //create szip header
            var header = new SZipHeader();

            header.Set((System.Int16)_contentFileInfoTable.Count,
                       SZipUtility.FNVHash(compressedContentNameTable),
                       SZipUtility.FNVHash(compressedContentTable),
                       compressedContentTable.Length,
                       compressedContentNameTableSize,
                       compressedContentNameTable.Length);

            //書き込み
            //write to byte[]
            {
                int totalSize = SZipHeader.Size
                                + compressedContentTable.Length
                                + compressedContentNameTable.Length
                                + compressedContentDataTableSize;

                byte[] output = new byte[totalSize];

                using (MemoryStream stream = new MemoryStream(output))
                {
                    using (BinaryWriter writer = new BinaryWriter(stream))
                    {
                        //ヘッダ
                        header.Write(writer);

                        //コンテンツ
                        writer.Write(compressedContentTable);

                        //コンテンツ名
                        writer.Write(compressedContentNameTable);

                        //データ
                        foreach (var data in compressedContentDataTable)
                        {
                            writer.Write(data);
                        }
                    }
                }

                return(output);
            }
        }
Exemplo n.º 13
0
 public byte[] GetZlib()
 {
     byte[] ret = ZlibStream.CompressBuffer(((MemoryStream)MyStream).ToArray());
     return(ret);
 }
Exemplo n.º 14
0
        private void FlushVer2()
        {
            byte[]      buffer = new byte[m_Items.Count * GRF_ITEM_SIZE];
            IntPtrEx    pName;
            int         i, offset, len;
            GrfFileInfo gfile = null;

            try
            {
                m_Items.SortToPosition();

                using (IntPtrEx pBuffer = new IntPtrEx(buffer))
                {
                    for (i = offset = 0; i < Items.Count; i++)
                    {
                        len = m_Items[i].FullName.Length + 1;
                        using (pName = new IntPtrEx(m_Items[i].FullName))
                        {
                            Marshal.Copy(pName, buffer, offset, len);
                        }

                        offset += len;

                        if (m_Items[i] is GrfFileInfo)
                        {
                            gfile = (GrfFileInfo)m_Items[i];

                            if (m_ForceRepack)
                            {
                                gfile.CompressedLength        = 0;
                                gfile.AlignedCompressedLength = 0;
                                gfile.Position = 0;
                            }

                            if (gfile.CompressedLength == 0 &&
                                gfile.AlignedCompressedLength == 0 &&
                                gfile.Position == 0 &&
                                gfile.Length != 0)
                            {
                                if (!m_AllowCrypt)
                                {
                                    gfile.Flags &= ~(GrfFileFlags.MixCrypt | GrfFileFlags.Des_0x14);
                                }

                                FlushFile(i);
                            }

                            pBuffer.Write <int>(offset, EndianConverter.LittleEndian(gfile.CompressedLength));
                            pBuffer.Write <int>(offset + 4, EndianConverter.LittleEndian(gfile.AlignedCompressedLength));
                            pBuffer.Write <int>(offset + 8, EndianConverter.LittleEndian(gfile.Length));
                            pBuffer.Write <int>(offset + 0xD, EndianConverter.LittleEndian(gfile.Position - GRF_HEADER_FULL_LEN));
                        }
                        else
                        {
                            pBuffer.Write <int>(offset, EndianConverter.LittleEndian(GrfItem.GRFFILE_DIR_SZSMALL));
                            pBuffer.Write <int>(offset + 4, EndianConverter.LittleEndian(GrfItem.GRFFILE_DIR_SZFILE));
                            pBuffer.Write <int>(offset + 8, EndianConverter.LittleEndian(GrfItem.GRFFILE_DIR_SZORIG));
                            pBuffer.Write <int>(offset + 0xD, EndianConverter.LittleEndian(GrfItem.GRFFILE_DIR_OFFSET - GRF_HEADER_FULL_LEN));
                        }

                        pBuffer.Write <byte>(offset + 0xC, (byte)m_Items[i].Flags);

                        offset += 0x11;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            Array.Resize <byte>(ref buffer, offset);
            buffer = ZlibStream.CompressBuffer(buffer);

            m_Items.SortToPosition();

            int writeOffset = m_Items.FindUnused(8 + buffer.Length);

            if (writeOffset == 0)
            {
                FileStream.Seek(0, SeekOrigin.End);
                writeOffset = (int)FileStream.Position;
            }
            else
            {
                FileStream.Seek(writeOffset, SeekOrigin.Begin);
            }

            FileStream.Write(BitConverter.GetBytes(EndianConverter.LittleEndian(buffer.Length)), 0, 4);
            FileStream.Write(BitConverter.GetBytes(EndianConverter.LittleEndian(offset)), 0, 4);
            FileStream.Write(buffer, 0, buffer.Length);

            FileStream.Seek(GRF_HEADER_MID_LEN, SeekOrigin.Begin);

            FileStream.Write(BitConverter.GetBytes(EndianConverter.LittleEndian(writeOffset - GRF_HEADER_FULL_LEN)), 0, 4);
            FileStream.Write(BitConverter.GetBytes(0), 0, 4);
            FileStream.Write(BitConverter.GetBytes(EndianConverter.LittleEndian(i + 7)), 0, 4);
        }
Exemplo n.º 15
0
        public static ChunkDataPacket CreatePacket(Chunk chunk)
        {
            var packet = new ChunkDataPacket();

            var X = (int)chunk.AbsolutePosition.X;
            var Z = (int)chunk.AbsolutePosition.Z;

            byte[] blockData;
            byte[] metadata;
            byte[] blockLight;
            byte[] skyLight;

            ushort mask = 1, chunkY = 0;
            bool   nonAir = true;

            // First pass calculates number of sections to send
            int totalSections = 0;

            for (int i = 15; i >= 0; i--)
            {
                Section s = chunk.Sections[chunkY++];

                if (s.IsAir)
                {
                    nonAir = false;
                }
                if (nonAir)
                {
                    totalSections++;
                }
            }

            mask       = 1;
            chunkY     = 0;
            nonAir     = true;
            blockData  = new byte[totalSections * BlockDataLength];
            metadata   = new byte[totalSections * NibbleDataLength];
            blockLight = new byte[totalSections * NibbleDataLength];
            skyLight   = new byte[totalSections * NibbleDataLength];

            ushort PrimaryBitMap = 0, AddBitMap = 0;

            // Second pass produces the arrays
            for (int i = 15; i >= 0; i--)
            {
                Section s = chunk.Sections[chunkY++];

                if (s.IsAir)
                {
                    nonAir = false;
                }
                if (nonAir)
                {
                    Array.Copy(s.Blocks, 0, blockData, (chunkY - 1) * BlockDataLength, BlockDataLength);
                    Array.Copy(s.Metadata.Data, 0, metadata, (chunkY - 1) * NibbleDataLength, NibbleDataLength);
                    Array.Copy(s.BlockLight.Data, 0, blockLight, (chunkY - 1) * NibbleDataLength, NibbleDataLength);
                    Array.Copy(s.SkyLight.Data, 0, skyLight, (chunkY - 1) * NibbleDataLength, NibbleDataLength);

                    PrimaryBitMap |= mask;
                }

                mask <<= 1;
            }

            // Create the final array
            // TODO: Merge this into the other loop, reduce objects
            byte[] data = new byte[blockData.Length + metadata.Length +
                                   blockLight.Length + skyLight.Length + chunk.Biomes.Length];
            int index = 0;

            Array.Copy(blockData, 0, data, index, blockData.Length);
            index += blockData.Length;
            Array.Copy(metadata, 0, data, index, metadata.Length);
            index += metadata.Length;
            Array.Copy(blockLight, 0, data, index, blockLight.Length);
            index += blockLight.Length;
            Array.Copy(skyLight, 0, data, index, skyLight.Length);
            index += skyLight.Length;
            Array.Copy(chunk.Biomes, 0, data, index, chunk.Biomes.Length);

            // Compress the array
            var result             = ZlibStream.CompressBuffer(data);
            var GroundUpContiguous = true;

            return(new ChunkDataPacket(X, Z, GroundUpContiguous, PrimaryBitMap, AddBitMap, result));
        }
Exemplo n.º 16
0
 public static byte[] CompressStream(byte[] unCompressedBytes)
 {
     return(ZlibStream.CompressBuffer(unCompressedBytes));
 }
Exemplo n.º 17
0
        public string ToJson()
        {
            var obj = new json_dat();

            obj.width = Width; obj.height = Height;
            List <loc>   locs = new List <loc>();
            MemoryStream ms   = new MemoryStream();

            using (PacketWriter wtr = new PacketWriter(ms))
                for (int y = 0; y < obj.height; y++)
                {
                    for (int x = 0; x < obj.width; x++)
                    {
                        var loc = new loc();
                        loc.ground = Tiles[x][y] != -1 ? GetTileId((ushort)Tiles[x][y]) : null;
                        loc.objs   = new obj[Entities[x][y].Length];
                        for (int i = 0; i < loc.objs.Length; i++)
                        {
                            var en = Entities[x][y][i];
                            obj o  = new obj()
                            {
                                id = GetEntityId(en.ObjectType)
                            };
                            string s = "";
                            Dictionary <StatsType, object> vals = new Dictionary <StatsType, object>();
                            foreach (var z in en.Status.Data)
                            {
                                vals.Add(z.Id, z.IsStringData() ? (object)z.StringValue : (object)z.IntValue);
                            }
                            if (vals.ContainsKey(StatsType.Name))
                            {
                                s += ";name:" + vals[StatsType.Name];
                            }
                            if (vals.ContainsKey(StatsType.Size))
                            {
                                s += ";size:" + vals[StatsType.Size];
                            }
                            if (vals.ContainsKey(StatsType.ObjectConnection))
                            {
                                s += ";conn:0x" + ((int)vals[StatsType.ObjectConnection]).ToString("X8");
                            }
                            if (vals.ContainsKey(StatsType.MerchandiseType))
                            {
                                s += ";mtype:" + vals[StatsType.MerchandiseType];
                            }
                            if (vals.ContainsKey(StatsType.MerchandiseRemainingCount))
                            {
                                s += ";mcount:" + vals[StatsType.MerchandiseRemainingCount];
                            }
                            if (vals.ContainsKey(StatsType.MerchandiseRemainingMinutes))
                            {
                                s += ";mtime:" + vals[StatsType.MerchandiseRemainingMinutes];
                            }
                            if (vals.ContainsKey(StatsType.RankRequired))
                            {
                                s += ";nstar:" + vals[StatsType.RankRequired];
                            }
                            o.name      = s.Trim(';');
                            loc.objs[i] = o;
                        }

                        int ix = -1;
                        for (int i = 0; i < locs.Count; i++)
                        {
                            if (locs[i].ground != loc.ground)
                            {
                                continue;
                            }
                            if (!((locs[i].objs != null && loc.objs != null) ||
                                  (locs[i].objs == null && loc.objs == null)))
                            {
                                continue;
                            }
                            if (locs[i].objs != null)
                            {
                                if (locs[i].objs.Length != loc.objs.Length)
                                {
                                    continue;
                                }
                                bool b = false;
                                for (int j = 0; j < loc.objs.Length; j++)
                                {
                                    if (locs[i].objs[j].id != loc.objs[j].id ||
                                        locs[i].objs[j].name != loc.objs[j].name)
                                    {
                                        b = true;
                                        break;
                                    }
                                }
                                if (b)
                                {
                                    continue;
                                }
                            }
                            ix = i;
                            break;
                        }
                        if (ix == -1)
                        {
                            ix = locs.Count;
                            locs.Add(loc);
                        }
                        wtr.Write((short)ix);
                    }
                }
            obj.data = ZlibStream.CompressBuffer(ms.ToArray());
            obj.dict = locs.ToArray();
            var settings = new JsonSerializerSettings();

            settings.NullValueHandling = NullValueHandling.Ignore;
            return(JsonConvert.SerializeObject(obj, settings));
        }
Exemplo n.º 18
0
 public byte[] CompressZlibStream(byte[] bytes, CompressionLevel level = CompressionLevel.Default)
 {
     return(ZlibStream.CompressBuffer(bytes));
 }
Exemplo n.º 19
0
        public string ToJson()
        {
            var obj = new json_dat();

            obj.width = Width; obj.height = Height;
            var locs = new List <loc>();
            var ms   = new MemoryStream();

            using (var wtr = new NWriter(ms))
                for (var y = 0; y < obj.height; y++)
                {
                    for (var x = 0; x < obj.width; x++)
                    {
                        var loc = new loc();
                        loc.ground = XmlDatas.TypeToId[(short)Tiles[x][y]];
                        loc.objs   = new obj[Entities[x][y].Length];
                        for (var i = 0; i < loc.objs.Length; i++)
                        {
                            var en = Entities[x][y][i];
                            var o  = new obj()
                            {
                                id = XmlDatas.TypeToId[(short)en.ObjectType]
                            };
                            var s    = "";
                            var vals = new Dictionary <StatsType, object>();
                            foreach (var z in en.Stats.Stats)
                            {
                                vals.Add(z.Key, z.Value);
                            }
                            if (vals.ContainsKey(StatsType.Name))
                            {
                                s += ";name:" + vals[StatsType.Name];
                            }
                            if (vals.ContainsKey(StatsType.Size))
                            {
                                s += ";size:" + vals[StatsType.Size];
                            }
                            if (vals.ContainsKey(StatsType.ObjectConnection))
                            {
                                s += ";conn:0x" + ((int)vals[StatsType.ObjectConnection]).ToString("X8");
                            }
                            if (vals.ContainsKey(StatsType.MerchantMerchandiseType))
                            {
                                s += ";mtype:" + vals[StatsType.MerchantMerchandiseType];
                            }
                            if (vals.ContainsKey(StatsType.MerchantRemainingCount))
                            {
                                s += ";mcount:" + vals[StatsType.MerchantRemainingCount];
                            }
                            if (vals.ContainsKey(StatsType.MerchantRemainingMinute))
                            {
                                s += ";mtime:" + vals[StatsType.MerchantRemainingMinute];
                            }
                            if (vals.ContainsKey(StatsType.NameChangerStar))
                            {
                                s += ";nstar:" + vals[StatsType.NameChangerStar];
                            }
                            o.name      = s.Trim(';');
                            loc.objs[i] = o;
                        }

                        var ix = -1;
                        for (var i = 0; i < locs.Count; i++)
                        {
                            if (locs[i].ground != loc.ground)
                            {
                                continue;
                            }
                            if (!((locs[i].objs != null && loc.objs != null) ||
                                  (locs[i].objs == null && loc.objs == null)))
                            {
                                continue;
                            }
                            if (locs[i].objs != null)
                            {
                                if (locs[i].objs.Length != loc.objs.Length)
                                {
                                    continue;
                                }
                                var b = false;
                                for (var j = 0; j < loc.objs.Length; j++)
                                {
                                    if (locs[i].objs[j].id != loc.objs[j].id ||
                                        locs[i].objs[j].name != loc.objs[j].name)
                                    {
                                        b = true;
                                        break;
                                    }
                                }
                                if (b)
                                {
                                    continue;
                                }
                            }
                            ix = i;
                            break;
                        }
                        if (ix == -1)
                        {
                            ix = locs.Count;
                            locs.Add(loc);
                        }
                        wtr.Write((short)ix);
                    }
                }
            obj.data = ZlibStream.CompressBuffer(ms.ToArray());
            obj.dict = locs.ToArray();
            return(JsonConvert.SerializeObject(obj));
        }
Exemplo n.º 20
0
        public static string ConvertReverse(XmlData data, byte[] wmap)
        {
            var obj = new json_dat();
            List <TerrainTile> terdict = new List <TerrainTile>();
            List <loc>         dict    = new List <loc>();

            List <byte> wmb = new List <byte>();

            foreach (var i in wmap)
            {
                wmb.Add(i);
            }
            wmb.RemoveAt(0);
            wmap = ZlibStream.UncompressBuffer(wmb.ToArray());

            List <byte>  dat    = new List <byte>();
            List <short> newDat = new List <short>();

            using (var rdr = new BinaryReader(new MemoryStream(wmap)))
            {
                short dicLength = rdr.ReadInt16();
                for (short i = 0; i < dicLength; i++)
                {
                    terdict.Add(new TerrainTile()
                    {
                        TileId  = rdr.ReadUInt16(),
                        TileObj = rdr.ReadString(),
                        Name    = rdr.ReadString(),
                        Terrain = (TerrainType)rdr.ReadByte(),
                        Region  = (TileRegion)rdr.ReadByte()
                    });
                }
                obj.width  = rdr.ReadInt32();
                obj.height = rdr.ReadInt32();
                dat        = new List <byte>(rdr.ReadBytes(obj.width * obj.height * 3));
            }
            using (var rdr = new BinaryReader(new MemoryStream(dat.ToArray())))
            {
                for (int i = 0; i < obj.width * obj.height; i++)
                {
                    newDat.Add(rdr.ReadInt16());
                    rdr.ReadByte(); //Elevation, don't need
                }
            }
            foreach (var i in terdict)
            {
                dict.Add(new loc()
                {
                    ground = data.Tiles[i.TileId].ObjectId,
                    objs   = i.TileObj == null ? null : new obj[] { new obj()
                                                                    {
                                                                        id = i.TileObj, name = i.Name
                                                                    } },
                    regions = i.Region == TileRegion.None ? null : new obj[] { new obj()
                                                                               {
                                                                                   id = i.Region.ToString().Replace('_', ' '), name = ""
                                                                               } }
                });
            }

            MemoryStream s = new MemoryStream();

            using (var wtr = new NWriter(s))
            {
                foreach (var i in newDat)
                {
                    wtr.Write(i);
                }
            }

            obj.dict = dict.ToArray();

            obj.data = ZlibStream.CompressBuffer(s.ToArray());
            return(JsonConvert.SerializeObject(obj));
        }
Exemplo n.º 21
0
 public TWADFile(byte[] Content, string FileName)
 {
     this.Content    = Content;
     this.FileName   = FileName;
     this.Compressed = ZlibStream.CompressBuffer(this.Content);
 }
Exemplo n.º 22
0
        internal override void Encode()
        {
            int Count = 6;

            this.Data.AddBool(false);

            this.Data.AddVInt(0);
            this.Data.AddVInt(21);
            this.Data.AddVInt((int)TimeUtils.ToUnixTimestamp(DateTime.Now)); // Timestamp
            this.Data.AddVInt(11);
            this.Data.AddVInt(0);

            this.Data.AddHexa("F3660944F693DC890701"); // Battle Checksum?

            if (this.Battle.Player1 == this.Device.Player)
            {
                this.Data.AddRange(this.Battle.Player2.Battle.ToBytes);

                this.Data.AddVInt(34);
                this.Data.AddVInt(0);
                this.Data.AddVInt(4);

                this.Data.AddRange(this.Battle.Player1.Battle.ToBytes);

                this.Data.AddVInt(0);
                this.Data.AddVInt(0);
                this.Data.AddVInt(0);

                this.Data.AddVInt(14); // Arena Base
                this.Data.AddVInt(2);
                this.Data.AddVInt(0);
                this.Data.AddVInt(21); // Arena but not actually arena?

                this.Data.AddVInt(this.Battle.Player2.UserHighId);
                this.Data.AddVInt(this.Battle.Player2.UserLowId);

                this.Data.AddVInt(0);

                this.Data.AddVInt(this.Battle.Player1.UserHighId);
                this.Data.AddVInt(this.Battle.Player1.UserLowId);

                this.Data.AddVInt(0);
            }
            else
            {
                this.Data.AddRange(this.Battle.Player1.Battle.ToBytes);

                this.Data.AddVInt(34);
                this.Data.AddVInt(0);
                this.Data.AddVInt(4);

                this.Data.AddRange(this.Battle.Player2.Battle.ToBytes);

                this.Data.AddVInt(0);
                this.Data.AddVInt(0);
                this.Data.AddVInt(0);

                this.Data.AddVInt(14); // Arena Base
                this.Data.AddVInt(2);
                this.Data.AddVInt(0);
                this.Data.AddVInt(21); // Arena but not actually arena?

                this.Data.AddVInt(this.Battle.Player1.UserHighId);
                this.Data.AddVInt(this.Battle.Player1.UserLowId);

                this.Data.AddVInt(0);

                this.Data.AddVInt(this.Battle.Player2.UserHighId);
                this.Data.AddVInt(this.Battle.Player2.UserLowId);
                this.Data.AddVInt(0);
            }

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddBool(false); //Is Trainer battle

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddVInt(142);
            this.Data.AddVInt(62077);

            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(Count);
            this.Data.AddVInt(Count);

            this.Data.AddVInt(35);
            this.Data.AddVInt(1);

            this.Data.AddVInt(35);
            this.Data.AddVInt(1);

            this.Data.AddVInt(35);
            this.Data.AddVInt(1);

            this.Data.AddVInt(35);
            this.Data.AddVInt(1);

            this.Data.AddVInt(35);
            this.Data.AddVInt(0);

            this.Data.AddVInt(35);
            this.Data.AddVInt(0);

            this.Data.AddVInt(1);
            this.Data.AddVInt(0);
            this.Data.AddVInt(1);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(1);

            for (int Index = 0; Index < Count; Index++)
            {
                this.Data.AddVInt(5);
                this.Data.AddVInt(Index);
            }

            this.Data.AddVInt(12);    //Level Tower R
            this.Data.AddVInt(13);    //Prefixed
            this.Data.AddVInt(14500); //Tower R Z
            this.Data.AddVInt(25500); //Tower R Y
            this.Data.AddRange("0000C07C00".HexaToBytes());
            this.Data.AddRange("A40100000000020000000000000000".HexaToBytes());

            this.Data.AddVInt(12);   //Level Tower R Enemy
            this.Data.AddVInt(13);   //Prefixed
            this.Data.AddVInt(3500); //Tower R Enemy X
            this.Data.AddVInt(6500); //Tower R Enemy Y
            this.Data.AddRange("0000800400".HexaToBytes());
            this.Data.AddRange("A40100000000010000000000000000".HexaToBytes());

            this.Data.AddVInt(12);    //Level Tower L
            this.Data.AddVInt(13);    //Prefixed
            this.Data.AddVInt(3500);  //Tower L X
            this.Data.AddVInt(25500); //Tower L Y
            this.Data.AddRange("0000C07C00".HexaToBytes());
            this.Data.AddRange("A40100000000010000000000000000".HexaToBytes());

            this.Data.AddVInt(12);    //Level Tower L Enemy
            this.Data.AddVInt(13);    //Prefixed
            this.Data.AddVInt(14500); //Tower L Enemy X
            this.Data.AddVInt(6500);  //Tower L Enemy Y
            this.Data.AddRange("0000800400".HexaToBytes());
            this.Data.AddRange("A40100000000020000000000000000".HexaToBytes());

            this.Data.AddVInt(12);   //Enemy Crown Tower Level
            this.Data.AddVInt(13);   //Prefixed
            this.Data.AddVInt(9000); //Crown Tower Enemy X
            this.Data.AddVInt(3000); //Tower Tower Enemy Y
            this.Data.AddRange("0000800400".HexaToBytes());
            this.Data.AddRange("A40100000000000000000000000000000504".HexaToBytes());
            this.Data.AddRange("05027D020401030200007F7F0000000500000000007F7F7F7F7F7F7F7F".HexaToBytes());

            this.Data.AddVInt(12);    //Crown Tower Level
            this.Data.AddVInt(13);    //Prefixed
            this.Data.AddVInt(9000);  //Crown Tower  X
            this.Data.AddVInt(29000); //Crown Tower Tower  Y
            this.Data.AddRange("0000C07C00".HexaToBytes());
            this.Data.AddRange("A40100000000000000000000000000000504".HexaToBytes());
            this.Data.AddRange("067B067E0403000204".HexaToBytes());
            this.Data.AddRange("007F7F000000".HexaToBytes());
            this.Data.AddVInt(5); //elixir bar start ?
            this.Data.AddRange("00000000007F7F7F7F7F7F7F7F".HexaToBytes());
            this.Data.AddRange("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".HexaToBytes());

            this.Data.AddVInt(3668); // Player R
            this.Data.AddVInt(3668); // Enemy R
            this.Data.AddVInt(3668); // Player L
            this.Data.AddVInt(3668); // Enemy L
            this.Data.AddVInt(5832); // Enemy Crown
            this.Data.AddVInt(5832); // Player Crown

            for (int Index = 0; Index < Count; Index++)
            {
                this.Data.AddRange("00000000000000A401A401".HexaToBytes());
            }

            this.Data.AddHexa("FE03");

            if (this.Battle.Player1 == this.Device.Player)
            {
                this.Data.AddRange(this.Battle.Player1.Decks.Hand());
            }
            else
            {
                this.Data.AddRange(this.Battle.Player2.Decks.Hand());
            }
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);

            this.Data.AddRange("05060202040201".HexaToBytes());
            this.Data.AddVInt(TimeSpan.FromSeconds(Battle.Time.GetRemainingSeconds(DateTime.Now)).Minutes);
            this.Data.AddVInt(TimeSpan.FromSeconds(Battle.Time.GetRemainingSeconds(DateTime.Now)).Seconds);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(0);
            this.Data.AddVInt(6);
            this.Data.AddVInt(9);
            this.Data.AddVInt(1);
            this.Data.AddVInt(1);
            this.Data.AddHexa("0000000000000000000000010000000000000000000000000C000000");
            this.Data.AddHexa("80A1B0A80F");
            this.Data.AddHexa("002A");
            this.Data.AddHexa("002B");

            ZlibStream.CompressBuffer(this.Data.ToArray());
        }
Exemplo n.º 23
0
 private static byte[] zlibCompress(byte[] bytes)
 {
     return(ZlibStream.CompressBuffer(bytes));
 }
Exemplo n.º 24
0
 public static string Encode(string text)
 {
     return(Convert.ToBase64String(ZlibStream.CompressBuffer(Encoding.UTF8.GetBytes(text))));
 }
Exemplo n.º 25
0
        internal static byte[] Array()
        {
            var part1          = Sodium.Utilities.HexToBinary("01 71 05 00 00".Replace(" ", ""));
            var decryptedpart2 = new List <byte>();

            decryptedpart2.AddHexa(
                "2A 02 7F 7F 7F 7F 00 00 00 00 00 00 01 80 32 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 0A 00 00 00 00 00 00 00 00 00 00 00 01 02 00 9F BD 19 00 9F BD 19 00 9F BD 19"
                .Replace(" ", ""));
            decryptedpart2.AddString(Constants.OwnHomeData.StartingPlayerName);
            decryptedpart2.AddHexa(
                "08 B5 31 86 06 95 2A 00 00 00 00 00 24 00 00 00 00 00 08 0E 05 01 BF AC 01 05 02 9D 0E 05 03 01 05 04 00 05 0C 8C 14 05 0D 00 05 0E 01 05 0F 98 11 05 16 B2 11 05 19 B4 D3 9F CA 0A 05 1A 0D 05 1C 00 05 1D 86 88 D5 44 05 25 00 00 00 00 05 05 06 95 35 05 07 80 0E 05 0B 24 05 14 0B 05 1B 0A 8D 01 1A 00 00 1A 01 00 1A 02 01 1A 03 00 1A 04 00 1A 05 01 1A 06 00 1A 07 00 1A 08 00 1A 09 00 1A 0A 00 1A 0B 00 1A 0C 00 1A 0D 00 1A 0E 00 1A 0F 00 1A 10 00 1A 11 00 1A 12 00 1A 13 00 1A 14 00 1A 15 00 1A 16 00 1A 17 00 1A 18 00 1A 19 00 1A 1A 00 1A 1B 00 1A 1C 00 1A 1D 00 1A 1E 00 1A 1F 00 1A 20 00 1A 21 00 1A 22 00 1A 23 00 1A 24 00 1A 25 37 1A 26 00 1A 27 00 1A 28 00 1A 29 00 1A 2A 00 1A 2B 00 1A 2D 00 1A 2E 01 1A 30 15 1A 31 00 1A 36 00 1A 37 10 1B 00 00 1B 01 00 1B 02 00 1B 03 00 1B 04 00 1B 05 00 1B 06 00 1B 07 00 1B 08 00 1B 09 00 1B 0A 00 1C 00 01 1C 01 00 1C 02 00 1C 03 00 1C 04 00 1C 05 00 1C 06 00 1C 07 00 1C 08 01 1C 09 00 1C 0A 00 1C 0B 00 1C 0C 00 1C 0D 00 1C 10 00 1A 39 00 00 00 0B 02 11 A1 B7 2E"
                .Replace(" ", ""));
            decryptedpart2.AddString(Constants.OwnHomeData.StartingClanName);
            decryptedpart2.AddHexa(
                "18 AD 48 92 08 00 B3 20 AD 1F 01 9F 03 17 00 00 00 00 2B 00 21 7F 0B 00 8D DE 59 6C 87 BB BE B7 03 02 02 26 01 7F 7F 00 00 9F BD 19 00 00 00 00 00 00 00 00 00 06"

                .Replace(" ", ""));
            decryptedpart2.Add(true);
            decryptedpart2.AddHexa("00 00 09 00 00 00 01 00 00 00 8E 02 F2 7D 00 00 06 7A 06 23 01 23 01 23 01 23 01 23 00 23 00 01 00 01 00 00 01 05 00 05 01 05 02 05 03 05 04 05 05 0A 0D A4 E2 01 9C 8E 03 00 00 7F 00 C0 7C 00 00 02 00 00 00 00 00 09 0D AC 36 A4 65 00 00 7F 00 80 04 00 00 01 00 00 00 00 00 0A 0D AC 36 9C 8E 03 00 00 7F 00 C0 7C 00 00 01 00 00 00 00 00 09 0D A4 E2 01 A4 65 00 00 7F 00 80 04 00 00 02 00 00 00 00 00 09 0D A8 8C 01 B8 2E 00 00 7F 00 80 04 00 00 00 00 00 00 00 00 0D 04 04 02 01 79 04 05 01 03 02 00 7F 7F 00 00 00 00 05 00 00 00 00 00 7F 7F 7F 7F 7F 7F 7F 7F 00 00 00 00".Replace(" ", ""));
            decryptedpart2.Add(12); //Crown tower level
            decryptedpart2.AddHexa(
                "0D A8 8C 01 88 C5 03 00 00 7F 00 C0 7C 00 00 00 00 00 00 00 00 0D 04 04 7F 7D 07 04 05 01 06 02 00 7F 7F 00 03 04"
                .Replace(" ", ""));
            decryptedpart2.AddString("Cast_Quest_HighCost");
            decryptedpart2.AddString("TID_CAST_QUEST_MIN_ELIXIR");
            decryptedpart2.AddString("TID_CAST_QUEST_MIN_ELIXIR_INFO");
            decryptedpart2.AddString("sc/ui.sc");
            decryptedpart2.AddString("quest_item_pvp");
            decryptedpart2.AddHexa(
                "14 1E 00 00 00 00 00 00 00 00 01 0E 00 2E 00 00 00 06 00 01 01 00 02".Replace(" ", ""));
            decryptedpart2.AddString("Play_Quest_Win_2v2Ladder_PvP");
            decryptedpart2.AddString("TID_LADDER_QUEST_2V2_WIN");
            decryptedpart2.AddString("TID_LADDER_QUEST_WIN_2V2_INFO");
            decryptedpart2.AddString("sc/ui.sc");
            decryptedpart2.AddString("quest_item_pvp");
            decryptedpart2.AddHexa(
                "14 05 02 00 00 00 00 00 00 00 01 05 00 0A 01 00 01 02 00 02 00 00 00 00".Replace(" ", ""));
            decryptedpart2.AddString("");
            decryptedpart2.AddString("");
            decryptedpart2.AddString("sc/ui.sc");
            decryptedpart2.AddString("quest_item_special_pvp");
            decryptedpart2.AddHexa("14 28 B4 12 0A 0A 01".Replace(" ", ""));
            decryptedpart2.AddString("icon_quest_type_specialevent"); //ELIXIR ..
            decryptedpart2.AddHexa("01 0E 02 04 02 00 00 00 02 B1 12 B3 12 00 00".Replace(" ", ""));
            decryptedpart2.Add(8);                                    //elixir NOT MORE THAT 63
            decryptedpart2.AddHexa(
                "00 00 00 00 00 7F 7F 7F 7F 7F 7F 7F 7F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 AC 2F 00 A2 2B 00 AC 2F 00 A2 2B 00 A8 44 00 98 4B 00 00 00 00 00 00 00 00 A4 01 A4 01 00 00 00 00 00 00 00 00 A4 01 A4 01 00 00 00 00 00 00 00 00 A4 01 A4 01 00 00 00 00 00 00 00 00 A4 01 A4 01 00 00 00 00 00 00 00 00 A4 01 A4 01 00 00 00 00 00 00 00 00 A4 01 A4 01 00 FF 01 11 04 01 09 05 04 03 09 1B 01 13 07 8F 01 09 1C 04 00 FE 03"

                .Replace(" ", ""));
            // decryptedpart2.AddHexa("2F 00 38 04 03 09 16 07 02 0A 0C 07 96 01 09 8E 01 06 00 00 05 06 02 02 04 02 01".Replace(" ",""));

            foreach (var cardid in Constants.OwnHomeData.Deck)
            {
                decryptedpart2.AddVInt(cardid);
                decryptedpart2.AddVInt(4);
            }
            decryptedpart2.AddHexa("00 00 05 06 02 02 04 02 01".Replace(" ", ""));

            decryptedpart2.Add(3); //2 for weird things (on troops), 3 for normal
            decryptedpart2.AddHexa("00 00 00 00 00 00 00 00 0C 00 00 00 90 EE FC F9 0F 00".Replace(" ", ""));
            return(part1.Concat(ZlibStream.CompressBuffer(decryptedpart2.ToArray())).ToArray());
        }
Exemplo n.º 26
0
        /// <summary>
        /// Writes the given record to the PQDIF file.
        /// </summary>
        /// <param name="record">The record to be written to the file.</param>
        /// <param name="lastRecord">Indicates whether this record is the last record in the file.</param>
        /// <exception cref="InvalidDataException">The PQDIF data is invalid.</exception>
        /// <exception cref="ObjectDisposedException">The writer was disposed.</exception>
        public void WriteRecord(Record record, bool lastRecord = false)
        {
            byte[] bodyImage;
            uint   checksum;

            if (m_disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            using (MemoryStream bodyStream = new MemoryStream())
                using (BinaryWriter bodyWriter = new BinaryWriter(bodyStream))
                {
                    // Write the record body to the memory stream
                    if (record.Body != null)
                    {
                        WriteCollection(bodyWriter, record.Body.Collection);
                    }

                    // Read and compress the body to a byte array
                    bodyImage = bodyStream.ToArray();

                    if (m_compressionAlgorithm == CompressionAlgorithm.Zlib && m_compressionStyle == CompressionStyle.RecordLevel)
                    {
                        bodyImage = ZlibStream.CompressBuffer(bodyImage);
                    }

                    // Create the checksum after compression
                    uint adler = Adler.Adler32(0u, null, 0, 0);
                    checksum = Adler.Adler32(adler, bodyImage, 0, bodyImage.Length);

                    // Write the record body to the memory stream
                    if (record.Body != null)
                    {
                        record.Body.Checksum = checksum;
                    }
                }

            // Fix the pointer to the next
            // record before writing this record
            if (m_stream.CanSeek && m_stream.Length > 0)
            {
                m_writer.Write((int)m_stream.Length);
                m_stream.Seek(0L, SeekOrigin.End);
            }

            // Make sure the header points to the correct location based on the size of the body
            record.Header.HeaderSize         = 64;
            record.Header.BodySize           = bodyImage.Length;
            record.Header.NextRecordPosition = (int)m_stream.Length + record.Header.HeaderSize + record.Header.BodySize;
            record.Header.Checksum           = checksum;

            // Write up to the next record position
            m_writer.Write(record.Header.RecordSignature.ToByteArray());
            m_writer.Write(record.Header.RecordTypeTag.ToByteArray());
            m_writer.Write(record.Header.HeaderSize);
            m_writer.Write(record.Header.BodySize);

            // The PQDIF standard defines the NextRecordPosition to be 0 for the last record in the file
            // We treat seekable streams differently because we can go back and fix the pointers later
            if (m_stream.CanSeek || lastRecord)
            {
                m_writer.Write(0);
            }
            else
            {
                m_writer.Write(record.Header.NextRecordPosition);
            }

            // Write the rest of the header as well as the body
            m_writer.Write(record.Header.Checksum);
            m_writer.Write(record.Header.Reserved);
            m_writer.Write(bodyImage);

            // If the stream is seekable, seek to the next record
            // position so we can fix the pointer if we end up
            // writing another record to the file
            if (m_stream.CanSeek)
            {
                m_stream.Seek(-(24 + record.Header.BodySize), SeekOrigin.Current);
            }

            // Dispose of the writer if this is the last record
            if (!m_stream.CanSeek && lastRecord)
            {
                Dispose();
            }
        }
Exemplo n.º 27
0
 public static byte[] Deflate(byte[] buffer)
 {
     return(ZlibStream.CompressBuffer(buffer));
 }
Exemplo n.º 28
0
        public static void WriteGEX(ProjectWriter writer, string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (ProjectReader pr = new ProjectReader(fs))
                {
                    GEX gex = new GEX();
                    gex.Load(pr);

                    writer.Write(gex.Package.Version);
                    writer.Write(gex.Package.Name);
                    writer.Write(gex.Package.Folder);
                    writer.Write(gex.Package.Files.Count);
                    foreach (var file in gex.Package.Files)
                    {
                        writer.Write(file.Version);
                        writer.Write(file.FileName);
                        writer.Write((int)file.Kind);
                        writer.Write(file.Initialization);
                        writer.Write(file.Finalization);
                        writer.Write(file.Functions.Count);
                        int id = 0;
                        foreach (var func in file.Functions)
                        {
                            writer.Write(func.Version);
                            writer.Write(func.Name);
                            writer.Write(func.ExternalName);
                            writer.Write((int)func.Convention);
                            writer.Write(id); // ?????
                            writer.Write(func.Argc);
                            for (int i = 0; i < 17; i++)
                            {
                                writer.Write((int)func.ArgTypes[i]);
                            }
                            writer.Write((int)func.Return);
                            id++;
                        }
                    }
                    writer.Write(gex.Seed);

                    // Prepare DAT files...
                    MemoryStream ms = new MemoryStream();
                    for (int i = 0; i < gex.Package.Files.Count; i++)
                    {
                        if (gex.Package.Files[i].Kind == GEDFile.GEDFileKind.ActionLib)
                        {
                            continue;
                        }

                        byte[] zlibbed = ZlibStream.CompressBuffer(gex.RawDATs[i]);
                        byte[] size    = BitConverter.GetBytes(zlibbed.Length);
                        ms.Write(size);
                        ms.Write(zlibbed);
                    }
                    byte[] includes = ms.ToArray();
                    writer.Write(includes.Length);

                    // GMKrypt the data.
                    for (int i = 1; i < includes.Length; i++)
                    {
                        includes[i] = gex.GMKrypt[0][includes[i]];
                    }
                    writer.Write(includes);
                }
        }
Exemplo n.º 29
0
 public static byte[] Compress(byte[] data)
 {
     return(ZlibStream.CompressBuffer(data));
 }
Exemplo n.º 30
0
        ///<summary>Generates a full .mca file stream for use in Minecraft.</summary>
        public static void WriteRegionToStream(Region region, FileStream stream, Version version, bool writeProgressBar = false)
        {
            DateTime time = System.DateTime.Now;

            int[]  locations = new int[1024];
            byte[] sizes     = new byte[1024];
            for (int i = 0; i < 8192; i++)
            {
                stream.WriteByte(0);
            }
            for (int z = 0; z < 32; z++)
            {
                for (int x = 0; x < 32; x++)
                {
                    int i     = z * 32 + x;
                    var chunk = region.chunks[x, z];
                    if (chunk != null)
                    {
                        locations[i] = (int)(stream.Position / 4096);
                        var         chunkData = ChunkSerializer.CreateCompoundForChunk(chunk, version);
                        List <byte> bytes     = new List <byte>();
                        chunkData.WriteToBytes(bytes, true);
                        byte[] compressed = ZlibStream.CompressBuffer(bytes.ToArray());
                        var    cLength    = Converter.ReverseEndianness(BitConverter.GetBytes(compressed.Length));
                        stream.Write(cLength, 0, cLength.Length);
                        stream.WriteByte(2);
                        stream.Write(compressed, 0, compressed.Length);
                        var padding = stream.Length % 4096;
                        //Pad the data to the next 4096 byte mark
                        if (padding > 0)
                        {
                            byte[] paddingBytes = new byte[4096 - padding];
                            stream.Write(paddingBytes, 0, paddingBytes.Length);
                        }
                        sizes[i] = (byte)((int)(stream.Position / 4096) - locations[i]);
                        if (sizes[i] == 0)
                        {
                            throw new InvalidOperationException("0 byte sized chunk detected.");
                        }
                    }
                    else
                    {
                        locations[i] = 0;
                        sizes[i]     = 0;
                    }
                }
                if (writeProgressBar)
                {
                    MCUtilsConsole.WriteProgress(string.Format("Writing chunks to stream [{0}/{1}]", z * 32, 1024), (z * 32f) / 1024f);
                }
            }
            stream.Position = 0;
            for (int i = 0; i < 1024; i++)
            {
                byte[] offsetBytes = Converter.ReverseEndianness(BitConverter.GetBytes(locations[i]));
                stream.WriteByte(offsetBytes[1]);
                stream.WriteByte(offsetBytes[2]);
                stream.WriteByte(offsetBytes[3]);
                stream.WriteByte(sizes[i]);
            }
            DateTime time2 = System.DateTime.Now;
            TimeSpan len   = time2.Subtract(time);

            MCUtilsConsole.WriteLine("Generating MCA took " + Math.Round(len.TotalSeconds * 100f) / 100f + "s");
        }