Ejemplo n.º 1
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string inFile;
            int    i = Program.OpenFile(InFilter, out inFile);

            if (i != 0)
            {
                if (i == 32)
                {
                    FileMap      map  = FileMap.FromFile(inFile, FileMapProtect.Read);
                    FileScanNode node = new FileScanNode();
                    Program.Scan(map, node);
                    if (node.Children.Count == 0)
                    {
                        MessageBox.Show("No formats recognized.");
                    }
                    else
                    {
                        Program._rootNode = node;
                        Program._rootPath = inFile;
                        node._list        = node._children;
                        node.Initialize(null, new DataSource(map));
                        Reset();
                    }
                }
                else if (Program.Open(inFile))
                {
                    RecentFileHandler.AddFile(inFile);
                }
            }
        }
Ejemplo n.º 2
0
        public ACMDFile OpenFile(string Filepath, ACMDType type)
        {
            DataSource source = new DataSource(FileMap.FromFile(Filepath));

            if (*(buint *)source.Address != 0x41434D44) // ACMD
            {
                MessageBox.Show("Not an ACMD file:\n" + Filepath);
                return(null);
            }

            if (*(byte *)(source.Address + 0x04) == 0x02)
            {
                Runtime.WorkingEndian = Endianness.Little;
            }
            else if ((*(byte *)(source.Address + 0x04) == 0x00))
            {
                Runtime.WorkingEndian = Endianness.Big;
            }
            else
            {
                return(null);
            }


            return(new ACMDFile(source)
            {
                Type = type
            });
        }
Ejemplo n.º 3
0
        public PatchListFile(string patchFile)
        {
            DataSource patchFileSource = new DataSource(FileMap.FromFile(patchFile));

            _Header = patchFileSource.Slice(0, 0x80);
            VoidPtr addr = patchFileSource.Address + 4;

            _Files = new PatchFileItem[*(uint *)addr];
            for (int i = 0; i < _Files.Length; i++)
            {
                string absolutePath = Encoding.ASCII.GetString(patchFileSource.Slice(0x80 + (i * 0x80), 0x80));
                if (absolutePath.Contains('\0'))
                {
                    absolutePath = absolutePath.Substring(0, absolutePath.IndexOf('\0'));
                }
                string relativePath = absolutePath;
                if (relativePath.Contains("/"))
                {
                    relativePath = relativePath.Substring(relativePath.IndexOf("/") + 1);
                }
                if (absolutePath.Contains("packed"))
                {
                    _Files[i] = new PatchFileItem(relativePath.Replace("packed", string.Empty), absolutePath.Replace("packed", string.Empty), true);
                }
                else
                {
                    _Files[i] = new PatchFileItem(relativePath, absolutePath, false);
                }
            }
            patchFileSource.Close();
        }
Ejemplo n.º 4
0
        //Parser commands must initialize the node before returning.
        public static ResourceNode FromFile(ResourceNode parent, string path)
        {
            ResourceNode node = null;
            FileMap      map  = FileMap.FromFile(path, FileMapProtect.Read);

            try
            {
                if (Path.GetExtension(path).ToUpper().ToString() == ".MRG")
                {
                    node = new MRGNode();
                    node.Initialize(parent, map);
                }
                else if (Path.GetExtension(path).ToUpper().ToString() == ".REL")
                {
                    node = new RELNode();
                    node.Initialize(parent, map);
                }
                else if (Path.GetExtension(path).ToUpper().ToString() == ".DOL")
                {
                    node = new DOLNode();
                    node.Initialize(parent, map);
                }
                else
                {
                    node = FromSource(parent, new DataSource(map));
                }
            }
            finally { if (node == null)
                      {
                          map.Dispose();
                      }
            }
            return(node);
        }
Ejemplo n.º 5
0
        public bool ExtractFileFromPatch(ResourceItem rItem, string outputFile)
        {
            try
            {
                //Simple file
                string gameFile = PathHelper.GetGameFolder(PathHelperEnum.FOLDER_PATCH) + rItem.AbsolutePath.Replace('/', Path.DirectorySeparatorChar);
                if (File.Exists(gameFile))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(outputFile));
                    File.Copy(gameFile, outputFile, true);
                    return(true);
                }

                string mainfolder = "";
                if (!rItem.AbsolutePath.EndsWith("/"))
                {
                    DataSource packedSource;

                    //If packed file not datasourced yet
                    string packed = rItem.PatchItem.AbsolutePath;
                    if (!_CachedDataSources.TryGetValue(packed, out packedSource))
                    {
                        string path = gameFile.Substring(0, gameFile.LastIndexOf("\\data")) + Path.DirectorySeparatorChar + packed.Replace("/", "\\") + "packed";
                        if (File.Exists(path))
                        {
                            packedSource = new DataSource(FileMap.FromFile(path));
                            _CachedDataSources.Add(packed, packedSource);
                            mainfolder = path.Remove(path.Length - 6);
                        }
                    }

                    var fileData = new byte[0];

                    byte[] checkCmp = packedSource.Slice((int)rItem.OffInPack, 4);
                    if (checkCmp[0] == 0x78 && checkCmp[1] == 0x9c)
                    {
                        fileData = Utils.DeCompress(packedSource.Slice((int)rItem.OffInPack, (int)rItem.CmpSize));
                    }
                    else
                    {
                        fileData = packedSource.Slice((int)rItem.OffInPack, (int)rItem.DecSize);
                    }
                    Directory.CreateDirectory(Path.GetDirectoryName(outputFile));
                    File.WriteAllBytes(outputFile, fileData);
                }
                else
                {
                    LogHelper.Error(string.Format("Error extracting '{0}', the file could not be found in '{1}'", rItem.AbsolutePath, outputFile));
                }
                return(true);
            }
            catch (Exception e)
            {
                LogHelper.Error(string.Format("Error extracting '{0}', error: {1}", rItem.AbsolutePath, e.Message));
                return(false);
            }
        }
