Пример #1
0
        public string Read(Stream stream)
        {
            int count = stream.Read(_compressedBlock, 0, BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength);

            if (count == 0)
            {
                return(string.Empty);
            }

            if (!BlockGZipStream.HasValidHeader(count, _compressedBlock))
            {
                throw new InvalidDataException("Found an invalid header when reading the GZip block");
            }

            int blockLength = BitConverter.ToUInt16(_compressedBlock, 16) + 1;
            int remaining   = blockLength - BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength;

            count = stream.Read(_compressedBlock, BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength, remaining);

            if (count != remaining)
            {
                throw new InvalidDataException("Found unexpected truncation when reading the GZip block");
            }

            count = _bgzf.Decompress(_compressedBlock, blockLength, _uncompressedBlock, MaxBlockSize);

            if (count < 0)
            {
                throw new CompressionException("Encountered an error when uncompressing the GZip block");
            }
            return(Encoding.UTF8.GetString(_uncompressedBlock, 0, count));
        }
    public override void Action(BinaryWriter writer)
    {
        var uncompressedData = Zlib.Decompress(compressedData);

        if (GetCalculatedUncompressedDataSize() != uncompressedData.Length)
        {
            Debug.LogError("Uncompressed size != calculated size!");
        }

        for (int i = 0; i < 16; ++i)
        {
            var chunk = ChunkManager.Get().GetChunk(new Vector3(x, i * 16, z));
            if ((primaryBitMap & (1 << i)) != 0)
            {
                for (int ix = 0; ix < 16; ++ix)
                {
                    for (int iy = 0; iy < 16; ++iy)
                    {
                        for (int iz = 0; iz < 16; ++iz)
                        {
                            chunk.SetBlock(ix, iy, iz, uncompressedData[GetUncompressedDataIndex(i, ix, iy, iz)]);
                        }
                    }
                }
            }
            chunk.Loaded = true;
        }
        ChunkManager.LoadedChunks++;
    }
Пример #3
0
        public static string SendRequest(string url, string body)
        {
            // send request
            Log.Info(Constants.backendUrl + url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Constants.backendUrl + url);

            byte[] data = Zlib.Compress(Encoding.UTF8.GetBytes(body));

            request.Method                 = "POST";
            request.ContentType            = "text/plain";
            request.AutomaticDecompression = DecompressionMethods.Deflate;
            request.ContentLength          = data.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            // get response
            Stream responseData = request.GetResponse().GetResponseStream();

            using (MemoryStream ms = new MemoryStream())
            {
                responseData.CopyTo(ms);
                return(Encoding.UTF8.GetString(Zlib.Decompress(ms.ToArray())));
            }
        }
        private static void ExtractHg3ImageJpegAlpha(BinaryReader reader, Hg3FrameInfo frameInfo, HgxOptions options,
                                                     string pngFile)
        {
            HG3STDINFO std = frameInfo.StdInfo;
            HG3IMG_AL  img = frameInfo.ImgAl.Data;
            HG3TAG     tag = frameInfo.ImgJpg.Tag;

            reader.BaseStream.Position = frameInfo.ImgAl.Offset;

            // WGC handles bad alpha buffer errors gracefully, so we should too
            byte[] alphaBuffer;
            try {
                alphaBuffer = Zlib.Decompress(reader, img.CompressedLength, img.DecompressedLength);
            } catch (ZlibException ex) {
                if (ex.Result == ZResult.DataError || ex.Result == ZResult.BufferError)
                {
                    alphaBuffer = ex.OutputBuffer;
                }
                else
                {
                    throw;
                }
            }

            reader.BaseStream.Position = frameInfo.ImgJpg.Offset;

            byte[] buffer = reader.ReadBytes(tag.Length);

            if (!CatDebug.SpeedTestHgx)
            {
                WriteJpegAlphaMaskToPng(buffer, alphaBuffer, std, options, pngFile);
            }
        }
