Exemple #1
0
        public override void Write(Stream source, Stream destination)
        {
            // Writing PVR textures is done through VrSharp, so just pass it to that
            PvrTextureEncoder texture = new PvrTextureEncoder(source, PixelFormat, DataFormat);

            if (!texture.Initalized)
            {
                throw new TextureNotInitalizedException("Unable to initalize texture.");
            }

            texture.CompressionFormat = compressionFormat;

            texture.HasGlobalIndex = HasGlobalIndex;
            if (texture.HasGlobalIndex)
            {
                texture.GlobalIndex = GlobalIndex;
            }

            // If we have an external palette file, save it
            if (texture.NeedsExternalPalette)
            {
                needsExternalPalette = true;

                PaletteStream = new MemoryStream();
                texture.PaletteEncoder.Save(PaletteStream);
            }
            else
            {
                needsExternalPalette = false;
            }

            texture.Save(destination);
        }
        private void button_genPrev_Click(object sender, EventArgs e)
        {
            SixLabors.ImageSharp.Image <Bgra32> tmpImg = ImageSharpExtensions.ToImageSharpImage(_img);

            var pf = (PvrPixelFormat)comboBox_PixelFormat.SelectedItem;
            var df = (PvrDataFormat)comboBox_DataFormat.SelectedItem;
            var dr = comboBox_Dithering.SelectedIndex;
            var em = checkBox_eyeMode.Checked;

            using (var ms = new MemoryStream())
            {
                // Temp encode to pvr
                PvrTextureEncoder tmpImgRaw = new PvrTextureEncoder(tmpImg, pf, df);
                tmpImgRaw.DitheringMode = dr;
                if (em == false)
                {
                    tmpImgRaw.MetricMode = 0;
                }
                else
                {
                    tmpImgRaw.MetricMode = 1;
                }

                tmpImgRaw.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);

                //Tmp decode for preview
                var tmpPreview = new PvrTextureDecoder(ms);
                var img        = tmpPreview.GetImage();
                var imgNative  = ImageSharpExtensions.ToBitmap(img);

                pictureBox_PVRPreview.Image = imgNative;

                pictureBox_PVRPreview.Update();
                panel1.Update();
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            ArchiveFromFolderMode folderMode;
            string        dir;
            string        filePath;
            string        directoryName;
            ArchiveBase   pvmArchive;
            ArchiveWriter pvmWriter;
            string        archiveName;
            string        path;

            byte[] filedata;
            bool   isPRS;
            bool   isBIN = false;
            string extension;

            // Usage
            if (args.Length == 0)
            {
                Console.WriteLine("ArchiveTool is a command line tool to extract and create PVM, GVM, PRS, DAT and PB archives.\nIt can also decompress SADX Gamecube 'SaCompGC' REL files.\n");
                Console.WriteLine("Usage:\n");
                Console.WriteLine("Extracting a PVM/GVM/PRS/PB/PVMX/DAT/REL file:\nArchiveTool <archivefile>\nIf the archive is PRS compressed, it will be decompressed first.\nIf the archive contains textures/sounds, the program will extract them and create a list of files named 'index.txt'.\n");
                Console.WriteLine("Extracting an NjUtil archive: ArchiveTool -nju <archivefile>\n");
                Console.WriteLine("Converting PVM/GVM to a folder texture pack: ArchiveTool -png <archivefile>\n");
                Console.WriteLine("Creating a PB archive from a folder with textures: ArchiveTool -pb <foldername>");
                Console.WriteLine("Creating a PVM/GVM/DAT/PVMX from a folder with textures/sounds: ArchiveTool <foldername> [-prs]\nThe program will create an archive from files listed in 'index.txt' in the folder.\nThe -prs option will make the program output a PRS compressed archive.\n");
                Console.WriteLine("Creating a PVM from PNG textures: ArchiveTool -pvm <folder> [-prs]\nThe texture list 'index.txt' must contain global indices listed before each texture filename for this option to work.\n");
                Console.WriteLine("Converting GVM to PVM (lossy): ArchiveTool -gvm2pvm <file.gvm> [-prs]\n");
                Console.WriteLine("Creating a PRS compressed binary: ArchiveTool <file.bin>\nFile extension must be .BIN for this option to work.\n");
                Console.WriteLine("Press ENTER to exit.");
                Console.ReadLine();
                return;
            }
            switch (args[0].ToLowerInvariant())
            {
            // GVM2PVM mode
            case "-gvm2pvm":
                filePath = args[1];
                isPRS    = false;
                if (args.Length > 2 && args[2] == "-prs")
                {
                    isPRS = true;
                }
                Console.WriteLine("Converting GVM to PVM: {0}", filePath);
                directoryName = Path.GetDirectoryName(filePath);
                extension     = Path.GetExtension(filePath).ToLowerInvariant();
                if (!File.Exists(filePath))
                {
                    Console.WriteLine("Supplied GVM archive does not exist!");
                    Console.WriteLine("Press ENTER to exit.");
                    Console.ReadLine();
                    return;
                }
                if (extension != ".gvm")
                {
                    Console.WriteLine("GVM2PVM mode can only be used with GVM files.");
                    Console.WriteLine("Press ENTER to exit.");
                    Console.ReadLine();
                    return;
                }
                path = Path.Combine(directoryName, Path.GetFileNameWithoutExtension(filePath));
                Directory.CreateDirectory(path);
                filedata = File.ReadAllBytes(filePath);
                using (TextWriter texList = File.CreateText(Path.Combine(path, Path.GetFileName(path) + ".txt")))
                {
                    try
                    {
                        ArchiveBase gvmfile = null;
                        byte[]      gvmdata = File.ReadAllBytes(filePath);
                        gvmfile = new GvmArchive();
                        ArchiveReader gvmReader = gvmfile.Open(gvmdata);
                        Stream        pvmStream = File.Open(Path.ChangeExtension(filePath, ".pvm"), FileMode.Create);
                        pvmArchive = new PvmArchive();
                        pvmWriter  = pvmArchive.Create(pvmStream);
                        foreach (ArchiveEntry file in gvmReader.Entries)
                        {
                            if (!File.Exists(Path.Combine(path, file.Name)))
                            {
                                gvmReader.ExtractToFile(file, Path.Combine(path, file.Name));
                            }
                            Stream    data        = File.Open(Path.Combine(path, file.Name), FileMode.Open);
                            VrTexture vrfile      = new GvrTexture(data);
                            Bitmap    tempTexture = vrfile.ToBitmap();
                            System.Drawing.Imaging.BitmapData bmpd = tempTexture.LockBits(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                            int    stride = bmpd.Stride;
                            byte[] bits   = new byte[Math.Abs(stride) * bmpd.Height];
                            System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length);
                            tempTexture.UnlockBits(bmpd);
                            int tlevels = 0;
                            archiveName = Path.GetFileNameWithoutExtension(filePath);
                            for (int y = 0; y < tempTexture.Height; y++)
                            {
                                int srcaddr = y * Math.Abs(stride);
                                for (int x = 0; x < tempTexture.Width; x++)
                                {
                                    Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4)));
                                    if (c.A == 0)
                                    {
                                        tlevels = 1;
                                    }
                                    else if (c.A < 255)
                                    {
                                        tlevels = 2;
                                        break;
                                    }
                                }
                                if (tlevels == 2)
                                {
                                    break;
                                }
                            }
                            PvrPixelFormat ppf = PvrPixelFormat.Rgb565;
                            if (tlevels == 1)
                            {
                                ppf = PvrPixelFormat.Argb1555;
                            }
                            else if (tlevels == 2)
                            {
                                ppf = PvrPixelFormat.Argb4444;
                            }
                            PvrDataFormat pdf;
                            if (!vrfile.HasMipmaps)
                            {
                                if (tempTexture.Width == tempTexture.Height)
                                {
                                    pdf = PvrDataFormat.SquareTwiddled;
                                }
                                else
                                {
                                    pdf = PvrDataFormat.Rectangle;
                                }
                            }
                            else
                            {
                                if (tempTexture.Width == tempTexture.Height)
                                {
                                    pdf = PvrDataFormat.SquareTwiddledMipmaps;
                                }
                                else
                                {
                                    pdf = PvrDataFormat.RectangleTwiddled;
                                }
                            }
                            PvrTextureEncoder encoder = new PvrTextureEncoder(tempTexture, ppf, pdf);
                            encoder.GlobalIndex = vrfile.GlobalIndex;
                            string pvrPath = Path.ChangeExtension(Path.Combine(path, file.Name), ".pvr");
                            if (!File.Exists(pvrPath))
                            {
                                encoder.Save(pvrPath);
                            }
                            data.Close();
                            File.Delete(Path.Combine(path, file.Name));
                            pvmWriter.CreateEntryFromFile(pvrPath);
                            texList.WriteLine(Path.GetFileName(pvrPath));
                            Console.WriteLine("Adding texture {0}", pvrPath);
                        }
                        pvmWriter.Flush();
                        pvmStream.Flush();
                        pvmStream.Close();
                        if (isPRS)
                        {
                            Console.WriteLine("Compressing to PRS...");
                            byte[] pvmdata = File.ReadAllBytes(Path.ChangeExtension(filePath, ".pvm"));
                            pvmdata = FraGag.Compression.Prs.Compress(pvmdata);
                            File.WriteAllBytes(Path.ChangeExtension(filePath, ".PVM.PRS"), pvmdata);
                            File.Delete(Path.ChangeExtension(filePath, ".PVM"));
                        }
                        Console.WriteLine("Archive converted!");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception thrown: {0}", ex.ToString());
                        Console.WriteLine("Press ENTER to exit.");
                        Console.ReadLine();
                        return;
                    }
                }
                break;

            // CompilePVM mode
            case "-pvm":
                bool IsPRS = false;
                if (args[args.Length - 1] == "-prs")
                {
                    IsPRS = true;
                }
                filePath = args[1];
                string            FullLine;
                string            texturename;
                uint              GBIX             = 0;
                List <string>     textureNames     = new List <String>();
                List <PvrTexture> finalTextureList = new List <PvrTexture>();
                directoryName = Path.GetDirectoryName(filePath);
                archiveName   = Path.GetFileNameWithoutExtension(filePath);
                if (Directory.Exists(filePath))
                {
                    Console.WriteLine("Converting texture pack to PVM: {0}", filePath);
                    StreamReader texlistStream = File.OpenText(Path.Combine(filePath, "index.txt"));
                    while (!texlistStream.EndOfStream)
                    {
                        textureNames.Add(texlistStream.ReadLine());
                    }
                    pvmArchive = new PvmArchive();
                    Stream pvmStream = File.Open(Path.ChangeExtension(filePath, ".pvm"), FileMode.Create);
                    pvmWriter = (PvmArchiveWriter)pvmArchive.Create(pvmStream);
                    // Reading in textures
                    for (uint imgIndx = 0; imgIndx < textureNames.Count; imgIndx++)
                    {
                        FullLine = textureNames[(int)imgIndx];
                        if (string.IsNullOrEmpty(FullLine))
                        {
                            continue;
                        }
                        String[] substrings = FullLine.Split(',');
                        GBIX        = UInt32.Parse(substrings[0]);
                        texturename = substrings[1];
                        Bitmap tempTexture = new Bitmap(8, 8);
                        string texturePath = Path.Combine(filePath, Path.ChangeExtension(texturename, ".png"));
                        if (File.Exists(texturePath))
                        {
                            Console.WriteLine("Adding texture: " + (texturePath));
                            tempTexture = (Bitmap)Bitmap.FromFile(texturePath);
                            tempTexture = tempTexture.Clone(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                        }
                        else
                        {
                            Console.WriteLine(String.Concat("Texture ", textureNames[(int)imgIndx], " not found. Generating a placeholder. Check your files."));
                        }

                        System.Drawing.Imaging.BitmapData bmpd = tempTexture.LockBits(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                        int    stride = bmpd.Stride;
                        byte[] bits   = new byte[Math.Abs(stride) * bmpd.Height];
                        System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length);
                        tempTexture.UnlockBits(bmpd);
                        int tlevels = 0;
                        for (int y = 0; y < tempTexture.Height; y++)
                        {
                            int srcaddr = y * Math.Abs(stride);
                            for (int x = 0; x < tempTexture.Width; x++)
                            {
                                Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4)));
                                if (c.A == 0)
                                {
                                    tlevels = 1;
                                }
                                else if (c.A < 255)
                                {
                                    tlevels = 2;
                                    break;
                                }
                            }
                            if (tlevels == 2)
                            {
                                break;
                            }
                        }
                        PvrPixelFormat ppf = PvrPixelFormat.Rgb565;
                        if (tlevels == 1)
                        {
                            ppf = PvrPixelFormat.Argb1555;
                        }
                        else if (tlevels == 2)
                        {
                            ppf = PvrPixelFormat.Argb4444;
                        }
                        PvrDataFormat pdf = PvrDataFormat.Rectangle;
                        if (tempTexture.Width == tempTexture.Height)
                        {
                            pdf = PvrDataFormat.SquareTwiddled;
                        }
                        PvrTextureEncoder encoder = new PvrTextureEncoder(tempTexture, ppf, pdf);
                        encoder.GlobalIndex = GBIX;
                        string pvrPath = Path.ChangeExtension(texturePath, ".pvr");
                        encoder.Save(pvrPath);
                        pvmWriter.CreateEntryFromFile(pvrPath);
                    }
                    pvmWriter.Flush();
                    pvmStream.Close();
                    if (IsPRS)
                    {
                        Console.WriteLine("Compressing to PRS...");
                        byte[] pvmdata = File.ReadAllBytes(Path.ChangeExtension(filePath, ".pvm"));
                        pvmdata = FraGag.Compression.Prs.Compress(pvmdata);
                        File.WriteAllBytes(Path.ChangeExtension(filePath, ".prs"), pvmdata);
                        File.Delete(Path.ChangeExtension(filePath, ".pvm"));
                    }
                    Console.WriteLine("Archive was compiled successfully!");
                }
                else
                {
                    Console.WriteLine("Supplied texture list does not exist!");
                    Console.WriteLine("Press ENTER to continue...");
                    Console.ReadLine();
                    return;
                }
                break;

            // Create PB mode
            case "-pb":
                filePath = args[1];
                Console.WriteLine("Building PB from folder: {0}", filePath);
                if (Directory.Exists(filePath))
                {
                    string indexfilename = Path.Combine(filePath, "index.txt");
                    if (!File.Exists(indexfilename))
                    {
                        Console.WriteLine("Supplied path does not have an index file.");
                        Console.WriteLine("Press ENTER to exit.");
                        Console.ReadLine();
                        return;
                    }
                    List <string> filenames = new List <string>(File.ReadAllLines(indexfilename).Where(a => !string.IsNullOrEmpty(a)));
                    PBFile        pba       = new PBFile(filenames.Count);
                    int           l         = 0;
                    foreach (string tex in filenames)
                    {
                        byte[] texbytes = File.ReadAllBytes(Path.Combine(filePath, tex));
                        pba.AddPVR(texbytes, l);
                        l++;
                    }
                    path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(filePath)), Path.GetFileNameWithoutExtension(filePath));
                    string filename_full = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(filePath)), Path.GetFileName(filePath) + ".pb");
                    Console.WriteLine("Output file: {0}", filename_full);
                    File.WriteAllBytes(filename_full, pba.GetBytes());
                }
                else
                {
                    Console.WriteLine("Supplied path does not exist.");
                    Console.WriteLine("Press ENTER to exit.");
                    Console.ReadLine();
                    return;
                }
                break;

            // Extract NjArchive mode
            case "-nju":
                filePath = args[1];
                filedata = File.ReadAllBytes(filePath);
                if (Path.GetExtension(filePath).Equals(".prs", StringComparison.OrdinalIgnoreCase))
                {
                    filedata = FraGag.Compression.Prs.Decompress(filedata);
                }
                NjArchive njarc = new NjArchive(filedata);
                Console.WriteLine("Extracting Ninja archive: {0}", filePath);
                dir = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
                Console.WriteLine("Output folder: {0}", dir);
                Directory.CreateDirectory(dir);
                for (int i = 0; i < njarc.Entries.Count; i++)
                {
                    byte[] data = njarc.Entries[i];
                    extension = ".bin";
                    string desc = "Unknown";
                    switch (System.Text.Encoding.ASCII.GetString(data, 0, 4))
                    {
                    case "NJIN":
                        desc      = "Ninja Information";
                        extension = ".nji";
                        break;

                    case "NJCM":
                        desc      = "Ninja Chunk model";
                        extension = ".nj";
                        break;

                    case "GJCM":
                        desc      = "Ninja Chunk model (GC)";
                        extension = ".gj";
                        break;

                    case "NJBM":
                        desc      = "Ninja Basic model";
                        extension = ".nj";
                        break;

                    case "NMDM":
                        desc      = "Ninja Motion";
                        extension = ".njm";
                        break;

                    case "NJLI":
                        desc      = "Ninja Light";
                        extension = ".njl";
                        break;

                    case "NLIM":
                        desc      = "Ninja Light Motion";
                        extension = ".njlm";
                        break;

                    case "NSSM":
                        desc      = "Ninja Simple Shape Motion";
                        extension = ".njsm";
                        break;

                    case "NCAM":
                        desc      = "Ninja Camera Motion";
                        extension = ".ncm";
                        break;

                    case "NJTL":
                        desc      = "Ninja Texlist";
                        extension = ".nj";
                        break;

                    case "GJTL":
                        desc      = "Ninja Texlist (GC)";
                        extension = ".gj";
                        break;

                    case "PVMH":
                        desc      = "PVM";
                        extension = ".pvm";
                        break;

                    case "GVMH":
                        desc      = "GVM";
                        extension = ".gvm";
                        break;
                    }
                    Console.WriteLine("Entry {0} is {1}", i, desc);
                    string outpath = Path.Combine(dir, i.ToString("D3") + extension);
                    File.WriteAllBytes(outpath, njarc.Entries[i]);
                }
                break;

            // PVM2TexPack mode
            case "-png":
                Queue <string> files = new Queue <string>();
                for (int u = 1; u < args.Length; u++)
                {
                    files.Enqueue(args[u]);
                }
                if (files.Count == 0)
                {
                    Console.Write("File: ");
                    files.Enqueue(Console.ReadLine());
                }
                while (files.Count > 0)
                {
                    string filename = files.Dequeue();
                    path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(filename)), Path.GetFileNameWithoutExtension(filename));
                    string filename_full = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(filename)), Path.GetFileName(filename));
                    Console.WriteLine("Converting file to texture pack: {0}", filename_full);
                    Directory.CreateDirectory(path);
                    filedata = File.ReadAllBytes(filename_full);
                    using (TextWriter texList = File.CreateText(Path.Combine(path, "index.txt")))
                    {
                        try
                        {
                            if (PvrTexture.Is(filedata))
                            {
                                if (!AddTexture(false, path, Path.GetFileName(filename_full), new MemoryStream(filedata), texList))
                                {
                                    texList.Close();
                                    Directory.Delete(path, true);
                                }
                                continue;
                            }
                            else if (GvrTexture.Is(filedata))
                            {
                                if (!AddTexture(true, path, Path.GetFileName(filename_full), new MemoryStream(filedata), texList))
                                {
                                    texList.Close();
                                    Directory.Delete(path, true);
                                }
                                continue;
                            }
                            bool        gvm     = false;
                            ArchiveBase pvmfile = null;
                            byte[]      pvmdata = File.ReadAllBytes(filename_full);
                            if (Path.GetExtension(filename_full).Equals(".prs", StringComparison.OrdinalIgnoreCase))
                            {
                                pvmdata = FraGag.Compression.Prs.Decompress(pvmdata);
                            }
                            pvmfile = new PvmArchive();
                            MemoryStream stream = new MemoryStream(pvmdata);
                            if (!PvmArchive.Identify(stream))
                            {
                                pvmfile = new GvmArchive();
                                gvm     = true;
                            }
                            ArchiveEntryCollection pvmentries = pvmfile.Open(pvmdata).Entries;
                            bool fail = false;
                            foreach (ArchiveEntry file in pvmentries)
                            {
                                if (!AddTexture(gvm, path, file.Name, file.Open(), texList))
                                {
                                    texList.Close();
                                    Directory.Delete(path, true);
                                    fail = true;
                                    break;
                                }
                            }
                            if (fail)
                            {
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Exception thrown: " + ex.ToString() + "\nCanceling conversion.");
                            return;
                        }
                        Console.WriteLine("Conversion complete!");
                    }
                }
                break;

            // Other modes
            default:
                filePath = args[0];
                IsPRS    = false;
                if (args.Length > 1 && args[1] == "-prs")
                {
                    IsPRS = true;
                }
                extension = Path.GetExtension(filePath).ToLowerInvariant();
                //Folder mode
                if (Directory.Exists(filePath))
                {
                    string        indexfilename = Path.Combine(filePath, "index.txt");
                    List <string> filenames     = new List <string>(File.ReadAllLines(indexfilename).Where(a => !string.IsNullOrEmpty(a)));
                    string        ext           = Path.GetExtension(filenames[0]).ToLowerInvariant();
                    pvmArchive = new PvmArchive();
                    switch (ext)
                    {
                    case ".pvr":
                        folderMode = ArchiveFromFolderMode.PVM;
                        break;

                    case ".gvr":
                        pvmArchive = new GvmArchive();
                        folderMode = ArchiveFromFolderMode.GVM;
                        break;

                    case ".wav":
                        folderMode = ArchiveFromFolderMode.DAT;
                        break;

                    case ".png":
                    case ".jpg":
                    case ".bmp":
                    case ".dds":
                    case ".gif":
                    default:
                        folderMode = ArchiveFromFolderMode.PVMX;
                        break;
                    }
                    Console.WriteLine("Creating {0} archive from folder: {1}", folderMode.ToString(), filePath);
                    switch (folderMode)
                    {
                    case ArchiveFromFolderMode.DAT:
                        // Load index
                        DATFile    dat  = new DATFile();
                        TextReader tr   = File.OpenText(Path.Combine(filePath, "index.txt"));
                        string     line = tr.ReadLine();
                        while (line != null)
                        {
                            Console.WriteLine("Adding file {0}", Path.Combine(filePath, line));
                            dat.AddFile(Path.Combine(filePath, line));
                            line = tr.ReadLine();
                        }
                        tr.Close();
                        // Save DAT archive
                        File.WriteAllBytes(filePath + ".DAT", dat.GetBytes());
                        if (IsPRS)
                        {
                            Console.WriteLine("Compressing to PRS...");
                            byte[] datdata = File.ReadAllBytes(filePath + ".DAT");
                            datdata = FraGag.Compression.Prs.Compress(datdata);
                            File.WriteAllBytes(filePath + ".PRS", datdata);
                            File.Delete(filePath + ".DAT");
                        }
                        Console.WriteLine("Archive compiled successfully!");
                        return;

                    case ArchiveFromFolderMode.PVM:
                    case ArchiveFromFolderMode.GVM:
                        if (filenames.Any(a => !Path.GetExtension(a).Equals(ext, StringComparison.OrdinalIgnoreCase)))
                        {
                            Console.WriteLine("Cannot create archive from mixed file types.");
                            Console.WriteLine("Press ENTER to exit.");
                            Console.ReadLine();
                            return;
                        }
                        ext = folderMode == ArchiveFromFolderMode.PVM ? ".pvm" : ".gvm";
                        using (Stream pvmStream = File.Open(Path.ChangeExtension(filePath, ext), FileMode.Create))
                        {
                            pvmWriter = pvmArchive.Create(pvmStream);
                            // Reading in textures
                            foreach (string tex in filenames)
                            {
                                if (folderMode == ArchiveFromFolderMode.PVM)
                                {
                                    pvmWriter.CreateEntryFromFile(Path.Combine(filePath, Path.ChangeExtension(tex, ".pvr")));
                                }
                                else
                                {
                                    pvmWriter.CreateEntryFromFile(Path.Combine(filePath, Path.ChangeExtension(tex, ".gvr")));
                                }
                                Console.WriteLine("Adding file: {0}", tex);
                            }
                            pvmWriter.Flush();
                        }
                        if (IsPRS)
                        {
                            Console.WriteLine("Compressing to PRS...");
                            byte[] pvmdata = File.ReadAllBytes(Path.ChangeExtension(filePath, ext));
                            pvmdata = FraGag.Compression.Prs.Compress(pvmdata);
                            File.WriteAllBytes(Path.ChangeExtension(filePath, ".prs"), pvmdata);
                            File.Delete(Path.ChangeExtension(filePath, ext));
                        }
                        Console.WriteLine("Archive was compiled successfully!");
                        return;

                    case ArchiveFromFolderMode.PVMX:
                        // Load index
                        PVMXFile   pvmx = new PVMXFile();
                        TextReader trp  = File.OpenText(Path.Combine(filePath, "index.txt"));
                        foreach (string str in filenames)
                        {
                            string[] split   = str.Split(',');
                            string   texfile = Path.Combine(Path.GetFullPath(filePath), split[1]);
                            Console.WriteLine("Adding file {0}", texfile);
                            if (split.Length > 2)
                            {
                                string[] dimensions = split[2].Split('x');
                                pvmx.AddFile(split[1], uint.Parse(split[0]), File.ReadAllBytes(texfile), int.Parse(dimensions[0]), int.Parse(dimensions[1]));
                            }
                            else
                            {
                                pvmx.AddFile(split[1], uint.Parse(split[0]), File.ReadAllBytes(texfile));
                            }
                        }
                        Console.WriteLine("Output file: {0}", Path.ChangeExtension(filePath, ".pvmx"));
                        File.WriteAllBytes(Path.ChangeExtension(filePath, ".pvmx"), pvmx.GetBytes());
                        Console.WriteLine("Archive was compiled successfully!");
                        return;
                    }
                }
                //Continue with file mode otherwise
                if (!File.Exists(filePath))
                {
                    Console.WriteLine("Supplied archive/texture list does not exist!");
                    Console.WriteLine("Press ENTER to exit.");
                    Console.ReadLine();
                    return;
                }
                switch (extension)
                {
                case ".rel":
                    Console.WriteLine("Decompressing REL file: {0}", filePath);
                    byte[] input  = File.ReadAllBytes(args[0]);
                    byte[] output = SA_Tools.HelperFunctions.DecompressREL(input);
                    File.WriteAllBytes(Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath) + "_dec.rel"), output);
                    return;

                case ".dat":
                    Console.WriteLine("Extracting DAT file: {0}", filePath);
                    DATFile dat = new DATFile(File.ReadAllBytes(filePath));
                    dir = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
                    if (Directory.Exists(dir))
                    {
                        Directory.Delete(dir, true);
                    }
                    Directory.CreateDirectory(dir);
                    using (StreamWriter sw = File.CreateText(Path.Combine(dir, "index.txt")))
                    {
                        dat.Entries.Sort((f1, f2) => StringComparer.OrdinalIgnoreCase.Compare(f1.name, f2.name));
                        for (int i = 0; i < dat.GetCount(); i++)
                        {
                            string fname = dat.Entries[i].name;
                            sw.WriteLine(fname);
                            if (dat.Steam)
                            {
                                fname = Path.GetFileNameWithoutExtension(fname) + ".adx";
                            }
                            Console.WriteLine("Extracting file: {0}", fname);
                            File.WriteAllBytes(Path.Combine(dir, fname), dat.GetFile(i));
                        }
                        sw.Flush();
                        sw.Close();
                    }
                    Console.WriteLine("Archive extracted!");
                    break;

                case ".pvmx":
                    Console.WriteLine("Extracting PVMX file: {0}", filePath);
                    byte[] pvmxdata = File.ReadAllBytes(filePath);
                    dir = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
                    Directory.CreateDirectory(dir);
                    PVMXFile pvmx = new PVMXFile(pvmxdata);
                    using (TextWriter texList = File.CreateText(Path.Combine(dir, "index.txt")))
                    {
                        for (int u = 0; u < pvmx.GetCount(); u++)
                        {
                            byte[] tdata   = pvmx.GetFile(u);
                            string outpath = Path.Combine(dir, pvmx.GetName(u));
                            File.WriteAllBytes(outpath, tdata);
                            string entry;
                            string dimensions = string.Join("x", pvmx.GetWidth(u).ToString(), pvmx.GetHeight(u).ToString());
                            if (pvmx.HasDimensions(u))
                            {
                                entry = string.Join(",", pvmx.GetGBIX(u).ToString(), pvmx.GetName(u), dimensions);
                            }
                            else
                            {
                                entry = string.Join(",", pvmx.GetGBIX(u).ToString(), pvmx.GetName(u));
                            }
                            texList.WriteLine(entry);
                        }
                        texList.Flush();
                        texList.Close();
                    }
                    Console.WriteLine("Archive extracted!");
                    break;

                case ".pb":
                    Console.WriteLine("Extracting PB file: {0}", filePath);
                    byte[] pbdata = File.ReadAllBytes(filePath);
                    dir = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
                    Directory.CreateDirectory(dir);
                    PBFile pba = new PBFile(pbdata);
                    using (TextWriter texList = File.CreateText(Path.Combine(dir, "index.txt")))
                    {
                        for (int u = 0; u < pba.GetCount(); u++)
                        {
                            byte[] pvrt    = pba.GetPVR(u);
                            string outpath = Path.Combine(dir, u.ToString("D3") + ".pvr");
                            File.WriteAllBytes(outpath, pvrt);
                            texList.WriteLine(u.ToString("D3") + ".pvr");
                        }
                        texList.Flush();
                        texList.Close();
                    }
                    Console.WriteLine("Archive extracted!");
                    break;

                case ".bin":
                    Console.WriteLine("Compressing BIN file: {0}", filePath);
                    byte[] bindata = File.ReadAllBytes(Path.ChangeExtension(filePath, ".bin"));
                    bindata = FraGag.Compression.Prs.Compress(bindata);
                    File.WriteAllBytes(Path.ChangeExtension(filePath, ".prs"), bindata);
                    Console.WriteLine("PRS archive was compiled successfully!");
                    return;

                case ".prs":
                case ".pvm":
                case ".gvm":
                    Console.WriteLine("Extracting archive: {0}", filePath);
                    path = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
                    Directory.CreateDirectory(path);
                    filedata = File.ReadAllBytes(filePath);
                    using (TextWriter texList = File.CreateText(Path.Combine(path, "index.txt")))
                    {
                        try
                        {
                            ArchiveBase pvmfile = null;
                            byte[]      pvmdata = File.ReadAllBytes(filePath);
                            if (extension == ".prs")
                            {
                                pvmdata = FraGag.Compression.Prs.Decompress(pvmdata);
                            }
                            pvmfile = new PvmArchive();
                            MemoryStream stream = new MemoryStream(pvmdata);
                            if (!PvmArchive.Identify(stream))
                            {
                                pvmfile = new GvmArchive();
                                if (!GvmArchive.Identify(stream))
                                {
                                    File.WriteAllBytes(Path.ChangeExtension(filePath, ".bin"), pvmdata);
                                    isBIN = true;
                                    Console.WriteLine("PRS archive extracted!");
                                }
                            }
                            if (!isBIN)
                            {
                                ArchiveReader pvmReader = pvmfile.Open(pvmdata);
                                foreach (ArchiveEntry pvmentry in pvmReader.Entries)
                                {
                                    Console.WriteLine("Extracting file: {0}", pvmentry.Name);
                                    texList.WriteLine(pvmentry.Name);
                                    pvmReader.ExtractToFile(pvmentry, Path.Combine(path, pvmentry.Name));
                                }
                                Console.WriteLine("Archive extracted!");
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Exception thrown. Canceling conversion.");
                            Console.WriteLine("Press ENTER to exit.");
                            Console.ReadLine();
                            Directory.Delete(path, true);
                            throw;
                        }
                    }
                    if (isBIN)
                    {
                        Directory.Delete(path, true);
                    }
                    break;

                default:
                    Console.WriteLine("Unknown extension \"{0}\".", extension);
                    Console.WriteLine("Press ENTER to exit.");
                    Console.ReadLine();
                    break;
                }
                break;
            }
        }
