Beispiel #1
0
		public Image GetMapImage() {
			if (mMapImage == null) {
				var filepath = MapImageFilepath;
				var img = new DDSImage(filepath);
				mMapImage = img.images[0];
			}

			return mMapImage.Clone() as Image;
		}
Beispiel #2
0
        public static void Load()
        {
            int index = selectedIndex;

            if (index < 0)
            {
                index = 0;
            }
            if (index > available.Count - 1)
            {
                index = available.Count - 1;
            }

            if (index >= 0 && index < available.Count)
            {
                string f = available[index];

                string iradpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Hdri", f, "irradiance.dds");
                string prefpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Hdri", f, "prefiltered.dds");

                try
                {
                    DDSImage rad = DDSReader.DDSReader.ReadImage(iradpath);
                    DDSImage pre = DDSReader.DDSReader.ReadImage(prefpath);

                    Collection <DDSMipMap> mips = (Collection <DDSMipMap>)rad.Frames;

                    if (mips.Count > 0)
                    {
                        var    mip  = mips[0];
                        byte[] data = mip.MipmapData[0];
                        if (Irradiance != null)
                        {
                            Irradiance.Release();
                        }

                        Irradiance = new GLTextuer2D(PixelInternalFormat.Rgb16f);
                        Irradiance.Bind();
                        Irradiance.SetData(data, PixelFormat.Rgb, (int)mip.Width, (int)mip.Height);
                        Irradiance.SetFilter((int)TextureMinFilter.Linear, (int)TextureMagFilter.Linear);
                        Irradiance.SetWrap((int)TextureWrapMode.ClampToEdge);
                        GLTextuer2D.Unbind();
                    }

                    mips = (Collection <DDSMipMap>)pre.Frames;

                    if (mips.Count > 0)
                    {
                        if (Prefiltered != null)
                        {
                            Prefiltered.Release();
                        }

                        Prefiltered = new GLTextuer2D(PixelInternalFormat.Rgb16f);
                        Prefiltered.Bind();
                        Prefiltered.SetMaxMipLevel(4);

                        for (int i = 0; i < mips.Count; i++)
                        {
                            var    mip  = mips[i];
                            byte[] data = mip.MipmapData[0];

                            Prefiltered.SetData(data, PixelFormat.Rgb, (int)mip.Width, (int)mip.Height, i);
                        }

                        Prefiltered.SetFilter((int)TextureMinFilter.LinearMipmapLinear, (int)TextureMagFilter.Linear);
                        Prefiltered.SetWrap((int)TextureWrapMode.ClampToEdge);

                        GLTextuer2D.Unbind();
                    }

                    if (OnHdriLoaded != null)
                    {
                        OnHdriLoaded.Invoke(Irradiance, Prefiltered);
                    }
                }
                catch (Exception e)
                {
                }
            }
        }
 public static void WriteToStream(Stream output, DDSImage image)
 {
     DDSWriter.WriteFile(output, image);
 }
        public static DDSImage GenerateDDS(byte[] rgba, Vector2I size, DDSImage.FormatEnum format, bool normalMap, bool generateMipmaps, out string error)
        {
            //!!!!может не инициализировать каждый раз

            NvidiaTextureTools.Compressor         compressor         = null;
            NvidiaTextureTools.InputOptions       inputOptions       = null;
            NvidiaTextureTools.CompressionOptions compressionOptions = null;
            NvidiaTextureTools.OutputOptions      outputOptions      = null;

            try
            {
                NativeLibraryManager.PreLoadLibrary("nvtt");

                compressor         = new NvidiaTextureTools.Compressor();
                inputOptions       = new NvidiaTextureTools.InputOptions();
                compressionOptions = new NvidiaTextureTools.CompressionOptions();
                outputOptions      = new NvidiaTextureTools.OutputOptions();

                inputOptions.SetTextureLayout(NvidiaTextureTools.TextureType.Texture2D, size.X, size.Y, 1);

                byte[] bgra = new byte[rgba.Length];
                //bool containAlpha = false;
                {
                    for (int y = 0; y < size.Y; y++)
                    {
                        for (int x = 0; x < size.X; x++)
                        {
                            int offset = (y * size.X + x) * 4;
                            bgra[offset + 0] = rgba[offset + 2];
                            bgra[offset + 1] = rgba[offset + 1];
                            bgra[offset + 2] = rgba[offset + 0];
                            bgra[offset + 3] = rgba[offset + 3];

                            //byte alpha = bgra[ offset + 3 ];
                            //if( alpha != 255 )
                            //	containAlpha = true;
                        }
                    }
                }

                unsafe
                {
                    fixed(byte *pData = bgra)
                    inputOptions.SetMipmapData((IntPtr)pData, size.X, size.Y, 1, 0, 0);
                }

                inputOptions.SetWrapMode(NvidiaTextureTools.WrapMode.Repeat);
                inputOptions.SetFormat(NvidiaTextureTools.InputFormat.BGRA_8UB);
                if (normalMap)
                {
                    inputOptions.SetNormalMap(true);
                }
                inputOptions.SetMipmapGeneration(generateMipmaps);

                inputOptions.SetRoundMode(NvidiaTextureTools.RoundMode.ToNextPowerOfTwo);

                //sense?
                if (format == DDSImage.FormatEnum.DXT5)
                {
                    inputOptions.SetAlphaMode(NvidiaTextureTools.AlphaMode.Transparency);
                }
                //if( containAlpha )
                //{
                //	if( format == DDSImage.FormatEnum.DXT1 )
                //		inputOptions.SetAlphaMode( NvidiaTextureTools.AlphaMode.Premultiplied );
                //	else
                //		inputOptions.SetAlphaMode( NvidiaTextureTools.AlphaMode.Transparency );
                //}
                //else
                //	inputOptions.SetAlphaMode( NvidiaTextureTools.AlphaMode.None );

                //inputOptions.SetNormalMap( format == DDSImage.FormatTypes._3DC );
                //inputOptions.SetNormalMap( true );
                //inputOptions.SetConvertToNormalMap( true );
                //public void SetHeightEvaluation(float redScale, float greenScale, float blueScale, float alphaScale)
                //public void SetNormalFilter(float small, float medium, float big, float large)
                //inputOptions.SetNormalizeMipmaps( true );
                //public void SetColorTransform(ColorTransform t);
                //public void SetLinearTransfrom(int channel, float w0, float w1, float w2, float w3)

                switch (format)
                {
                case DDSImage.FormatEnum.DXT1:
                    compressionOptions.SetFormat(NvidiaTextureTools.Format.DXT1a);
                    //compressionOptions.SetFormat( containAlpha ? NvidiaTextureTools.Format.DXT1a : NvidiaTextureTools.Format.DXT1 );
                    break;

                case DDSImage.FormatEnum.DXT3:
                    compressionOptions.SetFormat(NvidiaTextureTools.Format.DXT3);
                    break;

                case DDSImage.FormatEnum.DXT5:
                    compressionOptions.SetFormat(NvidiaTextureTools.Format.DXT5);
                    break;

                case DDSImage.FormatEnum.BC5:
                    compressionOptions.SetFormat(NvidiaTextureTools.Format.BC5);
                    break;

                case DDSImage.FormatEnum.R8G8B8:
                    compressionOptions.SetFormat(NvidiaTextureTools.Format.RGB);
                    break;

                case DDSImage.FormatEnum.A8R8G8B8:
                    compressionOptions.SetFormat(NvidiaTextureTools.Format.RGBA);
                    break;

                default:
                    error = $"Format \'{format}\' is not supported.";
                    break;
                }

                //!!!!зависает BC5 на Highest и Production
                if (format == DDSImage.FormatEnum.BC5)
                {
                    compressionOptions.SetQuality(NvidiaTextureTools.Quality.Normal);
                }
                else
                {
                    compressionOptions.SetQuality(NvidiaTextureTools.Quality.Highest);
                }
                //compressionOptions.SetQuality( NvidiaTextureTools.Quality.Production );

                outputOptions.SetOutputHeader(false);
                outputOptions.SetOutputHandler(OutputOptions_BeginImage, OutputOptions_WriteData, OutputOptions_EndImage);

                generatingSurfaces = new List <DDSImage.Surface>();

                if (!compressor.Compress(inputOptions, compressionOptions, outputOptions))
                {
                    error = "Compression failed.";
                    return(null);
                }

                DDSImage.FormatEnum resultFormat = format;
                if (resultFormat == DDSImage.FormatEnum.R8G8B8)
                {
                    resultFormat = DDSImage.FormatEnum.A8R8G8B8;
                }
                DDSImage ddsImage = new DDSImage(resultFormat, generatingSurfaces.ToArray(), false);

                error = "";
                return(ddsImage);
            }
            catch (Exception e)
            {
                error = e.Message;
                return(null);
            }
            finally
            {
                generatingSurfaces          = null;
                generatingSurfaceDataOffset = 0;

                inputOptions?.Dispose();
                compressionOptions?.Dispose();
                outputOptions?.Dispose();
                compressor?.Dispose();
            }
        }
Beispiel #5
0
        public void applyModules()
        {
            for (int i = 0; i < memFiles.Count; i++)
            {
                log += "Mod: " + (i + 1) + " of " + memFiles.Count + " started: " + Path.GetFileName(memFiles[i]) + Environment.NewLine;
                using (FileStream fs = new FileStream(memFiles[i], FileMode.Open, FileAccess.Read))
                {
                    uint tag     = fs.ReadUInt32();
                    uint version = fs.ReadUInt32();
                    if (tag != TexExplorer.TextureModTag || version != TexExplorer.TextureModVersion)
                    {
                        if (version != TexExplorer.TextureModVersion)
                        {
                            errors += "File " + memFiles[i] + " was made with an older version of MEM, skipping..." + Environment.NewLine;
                            log    += "File " + memFiles[i] + " was made with an older version of MEM, skipping..." + Environment.NewLine;
                        }
                        else
                        {
                            errors += "File " + memFiles[i] + " is not a valid MEM mod, skipping..." + Environment.NewLine;
                            log    += "File " + memFiles[i] + " is not a valid MEM mod, skipping..." + Environment.NewLine;
                        }
                        continue;
                    }
                    else
                    {
                        uint gameType = 0;
                        fs.JumpTo(fs.ReadInt64());
                        gameType = fs.ReadUInt32();
                        if ((MeType)gameType != GameData.gameType)
                        {
                            errors += "File " + memFiles[i] + " is not a MEM mod valid for this game, skipping..." + Environment.NewLine;
                            log    += "File " + memFiles[i] + " is not a MEM mod valid for this game, skipping..." + Environment.NewLine;
                            continue;
                        }
                    }
                    int numFiles = fs.ReadInt32();
                    List <MipMaps.FileMod> modFiles = new List <MipMaps.FileMod>();
                    for (int k = 0; k < numFiles; k++)
                    {
                        MipMaps.FileMod fileMod = new MipMaps.FileMod();
                        fileMod.tag    = fs.ReadUInt32();
                        fileMod.name   = fs.ReadStringASCIINull();
                        fileMod.offset = fs.ReadInt64();
                        fileMod.size   = fs.ReadInt64();
                        modFiles.Add(fileMod);
                    }
                    numFiles = modFiles.Count;
                    for (int l = 0; l < numFiles; l++)
                    {
                        string name = "";
                        uint   crc = 0;
                        long   size = 0, dstLen = 0;
                        int    exportId = -1;
                        string pkgPath  = "";
                        byte[] dst      = null;
                        fs.JumpTo(modFiles[l].offset);
                        size = modFiles[l].size;
                        if (modFiles[l].tag == MipMaps.FileTextureTag)
                        {
                            name = fs.ReadStringASCIINull();
                            crc  = fs.ReadUInt32();
                        }
                        else if (modFiles[l].tag == MipMaps.FileBinaryTag)
                        {
                            name     = modFiles[l].name;
                            exportId = fs.ReadInt32();
                            pkgPath  = fs.ReadStringASCIINull();
                        }

                        dst    = MipMaps.decompressData(fs, size);
                        dstLen = dst.Length;

                        updateStatusTextures("Mod: " + (i + 1) + " of " + memFiles.Count + " - in progress: " + ((l + 1) * 100 / numFiles) + " % ");

                        if (modFiles[l].tag == MipMaps.FileTextureTag)
                        {
                            FoundTexture foundTexture;
                            foundTexture = textures.Find(s => s.crc == crc);
                            if (foundTexture.crc != 0)
                            {
                                DDSImage image = new DDSImage(new MemoryStream(dst, 0, (int)dstLen));
                                if (!image.checkExistAllMipmaps())
                                {
                                    errors += "Error in texture: " + name + string.Format("_0x{0:X8}", crc) + " Texture skipped. This texture has not all the required mipmaps" + Environment.NewLine;
                                    log    += "Error in texture: " + name + string.Format("_0x{0:X8}", crc) + " Texture skipped. This texture has not all the required mipmaps" + Environment.NewLine;
                                    continue;
                                }
                                errors += mipMaps.replaceTexture(image, foundTexture.list, cachePackageMgr, foundTexture.name, crc);
                            }
                            else
                            {
                                log += "Texture skipped. Texture " + name + string.Format("_0x{0:X8}", crc) + " is not present in your game setup" + Environment.NewLine;
                            }
                        }
                        else if (modFiles[l].tag == MipMaps.FileBinaryTag)
                        {
                            string path = GameData.GamePath + pkgPath;
                            if (!File.Exists(path))
                            {
                                log += "Warning: File " + path + " not exists in your game setup." + Environment.NewLine;
                                continue;
                            }
                            Package pkg = cachePackageMgr.OpenPackage(path);
                            pkg.setExportData(exportId, dst);
                        }
                        else
                        {
                            errors += "Unknown tag for file: " + name + Environment.NewLine;
                            log    += "Unknown tag for file: " + name + Environment.NewLine;
                        }
                    }
                }
            }
        }
