Пример #1
0
    public static IEnumerable <SysCpkEntry> EnumerateSysFiles(Cpk cpk, int index)
    {
        if (cpk.ItocEntries.Count != 16)
        {
            throw new InvalidDataException($"{cpk.ItocEntries.Count} != 16");
        }

        byte[] data;
        using (var ms = new MemoryStream()) {
            cpk.ExtractItoc(ms, cpk.ItocEntries[index]);
            if (index != 1)   // lzss
            {
                Span <byte> span = stackalloc byte[4];
                ms.Position = 0;
                ms.Read(span);
                var size = BitConverter.ToInt32(span);
                data = LZSS.Decode(ms.StreamAsIEnumerable()).ToArray();
                if (data.Length != size)
                {
                    throw new InvalidDataException($"itoc {index} decoded size {data.Length} != {size}");
                }
            }
            else
            {
                data        = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(data);
            }
        }
        return(HandleNested("", data));
    }
Пример #2
0
 private void tabMain_DragDrop(object sender, string path)
 {
     if (sender == PB_Unpack)
     {
         openARC(path, pBar1);
     }
     else if (sender == PB_BCLIM)
     {
         openIMG(path);
     }
     else if (sender == PB_Repack)
     {
         saveARC(path);
     }
     else
     {
         try {
             LZSS.Decompress(path, Path.Combine(Path.GetDirectoryName(path), "dec_" + Path.GetFileName(path)));
             File.Delete(path);
             System.Media.SystemSounds.Asterisk.Play();
         } catch { try { if (threads < 1)
                         {
                             new Thread(() => { threads++; new BLZCoder(new[] { "-d", path }, pBar1); threads--; WinFormsUtil.Alert("Decompressed!"); }).Start();
                         }
                   } catch { WinFormsUtil.Error("Unable to process file."); threads = 0; } }
     }
 }
Пример #3
0
        private static void ExtractFiles(FileList fileList, IFileWriter writer)
        {
            Console.WriteLine($"Extracting {fileList.Name}");

            writer.CreateDirectory(fileList.Name);

            foreach (FileData file in fileList.GetFiles())
            {
                if (file.Compressed)
                {
                    using (var compressed = new MemoryStream(file.Contents))
                    {
                        using (var decompressed = new MemoryStream())
                        {
                            LZSS.Decompress(compressed, decompressed);
                            file.Contents = decompressed.ToArray();
                        }
                    }
                }

                if (file.IsArchive())
                {
                    ExtractFiles(new ArchiveFileList(Path.Combine(fileList.Name, file.Name), file.Contents), writer);
                }
                else
                {
                    writer.Write(Path.Combine(fileList.Name, $"{file.Name}.{file.GetExtension()}"), file.Contents);
                }
            }
        }
Пример #4
0
 // Token: 0x06000026 RID: 38 RVA: 0x000024C4 File Offset: 0x000006C4
 public byte[] ReadLZSS(uint expectedSize, bool inPAA = false)
 {
     if (expectedSize < 1024u && !inPAA)
     {
         return(this.ReadBytes((int)expectedSize));
     }
     byte[] result = new byte[expectedSize];
     LZSS.readLZSS(this.BaseStream, out result, expectedSize, inPAA);
     return(result);
 }
Пример #5
0
    byte[] GetType1FileData(int indexOffset)
    {
        DataStream.Seek(indexOffset, SeekOrigin.Begin);

        UInt16 uncmpSize = ReadUInt16LE(DataStream);
        UInt16 cmpSize   = ReadUInt16LE(DataStream);

        DataStream.Seek(indexOffset + 4, SeekOrigin.Begin);
        return(LZSS.Decode(DataStream, cmpSize, uncmpSize));
    }
Пример #6
0
        public void Save(System.IO.Stream stream)
        {
            using (var writer = new FileWriter(stream))
            {
                writer.SetByteOrder(true);
                writer.Write(files.Count);
                writer.Write(new uint[files.Count]); //reserve space for offsets
                for (int i = 0; i < files.Count; i++)
                {
                    uint uncomp_size = (uint)files[i].FileData.Length;

                    writer.WriteUint32Offset(4 + (i * 4));
                    writer.Write(uncomp_size);
                    writer.Write((uint)files[i].CompressionType);

                    byte[] savedBytes = files[i].AsBytes();
                    switch (files[i].CompressionType)
                    {
                    case CompressionType.LZSS:
                        savedBytes = LZSS.Encode(savedBytes);
                        break;

                    case CompressionType.INFLATE:
                    {
                        var compressed = STLibraryCompression.ZLIB.Compress(savedBytes);

                        List <byte> output = new List <byte>();
                        output.AddRange(WriteBigEndian(uncomp_size));
                        output.AddRange(WriteBigEndian((uint)compressed.Length));
                        output.AddRange(compressed);
                        savedBytes = output.ToArray();
                        output.Clear();
                    }
                    break;

                    case CompressionType.SLIDE:
                    case CompressionType.FSLIDE_Alt:
                    case CompressionType.FLIDE:
                    {
                        List <byte> output = new List <byte>();
                        output.AddRange(WriteBigEndian(uncomp_size));
                        output.AddRange(CompressSlide(savedBytes, uncomp_size));
                        savedBytes = output.ToArray();
                        output.Clear();
                    }
                    break;

                    default:
                        throw new Exception($"Compression not supported! {files[i].CompressionType}");
                    }
                    writer.Write(savedBytes);
                }
            }
        }
Пример #7
0
 private static void Compress(string filename, Stream file)
 {
     using (var output = new FileStream($"{filename}{Extension}", FileMode.Create, FileAccess.Write))
     {
         output.WriteCharacters(Header);
         output.WriteUInt(Version);
         output.Position += 4;
         output.WriteUInt((uint)file.Length);
         LZSS.Compress(file, output);
         output.Position = 8;
         output.WriteUInt((uint)(output.Length - 16));
     }
 }
