예제 #1
0
        /// <summary>
        /// Saves DdsImage into Data.
        /// </summary>
        public void SaveDds(bool onlySaveIfEdited = true)
        {
            if (DdsImage == null || (!wasEdited && onlySaveIfEdited))
            {
                return;
            }

            try
            {
                _loadDdsLock = true;
                ImageEngineImage newImage = null;

                using (MemoryStream png = new MemoryStream())
                {
                    DdsImage.Save(png);
                    newImage = new ImageEngineImage(png);
                }
                Data = newImage.Save(ImageFormat, MipHandling.Default).ToList();
            }
            finally
            {
                wasReloaded  = true;
                _loadDdsLock = false;
            }
        }
예제 #2
0
파일: Program.cs 프로젝트: Tsohg/texconvert
        /// <summary>
        /// Converts a single .dds file to .png format.
        /// </summary>
        /// <param name="file">Full path of the file.</param>
        /// <param name="inPath">Full input directory path.</param>
        /// <param name="outPath">Full output directory path.</param>
        /// <param name="index">Integer label. Start at i = 1.</param>
        /// <param name="total">Total number of files to be converted.</param>
        public void ConvertDdsToPng(string file, string inPath, string outPath, ref int index, int total)
        {
            Console.Out.WriteLine("Converting: " + Path.GetFileName(file) + " " + index + "\\" + total);
            ImageEngineImage imi = new ImageEngineImage(Path.Combine(inPath, file));

            //debug
            //formats.Add(imi.Format);

            BitmapSource     bmps = imi.GetWPFBitmap(0, true);
            PngBitmapEncoder enc  = new PngBitmapEncoder();

            enc.Frames.Add(BitmapFrame.Create(bmps));
            //FileStream fs = new FileStream(Path.Combine(outPath, Path.ChangeExtension(Path.GetFileName(file), ".png")), FileMode.Create);

            //String manipulation to remove the .target extension, insert the dds format delimited by '-', and append the new .png extension.
            string noExt = Path.ChangeExtension(file, "");

            noExt = noExt.Remove(noExt.Length - 1);
            string fNewName = Path.GetFileName(noExt) + "-" + imi.Format.ToString();
            string pathNew  = Path.Combine(outPath, fNewName);
            string extNew   = pathNew += ".png";

            //save file.
            FileStream fs = new FileStream(extNew, FileMode.Create);

            enc.Save(fs);
            fs.Close();
        }
예제 #3
0
        public MainWindow()
        {
            InitializeComponent();
            ImageEngineImage dds = new ImageEngineImage("C:\\Dates\\Files\\Ha\\Map\\Map\\Maps\\Hollywood\\2AF\\000000001C32.dds");

            Image_Texture.Source = dds.GeneratePreview(0, true);
        }
예제 #4
0
        public static Bitmap Decode(GNFTexture texture)
        {
            var ddsBytes = DecodeToDDS(texture);
            var ddsImage = new ImageEngineImage(ddsBytes);

            return(ImageEngineImageToBitmap(ddsImage));
        }
예제 #5
0
        public override async Task SaveObject(string filename)
        {
            if (MipMaps == null || !MipMaps.Any())
            {
                return;
            }

            ImageEngineFormat format;

            DomainMipMap mipMap = MipMaps.Where(mm => mm.ImageData != null && mm.ImageData.Length > 0).OrderByDescending(mm => mm.Width > mm.Height ? mm.Width : mm.Height).FirstOrDefault();

            if (mipMap == null)
            {
                return;
            }

            MemoryStream memory = buildDdsImage(MipMaps.IndexOf(mipMap), out format);

            if (memory == null)
            {
                return;
            }

            ImageEngineImage ddsImage = new ImageEngineImage(memory);

            FileStream stream = new FileStream(filename, FileMode.Create);

            await Task.Run(() => ddsImage.Save(stream, format, MipHandling.KeepTopOnly));

            stream.Close();

            memory.Close();
        }
예제 #6
0
        public static Bitmap Decode(byte[] data, TextureFormat format)
        {
            Bitmap bitmap;

            if (format == TextureFormat.DDS)
            {
                try
                {
                    // load image from dds data
                    var image = new ImageEngineImage(data);
                    bitmap = ImageEngineImageToBitmap(image);
                }
                catch (Exception)
                {
                    // Bug: ImagineEngine randomly crashes? Seems to happen with P3D/P5D files only.
                    // Seems like it doesn't support some configuration
                    bitmap = new Bitmap(32, 32, PixelFormat.Format32bppArgb);
                    Trace.WriteLine("ImageEngine failed to decode DDS texture");
                }
            }
            else
            {
                throw new NotSupportedException();
            }

            return(bitmap);
        }
