Beispiel #1
0
        public XMBFile LoadXMB(string barPath, string fileName)
        {
            var extFile = Path.Combine(Path.GetDirectoryName(barPath), fileName);

            try {
                if (File.Exists(extFile))
                {
                    using (var file = File.OpenRead(extFile)) {
                        return(XMBFile.Load(file));
                    }
                }
            } catch { }
            {
                var barFile = GetFile(barPath);
                if (barFile == null)
                {
                    return(null);
                }
                var file = barFile.GetFileStream(fileName);
                if (file == null)
                {
                    return(null);
                }
                return(XMBFile.Load(file));
            }
        }
 public void OpenModelXmb(string pathXMB)
 {
     if (string.IsNullOrEmpty(pathXMB))
     {
         return;
     }
     XMB = new XMBFile(pathXMB);
 }
Beispiel #3
0
        static void convertXMB(string path)
        {
            XMBFile xmb         = new XMBFile(path);
            string  newfilename = String.Format("{0}", Path.ChangeExtension(path, "xml"));

            Console.WriteLine(newfilename);
            xmb.SaveAsXML(newfilename);
        }
Beispiel #4
0
        public string ConvertFileTo(FileViewModel file, string path)
        {
            try {
                switch (file.Extension.ToLower())
                {
                case ".xmb": {
                    var xdoc = XMBFile.Load(GetFileStream(file.Entry)).GetAsXDocument();
                    xdoc.Save(path);
                } break;

                case ".btx":
                case ".ddt": {
                    RTS3Image srcImg = null;
                    if (file.Extension.ToLower() == ".ddt")
                    {
                        srcImg = DDTImage.Load(GetFileStream(file.Entry));
                    }
                    else if (file.Extension.ToLower() == ".btx")
                    {
                        srcImg = BTXImage.Load(GetFileStream(file.Entry));
                    }
                    byte[] pixData = srcImg.Get32BitUncompressed();
                    if (pixData == null)
                    {
                        return(null);
                    }
                    var           bmp     = BitmapSource.Create(srcImg.Width, srcImg.Height, 96, 96, PixelFormats.Bgra32, null, pixData, srcImg.Width * 4);
                    BitmapEncoder encoder = null;
                    if (Path.GetExtension(path).ToLower() == ".png")
                    {
                        encoder = new PngBitmapEncoder();
                    }
                    else if (Path.GetExtension(path).ToLower() == ".jpg")
                    {
                        encoder = new JpegBitmapEncoder();
                    }
                    else if (Path.GetExtension(path).ToLower() == ".gif")
                    {
                        encoder = new GifBitmapEncoder();
                    }
                    else if (Path.GetExtension(path).ToLower() == ".bmp")
                    {
                        encoder = new BmpBitmapEncoder();
                    }
                    encoder.Frames.Add(BitmapFrame.Create(bmp));
                    using (var stream = File.Create(path)) {
                        encoder.Save(stream);
                    }
                } break;

                default: return(null);
                }
            } catch {
                return(null);
            }
            return(path);
        }
Beispiel #5
0
        private void GetXmbDump(XMBFile xmb)
        {
            foreach (XMBEntry entry in xmb.Entries)
            {
                textBox1.Text += entry.deserialize();
            }

            // Deselect the text that was added.
            textBox1.SelectionLength = 0;
            textBox1.Select(0, 0);
        }
Beispiel #6
0
        static XMBFile from_text(string filepath)
        {
            var file = new XMBFile();

            using (var reader = File.OpenText(filepath))
            {
                List <XMBEntry> tmp   = new List <XMBEntry>();
                int             index = 0;
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine().Trim();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }

                    var entry = new XMBEntry();
                    entry.Name        = line.TrimEnd('{');
                    entry.ParentIndex = -1;
                    entry.Index       = index;
                    if (line.EndsWith("{") | reader.ReadLine().EndsWith("{"))
                    {
                        bool endScope = false;
                        while (!endScope)
                        {
                            line = reader.ReadLine().Trim();
                            if (string.IsNullOrEmpty(line) | line.EndsWith("{"))
                            {
                                continue;
                            }

                            if (line.Contains('='))
                            {
                                entry.Expressions.Add(line.Trim());
                            }
                            else if (line.EndsWith("}"))
                            {
                                endScope = true;
                                continue;
                            }
                            else
                            {
                                var child = parse_entry(reader, line, ref index);
                                child.ParentIndex = (short)entry.Index;
                                entry.Children.Add(child);
                            }
                        }
                    }
                    file.Entries.Add(entry);
                }
            }
            return(file);
        }
