/// <summary>
        /// When a RafContentView node is double clicked, extract and view its content
        /// </summary>
        void rafContentView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            RAFInMemoryFileSystemObject node = (RAFInMemoryFileSystemObject)e.Node;
            string nodeInternalPath          = node.GetRAFPath();

            if (node.GetFSOType() == RAFFSOType.FILE)
            {
                //We have double clicked a file... find out what file it was
                List <RAFFileListEntry> entries = rafManager.Archives.Where(
                    (Func <RAFArchive, bool>) delegate(RAFArchive arc)
                {
                    return(arc.GetID().ToLower() == node.GetTopmostParent().Name);
                }
                    ).First().GetDirectoryFile().GetFileList().GetFileEntries();

                //Find the RAF File entry that corresponds to the clicked file...
                RAFFileListEntry entry = entries.Where(
                    (Func <RAFFileListEntry, bool>) delegate(RAFFileListEntry theEntry)
                {
                    return(theEntry.FileName == nodeInternalPath);
                }
                    ).First();

                //Now select a viewer to use for the file.
                //Unnecessary for the most part, can be enabled in the future: if (entry.FileSize < 10000 || //If > 200, ask, then continue MessageBox.Show("This file is quite large ({0} bytes).  Sure you want to read it?".F(entry.FileSize), "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)

                if (entry.FileName.ToLower().EndsWith("dds"))
                {
                    ShowDirectDrawSurface(entry.GetContent());
                }
                else if (entry.FileName.ToLower().EndsWith("inibin") || entry.FileName.ToLower().EndsWith("troybin"))
                {
                    ShowInibinFile(this.baseTitle + " - inibin/troybin view - " + nodeInternalPath, entry.GetContent());
                }
                else if (entry.FileName.EndsWithAny(new string[] { ".cfg", ".ini", ".txt", ".log", ".list", ".xml" }))
                {
                    ShowEditableTextFile(rafManager.ResolveRAFPathToEntry(node.GetTopmostParent().Text + "/" + node.GetRAFPath()));
                }
                else if (entry.FileName.EndsWithAny(new string[] { ".bmp", ".jpg" }))
                {
                    new BitmapViewer("Bitmap Viewer", entry.GetContent()).Show();
                }
                else //If all else fails, just use the binary viewer
                {
                    ShowBinaryFile(this.baseTitle + " - " + nodeInternalPath, entry.GetContent());
                }
            }
        }
예제 #2
0
        public static bool Read(int skin, RAFFileListEntry file, ref Dictionary <String, String> animations, Logger logger)
        {
            bool result = true;

            logger.Event("Parsing animation list: " + file.FileName);

            try
            {
                // Get the data from the archive
                MemoryStream myInput = new MemoryStream(file.GetContent());
                StreamReader reader  = new StreamReader(myInput);

                ParseAnimations(skin, reader, ref animations);

                reader.Close();
                myInput.Close();
            }
            catch
            {
                logger.Error("Failed to parse animation list: " + file.FileName);

                result = false;
                animations.Clear();
            }

            return(result);
        }
예제 #3
0
        public static bool Read(RAFFileListEntry file, ref InibinFile data, Logger logger)
        {
            bool result = true;

            logger.Event("Reading inibin: " + file.FileName);

            try
            {
                // Get the data from the archive
                MemoryStream myInput = new MemoryStream(file.GetContent());
                result = ReadCharacterInibin(myInput, ref data, logger);

                int    end       = file.FileName.LastIndexOf("/");
                String directory = file.FileName.Substring(0, end);
                String archive   = file.RAFArchive.RAFFilePath;
                archive = archive.Replace("\\", "/");
                end     = archive.LastIndexOf("/");
                archive = archive.Substring(0, end);

                data.directory = new DirectoryInfo(archive + "/" + directory);
                myInput.Close();
            }
            catch (Exception e)
            {
                logger.Error("Unable to open memory stream: " + file.FileName);
                logger.Error(e.Message);
                result = false;
            }

            return(result);
        }