Пример #8
0
 public byte[] ReadLZSS(uint expectedSize, bool inPAA = false)
 {
     if (expectedSize < 1024 && !inPAA) //data is always compressed in PAAs
     {
         return(ReadBytes((int)expectedSize));
     }
     else
     {
         var dst = new byte[expectedSize];
         LZSS.ReadLZSS(BaseStream, out dst, expectedSize, inPAA); //PAAs calculate checksums with signed byte values
         return(dst);
     }
 }
Пример #9
0
            public void DecompressSimpleText()
            {
                var inputPath    = TestContext.CurrentContext.TestDirectory + "../../../res/compressedTestFile";
                var expectedPath = TestContext.CurrentContext.TestDirectory + "../../../res/testfile2";
                var expectedFile = new DataFile(expectedPath);
                var inputFile    = new DataFile(inputPath);

                var comp       = new LZSS();
                var actualFile = comp.Decompress(inputFile);

                Assert.AreEqual(expectedFile.GetBytes(0, expectedFile.Length),
                                actualFile.GetBytes(0, actualFile.Length));
                ;
            }
Пример #10
0
            public void CompressSimpleTextNoPointersByteArraysOnly()
            {
                byte[] inputBytes = { 97, 98, 99 };
                var    inputFile  = new DataFile();

                inputFile.LoadBytes(inputBytes);
                byte[] expected = { 48, 152, 140, 96 };

                var comp   = new LZSS();
                var output = comp.Compress(inputFile);
                var actual = output.GetBytes(0, output.Length);

                Assert.AreEqual(expected, actual);
            }
Пример #11
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                return;
            }

            using (FileStream input = new FileStream(args[0], FileMode.Open))
            {
                using (FileStream output = new FileStream(args[0] + "_decompressed", FileMode.Create))
                {
                    LZSS.Decompress(input, output);
                }
            }
        }
Пример #12
0
            public void CompressSimpleTextPointers()
            {
                var inputPath = TestContext.CurrentContext.TestDirectory + "../../../res/testfile3";
                var inputFile = new DataFile(inputPath);

                byte[] expectedData = { 48, 152, 140, 102, 72, 1, 152 };
                var    expected     = new DataFile();

                expected.LoadBytes(expectedData);

                var comp   = new LZSS();
                var actual = comp.Compress(inputFile);

                Assert.AreEqual(expected.GetBytes(0, expected.Length), actual.GetBytes(0, actual.Length));
            }
Пример #13
0
            public void CompressSimpleTextNoPointersDataFile()
            {
                var inputPath = TestContext.CurrentContext.TestDirectory + "../../../res/testfile1";
                var inputFile = new DataFile(inputPath);

                byte[] expectedData = { 48, 152, 140, 96 };
                var    expected     = new DataFile();

                expected.LoadBytes(expectedData);

                var comp   = new LZSS();
                var actual = comp.Compress(inputFile);

                Assert.IsTrue(DataFile.Compare(expected, actual));
            }
Пример #14
0
    // private methods

    byte[] GetType2FileData(int indexOffset, int part)
    {
        DataRunStream.Seek(indexOffset, SeekOrigin.Begin);

        int data001Offset = DataRunStream.ReadByte() + (DataRunStream.ReadByte() << 8) + (DataRunStream.ReadByte() << 16);

        for (int i = 0; i < part; i++)
        {
            int size = ReadUInt16LE(DataRunStream);
            data001Offset += size;
        }

        DataStream.Seek(data001Offset, SeekOrigin.Begin);
        UInt16 uncmpSize = ReadUInt16LE(DataStream);
        UInt16 cmpSize   = ReadUInt16LE(DataStream);

        return(LZSS.Decode(DataStream, cmpSize, uncmpSize));
    }
Пример #15
0
        public /*bool*/ byte[] TryDecompress()
        {
            string s;

            using (OpenFileDialog ofd = new OpenFileDialog())
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    s = ofd.FileName;
                }
                else
                {
                    return(null /*false*/);
                }
            fileSave = Path.GetFileName(s);
            byte[] buffer = System.IO.File.ReadAllBytes(s);
            //return LZSS.DecompressAll(buffer, (uint)buffer.Length).Length > 0 ? false:g
            return(LZSS.DecompressAll(buffer, (uint)buffer.Length));
        }
Пример #16
0
        private void button_decompDbg_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "binary dump|*.*";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                byte[] dump             = File.ReadAllBytes(openFileDialog.FileName);
                byte[] decompDump       = LZSS.Decompress(dump);
                var    outputFolderPath = Path.GetDirectoryName(openFileDialog.FileName);

                //Decompressed file
                using (FileStream fs = File.Create(outputFolderPath + "//" + "decompressed_blob.bin"))
                {
                    fs.Write(decompDump, 0, decompDump.Length);
                }
            }
        }
Пример #17
0
 private void DecompressLZSS_BLZ(string path)
 {
     try
     {
         LZSS.Decompress(path, Path.Combine(Path.GetDirectoryName(path), "dec_" + Path.GetFileName(path)));
         File.Delete(path);
     }
     catch
     {
         try
         {
             if (threads < 1)
             {
                 new Thread(() => { Interlocked.Increment(ref threads); new BLZCoder(new[] { "-d", path }, pBar1); Interlocked.Decrement(ref threads); WinFormsUtil.Alert("Decompressed!"); }).Start();
             }
         }
         catch { WinFormsUtil.Error("Unable to process file."); threads = 0; }
     }
 }