Exemple #4
0
        public static void Encode(string[] args)
        {
            string outPath        = Path.ChangeExtension(args[1], ".pvr");
            string outPalettePath = Path.ChangeExtension(args[1], ".pvp");

            PvrTextureEncoder texture = new PvrTextureEncoder(args[1], StringToPixelFormat(args[3]), StringToDataFormat(args[4]));

            // Was this texture initalized successfully
            if (!texture.Initalized)
            {
                Console.WriteLine("Error: Unable to encode using the specified texture.");
                return;
            }

            // Get arguments
            for (int i = 5; i < args.Length; i++)
            {
                string arg = args[i].ToLower();

                // Change the output path
                if (arg == "-o" && args.Length > i + 1)
                {
                    outPath = args[i + 1];
                    i++;
                }

                // Change the output path for the palette
                if (arg == "-op" && args.Length > i + 1)
                {
                    outPalettePath = args[i + 1];
                    i++;
                }

                // No global index
                if (arg == "-nogbix")
                {
                    texture.HasGlobalIndex = false;
                }

                // Set global index
                if (arg == "-gi" && args.Length > i + 1)
                {
                    uint globalIndex;
                    if (!uint.TryParse(args[i + 1], out globalIndex))
                    {
                        globalIndex = 0;
                    }
                    texture.GlobalIndex = globalIndex;

                    i++;
                }

                // Set compression format
                if (arg == "-cmp" && args.Length > i + 1)
                {
                    texture.CompressionFormat = StringToCompressionFormat(args[i + 1]);
                    i++;
                }
            }

            Console.WriteLine("Texture Information");
            Console.WriteLine("--------------------");
            Console.WriteLine("Format       : PVR");
            if (texture.HasGlobalIndex)
            {
                Console.WriteLine("Global Index : {0}", texture.GlobalIndex);
            }
            Console.WriteLine("Dimensions   : {0}x{1}", texture.TextureWidth, texture.TextureHeight);
            Console.WriteLine("Pixel Format : {0}", PixelFormatToString(texture.PixelFormat));
            Console.WriteLine("Data Format  : {0}", DataFormatToString(texture.DataFormat));
            if (texture.CompressionFormat != PvrCompressionFormat.None)
            {
                Console.WriteLine("Compression  : {0}", CompressionFormatToString(texture.CompressionFormat));
            }

            texture.Save(outPath);

            if (texture.NeedsExternalPalette)
            {
                texture.PaletteEncoder.Save(outPalettePath);
            }

            Console.WriteLine("\nTexture encoded successfully.");
        }