예제 #4
0
        /// <summary>
        /// Read in binary .dds file from RAF.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="data">The contents of the file are stored in here.</param>
        /// <returns></returns>
        public static bool Read(RAFFileListEntry file, ref Bitmap bitmap, Logger logger)
        {
            bool result = true;

            logger.Event("Reading dds: " + file.FileName);

            try
            {
                // Create image.
                int[] images = new int[1];
                Il.ilGenImages(1, images);

                // Bind image.
                Il.ilBindImage(images[0]);

                // Load the image data into DevIL.
                byte[] data = file.GetContent();
                result = Il.ilLoadL(Il.IL_DDS, data, data.Length);
                if (result == true)
                {
                    int width  = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
                    int height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);;

                    // Create the bitmap.
                    bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                    Rectangle rect = new Rectangle(0, 0, width, height);

                    // Store the DevIL image data into the bitmap.
                    BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

                    Il.ilConvertImage(Il.IL_BGRA, Il.IL_UNSIGNED_BYTE);
                    Il.ilCopyPixels(0, 0, 0, width, height, 1, Il.IL_BGRA, Il.IL_UNSIGNED_BYTE, bitmapData.Scan0);

                    bitmap.UnlockBits(bitmapData);
                }

                // Free image.
                Il.ilDeleteImages(1, images);

                if (result == false)
                {
                    throw new System.Exception("Unable to load image data.");
                }
            }
            catch (Exception e)
            {
                logger.Error("Unable to open dds file: " + file.FileName);
                logger.Error(e.Message);
                result = false;
            }

            return(result);
        }
예제 #5
0
        private bool ExpandRAF(string fileDirectory)
        {
            LogTextBox("Loading RAF Packages in " + fileDirectory);
            var list = new RAFMasterFileList(fileDirectory);

            LogTextBox("Expanding RAF packages. This will take a while (~20-30 minutes)...");
            LogTextBox(
                "During this time computer performance may be affected. While patching, running applications should be closed or not in-use");
            int i = 0;

            foreach (var x in list.FileDictFull)
            {
                string           FileLastWritten = string.Empty;
                RAFFileListEntry RAFFile         = x.Value[0];
                string           n = Path.Combine(Client.ExecutingDirectory, "RADS", "lol_game_client");
                foreach (string directories in RAFFile.FileName.Split('/'))
                {
                    if (!directories.Contains('.'))
                    {
                        if (!Directory.Exists(Path.Combine(n, directories)))
                        {
                            Directory.CreateDirectory(Path.Combine(n, directories));
                        }

                        n = Path.Combine(n, directories);
                    }
                    else
                    {
                        try
                        {
                            var writer = new BinaryWriter(File.OpenWrite(Path.Combine(n, directories)));

                            // Writer raw data
                            writer.Write(RAFFile.GetContent());
                            writer.Flush();
                            writer.Close();
                            FileLastWritten = Path.Combine(n, directories);
                        }
                        catch
                        {
                            LogTextBox("Unable to write " + Path.Combine(n, directories));
                        }
                    }
                }
                LogTextBox("(" + i + "/" + list.FileDictFull.Count + ") " +
                           ((i / (decimal)list.FileDictFull.Count) * 100).ToString("N2") + "%");
                i += 1;
            }
            return(true);
        }
예제 #6
0
        public Tuple <IoResult, byte[]> ReadAllBytesInternal(IFileSystemHandle handle)
        {
            var internalHandle = handle as InternalHandle;

            if (internalHandle == null || internalHandle.State == HandleState.Invalidated || internalHandle.State == HandleState.Disposed)
            {
                return(new Tuple <IoResult, byte[]>(IoResult.InvalidHandle, null));
            }

            var asFile = internalHandle.Node as ReleaseManifestFileEntry;

            if (asFile == null)
            {
                // we have a directory
                return(new Tuple <IoResult, byte[]>(IoResult.InvalidOperation, null));
            }

            IReadOnlyList <RiotArchive> archives;

            try {
                archives = GetArchivesOrNull(asFile.ArchiveId);
            } catch (ArchiveNotFoundException) {
                return(new Tuple <IoResult, byte[]>(IoResult.Unavailable, null));
            }

            RAFFileListEntry entry = null;

            foreach (var archive in archives)
            {
                entry = archive.GetDirectoryFile().GetFileList().GetFileEntryOrNull(internalHandle.Node.GetPath());
                if (entry != null)
                {
                    break;
                }
            }
            if (entry == null)
            {
                return(new Tuple <IoResult, byte[]>(IoResult.NotFound, null));
            }

            return(new Tuple <IoResult, byte[]>(IoResult.Success, entry.GetContent()));
        }