예제 #7
0
        /// <summary>
        /// Collects details of current texture, like thumbnail, number of mips, and format.
        /// </summary>
        public void EnumerateDetails()
        {
            byte[] data = Extract("", true);
            if (data == null)
            {
                DebugOutput.PrintLn("Unable to get image data for: " + FileName);
            }
            else
            {
                // KFreon: Check formatting etc
                try
                {
                    using (ImageEngineImage image = new ImageEngineImage(data))
                    {
                        NumMips = image.NumMipMaps;
                        Height  = image.Height;
                        Width   = image.Width;
                        Format  = image.Format.InternalFormat.ToString().Replace("DDS_", "");

                        image.Save(Thumbnail, ImageEngineFormat.JPG, false, 64);
                    }
                }
                catch (Exception e)
                {
                    DebugOutput.PrintLn("Error checking texture: " + e.Message);
                    NumMips   = 0;
                    Format    = Format ?? Path.GetExtension(FileName);
                    Thumbnail = null;
                }
                data = null;
            }
        }
 public void SetImage(Bitmap bmp)
 {
     using (var stream = new MemoryStream())
     {
         bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
         byte[] bytes = stream.ToArray();
         image = new ImageEngineImage(bytes);
         UIManager.Instance.ShowImage(UsefulThings.WinForms.Imaging.CreateBitmap(image.GetWPFBitmap(), false));
     }
 }
예제 #9
0
        private static Bitmap ImageEngineImageToBitmap(ImageEngineImage image)
        {
            // save the image to bmp
            var bitmapStream = new MemoryStream();

            image.Save(bitmapStream, new ImageFormats.ImageEngineFormatDetails(ImageEngineFormat.BMP), MipHandling.KeepTopOnly);

            // load the saved bmp into a new bitmap
            return(new Bitmap(bitmapStream));
        }