Exemple #5
0
 private void SaveTextures()
 {
     byte[] data;
     using (MemoryStream str = new MemoryStream())
     {
         PvmArchiveWriter writer = new PvmArchiveWriter(str);
         foreach (TextureInfo tex in textures)
         {
             if (tex.DataFormat != PvrDataFormat.Index4 && tex.DataFormat != PvrDataFormat.Index8)
             {
                 System.Drawing.Imaging.BitmapData bmpd = tex.Image.LockBits(new Rectangle(Point.Empty, tex.Image.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                 int    stride = bmpd.Stride;
                 byte[] bits   = new byte[Math.Abs(stride) * bmpd.Height];
                 System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length);
                 tex.Image.UnlockBits(bmpd);
                 int tlevels = 0;
                 for (int y = 0; y < tex.Image.Height; y++)
                 {
                     int srcaddr = y * Math.Abs(stride);
                     for (int x = 0; x < tex.Image.Width; x++)
                     {
                         Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4)));
                         if (c.A == 0)
                         {
                             tlevels = 1;
                         }
                         else if (c.A < 255)
                         {
                             tlevels = 2;
                             break;
                         }
                     }
                     if (tlevels == 2)
                     {
                         break;
                     }
                 }
                 if (tlevels == 0)
                 {
                     tex.PixelFormat = PvrPixelFormat.Rgb565;
                 }
                 else if (tlevels == 1)
                 {
                     tex.PixelFormat = PvrPixelFormat.Argb1555;
                 }
                 else if (tlevels == 2)
                 {
                     tex.PixelFormat = PvrPixelFormat.Argb4444;
                 }
                 if (tex.Image.Width == tex.Image.Height)
                 {
                     if (tex.Mipmap)
                     {
                         tex.DataFormat = PvrDataFormat.SquareTwiddledMipmaps;
                     }
                     else
                     {
                         tex.DataFormat = PvrDataFormat.SquareTwiddled;
                     }
                 }
                 else
                 {
                     tex.DataFormat = PvrDataFormat.Rectangle;
                 }
             }
             PvrTextureEncoder encoder = new PvrTextureEncoder(tex.Image, tex.PixelFormat, tex.DataFormat);
             encoder.GlobalIndex = tex.GlobalIndex;
             MemoryStream pvr = new MemoryStream();
             encoder.Save(pvr);
             pvr.Seek(0, SeekOrigin.Begin);
             writer.CreateEntry(pvr, tex.Name);
         }
         writer.Flush();
         data = str.ToArray();
         str.Close();
     }
     if (Path.GetExtension(filename).Equals(".prs", StringComparison.OrdinalIgnoreCase))
     {
         FraGag.Compression.Prs.Compress(data, filename);
     }
     else
     {
         File.WriteAllBytes(filename, data);
     }
 }
        /// <summary>
        /// Convert a GBIX indexed texture pack to PVM.
        /// </summary>
        static void TexPack2PVM(string[] args)
        {
            bool compressPRS = false;

            if (args[args.Length - 1] == "-prs")
            {
                compressPRS = true;
            }
            filePath = args[1];
            string            FullLine;
            string            texturename;
            uint              GBIX             = 0;
            List <string>     textureNames     = new List <String>();
            List <PvrTexture> finalTextureList = new List <PvrTexture>();

            directoryName = Path.GetDirectoryName(filePath);
            string archiveName = Path.GetFileNameWithoutExtension(filePath);

            if (Directory.Exists(filePath))
            {
                Console.WriteLine("Converting texture pack to PVM: {0}", Path.GetFullPath(filePath));
                StreamReader texlistStream = File.OpenText(Path.Combine(filePath, "index.txt"));
                while (!texlistStream.EndOfStream)
                {
                    textureNames.Add(texlistStream.ReadLine());
                }
                PuyoFile puyo = new PuyoFile();
                outputPath = Path.ChangeExtension(filePath, ".pvm");
                // Reading in textures
                for (uint imgIndx = 0; imgIndx < textureNames.Count; imgIndx++)
                {
                    FullLine = textureNames[(int)imgIndx];
                    if (string.IsNullOrEmpty(FullLine))
                    {
                        continue;
                    }
                    string[] substrings = FullLine.Split(',');
                    GBIX        = UInt32.Parse(substrings[0]);
                    texturename = substrings[1];
                    Bitmap tempTexture = new Bitmap(8, 8);
                    string texturePath = Path.Combine(filePath, Path.ChangeExtension(texturename, ".png"));
                    if (File.Exists(texturePath))
                    {
                        Console.WriteLine("Adding texture: " + (texturePath));
                        tempTexture = (Bitmap)Bitmap.FromFile(texturePath);
                        tempTexture = tempTexture.Clone(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    }
                    else
                    {
                        Console.WriteLine(string.Concat("Texture ", textureNames[(int)imgIndx], " not found. Generating a placeholder. Check your files."));
                    }

                    System.Drawing.Imaging.BitmapData bmpd = tempTexture.LockBits(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    int    stride = bmpd.Stride;
                    byte[] bits   = new byte[Math.Abs(stride) * bmpd.Height];
                    System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length);
                    tempTexture.UnlockBits(bmpd);
                    int tlevels = 0;
                    for (int y = 0; y < tempTexture.Height; y++)
                    {
                        int srcaddr = y * Math.Abs(stride);
                        for (int x = 0; x < tempTexture.Width; x++)
                        {
                            Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4)));
                            if (c.A == 0)
                            {
                                tlevels = 1;
                            }
                            else if (c.A < 255)
                            {
                                tlevels = 2;
                                break;
                            }
                        }
                        if (tlevels == 2)
                        {
                            break;
                        }
                    }
                    PvrPixelFormat ppf = PvrPixelFormat.Rgb565;
                    if (tlevels == 1)
                    {
                        ppf = PvrPixelFormat.Argb1555;
                    }
                    else if (tlevels == 2)
                    {
                        ppf = PvrPixelFormat.Argb4444;
                    }
                    PvrDataFormat pdf = PvrDataFormat.Rectangle;
                    if (tempTexture.Width == tempTexture.Height)
                    {
                        pdf = PvrDataFormat.SquareTwiddled;
                    }
                    PvrTextureEncoder encoder = new PvrTextureEncoder(tempTexture, ppf, pdf);
                    encoder.GlobalIndex = GBIX;
                    string pvrPath = Path.ChangeExtension(texturePath, ".pvr");
                    encoder.Save(pvrPath);
                    puyo.Entries.Add(new PVMEntry(pvrPath));
                }
                File.WriteAllBytes(outputPath, puyo.GetBytes());
                if (compressPRS)
                {
                    Console.WriteLine("Compressing to PRS...");
                    byte[] pvmdata = File.ReadAllBytes(Path.ChangeExtension(filePath, ".pvm"));
                    pvmdata    = FraGag.Compression.Prs.Compress(pvmdata);
                    outputPath = Path.ChangeExtension(filePath, ".prs");
                    File.WriteAllBytes(outputPath, pvmdata);
                    File.Delete(Path.ChangeExtension(filePath, ".pvm"));
                }
                Console.WriteLine("Output file: {0}", Path.GetFullPath(outputPath));
                Console.WriteLine("Archive was compiled successfully!");
            }
            else
            {
                Console.WriteLine("Supplied texture list does not exist!");
                Console.WriteLine("Press ENTER to continue...");
                Console.ReadLine();
                return;
            }
        }