Beispiel #6
0
        static public void Convert(string[] inArgs, long unitNumerator, long unitDenominator, bool idUseRenderAutoTip = false)
        {
            // configuration
            Configuration config          = Configuration.LoadIIDXConfig(Common.configFileName);
            Configuration db              = Common.LoadDB();
            int           quantizeMeasure = config["BMS"].GetValue("QuantizeMeasure");
            int           quantizeNotes   = config["BMS"].GetValue("QuantizeNotes");

            // splash
            Splash.Show("Chuni to Sus Script");
            Console.WriteLine("Timing: " + unitNumerator.ToString() + "/" + unitDenominator.ToString());
            Console.WriteLine("Measure Quantize: " + quantizeMeasure.ToString());

            // args
            string[] args;
            if (inArgs.Length > 0)
            {
                args = Subfolder.Parse(inArgs);
            }
            else
            {
                args = inArgs;
            }

            // debug args (if applicable)
            if (System.Diagnostics.Debugger.IsAttached && args.Length == 0)
            {
                Console.WriteLine();
                Console.WriteLine("Debugger attached. Input file name:");
                args = new string[] { Console.ReadLine() };
            }

            // show usage if no args provided
            if (args.Length == 0)
            {
                Console.WriteLine();
                Console.WriteLine("Usage: ChuniToSus <input file>");
                Console.WriteLine();
                Console.WriteLine("Drag and drop with files and folders is fully supported for this application.");
                Console.WriteLine();
                Console.WriteLine("Supported formats:");
                Console.WriteLine("C2S");
            }

            string output = config["BMS"]["Output"];

            // process files
            for (int i = 0; i < args.Length; i++)
            {
                if (File.Exists(args[i]))
                {
                    Console.WriteLine();
                    Console.WriteLine("Processing File: " + args[i]);
                    string filename = args[i];

                    byte[] data = File.ReadAllBytes(args[i]);
                    switch (Path.GetExtension(args[i]).ToUpper())
                    {
                    case @".C2S":
                        // Find ID
                        string fileName = Path.GetFileName(filename);
                        // Read Music file
                        string   C2sDir        = Path.GetDirectoryName(filename) + "\\";
                        XElement musicXml      = XElement.Load(Path.Combine(C2sDir, "Music.xml"));
                        string   id            = musicXml.Element("name").Element("id").Value;
                        string   title         = musicXml.Element("name").Element("str").Value;
                        string   artist        = musicXml.Element("artistName").Element("str").Value;
                        string   genre         = musicXml.Element("genreNames").Element("list").Element("StringID").Element("str").Value;
                        var      boxedLunchRow = musicXml.Element("fumens").Elements("MusicFumenData");

                        Dictionary <string, MusicData> musicData = new Dictionary <string, MusicData>();
                        foreach (XElement boxedLunchElement in boxedLunchRow)
                        {
                            if (boxedLunchElement.Element("file").Element("path").Value != "")
                            {
                                if (boxedLunchElement.Element("type").Element("id").Value == "4")
                                {
                                    musicData.Add(
                                        boxedLunchElement.Element("file").Element("path").Value,
                                        new MusicData()
                                    {
                                        type     = boxedLunchElement.Element("type").Element("id").Value + ":" + musicXml.Element("worldsEndTagName").Element("str").Value,
                                        typeName = boxedLunchElement.Element("type").Element("data").Value,
                                        level    = musicXml.Element("starDifType").Value
                                    }
                                        );
                                }
                                else
                                {
                                    musicData.Add(
                                        boxedLunchElement.Element("file").Element("path").Value,
                                        new MusicData()
                                    {
                                        type     = boxedLunchElement.Element("type").Element("id").Value,
                                        typeName = boxedLunchElement.Element("type").Element("data").Value,
                                        level    = boxedLunchElement.Element("level").Value
                                    }
                                        );
                                }
                            }
                        }

                        System.IO.StreamReader file = new System.IO.StreamReader(args[i]);
                        ChuniC2S   archive          = ChuniC2S.Read(file, unitNumerator, unitDenominator);
                        ChartChuni chart            = archive.chart;
                        chart.Tags["ID"]        = id;
                        chart.Tags["TITLE"]     = title;
                        chart.Tags["ARTIST"]    = artist;
                        chart.Tags["GENRE"]     = genre;
                        chart.Tags["PLAYLEVEL"] = musicData[fileName].level;
                        chart.Tags["TYPE"]      = musicData[fileName].type;
                        chart.Tags["TYPENAME"]  = musicData[fileName].typeName;

                        ConvertChart(chart, config, filename, 1, null, "1");
                        break;

                    case @".DDS":
                        // Find ID
                        fileName = Path.GetFileName(filename);
                        // Read Music file
                        C2sDir   = Path.GetDirectoryName(filename) + "\\";
                        musicXml = XElement.Load(Path.Combine(C2sDir, "Music.xml"));
                        title    = musicXml.Element("name").Element("str").Value;
                        genre    = musicXml.Element("genreNames").Element("list").Element("StringID").Element("str").Value;

                        DDSImage img = new DDSImage(filename);

                        string dirPath = Path.Combine(config["BMS"]["Output"], Common.nameReplace(genre), Common.nameReplace(title), "jacket.jpg");
                        img.Save(dirPath);

                        break;
                    }
                }
            }

            // wrap up
            Console.WriteLine("BemaniToBMS finished.");
        }
Beispiel #7
0
        private void OnSelectedItemChanged_ItemTree( object sender, RoutedPropertyChangedEventArgs<object> e )
        {
            TreeViewItem ViewItem = e.NewValue as TreeViewItem;
            if ( ViewItem == null )
            {
                return;
            }

            if ( SelectedRect == null )
            {
                SelectedRect = new Rectangle();
                MainCanvas.Children.Add( SelectedRect );
            }

            FileGUI.Element Win = ViewItem.Tag as FileGUI.Element;
            FileGUI.Element Size = Win[ "size" ];
            FileGUI.Element Pos = Win[ "position" ];

            SelectedRect.Width = Size.Field<double>( "x" );
            SelectedRect.Height = Size.Field<double>( "y" );
            Canvas.SetLeft( SelectedRect, Pos.Field<double>( "x" ) );
            Canvas.SetTop( SelectedRect, Pos.Field<double>( "x" ) );
            SelectedRect.Fill = Brushes.Transparent;
            SelectedRect.Stroke = Brushes.Black;

            PropGrid.ItemsSource = Win.ItemList;

            TextView.Focus();
            TextView.SelectionBrush = Brushes.Red;

            int Index = TextView.Text.IndexOf( Win.OuterText );
            if ( Index != -1 )
            {
                TextView.CaretIndex = Index;
                TextView.Select( Index, Win.OuterText.Length );
                TextView.Focus();
            }
            else
            {
                TextView.Select( 0, 0 );
            }

            FileGUI.Element GfxElement = Win.FindFirst( Elem => Elem.Name == "spriteType" );

            if ( GfxDoc != null && GfxElement != null )
            {
                char[] ToTrim = { '"' };
                string SpriteName = GfxElement.Value;//.Trim( ToTrim );

                FileGUI.Element Sprite = GfxDoc.FindFirst( Elem => Elem.Name == "spriteType" && Elem.Field<string>( "name" ) == SpriteName );
                if ( Sprite != null )
                {
                    string SpriteFileName = Sprite.Field<string>( "texturefile" ).Trim( ToTrim );
                    SpriteFileName = System.IO.Path.Combine( Utils.FindGamePath(), SpriteFileName );

                    DDSImage dds = new DDSImage( File.Open( SpriteFileName, FileMode.Open ) );
                    TestImage.Source = dds.Bitmap;
                    TestImage.Visibility = System.Windows.Visibility.Visible;
                }
            }
            else
            {
                TestImage.Visibility = System.Windows.Visibility.Hidden;
            }
        }