예제 #10
0
        public void SaveSubImage(SubImage subImage, string path, string extension)
        {
            Bitmap bmp = UsefulThings.WinForms.Imaging.CreateBitmap(ImageManager.Instance.image.GetWPFBitmap(), false);

            UIManager.Instance.MainForm.displayImageBox.Image = bmp;
            int top = 0, bottom = 0, left = 0, right = 0;

            foreach (var property in subImage.properties)
            {
                if (property.name == "top")
                {
                    top = Convert.ToInt32(property.value);
                }

                if (property.name == "bottom")
                {
                    bottom = Convert.ToInt32(property.value);
                }

                if (property.name == "left")
                {
                    left = Convert.ToInt32(property.value);
                }

                if (property.name == "right")
                {
                    right = Convert.ToInt32(property.value);
                }
            }

            Rectangle rect = Rectangle.FromLTRB(left, top, right, bottom);

            if (rect.Width <= 0 || rect.Height <= 0)
            {
                LogManager.Instance.MsgError("Invalid sub image on file " + subImage.path);
                return;
            }

            try
            {
                bmp = bmp.Clone(rect, bmp.PixelFormat);

                using (var stream = new MemoryStream())
                {
                    bmp.Save(stream, ImageFormat.Png);
                    ImageEngineImage img = new ImageEngineImage(stream.ToArray());
                    img.Save(path + @"\" + subImage.name + "." + extension, ImageEngineFormat.DDS_DXT3, MipHandling.KeepExisting, 0, 0, false);
                }
            }
            catch (Exception e)
            {
                LogManager.Instance.MsgError("Could not save image " + path + @"\" + subImage.name + "." + extension
                                             + "\nError: " + e.Message);
            }
        }
예제 #11
0
        public FontEditor(string dds_path)
        {
            XamlReader.Load(this);
            ImageEngineImage img  = new ImageEngineImage(dds_path);
            MemoryStream     meme = new MemoryStream();

            img.GetGDIBitmap(false, false).Save(meme, System.Drawing.Imaging.ImageFormat.Bmp);
            Bitmap bmp = new Bitmap(meme.ToArray());

            this.imgView.Image = bmp;
        }
예제 #12
0
            /// <summary>
            /// Returns a thumbnail sized bitmap of current job data (if texture).
            /// </summary>
            /// <returns>Thumbnail bitmap of current job data.</returns>
            public Image GenerateJobThumbnail()
            {
                DebugOutput.PrintLn("Generating thumbnail for: " + this.Name);

                Bitmap bmp = null;

                using (ImageEngineImage img = new ImageEngineImage(data, 64, false))
                    bmp = img.GetGDIBitmap(true, false, 64);

                return(bmp);
            }
예제 #13
0
        /// <summary>
        /// Loads DdsImage from Data.
        /// </summary>
        public void LoadDds()
        {
            if (!EepkToolInterlop.LoadTextures)
            {
                return;
            }

            try
            {
                ddsIsLoading = true;
                byte[] data       = Data.ToArray();
                int    numMipMaps = 0;

                //PROBLEM: Most files load fine with DDSReader, but it CANT load files that are saved with CSharpImageLibrary.
                //CSharpImageLibrary may be able to load them on Win7/Win8 machines, but I cant test that...

                using (var ImageSource = new ImageEngineImage(data))
                {
                    DdsImage    = new WriteableBitmap(ImageSource.GetWPFBitmap());
                    ImageFormat = ImageSource.Format.SurfaceFormat;
                    numMipMaps  = ImageSource.NumMipMaps;
                }

                //If CSharpImageLibrary fails to load the image, then try DDSReader
                //IMPORTANT: DDSReader CANNOT load files saved by CSharpImageLibrary!
                //if (DdsImage == null || numMipMaps == 0)
                //{

                //    DDSReader.Utils.PixelFormat format;
                //    DdsImage = new WriteableBitmap(DDSReader.DDS.LoadImage(data, out format, true));
                //    ImageFormat = ImageEngineFormat.DDS_DXT5; //Default to DXT5

                //If DdsImage is still null, then the image has failed to load.
                //    if (DdsImage == null)
                //    {
                //        throw new InvalidDataException(string.Format("Unable to parse \"{0}\".", Name));
                //    }
                //}
            }
            catch
            {
                loadDdsFail = true;
            }
            finally
            {
                loadDds      = true;
                ddsIsLoading = false;
            }
        }
예제 #14
0
 public System.Drawing.Bitmap GetImage(int size = -1)
 {
     try
     {
         byte[] imgdata = GetImageData(size);
         if (imgdata == null)
         {
             return(null);
         }
         using (ImageEngineImage img = new ImageEngineImage(imageData))
             return(img.GetGDIBitmap(true, false));
     }
     catch { }
     return(null);
 }
        //////////////////////////////////////////////////////////////////
        ///// UI Preparing Operations



        //////////////////////////////////////////////////////////////////
        ///// Manager Operations

        public void SetImage(string imagePath)
        {
            byte[] bytes = null;
            try
            {
                bytes = File.ReadAllBytes(imagePath);
                image = new ImageEngineImage(bytes);
                UIManager.Instance.ShowImage(UsefulThings.WinForms.Imaging.CreateBitmap(image.GetWPFBitmap(), false));
            }
            catch (Exception)
            {
                LogManager.Instance.MsgError("Cannot load image: " + imagePath);
                throw;
            }
        }
예제 #16
0
파일: Program.cs 프로젝트: Tsohg/texconvert
        /// <summary>
        /// Converts a single .png file to .dds format.
        /// </summary>
        /// <param name="file">Full path of the file.</param>
        /// <param name="inPath">Full input directory path.</param>
        /// <param name="outPath">Full output directory path.</param>
        /// <param name="index">Integer label. Start at i = 1.</param>
        /// <param name="total">Total number of files to be converted.</param>
        public void ConvertPngToDds(string file, string inPath, string outPath, ref int index, int total)
        {
            //get data about file..."D:\\msys2\\home\\Nathan\\dbg\\00004d824c7204b6f7-DDS_ARGB_8.png"
            string name = Path.GetFileName(file);

            string[] details = name.Split('-');
            if (details.Length > 2)
            {
                throw new Exception("Additional details detected.");
            }
            if (details.Length == 1) //no details found
            {
                details = new string[] { name, "" }
            }
            ;

            ImageFormats.ImageEngineFormatDetails imageDetails;
            switch (details[1].Split('.')[0]) //A bit of a complicated way to only look at the part without file extension...
            {
            case "DDS_ARGB_8":
                imageDetails = new ImageFormats.ImageEngineFormatDetails(ImageEngineFormat.DDS_ARGB_8);
                break;

            case "DDS_G16_R16":
                imageDetails = new ImageFormats.ImageEngineFormatDetails(ImageEngineFormat.DDS_G16_R16);
                break;

            case "DDS_DXT1":
                imageDetails = new ImageFormats.ImageEngineFormatDetails(ImageEngineFormat.DDS_DXT1);
                break;

            case "DDS_DXT5":
            default:     //we don't know what to do here...so we just assume DXT5.
                imageDetails = new ImageFormats.ImageEngineFormatDetails(ImageEngineFormat.DDS_DXT5);
                break;
            }

            //we have already stripped metadata in split. Begin to return it to dds with the stripped metadata.
            FileStream       fs  = new FileStream(Path.Combine(outPath, Path.ChangeExtension(details[0], ".dds")), FileMode.Create);
            ImageEngineImage imi = new ImageEngineImage(Path.Combine(inPath, name));

            Console.Out.WriteLine("Converting: " + Path.GetFileName(file) + " " + index + "\\" + total);
            imi.Save(fs, imageDetails, MipHandling.Default, 0, 0, false);
            fs.Close();
        }
    }
예제 #17
0
        private static Bitmap ImageEngineImageToBitmap(ImageEngineImage image)
        {
            // save the image to bmp
            var bitmapStream = new MemoryStream();

            try
            {
                image.Save(bitmapStream, new ImageFormats.ImageEngineFormatDetails(ImageEngineFormat.PNG), MipHandling.KeepTopOnly, 0, 0, false);
            }
            catch (NullReferenceException /* good library */)
            {
                image.Save(bitmapStream, new ImageFormats.ImageEngineFormatDetails(ImageEngineFormat.PNG), MipHandling.KeepTopOnly);
            }

            // load the saved bmp into a new bitmap
            return(new Bitmap(bitmapStream));
        }
