private void btnDecomp_Click(object sender, EventArgs e) { int address = GetInt(txtAddress); if (address == -1) { txtAddress.SelectAll(); return; } // Try to decomp byte[] output; int res = LZ77.Decompress(M3Rom.Rom, address, out output); if (res == -1) { MessageBox.Show("There was an error decompressing the data!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show("Decompressed " + output.Length + " bytes from " + res + " bytes.", "Success"); if (dlgSave.ShowDialog() == DialogResult.OK) { File.WriteAllBytes(dlgSave.FileName, output); } } }
private void WriteTitleToLZ(string filename, int id) { DrawString2(storyList.Stories[id].Title); Graphics g3 = Graphics.FromImage(title_output); for (int i = 0; i < 7; i++) { var sRect = new Rectangle(i * 32, 0, 32, 16); var dRect = new Rectangle(0, i * 16, 32, 16); g3.DrawImage(title, dRect, sRect, GraphicsUnit.Pixel); } Color[] palette = new Color[16]; int palIndex = 14; LoadPalFile("obj.pal"); for (int j = 0; j < palette.Length; j++) { palette[j] = PALfilePalette[j + 16 * palIndex]; } byte[] raw = GBAGraphics.ToGBARaw(title_output, palette, GraphicsMode.Tile4bit); byte[] lzcomped = LZ77.Compress(raw); File.WriteAllBytes(filename, lzcomped); }
/// <summary> /// Reads TSA data at the given address, handling the byte array as necessary /// </summary> /// <param name="address">The address to the read the data at</param> /// <param name="width">The width of the TSA, in tiles</param> /// <param name="height">The height of the TSA, in tiles</param> /// <param name="compressed">Whether or not the TSA data is LZ77 compressed</param> /// <param name="flipRows">Whether or not to flip the rows of the TSA (usually for uncompressed TSA)</param> /// <returns></returns> public static TSA_Array ReadTSA(Pointer address, int width, int height, bool compressed, bool flipRows) { if (address == 0) { return(null); } //Program.Core.FEH.Space.MarkSpace("TSA ", address, address + length); byte[] data; if (compressed) { try { data = LZ77.Decompress(address); if (flipRows) { width = data[0] + 1; height = data[1] + 1; data = data.GetBytes(2); } } catch (Exception ex) { Program.ShowError("There has been an error while trying to decompress the TSA.", ex); return(null); } } else if (flipRows) { width = Core.ReadByte(address) + 1; height = Core.ReadByte(address + 1) + 1; data = Program.Core.ROM.Read(address + 2, width * height * 2); } else { data = Program.Core.ROM.Read(address, width * height * 2); } if (flipRows) { byte[] result = new byte[width * height * 2]; int row = width * 2; for (int i = 0; i < height; i++) { Array.Copy(data, (height - 1 - i) * row, result, i * row, row); } return(new TSA_Array(width, height, result)); } else { return(new TSA_Array(width, height, data)); } }
public void Decompress3_Decompresses_Decompressed() { var lz77 = new LZ77(); var input = new MemoryStream(new byte[] { 16, 9, 0, 0, 0, 0, 128, 0, 0, 0, 128, 0, 0, 0, 96 }); var output = new MemoryStream(); byte[] excpected = { 1, 2, 3 }; lz77.Decompress(input, output); byte[] result = output.ToArray(); CollectionAssert.AreEqual(excpected, result); }
public void Decompress2_Decompresses_Decompressed() { var lz77 = new LZ77(); var input = new MemoryStream(new byte[] { 16, 9, 0, 0, 0, 2, 128, 0, 0, 0, 128, 0, 128, 33, 0, 0, 0, 0, 16, 0, 0, 0, 80, 0, 40, 4, 16, 0, 0, 0, 12, 0, 0, 0, 9, 0, 9, 0, 129, 128, 5, 0, 192, 64, 3, 192, 32, 32, 0, 32, 48, 128, 0, 0, 0, 0, 0, 152, 4, 48 }); var output = new MemoryStream(); byte[] excpected = { 5, 2, 5, 8, 1, 10, 2, 4, 6, 9, 2, 3, 5, 8, 1, 1, 2, 1, 1, 1, 1, 8, 0, 1, 12 }; lz77.Decompress(input, output); byte[] result = output.ToArray(); CollectionAssert.AreEqual(excpected, result); }
public void Decompress_Decompresses_Decompressed() { var lz77 = new LZ77(); var input = new MemoryStream(new byte[] { 16, 9, 0, 0, 0, 1, 0, 0, 0, 1, 64, 0, 0, 0, 224, 0, 0, 0, 16, 0, 0, 0, 64, 0, 40, 8, 8, 0, 0, 0, 0, 0, 18, 2, 1, 0, 0, 0, 3, 0, 4, 128, 66, 64, 3, 192, 32, 32 }); var output = new MemoryStream(); byte[] excpected = { 2, 5, 7, 1, 8, 2, 5, 2, 0, 2, 5, 1, 6, 8, 9, 2, 1 }; lz77.Decompress(input, output); byte[] result = output.ToArray(); CollectionAssert.AreEqual(excpected, result); }
void Core_Insert( Palette palette, byte[] graphics, TSA_Array tsa = null) { Core.SuspendUpdate(); try { byte[] data_palette = palette.ToBytes(Palette_CheckBox.Checked); byte[] data_tileset = Tileset_CheckBox.Checked ? LZ77.Compress(graphics) : graphics; byte[] data_tsa = null; List <Tuple <string, Pointer, int> > repoints = new List <Tuple <string, Pointer, int> >(); repoints.Add(Tuple.Create("Palette", Palette_PointerBox.Value, data_palette.Length)); repoints.Add(Tuple.Create("Tileset", Tileset_PointerBox.Value, data_tileset.Length)); if (tsa != null) { data_tsa = tsa.ToBytes(TSA_CheckBox.Checked, TSA_FlipRows_CheckBox.Checked); repoints.Add(Tuple.Create("TSA", TSA_PointerBox.Value, data_tsa.Length)); } bool cancel = Prompt.ShowRepointDialog(this, "Repoint Graphics", "The image and palette to insert might need to be repointed.", "Image at " + Tileset_PointerBox.Value + " - ", repoints.ToArray()); if (cancel) { return; } Core.WriteData(this, Palette_PointerBox.Value, data_palette, "Palette at " + Palette_PointerBox.Value + " changed"); Core.WriteData(this, Tileset_PointerBox.Value, data_tileset, "Tileset at " + Tileset_PointerBox.Value + " changed"); if (tsa != null) { Core.WriteData(this, TSA_PointerBox.Value, data_tsa, "TSA Array at " + TSA_PointerBox.Value + " changed"); } } catch (Exception ex) { Program.ShowError("Could not insert image.", ex); } Core.ResumeUpdate(); Core.PerformUpdate(); }
private async Task <InputFormatterResult> ProcessInputData(byte[] data, string eAmuseInfo, string compAlgo) { data = await Task.Run(() => { IEnumerable <byte> rawData = data; if (eAmuseInfo != null) { rawData = RC4.ApplyEAmuseInfo(eAmuseInfo, data); } switch (compAlgo.ToLower()) { case "lz77": return(LZ77.Decompress(rawData).ToArray()); case "none": return(rawData.ToArray()); default: return(null); } }); if (data == null) { return(await InputFormatterResult.FailureAsync()); } KBinXML result = await Task.Run(() => { try { return(new KBinXML(data)); } catch (Exception) { Console.WriteLine("Got invalid binary XML input!"); return(null); } }); if (result == null) { return(await InputFormatterResult.FailureAsync()); } return(await InputFormatterResult.SuccessAsync(new EamuseXrpcData() { Document = result.Document, Encoding = result.BinEncoding, EamuseInfo = eAmuseInfo })); }
static void Test(byte[] bytes, Method method) { byte[] bytes2 = new byte[bytes.Length]; switch (method) { case Method.LZ10: bytes2 = LZ10.Decompress(new MemoryStream(LZ10.Compress(new MemoryStream(bytes))), bytes.Length); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.LZ11: bytes2 = LZ11.Decompress(new MemoryStream(LZ11.Compress(new MemoryStream(bytes))), bytes.Length); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.LZ40: bytes2 = LZ40.Decompress(new MemoryStream(LZ40.Compress(new MemoryStream(bytes))), bytes.Length); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.LZ77: bytes2 = LZ77.Decompress(new MemoryStream(LZ77.Compress(new MemoryStream(bytes)))); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.RevLZ77: bytes2 = RevLZ77.Decompress(new MemoryStream(RevLZ77.Compress(new MemoryStream(bytes)))); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.LZ4: bytes2 = LZ4.Decompress(new MemoryStream(LZ4.Compress(new MemoryStream(bytes)))); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.LZECD: bytes2 = LZECD.Decompress(new MemoryStream(LZECD.Compress(new MemoryStream(bytes)))); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.LZOvl: bytes2 = LZOvl.Decompress(new MemoryStream(LZOvl.Compress(new MemoryStream(bytes)))); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.MIO0: bytes2 = MIO0.Decompress(new MemoryStream(MIO0.Compress(new MemoryStream(bytes), ByteOrder.LittleEndian)), ByteOrder.LittleEndian); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; } }
public byte[] GetTSAandTerrain(bool compressed) { List <byte> tsa = new List <byte>(); foreach (MapTile tile in Tiles) { tsa.AddRange(tile.ToBytes()); } byte[] result = new byte[tsa.Count + Terrain.Length]; Array.Copy(tsa.ToArray(), result, tsa.Count); Array.Copy(Terrain, 0, result, tsa.Count, Terrain.Length); return(compressed ? LZ77.Compress(result) : result); }
unsafe public static Bitmap[] GetEnemySprite(int index) { Bitmap[] ret = new Bitmap[2]; // Get gfx stuff int gfxPointer = GetPointer(index + 8) + 12; byte[] gfxData; if (LZ77.Decompress(Rom, gfxPointer, out gfxData) == -1) { return(null); } // Bug with MOTHER 3: for the second Mole Cricket (index 0x3D), // it uses tiles that are out of bounds in the tile data! // So let's resize the tile buffer to 32KB (max addressable size) Array.Resize(ref gfxData, 0x8000); // Get pal stuff var palette = GetPals(index); // Get OAM stuff int oamPointer = GetPointer(index + 0x2A4); var oam = new OamSprite[2][]; for (int i = 0; i < 2; i++) { // Get the front/back sprite pointer int subPointer = Rom.ReadUShort(oamPointer + 8 + (i << 1)) + oamPointer; // Get the number of sub-sprites ushort numSubSprites = Rom.ReadUShort(subPointer + 2); oam[i] = new OamSprite[numSubSprites]; // Get the OAM data for (int j = 0; j < numSubSprites; j++) { oam[i][j] = Rom.ReadOam(subPointer + 4 + (j << 3)); // Filter out the palette -- each enemy only has one palette, regardless of what the OAM entry says // This is only an issue with enemy #0 anyway oam[i][j].Palette = 0; } // Render the sprites Bitmap bmp = GfxProvider.RenderSprites(oam[i], gfxData, palette); ret[i] = bmp; } return(ret); }
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { var response = context.HttpContext.Response; if (!(context.Object is EamuseXrpcData data)) { throw new ArgumentNullException("Input EamuseXrpcData is null"); } (byte[] rawData, string compAlgo) = await Task.Run(() => { byte[] resData; if (data.Encoding != null) { resData = new KBinXML(data.Document, data.Encoding).Bytes; } else { resData = new KBinXML(data.Document).Bytes; } string algo = "none"; byte[] compressed = LZ77.Compress(resData, 32); if (compressed.Length < resData.Length) { resData = compressed; algo = "lz77"; } compressed = null; if (data.EamuseInfo != null) { RC4.ApplyEAmuseInfo(data.EamuseInfo, resData); } return(resData, algo); }); if (data.EamuseInfo != null) { response.Headers.Add("X-Eamuse-Info", data.EamuseInfo); } response.Headers.Add("X-Compress", compAlgo); response.ContentType = "application/octet-stream"; response.ContentLength = rawData.Length; await response.Body.WriteAsync(rawData, 0, rawData.Length); }
void Core_InsertLargeMap(string filepath) { try { Palette palette = Core.FindPaletteFile(filepath); CurrentLargeMap = new WorldMap_FE8_Large(filepath, palette); } catch (Exception ex) { Program.ShowError("Could not insert the large world map image.", ex); return; } byte[] data_palette = Palette.Merge(CurrentLargeMap.Palettes).ToBytes(false); byte[] data_tileset = CurrentLargeMap.Graphics.ToBytes(false); byte[] data_tsa = LZ77.Compress(CurrentLargeMap.GetPaletteMap()); Core.SuspendUpdate(); bool cancel = Prompt.ShowRepointDialog(this, "Repoint Large World Map", "The different parts of this image may need to be repointed upon insertion.", CurrentEntry("Large"), new Tuple <string, Pointer, int>[] { Tuple.Create("Palette", Core.GetPointer("Large World Map Palette"), data_palette.Length), Tuple.Create("Tileset", Core.GetPointer("Large World Map Tileset"), data_tileset.Length), Tuple.Create("TSA", Core.GetPointer("Large World Map TSA"), data_tsa.Length) }); if (cancel) { return; } Core.WriteData(this, Core.GetPointer("Large World Map Palette"), data_palette, CurrentEntry("Large") + "Palette changed"); Core.WriteData(this, Core.GetPointer("Large World Map Tileset"), data_tileset, CurrentEntry("Large") + "Graphics changed"); Core.WriteData(this, Core.GetPointer("Large World Map TSA"), data_tsa, CurrentEntry("Large") + "TSA changed"); Core.ResumeUpdate(); Core.PerformUpdate(); }
private void WriteData_Click(object sender, EventArgs e) { Pointer address = Write_AddressBox.Value; byte[] data = (Write_LZ77CheckBox.Checked) ? LZ77.Compress(Write_HexBox.Value) : Write_HexBox.Value; if (address == 0) { return; } Accessed.Add(Tuple.Create(true, address, data)); Core.WriteData(this, address, data); }
public void Core_Write() { if (Current[Entry_NumBox.Value].IsAffineSprite()) { while (Affine_Index_NumBox.Value >= Current.Affines.Count) { Current.Affines.Add(new OAM_Affine()); } } Core.SuspendUpdate(); try { byte[] data; if (Compressed < 0) { data = Current.ToBytes(); } else // its in a compressed OAM data block { data = Core.ReadData(Address, 0); byte[] oam = Current.ToBytes(); Array.Copy(oam, 0, data, Compressed, oam.Length); data = LZ77.Compress(data); } Pointer address = Core.FindData(Address.ToBytes(), 4); bool cancel = Prompt.ShowRepointDialog(this, "Repoint OAM Data", "The OAM data to insert might need to be repointed.", Entry, new Tuple <string, Pointer, int>[] { Tuple.Create("OAM Data", Address, data.Length) }, new Pointer[] { address }); if (cancel) { return; } Address = Core.ReadPointer(address); Core.WriteData(this, Address, data, Entry + "OAM changed"); } catch (Exception ex) { Program.ShowError("Could not insert the OAM data.", ex); } Core.ResumeUpdate(); Core.PerformUpdate(); }
public unsafe static int Main(string[] args) { if (args.Length != 3) { Console.Error.WriteLine(USAGE); return(1); } if (!new[] { "banner", "icon", "sound" }.Contains(args[1])) { Console.Error.WriteLine(USAGE); return(1); } string parent_archive = Path.GetTempFileName(); try { using (var fs1 = new FileStream(args[0], FileMode.Open, FileAccess.Read)) using (var fs2 = new FileStream(parent_archive, FileMode.Create, FileAccess.Write)) { fs1.Position = 0x640; fs1.CopyTo(fs2); } using (var parent_node = NodeFactory.FromFile(null, parent_archive)) { var child_node = parent_node.FindChild($"meta/{args[1]}.bin", false); CompressionHeader *header = (CompressionHeader *)(child_node.WorkingSource.Address + 0x24); byte[] buffer = new byte[checked ((int)header->ExpandedSize)]; fixed(byte *ptr = buffer) { LZ77.Expand(header, ptr, buffer.Length); } File.WriteAllBytes(args[2], buffer); } return(0); } finally { if (File.Exists(parent_archive)) { File.Delete(parent_archive); } } }
public Byte[] ToBytes() { byte[] result = new byte[2 + WidthTiles * HeightTiles * 2]; result[0] = WidthTiles; result[1] = HeightTiles; int x = 0; int y = 0; for (int i = 2; i < result.Length; i += 2) { result[i] = (byte)((Layout[x, y] << 2) & 0xFF); result[i + 1] = (byte)(Layout[x, y] >> 6); x++; if (x % WidthTiles == 0) { x = 0; y++; } } return(LZ77.Compress(result)); }
public static Tuple <uint, uint> Compress(Stream inStream, Stream outStream) { var crc = Crc32.InitCrc(); var count = 0u; var bitOut = new BitStream.BitWriter(outStream); var lookupPair = Huffman.HuffmanTree.StaticTree.GetLookupTable(287); var codeTable = lookupPair.Item1; var lengthTable = lookupPair.Item2; while (true) { var buffer = new byte[(1 << 16) - 1]; var size = 0; int delta; while ((delta = inStream.Read(buffer, size, (1 << 16) - 1 - size)) > 0) { size += delta; } if (size == 0) { break; } count += (uint)size; // TODO is it guarantees to be correct after overflow (modulo 1 << 32)? for (var i = 0; i < size; i++) { Crc32.NextCrc(ref crc, buffer[i]); } var lzCompressed = LZ77.Compress(buffer, size); bitOut.WriteBits(2, 3); for (var i = 0; i < size; i++) { bitOut.WriteBits(codeTable[lzCompressed[i]], lengthTable[lzCompressed[i]]); } bitOut.WriteBits(codeTable[256], lengthTable[256]); } bitOut.WriteBits(3, 3); bitOut.WriteBits(codeTable[256], lengthTable[256]); bitOut.Flush(); Crc32.FinishCrc(ref crc); return(new Tuple <uint, uint>(crc, count)); }
void Core_WriteSmallMap(string path) { try { CurrentSmallMap = new WorldMap_FE6_Small(path); } catch (Exception ex) { Program.ShowError("Could not insert the image.", ex); return; } byte[] data_palette = CurrentSmallMap.Colors.ToBytes(true); byte[] data_tileset = LZ77.Compress(CurrentSmallMap.ToBytes()); Core.SuspendUpdate(); bool cancel = Prompt.ShowRepointDialog(this, "Repoint Small World Map", "The different parts of this image may need to be repointed upon insertion.", CurrentEntry(true), new Tuple <string, Pointer, int>[] { Tuple.Create("Palette", Core.GetPointer("Small World Map Palette"), data_palette.Length), Tuple.Create("Tileset", Core.GetPointer("Small World Map Tileset"), data_tileset.Length) }); if (cancel) { return; } Core.WriteData(this, Core.GetPointer("Small World Map Palette"), data_palette, CurrentEntry(true) + "Palette changed"); Core.WriteData(this, Core.GetPointer("Small World Map Tileset"), data_tileset, CurrentEntry(true) + "Tileset changed"); Core.ResumeUpdate(); Core.PerformUpdate(); }
void Core_WriteLargeMap(string path) { try { CurrentLargeMap = new WorldMap_FE6_Large(new Bitmap(path)); } catch (Exception ex) { Program.ShowError("Could not insert the image.", ex); return; } Core.SuspendUpdate(); Core.WriteData(this, LargeMap_PalettePointerBox.Value, CurrentLargeMap.Graphics[0].Colors.ToBytes(true), CurrentEntry(true) + "Palette changed"); Core.WriteData(this, LargeMap_TL_GraphicsPointerBox.Value, LZ77.Compress(CurrentLargeMap.Graphics[0].ToBytes()), CurrentEntry(true) + "Graphics (TL) changed"); Core.WriteData(this, LargeMap_TR_GraphicsPointerBox.Value, LZ77.Compress(CurrentLargeMap.Graphics[1].ToBytes()), CurrentEntry(true) + "Graphics (TR) changed"); Core.WriteData(this, LargeMap_BL_GraphicsPointerBox.Value, LZ77.Compress(CurrentLargeMap.Graphics[2].ToBytes()), CurrentEntry(true) + "Graphics (BL) changed"); Core.WriteData(this, LargeMap_BR_GraphicsPointerBox.Value, LZ77.Compress(CurrentLargeMap.Graphics[3].ToBytes()), CurrentEntry(true) + "Graphics (BR) changed"); Core.ResumeUpdate(); Core.PerformUpdate(); }
public static ArrEntry[] GetArr(int index) { int[] entry = GetEntry(index); byte[] bytes; int res = LZ77.Decompress(Rom, entry[0] + 12, out bytes); if (res == -1) { return(null); } if (bytes.Length != 2048) { return(null); } ArrEntry[] ret = new ArrEntry[1024]; for (int i = 0; i < 1024; i++) { ret[i] = bytes.ReadArrEntry(i << 1); } return(ret); }
public static void Expand(CompressionHeader *header, VoidPtr dstAddr, int dstLen) { switch (header->Algorithm) { case CompressionType.LZ77: case CompressionType.ExtendedLZ77: { LZ77.Expand(header, dstAddr, dstLen); break; } case CompressionType.RunLength: { RunLength.Expand(header, dstAddr, dstLen); break; } //case CompressionType.Huffman: { Huffman.Expand(header, dstAddr, dstLen); break; } //case CompressionType.Differential: { Differential.Expand(header, dstAddr, dstLen); break; } default: throw new InvalidCompressionException("Unknown compression type."); } }
static ClanMusicInfo() { Instance = Task.Run(() => { foreach (string name in Assembly.GetExecutingAssembly().GetManifestResourceNames()) { if (name.EndsWith("music_info_l44_8.kbin", StringComparison.InvariantCultureIgnoreCase)) { using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) using (MemoryStream ms = new MemoryStream()) { stream.CopyTo(ms); return(new ClanMusicInfo( new KBinXML( LZ77.Decompress(ms.ToArray()) ).Document )); } } } return(null); }); }
private void Button_Click_2(object sender, RoutedEventArgs e) { List <ImageWrapper> images = new List <ImageWrapper>(); int i = 0; for (int offset = 0; offset < (file.Length - 1); offset++) { if (file[offset] == 'L' && file[offset + 1] == 'e') { int size = Utils.GetIntAtPosition(file, offset + 2); if (size > 0 && size < 0x8000) { //ArrayPtr arrayPtr = new ArrayPtr(file, offset); byte[] data = Malias2.Decompress(file, offset); ImageWrapper result = new ImageWrapper(i, offset, data, "Malias2"); images.Add(result); i++; } } else if (file[offset] == 0x10) { int size = file[offset + 1] | file[offset + 2] << 8 | file[offset + 3] << 16; if (size > 0 && size < 0x8000 && size % 0x20 == 0) { byte[] data = LZ77.Decompress(file, offset); if (data != null) { ImageWrapper result = new ImageWrapper(i, offset, data, "LZ77"); images.Add(result); i++; } } } } imagesList.ItemsSource = images; }
public static unsafe void Compact(CompressionType type, VoidPtr srcAddr, int srcLen, Stream outStream, ResourceNode r) { switch (type) { case CompressionType.LZ77: { LZ77.Compact(srcAddr, srcLen, outStream, r, false); break; } case CompressionType.ExtendedLZ77: { LZ77.Compact(srcAddr, srcLen, outStream, r, true); break; } case CompressionType.RunLength: { RunLength.Compact(srcAddr, srcLen, outStream, r); break; } case CompressionType.RunLengthYAZ0: { RunLength.CompactYAZ0(srcAddr, srcLen, outStream, r); break; } case CompressionType.RunLengthYAY0: { RunLength.CompactYAY0(srcAddr, srcLen, outStream, r); break; } } }
private void recompressToolStripMenuItem_Click(object sender, EventArgs e) { // Set bit depth correctly var bitDepth = ImageCompression.ColorModel.RGB.ColorDepth.TwentyFour; if (this.compressionFlags.FlagIsSet((byte)CompressionFlags.EightBit)) { bitDepth = ImageCompression.ColorModel.RGB.ColorDepth.Eight; } else if (this.compressionFlags.FlagIsSet((byte)CompressionFlags.FifteenBit)) { bitDepth = ImageCompression.ColorModel.RGB.ColorDepth.Fifteen; } else if (this.compressionFlags.FlagIsSet((byte)CompressionFlags.EighteenBit)) { bitDepth = ImageCompression.ColorModel.RGB.ColorDepth.Eighteen; } else if (this.compressionFlags.FlagIsSet((byte)CompressionFlags.TwentyFourBit)) { bitDepth = ImageCompression.ColorModel.RGB.ColorDepth.TwentyFour; } // Re-Load the modified data this.modifiedData.data = this.originalImage.GetPixelMatrix(bitDepth); ImageCompression.Interfaces.IEncodable[] data = this.modifiedData.data.Flatten(); // If huffman is enabled if (this.compressionFlags.FlagIsSet((byte)CompressionFlags.Huffman)) { var huffmanData = Huffman <ImageCompression.Interfaces.IEncodable> .Encode(data); } // If run length is enabled if (this.compressionFlags.FlagIsSet((byte)CompressionFlags.RunLength)) { data = RunLength.Encode <ImageCompression.Interfaces.IEncodable>(data); } // If LZ77 is enabled if (this.compressionFlags.FlagIsSet((byte)CompressionFlags.LZ77)) { var encodedData = LZ77.Encode(data, 255, 255); data = encodedData.ToArray <ImageCompression.Interfaces.IEncodable>(); } // Pack the bytes this.compressedForm = ImageCompression.Helpers.BytePacker.Pack(data.ToList()); // Update compressed size this.compressedSizeLabelBytes.Text = ((this.compressedForm.Length + this.compressionFlags) / 1024) + " KB"; // Update compression radio this.compressionRatio.Text = this.CalculateCompressionRatio( int.Parse(this.originalSizeLabelBytes.Text.Substring(0, this.originalSizeLabelBytes.Text.Length - 3)), int.Parse(this.compressedSizeLabelBytes.Text.Substring(0, this.originalSizeLabelBytes.Text.Length - 3))); // Update MSE this.meanSquaredError.Text = this.originalImage.MeanSquaredError(this.modifiedData.data).ToString(); // Update the preview tab with the preview data if (this.compressedPictureBox.Image != null) { this.compressedPictureBox.Image.Dispose(); this.compressedImage.Dispose(); } // Save the modified data as a temporary image var modifiedBitmap = this.modifiedData.GetBitmap(); modifiedBitmap.Save(@"D:\GitHub\SE3IA11-Image-Analysis\ImageCompression\TestImage\Output\temp.bmp", System.Drawing.Imaging.ImageFormat.Bmp); this.compressedImage = new StandardImage(new Bitmap(@"D:\GitHub\SE3IA11-Image-Analysis\ImageCompression\TestImage\Output\temp.bmp")); this.compressedPictureBox.Image = this.compressedImage.GetBitmap(); }
public static void Compress(object sender, EventArgs e) { var tsi = sender as ToolStripMenuItem; if (!Shared.PrepareFiles("Open a decompressed " + tsi?.Tag + "file...", "Save your compressed file...", ".decomp", out var openFile, out var saveFile, true)) { return; } try { using (openFile) using (var outFs = new BinaryWriterX(saveFile)) switch (tsi?.Tag) { case Compression.L5LZ10: outFs.Write(Level5.Compress(openFile, Level5.Method.LZ10)); break; case Compression.L5Huff4: outFs.Write(Level5.Compress(openFile, Level5.Method.Huffman4Bit)); break; case Compression.L5Huff8: outFs.Write(Level5.Compress(openFile, Level5.Method.Huffman8Bit)); break; case Compression.L5RLE: outFs.Write(Level5.Compress(openFile, Level5.Method.RLE)); break; case Compression.NLZ10: outFs.Write(Nintendo.Compress(openFile, Nintendo.Method.LZ10)); break; case Compression.NLZ11: outFs.Write(Nintendo.Compress(openFile, Nintendo.Method.LZ11)); break; case Compression.NLZ60: outFs.Write(Nintendo.Compress(openFile, Nintendo.Method.LZ60)); break; case Compression.NHuff4: outFs.Write(Nintendo.Compress(openFile, Nintendo.Method.Huff4)); break; case Compression.NHuff8: outFs.Write(Nintendo.Compress(openFile, Nintendo.Method.Huff8)); break; case Compression.NRLE: outFs.Write(Nintendo.Compress(openFile, Nintendo.Method.RLE)); break; case Compression.LZ77: outFs.Write(LZ77.Compress(openFile)); break; case Compression.RevLZ77: outFs.Write(RevLZ77.Compress(openFile)); break; case Compression.LZOvl: outFs.Write(LZOvl.Compress(openFile)); break; case Compression.LZ4: outFs.Write(Kontract.Compression.LZ4.Compress(openFile)); break; case Compression.MIO0LE: outFs.Write(MIO0.Compress(openFile, ByteOrder.LittleEndian)); break; case Compression.MIO0BE: outFs.Write(MIO0.Compress(openFile, ByteOrder.BigEndian)); break; case Compression.Yay0LE: outFs.Write(Yay0.Compress(openFile, ByteOrder.LittleEndian)); break; case Compression.Yay0BE: outFs.Write(Yay0.Compress(openFile, ByteOrder.BigEndian)); break; case Compression.Yaz0LE: outFs.Write(Yaz0.Compress(openFile, ByteOrder.LittleEndian)); break; case Compression.Yaz0BE: outFs.Write(Yaz0.Compress(openFile, ByteOrder.BigEndian)); break; case Compression.GZip: outFs.Write(GZip.Compress(openFile)); break; case Compression.ZLib: outFs.Write(ZLib.Compress(openFile)); break; case Compression.PSVSpikeChun: outFs.Write(PSVSpikeChun.Compress(openFile)); break; } } catch (Exception ex) { MessageBox.Show(ex.ToString(), tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show($"Successfully compressed {Path.GetFileName(openFile.Name)}.", tsi.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); }
public static void Decompress(object sender, EventArgs e) { var tsi = sender as ToolStripMenuItem; if (!Shared.PrepareFiles("Open a " + tsi?.Tag + " compressed file...", "Save your decompressed file...", ".decomp", out var openFile, out var 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.Nintendo: outFs.Write(Nintendo.Decompress(openFile)); break; case Compression.LZ77: outFs.Write(LZ77.Decompress(openFile)); break; case Compression.RevLZ77: outFs.Write(RevLZ77.Decompress(openFile)); break; case Compression.LZOvl: outFs.Write(LZOvl.Decompress(openFile)); break; case Compression.LZ4: outFs.Write(Kontract.Compression.LZ4.Decompress(openFile)); break; case Compression.MIO0LE: outFs.Write(MIO0.Decompress(openFile, ByteOrder.LittleEndian)); break; case Compression.MIO0BE: outFs.Write(MIO0.Decompress(openFile, ByteOrder.BigEndian)); break; case Compression.Yay0LE: outFs.Write(Yay0.Decompress(openFile, ByteOrder.LittleEndian)); break; case Compression.Yay0BE: outFs.Write(Yay0.Decompress(openFile, ByteOrder.BigEndian)); break; case Compression.Yaz0LE: outFs.Write(Yaz0.Decompress(openFile, ByteOrder.LittleEndian)); break; case Compression.Yaz0BE: outFs.Write(Yaz0.Decompress(openFile, ByteOrder.BigEndian)); break; case Compression.LZECD: outFs.Write(LZECD.Decompress(openFile)); break; case Compression.LZ10VLE: outFs.Write(LZSSVLE.Decompress(openFile)); break; case Compression.GZip: outFs.Write(GZip.Decompress(openFile)); break; case Compression.ZLib: outFs.Write(ZLib.Decompress(openFile)); break; case Compression.PSVSpikeChun: outFs.Write(PSVSpikeChun.Decompress(openFile)); break; } } catch (Exception ex) { MessageBox.Show(ex.ToString(), tsi?.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show($"Successfully decompressed {Path.GetFileName(openFile.Name)}.", tsi.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); }
/// <summary> /// Process data in an input file that contains a layout. /// </summary> /// <param name="filename"></param> bool ProcessData(string filename, byte[] inData) { EndianBinaryReader reader = null; // now we need to decide what they just opened if (inData == null && filename != "") { reader = new EndianBinaryReader(File.Open(filename, FileMode.Open), Encoding.GetEncoding(932)); } else { reader = new EndianBinaryReader(inData); } string magic = ""; // we have a Yaz0 compressed file if (reader.ReadStringFrom(0, 4) == "Yaz0") { // we have to close our reader so we can properly read this file as a Yaz0 stream reader.Close(); MemoryStream ms = null; if (inData == null) { ms = new Yaz0(File.Open(filename, FileMode.Open)); } else { ms = new Yaz0(new MemoryStream(inData)); } reader = new EndianBinaryReader(ms); magic = reader.ReadStringFrom(0, 4); } // we have a LZ compressed file else if (reader.ReadByteFrom(0) == 0x11) { LZ77 lzFile = new LZ77(ref reader); byte[] lzData = lzFile.getData(); // close our current reader to open a new one with our input data reader.Close(); reader = new EndianBinaryReader(lzData); magic = reader.ReadStringFrom(0, 4); } // no compression else { // it is not yaz0 compressed, so we see the magic magic = reader.ReadStringFrom(0, 4); } // now we have to check our magic to see what kind of file it is switch (magic) { case "darc": mArchive = new DARC(ref reader); break; case "NARC": mArchive = new NARC(ref reader); break; case "SARC": mArchive = new SARC(ref reader); break; case "RARC": reader.SetEndianess(Endianess.Big); mArchive = new RARC(ref reader); break; case "U?8-": reader.SetEndianess(Endianess.Big); mArchive = new U8(ref reader); break; default: MessageBox.Show("Error. Unsupported format with magic: " + magic); break; } string layoutType = ""; // some files have their string table nullified, which makes the names obfuscated // I've only seen this in SARCs from MK7, but there's probably more if (mArchive != null) { if (mArchive.isStringTableObfuscated()) { MessageBox.Show("This file has obfuscated file names. The editor attempted to find layout files, but cannot supply names."); } } reader.Close(); if (mArchive == null) { MessageBox.Show("Format not supported."); return(false); } // the only familiar format with archives in archives is SARC and RARC if (mArchive.getType() == ArchiveType.SARC || mArchive.getType() == ArchiveType.RARC) { List <string> names = mArchive.getArchiveFileNames(); if (names.Count != 0) { DialogResult res = MessageBox.Show("This archive has another archive inside of it.\nDo you wish to choose one of the found archives to select a layout?", "Internal Archive", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { LayoutChooser archiveChooser = new LayoutChooser(); archiveChooser.insertEntries(names); archiveChooser.ShowDialog(); // if this worked, we dont need to do anything bool result = ProcessData(archiveChooser.getSelectedFile(), mArchive.getDataByName(archiveChooser.getSelectedFile())); if (result) { return(true); } else { MessageBox.Show("Failed to get the internal file."); return(false); } } } } // get all of our needed files mLayoutFiles = mArchive.getLayoutFiles(); mLayoutAnimFiles = mArchive.getLayoutAnimations(); mLayoutImages = mArchive.getLayoutImages(); mLayoutControls = mArchive.getLayoutControls(); if (mLayoutFiles.Count == 0) { MessageBox.Show("This file contains no layouts."); return(false); } LayoutChooser layoutChooser = new LayoutChooser(); layoutChooser.insertEntries(new List <string>(mLayoutFiles.Keys)); layoutChooser.ShowDialog(); string selectedFile = layoutChooser.getSelectedFile(); if (selectedFile == null) { return(false); } string[] sections = selectedFile.Split('/'); mMainRoot = ""; // remove "lyt" part and the file name // this will be our main root of the entire opened file for (int i = 0; i < sections.Length - 2; i++) { mMainRoot += sections[i] + "/"; } if (layoutType == "") { layoutType = Path.GetExtension(selectedFile); } // now we have to init a layout reader EndianBinaryReader layoutReader = null; byte[] data; switch (layoutType) { case ".brlyt": data = mLayoutFiles[selectedFile]; layoutReader = new EndianBinaryReader(data); mMainLayout = new BRLYT(ref layoutReader); layoutReader.Close(); break; case ".bclyt": data = mLayoutFiles[selectedFile]; layoutReader = new EndianBinaryReader(data); mMainLayout = new BCLYT(ref layoutReader); break; case ".bflyt": data = mLayoutFiles[selectedFile]; layoutReader = new EndianBinaryReader(data); mMainLayout = new BFLYT(ref layoutReader); break; case ".blo": data = mLayoutFiles[selectedFile]; layoutReader = new EndianBinaryReader(data); if (layoutReader.ReadStringFrom(4, 4) == "blo1") { mMainLayout = new BLO1(ref layoutReader); } else { mMainLayout = new BLO2(ref layoutReader); } break; default: MessageBox.Show("This format is not supported yet."); break; } layoutReader.Close(); if (mMainLayout == null) { return(false); } // set our propertygrid with our LYT object mainPropertyGrid.SelectedObject = mMainLayout.getLayoutParams(); if (mMainLayout.getRootPanel() == null) { MessageBox.Show("Error, the root pane in this layout is not specified."); return(false); } LayoutBase pane = null; LayoutBase group = null; // now we have to grab our root panel, which is different on each console // so we have to specifically get the one we want // the same applies to our root group pane = mMainLayout.getRootPanel(); // this should be RootPane TreeNode n1 = new TreeNode { Tag = pane, Name = pane.mName, Text = pane.mName, }; panelList.Nodes.Add(n1); fillNodes(pane.getChildren()); // now for our groups group = mMainLayout.getRootGroup(); if (group != null) { TreeNode n1_1 = new TreeNode { Tag = group, Name = group.mName, Text = group.mName, }; panelList.Nodes.Add(n1_1); fillNodes(group.getChildren()); } // now for textures and fonts // but it is possible for either one to not exist if (mMainLayout.containsTextures()) { foreach (string str in mMainLayout.getTextureNames()) { texturesList.Items.Add(str); } } if (mMainLayout.containsFonts()) { foreach (string str in mMainLayout.getFontNames()) { fontsList.Items.Add(str); } } // and our materials if (mMainLayout.containsMaterials()) { foreach (string str in mMainLayout.getMaterialNames()) { materialList.Items.Add(str); } } // this draws the border of the layout mMainLayout.draw(); layoutViewer.Refresh(); return(true); }
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.RevLZ77: outFs.Write(RevLZ77.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); }
public static string DecompressStr(byte[] data) { LZ77 lz = new LZ77(); return lz.Decompress(data); }
public static byte[] CompressStr(string data) { LZ77 lz = new LZ77(); return lz.Compress(Encoding.Default.GetBytes(data), 50); }