Пример #18
0
        private static void Decompress(string filename, Stream file)
        {
            if (file.ReadUInt() != Version)
            {
                Console.WriteLine("Unknown GTZ version");
                return;
            }

            uint compressedSize = file.ReadUInt();

            if (file.Length != compressedSize + 16)
            {
                Console.WriteLine("Incorrect file size");
                return;
            }

            uint uncompressedSize = file.ReadUInt();

            using (var compressed = new MemoryStream())
            {
                file.CopyTo(compressed);
                compressed.Position = 0;
                using (var decompressed = new MemoryStream())
                {
                    LZSS.Decompress(compressed, decompressed);

                    if (decompressed.Length < uncompressedSize)
                    {
                        Console.WriteLine("Decompressed data too short");
                        return;
                    }

                    decompressed.Position = 0;
                    decompressed.SetLength(uncompressedSize);
                    filename = filename.EndsWith(Extension) ? filename.Replace(Extension, "") : $"decompressed_{filename}";
                    using (var output = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    {
                        decompressed.CopyTo(output);
                    }
                }
            }
        }
Пример #19
0
 public byte[] ReadLZSS(uint expectedSize, bool inPAA = false)
 {
     if (expectedSize < 1024 && !inPAA) //data is always compressed in PAAs
     {
         return(ReadBytes((int)expectedSize));
     }
     else
     {
         // XXX: Needs testing
         //var buffer = new byte[expectedSize];
         //using (var lzss = new LzssStream(BaseStream, CompressionMode.Decompress, true))
         //{
         //    lzss.Read(buffer, 0, (int)expectedSize);
         //}
         //Chesksum(inPAA, buffer); //PAAs calculate checksums with signed byte values
         byte[] buffer;
         LZSS.ReadLZSS(BaseStream, out buffer, expectedSize, inPAA);
         return(buffer);
     }
 }
Пример #20
0
        private void button_NetworkControl_Disconnect_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream("far.exe", FileMode.Open);

            byte[] uncomp = new byte[fs.Length];

            fs.Read(uncomp, 0, uncomp.Length);

            ICompression iCompressionArray_obj = new LZSS(8, true, true, false, 131072);

            DateTime dt1 = DateTime.Now;

            byte [] compress = iCompressionArray_obj.Compress(uncomp, false);

            DateTime dt2 = DateTime.Now;

            TimeSpan ts1 = dt2 - dt1;

            MessageBox.Show(ts1.Minutes.ToString() + ":" + ts1.Seconds.ToString() + ":" + ts1.Milliseconds.ToString());
        }
Пример #21
0
        public static LPack FromData(byte[] Data)
        {
            if (Data.Length < 0x10)
            {
                return(null);
            }

            LPack Output = new LPack();

            using (MemoryStream Input = new MemoryStream(Data))
            {
                BinaryReader Reader = new BinaryReader(Input);

                uint FilesCount    = Reader.ReadUInt32();
                uint FileDecLength = Reader.ReadUInt32();

                //Simple validity check
                uint FirstAddr = 8 + FilesCount * 8;
                Input.Seek(4, SeekOrigin.Current);
                if (Reader.ReadUInt32() != FirstAddr)
                {
                    return(null);
                }

                Output.Files = new PackFile[FilesCount];

                for (int i = 0; i < FilesCount; i++)
                {
                    Input.Seek(8 + i * 8, SeekOrigin.Begin);

                    uint DecLength = Utils.ReadUInt24(Reader);
                    byte FileId    = Reader.ReadByte();
                    uint Address   = Reader.ReadUInt32();

                    Output.Files[i].FileId = FileId;
                    Output.Files[i].Data   = LZSS.Decompress(Data, Address, DecLength);
                }
            }

            return(Output);
        }
Пример #22
0
        public static byte[] ToData(LPack Pack)
        {
            using (MemoryStream Output = new MemoryStream())
            {
                BinaryWriter Writer = new BinaryWriter(Output);

                Writer.Write(Pack.Files.Length);
                Writer.Write(0u); //Total decompressed length Place Holder

                uint DataAddress   = (uint)(8 + Pack.Files.Length * 8);
                uint FileDecLength = 0;

                for (int i = 0; i < Pack.Files.Length; i++)
                {
                    Output.Seek(8 + i * 8, SeekOrigin.Begin);

                    Utils.WriteUInt24(Writer, (uint)Pack.Files[i].Data.Length);
                    Writer.Write(Pack.Files[i].FileId);
                    Writer.Write(DataAddress);

                    Output.Seek(DataAddress, SeekOrigin.Begin);

                    byte[] Comp = LZSS.Compress(Pack.Files[i].Data);

                    Writer.Write(Comp);

                    DataAddress   += (uint)Comp.Length;
                    FileDecLength += (uint)Pack.Files[i].Data.Length;
                }

                Output.Seek(4, SeekOrigin.Begin);
                Writer.Write(FileDecLength);

                return(Output.ToArray());
            }
        }