예제 #7
0
        /// <summary>
        /// Read in binary .skn file from RAF.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="data">The contents of the file are stored in here.</param>
        /// <returns></returns>
        public static bool Read(RAFFileListEntry file, ref SKNFile data, Logger logger)
        {
            bool result = true;

            logger.Event("Reading skn: " + file.FileName);

            try
            {
                // Get the data from the archive
                MemoryStream myInput = new MemoryStream(file.GetContent());
                result = ReadBinary(myInput, ref data, logger);
                myInput.Close();
            }
            catch (Exception e)
            {
                logger.Error("Unable to open memory stream: " + file.FileName);
                logger.Error(e.Message);
                result = false;
            }

            return(result);
        }
예제 #8
0
        /// <summary>
        /// Instantiates a TextViewer form which displays a string
        /// </summary>
        /// <param name="title">Title of the window</param>
        /// <param name="content">Content displayed</param>
        public TextViewer(RAFFileListEntry fileEntry)
        {
            InitializeComponent();
            this.fileEntry = fileEntry;
            string content = Encoding.ASCII.GetString(fileEntry.GetContent());

            this.Text           = defaultTitle = "Text Viewer - " + fileEntry.FileName;
            this.contentTB.Text = content;

            this.Load += delegate(object sender, EventArgs e)
            {
                if (lastSize != Size.Empty)
                {
                    Size = lastSize;
                }
                if (lastLocation != Point.Empty)
                {
                    Location = lastLocation;
                }
            };

            this.FormClosing += new FormClosingEventHandler(TextViewer_FormClosing);
        }
예제 #9
0
        public int ReadFile(string filename, byte[] buffer, ref uint readBytes, long offset, DokanFileInfo info)
        {
            Console.WriteLine("RF: " + filename + ", off" + offset + ", len" + buffer.Length);

            RAFInMemoryFileSystemObject fso = rafManager.ResolveRAFPathTOFSO(filename);

            Console.WriteLine("->FSO NULL: " + (fso == null));
            if (fso == null)
            {
                return(-DokanNet.ERROR_FILE_NOT_FOUND);
            }
            else
            {
                RAFFileListEntry entry   = rafManager.ResolveRAFPathToEntry(fso.GetRAFPath(true));
                byte[]           content = entry.GetContent();

                readBytes = Math.Min((uint)(content.Length - offset), (uint)buffer.Length);

                Array.Copy(content, offset, buffer, 0, readBytes);
                Console.WriteLine("-> " + readBytes + " bytes read");
                return(0);
            }
            //throw new NotImplementedException();
        }
예제 #10
0
 public AIMesh(RAFFileListEntry file)
     : this(file.GetContent())
 {
 }