Пример #5
0
        internal void SendRoomScribble(Predicate <IClient> pred, string name, RoomScribble scribble)
        {
            byte[] buffer;
            if (scribble.Size <= 4000)
            {
                Server.SendAnnounce(pred, string.Format("\x000314--- From {0}", name));
                Server.SendPacket(pred, new ClientCustom(string.Empty, "cb0t_scribble_once", scribble.RawImage()));
            }
            else
            {
                scribble.Index = 0;

                int length = Math.Min((int)scribble.Received, 4000);

                buffer = scribble.Read();

                Server.SendAnnounce(pred, string.Format("\x000314--- From {0}", name));
                Server.SendPacket(pred, new ClientCustom(string.Empty, "cb0t_scribble_first", buffer));

                while (scribble.Remaining > 0)
                {
                    buffer = scribble.Read();

                    if (scribble.Remaining > 0)
                    {
                        Server.SendPacket(pred, new ClientCustom(string.Empty, "cb0t_scribble_chunk", buffer));
                    }
                    else
                    {
                        Server.SendPacket(pred, new ClientCustom(string.Empty, "cb0t_scribble_last", buffer));
                    }
                }
            }

            var ib0ts = Server.Users.Where(s => s.Socket.Isib0tSocket && pred(s));

            if (ib0ts.Count() > 0)
            {
                buffer = Zlib.Decompress(scribble.RawImage());

                int    height = RoomScribble.GetHeight(buffer);
                string base64 = Convert.ToBase64String(buffer);

                string[] chunks = new string[(int)Math.Round((double)(base64.Length / 1024), MidpointRounding.AwayFromZero)];

                for (int i = 0; i < chunks.Length; i++)
                {
                    chunks[i] = base64.Substring(i * 1024, 1024);
                }

                ib0ts.ForEach(s => s.SendPacket(new ScribbleHead(name, height, chunks.Length)));

                foreach (string chunk in chunks)
                {
                    ib0ts.ForEach(s => s.SendPacket(new ScribbleBlock(chunk)));
                }
            }
        }
Пример #6
0
        public static byte[] Decompress(byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException();
            }

            using (MemoryStream buffStream = new MemoryStream(buffer))
            {
                uint magicStream = buffStream.ReadValueU32();
                if (magicStream != magic && magicStream.Swap() != magic)
                {
                    throw new InvalidDataException("found an invalid zlib block");
                }

                uint buffMaxSegmentSize = buffStream.ReadValueU32();
                if (buffMaxSegmentSize != maxSegmentSize)
                {
                    throw new FormatException();
                }

                uint totComprSize   = buffStream.ReadValueU32();
                uint totUncomprSize = buffStream.ReadValueU32();

                byte[] outputBuffer = new byte[totUncomprSize];
                int    numOfSegm    = (int)Math.Ceiling(totUncomprSize / (double)maxSegmentSize);
                int    headSegm     = 16;
                int    dataSegm     = headSegm + (numOfSegm * 8);
                int    buffOff      = 0;

                for (int i = 0; i < numOfSegm; i++)
                {
                    buffStream.Seek(headSegm, SeekOrigin.Begin);
                    int comprSegm   = buffStream.ReadValueS32();
                    int uncomprSegm = buffStream.ReadValueS32();
                    headSegm = (int)buffStream.Position;

                    buffStream.Seek(dataSegm, SeekOrigin.Begin);
                    //Console.WriteLine("compr size: {0}, uncompr size: {1}, data offset: 0x{2:X8}", comprSegm, uncomprSegm, dataSegm);
                    byte[] src = buffStream.ReadBytes(comprSegm);
                    byte[] dst = new byte[uncomprSegm];
                    if (Zlib.Decompress(src, (uint)src.Length, dst) != uncomprSegm)
                    {
                        throw new Exception("Zlib decompression failed!");
                    }

                    Buffer.BlockCopy(dst, 0, outputBuffer, buffOff, uncomprSegm);

                    buffOff  += uncomprSegm;
                    dataSegm += comprSegm;
                }
                buffStream.Close();
                return(outputBuffer);
            }
        }
Пример #7
0
        public override ITexture ConvertToBitmap(Sprite entity)
        {
            var data = entity.Data;
            var type = entity.Type;
            var size = entity.Width * entity.Height * (type == ColorBits.ARGB_8888 ? 4 : 2);

            if (entity.CompressMode == CompressMode.ZLIB)
            {
                data = Zlib.Decompress(data, size);
            }
            return(TextureUitls.Instance.FromArray(data, entity.Size, type));
        }