Пример #23
0
        static void Main(string[] args)
        {
            Console.Title = "MBuild - A Marvelous Translation and Hacking Tool";

            Console.WriteLine("MBuild - " + Application.ProductVersion.ToString().Split('.')[0] + "." + Application.ProductVersion.ToString().Split('.')[1]);
            Console.WriteLine("A Marvelous Translation and Hacking Tool");
            Console.WriteLine("Written by DackR aka Daniel Martin Burgess\r\n");

            if (args.Length == 0)
            {
                Console.WriteLine("No Arguments specified.");
                UseXML("MBuild.MBXML", !Settings.Default.AutoBuild);
            }
            else
            {
                string mArg = args[0].Trim().ToLower();
                switch (mArg)
                {
                case "build":
                    BuildXML(args);
                    break;

                case "dump-script":
                    DumpScript(args);
                    break;

                case "bin-script":
                    BuildScript(args);
                    break;

                case "comp":
                    CompressFile(args);
                    break;

                case "decomp":
                    DeCompressFile(args);
                    break;

                case "bpp-convert":
                    //BuildScript(args);
                    break;

                case "dmpptr":
                    DumpPointers();
                    break;

                case "fixsum":
                    FixCheckSum(args);
                    break;

                case "mbxml-shell":
                    string[] makeArg = new string[] { "-f", "-t", ".mbxml", "-si", Application.ExecutablePath, "-a", Application.ExecutablePath, "-sn", "MBXML File", "-sc", "MBuild_XML_File" };
                    //string[] assocArg = new string[] { "-f", "-t", ".txt", "-associate", Application.ExecutablePath };
                    CTypes.Main(makeArg);
                    //CTypes.Main(assocArg);
                    //FileAssociation.SetAssociation(".mbxml", "MBuild_XML_File", Application.ExecutablePath, "MBXML File", args);
                    break;

                case "ips":
                    MakeIPS(args);
                    break;

                case "xdelta":
                    MakexDelta(args);
                    break;

                case "extract":    //used to extract RAW binary data from a file
                    ExtractBin(args);
                    break;

                case "dmpdata":
                    //Dump data located at the various pointers
                    DumpData(args);
                    break;

                case "bm5dump":
                    SBM5.DumpDataFromPointerTab(@"F:\GoogleDrive\SBM5\Base\Base.sfc", @"F:\GoogleDrive\SBM5\Dump\");
                    break;

                case "test":
                    string       romfile = @"D:\GoogleDrive\SuperFamicomWars\base.sfc";
                    byte[]       data    = File.ReadAllBytes(romfile);
                    MemoryStream ms      = LZSS.Decompress(data);
                    byte[]       dcdata  = ms.ToArray();
                    break;

                default:
                    if (mArg.ToLower().Contains(".mbxml") && File.Exists(mArg))
                    {    //detected xml file specified... Try to build.
                        UseXML(mArg, false);
                        //Console.WriteLine(mArg);
                        //Console.ReadKey(true);
                    }
                    break;
                }
            }
            LCompress.LunarCompressCleanup();
            xDelta.xDeltaCleanup();
            bool wait = false;

            Console.Write("Press any key to exit (\"q\" to stop count-down)");
            DateTime beginWait = DateTime.Now;

            while (!Console.KeyAvailable && DateTime.Now.Subtract(beginWait).TotalSeconds < 3)
            {
                Console.Write(".");
                Thread.Sleep(250);
            }
            if (Console.KeyAvailable && (Console.ReadKey(true).Key == ConsoleKey.Q))
            {
                wait = true;
            }
            if (wait)
            {
                Console.CursorLeft = 0;
                Console.Write(("").PadLeft(79, ' '));
                Console.CursorLeft = 0;
                Console.Write("Press any key to exit...");
                Console.ReadKey(true);
            }
        }
Пример #24
0
        public static file load(Stream data)
        {
            //Too small
            if (data.Length < 0x10)
            {
                data.Close();
                return(new file {
                    type = formatType.unsupported
                });
            }

            BinaryReader input = new BinaryReader(data);
            uint         magic, length;

            switch (peek(input))
            {
            case 0x00010000: return(new file {
                    data = GfModel.load(data), type = formatType.model
                });

            case 0x00060000: return(new file {
                    data = GfMotion.loadAnim(input), type = formatType.anims
                });

            case 0x15041213: return(new file {
                    data = GfTexture.load(data), type = formatType.image
                });

            case 0x15122117:
                RenderBase.OModelGroup mdls = new RenderBase.OModelGroup();
                mdls.model.Add(GfModel.loadModel(data));
                return(new file {
                    data = mdls, type = formatType.model
                });
            }

            switch (getMagic(input, 5))
            {
            case "MODEL": return(new file {
                    data = DQVIIPack.load(data), type = formatType.container
                });
            }

            switch (getMagic(input, 4))
            {
            case "CGFX": return(new file {
                    data = CGFX.load(data), type = formatType.model
                });

            case "CRAG": return(new file {
                    data = GARC.load(data), type = formatType.container
                });

            case "darc": return(new file {
                    data = DARC.load(data), type = formatType.container
                });

            case "FPT0": return(new file {
                    data = FPT0.load(data), type = formatType.container
                });

            case "IECP":
                magic  = input.ReadUInt32();
                length = input.ReadUInt32();
                return(load(new MemoryStream(LZSS.decompress(data, length))));

            case "NLK2":
                data.Seek(0x80, SeekOrigin.Begin);
                return(new file
                {
                    data = CGFX.load(data),
                    type = formatType.model
                });

            case "SARC": return(new file {
                    data = SARC.load(data), type = formatType.container
                });

            case "SMES": return(new file {
                    data = NLP.loadMesh(data), type = formatType.model
                });

            case "Yaz0":
                magic  = input.ReadUInt32();
                length = IOUtils.endianSwap(input.ReadUInt32());
                data.Seek(8, SeekOrigin.Current);
                return(load(new MemoryStream(Yaz0.decompress(data, length))));

            case "zmdl": return(new file {
                    data = ZMDL.load(data), type = formatType.model
                });

            case "ztex": return(new file {
                    data = ZTEX.load(data), type = formatType.texture
                });
            }

            //Check if is a BCLIM or BFLIM file (header on the end)
            if (data.Length > 0x28)
            {
                data.Seek(-0x28, SeekOrigin.End);
                string clim = IOUtils.readStringWithLength(input, 4);
                if (clim == "CLIM" || clim == "FLIM")
                {
                    return new file {
                               data = BCLIM.load(data), type = formatType.image
                    }
                }
                ;
            }

            switch (getMagic(input, 3))
            {
            case "BCH":
                byte[] buffer = new byte[data.Length];
                input.Read(buffer, 0, buffer.Length);
                data.Close();
                return(new file
                {
                    data = BCH.load(new MemoryStream(buffer)),
                    type = formatType.model
                });

            case "DMP": return(new file {
                    data = DMP.load(data), type = formatType.image
                });
            }

            string magic2b = getMagic(input, 2);

            switch (magic2b)
            {
            case "AD": return(new file {
                    data = AD.load(data), type = formatType.model
                });

            case "BM": return(new file {
                    data = MM.load(data), type = formatType.model
                });

            case "BS": return(new file {
                    data = BS.load(data), type = formatType.anims
                });

            case "CM": return(new file {
                    data = CM.load(data), type = formatType.model
                });

            case "CP": return(new file {
                    data = CP.load(data), type = formatType.model
                });

            case "GR": return(new file {
                    data = GR.load(data), type = formatType.model
                });

            case "MM": return(new file {
                    data = MM.load(data), type = formatType.model
                });

            case "PC": return(new file {
                    data = PC.load(data), type = formatType.model
                });

            case "PT": return(new file {
                    data = PT.load(data), type = formatType.texture
                });
            }

            if (magic2b.Length == 2)
            {
                if ((magic2b[0] >= 'A' && magic2b[0] <= 'Z') &&
                    (magic2b[1] >= 'A' && magic2b[1] <= 'Z'))
                {
                    return(new file {
                        data = PkmnContainer.load(data), type = formatType.container
                    });
                }
            }

            //Compressions
            data.Seek(0, SeekOrigin.Begin);
            uint cmp = input.ReadUInt32();

            if ((cmp & 0xff) == 0x13)
            {
                cmp = input.ReadUInt32();
            }
            switch (cmp & 0xff)
            {
            case 0x11: return(load(new MemoryStream(LZSS_Ninty.decompress(data, cmp >> 8))));

            case 0x90:
                byte[] buffer  = BLZ.decompress(data);
                byte[] newData = new byte[buffer.Length - 1];
                Buffer.BlockCopy(buffer, 1, newData, 0, newData.Length);
                return(load(new MemoryStream(newData)));
            }

            data.Close();
            return(new file {
                type = formatType.unsupported
            });
        }
Пример #25
0
        public static void Decompress(object sender, EventArgs e)
        {
            var tsi = sender as ToolStripMenuItem;

            if (!PrepareFiles("Open a " + tsi.Tag.ToString() + " compressed file...", "Save your decompressed file...", ".decomp", out FileStream openFile, out FileStream saveFile))
            {
                return;
            }

            try
            {
                using (openFile)
                    using (var outFs = new BinaryWriterX(saveFile))
                        switch (tsi.Tag)
                        {
                        case Compression.Level5:
                            outFs.Write(Level5.Decompress(openFile));
                            break;

                        case Compression.GZip:
                            outFs.Write(GZip.Decompress(openFile));
                            break;

                        case Compression.Huff4:
                            outFs.Write(Huffman.Decompress(openFile, 4));
                            break;

                        case Compression.Huff8:
                            outFs.Write(Huffman.Decompress(openFile, 8));
                            break;

                        case Compression.LZ10:
                            outFs.Write(LZ10.Decompress(openFile));
                            break;

                        case Compression.LZ11:
                            outFs.Write(LZ11.Decompress(openFile));
                            break;

                        case Compression.LZ77:
                            outFs.Write(LZ77.Decompress(openFile));
                            break;

                        case Compression.LZSS:
                            outFs.Write(LZSS.Decompress(openFile, LZSS.GetDecompressedSize(openFile)));
                            break;

                        case Compression.LZSSVLE:
                            outFs.Write(LZSSVLE.Decompress(openFile));
                            break;

                        case Compression.RevLZ77:
                            outFs.Write(RevLZ77.Decompress(openFile));
                            break;

                        case Compression.LZECD:
                            outFs.Write(LZECD.Decompress(openFile));
                            break;

                        case Compression.RLE:
                            outFs.Write(RLE.Decompress(openFile));
                            break;

                        case Compression.ZLib:
                            outFs.Write(ZLib.Decompress(openFile));
                            break;
                        }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            MessageBox.Show($"Successfully decompressed {Path.GetFileName(openFile.Name)}.", tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Пример #26
0
        public static List <LZSS> SetLZSS(string text)
        {
            var lzss = new List <LZSS>();
            int i    = 0;

            while (i < text.Count())
            {
                var lz = new LZSS();
                if (lzss.Count == 0)
                {
                    lz.Dictionary       = "";
                    lz.FutureDictionary = text[0].ToString();
                    lz.Buffer           = text.Substring(0, 8);
                    lz.Code             = $"0, {text[0]} ";
                    lz.LengthCode       = 9;
                    lzss.Add(lz);
                }
                else
                {
                    int  vh   = -1;
                    bool flag = false;
                    lz.Dictionary = lzss.LastOrDefault().FutureDictionary;
                    int length = 0;
                    if (text.Length - (i + 1) >= 8)
                    {
                        length    = 8;
                        lz.Buffer = text.Substring(i, length);
                    }
                    else
                    {
                        length    = text.Length - (i + 1);
                        lz.Buffer = text.Substring(i, length);
                    }
                    for (int j = lz.Buffer.Length - 1; j >= 0; j--)
                    {
                        vh = lz.Dictionary.IndexOf(lz.Buffer.Substring(0, j + 1));
                        if (vh != -1)
                        {
                            flag = true;
                            int lengthSub = 0;
                            if (j == 0 && vh != 0)
                            {
                                if (lz.Buffer.Count() != 1)
                                {
                                    lengthSub = j + 2;
                                }
                                else
                                {
                                    lengthSub = j + 1;
                                }
                            }
                            else if (j == 0 && vh == 0)
                            {
                                lengthSub = j + 1;
                            }
                            else if (j != 0)
                            {
                                lengthSub = j + 1;
                            }
                            if (lz.Dictionary.Length >= 16 || (lz.Dictionary + lz.Buffer.Substring(0, lengthSub)).Length >= 16)
                            {
                                int dict = lz.Dictionary.Length + lz.Buffer.Substring(0, lengthSub).Length - lz.Dictionary.Length;
                                lz.FutureDictionary = lz.Dictionary.Remove(0, dict) + lz.Buffer.Substring(0, lengthSub);
                                lz.Code             = $"1, ({vh}, {lengthSub})";
                                lz.LengthCode       = 7;
                                i = i + dict - 1;
                                break;
                            }
                            else
                            {
                                int dict = lz.Dictionary.Length + lz.Buffer.Substring(0, lengthSub).Length - lz.Dictionary.Length;
                                lz.FutureDictionary = lz.Dictionary + lz.Buffer.Substring(0, lengthSub);
                                lz.Code             = $"1, ({vh}, {lengthSub})";
                                lz.LengthCode       = 7;
                                i = i + dict - 1;
                                break;
                            }
                        }
                    }
                    if (flag == false)
                    {
                        if (lz.Dictionary.Length >= 16)
                        {
                            lz.FutureDictionary = lz.Dictionary.Remove(0, 1) + text[i];
                            lz.Code             = $"0, {text[i]} ";
                            lz.LengthCode       = 9;
                        }
                        else
                        {
                            lz.FutureDictionary = lz.Dictionary + text[i];
                            lz.Code             = $"0, {text[i]} ";
                            lz.LengthCode       = 9;
                        }
                    }
                    lzss.Add(lz);
                }
                i++;
            }
            return(lzss);
        }
Пример #27
0
        private void button_Decompress_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "LoGH Containers|*.mvx;*.arc";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string      outputFolderPath = openFileDialog.FileName + "_";
                GenericInfo tmpGeneric       = new GenericInfo
                {
                    ContainerName = openFileDialog.FileName,
                    ContainerType = Path.GetExtension(openFileDialog.FileName)
                };

                ARCHeader     tmpHeader = new ARCHeader();
                List <ARCToc> tmpToc    = new List <ARCToc>();

                using (BinaryReader reader = new BinaryReader(new FileStream(openFileDialog.FileName, FileMode.Open)))
                {
                    //Parse Header
                    reader.BaseStream.Seek(0, SeekOrigin.Begin);
                    tmpHeader.HeaderIdentifier     = reader.ReadBytes(4);
                    tmpHeader.FileReaderBufferSize = reader.ReadByte();
                    tmpHeader.UnknownType          = reader.ReadByte();

                    reader.BaseStream.Seek(3, SeekOrigin.Current); //0x00 three times

                    tmpHeader.UnknownValue1   = reader.ReadByte();
                    tmpHeader.TocPointer2     = reader.ReadByte();
                    tmpHeader.UnknownValue2   = reader.ReadByte();
                    tmpHeader.UnknownType2    = reader.ReadByte();
                    tmpHeader.FileCount       = reader.ReadByte();
                    tmpHeader.UnknownValue3   = reader.ReadByte();
                    tmpHeader.CompressionType = reader.ReadByte();

                    tmpHeader.HeaderLeftover = reader.ReadBytes(112);

                    //Begin of TOC
                    reader.BaseStream.Seek(2, SeekOrigin.Current); //skip two 0x00
                    for (int i = 1; i <= tmpHeader.FileCount; i++)
                    {
                        long   entryOffset = reader.BaseStream.Position;
                        ARCToc localToc    = new ARCToc();

                        for (int j = 1; j <= 5; j++)
                        {
                            var VAL1 = reader.ReadByte();
                            reader.BaseStream.Seek(6, SeekOrigin.Current);
                            var VAL2 = reader.ReadByte();
                            reader.BaseStream.Seek(6, SeekOrigin.Current);
                            var VAL3 = reader.ReadByte();
                            reader.BaseStream.Seek(6, SeekOrigin.Current);
                            var VAL4 = reader.ReadByte();
                            reader.BaseStream.Seek(6, SeekOrigin.Current);

                            var tmpVal = (VAL1 | (VAL2 << 8) | (VAL3 << 16) | (VAL4 << 24));

                            switch (j)
                            {
                            case 1:
                                localToc.NameOffset = tmpVal;
                                break;

                            case 2:
                                localToc.NameLength = tmpVal;
                                break;

                            case 3:
                                localToc.Offset = tmpVal;
                                break;

                            case 4:
                                localToc.Zsize = tmpVal;
                                break;

                            case 5:
                                localToc.Size = tmpVal;
                                break;

                            default:
                                throw new Exception("NOPE!");
                            }

                            entryOffset += 1;
                            reader.BaseStream.Seek(entryOffset, SeekOrigin.Begin);
                        }

                        //Readout name string
                        long preOffset = reader.BaseStream.Position;
                        reader.BaseStream.Seek(localToc.NameOffset, SeekOrigin.Begin);
                        localToc.NameBytes = reader.ReadBytes(localToc.NameLength);
                        localToc.Name      = new ASCIIEncoding().GetString(localToc.NameBytes, 0, localToc.NameLength - 1); //-1 because we dont want the null terminator

                        //Read DATA (offset since file begin)
                        reader.BaseStream.Seek(localToc.Offset, SeekOrigin.Begin);
                        localToc.Data      = reader.ReadBytes(localToc.Zsize);
                        localToc.OffsetEnd = (int)reader.BaseStream.Position;

                        //Reset Seek for next header file
                        reader.BaseStream.Seek(preOffset, SeekOrigin.Begin);

                        //Add toc to list
                        tmpToc.Add(localToc);

                        //Everything is ready to readout compressed data
                        if (localToc.Zsize == localToc.Size)
                        {
                            //Content is unencrypted... passtrough directly to filewriter
                            localToc.DataDecompressed = localToc.Data;
                        }
                        else
                        {
                            //decompress with lzss
                            localToc.DataDecompressed = LZSS.Decompress(localToc.Data);
                        }

                        reader.BaseStream.Seek(27, SeekOrigin.Current);
                    }
                }

                //PHASE 2: Export data from memory to Filesystem
                DirectoryInfo di = Directory.CreateDirectory(outputFolderPath);
                foreach (var toc in tmpToc)
                {
                    //Check name for sub-folders - when there are some - create
                    Directory.CreateDirectory(Path.GetDirectoryName(outputFolderPath + "//" + toc.Name));

                    //Decompressed file
                    using (FileStream fs = File.Create(outputFolderPath + "//" + toc.Name))
                    {
                        fs.Write(toc.DataDecompressed, 0, toc.DataDecompressed.Length);
                    }

                    //Compressed file
                    using (FileStream fs = File.Create(outputFolderPath + "//" + toc.Name + "_COMP"))
                    {
                        fs.Write(toc.Data, 0, toc.Data.Length);
                    }
                }

                SerializeCollection tmpSer = new SerializeCollection
                {
                    generic   = tmpGeneric,
                    arcHeader = tmpHeader,
                    arcToc    = tmpToc
                };

                //Serialize header & toc
                IFormatter formatter = new BinaryFormatter();
                Stream     stream    = new FileStream(outputFolderPath + "//_header.bin", FileMode.Create, FileAccess.Write, FileShare.None);
                //GZipStream gzip = new GZipStream(stream, CompressionLevel.Fastest);
                formatter.Serialize(stream, tmpSer);
                stream.Close();
            }
        }
Пример #28
0
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: <input path> [-o <output path>] [-A <algorithm (lz, ppm, huffman)>]");
                return;
            }

            DataFile    input;
            string      outputPath;
            Stopwatch   watch         = new Stopwatch();
            ICompressor compressor    = new LZSS();
            var         fileExtension = "lz";

            try {
                var inputPath = args[0];
                input = new DataFile(inputPath);

                if (args.Contains("-A"))
                {
                    var i = Array.IndexOf(args, "-A") + 1;
                    Console.WriteLine($"{args[i]}");
                    switch (args[i])
                    {
                    case "lz":
                        compressor    = new LZSS();
                        fileExtension = "lz";
                        break;

                    case "ppm":
                        compressor    = new PredictionByPartialMatching();
                        fileExtension = "ppm";
                        break;

                    case "huffman":
                        compressor    = new HuffmanCompressor();
                        fileExtension = "huffman";
                        break;

                    default:
                        throw new InvalidCompressorException();
                    }
                }

                var compress = !args.Contains("-D");

                if (!compress)
                {
                    outputPath = Path.GetFullPath(inputPath);
                    outputPath = Path.ChangeExtension(outputPath, null);
                }
                else
                {
                    outputPath = Path.GetFullPath(inputPath) + "." + fileExtension;
                }

                if (args.Contains("-o"))
                {
                    var i = Array.IndexOf(args, "-o") + 1;
                    outputPath = args[i];
                }

                Console.WriteLine("{0}ompressing file with algorithm {1}.", compress ? "C" : "Dec", fileExtension);
                DataFile output;
                Thread   t = new Thread(PrintStatus);

                t.Start(compressor);
                watch.Start();
                if (compress)
                {
                    output = compressor.Compress(input);
                }
                else
                {
                    output = compressor.Decompress(input);
                }

                output.WriteToFile(outputPath);
                Console.WriteLine("\rPercent: 100.0%");
                Console.WriteLine($"Elapsed time: {watch.Elapsed} Ratio: {(double)output.Length / input.Length}");
                Console.WriteLine("Compression speed: " + (double)input.Length / watch.ElapsedMilliseconds + " kb/s");
                Console.WriteLine("File written to {0}", outputPath);
                t.Abort();
            }
            catch (FileNotFoundException e) {
                Console.WriteLine("File was not found: {0}", e.Message);
            }
            catch (InvalidCompressorException) {
                Console.WriteLine("The compression algorithm specified does not exist");
            }
            catch (DirectoryNotFoundException e) {
                Console.WriteLine("Directory or file does not exist: {0}", e.Message);
            }
        }