Beispiel #7
0
 public ModelContainer()
 {
     ImageKey         = "folder";
     SelectedImageKey = "folder";
     nud     = new NUD();
     nut     = new NUT();
     mta     = new MTA();
     MOI     = new MOI();
     jtb     = new JTB();
     XMB     = new XMBFile();
     Checked = true;
     Refresh();
 }
Beispiel #8
0
        public byte[] UnConvertData(FileViewModel file, byte[] data)
        {
            switch (file.Extension.ToLower())
            {
            case ".xmb": {
                var xdoc = XDocument.Load(new MemoryStream(data));
                var xmb  = XMBFile.FromDocument(xdoc);
                using (var stream = new MemoryStream()) {
                    xmb.Save(stream, true);
                    return(stream.GetBuffer().Take((int)stream.Length).ToArray());
                }
            }

            default: return(null);
            }
        }
Beispiel #9
0
 public static void CreateLightMapsFromXMB(XMBFile xmb)
 {
     if (xmb != null)
     {
         foreach (XMBEntry entry in xmb.Entries)
         {
             if (entry.Children.Count > 0)
             {
                 foreach (XMBEntry lightMapEntry in entry.Children)
                 {
                     LightMap newLightMap = CreateLightMapFromXMBEntry(lightMapEntry);
                     lightMaps.Add(newLightMap);
                 }
             }
         }
     }
 }
Beispiel #10
0
 public static void CreateAreaLightsFromXMB(XMBFile xmb)
 {
     if (xmb != null)
     {
         foreach (XMBEntry entry in xmb.Entries)
         {
             if (entry.Children.Count > 0)
             {
                 foreach (XMBEntry lightEntry in entry.Children)
                 {
                     AreaLight newAreaLight = CreateAreaLightFromXMBEntry(lightEntry);
                     areaLights.Add(newAreaLight);
                 }
             }
         }
     }
 }
Beispiel #11
0
        static void Main(string[] args)
        {
            Console.WriteLine($"\n> XMBD v0.5 - Smash 4 xmb file dumper.\n" +
                              "> Licensed under the MIT License\n" +
                              "> Copyright(c) 2017 Sammi Husky\n");

            string output = "output.xms";
            bool   decomp = false;
            bool   recomp = false;
            string target = "";

            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];
                if (arg.Equals("-o", StringComparison.InvariantCultureIgnoreCase))
                {
                    output = args[++i];
                }
                else if (arg.EndsWith(".xms", StringComparison.InvariantCultureIgnoreCase))
                {
                    recomp = true;
                    target = arg;
                    output = Path.GetFileNameWithoutExtension(arg) + ".xmb";
                }
                else if (arg.EndsWith(".xmb", StringComparison.InvariantCultureIgnoreCase))
                {
                    decomp = true;
                    target = arg;
                    output = Path.GetFileNameWithoutExtension(arg) + ".xms";
                }
            }
            if (decomp && !recomp)
            {
                Console.WriteLine($">\t Decompiling {Path.GetFileName(target)}.. -> \"{output}\"");
                XMBFile f = new XMBFile(target);
                f.Deserialize(output);
            }
            else if (recomp)
            {
                Console.WriteLine($">\t Compiling {Path.GetFileName(target)}.. -> \"{output}\"");
                XMBFile f = from_text(target);
                //f.Export(output);
            }
        }
        public async Task readFile(BarEntry file)
        {
            // Firstly, is the file parameter null?

            PreviewDdt   = null;
            Preview      = null;
            PreviewImage = null;
            if (file == null)
            {
                return;
            }

            if (file.Extension == ".WAV" /* || file.Extension == ".MP3"*/)
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                //File.WriteAllBytes(file.fileNameWithoutPath, data);
                audio = new MemoryStream(data);
                if (file.isCompressed)
                {
                    //   AudioFileReader audioFileReader = new AudioFileReader();
                    //  DirectSoundOut directSoundOut = new DirectSoundOut();

                    // audioFileReader.
                    audio = new MemoryStream(data);
                }
                else
                {
                    audio = new MemoryStream(data);
                }

                return;
            }
            if (file.Extension == ".DDT")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);


                if (Alz4Utils.IsAlz4File(data))
                {
                    data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                }
                else
                {
                    if (L33TZipUtils.IsL33TZipFile(data))
                    {
                        data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                    }
                }

                PreviewDdt = new DdtFile(data, true);
                return;
            }
            if (file.Extension == ".BMP" || file.Extension == ".PNG" || file.Extension == ".CUR" || file.Extension == ".JPG")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                if (Alz4Utils.IsAlz4File(data))
                {
                    data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                }
                else
                {
                    if (L33TZipUtils.IsL33TZipFile(data))
                    {
                        data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                    }
                }
                var bitmap = new BitmapImage();
                using (var stream = new MemoryStream(data))
                {
                    bitmap.BeginInit();
                    bitmap.StreamSource = stream;
                    bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                    bitmap.Freeze();
                }

                PreviewImage = bitmap;
                return;
            }

            if (file.Extension == ".XMB")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                if (Alz4Utils.IsAlz4File(data))
                {
                    data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                }
                else
                {
                    if (L33TZipUtils.IsL33TZipFile(data))
                    {
                        data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                    }
                }

                //File.WriteAllBytes(file.fileNameWithoutPath, data);

                Preview = new Document();
                Preview.SyntaxHighlighting = "XML";
                Preview.Text = await XMBFile.XmbToXmlAsync(data);

                NotifyPropertyChanged("Preview");
                return;
            }
            if (file.Extension == ".XAML" || file.Extension == ".XML" || file.Extension == ".SHP" || file.Extension == ".LGT" || file.Extension == ".XS" || file.Extension == ".TXT" || file.Extension == ".CFG" || file.Extension == ".PY")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                if (Alz4Utils.IsAlz4File(data))
                {
                    data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                }
                else
                {
                    if (L33TZipUtils.IsL33TZipFile(data))
                    {
                        data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                    }
                }
                Preview      = new Document();
                Preview.Text = System.Text.Encoding.UTF8.GetString(data);
                if (file.Extension == ".XS")
                {
                    Preview.SyntaxHighlighting = "C++";
                }
                else
                {
                    Preview.SyntaxHighlighting = "XML";
                }
                NotifyPropertyChanged("Preview");
                return;
            }

            return;
        }