예제 #11
0
        private void PackNode(TristateTreeNode node)
        {
            ChangesViewEntry cventry = (ChangesViewEntry)node.Tag;

            if (cventry == null) //Group node
            {
                for (int i = 0; i < node.Nodes.Count; i++)
                {
                    PackNode(node.Nodes[i]);
                }
            }
            else
            {
                RAFFileListEntry entry     = cventry.Entry;
                string           rafPath   = entry.FileName;
                string           localPath = cventry.LocalPath;
                bool             useFile   = cventry.Checked;

                packTick = (packTick + 1) % 10;
                if (packTick == 0 || verboseLoggingCB.Checked)
                {
                    Title("Pack File: " + localPath.Replace("\\", "/").Split("/").Last());
                }

                //Console.WriteLine(Environment.CurrentDirectory + "/backup/");
                PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + entry.FileName.Replace("/", "_");
                if (!File.Exists(fileBackupLoc))
                {
                    if (entry.IsMemoryEntry)
                    {
                        File.WriteAllText(fileBackupLoc, "this file should be deleted");
                    }
                    else
                    {
                        File.WriteAllBytes(fileBackupLoc, entry.GetContent());
                    }
                }

                //Open the RAF archive, insert.
                if (useFile)
                {
                    entry.RAFArchive.InsertFile(
                        rafPath,
                        File.ReadAllBytes(localPath),
                        new LogTextWriter(
                            (Func <string, object>) delegate(string s)
                    {
                        if (verboseLoggingCB.Checked)
                        {
                            Log(s);
                        }
                        return(null);
                    }
                            )
                        );
                }
                else
                {
                    //Insert backup
                    if (File.ReadAllText(fileBackupLoc) == "this file should be deleted")
                    {
                        //The file should be deleted...
                        entry.RAFArchive.GetDirectoryFile().DeleteFileEntry(entry);
                    }
                    else
                    {
                        entry.RAFArchive.InsertFile(
                            rafPath,
                            File.ReadAllBytes(fileBackupLoc),
                            new LogTextWriter(
                                (Func <string, object>) delegate(string s)
                        {
                            if (verboseLoggingCB.Checked)
                            {
                                Log(s);
                            }
                            return(null);
                        }
                                )
                            );
                    }
                }
                List <RAFArchive> archives = new List <RAFArchive>(rafArchives.Values);
                for (int i = 0; i < archives.Count; i++)
                {
                    SetTaskbarProgress((i + 1) * 100 / (archives.Count + 1));
                    archives[i].SaveDirectoryFile();
                }

                SetTaskbarProgress(0);
            }
        }
예제 #12
0
        private void packToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Console.Clear();
            Log("");
            Log("Begin Packing");
            for (int i = 0; i < modEntries.Count; i++)
            {
                ModEntry entry = modEntries[i];
                if (entry.Script == null || (entry.IsChecked?!entry.Script.HasPackTimeOverride:!entry.Script.HasRestoreTimeOverride))
                {
                    DLog("->Pack/Restore Nonscripted Entry: " + entry.ModName);
                    ModEntryNodeTag[] nodeTags = entry.GetModEntryTags();
                    for (int j = 0; j < nodeTags.Length; j++)
                    {
                        RAFFileListEntry rafEntry = ResolveRAFPathToEntry(nodeTags[j].rafPath);

                        string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + nodeTags[j].rafPath.Replace("/", "_");
                        if (entry.IsChecked)
                        {
                            if (rafEntry == null && permitExperimentalFileAddingCB.Checked)
                            {
                                //File doesn't exist in archive
                                //Our backup = "this file should be deleted"
                                DLog("  Marking for restore op deletion: " + nodeTags[j].rafPath);
                                PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                File.WriteAllText(fileBackupLoc, "this file should be deleted");

                                DLog("  Adding " + nodeTags[j].rafPath);
                                string archiveName = nodeTags[j].rafPath.Split("/").First();
                                rafArchives[archiveName].InsertFile(
                                    nodeTags[j].rafPath.Replace(archiveName + "/", ""),
                                    File.ReadAllBytes(nodeTags[j].localPath),
                                    new LogTextWriter(
                                        (Func <string, object>) delegate(string s)
                                {
                                    if (updateDuringLongOperationsCB.Checked)
                                    {
                                        DLog(s);
                                    }
                                    return(null);
                                }
                                        )
                                    );
                            }
                            else
                            {
                                //File does exist in archive, do backup if not done already
                                if (!File.Exists(fileBackupLoc))
                                {
                                    DLog("  Backing up " + nodeTags[j].rafPath);
                                    PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                    File.WriteAllBytes(fileBackupLoc, rafEntry.GetContent());
                                }
                                DLog("  Inserting " + nodeTags[j].rafPath);
                                rafEntry.RAFArchive.InsertFile(
                                    rafEntry.FileName,
                                    File.ReadAllBytes(nodeTags[j].localPath),
                                    new LogTextWriter(
                                        (Func <string, object>) delegate(string s)
                                {
                                    if (updateDuringLongOperationsCB.Checked)
                                    {
                                        DLog(s);
                                    }
                                    return(null);
                                }
                                        )
                                    );
                            }
                        }
                        else if (File.Exists(fileBackupLoc))
                        {
                            if (permitExperimentalFileAddingCB.Checked && File.ReadAllText(fileBackupLoc) == "this file should be deleted")
                            {
                                DLog("  Deleting " + nodeTags[j].rafPath);
                                rafEntry.RAFArchive.GetDirectoryFile().DeleteFileEntry(rafEntry);
                            }
                            else
                            {
                                DLog("  Restoring " + nodeTags[j].rafPath);
                                rafEntry.RAFArchive.InsertFile(
                                    rafEntry.FileName,
                                    File.ReadAllBytes(fileBackupLoc),
                                    null
                                    );
                            }
                        }
                    }
                    DLog("  Done");
                }
                else
                {
                    if (entry.IsChecked)
                    {
                        DLog("->Running RAF Manager Script : Packtime Command");
                        entry.Script.RunPacktimeCommand();
                        DLog("  Done");
                    }
                    else
                    {
                        DLog("->Running RAF Manager Script : Restoretime Command");
                        entry.Script.RunRestoreTimeCommand();
                        DLog("  Done");
                    }
                }
            }
            DLog("Saving Archive Directory Files (*.raf)");
            for (int i = 0; i < rafArchives.Count; i++)
            {
                new List <RAFArchive>(rafArchives.Values)[i].SaveDirectoryFile();
            }
            Log("Done Packing");
        }