Exemple #7
0
        static void Main(string[] args)
        {
            string            directoryName;
            string            FullLine;
            string            texturename;
            UInt32            GBIX             = 0;
            List <String>     textureNames     = new List <String>();
            List <PvrTexture> finalTextureList = new List <PvrTexture>();

            if (args.Length == 0)
            {
                Console.WriteLine("Error - no texturelist provided. Provide a path to a texturelist as your first command line argument");
                Console.WriteLine("Press ENTER to continue...");
                Console.ReadLine();
                return;
            }
            String filePath = args[0];

            directoryName = Path.GetDirectoryName(filePath);
            string archiveName = Path.GetFileNameWithoutExtension(filePath);

            if (File.Exists(filePath))
            {
                StreamReader texlistStream = File.OpenText(filePath);
                while (!texlistStream.EndOfStream)
                {
                    textureNames.Add(texlistStream.ReadLine());
                }
                PvmArchive       pvmArchive = new PvmArchive();
                Stream           pvmStream  = File.Open(Path.ChangeExtension(filePath, ".pvm"), FileMode.Create);
                PvmArchiveWriter pvmWriter  = (PvmArchiveWriter)pvmArchive.Create(pvmStream);
                // Reading in textures
                for (uint imgIndx = 0; imgIndx < textureNames.Count; imgIndx++)
                {
                    FullLine = textureNames[(int)imgIndx];
                    if (string.IsNullOrEmpty(FullLine))
                    {
                        continue;
                    }
                    String[] substrings = FullLine.Split(',');
                    GBIX        = UInt32.Parse(substrings[0]);
                    texturename = substrings[1];
                    Bitmap tempTexture = new Bitmap(8, 8);
                    string texturePath = Path.Combine(directoryName, Path.ChangeExtension(texturename, ".png"));
                    if (File.Exists(texturePath))
                    {
                        Console.WriteLine("Adding texture:" + (texturePath));
                        tempTexture = (Bitmap)Bitmap.FromFile(texturePath);
                        tempTexture = tempTexture.Clone(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    }
                    else
                    {
                        Console.WriteLine(String.Concat("Texture ", textureNames[(int)imgIndx], " not found. Generating a placeholder. Check your files."));
                    }

                    System.Drawing.Imaging.BitmapData bmpd = tempTexture.LockBits(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    int    stride = bmpd.Stride;
                    byte[] bits   = new byte[Math.Abs(stride) * bmpd.Height];
                    System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length);
                    tempTexture.UnlockBits(bmpd);
                    int tlevels = 0;
                    for (int y = 0; y < tempTexture.Height; y++)
                    {
                        int srcaddr = y * Math.Abs(stride);
                        for (int x = 0; x < tempTexture.Width; x++)
                        {
                            Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4)));
                            if (c.A == 0)
                            {
                                tlevels = 1;
                            }
                            else if (c.A < 255)
                            {
                                tlevels = 2;
                                break;
                            }
                        }
                        if (tlevels == 2)
                        {
                            break;
                        }
                    }
                    PvrPixelFormat ppf = PvrPixelFormat.Rgb565;
                    if (tlevels == 1)
                    {
                        ppf = PvrPixelFormat.Argb1555;
                    }
                    else if (tlevels == 2)
                    {
                        ppf = PvrPixelFormat.Argb4444;
                    }
                    PvrDataFormat pdf = PvrDataFormat.Rectangle;
                    if (tempTexture.Width == tempTexture.Height)
                    {
                        pdf = PvrDataFormat.SquareTwiddled;
                    }
                    PvrTextureEncoder encoder = new PvrTextureEncoder(tempTexture, ppf, pdf);
                    encoder.GlobalIndex = GBIX;
                    string pvrPath = Path.ChangeExtension(texturePath, ".pvr");
                    encoder.Save(pvrPath);

                    pvmWriter.CreateEntryFromFile(pvrPath);
                }

                pvmWriter.Flush();
                pvmStream.Close();
                Console.WriteLine("PVM was compiled successfully!");
                Console.WriteLine("Press ENTER to continue...");
                Console.ReadLine();
                return;
            }
            else             // error, supplied path is invalid
            {
                Console.WriteLine("Supplied texturelist does not exist!");
                Console.WriteLine("Press ENTER to continue...");
                Console.ReadLine();
                return;
            }
        }
 /// <summary>
 /// Convert GVM to PVM.
 /// </summary>
 static void GVM2PVM(string[] args)
 {
     filePath = args[1];
     if (args.Length > 2 && args[2] == "-prs")
     {
         compressPRS = true;
     }
     Console.WriteLine("Converting GVM to PVM: {0}", filePath);
     directoryName = Path.GetDirectoryName(filePath);
     extension     = Path.GetExtension(filePath).ToLowerInvariant();
     if (!File.Exists(filePath))
     {
         Console.WriteLine("Supplied GVM archive does not exist!");
         Console.WriteLine("Press ENTER to exit.");
         Console.ReadLine();
         return;
     }
     if (extension != ".gvm")
     {
         Console.WriteLine("GVM2PVM mode can only be used with GVM files.");
         Console.WriteLine("Press ENTER to exit.");
         Console.ReadLine();
         return;
     }
     fileNameFromFolder = Path.Combine(directoryName, Path.GetFileNameWithoutExtension(filePath));
     Directory.CreateDirectory(fileNameFromFolder);
     using (TextWriter texList = File.CreateText(Path.Combine(fileNameFromFolder, Path.GetFileName(fileNameFromFolder) + ".txt")))
     {
         try
         {
             PuyoFile gvmFile = new PuyoFile(File.ReadAllBytes(filePath));
             PuyoFile pvmFile = new PuyoFile();
             outputPath = Path.ChangeExtension(filePath, ".pvm");
             foreach (GVMEntry file in gvmFile.Entries)
             {
                 if (!File.Exists(Path.Combine(fileNameFromFolder, file.Name)))
                 {
                     File.WriteAllBytes(Path.Combine(fileNameFromFolder, file.Name), file.Data);
                 }
                 Stream    data        = File.Open(Path.Combine(fileNameFromFolder, file.Name), FileMode.Open);
                 VrTexture vrfile      = new GvrTexture(data);
                 Bitmap    tempTexture = vrfile.ToBitmap();
                 System.Drawing.Imaging.BitmapData bmpd = tempTexture.LockBits(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                 int    stride = bmpd.Stride;
                 byte[] bits   = new byte[Math.Abs(stride) * bmpd.Height];
                 System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length);
                 tempTexture.UnlockBits(bmpd);
                 int tlevels = 0;
                 for (int y = 0; y < tempTexture.Height; y++)
                 {
                     int srcaddr = y * Math.Abs(stride);
                     for (int x = 0; x < tempTexture.Width; x++)
                     {
                         Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4)));
                         if (c.A == 0)
                         {
                             tlevels = 1;
                         }
                         else if (c.A < 255)
                         {
                             tlevels = 2;
                             break;
                         }
                     }
                     if (tlevels == 2)
                     {
                         break;
                     }
                 }
                 PvrPixelFormat ppf = PvrPixelFormat.Rgb565;
                 if (tlevels == 1)
                 {
                     ppf = PvrPixelFormat.Argb1555;
                 }
                 else if (tlevels == 2)
                 {
                     ppf = PvrPixelFormat.Argb4444;
                 }
                 PvrDataFormat pdf;
                 if (!vrfile.HasMipmaps)
                 {
                     if (tempTexture.Width == tempTexture.Height)
                     {
                         pdf = PvrDataFormat.SquareTwiddled;
                     }
                     else
                     {
                         pdf = PvrDataFormat.Rectangle;
                     }
                 }
                 else
                 {
                     if (tempTexture.Width == tempTexture.Height)
                     {
                         pdf = PvrDataFormat.SquareTwiddledMipmaps;
                     }
                     else
                     {
                         pdf = PvrDataFormat.RectangleTwiddled;
                     }
                 }
                 PvrTextureEncoder encoder = new PvrTextureEncoder(tempTexture, ppf, pdf);
                 encoder.GlobalIndex = vrfile.GlobalIndex;
                 string pvrPath = Path.ChangeExtension(Path.Combine(fileNameFromFolder, file.Name), ".pvr");
                 if (!File.Exists(pvrPath))
                 {
                     encoder.Save(pvrPath);
                 }
                 data.Close();
                 File.Delete(Path.Combine(fileNameFromFolder, file.Name));
                 MemoryStream readfile = new MemoryStream(File.ReadAllBytes(pvrPath));
                 pvmFile.Entries.Add(new PVMEntry(pvrPath));
                 texList.WriteLine(Path.GetFileName(pvrPath));
                 Console.WriteLine("Adding texture {0}", pvrPath);
             }
             File.WriteAllBytes(outputPath, pvmFile.GetBytes());
             texList.Flush();
             texList.Close();
         }
         catch (Exception ex)
         {
             Console.WriteLine("Exception thrown: {0}", ex.ToString());
             Console.WriteLine("Press ENTER to exit.");
             Console.ReadLine();
             return;
         }
     }
     if (compressPRS)
     {
         outputPath = Path.ChangeExtension(filePath, ".PVM.PRS");
         Console.WriteLine("Compressing to PRS...");
         byte[] pvmdata = File.ReadAllBytes(Path.ChangeExtension(filePath, ".pvm"));
         pvmdata = FraGag.Compression.Prs.Compress(pvmdata);
         File.WriteAllBytes(outputPath, pvmdata);
         File.Delete(Path.ChangeExtension(filePath, ".PVM"));
     }
     Console.WriteLine("Output file: {0}", Path.GetFullPath(outputPath));
     Console.WriteLine("Archive converted!");
     Directory.Delete(fileNameFromFolder, true);
 }