Beispiel #13
0
        public XmbViewer(XMBFile xmb)
        {
            InitializeComponent();

            GetXmbDump(xmb);
        }
        private async void convertFiles(object sender, RoutedEventArgs e)
        {
            mainMenu.IsEnabled        = false;
            SpinnerConvert.Visibility = Visibility.Visible;
            tbConvert.Text            = "Converting";
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = Settings.Default.lastConvertedPath;
            openFileDialog.Multiselect      = true;

            string operationType = (sender as MenuItem).Tag.ToString();

            //await DdtFileUtils.Ddt2PngAsync(@"D:\Development\Resource Manager\Resource Manager\bin\Release\netcoreapp3.1\Art\ui\alerts\alert_treatyend_bump.ddt");



            if (operationType == "totga")
            {
                openFileDialog.Filter = "Age of Empires 3 ddt files (*.ddt)|*.ddt";
                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await DdtFileUtils.Ddt2TgaAsync(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "topng")
            {
                openFileDialog.Filter = "Age of Empires 3 ddt files (*.ddt)|*.ddt";
                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await DdtFileUtils.Ddt2PngAsync(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxml")
            {
                openFileDialog.Filter = "Age of Empires 3 xmb files (*.xmb)|*.xmb";

                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            var data = await File.ReadAllBytesAsync(file);


                            if (Alz4Utils.IsAlz4File(data))
                            {
                                data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                            }
                            else
                            {
                                if (L33TZipUtils.IsL33TZipFile(data))
                                {
                                    data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                                }
                            }


                            using MemoryStream stream = new MemoryStream(data);
                            XMBFile xmb = await XMBFile.LoadXMBFile(stream);

                            var newName = Path.ChangeExtension(file, "");

                            xmb.file.Save(newName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "jsontoxml")
            {
                openFileDialog.Filter = "JSON files (*.json)|*.json";

                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            var data = await File.ReadAllBytesAsync(file);


                            if (Alz4Utils.IsAlz4File(data))
                            {
                                data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                            }
                            else
                            {
                                if (L33TZipUtils.IsL33TZipFile(data))
                                {
                                    data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                                }
                            }
                            string json = await File.ReadAllTextAsync(file);

                            var xml = JsonConvert.DeserializeXmlNode(json);

                            var newName = Path.ChangeExtension(file, "");



                            xml.Save(newName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "xmbtojson")
            {
                openFileDialog.Filter = "Age of Empires 3 xmb files (*.xmb)|*.xmb";

                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            var data = await File.ReadAllBytesAsync(file);


                            if (Alz4Utils.IsAlz4File(data))
                            {
                                data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                            }
                            else
                            {
                                if (L33TZipUtils.IsL33TZipFile(data))
                                {
                                    data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                                }
                            }


                            using MemoryStream stream = new MemoryStream(data);

                            XMBFile xmb = await XMBFile.LoadXMBFile(stream);

                            string json = JsonConvert.SerializeXmlNode(xmb.file);
                            await File.WriteAllTextAsync(Path.ChangeExtension(file, "json"), json);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "xmltojson")
            {
                openFileDialog.Filter = "Age of Empires 3 xml files (*.*)|*.*";

                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            XmlDocument xml = new XmlDocument();
                            xml.Load(file);
                            string json = JsonConvert.SerializeXmlNode(xml);
                            await File.WriteAllTextAsync(Path.ChangeExtension(file, "json"), json);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "jsontoxmblegacy")
            {
                openFileDialog.Filter = "JSON files (*.json)|*.json";

                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            string json = await File.ReadAllTextAsync(file);

                            var xml = JsonConvert.DeserializeXmlNode(json);
                            await XMBFile.CreateXMBFileL33T(xml, file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "jsontoxmbde")
            {
                openFileDialog.Filter = "JSON files (*.json)|*.json";

                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            string json = await File.ReadAllTextAsync(file);

                            var xml = JsonConvert.DeserializeXmlNode(json);
                            await XMBFile.CreateXMBFileALZ4(xml, file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxmbde")
            {
                openFileDialog.Filter = "Age of Empires 3 xml files (*.*)|*.*";

                if (openFileDialog.ShowDialog() == true)
                {
                    Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                    Settings.Default.Save();
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await XMBFile.CreateXMBFileALZ4(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxmbcc")
            {
                openFileDialog.Filter = "Age of Empires 3 xml files (*.*)|*.*";
                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        Settings.Default.lastConvertedPath = Path.GetDirectoryName(openFileDialog.FileName);
                        Settings.Default.Save();
                        try
                        {
                            await XMBFile.CreateXMBFileL33T(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }



            tbConvert.Text            = "Convert";
            SpinnerConvert.Visibility = Visibility.Collapsed;
            mainMenu.IsEnabled        = true;
        }
        public async Task saveFiles(List <BarEntry> files, string savePath, bool Decompress, CancellationToken token, bool convertDDT, bool convertXMB)
        {
            ResetProgress();
            if (files.Count == 0)
            {
                return;
            }

            using var input = File.OpenRead(barFilePath);

            long filesSize = files.Sum(x => (long)x.FileSize2);

            foreach (var file in files)
            {
                if (token.IsCancellationRequested)
                {
                    while (extractingState == 1)
                    {
                        await Task.Delay(1000);
                    }
                }
                if (token.IsCancellationRequested && extractingState == 2)
                {
                    ResetProgress();
                    return;
                }
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);

                Directory.CreateDirectory(Path.Combine(savePath, Path.GetDirectoryName(file.FileNameWithRoot)));



                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);


                if (file.Extension != ".XMB" && (L33TZipUtils.IsL33TZipFile(data) || Alz4Utils.IsAlz4File(data)) && Decompress)
                {
                    if (Alz4Utils.IsAlz4File(data))
                    {
                        data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                    }
                    else
                    {
                        if (L33TZipUtils.IsL33TZipFile(data))
                        {
                            data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                        }
                    }
                }

                if (file.Extension == ".WAV" || file.Extension == ".MP3")
                {
                    if (file.isCompressed == 2)
                    {
                        data = await soundUtils.DecryptSound(data);
                    }
                }

                await File.WriteAllBytesAsync(Path.Combine(savePath, file.FileNameWithRoot), data);



                if (file.Extension == ".XMB" && convertXMB)
                {
                    if (Alz4Utils.IsAlz4File(data))
                    {
                        data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                    }
                    else
                    {
                        if (L33TZipUtils.IsL33TZipFile(data))
                        {
                            data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                        }
                    }

                    using MemoryStream stream = new MemoryStream(data);
                    XMBFile xmb = await XMBFile.LoadXMBFile(stream);

                    var newName = Path.ChangeExtension(Path.Combine(savePath, file.FileNameWithRoot), "");

                    xmb.file.Save(newName);
                }

                if (file.Extension == ".DDT" && convertDDT)
                {
                    await DdtFileUtils.DdtBytes2PngAsync(data, Path.Combine(savePath, file.FileNameWithRoot));
                }


                CurrentProgress += (double)file.FileSize2 / filesSize;
            }
            ResetProgress();
        }
        private async void convertFiles(object sender, RoutedEventArgs e)
        {
            mainMenu.IsEnabled        = false;
            SpinnerConvert.Visibility = Visibility.Visible;
            tbConvert.Text            = "Converting";
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Multiselect = true;

            string operationType = (sender as MenuItem).Tag.ToString();

            //await DdtFileUtils.Ddt2PngAsync(@"D:\Development\Resource Manager\Resource Manager\bin\Release\netcoreapp3.1\Art\ui\alerts\alert_treatyend_bump.ddt");

            if (operationType == "topng")
            {
                openFileDialog.Filter = "Age of Empires 3 ddt files (*.ddt)|*.ddt";
                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await DdtFileUtils.Ddt2PngAsync(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxml")
            {
                openFileDialog.Filter = "Age of Empires 3 xmb files (*.xmb)|*.xmb";

                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            var data = await File.ReadAllBytesAsync(file);


                            if (Alz4Utils.IsAlz4File(data))
                            {
                                data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                            }
                            else
                            {
                                if (L33TZipUtils.IsL33TZipFile(data))
                                {
                                    data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                                }
                            }


                            using MemoryStream stream = new MemoryStream(data);
                            XMBFile xmb = await XMBFile.LoadXMBFile(stream);

                            var newName = Path.ChangeExtension(file, "");

                            xmb.file.Save(newName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxmbde")
            {
                openFileDialog.Filter = "Age of Empires 3 xml files (*.xml)|*.xml";

                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await XMBFile.CreateXMBFileALZ4(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxmbcc")
            {
                openFileDialog.Filter = "Age of Empires 3 xml files (*.xml)|*.xml";
                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await XMBFile.CreateXMBFileL33T(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }



            tbConvert.Text            = "Convert";
            SpinnerConvert.Visibility = Visibility.Collapsed;
            mainMenu.IsEnabled        = true;
        }
        public async Task saveFiles(List <BarEntry> files, string savePath, bool Decompress, CancellationToken token, bool convertDDTToPNG, bool convertDDTToTGA, bool convertXMB, bool OneFolder, bool SavePNGasBMP, bool AutoJSONConversion, Color OverlayColor)
        {
            ResetProgress();
            if (files.Count == 0)
            {
                return;
            }

            using var input = File.OpenRead(barFilePath);

            long filesSize = files.Sum(x => (long)x.FileSize2);

            foreach (var file in files)
            {
                if (token.IsCancellationRequested)
                {
                    while (extractingState == 1)
                    {
                        await Task.Delay(1000);
                    }
                }
                if (token.IsCancellationRequested && extractingState == 2)
                {
                    ResetProgress();
                    return;
                }
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);


                string ExtractPath = Path.Combine(savePath, file.FileNameWithRoot);
                if (OneFolder)
                {
                    ExtractPath = Path.Combine(savePath, file.fileNameWithoutPath);
                }

                Directory.CreateDirectory(Path.GetDirectoryName(ExtractPath));


                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                // XMB and decompress
                if (file.Extension != ".XMB" && (L33TZipUtils.IsL33TZipFile(data) || Alz4Utils.IsAlz4File(data)) && Decompress)
                {
                    if (Alz4Utils.IsAlz4File(data))
                    {
                        data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                    }
                    else
                    {
                        if (L33TZipUtils.IsL33TZipFile(data))
                        {
                            data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                        }
                    }
                }

                // WAV or MP3
                if (file.Extension == ".WAV" || file.Extension == ".MP3")
                {
                    if (file.isCompressed == 2)
                    {
                        data = await soundUtils.DecryptSound(data);
                    }
                }

                // Save PNG as BMP, skip saving as PNG
                if (file.Extension == ".PNG" && SavePNGasBMP)
                {
                    using var memory = new MemoryStream(data);
                    Bitmap img = new Bitmap(memory);


                    PixelFormat fmt1 = img.PixelFormat;
                    byte        bpp1 = 4;

                    Rectangle  rect    = new Rectangle(Point.Empty, new Size(img.Width, img.Height));
                    BitmapData bmpData = img.LockBits(rect, ImageLockMode.ReadWrite, fmt1);

                    int    size1  = bmpData.Stride * bmpData.Height;
                    byte[] pixels = new byte[size1];
                    Marshal.Copy(bmpData.Scan0, pixels, 0, size1);

                    for (int y = 0; y < img.Height; y++)
                    {
                        for (int x = 0; x < img.Width; x++)
                        {
                            int index = y * bmpData.Stride + x * bpp1;
                            var alpha = pixels[index + 3];
                            if (alpha < 255)
                            {
                                pixels[index]     = (byte)(pixels[index] * OverlayColor.B / 255);     //b
                                pixels[index + 1] = (byte)(pixels[index + 1] * OverlayColor.G / 255); //g
                                pixels[index + 2] = (byte)(pixels[index + 2] * OverlayColor.R / 255); //r
                                pixels[index + 3] = 255;
                            }
                        }
                    }

                    Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
                    img.UnlockBits(bmpData);
                    using (Graphics g = Graphics.FromImage(img))
                    {
                        g.DrawImage(new Bitmap(memory), Point.Empty);
                    }
                    img.Save(ExtractPath, System.Drawing.Imaging.ImageFormat.Png);
                    CurrentProgress += (double)file.FileSize2 / filesSize;
                    continue;
                }


                // Save data
                await File.WriteAllBytesAsync(ExtractPath, data);


                // Additionaly convert xmb
                if (file.Extension == ".XMB" && convertXMB)
                {
                    if (Alz4Utils.IsAlz4File(data))
                    {
                        data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                    }
                    else
                    {
                        if (L33TZipUtils.IsL33TZipFile(data))
                        {
                            data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                        }
                    }

                    using MemoryStream stream = new MemoryStream(data);
                    XMBFile xmb = await XMBFile.LoadXMBFile(stream);

                    xmb.file.Save(Path.ChangeExtension(ExtractPath, ""));
                }

                // Additionaly convert xmb -> json
                if (file.Extension == ".XMB" && AutoJSONConversion)
                {
                    if (Alz4Utils.IsAlz4File(data))
                    {
                        data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                    }
                    else
                    {
                        if (L33TZipUtils.IsL33TZipFile(data))
                        {
                            data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                        }
                    }

                    using MemoryStream stream = new MemoryStream(data);
                    XMBFile xmb = await XMBFile.LoadXMBFile(stream);

                    string json = JsonConvert.SerializeXmlNode(xmb.file);
                    await File.WriteAllTextAsync(Path.ChangeExtension(ExtractPath, "json"), json);
                }

                // Additionaly convert xml -> json
                if (file.Extension == ".XML" && AutoJSONConversion)
                {
                    if (Alz4Utils.IsAlz4File(data))
                    {
                        data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                    }
                    else
                    {
                        if (L33TZipUtils.IsL33TZipFile(data))
                        {
                            data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                        }
                    }

                    using MemoryStream stream = new MemoryStream(data);
                    XmlDocument xml = new XmlDocument();
                    xml.Load(stream);
                    string json = JsonConvert.SerializeXmlNode(xml);
                    await File.WriteAllTextAsync(Path.ChangeExtension(ExtractPath, "json"), json);
                }



                // Additionaly convert ddt to png
                if (file.Extension == ".DDT" && convertDDTToPNG)
                {
                    await DdtFileUtils.DdtBytes2PngAsync(data, ExtractPath);
                }
                // Additionaly convert ddt to tga
                if (file.Extension == ".DDT" && convertDDTToTGA)
                {
                    await DdtFileUtils.DdtBytes2TgaAsync(data, ExtractPath);
                }



                CurrentProgress += (double)file.FileSize2 / filesSize;
            }
            ResetProgress();
        }
        public async Task readFile(BarEntry file)
        {
            // Firstly, is the file parameter null?

            PreviewDdt   = null;
            Preview      = null;
            PreviewImage = null;
            if (file == null)
            {
                return;
            }

            if (file.Extension == ".WAV" || file.Extension == ".MP3")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                if (file.isCompressed == 2)
                {
                    audio = new MemoryStream(await soundUtils.DecryptSound(data));
                }
                else
                {
                    audio = new MemoryStream(data);
                }
                return;
            }
            if (file.Extension == ".DDT")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);


                if (Alz4Utils.IsAlz4File(data))
                {
                    data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                }
                else
                {
                    if (L33TZipUtils.IsL33TZipFile(data))
                    {
                        data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                    }
                }



                PreviewDdt = new DdtFile(data, true);
                return;
            }
            if (file.Extension == ".BMP" || file.Extension == ".TGA" || file.Extension == ".PNG" || file.Extension == ".CUR" || file.Extension == ".JPG")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                if (Alz4Utils.IsAlz4File(data))
                {
                    data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                }
                else
                {
                    if (L33TZipUtils.IsL33TZipFile(data))
                    {
                        data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                    }
                }
                var bitmap = new BitmapImage();

                using (var stream = new MemoryStream(data))
                {
                    if (file.Extension == ".TGA")
                    {
                        IImage image = await Task.Run(() => Pfim.Pfim.FromStream(stream));

                        var pinnedArray = GCHandle.Alloc(image.Data, GCHandleType.Pinned);
                        var addr        = pinnedArray.AddrOfPinnedObject();
                        var bsource     = BitmapSource.Create(image.Width, image.Height, 96.0, 96.0,
                                                              PixelFormat(image), null, addr, image.DataLen, image.Stride);
                        PngBitmapEncoder encoder      = new PngBitmapEncoder();
                        MemoryStream     memoryStream = new MemoryStream();

                        encoder.Frames.Add(BitmapFrame.Create(bsource));
                        encoder.Save(memoryStream);
                        memoryStream.Position = 0;
                        bitmap.BeginInit();
                        bitmap.StreamSource = memoryStream;
                        bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                        bitmap.EndInit();
                        bitmap.Freeze();
                        memoryStream.Close();
                    }

                    /*else if (file.Extension == ".PNG")
                     * {
                     *  System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                     *  using var memory = new MemoryStream();
                     *  image.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
                     *  memory.Seek(0, SeekOrigin.Begin);
                     *  bitmap.BeginInit();
                     *  bitmap.CacheOption = BitmapCacheOption.OnLoad;
                     *  bitmap.StreamSource = memory;
                     *  bitmap.EndInit();
                     * }*/
                    else
                    {
                        bitmap.BeginInit();
                        bitmap.StreamSource = stream;
                        bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                        bitmap.EndInit();
                        bitmap.Freeze();
                    }
                }


                PreviewImage = bitmap;
                return;
            }

            if (file.Extension == ".XMB")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                if (Alz4Utils.IsAlz4File(data))
                {
                    data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                }
                else
                {
                    if (L33TZipUtils.IsL33TZipFile(data))
                    {
                        data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                    }
                }

                //File.WriteAllBytes(file.fileNameWithoutPath, data);

                Preview = new Document();
                Preview.SyntaxHighlighting = "XML";
                Preview.Text = await XMBFile.XmbToXmlAsync(data);

                NotifyPropertyChanged("Preview");
                return;
            }
            if (file.Extension == ".XAML" || file.Extension == ".XML" || file.Extension == ".SHP" || file.Extension == ".LGT" || file.Extension == ".XS" || file.Extension == ".TXT" || file.Extension == ".CFG" || file.Extension == ".PY" || file.Extension == ".TACTICS")
            {
                using FileStream input = File.OpenRead(barFilePath);
                // Locate the file within the BAR file.
                input.Seek(file.Offset, SeekOrigin.Begin);
                var data = new byte[file.FileSize2];
                await input.ReadAsync(data, 0, data.Length);

                if (Alz4Utils.IsAlz4File(data))
                {
                    data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                }
                else
                {
                    if (L33TZipUtils.IsL33TZipFile(data))
                    {
                        data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                    }
                }
                Preview      = new Document();
                Preview.Text = System.Text.Encoding.UTF8.GetString(data);
                if (file.Extension == ".XS")
                {
                    Preview.SyntaxHighlighting = "C++";
                }
                else
                {
                    Preview.SyntaxHighlighting = "XML";
                }
                NotifyPropertyChanged("Preview");
                return;
            }

            return;
        }