Пример #29
0
        public TitleScreenEditor6()
        {
            InitializeComponent();
            AllowDrop           = true;
            DragEnter          += TC_Main_DragEnter;
            DragDrop           += TC_Main_DragDrop;
            PB_Image.AllowDrop  = true;
            PB_Image.DragEnter += TC_Main_DragEnter;
            PB_Image.DragDrop  += TC_Main_DragDrop;

            // Add tooltip to image
            new ToolTip().SetToolTip(PB_Image, "Click to toggle Green Screen\nRightClick for I/O\nCTRL+Click for Copy->Clipboard.");

            // Add context menus
            ContextMenuStrip  mnu  = new ContextMenuStrip();
            ToolStripMenuItem mnuR = new ToolStripMenuItem("Replace with...");
            ToolStripMenuItem mnuS = new ToolStripMenuItem("Save as...");

            // Assign event handlers
            mnuR.Click += ClickOpen;
            mnuS.Click += ClickSave;
            // Add to main context menu
            mnu.Items.AddRange(new ToolStripItem[] { mnuR, mnuS, });

            // Assign
            PB_Image.ContextMenuStrip = mnu;

            // Set up languages
            string[] languages = (Main.Config.ORAS ? new[] { "JP1" } : Array.Empty <string>()).Concat(new[] { "DE", "ES", "FR", "IT", "JP", "KO", "EN" }).ToArray();
            string[] games     = Main.Config.ORAS ? new[] { "OR", "AS" } : new[] { "X", "Y" };
            for (int i = 0; i < darcs.Length / 2; i++)
            {
                CB_DARC.Items.Add($"{games[0]} - {languages[i]}");
            }
            for (int i = darcs.Length / 2; i < darcs.Length; i++)
            {
                CB_DARC.Items.Add($"{games[1]} - {languages[i - (darcs.Length/2)]}");
            }

            // Load darcs
            for (int i = 0; i < darcs.Length; i++)
            {
                // Get DARC name and assign the decompressed name
                usedFiles[i] = "titlescreen\\" + (compressed ? "dec_" : "") + Path.GetFileName(files[darcFiles[i]]);
                if (compressed) // Decompress file (XY does not compress)
                {
                    LZSS.Decompress(files[darcFiles[i]], usedFiles[i]);
                }
                // Read decompressed file
                var data = File.ReadAllBytes(usedFiles[i]);

                // Find darc data offset (ignore header)
                int pos = 0;
                while (BitConverter.ToUInt32(data, pos) != 0x63726164)
                {
                    pos += 4;
                    if (pos >= data.Length)
                    {
                        throw new Exception("Invalid DARC?\n\n" + usedFiles[i]);
                    }
                }
                var darcData = data.Skip(pos).ToArray();
                darcs[i] = new DARC(darcData);
            }

            CB_DARC.SelectedIndex = CB_DARC.Items.Count - 1; // last (english game2)
        }