Beispiel #8
0
        public void textureInit(byte[] imageData, string _name)
        {
            DDSImage ddsImage;

            name = _name;

            ddsImage = new DDSImage(imageData);
            RenderStats.texturesNum += 1; //Accumulate settings

            Console.WriteLine("Sampler Name Path " + name + " Width {0} Height {1}", ddsImage.header.dwWidth, ddsImage.header.dwHeight);
            width  = ddsImage.header.dwWidth;
            height = ddsImage.header.dwHeight;
            int blocksize = 16;

            switch (ddsImage.header.ddspf.dwFourCC)
            {
            //DXT1
            case (0x31545844):
                pif       = InternalFormat.CompressedSrgbAlphaS3tcDxt1Ext;
                blocksize = 8;
                break;

            case (0x35545844):
                pif = InternalFormat.CompressedSrgbAlphaS3tcDxt5Ext;
                break;

            case (0x32495441):                          //ATI2A2XY
                pif = InternalFormat.CompressedRgRgtc2; //Normal maps are probably never srgb
                break;

            //DXT10 HEADER
            case (0x30315844):
            {
                switch (ddsImage.header10.dxgiFormat)
                {
                case (DXGI_FORMAT.DXGI_FORMAT_BC7_UNORM):
                    pif = InternalFormat.CompressedSrgbAlphaBptcUnorm;
                    break;

                default:
                    throw new ApplicationException("Unimplemented DX10 Texture Pixel format");
                }
                break;
            }

            default:
                throw new ApplicationException("Unimplemented Pixel format");
            }

            //Temp Variables
            int w           = width;
            int h           = height;
            int mm_count    = ddsImage.header.dwMipMapCount;
            int depth_count = Math.Max(1, ddsImage.header.dwDepth); //Fix the counter to 1 to fit the texture in a 3D container
            int temp_size   = ddsImage.header.dwPitchOrLinearSize;


            //Generate PBO
            pboID = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.PixelUnpackBuffer, pboID);
            GL.BufferData(BufferTarget.PixelUnpackBuffer, ddsImage.bdata.Length, ddsImage.bdata, BufferUsageHint.StaticDraw);
            //GL.BufferSubData(BufferTarget.PixelUnpackBuffer, IntPtr.Zero, ddsImage.bdata.Length, ddsImage.bdata);

            //Upload to GPU
            texID  = GL.GenTexture();
            target = TextureTarget.Texture2DArray;

            GL.BindTexture(target, texID);
            //When manually loading mipmaps, levels should be loaded first
            GL.TexParameter(target, TextureParameterName.TextureBaseLevel, 0);
            //GL.TexParameter(target, TextureParameterName.TextureMaxLevel, mm_count - 1);

            int offset = 0;

            for (int i = 0; i < mm_count; i++)
            {
                GL.CompressedTexImage3D(target, i, pif, w, h, depth_count, 0, temp_size * depth_count, IntPtr.Zero + offset);
                offset += temp_size * depth_count;

                w = Math.Max(w >> 1, 1);
                h = Math.Max(h >> 1, 1);

                temp_size = Math.Max(1, (w + 3) / 4) * Math.Max(1, (h + 3) / 4) * blocksize;
                //This works only for square textures
                //temp_size = Math.Max(temp_size/4, blocksize);
            }

            //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureLodBias, -0.2f);
            GL.TexParameter(target, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(target, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            GL.TexParameter(target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            //Console.WriteLine(GL.GetError());

            //Use anisotropic filtering
            float af_amount = GL.GetFloat((GetPName)All.MaxTextureMaxAnisotropy);

            af_amount = (float)Math.Max(af_amount, 4.0f);
            //GL.TexParameter(TextureTarget.Texture2D,  (TextureParameterName) 0x84FE, af_amount);
            int max_level = 0;

            GL.GetTexParameter(target, GetTextureParameter.TextureMaxLevel, out max_level);
            int base_level = 0;

            GL.GetTexParameter(target, GetTextureParameter.TextureBaseLevel, out base_level);

            int maxsize = Math.Max(height, width);
            int p       = (int)Math.Floor(Math.Log(maxsize, 2)) + base_level;
            int q       = Math.Min(p, max_level);

#if (DEBUGNONO)
            //Get all mipmaps
            temp_size = ddsImage.header.dwPitchOrLinearSize;
            for (int i = 0; i < q; i++)
            {
                //Get lowest calculated mipmap
                byte[] pixels = new byte[temp_size];

                //Save to disk
                GL.GetCompressedTexImage(TextureTarget.Texture2D, i, pixels);
                File.WriteAllBytes("Temp\\level" + i.ToString(), pixels);
                temp_size = Math.Max(temp_size / 4, 16);
            }
#endif

#if (DUMP_TEXTURESNONO)
            Sampler.dump_texture(name.Split('\\').Last().Split('/').Last(), width, height);
#endif
            //avgColor = getAvgColor(pixels);
            ddsImage = null;
            GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); //Unbind texture PBO
        }
Beispiel #9
0
        private static void LoadTexture(Stream input, out Texture output)
        {
            if (input == null)
            {
                output = null;
                return;
            }

            var magic = new byte[4];

            input.Read(magic, 0, 4);
            input.Position = 0;

            var a = (char)magic[0];
            var b = (char)magic[1];
            var c = (char)magic[2];
            var d = (char)magic[3];

            if (VisualC.CompareMemory(magic, DDSImage.MagicBytes, 4) == 0)
            {
                var test = new DDSImage(input);

                output = new Texture(test.Texture2D)
                {
                    Name = "Cubemap (DDS)"
                };
                return;
            }

            var faces = new DataRectangle[6];

            using (var decoder = new BitmapDecoder(Renderer.ImagingFactory, input, DecodeOptions.CacheOnDemand))
            {
                var frame     = decoder.GetFrame(0);
                var converter = new FormatConverter(Renderer.ImagingFactory);

                converter.Initialize(
                    frame,
                    PixelFormat.Format32bppPRGBA,
                    BitmapDitherType.None, null,
                    0.0, BitmapPaletteType.Custom);

                var width  = frame.Size.Width;
                var height = frame.Size.Height;
                var ratio  = width / (float)height;

                if (Math.Abs(ratio - 2) < 0.001)                 // panorama
                {
                    throw new NotImplementedException();
                }
                if (Math.Abs(ratio - 1.333f) < 0.001)                 // cubic
                {
                    var tileDim = (int)(width / 4f);
                    var stride  = tileDim * 4;

                    Action <int, int, int> loadFace = delegate(int index, int coordX, int coordY)
                    {
                        var faceStream = new DataStream(tileDim * stride, false, true);

                        using (var crop = new BitmapClipper(Renderer.ImagingFactory))
                        {
                            crop.Initialize(converter, new RawBox(coordX, coordY, tileDim, tileDim));
                            crop.CopyPixels(stride, faceStream);
                        }

                        faces[index] = new DataRectangle(faceStream.DataPointer, stride);
                    };

                    loadFace(0, tileDim * 2, tileDim);
                    loadFace(1, 0, tileDim);
                    loadFace(2, tileDim, 0);
                    loadFace(3, tileDim, tileDim * 2);
                    loadFace(4, tileDim, tileDim);
                    loadFace(5, tileDim * 3, tileDim);

                    var texture2D = new Texture2D(Renderer.Device, new Texture2DDescription
                    {
                        Width             = tileDim,
                        Height            = tileDim,
                        ArraySize         = 6,
                        BindFlags         = BindFlags.ShaderResource,
                        Usage             = ResourceUsage.Immutable,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        Format            = Format.R8G8B8A8_UNorm,
                        MipLevels         = 1,
                        OptionFlags       = ResourceOptionFlags.TextureCube,
                        SampleDescription = new SampleDescription(1, 0)
                    }, faces);

                    converter.Dispose();

                    output      = new Texture(texture2D);
                    output.Name = output.NativeTexture.Tag.ToString();
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
        }
Beispiel #10
0
        static bool GenerateFile(string sourceRealFileName, bool generateIrradiance, int destSize, string destRealFileName, List <Vector3> outIrradianceValues, out string error)
        {
            var tempDirectory = GetTemporaryDirectory();

            string arguments;

            if (generateIrradiance)
            {
                arguments = $"--format=hdr --size={destSize} --type=cubemap --ibl-irradiance=\"{tempDirectory}\" \"{sourceRealFileName}\"";
            }
            else
            {
                arguments = $"--format=hdr --size={destSize} --type=cubemap -x \"{tempDirectory}\" \"{sourceRealFileName}\"";
            }

            var process = new Process();

            process.StartInfo.FileName  = Path.Combine(VirtualFileSystem.Directories.EngineInternal, @"Tools\Filament\cmgen.exe");
            process.StartInfo.Arguments = arguments;
            process.Start();
            process.WaitForExit();

            var exitCode = process.ExitCode;

            if (exitCode != 0)
            {
                error = $"cmgen.exe exit code = {exitCode}.";
                return(false);
            }

            var folder = Path.Combine(tempDirectory, Path.GetFileNameWithoutExtension(sourceRealFileName));

            int  size;
            bool need16bit = false;
            {
                var file  = Path.Combine(folder, generateIrradiance ? "i_nx.hdr" : "m0_nx.hdr");
                var bytes = File.ReadAllBytes(file);
                if (!ImageUtility.LoadFromBuffer(bytes, "hdr", out var data, out var size2, out _, out var format, out _, out _, out error))
                {
                    return(false);
                }
                size = size2.X;
                if (format != PixelFormat.Float32RGB)
                {
                    error = "format != PixelFormat.Float32RGB";
                    return(false);
                }

                var image2D = new ImageUtility.Image2D(format, size2, data);
                for (int y = 0; y < image2D.Size.Y; y++)
                {
                    for (int x = 0; x < image2D.Size.X; x++)
                    {
                        var v = image2D.GetPixel(new Vector2I(x, y));
                        if (v.X > 1.001f || v.Y >= 1.001f || v.Z >= 1.001f)
                        {
                            need16bit = true;
                            goto end16bit;
                        }
                    }
                }
                end16bit :;
            }

            var surfaces = new List <DDSImage.Surface>();

            for (int face = 0; face < 6; face++)
            {
                int counter     = 0;
                int currentSize = size;
                while (currentSize > 0)
                {
                    var postfixes = new string[] { "px", "nx", "py", "ny", "pz", "nz" };

                    string file;
                    if (generateIrradiance)
                    {
                        file = Path.Combine(folder, $"i_{postfixes[ face ]}.hdr");
                    }
                    else
                    {
                        file = Path.Combine(folder, $"m{counter}_{postfixes[ face ]}.hdr");
                    }

                    var bytes = File.ReadAllBytes(file);
                    if (!ImageUtility.LoadFromBuffer(bytes, "hdr", out var data, out var size2, out _, out var format, out _, out _, out error))
                    {
                        return(false);
                    }
                    if (format != PixelFormat.Float32RGB)
                    {
                        error = "format != PixelFormat.Float32RGB";
                        return(false);
                    }
                    if (size2.X != currentSize)
                    {
                        error = "size2.X != currentSize";
                        return(false);
                    }

                    if (need16bit)
                    {
                        byte[] newData = new byte[currentSize * currentSize * 4 * 2];

                        unsafe
                        {
                            fixed(byte *pData = data)
                            {
                                float *pData2 = (float *)pData;

                                fixed(byte *pNewData = newData)
                                {
                                    Half *pNewData2 = (Half *)pNewData;

                                    for (int n = 0; n < currentSize * currentSize; n++)
                                    {
                                        pNewData2[n * 4 + 0] = new Half(pData2[n * 3 + 0]);
                                        pNewData2[n * 4 + 1] = new Half(pData2[n * 3 + 1]);
                                        pNewData2[n * 4 + 2] = new Half(pData2[n * 3 + 2]);
                                        pNewData2[n * 4 + 3] = new Half(1.0f);
                                    }
                                }
                            }
                        }

                        surfaces.Add(new DDSImage.Surface(new Vector2I(currentSize, currentSize), newData));
                    }
                    else
                    {
                        byte[] newData = new byte[currentSize * currentSize * 4];

                        unsafe
                        {
                            fixed(byte *pData = data)
                            {
                                float *pData2 = (float *)pData;

                                for (int n = 0; n < currentSize * currentSize; n++)
                                {
                                    newData[n * 4 + 3] = 255;
                                    newData[n * 4 + 2] = (byte)(MathEx.Saturate(pData2[n * 3 + 0]) * 255.0);
                                    newData[n * 4 + 1] = (byte)(MathEx.Saturate(pData2[n * 3 + 1]) * 255.0);
                                    newData[n * 4 + 0] = (byte)(MathEx.Saturate(pData2[n * 3 + 2]) * 255.0);
                                }
                            }
                        }

                        surfaces.Add(new DDSImage.Surface(new Vector2I(currentSize, currentSize), newData));
                    }

                    counter++;
                    currentSize /= 2;

                    if (generateIrradiance)
                    {
                        break;
                    }
                }
            }

            var image = new DDSImage(need16bit ? DDSImage.FormatEnum.R16G16B16A16 : DDSImage.FormatEnum.X8R8G8B8, surfaces.ToArray(), true);

            if (!WriteToFile(destRealFileName, image, out error))
            {
                return(false);
            }

            if (outIrradianceValues != null)
            {
                var shFile = Path.Combine(folder, "sh.txt");
                var lines  = File.ReadAllLines(shFile);
                foreach (var line in lines)
                {
                    var index1 = line.IndexOf('(');
                    var index2 = line.IndexOf(')');
                    if (index1 != -1 && index2 != -1)
                    {
                        var str = line.Substring(index1 + 1, index2 - index1 - 1).Trim();

                        var strs = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (strs.Length != 3)
                        {
                            error = "Unable to parse \"sh.txt\".";
                            return(false);
                        }

                        var x = double.Parse(strs[0].Trim());
                        var y = double.Parse(strs[1].Trim());
                        var z = double.Parse(strs[2].Trim());

                        outIrradianceValues.Add(new Vector3(x, y, z));
                    }
                }
            }

            DeleteDirectory(tempDirectory);

            error = "";
            return(true);
        }
        public string replaceTexture(DDSImage image, List <MatchedTexture> list, CachePackageMgr cachePackageMgr, string textureName, uint crc)
        {
            List <Texture> masterTextures = new List <Texture>();
            Texture        arcTexture = null, cprTexture = null;
            string         errors = "";

            for (int n = 0; n < list.Count; n++)
            {
                MatchedTexture nodeTexture = list[n];
                Package        package     = cachePackageMgr.OpenPackage(GameData.GamePath + nodeTexture.path);
                Texture        texture     = new Texture(package, nodeTexture.exportID, package.getExportData(nodeTexture.exportID));
                while (texture.mipMapsList.Exists(s => s.storageType == Texture.StorageTypes.empty))
                {
                    texture.mipMapsList.Remove(texture.mipMapsList.First(s => s.storageType == Texture.StorageTypes.empty));
                }
                bool master = true;
                if (GameData.gameType == MeType.ME1_TYPE)
                {
                    if (texture.packageName.ToLowerInvariant() != Path.GetFileNameWithoutExtension(package.packageFile.Name).ToLowerInvariant())
                    {
                        master = false;
                        if (!masterTextures.Exists(s => s.packageName.ToLowerInvariant() == texture.packageName.ToLowerInvariant()))
                        {
                            errors += "Error in texture: " + textureName + " Broken game file: " + nodeTexture.path + ", skipping texture..." + Environment.NewLine;
                            continue;
                        }
                    }
                }

                if (texture.mipMapsList.Count > 1 && image.mipMaps.Count() <= 1)
                {
                    errors += "Error in texture: " + textureName + " This texture has not all the required mipmaps, skipping texture..." + Environment.NewLine;
                    break;
                }

                string    fmt       = texture.properties.getProperty("Format").valueName;
                DDSFormat ddsFormat = DDSImage.convertFormat(fmt);
                if (image.ddsFormat != ddsFormat)
                {
                    errors += "Error in texture: " + textureName + " This texture has wrong texture format, should be: " + ddsFormat + ", skipping texture..." + Environment.NewLine;
                    break;
                }

                if (image.mipMaps[0].origWidth / image.mipMaps[0].origHeight !=
                    texture.mipMapsList[0].width / texture.mipMapsList[0].height)
                {
                    errors += "Error in texture: " + textureName + " This texture has wrong aspect ratio, skipping texture..." + Environment.NewLine;
                    break;
                }

                // remove lower mipmaps from source image which not exist in game data
                for (int t = 0; t < image.mipMaps.Count(); t++)
                {
                    if (image.mipMaps[t].origWidth <= texture.mipMapsList[0].width &&
                        image.mipMaps[t].origHeight <= texture.mipMapsList[0].height &&
                        texture.mipMapsList.Count > 1)
                    {
                        if (!texture.mipMapsList.Exists(m => m.width == image.mipMaps[t].origWidth && m.height == image.mipMaps[t].origHeight))
                        {
                            image.mipMaps.RemoveAt(t--);
                        }
                    }
                }

                bool skip = false;
                // reuse lower mipmaps from game data which not exist in source image
                for (int t = 0; t < texture.mipMapsList.Count; t++)
                {
                    if (texture.mipMapsList[t].width <= image.mipMaps[0].origWidth &&
                        texture.mipMapsList[t].height <= image.mipMaps[0].origHeight)
                    {
                        if (!image.mipMaps.Exists(m => m.origWidth == texture.mipMapsList[t].width && m.origHeight == texture.mipMapsList[t].height))
                        {
                            byte[] data = texture.getMipMapData(texture.mipMapsList[t]);
                            if (data == null)
                            {
                                errors += "Error in game data: " + nodeTexture.path + ", skipping texture..." + Environment.NewLine;
                                skip    = true;
                                break;
                            }
                            DDSImage.MipMap mipmap = new DDSImage.MipMap(data, ddsFormat, texture.mipMapsList[t].width, texture.mipMapsList[t].height);
                            image.mipMaps.Add(mipmap);
                        }
                    }
                }
                if (skip)
                {
                    continue;
                }

                package.DisposeCache();

                bool   triggerCacheArc = false, triggerCacheCpr = false;
                string archiveFile = "";
                byte[] origGuid    = new byte[16];
                if (texture.properties.exists("TextureFileCacheName"))
                {
                    Array.Copy(texture.properties.getProperty("TFCFileGuid").valueStruct, origGuid, 16);
                    string archive = texture.properties.getProperty("TextureFileCacheName").valueName;
                    archiveFile = Path.Combine(GameData.MainData, archive + ".tfc");
                    if (nodeTexture.path.ToLowerInvariant().Contains("\\dlc"))
                    {
                        string DLCArchiveFile = Path.Combine(Path.GetDirectoryName(GameData.GamePath + nodeTexture.path), archive + ".tfc");
                        if (File.Exists(DLCArchiveFile))
                        {
                            archiveFile = DLCArchiveFile;
                        }
                        else if (!File.Exists(archiveFile))
                        {
                            List <string> files = Directory.GetFiles(GameData.bioGamePath, archive + ".tfc",
                                                                     SearchOption.AllDirectories).Where(item => item.EndsWith(".tfc", StringComparison.OrdinalIgnoreCase)).ToList();
                            if (files.Count == 0)
                            {
                                archiveFile = Path.Combine(GameData.MainData, "Textures.tfc");
                            }
                            else if (files.Count == 1)
                            {
                                archiveFile = files[0];
                            }
                            else
                            {
                                throw new Exception("");
                            }
                        }
                    }
                    long fileLength = new FileInfo(archiveFile).Length;
                    if (fileLength + 0x5000000 > 0x80000000)
                    {
                        archiveFile = "";
                        foreach (TFCTexture newGuid in guids)
                        {
                            archiveFile = Path.Combine(GameData.MainData, newGuid.name + ".tfc");
                            if (!File.Exists(archiveFile))
                            {
                                texture.properties.setNameValue("TextureFileCacheName", newGuid.name);
                                texture.properties.setStructValue("TFCFileGuid", "Guid", newGuid.guid);
                                using (FileStream fs = new FileStream(archiveFile, FileMode.CreateNew, FileAccess.Write))
                                {
                                    fs.WriteFromBuffer(newGuid.guid);
                                }
                                break;
                            }
                            else
                            {
                                fileLength = new FileInfo(archiveFile).Length;
                                if (fileLength + 0x5000000 < 0x80000000)
                                {
                                    texture.properties.setNameValue("TextureFileCacheName", newGuid.name);
                                    texture.properties.setStructValue("TFCFileGuid", "Guid", newGuid.guid);
                                    break;
                                }
                            }
                            archiveFile = "";
                        }
                        if (archiveFile == "")
                        {
                            throw new Exception("No free TFC texture file!");
                        }
                    }
                }

                List <Texture.MipMap> mipmaps = new List <Texture.MipMap>();
                for (int m = 0; m < image.mipMaps.Count(); m++)
                {
                    Texture.MipMap mipmap = new Texture.MipMap();
                    mipmap.width  = image.mipMaps[m].origWidth;
                    mipmap.height = image.mipMaps[m].origHeight;
                    if (texture.existMipmap(mipmap.width, mipmap.height))
                    {
                        mipmap.storageType = texture.getMipmap(mipmap.width, mipmap.height).storageType;
                    }
                    else
                    {
                        mipmap.storageType = texture.getTopMipmap().storageType;
                        if (GameData.gameType == MeType.ME1_TYPE && master == false)
                        {
                            if (mipmap.storageType == Texture.StorageTypes.pccUnc ||
                                mipmap.storageType == Texture.StorageTypes.pccLZO ||
                                mipmap.storageType == Texture.StorageTypes.pccZlib)
                            {
                                mipmap.storageType = Texture.StorageTypes.extLZO;
                            }
                        }
                        else if (GameData.gameType == MeType.ME2_TYPE || GameData.gameType == MeType.ME3_TYPE)
                        {
                            if (texture.properties.exists("TextureFileCacheName") && texture.mipMapsList.Count > 1)
                            {
                                if (texture.mipMapsList.Count < 6)
                                {
                                    mipmap.storageType = Texture.StorageTypes.pccUnc;
                                    if (!texture.properties.exists("NeverStream"))
                                    {
                                        if (package.existsNameId("NeverStream"))
                                        {
                                            texture.properties.addBoolValue("NeverStream", true);
                                        }
                                        else
                                        {
                                            goto skip;
                                        }
                                    }
                                }
                                else
                                {
                                    if (GameData.gameType == MeType.ME2_TYPE)
                                    {
                                        mipmap.storageType = Texture.StorageTypes.extLZO;
                                    }
                                    else
                                    {
                                        mipmap.storageType = Texture.StorageTypes.extZlib;
                                    }
                                }
                            }
                        }
                    }

                    if (mipmap.storageType == Texture.StorageTypes.extLZO)
                    {
                        mipmap.storageType = Texture.StorageTypes.extZlib;
                    }
                    if (mipmap.storageType == Texture.StorageTypes.pccLZO)
                    {
                        mipmap.storageType = Texture.StorageTypes.pccZlib;
                    }

                    mipmap.uncompressedSize = image.mipMaps[m].data.Length;
                    if (GameData.gameType == MeType.ME1_TYPE)
                    {
                        if (mipmap.storageType == Texture.StorageTypes.pccLZO ||
                            mipmap.storageType == Texture.StorageTypes.pccZlib)
                        {
                            if (master)
                            {
                                mipmap.newData = texture.compressTexture(image.mipMaps[m].data, mipmap.storageType);
                            }
                            else
                            {
                                mipmap.newData = masterTextures.Find(s => s.packageName.ToLowerInvariant() == texture.packageName.ToLowerInvariant()).mipMapsList[m].newData;
                            }
                            mipmap.compressedSize = mipmap.newData.Length;
                        }
                        if (mipmap.storageType == Texture.StorageTypes.pccUnc)
                        {
                            mipmap.compressedSize = mipmap.uncompressedSize;
                            mipmap.newData        = image.mipMaps[m].data;
                        }
                        if ((mipmap.storageType == Texture.StorageTypes.extLZO ||
                             mipmap.storageType == Texture.StorageTypes.extZlib) && master == false)
                        {
                            mipmap.compressedSize = masterTextures.Find(s => s.packageName.ToLowerInvariant() == texture.packageName.ToLowerInvariant()).mipMapsList[m].compressedSize;
                            mipmap.dataOffset     = masterTextures.Find(s => s.packageName.ToLowerInvariant() == texture.packageName.ToLowerInvariant()).mipMapsList[m].dataOffset;
                        }
                    }
                    else
                    {
                        if (mipmap.storageType == Texture.StorageTypes.extZlib ||
                            mipmap.storageType == Texture.StorageTypes.extLZO)
                        {
                            if (cprTexture == null || (cprTexture != null && mipmap.storageType != cprTexture.mipMapsList[m].storageType))
                            {
                                mipmap.newData  = texture.compressTexture(image.mipMaps[m].data, mipmap.storageType);
                                triggerCacheCpr = true;
                            }
                            else
                            {
                                if (cprTexture.mipMapsList[m].width != mipmap.width ||
                                    cprTexture.mipMapsList[m].height != mipmap.height)
                                {
                                    throw new Exception();
                                }
                                mipmap.newData = cprTexture.mipMapsList[m].newData;
                            }
                            mipmap.compressedSize = mipmap.newData.Length;
                        }
                        if (mipmap.storageType == Texture.StorageTypes.pccUnc ||
                            mipmap.storageType == Texture.StorageTypes.extUnc)
                        {
                            mipmap.compressedSize = mipmap.uncompressedSize;
                            mipmap.newData        = image.mipMaps[m].data;
                        }
                        if (mipmap.storageType == Texture.StorageTypes.extZlib ||
                            mipmap.storageType == Texture.StorageTypes.extLZO ||
                            mipmap.storageType == Texture.StorageTypes.extUnc)
                        {
                            if (arcTexture == null ||
                                !StructuralComparisons.StructuralEqualityComparer.Equals(
                                    arcTexture.properties.getProperty("TFCFileGuid").valueStruct,
                                    texture.properties.getProperty("TFCFileGuid").valueStruct))
                            {
                                triggerCacheArc = true;
                                Texture.MipMap oldMipmap = texture.getMipmap(mipmap.width, mipmap.height);
                                if (StructuralComparisons.StructuralEqualityComparer.Equals(origGuid,
                                                                                            texture.properties.getProperty("TFCFileGuid").valueStruct) &&
                                    oldMipmap.width != 0 && mipmap.newData.Length <= oldMipmap.compressedSize)
                                {
                                    try
                                    {
                                        using (FileStream fs = new FileStream(archiveFile, FileMode.Open, FileAccess.Write))
                                        {
                                            fs.JumpTo(oldMipmap.dataOffset);
                                            mipmap.dataOffset = oldMipmap.dataOffset;
                                            fs.WriteFromBuffer(mipmap.newData);
                                        }
                                    }
                                    catch
                                    {
                                        throw new Exception("Problem with access to TFC file: " + archiveFile);
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        using (FileStream fs = new FileStream(archiveFile, FileMode.Open, FileAccess.Write))
                                        {
                                            fs.SeekEnd();
                                            mipmap.dataOffset = (uint)fs.Position;
                                            fs.WriteFromBuffer(mipmap.newData);
                                        }
                                    }
                                    catch
                                    {
                                        throw new Exception("Problem with access to TFC file: " + archiveFile);
                                    }
                                }
                            }
                            else
                            {
                                if (arcTexture.mipMapsList[m].width != mipmap.width ||
                                    arcTexture.mipMapsList[m].height != mipmap.height)
                                {
                                    throw new Exception();
                                }
                                mipmap.dataOffset = arcTexture.mipMapsList[m].dataOffset;
                            }
                        }
                    }

                    mipmap.width  = image.mipMaps[m].width;
                    mipmap.height = image.mipMaps[m].height;
                    mipmaps.Add(mipmap);
                    if (texture.mipMapsList.Count() == 1)
                    {
                        break;
                    }
                }
                texture.replaceMipMaps(mipmaps);
                texture.properties.setIntValue("SizeX", texture.mipMapsList.First().width);
                texture.properties.setIntValue("SizeY", texture.mipMapsList.First().height);
                if (texture.properties.exists("MipTailBaseIdx"))
                {
                    texture.properties.setIntValue("MipTailBaseIdx", texture.mipMapsList.Count() - 1);
                }
                if (GameData.gameType == MeType.ME1_TYPE && crc == 0x39A26907)
                {
                    if (!texture.properties.exists("LODGroup"))
                    {
                        texture.properties.addByteValue("LODGroup", "TEXTUREGROUP_Character", 1025);
                    }
                    else
                    {
                        texture.properties.setByteValue("LODGroup", "TEXTUREGROUP_Character", 1025);
                    }
                }

                using (MemoryStream newData = new MemoryStream())
                {
                    newData.WriteFromBuffer(texture.properties.toArray());
                    newData.WriteFromBuffer(texture.toArray(0)); // filled later
                    package.setExportData(nodeTexture.exportID, newData.ToArray());
                }

                using (MemoryStream newData = new MemoryStream())
                {
                    newData.WriteFromBuffer(texture.properties.toArray());
                    newData.WriteFromBuffer(texture.toArray(package.exportsTable[nodeTexture.exportID].dataOffset + (uint)newData.Position));
                    package.setExportData(nodeTexture.exportID, newData.ToArray());
                }

                if (GameData.gameType == MeType.ME1_TYPE)
                {
                    if (master)
                    {
                        masterTextures.Add(texture);
                    }
                }
                else
                {
                    if (triggerCacheCpr)
                    {
                        cprTexture = texture;
                    }
                    if (triggerCacheArc)
                    {
                        arcTexture = texture;
                    }
                }
skip:
                package = null;
            }
            masterTextures = null;
            arcTexture     = cprTexture = null;

            return(errors);
        }
        public override void ParseBytes(CR2WBinaryReader br, uint size)
        {
            base.ParseBytes(br, size);

            /*
             *  This is a temporary solution for reading the contents of a CBitmapTexture
             *  What this does is contruct a dds header object and parse it and the raw bytes
             *  using the dds library.
             *
             *  The bitmap bytes from the cr2w has a header 28 bytes long, containing data about the
             *  image such as size and height etc...
             *  There are 4 unknown ones.
             *
             *  This class should in the end support reading all xbm files with means supporting not just
             *  dds but tga, bmp, png, and jpg.
             *
             */

            var zero        = br.ReadUInt32();
            var mipCount    = br.ReadUInt32();
            var width       = br.ReadUInt32();
            var height      = br.ReadUInt32();
            var unknown5    = br.ReadUInt32();
            var sizeorpitch = br.ReadUInt32();

            Console.WriteLine("zero        {0}", zero);
            Console.WriteLine("mipCount    {0}", mipCount);
            Console.WriteLine("width       {0}", width);
            Console.WriteLine("height      {0}", height);
            Console.WriteLine("unknown5    {0}", unknown5);
            Console.WriteLine("sizeorpitch {0}", sizeorpitch);

            var ddsheader = new DDSStruct
            {
                size        = 124,
                flags       = 659463,
                width       = width,
                height      = height,
                sizeorpitch = sizeorpitch,
                depth       = 1,
                mipmapcount = 1,
                reserved    = new uint[10],
            };

            ddsheader.ddscaps.caps1      = 4096;
            ddsheader.pixelformat.size   = 32;
            ddsheader.pixelformat.flags  = 5;
            ddsheader.pixelformat.fourcc = DDSHelper.FOURCC_DXT1;

            var dds = new DDSImage(br, ddsheader, true);

            Form form = new Form
            {
                Text       = "Image",
                ClientSize = new Size((int)width, (int)height),
            };
            PictureBox pictureBox = new PictureBox
            {
                Image  = dds.BitmapImage,
                Width  = (int)width,
                Height = (int)height
            };

            form.Controls.Add(pictureBox);
            var t = new Task(() =>
            {
                Application.Run(form);
            });

            t.Start();
        }
        public static bool ExportModel(rModel model, string outputFolder)
        {
            // Setup xml writer formatting settings.
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent       = true;
            settings.IndentChars  = "  ";
            settings.NewLineChars = "\r\n";
            settings.Encoding     = Encoding.UTF8;

            // Create a new xml writer for the output collada file.
            string modelName = Path.GetFileName(model.FileName).Replace(".rModel", "");

            using (XmlWriter writer = XmlWriter.Create(string.Format("{0}\\{1}.dae", outputFolder, modelName), settings))
            {
                // Write the xml header.
                writer.WriteStartDocument();

                // Write the collada element start.
                writer.WriteStartElement("COLLADA", "http://www.collada.org/2004/COLLADASchema");
                writer.WriteAttributeString("version", "1.4.1");

                // Write the asset element.
                writer.WriteStartElement("asset");
                writer.WriteStartElement("contributor");
                writer.WriteElementString("authoring_tool", "Dead Rising Arc Tool");
                writer.WriteFullEndElement();
                writer.WriteElementString("created", DateTime.Now.ToString());
                writer.WriteElementString("modified", DateTime.Now.ToString());
                writer.WriteFullEndElement();

                // Write the images library element.
                writer.WriteStartElement("library_images");
                {
                    // Loop and write and image element for every texture the model has.
                    for (int i = 0; i < model.textureFileNames.Length; i++)
                    {
                        // Get name of the texture.
                        string textureName = Path.GetFileName(model.textureFileNames[i]);

                        // Find the arc file the resource is in.
                        string textureFileName = GameResource.GetFullResourceName(model.textureFileNames[i], ResourceType.rTexture);
                        ArchiveCollection.Instance.GetArchiveFileEntryFromFileName(textureFileName, out Archive.Archive arcFile, out ArchiveFileEntry fileEntry);
                        if (arcFile == null || fileEntry == null)
                        {
                            // Failed to find a resource with the specified name.
                            return(false);
                        }

                        // Parse the game resource and cast it to rtexture.
                        rTexture texture = arcFile.GetFileAsResource <rTexture>(textureFileName);

                        // Save the texture to a dds image that can be loaded with the model.
                        DDSImage ddsImage = DDSImage.FromGameTexture(texture);
                        if (ddsImage.WriteToFile(string.Format("{0}\\{1}.dds", outputFolder, textureName)) == false)
                        {
                            // Failed to extract texture to file.
                            return(false);
                        }

                        // Write the image element.
                        writer.WriteStartElement("image");
                        writer.WriteAttributeString("name", textureName);
                        writer.WriteElementString("init_from", "./" + textureName + ".dds");
                        writer.WriteFullEndElement();
                    }
                }
                writer.WriteFullEndElement();

                // Write the materials library element.
                //writer.WriteStartElement("library_materials");
                //{
                //    // Loop through all of the materials and write each one.
                //    for (int i = 0; i < model.materials.Length; i++)
                //    {
                //        // Write the material element.
                //        writer.WriteStartElement("material");
                //        writer.WriteAttributeString("id", "Material " + i.ToString());
                //    }
                //}
                //writer.WriteFullEndElement();

                // TODO: Joints

                // Write the geometries library element.
                writer.WriteStartElement("library_geometries");
                {
                    // Loop through all the primitives and write each one.
                    for (int i = 0; i < model.primitives.Length; i++)
                    {
                        // Write the primitive to file.
                        WritePrimitiveBlock(model, writer, i);
                    }
                }
                writer.WriteFullEndElement();

                // Write the collada and document end.
                writer.WriteEndElement();
                writer.WriteEndDocument();

                // Flush to file.
                writer.Close();
                return(true);
            }
        }
Beispiel #14
0
        public void SetImage(Image NewImage, string Format)
        {
            this._Image          = NewImage;
            this._IsImageChecked = true;
            this._Thumbnail      = null;

            Format           = Format.ToLower();
            this.ImageFormat = Format;

            if (NewImage == null)
            {
                this.SetContents(null);
            }
            else
            {
                MemoryStream _newStream = new MemoryStream();                 // MemoryStream should remain open for the lifetime of the Bitmap

                switch (Format)
                {
                case "16-bit":
                case "rgb16":
                case "argb16":
                case "dxt1":
                    if (GetAlphaBits() == 0)
                    {
                        DDSImage.Save((Bitmap)this.GetImage(), _newStream, DDSImage.CompressionMode.R5G6B5);
                        this.ImageFormat    = ".dds";
                        this.ImageSubformat = "RGB16";
                    }
                    else
                    {
                        DDSImage.Save((Bitmap)this.GetImage(), _newStream, DDSImage.CompressionMode.A1R5G5B5);
                        this.ImageFormat    = ".dds";
                        this.ImageSubformat = "ARGB16";
                    }
                    break;

                case "24-bit":
                case "rgb24":
                    DDSImage.Save((Bitmap)this.GetImage(), _newStream, DDSImage.CompressionMode.RGB24);
                    this.ImageFormat    = ".dds";
                    this.ImageSubformat = "RGB24";
                    break;

                case "32-bit":
                case "rgb32":
                case "dxt2":
                case "dxt3":
                case "dxt4":
                case "dxt5":
                    DDSImage.Save((Bitmap)this.GetImage(), _newStream, DDSImage.CompressionMode.RGB32);
                    this.ImageFormat    = ".dds";
                    this.ImageSubformat = "RGB32";
                    break;

                case ".bmp":
                    this.GetImage().Save(_newStream, System.Drawing.Imaging.ImageFormat.Bmp);
                    break;

                case ".png":
                    this.GetImage().Save(_newStream, System.Drawing.Imaging.ImageFormat.Png);
                    break;

                case ".gif":
                    this.GetImage().Save(_newStream, System.Drawing.Imaging.ImageFormat.Gif);
                    break;

                case ".tif":
                case ".tiff":
                    this.GetImage().Save(_newStream, System.Drawing.Imaging.ImageFormat.Tiff);
                    break;

                case ".jpg":
                case ".jpeg":
                    this.GetImage().Save(_newStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;

                default:
                    throw new Exception("Unsupported conversion format");
                }

                this.SetContents(_newStream.ToArray());
            }
        }
Beispiel #15
0
        public Image GetImage()
        {
            if (this._IsImageChecked)
            {
                return(this._Image);
            }

            this.ImageSubformat = "";
            this.ImageFormat    = "";
            this._AlphaBits     = -1;

            if (!Util.IsImage(this.Filename))
            {
                this._IsImageChecked = true;
                this._Image          = null;

                return(null);
            }

            byte[] _bytes = this.GetContents();

            if (_bytes == null)
            {
                this._IsImageChecked = true;

                this.Status = Result.OutOfMemory;

                return(null);
            }

            Bitmap _loading = null;

            MemoryStream _stream = new MemoryStream(_bytes);             // MemoryStream should remain open for the lifetime of the Bitmap.

            // Natively Supported Image File?
            try
            {
                _loading = new Bitmap(_stream);

                this.ImageFormat = System.IO.Path.GetExtension(this.Filename).ToLower();
            }
            catch
            {
                _loading = null;

                _stream.Seek(0, SeekOrigin.Begin);
            }

            if (_loading == null)
            {
                // TGA image?

                try
                {
                    TargaImage _tga = new TargaImage(_stream);

                    _loading = _tga.Image;

                    this.ImageFormat = ".tga";
                }
                catch
                {
                    _loading = null;
                }
            }

            if (_loading == null)
            {
                // DDS Texture?

                try
                {
                    DDSImage _dds = DDSImage.Load(_bytes);

                    _loading = _dds.Images[0];

                    this.ImageFormat    = ".dds";
                    this.ImageSubformat = _dds.FormatName;
                }
                catch
                {
                    _loading = null;
                }
            }

            this._IsImageChecked = true;

            this._Image = _loading;

            return(this._Image);
        }
Beispiel #16
0
        public string createTextureMod(string inDir, string outFile, List <FoundTexture> textures, MainWindow mainWindow, ref string log)
        {
            string errors = "";
            int    count  = 0;

            List <string> files = Directory.GetFiles(inDir, "*.dds").Where(item => item.EndsWith(".dds", StringComparison.OrdinalIgnoreCase)).ToList();

            files.Sort();
            List <FileMod> modFiles = new List <FileMod>();

            using (FileStream outFs = new FileStream(outFile, FileMode.Create, FileAccess.Write))
            {
                outFs.WriteUInt32(TexExplorer.TextureModTag);
                outFs.WriteUInt32(TexExplorer.TextureModVersion);
                outFs.WriteInt64(0); // files info offset - filled later

                for (int n = 0; n < files.Count(); n++)
                {
                    string file = files[n];
                    if (mainWindow != null)
                    {
                        mainWindow.updateStatusLabel("Creating MOD: " + Path.GetFileName(outFile));
                        mainWindow.updateStatusLabel2("Texture " + (n + 1) + " of " + files.Count() + ", File: " + Path.GetFileName(file));
                    }
                    string filename = Path.GetFileNameWithoutExtension(file).ToLowerInvariant();
                    if (!filename.Contains("0x"))
                    {
                        errors += "Texture filename not valid: " + Path.GetFileName(file) + " Texture filename must include texture CRC (0xhhhhhhhh). Skipping texture..." + Environment.NewLine;
                        log    += "Texture filename not valid: " + Path.GetFileName(file) + " Texture filename must include texture CRC (0xhhhhhhhh). Skipping texture..." + Environment.NewLine;
                        continue;
                    }
                    int idx = filename.IndexOf("0x");
                    if (filename.Length - idx < 10)
                    {
                        errors += "Texture filename not valid: " + Path.GetFileName(file) + " Texture filename must include texture CRC (0xhhhhhhhh). Skipping texture..." + Environment.NewLine;
                        log    += "Texture filename not valid: " + Path.GetFileName(file) + " Texture filename must include texture CRC (0xhhhhhhhh). Skipping texture..." + Environment.NewLine;
                        continue;
                    }
                    uint   crc;
                    string crcStr = filename.Substring(idx + 2, 8);
                    try
                    {
                        crc = uint.Parse(crcStr, System.Globalization.NumberStyles.HexNumber);
                    }
                    catch
                    {
                        errors += "Texture filename not valid: " + Path.GetFileName(file) + " Texture filename must include texture CRC (_0xhhhhhhhh). Skipping texture..." + Environment.NewLine;
                        log    += "Texture filename not valid: " + Path.GetFileName(file) + " Texture filename must include texture CRC (_0xhhhhhhhh). Skipping texture..." + Environment.NewLine;
                        continue;
                    }

                    List <FoundTexture> foundCrcList = textures.FindAll(s => s.crc == crc);
                    if (foundCrcList.Count == 0)
                    {
                        errors += "Texture skipped. Texture " + Path.GetFileName(file) + " is not present in your game setup." + Environment.NewLine;
                        log    += "Texture skipped. Texture " + Path.GetFileName(file) + " is not present in your game setup." + Environment.NewLine;
                        continue;
                    }

                    int savedCount = count;
                    using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        byte[]   src   = fs.ReadToBuffer((int)fs.Length);
                        DDSImage image = new DDSImage(new MemoryStream(src));
                        if (!image.checkExistAllMipmaps())
                        {
                            errors += "Error in texture: " + Path.GetFileName(file) + " This texture has not all the required mipmaps, skipping texture..." + Environment.NewLine;
                            log    += "Error in texture: " + Path.GetFileName(file) + " This texture has not all the required mipmaps, skipping texture..." + Environment.NewLine;
                            continue;
                        }

                        Package pkg     = new Package(GameData.GamePath + foundCrcList[0].list[0].path);
                        Texture texture = new Texture(pkg, foundCrcList[0].list[0].exportID, pkg.getExportData(foundCrcList[0].list[0].exportID));

                        if (texture.mipMapsList.Count > 1 && image.mipMaps.Count() <= 1)
                        {
                            errors += "Error in texture: " + Path.GetFileName(file) + " This texture must have mipmaps, skipping texture..." + Environment.NewLine;
                            log    += "Error in texture: " + Path.GetFileName(file) + " This texture must have mipmaps, skipping texture..." + Environment.NewLine;
                            continue;
                        }

                        string    fmt       = texture.properties.getProperty("Format").valueName;
                        DDSFormat ddsFormat = DDSImage.convertFormat(fmt);
                        if (image.ddsFormat != ddsFormat)
                        {
                            errors += "Error in texture: " + Path.GetFileName(file) + " This texture has wrong texture format, should be: " + ddsFormat + ", skipping texture..." + Environment.NewLine;
                            log    += "Error in texture: " + Path.GetFileName(file) + " This texture has wrong texture format, should be: " + ddsFormat + ", skipping texture..." + Environment.NewLine;
                            continue;
                        }

                        if (image.mipMaps[0].origWidth / image.mipMaps[0].origHeight !=
                            texture.mipMapsList[0].width / texture.mipMapsList[0].height)
                        {
                            errors += "Error in texture: " + Path.GetFileName(file) + " This texture has wrong aspect ratio, skipping texture..." + Environment.NewLine;
                            log    += "Error in texture: " + Path.GetFileName(file) + " This texture has wrong aspect ratio, skipping texture..." + Environment.NewLine;
                            continue;
                        }

                        Stream dst = compressData(src);
                        dst.SeekBegin();

                        FileMod fileMod = new FileMod();
                        fileMod.tag    = FileTextureTag;
                        fileMod.name   = Path.GetFileName(file);
                        fileMod.offset = outFs.Position;
                        fileMod.size   = dst.Length;
                        count++;
                        modFiles.Add(fileMod);

                        outFs.WriteStringASCIINull(foundCrcList[0].name);
                        outFs.WriteUInt32(crc);
                        outFs.WriteFromStream(dst, dst.Length);
                    }
                    if (count == savedCount)
                    {
                        continue;
                    }
                }
                long pos = outFs.Position;
                outFs.SeekBegin();
                outFs.WriteUInt32(TexExplorer.TextureModTag);
                outFs.WriteUInt32(TexExplorer.TextureModVersion);
                outFs.WriteInt64(pos);
                outFs.JumpTo(pos);
                outFs.WriteUInt32((uint)GameData.gameType);
                outFs.WriteInt32(modFiles.Count);
                for (int i = 0; i < modFiles.Count; i++)
                {
                    outFs.WriteUInt32(modFiles[i].tag);
                    outFs.WriteStringASCIINull(modFiles[i].name);
                    outFs.WriteInt64(modFiles[i].offset);
                    outFs.WriteInt64(modFiles[i].size);
                }
            }
            if (count == 0)
            {
                errors += "There are no texture files in " + inDir + ", mod not generated." + Environment.NewLine;
                log    += "There are no texture files in " + inDir + ", mod not generated." + Environment.NewLine;
                File.Delete(outFile);
            }
            return(errors);
        }
Beispiel #17
0
        private string processTextureMod(string filenameMod, int previewIndex, bool extract, bool replace, string outDir, List <FoundTexture> textures, CachePackageMgr cachePackageMgr, TexExplorer texExplorer, ref string log)
        {
            string errors = "";

            using (FileStream fs = new FileStream(filenameMod, FileMode.Open, FileAccess.Read))
            {
                if (previewIndex == -1 && !extract && !replace)
                {
                    texExplorer.listViewTextures.BeginUpdate();
                }
                uint tag     = fs.ReadUInt32();
                uint version = fs.ReadUInt32();
                if (tag != TexExplorer.TextureModTag || version != TexExplorer.TextureModVersion)
                {
                    if (version != TexExplorer.TextureModVersion)
                    {
                        errors += "File " + filenameMod + " was made with an older version of MEM, skipping..." + Environment.NewLine;
                        log    += "File " + filenameMod + " was made with an older version of MEM, skipping..." + Environment.NewLine;
                    }
                    else
                    {
                        errors += "File " + filenameMod + " is not a valid MEM mod, skipping..." + Environment.NewLine;
                        log    += "File " + filenameMod + " is not a valid MEM mod, skipping..." + Environment.NewLine;
                    }
                    if (previewIndex == -1 && !extract && !replace)
                    {
                        texExplorer.listViewTextures.EndUpdate();
                    }
                    return(errors);
                }
                else
                {
                    uint gameType = 0;
                    fs.JumpTo(fs.ReadInt64());
                    gameType = fs.ReadUInt32();
                    if (textures != null && (MeType)gameType != GameData.gameType)
                    {
                        errors += "File " + filenameMod + " is not a MEM mod valid for this game" + Environment.NewLine;
                        log    += "File " + filenameMod + " is not a MEM mod valid for this game" + Environment.NewLine;
                        if (previewIndex == -1 && !extract && !replace)
                        {
                            texExplorer.listViewTextures.EndUpdate();
                        }
                        return(errors);
                    }
                }
                int            numFiles = fs.ReadInt32();
                List <FileMod> modFiles = new List <FileMod>();
                for (int i = 0; i < numFiles; i++)
                {
                    FileMod fileMod = new FileMod();
                    fileMod.tag    = fs.ReadUInt32();
                    fileMod.name   = fs.ReadStringASCIINull();
                    fileMod.offset = fs.ReadInt64();
                    fileMod.size   = fs.ReadInt64();
                    modFiles.Add(fileMod);
                }
                numFiles = modFiles.Count;

                for (int i = 0; i < numFiles; i++)
                {
                    string name = "";
                    uint   crc = 0;
                    long   size = 0, dstLen = 0;
                    int    exportId = -1;
                    string pkgPath  = "";
                    byte[] dst      = null;
                    if (previewIndex != -1)
                    {
                        i = previewIndex;
                    }
                    fs.JumpTo(modFiles[i].offset);
                    size = modFiles[i].size;
                    if (modFiles[i].tag == FileTextureTag)
                    {
                        name = fs.ReadStringASCIINull();
                        crc  = fs.ReadUInt32();
                    }
                    else if (modFiles[i].tag == FileBinaryTag)
                    {
                        name     = modFiles[i].name;
                        exportId = fs.ReadInt32();
                        pkgPath  = fs.ReadStringASCIINull();
                    }

                    if (texExplorer != null)
                    {
                        texExplorer._mainWindow.updateStatusLabel("Processing MOD " + Path.GetFileName(filenameMod) +
                                                                  " - File " + (i + 1) + " of " + numFiles + " - " + name);
                    }

                    if (previewIndex == -1 && !extract && !replace)
                    {
                        if (modFiles[i].tag == FileTextureTag)
                        {
                            FoundTexture foundTexture;
                            foundTexture = textures.Find(s => s.crc == crc);
                            if (foundTexture.crc != 0)
                            {
                                ListViewItem item = new ListViewItem(foundTexture.name + " (" + foundTexture.packageName + ")");
                                item.Name = i.ToString();
                                texExplorer.listViewTextures.Items.Add(item);
                            }
                            else
                            {
                                ListViewItem item = new ListViewItem(name + " (Texture not found: " + name + string.Format("_0x{0:X8}", crc) + ")");
                                item.Name = i.ToString();
                                texExplorer.listViewTextures.Items.Add(item);
                                log += "Texture skipped. Texture " + name + string.Format("_0x{0:X8}", crc) + " is not present in your game setup" + Environment.NewLine;
                            }
                        }
                        else if (modFiles[i].tag == FileBinaryTag)
                        {
                            ListViewItem item = new ListViewItem(name + " (Binary Mod)");
                            item.Name = i.ToString();
                            texExplorer.listViewTextures.Items.Add(item);
                        }
                        else
                        {
                            ListViewItem item = new ListViewItem(name + " (Unknown)");
                            item.Name = i.ToString();
                            errors   += "Unknown tag for file: " + name + Environment.NewLine;
                            log      += "Unknown tag for file: " + name + Environment.NewLine;
                        }
                        continue;
                    }

                    dst    = decompressData(fs, size);
                    dstLen = dst.Length;

                    if (extract)
                    {
                        if (modFiles[i].tag == FileTextureTag)
                        {
                            string filename = name + "_" + string.Format("0x{0:X8}", crc) + ".dds";
                            using (FileStream output = new FileStream(Path.Combine(outDir, Path.GetFileName(filename)), FileMode.Create, FileAccess.Write))
                            {
                                output.Write(dst, 0, (int)dstLen);
                            }
                        }
                        else if (modFiles[i].tag == FileBinaryTag)
                        {
                            string filename = name;
                            using (FileStream output = new FileStream(Path.Combine(outDir, Path.GetFileName(filename)), FileMode.Create, FileAccess.Write))
                            {
                                output.Write(dst, 0, (int)dstLen);
                            }
                        }
                        else
                        {
                            errors += "Unknown tag for file: " + name + Environment.NewLine;
                            log    += "Unknown tag for file: " + name + Environment.NewLine;
                        }
                        continue;
                    }

                    if (previewIndex != -1)
                    {
                        if (modFiles[i].tag == FileTextureTag)
                        {
                            DDSImage image = new DDSImage(new MemoryStream(dst, 0, (int)dstLen));
                            texExplorer.pictureBoxPreview.Image = image.mipMaps[0].bitmap;
                        }
                        else
                        {
                            texExplorer.pictureBoxPreview.Image = null;
                        }
                        break;
                    }
                    else if (replace)
                    {
                        if (modFiles[i].tag == FileTextureTag)
                        {
                            FoundTexture foundTexture;
                            foundTexture = textures.Find(s => s.crc == crc);
                            if (foundTexture.crc != 0)
                            {
                                DDSImage image = new DDSImage(new MemoryStream(dst, 0, (int)dstLen));
                                if (!image.checkExistAllMipmaps())
                                {
                                    errors += "Error in texture: " + name + string.Format("_0x{0:X8}", crc) + " Texture skipped. This texture has not all the required mipmaps." + Environment.NewLine;
                                    log    += "Error in texture: " + name + string.Format("_0x{0:X8}", crc) + " Texture skipped. This texture has not all the required mipmaps." + Environment.NewLine;
                                    continue;
                                }
                                errors += replaceTexture(image, foundTexture.list, cachePackageMgr, foundTexture.name, crc);
                            }
                            else
                            {
                                log += "Error: Texture " + name + string.Format("_0x{0:X8}", crc) + "is not present in your game setup. Texture skipped." + Environment.NewLine;
                            }
                        }
                        else if (modFiles[i].tag == FileBinaryTag)
                        {
                            string path = GameData.GamePath + pkgPath;
                            if (!File.Exists(path))
                            {
                                errors += "Warning: File " + path + " not exists in your game setup." + Environment.NewLine;
                                log    += "Warning: File " + path + " not exists in your game setup." + Environment.NewLine;
                                continue;
                            }
                            Package pkg = cachePackageMgr.OpenPackage(path);
                            pkg.setExportData(exportId, dst);
                        }
                        else
                        {
                            errors += "Error: Unknown tag for file: " + name + Environment.NewLine;
                            log    += "Error: Unknown tag for file: " + name + Environment.NewLine;
                        }
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
                if (previewIndex == -1 && !extract && !replace)
                {
                    texExplorer.listViewTextures.EndUpdate();
                }
            }
            return(errors);
        }
Beispiel #18
0
        private void LoadData(MasterInfo master)
        {
            if (master != null)
            {
                string name = master.PicName;
                if (head.ContainsKey(name))
                {
                    DDSImage image = new DDSImage(head[name]);
                    pic1.Image = Image.FromHbitmap(image.images[0].GetHbitmap());
                }
                else
                {
                    if (pic1.Image != null)
                    {
                        pic1.Image.Dispose();
                        pic1.Image = null;
                    }
                }

                txtPic.Text     = name;
                txtId.Text      = master.ID.ToString();
                txtUnKnow.Text  = master.Unknow.ToString();
                txtName.Text    = master.UnitName;
                txtAddress.Text = master.Address;
                txtSheJi.Text   = master.SheJi.ToString();
                txtGeDou.Text   = master.GeDou.ToString();
                txtShouBei.Text = master.ShouBei.ToString();
                txtFanYin.Text  = master.FanYin.ToString();
                txtJueXin.Text  = master.JueXin.ToString();
                txtZhiHui.Text  = master.ZhiHui.ToString();
                txtFuZuo.Text   = master.FuZuo.ToString();
                txtTongXun.Text = master.TongXun.ToString();
                txtCaoDuo.Text  = master.CaoDuo.ToString();
                txtWeiXiu.Text  = master.WeiXiu.ToString();
                txtMeiLi.Text   = master.MeiLi.ToString();
                txtJinYan.Text  = master.JinYan.ToString();

                cboGrown.SelectedValue = master.ChengZhang.ToString();
                if (cboGrown.SelectedValue == null)
                {
                    GGCRUtil.AddMasterGrown(master.ChengZhang, "未知" + master.ChengZhang);
                    bindAll();
                    LoadData(master);
                    return;
                }

                cboGuYou1.SelectedValue = master.GuYou1.ToString();
                if (cboGuYou1.SelectedValue == null)
                {
                    GGCRUtil.AddPeopleSkill(master.GuYou1, "未知" + master.GuYou1);
                    bindAll();
                    LoadData(master);
                    return;
                }
                cboGuYou2.SelectedValue = master.GuYou2.ToString();
                if (cboGuYou2.SelectedValue == null)
                {
                    GGCRUtil.AddPeopleSkill(master.GuYou2, "未知" + master.GuYou2);
                    bindAll();
                    LoadData(master);
                    return;
                }
                cboGuYou3.SelectedValue = master.GuYou3.ToString();
                if (cboGuYou3.SelectedValue == null)
                {
                    GGCRUtil.AddPeopleSkill(master.GuYou3, "未知" + master.GuYou3);
                    bindAll();
                    LoadData(master);
                    return;
                }

                cboLast4.SelectedValue = master.Last4.ToString();
                if (cboLast4.SelectedValue == null)
                {
                    GGCRUtil.AddMasterZhaoPin(master.Last4, "未知" + master.Last4);
                    bindAll();
                    LoadData(master);
                    return;
                }

                btnSave.Enabled = true;
            }
            else
            {
                txtId.Text      = null;
                txtUnKnow.Text  = null;
                txtName.Text    = null;
                txtSheJi.Text   = null;
                txtGeDou.Text   = null;
                txtShouBei.Text = null;
                txtFanYin.Text  = null;
                txtJueXin.Text  = null;
                txtZhiHui.Text  = null;
                txtFuZuo.Text   = null;
                txtTongXun.Text = null;
                txtCaoDuo.Text  = null;
                txtWeiXiu.Text  = null;
                txtMeiLi.Text   = null;
                txtJinYan.Text  = null;

                cboGrown.SelectedValue  = -1;
                cboGuYou1.SelectedValue = -1;
                cboGuYou2.SelectedValue = -1;
                cboGuYou3.SelectedValue = -1;

                cboLast4.SelectedValue = -1;

                btnSave.Enabled = false;
            }
        }
        public SKBitmap GenerateBitmap()
        {
            Reader.BaseStream.Position = DataOffset;

            switch (Format)
            {
            case VTexFormat.RGBA8888:
                for (ushort i = 0; i < Depth && i < 0xFF; ++i)
                {
                    // Horribly skip all mipmaps
                    // TODO: Either this needs to be optimized, or allow saving each individual mipmap
                    for (var j = NumMipLevels; j > 0; j--)
                    {
                        if (j == 1)
                        {
                            break;
                        }

                        for (var k = 0; k < Height / Math.Pow(2.0, j - 1); ++k)
                        {
                            Reader.BaseStream.Position += (int)((4 * Width) / Math.Pow(2.0f, j - 1));
                        }
                    }

                    return(ReadRGBA8888(Reader, Width, Height));
                }

                break;

            case VTexFormat.RGBA16161616F:
                return(ReadRGBA16161616F(Reader, Width, Height));

            case VTexFormat.DXT1:
                for (ushort i = 0; i < Depth && i < 0xFF; ++i)
                {
                    // Horribly skip all mipmaps
                    // TODO: Either this needs to be optimized, or allow saving each individual mipmap
                    for (var j = NumMipLevels; j > 0; j--)
                    {
                        if (j == 1)
                        {
                            break;
                        }

                        for (var k = 0; k < Height / Math.Pow(2.0, j + 1); ++k)
                        {
                            for (var l = 0; l < Width / Math.Pow(2.0, j + 1); ++l)
                            {
                                Reader.BaseStream.Position += 8;
                            }
                        }
                    }

                    return(DDSImage.UncompressDXT1(Reader, Width, Height));
                }

                break;

            case VTexFormat.DXT5:
                var yCoCg = false;

                if (Resource.EditInfo.Structs.ContainsKey(ResourceEditInfo.REDIStruct.SpecialDependencies))
                {
                    var specialDeps = (SpecialDependencies)Resource.EditInfo.Structs[ResourceEditInfo.REDIStruct.SpecialDependencies];

                    yCoCg = specialDeps.List.Any(dependancy => dependancy.CompilerIdentifier == "CompileTexture" && dependancy.String == "Texture Compiler Version Image YCoCg Conversion");
                }

                for (ushort i = 0; i < Depth && i < 0xFF; ++i)
                {
                    // Horribly skip all mipmaps
                    // TODO: Either this needs to be optimized, or allow saving each individual mipmap
                    for (var j = NumMipLevels; j > 0; j--)
                    {
                        if (j == 1)
                        {
                            break;
                        }

                        for (var k = 0; k < Height / Math.Pow(2.0, j + 1); ++k)
                        {
                            for (var l = 0; l < Width / Math.Pow(2.0, j + 1); ++l)
                            {
                                Reader.BaseStream.Position += 16;
                            }
                        }
                    }

                    return(DDSImage.UncompressDXT5(Reader, Width, Height, yCoCg));
                }

                break;

            case (VTexFormat)17:
            case (VTexFormat)18:
            case VTexFormat.PNG:
                return(ReadPNG());
            }

            throw new NotImplementedException(string.Format("Unhandled image type: {0}", Format));
        }
        protected async Task LoadHdri(string folder)
        {
            string iradpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Hdri", folder, "irradiance.dds");
            string prefpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Hdri", folder, "prefiltered.dds");

            try
            {
                DDSImage rad = await DDSReader.DDSReader.ReadImageAsync(iradpath);

                DDSImage pre = await DDSReader.DDSReader.ReadImageAsync(prefpath);

                App.Current.Dispatcher.Invoke(() =>
                {
                    Collection <DDSMipMap> mips = (Collection <DDSMipMap>)rad.Frames;

                    if (mips.Count > 0)
                    {
                        var mip     = mips[0];
                        byte[] data = mip.MipmapData[0];
                        if (irradiance != null)
                        {
                            irradiance.Release();
                        }

                        irradiance = new GLTextuer2D(PixelInternalFormat.Rgb8);
                        irradiance.Bind();
                        irradiance.SetData(data, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, (int)mip.Width, (int)mip.Height);
                        irradiance.SetFilter((int)TextureMinFilter.Linear, (int)TextureMagFilter.Linear);
                        irradiance.SetWrap((int)TextureWrapMode.ClampToEdge);
                        GLTextuer2D.Unbind();
                    }

                    mips = (Collection <DDSMipMap>)pre.Frames;

                    if (mips.Count > 0)
                    {
                        if (prefiltered != null)
                        {
                            prefiltered.Release();
                        }

                        prefiltered = new GLTextuer2D(PixelInternalFormat.Rgb8);
                        prefiltered.Bind();
                        prefiltered.SetMaxMipLevel(4);

                        for (int i = 0; i < mips.Count; i++)
                        {
                            var mip     = mips[i];
                            byte[] data = mip.MipmapData[0];

                            prefiltered.SetData(data, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, (int)mip.Width, (int)mip.Height, i);
                        }

                        prefiltered.SetFilter((int)TextureMinFilter.LinearMipmapLinear, (int)TextureMagFilter.Linear);
                        prefiltered.SetWrap((int)TextureWrapMode.ClampToEdge);

                        GLTextuer2D.Unbind();
                    }

                    Invalidate();
                });
            }
            catch (Exception e) { Console.WriteLine(e.StackTrace); }
        }
Beispiel #21
0
        /// <summary>
        /// Shows preview for selected file.
        /// </summary>
        private void Preview()
        {
            if (LstFiles.SelectedIndices.Count == 0)
            {
                return;
            }

            var selected = LstFiles.SelectedItems[0];
            var fileName = (string)selected.Tag;
            var ipfFile  = _files[fileName];
            var ext      = Path.GetExtension(fileName).ToLowerInvariant();

            var previewType = PreviewType.None;
            var lexer       = Lexer.Null;

            FileFormat fileType;

            if (_fileTypes.TryGetValue(ext, out fileType))
            {
                previewType = fileType.PreviewType;
                lexer       = fileType.Lexer;
            }

            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    switch (previewType)
                    {
                    case PreviewType.Text:
                        var txtData = ipfFile.GetData();
                        var text    = Encoding.UTF8.GetString(txtData);

                        SetTextPreviewStyle(lexer);

                        Invoke((MethodInvoker) delegate
                        {
                            TxtPreview.ReadOnly = false;
                            TxtPreview.Text     = text;
                            TxtPreview.ReadOnly = true;
                            TxtPreview.Visible  = true;
                        });
                        break;

                    case PreviewType.Image:
                        var imgData = ipfFile.GetData();

                        Invoke((MethodInvoker) delegate
                        {
                            using (var ms = new MemoryStream(imgData))
                                ImgPreview.Image = Image.FromStream(ms);
                            ImgPreview.Size         = ImgPreview.Image.Size;
                            PnlImagePreview.Visible = true;
                        });
                        break;

                    case PreviewType.DdsImage:
                        var ddsData = ipfFile.GetData();

                        DDSImage ddsImage = null;
                        try
                        {
                            ddsImage = new DDSImage(ddsData);
                        }
                        catch (Exception)
                        {
                            Invoke((MethodInvoker) delegate
                            {
                                LblPreview.Text = "Preview failed";
                            });
                            break;
                        }

                        Invoke((MethodInvoker) delegate
                        {
                            ImgPreview.Image        = ddsImage.BitmapImage;
                            ImgPreview.Size         = ImgPreview.Image.Size;
                            PnlImagePreview.Visible = true;
                        });
                        break;

                    case PreviewType.TgaImage:
                        var tgaData = ipfFile.GetData();

                        TargaImage tgaImage = null;
                        try
                        {
                            using (var ms = new MemoryStream(tgaData))
                                tgaImage = new TargaImage(ms);
                        }
                        catch (Exception)
                        {
                            Invoke((MethodInvoker) delegate
                            {
                                LblPreview.Text = "Preview failed";
                            });
                            break;
                        }

                        Invoke((MethodInvoker) delegate
                        {
                            ImgPreview.Image        = tgaImage.Image;
                            ImgPreview.Size         = ImgPreview.Image.Size;
                            PnlImagePreview.Visible = true;
                        });
                        break;

                    case PreviewType.IesTable:
                        var iesData = ipfFile.GetData();
                        var iesFile = new IesFile(iesData);

                        Invoke((MethodInvoker) delegate
                        {
                            GridPreview.SuspendDrawing();

                            foreach (var iesColumn in iesFile.Columns)
                            {
                                GridPreview.Columns.Add(iesColumn.Name, iesColumn.Name);
                            }

                            foreach (var iesRow in iesFile.Rows)
                            {
                                var row = new DataGridViewRow();
                                row.CreateCells(GridPreview);

                                var i = 0;
                                foreach (var iesColumn in iesFile.Columns)
                                {
                                    row.Cells[i++].Value = iesRow[iesColumn.Name];
                                }

                                GridPreview.Rows.Add(row);
                            }

                            GridPreview.ResumeDrawing();

                            GridPreview.Visible = true;
                        });
                        break;

                    case PreviewType.TtfFont:
                        var pfc = new PrivateFontCollection();

                        try
                        {
                            var ttfData = ipfFile.GetData();
                            using (var ms = new MemoryStream(ttfData))
                            {
                                var fontdata = new byte[ms.Length];
                                ms.Read(fontdata, 0, (int)ms.Length);

                                unsafe
                                {
                                    fixed(byte *pFontData = fontdata)
                                    pfc.AddMemoryFont((IntPtr)pFontData, fontdata.Length);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            Invoke((MethodInvoker) delegate
                            {
                                LblPreview.Text = "Preview failed";
                            });
                            break;
                        }

                        var fontFamily = pfc.Families.First();
                        var font       = new Font(fontFamily, 18, FontStyle.Regular, GraphicsUnit.Pixel);
                        var arialFont  = new Font("Arial", 12);

                        var fontInfo = "Name: " + fontFamily.Name;
                        var example1 = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ\n1234567890.:,;'\" (!?) +-*/=";
                        var example2 = "Lorem ipsum dolor sit amet.";

                        var bmp = new Bitmap(600, 500);
                        using (var graphics = Graphics.FromImage(bmp))
                        {
                            var infoHeight     = graphics.MeasureString(fontInfo, arialFont).Height;
                            var example1Height = graphics.MeasureString(example1, font).Height;

                            graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                            graphics.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                            graphics.DrawString(fontInfo, arialFont, Brushes.Black, new Point(0, 0));
                            graphics.DrawString(example1, font, Brushes.Black, new PointF(0, infoHeight + 10));

                            var point = new PointF(10, infoHeight + 10 + example1Height + 20);
                            foreach (var size in new int[] { 12, 18, 24, 36, 48, 60, 72 })
                            {
                                font = new Font(fontFamily, size, FontStyle.Regular, GraphicsUnit.Pixel);
                                graphics.DrawString(example2, font, Brushes.Black, point);
                                point.Y += font.Height + 5;
                            }
                        }

                        Invoke((MethodInvoker) delegate
                        {
                            ImgPreview.Image        = bmp;
                            ImgPreview.Size         = ImgPreview.Image.Size;
                            PnlImagePreview.Visible = true;
                        });
                        break;

                    default:
                        Invoke((MethodInvoker) delegate
                        {
                            LblPreview.Text = "No Preview";
                        });
                        break;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
                }
            });
        }
Beispiel #22
0
 public static ICompressedImage LoadResourceDDS(string fileName)
 {
     return(DDSImage.CreateFromFile(TestResourceDirectory.GetFilePath(fileName)));
 }