Exemple #9
0
        private void SaveTextures()
        {
            byte[] data;
            using (MemoryStream str = new MemoryStream())
            {
                ArchiveWriter writer = null;
                switch (format)
                {
                case TextureFormat.PVM:
                    writer = new PvmArchiveWriter(str);
                    foreach (PvrTextureInfo tex in textures)
                    {
                        if (tex.DataFormat != PvrDataFormat.Index4 && tex.DataFormat != PvrDataFormat.Index8)
                        {
                            System.Drawing.Imaging.BitmapData bmpd = tex.Image.LockBits(new Rectangle(Point.Empty, tex.Image.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                            int    stride = bmpd.Stride;
                            byte[] bits   = new byte[Math.Abs(stride) * bmpd.Height];
                            System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length);
                            tex.Image.UnlockBits(bmpd);
                            int tlevels = 0;
                            for (int y = 0; y < tex.Image.Height; y++)
                            {
                                int srcaddr = y * Math.Abs(stride);
                                for (int x = 0; x < tex.Image.Width; x++)
                                {
                                    Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4)));
                                    if (c.A == 0)
                                    {
                                        tlevels = 1;
                                    }
                                    else if (c.A < 255)
                                    {
                                        tlevels = 2;
                                        break;
                                    }
                                }
                                if (tlevels == 2)
                                {
                                    break;
                                }
                            }
                            if (tlevels == 0)
                            {
                                tex.PixelFormat = PvrPixelFormat.Rgb565;
                            }
                            else if (tlevels == 1)
                            {
                                tex.PixelFormat = PvrPixelFormat.Argb1555;
                            }
                            else if (tlevels == 2)
                            {
                                tex.PixelFormat = PvrPixelFormat.Argb4444;
                            }
                            if (tex.Image.Width == tex.Image.Height)
                            {
                                if (tex.Mipmap)
                                {
                                    tex.DataFormat = PvrDataFormat.SquareTwiddledMipmaps;
                                }
                                else
                                {
                                    tex.DataFormat = PvrDataFormat.SquareTwiddled;
                                }
                            }
                            else
                            {
                                tex.DataFormat = PvrDataFormat.Rectangle;
                            }
                        }
                        PvrTextureEncoder encoder = new PvrTextureEncoder(tex.Image, tex.PixelFormat, tex.DataFormat);
                        encoder.GlobalIndex = tex.GlobalIndex;
                        MemoryStream pvr = new MemoryStream();
                        encoder.Save(pvr);
                        pvr.Seek(0, SeekOrigin.Begin);
                        writer.CreateEntry(pvr, tex.Name);
                    }
                    break;

                case TextureFormat.GVM:
                    writer = new GvmArchiveWriter(str);
                    foreach (GvrTextureInfo tex in textures)
                    {
                        if (tex.DataFormat != GvrDataFormat.Index4 && tex.DataFormat != GvrDataFormat.Index8)
                        {
                            System.Drawing.Imaging.BitmapData bmpd = tex.Image.LockBits(new Rectangle(Point.Empty, tex.Image.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                            int    stride = bmpd.Stride;
                            byte[] bits   = new byte[Math.Abs(stride) * bmpd.Height];
                            System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length);
                            tex.Image.UnlockBits(bmpd);
                            int tlevels = 0;
                            for (int y = 0; y < tex.Image.Height; y++)
                            {
                                int srcaddr = y * Math.Abs(stride);
                                for (int x = 0; x < tex.Image.Width; x++)
                                {
                                    Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4)));
                                    if (c.A == 0)
                                    {
                                        tlevels = 1;
                                    }
                                    else if (c.A < 255)
                                    {
                                        tlevels = 2;
                                        break;
                                    }
                                }
                                if (tlevels == 2)
                                {
                                    break;
                                }
                            }
                            if (!tex.Mipmap)
                            {
                                tex.DataFormat = GvrDataFormat.Argb8888;
                            }
                            else if (tlevels == 0)
                            {
                                tex.DataFormat = GvrDataFormat.Rgb565;
                            }
                            else
                            {
                                tex.DataFormat = GvrDataFormat.Rgb5a3;
                            }
                        }
                        GvrTextureEncoder encoder = new GvrTextureEncoder(tex.Image, tex.PixelFormat, tex.DataFormat);
                        encoder.GlobalIndex = tex.GlobalIndex;
                        MemoryStream gvr = new MemoryStream();
                        encoder.Save(gvr);
                        gvr.Seek(0, SeekOrigin.Begin);
                        writer.CreateEntry(gvr, tex.Name);
                    }
                    break;

                case TextureFormat.PVMX:
                    PvmxArchive.Save(str, textures.Cast <PvmxTextureInfo>());
                    break;

                case TextureFormat.PAK:
                    PAKFile     pak       = new PAKFile();
                    string      filenoext = Path.GetFileNameWithoutExtension(filename).ToLowerInvariant();
                    string      longdir   = "..\\..\\..\\sonic2\\resource\\gd_pc\\prs\\" + filenoext;
                    List <byte> inf       = new List <byte>(textures.Count * 0x3C);
                    foreach (TextureInfo item in textures)
                    {
                        Stream tex = TextureLoader.SaveToStream(ImageFileFormat.Dds, Texture.FromBitmap(d3ddevice, item.Image, Usage.SoftwareProcessing, Pool.Managed));
                        byte[] tb  = new byte[tex.Length];
                        tex.Read(tb, 0, tb.Length);
                        string name = item.Name.ToLowerInvariant();
                        if (name.Length > 0x1C)
                        {
                            name = name.Substring(0, 0x1C);
                        }
                        pak.Files.Add(new PAKFile.File(filenoext + '\\' + name + ".dds", longdir + '\\' + name + ".dds", tb));
                        inf.AddRange(Encoding.ASCII.GetBytes(name));
                        if (name.Length != 0x1C)
                        {
                            inf.AddRange(new byte[0x1C - name.Length]);
                        }
                        inf.AddRange(BitConverter.GetBytes(item.GlobalIndex));
                        inf.AddRange(new byte[0xC]);
                        inf.AddRange(BitConverter.GetBytes(item.Image.Width));
                        inf.AddRange(BitConverter.GetBytes(item.Image.Height));
                        inf.AddRange(new byte[4]);
                        inf.AddRange(BitConverter.GetBytes(0x80000000));
                    }
                    pak.Files.Insert(0, new PAKFile.File(filenoext + '\\' + filenoext + ".inf", longdir + '\\' + filenoext + ".inf", inf.ToArray()));
                    pak.Save(filename);

                    return;
                }
                writer?.Flush();
                data = str.ToArray();
                str.Close();
            }
            if (Path.GetExtension(filename).Equals(".prs", StringComparison.OrdinalIgnoreCase))
            {
                FraGag.Compression.Prs.Compress(data, filename);
            }
            else
            {
                File.WriteAllBytes(filename, data);
            }
        }