Ejemplo n.º 6
0
 public RFFile(string filepath)
 {
     CompressedSource = new DataSource(FileMap.FromFile(filepath));
     byte[] header   = CompressedSource.Slice(0, 0x80);
     byte[] filedata = Util.DeCompress(CompressedSource.Slice(0x80, CompressedSource.Length - 0x80));
     File.WriteAllBytes(filepath + ".dec", header.Concat(filedata).ToArray());
     WorkingSource = new DataSource(FileMap.FromFile(filepath + ".dec"));
     Parse();
 }
Ejemplo n.º 7
0
        public RFFile(string filename)
        {
            DataSource cmpSource = new DataSource(FileMap.FromFile(filename));

            byte[] header   = cmpSource.Slice(0, 0x80);
            byte[] filedata = Util.DeCompress(cmpSource.Slice(0x80, cmpSource.Length - 0x80));
            File.WriteAllBytes($"{filename}.dec", header.Concat(filedata).ToArray());
            cmpSource.Close();

            Parse($"{filename}.dec");
        }
Ejemplo n.º 8
0
        public Fighter OpenFighter(string dirPath)
        {
            return(new Fighter()
            {
                Main = OpenFile(dirPath + "/game.bin", ACMDType.Main),
                GFX = OpenFile(dirPath + "/effect.bin", ACMDType.GFX),
                SFX = OpenFile(dirPath + "/sound.bin", ACMDType.SFX),
                Expression = OpenFile(dirPath + "/expression.bin", ACMDType.Expression),

                MotionTable = ParseMTable(new DataSource(FileMap.FromFile(dirPath + "/motion.mtable")), Runtime.WorkingEndian)
            });
        }
Ejemplo n.º 9
0
        public Dictionary <uint, string> getAnimNames(string path)
        {
            Dictionary <uint, string> hashpairs = new Dictionary <uint, string>();

            if (path.EndsWith(".pac"))
            {
                byte[] filebytes = File.ReadAllBytes(path);
                int    count     = (int)Util.GetWord(filebytes, 8, Runtime.WorkingEndian);

                for (int i = 0; i < count; i++)
                {
                    uint   off      = (uint)Util.GetWord(filebytes, 0x10 + (i * 4), Runtime.WorkingEndian);
                    string FileName = Util.GetString(filebytes, off, Runtime.WorkingEndian);
                    string AnimName = Regex.Match(FileName, @"(.*)([A-Z])([0-9][0-9])(.*)\.omo").Groups[4].ToString();

                    hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes(AnimName.ToLower())), AnimName);
                    hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes((AnimName + "_C2").ToLower())), AnimName + "_C2");
                    hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes((AnimName + "_C3").ToLower())), AnimName + "_C3");

                    if (AnimName.EndsWith("s4s", StringComparison.InvariantCultureIgnoreCase) ||
                        AnimName.EndsWith("s3s", StringComparison.InvariantCultureIgnoreCase))
                    {
                        hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes(AnimName.Substring(0, AnimName.Length - 1).ToLower())), AnimName.Substring(0, AnimName.Length - 1));
                    }
                }
            }
            else if (path.EndsWith(".bch"))
            {
                DataSource src  = new DataSource(FileMap.FromFile(path));
                int        off  = *(int *)(src.Address + 0x0C);
                VoidPtr    addr = src.Address + off;
                while (*(byte *)addr != 0)
                {
                    string s        = new string((sbyte *)addr);
                    string AnimName = Regex.Match(s, @"(.*)([A-Z])([0-9][0-9])(.*)").Groups[4].ToString();
                    if (AnimName != "")
                    {
                        hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes(AnimName.ToLower())), AnimName);
                        hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes((AnimName + "_C2").ToLower())), AnimName + "_C2");
                        hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes((AnimName + "_C3").ToLower())), AnimName + "_C3");

                        if (AnimName.EndsWith("s4s", StringComparison.InvariantCultureIgnoreCase) ||
                            AnimName.EndsWith("s3s", StringComparison.InvariantCultureIgnoreCase))
                        {
                            hashpairs.Add(Crc32.Compute(Encoding.ASCII.GetBytes(AnimName.Substring(0, AnimName.Length - 1).ToLower())), AnimName.Substring(0, AnimName.Length - 1));
                        }
                    }
                    addr += s.Length + 1;
                }
            }
            return(hashpairs);
        }