예제 #13
0
        /// <summary>
        /// Todo: this needs to be modularized
        /// </summary>
        /// <param name="lines"></param>
        /// <param name="startLine"></param>
        /// <param name="isInitializerCall"></param>
        /// <param name="multilineExec"></param>
        /// <returns></returns>
        private int ProcessToEndStatement(string[] lines, int startLine, bool isInitializerCall, bool multilineExec)
        {
            int i = startLine;

            for (; i < lines.Length && lines[i].Trim().ToUpper() != "END";)
            {
                Console.WriteLine("ProcessToEndStatement @ ln" + i);
                string   line      = lines[i].Trim();
                string[] lineParts = line.QASS(' ');

                if (lineParts.Length == 0)
                {
                    i++;
                }
                else
                {
                    switch (lineParts[0].ToUpper())
                    {
                    case "SET":
                        string varName  = lineParts[1].Trim();
                        string varValue = lineParts[2];

                        Console.WriteLine("SETTING VARIABLE " + varName + " TO " + varValue);
                        if (!variables.ContainsKey(varName))
                        {
                            variables.Add(varName, varValue);
                        }
                        else
                        {
                            variables[varName] = varValue;
                        }
                        i++;
                        break;

                    case "OPTIONS":
                        i = ProcessOptionsBlock(lines, i) + 1;
                        break;

                    case "BACKUP_ONCE":
                    {
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("BACKUP_ONCE invalid syntax.  Expected: 'BACKUP_ONCE rafPath'.  ERROR @ ln " + i);
                        }

                        string rafFilePath = ResolveVariableToValue(lineParts[1].Trim());
                        Console.WriteLine("RAF FILE PATH: " + rafFilePath);
                        Console.WriteLine(variables.ContainsKey(rafFilePath));
                        string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + rafFilePath.Replace("/", "_");
                        if (File.Exists(fileBackupLoc))
                        {
                            Console.WriteLine("BACKUP_ONCE called when backup already created.  Ignoring command @ ln " + i);
                        }
                        else
                        {
                            RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(rafFilePath);
                            if (entry == null)
                            {
                                throw new Exception("BACKUP_ONCE: Entry '" + rafFilePath + "' did NOT exist, or could NOT be found. @ ln " + i + "\r\n" +
                                                    "Correct Syntax: BACKUP_ONCE [full raf path including archive]\r\n" +
                                                    "Ex: BACKUP_ONCE 0.0.0.25/DATA/CFG/defaults/Game.cfg");
                            }
                            else
                            {
                                Console.WriteLine("Backing up to " + fileBackupLoc);
                                Util.PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                File.WriteAllBytes(fileBackupLoc, entry.GetContent());
                            }
                        }
                        i++;
                        break;
                    }

                    case "INI_SET":
                    {
                        if (lineParts.Length < 4)
                        {
                            throw new Exception("INI_SET invalid syntax.  Expected: 'INI_SET RAFPath Section.Key value'.  ERROR @ ln " + i);
                        }
                        string rafPath       = ResolveVariableToValue(lineParts[1]);
                        string iniSectionKey = ResolveVariableToValue(lineParts[2]);
                        string newValue      = ResolveVariableToValue(lineParts[3]);

                        string[] sectionKeyParts = iniSectionKey.Split(".");
                        if (sectionKeyParts.Length != 2)
                        {
                            throw new Exception("Section.Key should only have 1 period in it.  ERROR @ ln " + i);
                        }
                        string iniSection = sectionKeyParts[0];
                        string iniKey     = sectionKeyParts[1];

                        RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(rafPath);
                        if (entry == null)
                        {
                            throw new Exception("BACKUP_ONCE: Entry '" + rafPath + "' did NOT exist, or could NOT be found. @ ln " + i);
                        }
                        else
                        {
                            Console.WriteLine("INI_SET: Section:{0}; Key:{1}; Value:{2};".F(iniSection, iniKey, newValue));
                            //extract it
                            string tempPath = Environment.CurrentDirectory + "/temp" + DateTime.Now.ToFileTime() + ".ini";
                            File.WriteAllBytes(tempPath, entry.GetContent());
                            IniFile iniFile = new IniFile(tempPath);
                            iniFile.IniWriteValue(iniSection, iniKey, newValue);

                            //write it again
                            entry.RAFArchive.InsertFile(
                                entry.FileName, File.ReadAllBytes(tempPath), null
                                );

                            //delete temp file
                            File.Delete(tempPath);
                        }
                        i++;
                        break;
                    }

                    case "PACKTIME":
                        if (isInitializerCall)
                        {
                            //We're done reading, since we're just running the initializer
                            //Store the PC of the packtime declaration
                            Console.WriteLine("Encountered PACKTIME command.  In Initializer call, skipping.");
                            packtimeCodeStartIndex = i;
                            i = FindNextEndOnSameLevel(lines, i) + 1;
                        }
                        else
                        {
                            //We're running the packtime code
                            i = ProcessToEndStatement(lines, i + 1, false);
                            Console.WriteLine("End of PACKTIME: " + i);
                            i++;
                            return(i);    //Return, as this is ALWAYS called by this.RunPacktimeCommand()
                        }
                        break;

                    case "RESTORETIME":
                        if (isInitializerCall)
                        {
                            //We're done reading, since we're just running the initializer
                            //Store the PC of the packtime declaration
                            Console.WriteLine("Encountered RESTORETIME command.  In Initializer call, returning.");
                            restoretimeCodeStartIndex = i;
                            i = FindNextEndOnSameLevel(lines, i) + 1;
                        }
                        else
                        {
                            //We're running the packtime code
                            i = ProcessToEndStatement(lines, i + 1, false) + 1;
                        }
                        break;

                    case "PACK":
                    {
                        Console.WriteLine("PACK COMMAND : " + lineParts[1]);
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("PACK invalid syntax.  Expected: 'PACK LocalPath'.  ERROR @ ln " + i);
                        }

                        string path = ResolveVariableToValue(lineParts[1]);

                        string rafPath = mainForm.GuessRafPathFromPath(path);
                        if (rafPath == "undefined")
                        {
                            Console.WriteLine("Pack probably failed - Didn't pack " + path);
                        }
                        else
                        {
                            RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(
                                mainForm.GuessRafPathFromPath(path)
                                );

                            string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + entry.RAFArchive.GetID() + "_" + entry.FileName.Replace("/", "_");
                            if (!File.Exists(fileBackupLoc))
                            {
                                Util.PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                File.WriteAllBytes(fileBackupLoc, entry.GetContent());
                            }

                            entry.RAFArchive.InsertFile(
                                entry.FileName,
                                File.ReadAllBytes(path),
                                null
                                );
                        }
                        i++;
                        break;
                    }

                    case "PACKDIR":
                    {
                        Console.WriteLine("PACKDIR COMMAND : " + lineParts[1]);
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("PACKDIR invalid syntax.  Expected: 'PACKDIR LocalPath'.  ERROR @ ln " + i);
                        }

                        string   localPath = ResolveVariableToValue(lineParts[1]);
                        string[] paths     = Util.GetAllChildFiles(scriptDir + "/" + localPath);
                        foreach (string path in paths)
                        {
                            string rafPath = mainForm.GuessRafPathFromPath(path);
                            if (rafPath == null || rafPath == "undefined")
                            {
                                Console.WriteLine("Pack probably failed - Didn't pack " + path);
                            }
                            else
                            {
                                RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(
                                    mainForm.GuessRafPathFromPath(path)
                                    );

                                string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + entry.RAFArchive.GetID() + "_" + entry.FileName.Replace("/", "_");
                                if (!File.Exists(fileBackupLoc))
                                {
                                    Util.PrepareDirectory(Environment.CurrentDirectory + "/backup/");
                                    File.WriteAllBytes(fileBackupLoc, entry.GetContent());
                                }

                                entry.RAFArchive.InsertFile(
                                    entry.FileName,
                                    File.ReadAllBytes(path),
                                    null
                                    );
                            }
                        }
                        i++;
                        break;
                    }

                    //The parameter can either be a RAF path or a LOCAL path... doesn't matter
                    case "RESTORE":
                    {
                        Console.WriteLine("RESTORE COMMAND : " + lineParts[1]);
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("RESTORE invalid syntax.  Expected: 'RESTORE RAFPath'.  ERROR @ ln " + i);
                        }
                        string rafPath = ResolveVariableToValue(lineParts[1]);

                        string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + rafPath.Replace("/", "_");

                        RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(rafPath);
                        if (entry == null)
                        {
                            throw new Exception("RESTORE: Entry '" + rafPath + "' did NOT exist, or could NOT be found. @ ln " + i);
                        }
                        else
                        {
                            entry.RAFArchive.InsertFile(
                                entry.FileName, File.ReadAllBytes(fileBackupLoc), null
                                );
                        }
                        i++;
                        break;
                    }

                    //The parameter must be a LOCAL path
                    case "RESTOREDIR":
                    {
                        Console.WriteLine("RESTOREDIR COMMAND : " + lineParts[1]);
                        if (lineParts.Length < 2)
                        {
                            throw new Exception("RESTOREDIR invalid syntax.  Expected: 'RESTOREDIR LocalDirPath'.  ERROR @ ln " + i);
                        }
                        string   localDirPath = ResolveVariableToValue(lineParts[1]);
                        string[] paths        = Util.GetAllChildFiles(scriptDir + "/" + localDirPath);

                        foreach (string path in paths)
                        {
                            RAFFileListEntry entry = mainForm.rafManager.ResolveRAFPathToEntry(
                                mainForm.GuessRafPathFromPath(path)
                                );

                            string fileBackupLoc = Environment.CurrentDirectory + "/backup/" + entry.RAFArchive.GetID() + "_" + entry.FileName.Replace("/", "_");

                            if (entry == null)
                            {
                                throw new Exception("RESTORE: Entry similar to '" + path + "' did NOT exist, or could NOT be found. @ ln " + i);
                            }
                            else
                            {
                                if (File.Exists(fileBackupLoc))    //Only swap if a backup exists.  Otherwise, we haven't changed it either way.
                                {
                                    entry.RAFArchive.InsertFile(
                                        entry.FileName, File.ReadAllBytes(fileBackupLoc), null
                                        );
                                }
                            }
                        }
                        i++;
                        break;
                    }

                    case "IF":
                    {
                        Console.WriteLine("IF STATEMENT : " + line);
                        if (lineParts[2] == "==" || lineParts[2] == "!=")
                        {
                            bool eval = ResolveVariableToValue(lineParts[1]) == ResolveVariableToValue(lineParts[3]);
                            if (lineParts[2] == "!=")
                            {
                                eval = !eval;
                            }

                            if (eval)
                            {
                                Console.WriteLine("EVAL");
                                if (lines[i + 1].ToUpper().Trim() == "THEN")
                                {
                                    i = ProcessToEndStatement(lines, i + 1, false, false) + 1;
                                }
                                else
                                {
                                    i++;
                                }
                            }
                            else
                            {
                                Console.WriteLine("NO EVAL");
                                if (lines[i + 1].ToUpper().Trim() == "THEN")
                                {
                                    Console.WriteLine("THEN " + (i + 1));
                                    i = FindNextEndOnSameLevel(lines, i + 1) + 1;
                                }
                                else
                                {
                                    i += 2;
                                    Console.WriteLine(i);
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("IF STATEMENT only supports IF [varname/value] == [varname/value] ERROR @ ln " + i);
                        }
                        break;
                    }

                    case "THEN":
                        return(ProcessToEndStatement(lines, i + 1, false));

                        break;

                    default:
                        throw new Exception("INVALID SYNTAX @ LN " + i + " - Unknown command");
                        break;
                    }
                }
                if (!multilineExec)
                {
                    return(i);
                }
            }
            return(i);
        }