Exemple #10
0
        protected override void OnSave(Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback)
        {
            RenderArgs ra = new RenderArgs(new Surface(input.Size));

            input.Render(ra, true);

            // Show dialog and setup engine parameters
            SaveDialogSettingsState pvrMetaData;

            if (pvrMetaDataCache != null)
            {
                pvrMetaData = ShowSetupDialogBox(pvrMetaDataCache, ra.Bitmap); //load from cache when there
            }
            else                                                               // no cache make clear instance of settings dialog
            {
                switch (LoadEngineMode)
                {
                case PvrEngineEnum.None:
                    pvrMetaData = ShowSetupDialogBox(loadedPvrPuyo, ra.Bitmap);     //null
                    break;

                case PvrEngineEnum.ShenmueDK:
                    pvrMetaData = ShowSetupDialogBox(loadedPvr, ra.Bitmap);
                    break;

                case PvrEngineEnum.PuyoTools:
                    pvrMetaData = ShowSetupDialogBox(loadedPvrPuyo, ra.Bitmap);
                    break;

                default:
                    pvrMetaData = ShowSetupDialogBox(loadedPvrPuyo, ra.Bitmap);     //null
                    break;
                }
            }
            using (var ms = new MemoryStream())
            {
                Image <Bgra32> image      = ImageSharpExtensions.ToImageSharpImage(ra.Bitmap);
                var            tmpPvrPuyo = new PvrTextureEncoder(image, pvrMetaData.PuyoPixelFormat, (PvrDataFormat)pvrMetaData.PuyoDataFormat);

                // optiona global id
                if (pvrMetaData.GbixId != null)
                {
                    tmpPvrPuyo.GlobalIndex = pvrMetaData.GbixId;
                }

                // dithering
                tmpPvrPuyo.DitheringMode = pvrMetaData.Dithering;

                // EyeWeightMode
                if (pvrMetaData.EyeWeightMode)
                {
                    tmpPvrPuyo.MetricMode = 1;
                }
                else
                {
                    tmpPvrPuyo.MetricMode = 0;
                }

                //GuardedStream workaround (forums.getpaint.net/topic/114912-i-can-not-save-my-work/)?
                tmpPvrPuyo.Save(ms);

                byte[] tmpBfr = ms.ToArray();
                output.Write(tmpBfr, 0, tmpBfr.Length);
                pvrMetaDataCache = pvrMetaData; // update settings cache
            }
        }