コード例 #1
0
        protected override Task<ResultStatus> DoCommandOverride(ICommandContext commandContext)
        {
            var assetManager = new AssetManager();

            // Load image
            var image = assetManager.Load<Image>(InputUrl);

            // Initialize TextureTool library
            using (var texTool = new TextureTool())
            using (var texImage = texTool.Load(image))
            {
                var outputFormat = Format.HasValue ? Format.Value : image.Description.Format;

                // Apply transformations
                texTool.Decompress(texImage);
                if (IsAbsolute)
                {
                    texTool.Resize(texImage, (int)Width, (int)Height, Filter.Rescaling.Lanczos3);
                }
                else
                {
                    texTool.Rescale(texImage, Width / 100.0f, Height / 100.0f, Filter.Rescaling.Lanczos3);
                }

                // Generate mipmaps
                if (GenerateMipmaps)
                {
                    texTool.GenerateMipMaps(texImage, Filter.MipMapGeneration.Box);
                }

                // Convert/Compress to output format
                texTool.Compress(texImage, outputFormat);

                // Save
                using (var outputImage = texTool.ConvertToParadoxImage(texImage))
                {
                    assetManager.Save(OutputUrl, outputImage);

                    commandContext.Logger.Verbose("Compression successful [{3}] to ({0}x{1},{2})",
                                                  outputImage.Description.Width,
                                                  outputImage.Description.Height, outputImage.Description.Format, OutputUrl);
                }
            }

            return Task.FromResult(ResultStatus.Successful);
        }
コード例 #2
0
ファイル: TextureTool.cs プロジェクト: Kurooka/paradox
        static void Main(string[] args)
        {
            var texTool = new TextureTool();
            GlobalLogger.GlobalMessageLogged += new ConsoleLogListener();


            try
            {
                /*var list = new List<TexImage>();
                for (int i = 0; i < 3; ++i)
                {
                    list.Add(texTool.Load(@"C:\dev\data\test\atlas\stones256.png"));
                    list.Add(texTool.Load(@"C:\dev\data\test\atlas\square256.png"));
                }

                var cube = texTool.CreateTextureCube(list);
                //texTool.Compress(cube, Paradox.Framework.Graphics.PixelFormat.BC3_UNorm);
                texTool.GenerateMipMaps(cube, Filter.MipMapGeneration.Box);

                texTool.Save(cube, @"C:\dev\data\test\cube.pvr");

                /*texTool.Remove(cube, 0);

                texTool.Save(array, @"C:\dev\data\test\array_after.dds");

                foreach (var texture in list)  
                {
                    texture.Dispose();
                }

                cube.Dispose();*/


                /*var list = new List<TexImage>();
                for (int i = 0; i < 5; ++i)
                {
                    list.Add(texTool.Load(@"C:\dev\data\test\input\atlas\stones256.png"));
                    list.Add(texTool.Load(@"C:\dev\data\test\input\atlas\square256.png"));
                }

                var array = texTool.CreateTextureArray(list);
                texTool.Compress(array, Paradox.Framework.Graphics.PixelFormat.BC3_UNorm);
                //texTool.GenerateMipMaps(array, Filter.MipMapGeneration.Box);

                texTool.Save(array, @"C:\dev\data\test\array_before.dds");

                texTool.Remove(array, 0);

                texTool.Save(array, @"C:\dev\data\test\array_after.dds");

                foreach (var texture in list)
                {
                    texture.Dispose();
                }

                array.Dispose();*/


                /*var list = new List<TexImage>();
                for (int i = 0; i < 5; ++i)
                {
                    list.Add(texTool.Load(@"C:\dev\data\test\atlas\stones256.png"));
                    list.Add(texTool.Load(@"C:\dev\data\test\atlas\square256.png"));
                }

                var array = texTool.CreateTextureArray(list);
                texTool.GenerateMipMaps(array, Filter.MipMapGeneration.Box);

                texTool.Save(array, @"C:\dev\data\test\array_before.dds");

                var newImg = texTool.Load(@"C:\dev\data\test\atlas\square512.png");
                texTool.Resize(newImg, array.Width, array.Height, Filter.Rescaling.Bilinear);
                texTool.Insert(array, newImg, 1);

                var newImg = texTool.Extract(array, 2, 16);
                texTool.Save(newImg, @"C:\dev\data\test\extract.png");

                //texTool.Save(array, @"C:\dev\data\test\array_after.dds");

                foreach (var texture in list)
                {
                    texture.Dispose();
                }

                array.Dispose();
                newImg.Dispose();*/

                /*string[] fileList = Directory.GetFiles(@"C:\dev\data\test\input\atlas");
                var list = new List<TexImage>(fileList.Length);

                foreach(string filePath in fileList)
                {
                    list.Add(texTool.Load(filePath));
                }

                var atlas = texTool.CreateAtlas(list);

                texTool.Save(atlas, @"C:\dev\data\test\input\atlas_WOMipMaps.png");*/

                /*string[] fileList = Directory.GetFiles(@"C:\dev\data\test\atlas");
                var list = new List<TexImage>(fileList.Length);

                /*foreach(string filePath in fileList)
                {
                    var img = texTool.Load(filePath);
                    list.Add(img);
                    texTool.GenerateMipMaps(img, Filter.MipMapGeneration.Cubic);
                    texTool.Save(img, @"C:\dev\data\test\"+img.Name);
                }

                var img = texTool.Load(@"C:\dev\data\test\atlas\rect100_128.png");
                list.Add(img);
                texTool.GenerateMipMaps(img, Filter.MipMapGeneration.Cubic);
                texTool.Save(img, @"C:\dev\data\test\" + img.Name);

                var atlas = texTool.CreateAtlas(list);
                //texTool.GenerateMipMaps(atlas, Filter.MipMapGeneration.Box);

                /*var newImg = texTool.Extract(atlas, "rect100_128.png");
                texTool.Save(newImg, @"C:\dev\data\test\extracted.png");

                texTool.Save(atlas, @"C:\dev\data\test\atlas_with_mipmaps_already.dds");

                /*var texImage = texTool.Extract(atlas, "stones256.png");

                texTool.Update(atlas, texImage, "square256.png");

                //var newImg = texTool.Load(@"C:\dev\data\test\atlas\stones256.png");
                //var newImg = texTool.Extract(atlas, "square128.png", 16);
                //texTool.Save(newImg, @"C:\dev\data\test\extracted.png");

                texTool.Save(atlas, @"C:\dev\data\test\atlas_after.dds");

                //newImg.Dispose();
                atlas.Dispose();*/
            }
            catch (TextureToolsException)
            {
            }

            texTool.Dispose();

            Log.Info("Done.");
            Console.ReadKey();
        }