예제 #18
0
        private void SaveDDS(List <string> paths, string outputPath)
        {
            ImageEngineImage outputImage = new ImageEngineImage(paths[0]);

            for (int i = 1; i < paths.Count; i++)
            {
                ImageEngineImage mipImage = new ImageEngineImage(paths[i]);
                MipMap           mip      = new MipMap(mipImage.MipMaps[0].Pixels, mipImage.Width, mipImage.Height, mipImage.FormatDetails);
                outputImage.MipMaps.Add(mip);
            }
            ImageFormats.ImageEngineFormatDetails outputFormat = new ImageFormats.ImageEngineFormatDetails(ImageEngineFormat.DDS_DXT1);
            byte[] data = outputImage.Save(outputFormat, MipHandling.KeepExisting);

            using (var file = File.Create(outputPath))
            {
                file.Write(data, 0, data.Length);
            }
        }
예제 #19
0
        /// <summary>
        /// Returns current texture as a Bitmap. Option to specify size.
        /// </summary>
        /// <param name="pathBIOGame">Path to BIOGame.</param>
        /// <param name="size">OPTIONAL: Maximum size on any dimension. Defaults to max.</param>
        /// <returns>Bitmap image of texture.</returns>
        public Bitmap GetImage(string pathBIOGame, int size = -1)
        {
            ITexture2D tex2D = Textures[0];

            byte[] imgData = tex2D.GetImageData();

            using (ImageEngineImage img = new ImageEngineImage(imgData))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    if (!img.Save(ms, ImageEngineFormat.PNG, MipHandling.KeepTopOnly))
                    {
                        return(null);
                    }

                    MemoryStream largest = KFreonLib.Textures.Creation.OverlayAndPickDetailed(ms, img.Width, img.Height);
                    return(new Bitmap(largest));
                }
            }
        }
예제 #20
0
        /// <summary>
        /// Collects details of current texture, like thumbnail, number of mips, and format.
        /// </summary>
        public void EnumerateDetails()
        {
            byte[] data = Extract("", true);
            if (data == null)
            {
                DebugOutput.PrintLn("Unable to get image data for: " + FileName);
            }
            else
            {
                // KFreon: Check formatting etc
                try
                {
                    using (ImageEngineImage image = new ImageEngineImage(data))
                    {
                        NumMips = image.NumMipMaps;
                        Height  = image.Height;
                        Width   = image.Width;
                        Format  = image.Format.InternalFormat;

                        if (OrigWidth == -1)
                        {
                            OrigWidth = Width;
                        }

                        if (OrigHeight == -1)
                        {
                            OrigHeight = Height;
                        }

                        image.Save(Thumbnail, ImageEngineFormat.JPG, MipHandling.Default, 64);
                    }
                }
                catch (Exception e)
                {
                    DebugOutput.PrintLn("Error checking texture: " + e.Message);
                    NumMips   = 0;
                    Thumbnail = null;
                }
                data = null;
            }
        }
예제 #21
0
        private void LoadBMFontXMLFont_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Multiselect     = false;
            dlg.Filter          = "BMFont|*.fnt";
            dlg.CheckPathExists = true;
            dlg.CheckFileExists = true;
            bool select = (bool)dlg.ShowDialog();

            if (select)
            {
                selectedFont = new DieselFont(XmlReader.Create(dlg.FileName));
                this.Title   = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName);
                //Check for page paramater in BMFont XML
                if (!File.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(dlg.FileName), System.IO.Path.GetFileNameWithoutExtension(dlg.FileName) + ".texture")))
                {
                    OpenFileDialog textureDLG = new OpenFileDialog();
                    textureDLG.Multiselect     = false;
                    textureDLG.Filter          = "Texture|*.texture;*.dds;*.jpg;*.png;*.bmp";
                    textureDLG.CheckPathExists = true;
                    textureDLG.CheckFileExists = true;
                    bool textureSelected = (bool)textureDLG.ShowDialog();
                    if (textureSelected)
                    {
                        using (FileStream str = new FileStream(textureDLG.FileName, FileMode.Open, FileAccess.Read))
                        {
                            selectedImage = new ImageEngineImage(str);
                        }
                    }
                }
                else
                {
                    using (FileStream str = new FileStream(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(dlg.FileName), System.IO.Path.GetFileNameWithoutExtension(dlg.FileName) + ".texture"), FileMode.Open, FileAccess.Read))
                    {
                        selectedImage = new ImageEngineImage(str);
                    }
                }
            }
        }