Пример #8
0
        public override Bitmap ConvertToBitmap(Sprite entity)
        {
            var data = entity.Data;
            var type = entity.Type;
            var size = entity.Width * entity.Height * (type == ColorBits.ARGB_8888 ? 4 : 2);

            if (entity.Compress == Compress.ZLIB)
            {
                data = Zlib.Decompress(data, size);
            }
            return(Bitmaps.FromArray(data, entity.Size, type));
        }
        private static void ExtractHg3ImageAlpha(BinaryReader reader, Hg3FrameInfo frameInfo, HgxOptions options,
                                                 string pngFile)
        {
            HG3STDINFO std = frameInfo.StdInfo;
            HG3IMG_AL  img = frameInfo.ImgAl.Data;

            reader.BaseStream.Position = frameInfo.ImgAl.Offset;

            // WGC handles bad alpha buffer errors gracefully, so we should too
            byte[] alphaBuffer;
            try {
                alphaBuffer = Zlib.Decompress(reader, img.CompressedLength, img.DecompressedLength);
            } catch (ZlibException ex) {
                if (ex.Result == ZResult.DataError || ex.Result == ZResult.BufferError)
                {
                    alphaBuffer = ex.OutputBuffer;
                }
                else
                {
                    throw;
                }
            }

            int depthBytes  = (std.DepthBits + 7) / 8;
            int stride      = (std.Width * depthBytes + 3) & ~3;
            int minStride   = (std.Width * depthBytes);
            int alphaStride = std.Width;

            byte[] pixelBuffer = new byte[stride * std.Height];
            for (int y = 0; y < std.Height; y++)
            {
                int src = y * alphaStride;
                int dst = y * stride;
                for (int x = 0; x < std.Width; x++)
                {
                    int  alphaIndex = src + x;
                    int  pixelIndex = dst + x * depthBytes;
                    byte alpha      = unchecked ((byte)(byte.MaxValue - alphaBuffer[alphaIndex]));
                    pixelBuffer[pixelIndex + 0] = alpha;
                    pixelBuffer[pixelIndex + 1] = alpha;
                    pixelBuffer[pixelIndex + 2] = alpha;
                    if (depthBytes == 4)
                    {
                        pixelBuffer[pixelIndex + 3] = byte.MaxValue;
                    }
                }
            }

            if (!CatDebug.SpeedTestHgx)
            {
                WritePng(pixelBuffer, std, options, pngFile);
            }
        }
Пример #10
0
        public void Read(byte[] data)
        {
            if (data.Length < 276)
            {
                data = Zlib.Decompress(data, 276);
            }
            BinaryReader br = new BinaryReader(new MemoryStream(data));

            Path   = br.ReadBytes(260).ToGBK().Replace("/", "\\");
            Offset = br.ReadUInt32();
            Size   = br.ReadInt32();
            CSize  = br.ReadInt32();
            br.Close();
        }
Пример #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string guid = Request.QueryString[string.Empty];

        if (guid == null || !Regex.IsMatch(guid, "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"))
        {
            Response.StatusCode = 301;
            Response.Status     = "301 Moved Permanently";
            Response.AddHeader("Location", SiteUri.ToString());
            Response.End();
        }

        Meta.SQL.IDatabase       db     = new Meta.SQL.Module().Database;
        Ps2Css.DB.Request.Module module = new Ps2Css.DB.Request.Module(db);
        Ps2Css.DB.Request.Item   item   = module.GetByID(new Guid(guid));
        if (item != null)
        {
            int diff = (int)Math.Ceiling((DateTime.Now - item.Created).TotalSeconds);
            if (diff < InitialDelay)
            {
                this.wait = InitialDelay - diff;
            }
            else
            {
                this.wait = 0;
                try
                {
                    Document doc = new Ps2Css.Xml.Document(Encoding.UTF8.GetString(Zlib.Decompress(item.Data)));
                    this.Styles = doc.Styles.ToArray();
                }
                catch (Ps2Css.Xml.CorruptedXmlException ex)
                {
                    exception = ex.GetType().ToString();
                    base.Log("XML parsing error");
                }
                catch (Exception ex)
                {
                    exception = "System.Exception";
                    base.Log(ex);
                }
            }
        }
        else
        {
            if (Request.UrlReferrer != null)
            {
                exception = "StyleNotFound";
            }
        }
    }
Пример #12
0
        private PacketBuffer ReadNextPacket(out int packetId)
        {
            var size   = ReadNextVarInt();
            var buffer = new PacketBuffer(Receive(size));

            if (CompressionThreshold > 0)
            {
                int sizeUncompressed = buffer.ReadVarInt();
                if (sizeUncompressed != 0)
                {
                    buffer = new PacketBuffer(Zlib.Decompress(buffer.ReadToEnd(), sizeUncompressed));
                }
            }
            packetId = buffer.ReadVarInt();
            return(buffer);
        }