예제 #14
0
        /// <summary>
        /// Load texture from RAF.
        /// </summary>
        /// <param name="file">The RAF file entry of the texture.</param>
        /// <param name="target">Only supports 2D.</param>
        /// <returns></returns>
        public bool Create(RAFFileListEntry file, TextureTarget target, SupportedImageEncodings encoding, Logger logger)
        {
            bool result = true;

            this.target = target;

            // Hacky sanity check
            if (target != TextureTarget.Texture2D)
            {
                return(false);
            }

            GL.Enable(EnableCap.Texture2D);
            GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

            // Create a System.Drawing.Bitmap.
            Bitmap bitmap = null;

            if (encoding == SupportedImageEncodings.DDS)
            {
                // Special case.
                result = DDSReader.Read(file, ref bitmap, logger);
            }
            else
            {
                // Normal case.
                result = CreateBitmap(file.GetContent(), ref bitmap);
            }

            // Pass the Bitmap into OpenGL.
            if (result == true &&
                bitmap != null)
            {
                result = CreateTexture(bitmap, target);
            }

            if (result == true)
            {
                // Set up texture parameters.
                GL.TexEnv(TextureEnvTarget.TextureEnv,
                          TextureEnvParameter.TextureEnvMode,
                          (Int32)TextureEnvModeCombine.Modulate);

                GL.TexParameter(TextureTarget.Texture2D,
                                TextureParameterName.TextureMinFilter,
                                (Int32)TextureMinFilter.Linear);

                GL.TexParameter(TextureTarget.Texture2D,
                                TextureParameterName.TextureMagFilter,
                                (Int32)TextureMagFilter.Linear);

                GL.TexParameter(TextureTarget.Texture2D,
                                TextureParameterName.TextureWrapS,
                                (Int32)TextureWrapMode.Repeat);

                GL.TexParameter(TextureTarget.Texture2D,
                                TextureParameterName.TextureWrapT,
                                (Int32)TextureWrapMode.Repeat);
            }

            return(result);
        }