예제 #22
0
        public static Bitmap DdsToBmp(int width, int height, byte[] rawData, bool preserveAlpha = true)
        {
            ImageEngineImage img = new ImageEngineImage(rawData);
            var newBytes         = img.Save(new ImageEngineFormatDetails(ImageEngineFormat.BMP), MipHandling.Default);

            Bitmap bmImage = new Bitmap(new MemoryStream(newBytes));

            return(bmImage);

            var pxFormat = PixelFormat.Format32bppRgb;

            if (preserveAlpha)
            {
                pxFormat = PixelFormat.Format32bppArgb;
            }

            Bitmap bitmap = new Bitmap(width, height);

            BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, pxFormat);
            IntPtr     scan = data.Scan0;
            int        size = bitmap.Width * bitmap.Height * 4;

            unsafe
            {
                byte *p = (byte *)scan;
                for (int i = 0; i < size; i += 4)
                {
                    // iterate through bytes.
                    // Bitmap stores it's data in RGBA order.
                    // DDS stores it's data in BGRA order.
                    p[i]     = rawData[i + 2]; // blue
                    p[i + 1] = rawData[i + 1]; // green
                    p[i + 2] = rawData[i];     // red
                    p[i + 3] = rawData[i + 3]; // alpha
                }
            }

            bitmap.UnlockBits(data);
            return(bitmap);
        }
예제 #23
0
 public System.Drawing.Bitmap GetImage(int size = -1)
 {
     try
     {
         byte[] imgdata = GetImageData(size);
         if (imgdata == null)
             return null;
         using (ImageEngineImage img = new ImageEngineImage(imgdata))
             return img.GetGDIBitmap(true, false);
     }
     catch { }
     return null;
 }