Ejemplo n.º 10
0
        //Parser commands must initialize the node before returning.
        public static ResourceNode FromFile(ResourceNode parent, string path)
        {
            ResourceNode node = null;
            FileMap      map  = FileMap.FromFile(path, FileMapProtect.Read);

            try { node = FromSource(parent, new DataSource(map)); }
            finally { if (node == null)
                      {
                          map.Dispose();
                      }
            }
            return(node);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Returns a DataSource object containing data at "Start".
        /// </summary>
        /// <param name="start"> Start of chunk.</param>
        /// <param name="size"> Size of the chunk in bytes</param>
        /// <param name="dtIndex">Index of the dt file to access</param>
        /// <returns></returns>
        private static DataSource GetFileChunk(uint start, int size, int dtIndex)
        {
            SYSTEM_INFO _info = new SYSTEM_INFO();

            GetSystemInfo(ref _info);

            uint chunk_start = start;
            int  chunk_len   = size;

            if (start % _info.allocationGranularity != 0)
            {
                chunk_start = start.RoundDown((int)_info.allocationGranularity);
                var difference = start - chunk_start;
                chunk_len = (int)difference + size;
            }
            return(new DataSource(FileMap.FromFile(DtPaths[dtIndex], FileMapProtect.ReadWrite, chunk_start, chunk_len)));
        }
Ejemplo n.º 12
0
        public PACKManager(string path)
        {
            _source = new DataSource(FileMap.FromFile(path));
            string magic = new String((sbyte *)_source.Address);

            if (magic == "PACK")
            {
                _endian = Endianness.little;
            }
            else if (magic == "KCAP")
            {
                _endian = Endianness.big;
            }
            else
            {
                Console.WriteLine("Not a valid PACK file");
            }
        }
Ejemplo n.º 13
0
        public static ResourceNode FromFile(ResourceNode parent, string path, FileOptions options)
        {
            ResourceNode node = null;
            FileMap      map  = FileMap.FromFile(path, FileMapProtect.Read, 0, 0, options);

            try
            {
                DataSource source = new DataSource(map);
                if ((node = FromSource(parent, source)) == null)
                {
                    string ext = path.Substring(path.LastIndexOf('.') + 1).ToUpper(CultureInfo.InvariantCulture);

                    if (Forced.ContainsKey(ext) &&
                        (node = Activator.CreateInstance(Forced[ext]) as ResourceNode) != null)
                    {
                        FileMap uncompressedMap = Compressor.TryExpand(ref source, false);
                        if (uncompressedMap != null)
                        {
                            node.Initialize(parent, source, new DataSource(uncompressedMap));
                        }
                        else
                        {
                            node.Initialize(parent, source);
                        }
                    }
#if DEBUG
                    else
                    {
                        node = new RawDataNode(Path.GetFileNameWithoutExtension(path));
                        node.Initialize(parent, source);
                    }
#endif
                }
            }
            finally
            {
                if (node == null)
                {
                    map.Dispose();
                }
            }

            return(node);
        }
Ejemplo n.º 14
0
        private unsafe void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog od = new OpenFileDialog();

            od.Filter   = "Brawlbox Settings (*.settings)|*.settings";
            od.FileName = Application.StartupPath;
            if (od.ShowDialog() == DialogResult.OK)
            {
                string path = od.FileName;
                using (FileMap map = FileMap.FromFile(path, FileMapProtect.Read))
                {
                    if (*(uint *)map.Address == BrawlBoxViewerSettings.Tag)
                    {
                        BrawlBoxViewerSettings *settings = (BrawlBoxViewerSettings *)map.Address;
                        DistributeSettings(*settings);
                        ScreenCapBgLocText.Text = new String((sbyte *)map.Address + settings->_screenCapPathOffset);
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public static ResourceNode FromFile(ResourceNode parent, string path, FileOptions options, Type t)
        {
            ResourceNode node = null;
            FileMap      map  = FileMap.FromFile(path, FileMapProtect.Read, 0, 0, options);

            try
            {
                DataSource source = new DataSource(map);

                bool supportsCompression = true;
                if (!(t is null))
                {
                    ResourceNode n = Activator.CreateInstance(t) as ResourceNode;
                    supportsCompression = n?.supportsCompression ?? true;
                }

                if ((node = FromSource(parent, source, t, supportsCompression)) == null)
                {
                    string ext = path.Substring(path.LastIndexOf('.') + 1).ToUpper(CultureInfo.InvariantCulture);

                    if (!(t is null) && (node = Activator.CreateInstance(t) as ResourceNode) != null ||
                        ForcedExtensions.ContainsKey(ext) &&
                        (node = Activator.CreateInstance(ForcedExtensions[ext]) as ResourceNode) != null)
                    {
                        FileMap uncompressedMap = Compressor.TryExpand(ref source, false);
                        if (uncompressedMap != null)
                        {
                            node.Initialize(parent, source, new DataSource(uncompressedMap));
                        }
                        else
                        {
                            node.Initialize(parent, source);
                        }
                    }
                    else
                    {
                        node = new RawDataNode(Path.GetFileName(path));
                        node.Initialize(parent, source);
                    }
                }
            }
Ejemplo n.º 16
0
        //Parser commands must initialize the node before returning.
        public unsafe static ResourceNode FromFile(ResourceNode parent, string path, FileOptions options = FileOptions.RandomAccess)
        {
            ResourceNode node = null;
            FileMap      map  = FileMap.FromFile(path, FileMapProtect.Read, 0, 0, options);

            try
            {
                DataSource source = new DataSource(map);
                if ((node = FromSource(parent, source)) == null)
                {
                    string ext = path.Substring(path.LastIndexOf('.') + 1).ToUpper();
                    if (Forced.ContainsKey(ext))
                    {
                        node = Activator.CreateInstance(Forced[ext]) as ResourceNode;
                        FileMap uncomp = Compressor.TryExpand(ref source, false);
                        if (uncomp != null)
                        {
                            node.Initialize(parent, source, new DataSource(uncomp));
                        }
                        else
                        {
                            node.Initialize(parent, source);
                        }
                    }
                    else if (UseRawDataNode)
                    {
                        (node = new RawDataNode(Path.GetFileNameWithoutExtension(path))).Initialize(parent, source);
                    }
                }
            }
            finally
            {
                if (node == null)
                {
                    map.Dispose();
                }
            }
            return(node);
        }
Ejemplo n.º 17
0
        private DataSource GetFileChunk(uint start, uint size, int dtIndex, out uint difference)
        {
            SYSTEM_INFO _info = new SYSTEM_INFO();

            GetSystemInfo(ref _info);

            uint chunk_start = start;
            uint chunk_len   = size;

            difference = 0;
            if (start % _info.allocationGranularity != 0)
            {
                chunk_start = start.RoundDown((int)_info.allocationGranularity);
                difference  = start - chunk_start;
                chunk_len   = difference + size;
            }
            if (chunk_len == 0)
            {
                return(new DataSource(FileMap.FromFile(_DtPaths[dtIndex], FileMapProtect.Read, chunk_start, 1)));
            }
            return(new DataSource(FileMap.FromFile(_DtPaths[dtIndex], FileMapProtect.Read, chunk_start, (int)chunk_len)));
        }
Ejemplo n.º 18
0
        private bool OpenFile(string Filepath)
        {
            bool handled = false;

            if (Filepath.EndsWith(".bin"))
            {
                DataSource source = new DataSource(FileMap.FromFile(Filepath));
                if (*(buint *)source.Address == 0x41434D44) // ACMD
                {
                    if (*(byte *)(source.Address + 0x04) == 0x02)
                    {
                        Runtime.WorkingEndian = Endianness.Little;
                    }
                    else if ((*(byte *)(source.Address + 0x04) == 0x00))
                    {
                        Runtime.WorkingEndian = Endianness.Big;
                    }
                    else
                    {
                        handled = false;
                    }

                    ACMD_FILES.Add(Path.GetFileNameWithoutExtension(Filepath), new ACMDFile(source));
                    handled = true;
                }
            }
            else if (Filepath.EndsWith(".mscsb")) // MSC
            {
                MSC_FILES.Add(Path.GetFileNameWithoutExtension(Filepath), new MSCFile(Filepath));
                handled = true;
            }
            else if (Filepath.EndsWith(".mtable"))
            {
                MotionTable = new MTable(Filepath, Runtime.WorkingEndian);
            }

            return(handled);
        }
Ejemplo n.º 19
0
        public ACMDFile OpenFile(string Filepath, ACMDType type)
        {
            DataSource source = new DataSource(FileMap.FromFile(Filepath));

            if (*(byte *)(source.Address + 0x04) == 0x02)
            {
                Runtime.WorkingEndian = Endianness.Little;
            }
            else if ((*(byte *)(source.Address + 0x04) == 0x00))
            {
                Runtime.WorkingEndian = Endianness.Big;
            }
            else
            {
                return(null);
            }


            return(new ACMDFile(source, Runtime.WorkingEndian)
            {
                Type = type
            });
        }
Ejemplo n.º 20
0
        public void OpenFile(string filepath)
        {
            if (filepath.EndsWith(".bin"))
            {
                DataSource source = new DataSource(FileMap.FromFile(filepath));
                if (*(buint *)source.Address == 0x41434D44) // ACMD
                {
                    if (*(byte *)(source.Address + 0x04) == 0x02)
                    {
                        Runtime.WorkingEndian = Endianness.Little;
                    }
                    else if ((*(byte *)(source.Address + 0x04) == 0x00))
                    {
                        Runtime.WorkingEndian = Endianness.Big;
                    }

                    var f    = new ACMDFile(source);
                    var node = new TreeNode("ACMD");
                    foreach (var keypair in f.Scripts)
                    {
                        node.Nodes.Add(new ScriptNode(keypair.Key, $"{keypair.Key:X8}", keypair.Value));
                    }
                    Runtime.Instance.FileTree.Nodes.Add(node);
                }
            }
            else if (filepath.EndsWith(".mscsb")) // MSC
            {
                var f    = new MSCFile(filepath);
                var node = new TreeNode("MSC");

                for (int i = 0; i < f.Scripts.Count; i++)
                {
                    node.Nodes.Add(new ScriptNode((uint)i, $"{i:X8}", f.Scripts.Values[i]));
                }
                Runtime.Instance.FileTree.Nodes.Add(node);
            }
        }
Ejemplo n.º 21
0
        public void Parse(string path)
        {
            _workingSource = new DataSource(FileMap.FromFile(path));

            short tag = *(short *)_workingSource.Address;

            if (tag != 0x666f)
            {
                return;
            }
            _version    = *(short *)(_workingSource.Address + 0x02);
            _entryCount = *(int *)(_workingSource.Address + 0x04);
            Entries     = new SortedList <uint, LSEntryObject>(_entryCount);

            for (int i = 0; i < _entryCount; i++)
            {
                LSEntryObject lsobj = new LSEntryObject();
                if (Version == 1)
                {
                    LSEntry_v1 entry = *(LSEntry_v1 *)(_workingSource.Address + 0x08 + (i * 0x0C));
                    lsobj.FileNameCRC = entry._crc;
                    lsobj.DTOffset    = entry._start;
                    lsobj.Size        = entry._size;
                }
                else if (Version == 2)
                {
                    LSEntry_v2 entry = *(LSEntry_v2 *)(_workingSource.Address + 0x08 + (i * 0x10));
                    lsobj.FileNameCRC   = entry._crc;
                    lsobj.DTOffset      = entry._start;
                    lsobj.Size          = entry._size;
                    lsobj.DTIndex       = entry._dtIndex;
                    lsobj.PaddingLength = entry._padlen;
                }
                Entries.Add(lsobj.FileNameCRC, lsobj);
            }
        }
Ejemplo n.º 22
0
        private unsafe void fOpen_Click(object sender, EventArgs e)
        {
            if (ofDlg.ShowDialog() == DialogResult.OK)
            {
                this.Reset();
                if (ofDlg.FileName.EndsWith(".bin"))
                {
                    DataSource source = new DataSource(FileMap.FromFile(ofDlg.FileName));
                    if (*(buint *)source.Address == 0x41434D44) // ACMD
                    {
                        if (*(byte *)(source.Address + 0x04) == 0x02)
                        {
                            Runtime.WorkingEndian = Endianness.Little;
                        }
                        else if ((*(byte *)(source.Address + 0x04) == 0x00))
                        {
                            Runtime.WorkingEndian = Endianness.Big;
                        }

                        var f = new ACMDFile(source);
                        ScriptFiles.Add(ofDlg.FileName, f);
                        var node = new TreeNode("ACMD")
                        {
                            Name = "nACMD"
                        };
                        foreach (var keypair in f.Scripts)
                        {
                            node.Nodes.Add(new ScriptNode(keypair.Key, $"{keypair.Key:X8}", keypair.Value));
                        }
                        FileTree.Nodes.Add(node);
                    }
                    else if (*(buint *)source.Address == 0xFFFF0000)
                    {
                        source.Close();
                        ParamFile = new ParamFile(ofDlg.FileName);
                        var node = new TreeNode("PARAMS")
                        {
                            Name = "nPARAMS"
                        };
                        FileTree.Nodes.Add(node);
                        PopulateParams();
                    }
                }
                else if (ofDlg.FileName.EndsWith(".mscsb")) // MSC
                {
                    var f = new MSCFile(ofDlg.FileName);
                    ScriptFiles.Add(ofDlg.FileName, f);

                    var node = new TreeNode("MSC")
                    {
                        Name = "nMSC"
                    };
                    for (int i = 0; i < f.Scripts.Count; i++)
                    {
                        var sn = new ScriptNode((uint)i, $"{i:D8}", f.Scripts.Values[i]);
                        if (((MSCScript)f.Scripts.Values[i]).IsEntrypoint)
                        {
                            sn.Text = "Entrypoint";
                        }
                        else if (i == 0)
                        {
                            sn.Text = "Init";
                        }

                        node.Nodes.Add(sn);
                    }
                    FileTree.Nodes.Add(node);
                }
                IDEMode    = IDE_MODE.File;
                this.Text += ofDlg.FileName;
            }
        }
Ejemplo n.º 23
0
        private static void Unpack_update(string resFile)
        {
            Console.WriteLine("Parsing resource file..");
            RFFile     rfFile     = new RFFile(resFile);
            var        pathParts  = new string[20];
            DataSource _curPacked = new DataSource();
            string     mainfolder = "";
            string     region     = "";

            if (resFile.Contains("("))
            {
                region = resFile.Substring(resFile.IndexOf("(", StringComparison.Ordinal), 7);
            }

            foreach (ResourceEntryObject rsobj in rfFile.ResourceEntries)
            {
                if (rsobj == null)
                {
                    continue;
                }

                pathParts[rsobj.FolderDepth - 1] = rsobj.EntryString;
                Array.Clear(pathParts, rsobj.FolderDepth, pathParts.Length - (rsobj.FolderDepth + 1));
                var path = $"data{region}/{string.Join("", pathParts)}";


                if (rsobj.HasPack)
                {
                    path += (rsobj.Compressed ? "packed" : "");
                    if (File.Exists(path))
                    {
                        _curPacked = new DataSource(FileMap.FromFile(path));
                        mainfolder = path.Remove(path.Length - 6);
                    }
                    continue;
                }

                if (!(rsobj.inPatch && path.Contains(mainfolder) && !string.IsNullOrEmpty(mainfolder)))
                {
                    continue;
                }

                if (path.EndsWith("/"))
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                }
                else
                {
                    var fileData = new byte[0];

                    if (rsobj.CmpSize > 0)
                    {
                        byte[] tmp = _curPacked.Slice((int)rsobj.OffInPack, 4);


                        if (tmp[0] == 0x78 && tmp[1] == 0x9c)
                        {
                            fileData = Util.DeCompress(_curPacked.Slice((int)rsobj.OffInPack, (int)rsobj.CmpSize));
                        }
                        else
                        {
                            fileData = _curPacked.Slice((int)rsobj.OffInPack, (int)rsobj.DecSize);
                        }
                    }

                    Console.WriteLine(path);
                    Logstream.WriteLine($"{path} : size: {rsobj.DecSize:X8}");

                    if (fileData.Length != rsobj.DecSize)
                    {
                        Console.WriteLine("Error: File length doesn't match specified decompressed length, quiting");
                        Logstream.WriteLine("Error: File length doesn't match specified decompressed length, quiting");
                        return;
                    }

                    File.WriteAllBytes(path, fileData);
                }
            }
            Logstream.Close();
            rfFile._workingSource.Close();
            Console.WriteLine("Extraction finished.");

            if (File.Exists($"resource{region}.dec"))
            {
                File.Delete($"resource{region}.dec");
            }
        }
Ejemplo n.º 24
0
 public ACMDFile(string filepath) : this(new DataSource(FileMap.FromFile(filepath)))
 {
 }
Ejemplo n.º 25
0
 public static IAudioStream FromFile(string path)
 {
     return(new PCMStream(FileMap.FromFile(path, FileMapProtect.Read)));
 }
Ejemplo n.º 26
0
        public void Parse(string fileDecomp)
        {
            _workingSource = new DataSource(FileMap.FromFile(fileDecomp));
            RFHeader rfheader = *(RFHeader *)_workingSource.Address;

            Header = new RfHeaderObject
            {
                Tag                = rfheader._rf,
                RegionEtc          = rfheader._regionEtc,
                HeaderLen1         = rfheader._headerLen1,
                Pad                = rfheader._pad0,
                EntriesChunkOffset = rfheader._headerLen2,
                EntriesChunkLen    = rfheader._0x18EntriesLen,
                UnixTimestamp      = rfheader._unixTimestamp,
                CompressedLen      = rfheader._compressedLen,
                DecompressedLen    = rfheader._decompressedLen,
                StrsChunkOffset    = rfheader._strsPlus,
                StrsChunkLen       = rfheader._strsLen,
                EntryCount         = rfheader._resourceEntries
            };

            VoidPtr addr = _workingSource.Address + Header.StrsChunkOffset;

            strChunks = new byte[*(uint *)addr][];
            addr     += 4;

            for (int i = 0; i < strChunks.Length; i++)
            {
                strChunks[i] = _workingSource.Slice((int)(Header.StrsChunkOffset + 4) + i * 0x2000,
                                                    0x2000);
            }

            addr            += strChunks.Length * 0x2000;
            ExtensionOffsets = new uint[*(uint *)addr];
            Extensions       = new string[ExtensionOffsets.Length];
            addr            += 4;

            for (int i = 0; i < ExtensionOffsets.Length; i++)
            {
                ExtensionOffsets[i] = *(uint *)(addr + i * 4);
                var ext = Encoding.ASCII.GetString(str_from_offset((int)ExtensionOffsets[i], 64));
                Extensions[i] = ext.Remove(ext.IndexOf('\0'));
            }

            addr = _workingSource.Address + Header.EntriesChunkOffset;
            uint size1 = *(uint *)addr * 8 + 4;

            addr += size1;
            uint size2 = *(uint *)addr + 4;

            addr += size2;

            ResourceEntries = new ResourceEntryObject[Header.EntryCount];

            for (int i = 0; i < Header.EntryCount; i++, addr += 0x18)
            {
                ResourceEntry       entry = *(ResourceEntry *)addr;
                ResourceEntryObject rsobj = new ResourceEntryObject()
                {
                    OffInPack     = entry.offInPack,
                    NameOffsetEtc = entry.nameOffsetEtc,
                    CmpSize       = entry.cmpSize,
                    DecSize       = entry.decSize,
                    Timestamp     = entry.timestamp,
                    Flags         = entry.flags,
                };

                if (rsobj.OffInPack == 0xBBBBBBBB)
                {
                    ResourceEntries[i] = null;
                    continue;
                }

                var strbytes = str_from_offset((int)rsobj.NameOffset, 128);
                var name     = Encoding.ASCII.GetString(str_from_offset((int)rsobj.NameOffset, 128));
                if ((entry.nameOffsetEtc & 0x00800000) > 0)
                {
                    var reference = BitConverter.ToUInt16(strbytes, 0);

                    var referenceLen = (reference & 0x1f) + 4;
                    var refReloff    = (reference & 0xe0) >> 6 << 8 | (reference >> 8);
                    name = Encoding.ASCII.GetString(str_from_offset((int)rsobj.NameOffset - refReloff, referenceLen)) +
                           name.Substring(2);
                }
                if (name.Contains('\0'))
                {
                    name = name.Substring(0, name.IndexOf('\0'));
                }

                rsobj.EntryString  = name + Extensions[rsobj.extIndex];
                ResourceEntries[i] = rsobj;
            }
            //_workingSource.Close();
        }
Ejemplo n.º 27
0
        internal static GCTNode IsParsable(string path)
        {
            FileMap map = FileMap.FromFile(path, FileMapProtect.ReadWrite);

            GCTCodeLine *data = (GCTCodeLine *)map.Address;

            if (GCTCodeLine.Tag._1 != data->_1 || GCTCodeLine.Tag._2 != data->_2)
            {
                map.Dispose();
                return(null);
            }

            data = (GCTCodeLine *)(map.Address + (uint)Helpers.RoundDown((uint)map.Length, 8) - GCTCodeLine.Size);
            bool endFound = false;
            int  i        = 0;

            while (!endFound)
            {
                GCTCodeLine line = *data--;
                if (line._1 == GCTCodeLine.End._1 && line._2 == GCTCodeLine.End._2)
                {
                    endFound = true;
                    break;
                }

                i++;
            }

            if (endFound && i <= 0)
            {
                data = (GCTCodeLine *)map.Address + 1;

                string s = "";
                while (true)
                {
                    GCTCodeLine line = *data++;
                    if (line._1 == GCTCodeLine.End._1 && line._2 == GCTCodeLine.End._2)
                    {
                        break;
                    }

                    s += line.ToStringNoSpace();
                }

                GCTNode g = new GCTNode();

                List <string> _unrecognized = new List <string>();

                foreach (CodeStorage c in Properties.Settings.Default.Codes)
                {
                    int index = -1;
                    if ((index = s.IndexOf(c._code)) >= 0)
                    {
                        g.AddChild(new GCTCodeEntryNode()
                        {
                            _name = c._name, _description = c._description, LinesNoSpaces = s.Substring(index, c._code.Length)
                        });
                        s = s.Remove(index, c._code.Length);
                    }
                }

                if (g.Children.Count > 0)
                {
                    if (s.Length > 0)
                    {
                        MessageBox.Show(String.Format("{0} code{1} w{2} recognized.", g.Children.Count.ToString(), g.Children.Count > 1 ? "s" : "", g.Children.Count > 1 ? "ere" : "as"));
                    }
                }
                else
                {
                    MessageBox.Show("This GCT does not contain any recognizable codes.");
                }

                if (s.Length > 0)
                {
                    g.AddChild(new GCTCodeEntryNode()
                    {
                        _name = "Unrecognized Code(s)", LinesNoSpaces = s
                    });
                }

                return(g);
            }
            else if (endFound && i > 0)
            {
                GCTNode g = new GCTNode();
                g.Initialize(null, new DataSource(map));
                return(g);
            }

            map.Dispose();
            return(null);
        }
Ejemplo n.º 28
0
 public unsafe virtual void Replace(string fileName, FileMapProtect prot, FileOptions options)
 {
     //Name = Path.GetFileNameWithoutExtension(fileName);
     ReplaceRaw(FileMap.FromFile(fileName, prot, 0, 0, options));
 }
Ejemplo n.º 29
0
        public static unsafe Bitmap FromFile(string path)
        {
            using (FileMap view = FileMap.FromFile(path, FileMapProtect.Read))// FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                TGAHeader *header = (TGAHeader *)view.Address;

                int w = header->imageSpecification.width, h = header->imageSpecification.height;
                int entryBpp  = header->imageSpecification.pixelDepth;
                int alphaBits = header->imageSpecification.AlphaBits;

                ColorPalette palette = null;
                PixelFormat  format;
                ColorParser  cParser;
                switch (header->imageType & (TGAImageType)0x3)
                {
                case TGAImageType.UncompressedColorMapped:
                {
                    int mapBpp = header->colorMapSpecification.entrySize;
                    if (entryBpp == 4)
                    {
                        format  = PixelFormat.Format4bppIndexed;
                        cParser = delegate(VoidPtr sPtr, int sIndex, VoidPtr dPtr, int dIndex)
                        {
                            byte val = ((byte *)sPtr)[sIndex >> 1], val2 = ((byte *)dPtr)[dIndex >> 1];
                            val = ((sIndex & 1) == 0) ? (byte)(val >> 4) : (byte)(val & 0xF);
                            ((byte *)dPtr)[dIndex >> 1] = ((dIndex & 1) == 0) ? (byte)((val2 & 0xF) | (val << 4)) : (byte)((val2 & 0xF0) | val);
                        };
                    }
                    else if (entryBpp == 8)
                    {
                        format  = PixelFormat.Format8bppIndexed;
                        cParser = delegate(VoidPtr sPtr, int sIndex, VoidPtr dPtr, int dIndex)
                        { ((byte *)dPtr)[dIndex] = ((byte *)sPtr)[sIndex]; };
                    }
                    else
                    {
                        throw new InvalidDataException("Invalid TGA color map format.");
                    }

                    int firstIndex = header->colorMapSpecification.firstEntryIndex;
                    int palSize    = firstIndex + header->colorMapSpecification.length;
                    palette = ColorPaletteExtension.CreatePalette(ColorPaletteFlags.None, palSize);

                    PaletteParser pParser;
                    if (mapBpp == 32)
                    {
                        pParser = (ref VoidPtr x) => { Color c = (Color)(*(ARGBPixel *)x); x += 4; return(c); }
                    }
                    ;
                    else if (mapBpp == 24)
                    {
                        pParser = (ref VoidPtr x) => { Color c = (Color)(*(RGBPixel *)x); x += 3; return(c); }
                    }
                    ;
                    else
                    {
                        throw new InvalidDataException("Invalid TGA color map format.");
                    }

                    VoidPtr palData = header->ColorMapData;
                    for (int i = firstIndex; i < palSize; i++)
                    {
                        palette.Entries[i] = pParser(ref palData);
                    }

                    break;
                }

                case TGAImageType.UncompressedTrueColor:
                {
                    if ((entryBpp == 15) || ((entryBpp == 16) && (alphaBits == 0)))
                    {
                        format  = PixelFormat.Format16bppRgb555;
                        cParser = delegate(VoidPtr sPtr, int sIndex, VoidPtr dPtr, int dIndex)
                        { ((RGB555Pixel *)dPtr)[dIndex] = ((RGB555Pixel *)sPtr)[sIndex]; };
                    }
                    else if (entryBpp == 16)
                    {
                        format  = PixelFormat.Format16bppArgb1555;
                        cParser = delegate(VoidPtr sPtr, int sIndex, VoidPtr dPtr, int dIndex)
                        { ((RGB555Pixel *)dPtr)[dIndex] = ((RGB555Pixel *)sPtr)[sIndex]; };
                    }
                    else if (entryBpp == 24)
                    {
                        format  = PixelFormat.Format24bppRgb;
                        cParser = delegate(VoidPtr sPtr, int sIndex, VoidPtr dPtr, int dIndex)
                        { ((RGBPixel *)dPtr)[dIndex] = ((RGBPixel *)sPtr)[sIndex]; };
                    }
                    else if (entryBpp == 32)
                    {
                        format  = (alphaBits == 8) ? PixelFormat.Format32bppArgb : PixelFormat.Format32bppRgb;
                        cParser = delegate(VoidPtr sPtr, int sIndex, VoidPtr dPtr, int dIndex)
                        { ((ARGBPixel *)dPtr)[dIndex] = ((ARGBPixel *)sPtr)[sIndex]; };
                    }
                    else
                    {
                        throw new InvalidDataException("Unknown TGA file format.");
                    }

                    break;
                }

                case TGAImageType.UncompressedGreyscale:
                {
                    if (entryBpp == 8)
                    {
                        format  = PixelFormat.Format24bppRgb;
                        cParser = delegate(VoidPtr sPtr, int sIndex, VoidPtr dPtr, int dIndex)
                        { ((RGBPixel *)dPtr)[dIndex] = RGBPixel.FromIntensity(((byte *)sPtr)[sIndex]); };
                    }
                    else
                    {
                        throw new InvalidDataException("Unknown TGA file format.");
                    }
                    break;
                }

                default: throw new InvalidDataException("Unknown TGA file format.");
                }

                Bitmap bmp = new Bitmap(w, h, format);
                if (palette != null)
                {
                    bmp.Palette = palette;
                }
                BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, format);

                bool rle          = ((int)header->imageType & 0x8) != 0;
                int  srcStride    = (entryBpp * w).Align(8) / 8;
                int  rleBufferLen = (rle) ? srcStride : 0;

                byte *buffer = stackalloc byte[rleBufferLen];

                int   origin = (int)header->imageSpecification.ImageOrigin;
                int   xStep  = ((origin & 1) == 0) ? 1 : -1;
                int   yStep  = ((origin & 2) != 0) ? 1 : -1;
                byte *imgSrc = header->ImageData;
                for (int dY = (yStep == 1) ? 0 : h - 1, sY = 0; sY < h; dY += yStep, sY++)
                {
                    VoidPtr imgDst = (VoidPtr)data.Scan0 + (data.Stride * dY);

                    if (rle)
                    {
                        imgSrc += DecodeRLE(imgSrc, buffer, srcStride, entryBpp);
                    }

                    for (int dX = (xStep == 1) ? 0 : w - 1, sX = 0; sX < w; dX += xStep, sX++)
                    {
                        cParser((rle) ? buffer : imgSrc, sX, imgDst, dX);
                    }

                    if (!rle)
                    {
                        imgSrc += srcStride;
                    }
                }

                bmp.UnlockBits(data);
                return(bmp);
            }
        }
Ejemplo n.º 30
0
        public void GetAnimHashPairs(string path)
        {
            Dictionary <uint, string> hashpairs = new Dictionary <uint, string>();

            foreach (string s in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
            {
                if (s.EndsWith(".pac"))
                {
                    byte[] filebytes = File.ReadAllBytes(s);
                    int    count     = (int)Util.GetWord(filebytes, 8, Runtime.WorkingEndian);

                    for (int i = 0; i < count; i++)
                    {
                        uint   off      = (uint)Util.GetWord(filebytes, 0x10 + (i * 4), Runtime.WorkingEndian);
                        string FileName = Util.GetString(filebytes, off, Runtime.WorkingEndian);
                        string AnimName = Regex.Match(FileName, @"(.*)([A-Z])([0-9][0-9])(.*)\.omo").Groups[4].ToString();
                        if (string.IsNullOrEmpty(AnimName))
                        {
                            continue;
                        }

                        AddAnimHash(AnimName);
                        AddAnimHash(AnimName + "_C2");
                        AddAnimHash(AnimName + "_C3");
                        AddAnimHash(AnimName + "L");
                        AddAnimHash(AnimName + "R");


                        if (AnimName.EndsWith("s4s", StringComparison.InvariantCultureIgnoreCase) ||
                            AnimName.EndsWith("s3s", StringComparison.InvariantCultureIgnoreCase))
                        {
                            AddAnimHash(AnimName.Substring(0, AnimName.Length - 1));
                        }
                    }
                }
                else if (s.EndsWith(".bch"))
                {
                    DataSource src  = new DataSource(FileMap.FromFile(s));
                    int        off  = *(int *)(src.Address + 0x0C);
                    VoidPtr    addr = src.Address + off;
                    while (*(byte *)addr != 0)
                    {
                        string AnimName = Regex.Match(s, @"(.*)([A-Z])([0-9][0-9])(.*)").Groups[4].ToString();
                        if (string.IsNullOrEmpty(AnimName))
                        {
                            addr += s.Length + 1;
                            continue;
                        }

                        AddAnimHash(AnimName);
                        AddAnimHash(AnimName + "_C2");
                        AddAnimHash(AnimName + "_C3");
                        AddAnimHash(AnimName + "L");
                        AddAnimHash(AnimName + "R");


                        if (AnimName.EndsWith("s4s", StringComparison.InvariantCultureIgnoreCase) ||
                            AnimName.EndsWith("s3s", StringComparison.InvariantCultureIgnoreCase))
                        {
                            AddAnimHash(AnimName.Substring(0, AnimName.Length - 1));
                        }

                        addr += s.Length + 1;
                    }
                }
            }
        }