コード例 #3
0
ファイル: TextureHelper.cs プロジェクト: releed/paradox
        public static ResultStatus ImportTextureImage(TextureTool textureTool, TexImage texImage, ImportParameters parameters, CancellationToken cancellationToken, Logger logger)
        {
            var assetManager = new AssetManager();

            // Apply transformations
            textureTool.Decompress(texImage, parameters.IsSRgb);

            // Special case when the input texture is monochromatic but it is supposed to be a color and we are working in SRGB
            // In that case, we need to transform it to a supported SRGB format (R8G8B8A8_UNorm_SRgb)
            // TODO: As part of a conversion phase, this code may be moved to a dedicated method in this class at some point
            if (parameters.TextureHint == TextureHint.Color && parameters.IsSRgb && (texImage.Format == PixelFormat.R8_UNorm || texImage.Format == PixelFormat.A8_UNorm))
            {
                textureTool.Convert(texImage, PixelFormat.R8G8B8A8_UNorm_SRgb);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;

            var fromSize =  new Size2(texImage.Width, texImage.Height);
            var targetSize = parameters.DesiredSize;

            // Resize the image
            if (parameters.IsSizeInPercentage)
            {
                targetSize = new Size2((int)(fromSize.Width * targetSize.Width / 100.0f), (int)(fromSize.Height * targetSize.Height / 100.0f));
            }

            // Find the target size
            targetSize = FindBestTextureSize(parameters, targetSize, logger);

            // Resize the image only if needed
            if (targetSize != fromSize)
            {
                textureTool.Resize(texImage, targetSize.Width, targetSize.Height, Filter.Rescaling.Lanczos3);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;

            // texture size is now determined, we can cache it
            var textureSize = new Int2(texImage.Width, texImage.Height);

            // determine the alpha format of the texture when set to Auto
            // Note: this has to be done before the ColorKey transformation in order to be able to take advantage of image file AlphaDepth information
            if(parameters.DesiredAlpha == AlphaFormat.Auto)
            {
                var colorKey = parameters.ColorKeyEnabled? (Color?)parameters.ColorKeyColor : null;
                var alphaLevel = textureTool.GetAlphaLevels(texImage, new Rectangle(0, 0, textureSize.X, textureSize.Y), colorKey, logger);
                parameters.DesiredAlpha = alphaLevel.ToAlphaFormat();
            }

            // Apply the color key
            if (parameters.ColorKeyEnabled)
                textureTool.ColorKey(texImage, parameters.ColorKeyColor);

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;

            // Pre-multiply alpha only for relevant formats 
            if (parameters.PremultiplyAlpha && texImage.Format.HasAlpha32Bits())
                textureTool.PreMultiplyAlpha(texImage);

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;


            // Generate mipmaps
            if (parameters.GenerateMipmaps)
            {
                var boxFilteringIsSupported = !texImage.Format.IsSRgb() || (MathUtil.IsPow2(textureSize.X) && MathUtil.IsPow2(textureSize.Y));
                textureTool.GenerateMipMaps(texImage, boxFilteringIsSupported? Filter.MipMapGeneration.Box: Filter.MipMapGeneration.Linear);
            }
                
            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;


            // Convert/Compress to output format
            // TODO: Change alphaFormat depending on actual image content (auto-detection)?
            var outputFormat = DetermineOutputFormat(parameters, textureSize, texImage.Format);
            textureTool.Compress(texImage, outputFormat, (TextureConverter.Requests.TextureQuality)parameters.TextureQuality);

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;

            // Save the texture
            using (var outputImage = textureTool.ConvertToParadoxImage(texImage))
            {
                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;

                assetManager.Save(parameters.OutputUrl, outputImage.ToSerializableVersion());

                logger.Info("Compression successful [{3}] to ({0}x{1},{2})", outputImage.Description.Width, outputImage.Description.Height, outputImage.Description.Format, parameters.OutputUrl);
            }

            return ResultStatus.Successful;
        }
コード例 #4
0
ファイル: TexturePackerTests.cs プロジェクト: cg123/xenko
        private Image LoadImage(TextureTool texTool, UFile sourcePath)
        {
            using (var texImage = texTool.Load(sourcePath, false))
            {
                // Decompresses the specified texImage
                texTool.Decompress(texImage, false);

                if (texImage.Format == PixelFormat.B8G8R8A8_UNorm)
                    texTool.SwitchChannel(texImage);

                return texTool.ConvertToXenkoImage(texImage);
            }
        }
コード例 #5
0
        public static ResultStatus ImportAndSaveTextureImage(UFile sourcePath, string outputUrl, TextureAsset textureAsset, TextureConvertParameters parameters, CancellationToken cancellationToken, Logger logger)
        {
            var assetManager = new AssetManager();

            using (var texTool = new TextureTool())
            using (var texImage = texTool.Load(sourcePath, textureAsset.SRgb))
            {
                // Apply transformations
                texTool.Decompress(texImage, textureAsset.SRgb);

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;

                var fromSize =  new Size2(texImage.Width, texImage.Height);
                var targetSize = new Size2((int)textureAsset.Width, (int)textureAsset.Height);

                // Resize the image
                if (textureAsset.IsSizeInPercentage)
                {
                    targetSize = new Size2((int)(fromSize.Width * (float)textureAsset.Width / 100.0f), (int)(fromSize.Height * (float) textureAsset.Height / 100.0f));
                }

                // Find the target size
                targetSize = FindBestTextureSize(textureAsset.Format, parameters.GraphicsPlatform, parameters.GraphicsProfile, fromSize, targetSize, textureAsset.GenerateMipmaps, logger);

                // Resize the image only if needed
                if (targetSize != fromSize)
                {
                    texTool.Resize(texImage, targetSize.Width, targetSize.Height, Filter.Rescaling.Lanczos3);
                }

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;

                // texture size is now determined, we can cache it
                var textureSize = new Int2(texImage.Width, texImage.Height);

                // Apply the color key
                if (textureAsset.ColorKeyEnabled)
                    texTool.ColorKey(texImage, textureAsset.ColorKeyColor);

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;


                // Pre-multiply alpha
                if (textureAsset.PremultiplyAlpha)
                    texTool.PreMultiplyAlpha(texImage);

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;


                // Generate mipmaps
                if (textureAsset.GenerateMipmaps)
                {
                    var boxFilteringIsSupported = texImage.Format != PixelFormat.B8G8R8A8_UNorm_SRgb || (IsPowerOfTwo(textureSize.X) && IsPowerOfTwo(textureSize.Y));
                    texTool.GenerateMipMaps(texImage, boxFilteringIsSupported? Filter.MipMapGeneration.Box: Filter.MipMapGeneration.Linear);
                }
                
                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;


                // Convert/Compress to output format
                // TODO: Change alphaFormat depending on actual image content (auto-detection)?
                var outputFormat = DetermineOutputFormat(textureAsset, parameters, textureSize, texImage.Format, parameters.Platform, parameters.GraphicsPlatform, parameters.GraphicsProfile);
                texTool.Compress(texImage, outputFormat, (TextureConverter.Requests.TextureQuality)parameters.TextureQuality);

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;

                // Save the texture
                using (var outputImage = texTool.ConvertToParadoxImage(texImage))
                {
                    if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                        return ResultStatus.Cancelled;

                    assetManager.Save(outputUrl, outputImage.ToSerializableVersion());

                    logger.Info("Compression successful [{3}] to ({0}x{1},{2})", outputImage.Description.Width, outputImage.Description.Height, outputImage.Description.Format, outputUrl);
                }
            }

            return ResultStatus.Successful;
        }
コード例 #6
0
ファイル: TexturePackerTests.cs プロジェクト: cg123/xenko
        private AtlasTextureElement CreateElementFromFile(string name, int borderSize, TextureAddressMode borderModeU, TextureAddressMode borderModeV, RotableRectangle? imageRegion = null)
        {
            using (var texTool = new TextureTool())
            {
                var image = LoadImage(texTool, new UFile(ImageInputPath + "/" + name + ".png"));
                var region = imageRegion ?? new RotableRectangle(0, 0, image.Description.Width, image.Description.Height);

                return new AtlasTextureElement(name, image, region, borderSize, borderModeU, borderModeV, Color.SteelBlue);
            }
        }
コード例 #7
0
ファイル: TexturePackerTests.cs プロジェクト: cg123/xenko
        private void SaveAndCompareTexture(Image outputImage, string fileName, ImageFileType extension = ImageFileType.Png)
        {
            // save
            Directory.CreateDirectory(ImageOutputPath);
            outputImage.Save(new FileStream(ImageOutputPath + fileName + extension.ToFileExtension(), FileMode.Create), extension); 

            // Compare
            using(var texTool = new TextureTool())
            {
                var referenceImage = LoadImage(texTool, new UFile(GoldImagePath + "/" + fileName + extension.ToFileExtension()));
                Assert.IsTrue(CompareImages(outputImage, referenceImage), "The texture outputted differs from the gold image.");
            }
        }
コード例 #8
0
        public static void CreateAndSaveSeparateTextures(TextureTool texTool, TexImage texImage, string originalTextureURL, bool shouldGenerateMipMaps, PixelFormat outputFormat = PixelFormat.ETC1)
        {
            var assetManager = new AssetManager();
            var alphaTextureURL = GenerateAlphaTextureURL(originalTextureURL);
            var colorTextureURL = GenerateColorTextureURL(originalTextureURL);

            // create a new image containing only the alpha component
            texTool.Decompress(texImage, texImage.Format.IsSRgb());
            using (var alphaImage = texTool.CreateImageFromAlphaComponent(texImage))
            {
                // generate the mip-maps for the alpha component if required
                if (shouldGenerateMipMaps)
                    texTool.GenerateMipMaps(alphaImage, Filter.MipMapGeneration.Box);

                // save the alpha component
                texTool.Compress(alphaImage, outputFormat);
                using (var outputImage = texTool.ConvertToXenkoImage(alphaImage))
                    assetManager.Save(alphaTextureURL, outputImage.ToSerializableVersion());
            }

            // save the color component
            texTool.Decompress(texImage, texImage.Format.IsSRgb());
            texTool.Compress(texImage, outputFormat);
            using (var outputImage = texTool.ConvertToXenkoImage(texImage))
                assetManager.Save(colorTextureURL, outputImage.ToSerializableVersion());
        }
コード例 #9
0
 public static void CreateAndSaveSeparateTextures(Image image, string originalTextureURL, bool shouldGenerateMipMaps, PixelFormat outputFormat = PixelFormat.ETC1)
 {
     using (var texTool = new TextureTool())
     using (var texImage = texTool.Load(image))
     {
         CreateAndSaveSeparateTextures(texTool, texImage, originalTextureURL, shouldGenerateMipMaps, outputFormat);
     }
 }
コード例 #10
0
ファイル: TextureHelper.cs プロジェクト: Julyuary/paradox
        /// <summary>
        /// Find the region of the sprite specified by the provided pixel coordinate in a texture.
        /// </summary>
        /// <param name="filePath">The full path to the texture</param>
        /// <param name="pixelCoordinates">A pixel of the sprite</param>
        /// <param name="transparencyColor">The transparency color of the texture</param>
        /// <returns></returns>
        public static Rectangle FindSpriteRegion(string filePath, Int2 pixelCoordinates, Color? transparencyColor)
        {
            using (var tool = new TextureTool())
            using (var image = tool.Load(filePath, false))
            {
                tool.Decompress(image, false);

                var mask = transparencyColor.HasValue ? 0xffffffff: 0xff000000;
                return tool.FindSpriteRegion(image, pixelCoordinates, transparencyColor, mask);
            }
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: h78hy78yhoi8j/xenko
        public void Run(string[] args)
        {
            // Print the exe header
            PrintHeader();

            foreach (String s in args)
                Console.WriteLine(s);

            Console.WriteLine("");

            // Parse the command line
            if (!ParseCommandLine(args))
            {
                Environment.Exit(-1);
            }

            // Check if we have a pattern
            InputPatternFile = Path.Combine(Environment.CurrentDirectory, InputPatternFile);

            int indexOfPattern = InputPatternFile.IndexOf('*');
            bool isPattern = indexOfPattern >= 0;

            if (!isPattern)
            {
                InputPatternFile = Path.GetFullPath(InputPatternFile);
            }
            OutputFileOrDirectory = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, OutputFileOrDirectory));

            var inputOutputFiles = new List<Tuple<string, string>>();

            if (isPattern)
            {

                if (!Directory.Exists(OutputFileOrDirectory))
                {
                    Directory.CreateDirectory(OutputFileOrDirectory);
                }

                var directory = InputPatternFile.Substring(0, indexOfPattern);
                var pattern = InputPatternFile.Substring(indexOfPattern, InputPatternFile.Length - indexOfPattern);

                foreach (var file in Directory.EnumerateFiles(directory, pattern, SearchOption.AllDirectories))
                {
                    var outputFile = Path.Combine(OutputFileOrDirectory, file.Substring(directory.Length, file.Length - directory.Length));

                    bool excludeFile = false;
                    foreach (var excludeItem in ExcludeList)
                    {
                        if (file.IndexOf(excludeItem, StringComparison.InvariantCultureIgnoreCase) >= 0)
                        {
                            excludeFile = true;
                            break;
                        }
                    }

                    if (!excludeFile)
                    {
                        inputOutputFiles.Add(new Tuple<string, string>(file, outputFile));
                    }
                }
            }
            else
            {
                inputOutputFiles.Add(new Tuple<string, string>(InputPatternFile, OutputFileOrDirectory));
            }

            var texTool = new TextureTool();
            GlobalLogger.GlobalMessageLogged += new ConsoleLogListener();

            bool hasErrors = false;
            foreach (var inputOutputFile in inputOutputFiles)
            {
                var inputFile = inputOutputFile.Item1;
                var outputFile = inputOutputFile.Item2;

                TexImage image = null;
                try
                {
                    image = texTool.Load(inputFile, IsSRgb);

                    HandleResizing(texTool, image);

                    if (FlipOrientation.HasValue) texTool.Flip(image, FlipOrientation.Value);

                    if (MipMap) texTool.GenerateMipMaps(image, MipMapFilter);
                    
                    if(PreMulAlpha) texTool.PreMultiplyAlpha(image);

                    if(TextureFormat.HasValue) texTool.Compress(image, TextureFormat.Value);

                    texTool.Save(image, outputFile, MipMapSize);
                }
                catch (TextureToolsException)
                {
                    hasErrors = true;
                }
                finally
                {
                    if(image!=null) image.Dispose();
                }
            }

            texTool.Dispose();

            if (hasErrors)
            {
                //Environment.Exit(-1);
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: h78hy78yhoi8j/xenko
        private void HandleResizing(TextureTool texTool, TexImage image)
        {
            if (Width != null && Height != null)
            {
                bool targetInPercent;
                var width = ParsePixelSize(Width, out targetInPercent);
                var height = ParsePixelSize(Height, out targetInPercent);

                if (targetInPercent)
                    texTool.Rescale(image, width / 100f, height / 100f, RescalingFilter);
                else
                    texTool.Resize(image, width, height, RescalingFilter);
            }
            else if (Width != null && Height == null)
            {
                bool targetInPercent;
                var width = ParsePixelSize(Width, out targetInPercent);

                if (targetInPercent)
                    texTool.Rescale(image, width / 100f, 1, RescalingFilter);
                else
                    texTool.Resize(image, width, image.Height, RescalingFilter);
            }
            else if (Width == null && Height != null)
            {
                bool targetInPercent;
                var height = ParsePixelSize(Height, out targetInPercent);

                if (targetInPercent)
                    texTool.Rescale(image, 1, height / 100f, RescalingFilter);
                else
                    texTool.Resize(image, image.Width, height, RescalingFilter);
            }
        }