예제 #24
0
        private void PreviewTex(ZipReader.ZipEntryFull ent, bool dds)
        {
            try
            {
                Bitmap img;
                if (dds)
                {
                    byte[] data = ent.Extract(true);
                    if (data == null)
                        throw new NullReferenceException("Data returned was null");

                    using (ImageEngineImage ddsimg = new ImageEngineImage(data))
                        img = ddsimg.GetGDIBitmap(true);
                }
                else
                {
                    ent.Extract(false, "preview.tga");
                    img = new TargaImage("preview.tga").Image;
                    File.Delete("preview.tga");
                }
                if (pictureBox1.Image != null)
                    pictureBox1.Image.Dispose();

                if (_resize)
                    pictureBox1.Image = resizeImage(img, new System.Drawing.Size(512, 512));
                else
                    pictureBox1.Image = img;
                pictureBox1.Visible = true;
                pictureBox1.Refresh();
            }
            catch (Exception exc)
            {
                MessageBox.Show("An error occurred: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #25
0
        public override async Task SetObject(string filename, List <DomainNameTableEntry> nameTable)
        {
            ImageEngineImage image = await Task.Run(() => new ImageEngineImage(filename));

            int width  = image.Width;
            int height = image.Height;

            DomainPropertyIntValue sizeX = PropertyHeader.GetProperty("SizeX").FirstOrDefault()?.Value as DomainPropertyIntValue;
            DomainPropertyIntValue sizeY = PropertyHeader.GetProperty("SizeY").FirstOrDefault()?.Value as DomainPropertyIntValue;

            sizeX?.SetPropertyValue(width);
            sizeY?.SetPropertyValue(height);

            DomainPropertyIntValue mipTailBaseIdx = PropertyHeader.GetProperty("MipTailBaseIdx").FirstOrDefault()?.Value as DomainPropertyIntValue;

            mipTailBaseIdx?.SetPropertyValue((int)Math.Log(width > height ? width : height, 2));

            DomainPropertyStringValue filePath = PropertyHeader.GetProperty("SourceFilePath").FirstOrDefault()?.Value as DomainPropertyStringValue;
            DomainPropertyStringValue fileTime = PropertyHeader.GetProperty("SourceFileTimestamp").FirstOrDefault()?.Value as DomainPropertyStringValue;

            filePath?.SetPropertyValue(filename);
            fileTime?.SetPropertyValue(File.GetLastWriteTime(filename).ToString("yyyy-MM-dd hh:mm:ss"));

            DomainPropertyByteValue pfFormat = PropertyHeader.GetProperty("Format").FirstOrDefault()?.Value as DomainPropertyByteValue;

            ImageEngineFormat imageFormat = image.Format.InternalFormat;

            if (!imageFormat.ToString().Contains("DDS"))
            {
                throw new Exception($"Image is not in a DDS format.  It is actually {imageFormat}.");
            }

            if (pfFormat != null)
            {
                string formatStr = imageFormat.ToString().Replace("DDS", "PF");

                if (formatStr.Contains("ARGB"))
                {
                    formatStr = "PF_A8R8G8B8";
                }
                else if (formatStr.Contains("G8"))
                {
                    formatStr = "PF_G8";
                }

                DomainNameTableEntry formatTableEntry = nameTable.SingleOrDefault(nt => nt.Name.String == formatStr) ?? nameTable.AddDomainNameTableEntry(formatStr);

                pfFormat.SetPropertyValue(formatTableEntry);
            }

            MipMaps.Clear();

            while (true)
            {
                MemoryStream stream = new MemoryStream();

                image.Save(stream, imageFormat, MipHandling.KeepTopOnly);

                await stream.FlushAsync();

                MipMaps.Add(new DomainMipMap
                {
                    ImageData = (await ByteArrayReader.CreateNew(stream.ToArray(), 0x80).Splice()).GetBytes(), // Strip off 128 bytes for the DDS header
                    Width     = image.Width,
                    Height    = image.Height
                });

                if (width == 1 && height == 1)
                {
                    break;
                }

                if (width > 1)
                {
                    width /= 2;
                }
                if (height > 1)
                {
                    height /= 2;
                }

                if (image.Width > 4 && image.Height > 4)
                {
                    image.Resize(0.5, false);
                }
            }
        }
예제 #26
0
        public bool InstallTexture(string texname, List<string> pccs, List<int> IDs, byte[] imgdata)
        {
            if (pccs.Count == 0)
            {
                DebugOutput.PrintLn("No PCC's found for " + texname + ", skipping.");
                return false;
            }
            string fulpath = pccs[0];
            //string temppath = (WhichGame == 1) ? Path.GetDirectoryName(pathBIOGame) : pathBIOGame;
            // Heff: Again, is the removal of the last dir for ME1 intended, and if so for what purpose?
            string temppath = pathBIOGame;
            if (!fulpath.Contains(temppath))
                fulpath = Path.Combine(temppath, fulpath);


            // KFreon: Skip files that don't exist
            if (!File.Exists(fulpath))
                return false;

            using (PCCObjects.IPCCObject pcc = PCCObjects.Creation.CreatePCCObject(fulpath, WhichGame))
            {
                if ((pcc.Exports[IDs[0]].ClassName != "Texture2D" && pcc.Exports[IDs[0]].ClassName != "LightMapTexture2D" && pcc.Exports[IDs[0]].ClassName != "TextureFlipBook") || String.Compare(pcc.Exports[IDs[0]].ObjectName, texname, true) != 0)
                    throw new InvalidDataException("Export is not correct class or name!");

                //Load the texture from the pcc
                using (Textures.ITexture2D tex2D = pcc.CreateTexture2D(IDs[0], pathBIOGame))
                {
                    
                    tex2D.allPccs = pccs;
                    tex2D.expIDs = IDs;
                    int noImg = tex2D.imgList.Count;

                    DebugOutput.PrintLn("Now replacing textures in texture: " + tex2D.texName, true);
                    Debug.WriteLine("Now replacing textures in texture: " + tex2D.texName + "  ID: " + IDs[0]);
                    WriteDebug("Now replacing textures in texture: " + tex2D.texName + "  ID: " + IDs[0]);

                    ImageFile im = null;
                    try
                    {
                        im = new DDS("", imgdata);
                    }
                    catch
                    {
                        Console.WriteLine("Error: Unable to detect input DDS format, skipping.");
                        return false;
                    }



                    // KFreon: TESTING
                    Debug.WriteLine("First pcc: " + fulpath + "    ArcName: " + tex2D.arcName);
                    WriteDebug("First pcc: " + fulpath + "    ArcName: " + tex2D.arcName);



                    //The texture is a single image, therefore use replace function
                    if (noImg == 1)
                    {
                        string imgSize = tex2D.imgList[0].imgSize.width.ToString() + "x" + tex2D.imgList[0].imgSize.height.ToString();
                        try
                        {
                            tex2D.replaceImage(imgSize, im, pathBIOGame);
                        }
                        catch
                        {
                            // KFreon:  If replace fails, it's single image thus use the singleimageupscale function
                            tex2D.singleImageUpscale(im, pathBIOGame);
                        }
                    }

                    //If the texture has multiple images, then check the input texture for MIPMAPS
                    else
                    {
                        bool hasMips = true;
                        ImageFile imgFile = im;
                        /*try { ImageMipMapHandler imgMipMap = new ImageMipMapHandler("", imgdata); }
                        catch (Exception e)
                        {
                            hasMips = false;
                        }*/
                        using (ImageEngineImage img = new ImageEngineImage(imgdata))
                            hasMips = img.NumMipMaps > 1;


                        if (!hasMips)
                        {
                            string imgSize = imgFile.imgSize.width.ToString() + "x" + imgFile.imgSize.height.ToString();
                            try
                            {
                                //Try replacing the image. If it doesn't exist then it'll throw and error and you'll need to upscale the image
                                tex2D.replaceImage(imgSize, imgFile, pathBIOGame);
                            }
                            catch (Exception e)
                            {
                                tex2D.addBiggerImage(imgFile, pathBIOGame);
                            }
                        }
                        else
                        {
                            try
                            {
                                tex2D.OneImageToRuleThemAll(imgFile, pathBIOGame, imgdata);
                            }
                            catch (Exception e)
                            {
                                if (e.Message.Contains("Format"))
                                {
                                    MessageBox.Show(texname + " is in the wrong format." + Environment.NewLine + Environment.NewLine + e.Message);
                                    return false;
                                }
                            }
                        }
                    }

                    Debug.WriteLine("After replace: " + tex2D.arcName);
                    WriteDebug("After replace: " + tex2D.arcName);


                    DebugOutput.PrintLn("Replacement complete. Now saving pcc: " + pcc.pccFileName, true);

                    PCCObjects.IExportEntry expEntry = pcc.Exports[IDs[0]];
                    expEntry.SetData(tex2D.ToArray(expEntry.DataOffset, pcc));
                    expEntry.hasChanged = true;
                    pcc.Exports[IDs[0]] = expEntry;

                    pcc.saveToFile(pcc.pccFileName);

                    int modCount = tex2D.allPccs.Count;

                    // KFreon: Elapsed time stuff
                    int start = Environment.TickCount;

                    if (modCount > 1)
                        for (int item = 1; item < modCount; item++)
                        {
                            Debug.WriteLine(pccs[item] + "   " + IDs[item]);
                            WriteDebug(pccs[item] + "   " + IDs[item]);
                            if (!SaveFile(pccs, IDs, tex2D, item))
                                break;
                        }
                    Debug.WriteLine("");
                    WriteDebug("");

                    // KFreon: More timer stuff
                    TimeSpan ts = TimeSpan.FromMilliseconds(Environment.TickCount - start);
                    Console.WriteLine(ts.Duration().ToString());
                    DebugOutput.Print("All PCC updates finished. ");
                    return true;
                }
            }
        }
예제 #27
0
        /// <summary>
        /// Collects details of current texture, like thumbnail, number of mips, and format.
        /// </summary>
        public void EnumerateDetails()
        {
            byte[] data = Extract("", true);
            if (data == null)
                DebugOutput.PrintLn("Unable to get image data for: " + FileName);
            else
            {
                // KFreon: Check formatting etc
                try
                { 
                    using (ImageEngineImage image = new ImageEngineImage(data))
                    {
                        NumMips = image.NumMipMaps;
                        Height = image.Height;
                        Width = image.Width;
                        Format = image.Format.InternalFormat;

                        if (OrigWidth == -1)
                            OrigWidth = Width;

                        if (OrigHeight == -1)
                            OrigHeight = Height;

                        image.Save(Thumbnail, ImageEngineFormat.JPG, MipHandling.Default, 64);
                    }
                }
                catch(Exception e)
                {
                    DebugOutput.PrintLn("Error checking texture: " + e.Message);
                    NumMips = 0;
                    Thumbnail = null;
                }
                data = null;
            }
        }
예제 #28
0
        /// <summary>
        /// Returns current texture as a Bitmap. Option to specify size.
        /// </summary>
        /// <param name="pathBIOGame">Path to BIOGame.</param>
        /// <param name="size">OPTIONAL: Maximum size on any dimension. Defaults to max.</param>
        /// <returns>Bitmap image of texture.</returns>
        public Bitmap GetImage(string pathBIOGame, int size = -1)
        {
            ITexture2D tex2D = Textures[0];
            byte[] imgData = tex2D.GetImageData();

            using (ImageEngineImage img = new ImageEngineImage(imgData))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    if (!img.Save(ms, ImageEngineFormat.PNG, MipHandling.KeepTopOnly))
                        return null;

                    MemoryStream largest = KFreonLib.Textures.Creation.OverlayAndPickDetailed(ms, img.Width, img.Height);
                        return new Bitmap(largest);
                }
            }
        }
예제 #29
0
        private string ExternalImageSelector(Textures.ITexture2D tex2D)
        {
            string path = "";
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Title = "Select the image to add";
                ofd.Filter = "Image file|*.dds|All files|*.*";
                //                ofd.Filter = "Image file|*" + tex2D.getFileFormat() + "|All files|*.*";

                if (ofd.ShowDialog() != DialogResult.OK)
                    return "";
                else
                    path = ofd.FileName;
            }

            StringBuilder sb = new StringBuilder();

            // KFreon: Check replacing texture
            using (ImageEngineImage img = new ImageEngineImage(path))
            {
                if (!img.Format.InternalFormat.ToString().Contains(tex2D.texFormat, StringComparison.OrdinalIgnoreCase))
                    sb.Append("Invalid format. Selected image is: " + img.Format.InternalFormat.ToString() + "  Required: " + tex2D.texFormat.ToUpperInvariant());

                if (img.NumMipMaps < tex2D.Mips)
                    sb.AppendLine("Mipmap error. Requires: " + tex2D.Mips + ".  Currently: " + img.NumMipMaps);
            }


            if (sb.Length != 0)
            {
                MessageBox.Show(sb.ToString(), "Mission Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "";
            }

            return path;
        }
예제 #30
0
        private bool AutofixInternal(TPFTexInfo tex)
        {
            bool retval = false;

            TPFTexInfo backup = tex.Clone();

            string path = tex.Autofixedpath(TemporaryPath);
            Directory.CreateDirectory(Path.GetDirectoryName(path));

            byte[] imgData = tex.Extract(Path.GetDirectoryName(path), true);

            using (ImageEngineImage img = new ImageEngineImage(imgData))
            {
                var destFormat = tex.ExpectedFormat;
                img.Resize(UsefulThings.General.RoundToNearestPowerOfTwo(img.Width), false);
                retval = img.Save(path, destFormat, tex.ExpectedMips > 1 ? MipHandling.Default : MipHandling.KeepTopOnly);
            }

            if (!retval)
            {
                tex.AutofixSuccess = false;
                return false;
            }

            tex.FilePath = Path.GetDirectoryName(tex.Autofixedpath(TemporaryPath));

            tex.FileName = Path.GetFileName(path);

            // Heff: Cancellation check
            if (cts.IsCancellationRequested)
                return false;
            tex.EnumerateDetails();

            // Heff: if fix was successfull, but the number of mips are still wrong,
            // force it and let texplorer skip the lowest resolutions
            // Heff: this should no longer happen, but keeping this as it might help in some real odd case.
            if (tex.ExpectedMips > 1 && (tex.NumMips < tex.ExpectedMips || tex.NumMips < TPFTexInfo.CalculateMipCount(tex.Width, tex.Height)))
                tex.NumMips = Math.Max(tex.ExpectedMips, TPFTexInfo.CalculateMipCount(tex.Width, tex.Height));

            if (!tex.Valid)
            {
                tex = backup;
                tex.AutofixSuccess = false;
            }
            else
                tex.AutofixSuccess = true;

            return tex.AutofixSuccess;
        }
예제 #31
0
        private void PreviewObject(TPFTexInfo tex)
        {
            // KFreon: Clear old image
            ClearPreview();

            // Clean cache if required
            if (Previews.Keys.Count > 10)
            {
                var img = Previews.First();
                img.Value.Dispose();
                Previews.Remove(img.Key);
            }

            // KFreon: Gather from cache if available
            if (Previews.ContainsKey(tex.PreviewKey))
            {
                Bitmap img = Previews[tex.PreviewKey];
                try
                {
                    this.Invoke(new Action(() => PreviewBox.Image = img));
                }
                catch (ObjectDisposedException)
                { } // DOn't care - it's when the form is closing. The form can become disposed while the preview is trying to be shown.

                DisappearTextBox(true);
                return;
            }


            // KFreon: Get data
            byte[] data = tex.Extract(null, true);
            if (data == null)
                return;

            // KFreon: Load new one
            if (tex.isDef)
            {
                DisappearTextBox(false);
                try
                {
                    string message = Encoding.UTF8.GetString(data);
                    this.Invoke(new Action(() => texmodPreviewBox.Text = message));
                }
                catch (Exception e)
                {
                    DebugOutput.PrintLn("Unable to get text from data: " + e.Message);
                }
            }
            else
            {
                Bitmap img = null;
                using (MemoryStream ms = new MemoryStream(data))
                    using (ImageEngineImage image = new ImageEngineImage(ms, null, 512, false))
                        img = image.GetGDIBitmap(true, false, 512);

                this.Invoke(new Action(() => PreviewBox.Image = img));
                Previews.Add(tex.PreviewKey, img);
                DisappearTextBox(true);
            }
        }
예제 #32
0
        private static Bitmap DecodeDDSWithImageEngine(byte[] data)
        {
            var ddsImage = new ImageEngineImage(data);

            return(ImageEngineImageToBitmap(ddsImage));
        }
예제 #33
0
        /// <summary>
        /// Collects details of current texture, like thumbnail, number of mips, and format.
        /// </summary>
        public void EnumerateDetails()
        {
            byte[] data = Extract("", true);
            if (data == null)
                DebugOutput.PrintLn("Unable to get image data for: " + FileName);
            else
            {
                // KFreon: Check formatting etc
                try
                {
                    using (ImageEngineImage image = new ImageEngineImage(data))
                    {
                        NumMips = image.NumMipMaps;
                        Height = image.Height;
                        Width = image.Width;
                        Format = image.Format.InternalFormat.ToString().Replace("DDS_", "");

                        image.Save(Thumbnail, ImageEngineFormat.JPG, false, 64);
                    }
                }
                catch(Exception e)
                {
                    DebugOutput.PrintLn("Error checking texture: " + e.Message);
                    NumMips = 0;
                    Format = Format ?? Path.GetExtension(FileName);
                    Thumbnail = null;
                }
                data = null;
            }
        }
예제 #34
0
            /// <summary>
            /// Returns a thumbnail sized bitmap of current job data (if texture).
            /// </summary>
            /// <returns>Thumbnail bitmap of current job data.</returns>
            public Image GenerateJobThumbnail()
            {
                DebugOutput.PrintLn("Generating thumbnail for: " + this.Name);

                Bitmap bmp = null;
                using (ImageEngineImage img = new ImageEngineImage(data, 64, false))
                    bmp = img.GetGDIBitmap(true, false, 64);

                return bmp;
            }