Пример #13
0
        private void decodeNotifyData(byte[] encryptData)
        {
            uint encryptAlgo  = Util.ReadProtoInt(encryptData, 1);
            uint compressAlgo = Util.ReadProtoInt(encryptData, 4);

            byte[] cipherText = Util.ReadProtoRawData(encryptData, 8);
            if (encryptAlgo == 5)
            {
                int    Salt         = (int)Util.ReadProtoInt(encryptData, 3);
                byte[] sencryptSalt = TLVUtil.int2byte(Salt, 4, false);
                byte[] sessionKey   = SessionPackMgr.getAccount().SessionKey;
                byte[] decodeKey    = new byte[20];

                Buffer.BlockCopy(sessionKey, 0, decodeKey, 0, 16);
                Buffer.BlockCopy(sencryptSalt, 0, decodeKey, 16, sencryptSalt.Length);

                byte[] decodeAesKey = MD5Core.GetHash(decodeKey);
                // Log.w("Network", string.Concat(new object[] { "encode notify salt ", Util.byteToHexStr(sencryptSalt), "SessionKey ", Util.byteToHexStr(sessionKey), "decode Key ", Util.byteToHexStr(decodeAesKey) }));
                byte[] decryptedData = Util.AESDecrypt(cipherText, decodeAesKey);

                if (compressAlgo == 1)
                {
                    Zlib.Decompress(decryptedData, decryptedData.Length, ref decryptedData);
                }

                Log.w("Network", string.Concat(new object[] { "decode notify result ", Util.byteToHexStr(decryptedData) }));

                cipherText = Util.ReadProtoRawData(decryptedData, 1);
                cipherText = Util.ReadProtoRawData(cipherText, 1);
                string ChatRoomId = Encoding.UTF8.GetString(cipherText);
                //  uint newMsgid = Util.ReadProtoInt(decryptedData, 2);

                uint newMsgSeq = Util.ReadProtoInt(decryptedData, 3);
                cipherText = Util.ReadProtoRawData(decryptedData, 6);
                cipherText = Util.ReadProtoRawData(cipherText, 1);
                string Contact = Encoding.UTF8.GetString(cipherText);

                uint msgType = Util.ReadProtoInt(decryptedData, 8);


                Log.w("Network", string.Concat(new object[] { "decode notify data ", " ChatRoomId ", ChatRoomId, " newMsgSeq ", newMsgSeq, "MsgType ", msgType, " Contact ", Contact }));


                new NetSceneGetChatRoomMsg().doScene(ChatRoomId, newMsgSeq);
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            string[] files = new string[] { "image.jpg.compress", "pdf_book.pdf.compress", "image_decompress.jpg", "pdf_book_decompress.pdf",
                                            "image.jpg.compress_stream", "image_decompress_stream.jpg", "", "" };
            foreach (string file in files)
            {
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
            }
            byte[] file1 = File.ReadAllBytes("image.jpg");
            if (Zlib.IsCompressedByZlib(file1))
            {
                Console.WriteLine("file1 - compressed by zlib");
            }
            else
            {
                Console.WriteLine("file1 - not compressed by zlib");
            }
            var fs1 = new FileStream("image.jpg", FileMode.Open, FileAccess.Read);
            var fs2 = new FileStream("image.jpg.compress_stream", FileMode.Create, FileAccess.Write);

            Zlib.Compress(fs1, fs2, ZlibCompressionLevel.BEST_COMPRESSION);
            fs2.Close();
            Zlib.Decompress(new FileStream("image.jpg.compress_stream", FileMode.Open, FileAccess.Read),
                            new FileStream("image_decompress_stream.jpg", FileMode.Create, FileAccess.Write));
            byte[] file2       = File.ReadAllBytes("pdf_book.pdf");
            byte[] compressed1 = Zlib.Compress(file1, ZlibCompressionLevel.BEST_COMPRESSION);
            File.WriteAllBytes("image.jpg.compress", compressed1);
            if (Zlib.IsCompressedByZlib(compressed1))
            {
                Console.WriteLine("compressed1 - compressed by zlib");
            }
            else
            {
                Console.WriteLine("compressed1 - not compressed by zlib");
            }
            byte[] compressed2 = Zlib.Compress(file2, ZlibCompressionLevel.BEST_COMPRESSION);
            File.WriteAllBytes("pdf_book.pdf.compress", compressed2);
            byte[] decompressed1 = Zlib.Decompress(compressed1, file1.Length);
            File.WriteAllBytes("image_decompress.jpg", decompressed1);
            byte[] decompressed2 = Zlib.Decompress(compressed2, file2.Length);
            File.WriteAllBytes("pdf_book_decompress.pdf", decompressed2);
            Console.ReadKey();
        }
Пример #15
0
        public void SetBody(HttpListenerRequest request)
        {
            if (request == null || !request.HasEntityBody)
            {
                return;
            }

            byte[] buffer = null;

            using (MemoryStream ms = new MemoryStream())
            {
                request.InputStream.CopyTo(ms);
                buffer = ms.ToArray();
            }

            body = Encoding.UTF8.GetString(Zlib.Decompress(buffer));
        }
 public byte[] GetFile(IArchiveEntry entry, bool reload = true)
 {
     if (reload)
     {
         Stream.Reopen(true);
     }
     Stream.Seek(entry.Offset, SeekOrigin.Begin);
     byte[] file = Stream.ReadBytes(entry.CSize);
     if (entry.CSize < entry.Size)
     {
         return(Zlib.Decompress(file, entry.Size));
     }
     else
     {
         return(file);
     }
 }
Пример #17
0
        static void Main(string[] args)
        {
            var file = args.Length > 0 ? args[0] : @"C:\Users\alexandr\Downloads\test.zip";

            var      data = File.ReadAllBytes(file);
            Document doc  = null;

            switch (Path.GetExtension(file).ToLowerInvariant())
            {
            case ".ai":
                doc = new Ai.Document(data);
                break;

            case ".asl":
                doc = new Asl.Document(data);
                break;

            case ".png":
                doc = new Png.Document(data);
                break;

            case ".xml":
                doc = new Xml.Document(Encoding.UTF8.GetString(data));
                break;

            case ".zip":
                doc = new Xml.Document(Encoding.UTF8.GetString(Zlib.Decompress(data)));
                break;
            }
            if (doc != null)
            {
                var sb = new StringBuilder();
                foreach (var style in doc.Styles)
                {
                    if (style != null)
                    {
                        sb.Append(style.ToString());
                    }
                }
                if (sb.Length > 0)
                {
                    Clipboard.SetText(sb.ToString());
                }
            }
        }
Пример #18
0
        byte[] ReadPacked(PacketReader reader)
        {
            int packLength = reader.ReadInt32() - 4;

            if (packLength < 0)
            {
                return(new byte[0]);
            }

            int length = reader.ReadInt32();

            byte[] pack   = reader.ReadBytes(packLength);
            byte[] buffer = new byte[length];

            Zlib.Decompress(buffer, ref length, pack, packLength);

            return(buffer);
        }
Пример #19
0
        private PacketBuffer ReadNextPacket(ref int packetID)
        {
            int          size   = ReadNextVarIntRAW();
            var          b      = ReadDataRAW(size);
            PacketBuffer buffer = new PacketBuffer(b);

            if (manager.compressionThreshold > 0)
            {
                int sizeUncompressed = buffer.ReadVarInt();
                if (sizeUncompressed != 0) // != 0 means compressed, let's decompress
                {
                    buffer = new PacketBuffer(Zlib.Decompress(buffer.ReadToEnd(), sizeUncompressed));
                }
            }
            packetID = buffer.ReadVarInt();
            stream   = new MemoryStream();
            return(buffer);
        }
Пример #20
0
        public override Bitmap ConvertToBitmap(Sprite entity)
        {
            var data = entity.Data;
            var type = entity.Type;
            var size = entity.Width * entity.Height * (type == ColorBits.ARGB_8888 ? 4 : 2);

            if (entity.Compress == Compress.ZLIB)
            {
                data = Zlib.Decompress(data, size);
            }
            using (var ms = new MemoryStream(data)) {
                data = new byte[entity.Size.Width * entity.Size.Height * 4];
                for (var i = 0; i < data.Length; i += 4)
                {
                    var temp = Colors.ReadColor(ms, type);
                    temp.CopyTo(data, i);
                }
            }
            return(Bitmaps.FromArray(data, entity.Size));
        }
Пример #21
0
        /// <summary>
        ///  Extracts the screen script information.
        /// </summary>
        /// <param name="stream">The stream to extract the screen script from.</param>
        /// <param name="fileName">The path or name of the screen script file being extracted.</param>
        /// <returns>The extracted <see cref="FesScreen"/> information.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="stream"/> or <paramref name="fileName"/> is null.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        ///  The <paramref name="stream"/> is closed.
        /// </exception>
        public static FesScreen Extract(Stream stream, string fileName)
        {
            BinaryReader reader = new BinaryReader(stream);
            FESHDR       hdr    = reader.ReadUnmanaged <FESHDR>();

            UnexpectedFileTypeException.ThrowIfInvalid(hdr.Signature, FESHDR.ExpectedSignature);

            byte[] scriptData = Zlib.Decompress(reader, hdr.CompressedLength, hdr.DecompressedLength);

            /*byte[] compressed = reader.ReadBytes(hdr.CompressedLength);
             * byte[] decompressed = new byte[hdr.DecompressedLength];
             * int decompressedLength = hdr.DecompressedLength;
             * Zlib.Uncompress(decompressed, ref decompressedLength, compressed, hdr.CompressedLength);*/

            string[] lines;
            using (MemoryStream ms = new MemoryStream(scriptData))
                using (StreamReader sr = new StreamReader(ms, CatUtils.ShiftJIS))
                    lines = sr.ReadLinesToEnd();

            return(new FesScreen(fileName, lines));
        }
        /// <summary>
        ///  Extracts the scene script information.
        /// </summary>
        /// <param name="stream">The stream to extract the scene script from.</param>
        /// <param name="fileName">The path or name of the scene script file being extracted.</param>
        /// <returns>The extracted <see cref="CstScene"/> information.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="stream"/> or <paramref name="fileName"/> is null.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        ///  The <paramref name="stream"/> is closed.
        /// </exception>
        public static CstScene Extract(Stream stream, string fileName)
        {
            BinaryReader reader = new BinaryReader(stream);
            CATSCENEHDR  hdr    = reader.ReadUnmanaged <CATSCENEHDR>();

            UnexpectedFileTypeException.ThrowIfInvalid(hdr.Signature, CATSCENEHDR.ExpectedSignature);

            byte[] scriptData = Zlib.Decompress(reader, hdr.CompressedLength, hdr.DecompressedLength);

            /*byte[] compressed = reader.ReadBytes(hdr.CompressedLength);
             * byte[] decompressed = new byte[hdr.DecompressedLength];
             * int decompressedLength = hdr.DecompressedLength;
             * Zlib.Uncompress(decompressed, ref decompressedLength, compressed, hdr.CompressedLength);*/

            SCRIPTLINE[] lines;

            using (var ms = new MemoryStream(scriptData))
                lines = ReadScript(ms);

            return(new CstScene(fileName, lines));
        }
Пример #23
0
        public override Bitmap ConvertToBitmap(Sprite entity)
        {
            var data = entity.Data;
            var size = entity.Width * entity.Height;

            if (entity.Compress == Compress.ZLIB)
            {
                data = Zlib.Decompress(data, size);
                var table = Album.CurrentTable;
                if (table.Count > 0)
                {
                    using (var os = new MemoryStream()) {
                        for (var i = 0; i < data.Length; i++)
                        {
                            var j = data[i] % table.Count;
                            Colors.WriteColor(os, table[j], ColorBits.ARGB_8888);
                        }
                        data = os.ToArray();
                    }
                }
            }
            return(Bitmaps.FromArray(data, entity.Size));
        }
Пример #24
0
        public override ITexture ConvertToBitmap(Sprite entity)
        {
            var data = entity.Data;
            var size = entity.Width * entity.Height;

            if (entity.Type == ColorBits.ARGB_1555 && entity.CompressMode == CompressMode.ZLIB)
            {
                data = Zlib.Decompress(data, size);
                var table = Album.CurrentTable;
                if (table.Count > 0)
                {
                    using (var os = new MemoryStream()) {
                        foreach (var i in data)
                        {
                            os.WriteColor(table[i % table.Count], ColorBits.ARGB_8888);
                        }
                        data = os.ToArray();
                    }
                    return(TextureUitls.Instance.FromArray(data, entity.Size));
                }
            }
            return(base.ConvertToBitmap(entity));
        }
Пример #25
0
        public override Bitmap ConvertToBitmap(Sprite entity)
        {
            var data = entity.Data;
            var size = entity.Width * entity.Height;

            if (entity.Compress != Compress.ZLIB || entity.Type > ColorBits.ARGB_1555)
            {
                return(base.ConvertToBitmap(entity));
            }
            data = Zlib.Decompress(data, size);
            var table = Album.CurrentTable;

            if (table.Count > 0)
            {
                using (var os = new MemoryStream()) {
                    foreach (var i in data)
                    {
                        Colors.WriteColor(os, table[i % table.Count], ColorBits.ARGB_8888);
                    }
                    data = os.ToArray();
                }
            }
            return(Bitmaps.FromArray(data, entity.Size));
        }
Пример #26
0
        private static ZtPackage ExtractInternal(Stream stream, string fileName, string outputDir)
        {
            BinaryReader reader = new BinaryReader(stream);

            long       startPosition = stream.Position;
            ZTENTRYHDR entryHdr      = new ZTENTRYHDR();
            ZTENTRY    entry;

            List <ZTENTRYHDR> fileHdrs    = new List <ZTENTRYHDR>();
            List <ZTENTRY>    fileEntries = new List <ZTENTRY>();

            do
            {
                stream.Position = startPosition + entryHdr.OffsetNext;
                startPosition   = stream.Position;

                entryHdr = reader.ReadUnmanaged <ZTENTRYHDR>();
                entry    = reader.ReadUnmanaged <ZTENTRY>();

                fileHdrs.Add(entryHdr);
                fileEntries.Add(entry);

                if (outputDir != null)
                {
                    byte[] fileData = Zlib.Decompress(reader, entry.CompressedLength, entry.DecompressedLength);

                    /*byte[] compressed = reader.ReadBytes(entry.CompressedLength);
                     * byte[] decompressed = new byte[entry.DecompressedLength];
                     *
                     * Zlib.Uncompress(decompressed, ref entry.DecompressedLength, compressed, entry.CompressedLength);*/
                    File.WriteAllBytes(Path.Combine(outputDir, entry.FileName), fileData);
                }
            } while (entryHdr.OffsetNext != 0);

            return(new ZtPackage(fileName, fileHdrs.ToArray(), fileEntries.ToArray()));
        }
Пример #27
0
 public int GetHeight()
 {
     return(GetHeight(Zlib.Decompress(RawImage())));
 }
Пример #28
0
        public ServerUpdate(BinaryReader reader)
        {
            byte[] uncompressed = Zlib.Decompress(reader.ReadBytes(reader.ReadInt32()));

            MemoryStream stream = new MemoryStream(uncompressed);
            BinaryReader r      = new BinaryReader(stream);

            var count = r.ReadInt32();

            for (int i = 0; i < count; i++)
            {
                blockDeltas.Add(new BlockDelta(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                hits.Add(new Hit(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                particles.Add(new Particle(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                sounds.Add(new Sound(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                shoots.Add(new Shoot(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                statics.Add(new StaticEntity(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                chunkItems.Add(new ChunkItems(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                p48s.Add(new P48(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                pickups.Add(new Pickup(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                kills.Add(new Kill(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                damages.Add(new Damage(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                passiveProcs.Add(new PassiveProc(r));
            }

            count = r.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                missions.Add(new Mission(r));
            }
        }
Пример #29
0
 public MemoryStream UncompressToLength(long destLength)
 {
     return(Zlib.Decompress(this, destLength));
 }
Пример #30
0
        /// <summary>
        /// Packets handled in this function are 'internal' and cannot be overriden.
        /// </summary>
        internal bool HandlePacket(PacketEventArgs e)
        {
            if (IsCaptcha)
            {
                switch ((AresId)e.Packet.Id)
                {
                case AresId.MSG_CHAT_CLIENT_FASTPING:
                    FastPing = true;
                    return(true);

                case AresId.MSG_CHAT_CLIENT_DUMMY:
                    return(true);

                case AresId.MSG_CHAT_CLIENT_AUTOLOGIN:
                    AutoLogin login = (AutoLogin)e.Packet;
                    AresCommands.HandleAutoLogin(server, this, login.Sha1Password);
                    return(true);

                case AresId.MSG_CHAT_CLIENT_PUBLIC:
                    ClientPublic pub = (ClientPublic)e.Packet;
                    FinishCaptcha(pub.Message);
                    return(true);

                case AresId.MSG_CHAT_CLIENT_EMOTE:
                    ClientEmote emote = (ClientEmote)e.Packet;
                    FinishCaptcha(emote.Message);
                    return(true);

                case AresId.MSG_CHAT_CLIENT_ADDSHARE:
                    return(true);

                case AresId.MSG_CHAT_CLIENT_UPDATE_STATUS:
                    ClientUpdate update = (ClientUpdate)e.Packet;

                    LastUpdate = DateTime.Now;
                    NodeIp     = update.NodeIp;
                    NodePort   = update.NodePort;
                    return(true);

                default:
                    break;
                }
                return(false);
            }
            else if (LoggedIn)
            {
                switch ((AresId)e.Packet.Id)
                {
                case AresId.MSG_CHAT_CLIENT_FASTPING:
                    FastPing = true;
                    return(true);

                case AresId.MSG_CHAT_CLIENT_DUMMY:
                    return(true);

                case AresId.MSG_CHAT_CLIENT_PUBLIC:
                    ClientPublic pub = (ClientPublic)e.Packet;

                    if (AresCommands.HandlePreCommand(server, this, pub.Message))
                    {
                        return(true);
                    }

                    if (Muzzled)
                    {
                        server.SendAnnounce(this, Strings.AreMuzzled);
                        return(true);
                    }
                    break;

                case AresId.MSG_CHAT_CLIENT_EMOTE:
                    ClientEmote emote = (ClientEmote)e.Packet;

                    if (AresCommands.HandlePreCommand(server, this, emote.Message))
                    {
                        return(true);
                    }

                    if (Muzzled)
                    {
                        server.SendAnnounce(this, Strings.AreMuzzled);
                        return(true);
                    }
                    break;

                case AresId.MSG_CHAT_CLIENT_COMMAND:
                    Command cmd = (Command)e.Packet;
                    if (AresCommands.HandleCommand(server, this, cmd.Message))
                    {
                        return(true);
                    }
                    break;

                case AresId.MSG_CHAT_CLIENT_PVT:
                    Private pvt = (Private)e.Packet;

                    if (Muzzled && !server.Config.MuzzledPMs)
                    {
                        pvt.Message = "[" + Strings.AreMuzzled + "]";
                        SendPacket(pvt);

                        return(true);
                    }

                    break;

                case AresId.MSG_CHAT_CLIENT_AUTHREGISTER: {
                    AuthRegister reg = (AuthRegister)e.Packet;
                    AresCommands.HandleRegister(server, this, reg.Password);
                    return(true);
                }

                case AresId.MSG_CHAT_CLIENT_AUTHLOGIN: {
                    AuthLogin login = (AuthLogin)e.Packet;
                    AresCommands.HandleLogin(server, this, login.Password);
                    return(true);
                }

                case AresId.MSG_CHAT_CLIENT_AUTOLOGIN: {
                    AutoLogin login = (AutoLogin)e.Packet;
                    AresCommands.HandleAutoLogin(server, this, login.Sha1Password);
                    return(true);
                }

                case AresId.MSG_CHAT_CLIENT_ADDSHARE:
                    return(true);

                case AresId.MSG_CHAT_CLIENT_IGNORELIST:
                    Ignored ignore = (Ignored)e.Packet;
                    if (ignore.Ignore)
                    {
                        lock (Ignored) {
                            if (!Ignored.Contains(ignore.Username))
                            {
                                Ignored.Add(ignore.Username);
                                server.SendAnnounce(this, String.Format(Strings.Ignored, ignore.Username));
                            }
                        }
                    }
                    else
                    {
                        lock (Ignored) {
                            if (Ignored.Contains(ignore.Username))
                            {
                                Ignored.Remove(ignore.Username);
                                server.SendAnnounce(this, String.Format(Strings.Unignored, ignore.Username));
                            }
                        }
                    }
                    return(true);

                case AresId.MSG_CHAT_CLIENT_UPDATE_STATUS:
                    ClientUpdate update = (ClientUpdate)e.Packet;

                    LastUpdate = DateTime.Now;
                    NodeIp     = update.NodeIp;
                    NodePort   = update.NodePort;
                    server.SendPacket((s) =>
                                      s.Vroom == Vroom &&
                                      s.CanSee(this),
                                      new ServerUpdate(this));

                    return(true);

                case AresId.MSG_CHAT_CLIENT_DIRCHATPUSH:
                    ClientDirectPush push = (ClientDirectPush)e.Packet;

                    if (Encoding.UTF8.GetByteCount(push.Username) < 2)
                    {
                        SendPacket(new DirectPushError(4));
                        return(true);
                    }

                    if (push.TextSync.Length < 16)
                    {
                        SendPacket(new DirectPushError(3));
                        return(true);
                    }

                    IClient target = server.FindUser(s => s.Name == push.Username);

                    if (target == null)
                    {
                        SendPacket(new DirectPushError(1));
                        return(true);
                    }

                    if (target.Ignored.Contains(Name))
                    {
                        SendPacket(new DirectPushError(2));
                        return(true);
                    }

                    SendPacket(new DirectPushError(0));
                    server.SendPacket(target, new ServerDirectPush(this, push));

                    return(true);

                case AresId.MSG_CHAT_CLIENT_BROWSE:
                    SendPacket(new BrowseError(((Browse)e.Packet).BrowseId));
                    return(true);

                case AresId.MSG_CHAT_CLIENT_SEARCH:
                    SendPacket(new SearchEnd(((Search)e.Packet).SearchId));
                    return(true);

                case AresId.MSG_CHAT_CLIENTCOMPRESSED: {
                    Compressed packet  = (Compressed)e.Packet;
                    byte[]     payload = Zlib.Decompress(packet.Data);

                    var reader = new PacketReader(payload)
                    {
                        Position = 0L
                    };

                    while (reader.Remaining >= 3)
                    {
                        ushort count = reader.ReadUInt16();
                        byte   id    = reader.ReadByte();

                        IPacket msg = Socket.Formatter.Unformat(id, reader.ReadBytes(count));
                        OnPacketReceived(Socket, new PacketEventArgs(msg, WebSocketMessageType.Binary, 0));
                    }
                    break;
                }

                default:
                    break;
                }

                return(false);//wasn't handled
            }
            else
            {
                //not captcha, not logged, error?
                Logging.Info("AresClient", "Client {0} sent {1} before logging in.", this.ExternalIp, e.Packet.Id);
                return(true);
            }
        }