Пример #30
0
        public static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("No options specified.");
                return(1);
            }

            switch (args[0])
            {
            // Pack a directory of files into DATA.001, DATA.DIR, DATA.RUN.
            case "--packfiles": {
                var cmpArchive          = new Archive(args[1]);
                var uncmpArchive        = new Archive(args[2]);
                PackedFileWriter writer = new PackedFileWriter(cmpArchive, uncmpArchive);
                writer.Save(args[3]);
                break;
            }

            // Decompress a file
            case "--compressfile": {
                byte[]     data    = File.ReadAllBytes(args[1]);
                byte[]     cmpData = LZSS.Encode(data);
                FileStream output  = File.Open(args[2], FileMode.Create);
                output.WriteByte((byte)(data.Length & 0xff));
                output.WriteByte((byte)(data.Length >> 8));
                output.Write(cmpData, 0, cmpData.Length);
                output.Close();
                break;
            }

            // Decompress a given file
            case "--decompressfile": {
                FileStream stream    = File.OpenRead(args[1]);
                byte[]     cmpData   = new byte[stream.Length - 2];
                UInt16     uncmpSize = (UInt16)(stream.ReadByte() + (stream.ReadByte() << 8));
                stream.Read(cmpData, 0, cmpData.Length);
                byte[] data = LZSS.Decode(cmpData, cmpData.Length, uncmpSize);

                FileStream output = File.Open(args[2], FileMode.Create);
                output.Write(data, 0, data.Length);
                output.Close();
                break;
            }

            // Dump uncompressed versions of all files
            case "--dumpallfiles": {
                var archive = new Archive(args[1]);
                var fileMgr = new PackedFileReader(archive);
                DumpAllFiles(fileMgr, args[2]);
                break;
            }

            // Dump compressed versions of all files
            case "--dumpallfilescmp": {
                var archive = new Archive(args[1]);
                var fileMgr = new PackedFileReader(archive);
                DumpAllCompressedFiles(fileMgr, args[2]);
                break;
            }

            // Dump text from an RDF file
            case "--dumprdftext": {
                byte[] data    = File.ReadAllBytes(args[1]);
                int    textPos = Int32.Parse(args[2]);
                Console.Write("\"");
                while (data[textPos] != '\0')
                {
                    char c = (char)(data[textPos++]);
                    if (c == '\\' || c == '"')
                    {
                        Console.Write("\\");
                    }
                    Console.Write(c);
                }
                Console.Write("\",\n");
                break;
            }

            // Dump table of text from an RDF file
            case "--dumprdftexttable": {
                byte[] data = File.ReadAllBytes(args[1]);
                int    pos  = Int32.Parse(args[2]);
                Console.WriteLine("const char *text[] = {");
                do
                {
                    int textPos = Helper.ReadUInt16(data, pos);
                    Console.Write("\t\"");
                    while (data[textPos] != '\0')
                    {
                        char c = (char)(data[textPos++]);
                        if (c == '\\' || c == '"')
                        {
                            Console.Write("\\");
                        }
                        Console.Write(c);
                    }
                    Console.Write("\",\n");
                    pos += 2;
                }while (Helper.ReadUInt16(data, pos) != 0);
                Console.WriteLine("\t\"\"\n};");
                break;
            }

            case "--dumpscript": {
                if (args.Length >= 3)
                {
                    DumpScript(args[1], args[2]);
                }
                else
                {
                    DumpScript(args[1], null);
                }
                break;
            }

            // Dump "scripts" (x86 code) from RDF files into txt files (uses objdump to disassemble)
            case "--dumpallscripts": {
                var    directory = args[1];
                var    outputDir = args[2];
                string sfxDir    = (args.Length >= 3 ? args[2] : null);
                foreach (String s in Directory.GetFiles(directory))
                {
                    if (s.EndsWith(".RDF"))
                    {
                        DumpScript(s, sfxDir, outputDir);
                    }
                }
                break;
            }

            default:
                Console.WriteLine("Unrecognized option \"" + args[0] + "\".");
                return(1);
            }

            return(0);
        }