Example #1
0
        void ImportStandard(string filename, SurfaceFormat expectedSurfaceFormat)
        {
            var importer = new TextureImporter( );
            var context  = new TestImporterContext(intermediateDirectory, outputDirectory);
            var content  = importer.Import(filename, context);

            Assert.NotNull(content);
            Assert.AreEqual(content.Faces.Count, 1);
            Assert.AreEqual(content.Faces[0].Count, 1);
            Assert.AreEqual(content.Faces[0][0].Width, 64);
            Assert.AreEqual(content.Faces[0][0].Height, 64);
            SurfaceFormat format;

            Assert.True(content.Faces[0][0].TryGetFormat(out format));
            Assert.AreEqual(expectedSurfaceFormat, format);
            // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
            try
            {
                Directory.Delete(intermediateDirectory, true);
                Directory.Delete(outputDirectory, true);
            }
            catch (DirectoryNotFoundException)
            {
            }
        }
Example #2
0
        private IList <Texture2DContent> ImportSLMC(string filename, ContentImporterContext context)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(filename);

            var channels = xmlDoc.DocumentElement;

            if (channels.Name != "channels")
            {
                throw new InvalidContentException(String.Format("Root element must be 'channels'."));
            }

            TextureImporter         txImporter = new TextureImporter();
            List <Texture2DContent> images     = new List <Texture2DContent>();

            foreach (XmlNode imageNode in channels.ChildNodes)
            {
                if (imageNode.Name != "image")
                {
                    throw new InvalidContentException(String.Format("Element '{0}' not supported in 'channels'.", imageNode.Name));
                }

                var imageSource     = GetAttribute(imageNode, "source");
                var fullImageSource = Path.Combine(Path.GetDirectoryName(filename), imageSource);
                context.AddDependency(fullImageSource);
                var textureContent = (Texture2DContent)txImporter.Import(fullImageSource, context);
                textureContent.Name = Path.GetFileNameWithoutExtension(fullImageSource);

                images.Add(textureContent);
            }

            return(images);
        }
Example #3
0
        public void ImportDdsCubemapDxt1()
        {
            var importer = new TextureImporter();
            var context  = new TestImporterContext(intermediateDirectory, outputDirectory);
            var content  = importer.Import("Assets/Textures/SampleCube64DXT1Mips.dds", context);

            Assert.NotNull(content);
            Assert.AreEqual(content.Faces.Count, 6);
            for (int f = 0; f < 6; ++f)
            {
                CheckDdsFace(content, f, 7, 64, 64);
            }
            SurfaceFormat format;

            Assert.True(content.Faces[0][0].TryGetFormat(out format));
            Assert.AreEqual(format, SurfaceFormat.Dxt1);
            // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
            try
            {
                Directory.Delete(intermediateDirectory, true);
                Directory.Delete(outputDirectory, true);
            }
            catch (DirectoryNotFoundException)
            { }
        }
Example #4
0
        public void ImportDds()
        {
            //TODO if pull #4304 gets merged uncomment the following line and delete the rest
            //ImportStandard("Assets/Textures/LogoOnly_64px.dds", SurfaceFormat.Dxt3);
            var importer = new TextureImporter();
            var context  = new TestImporterContext(intermediateDirectory, outputDirectory);
            var content  = importer.Import("Assets/Textures/LogoOnly_64px.dds", context);

            Assert.NotNull(content);
            Assert.AreEqual(content.Faces.Count, 1);
            Assert.AreEqual(content.Faces[0].Count, 1);
            Assert.AreEqual(content.Faces[0][0].Width, 64);
            Assert.AreEqual(content.Faces[0][0].Height, 64);
            SurfaceFormat format;

            Assert.True(content.Faces[0][0].TryGetFormat(out format));
            Assert.AreEqual(format, SurfaceFormat.Dxt3);
            // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
            try
            {
                Directory.Delete(intermediateDirectory, true);
                Directory.Delete(outputDirectory, true);
            }
            catch (DirectoryNotFoundException)
            {
            }
        }
Example #5
0
        public void ImportDdsCubemapColor()
        {
            var importer = new TextureImporter();
            var context  = new TestImporterContext(intermediateDirectory, outputDirectory);
            var content  = importer.Import("Assets/Textures/Sunset.dds", context);

            Assert.NotNull(content);
            Assert.AreEqual(content.Faces.Count, 6);
            for (int f = 0; f < 6; ++f)
            {
                CheckDdsFace(content, f, 1, 512, 512);
            }
            SurfaceFormat format;

            Assert.True(content.Faces[0][0].TryGetFormat(out format));
            // Ensure the red and blue bytes have been correctly swapped
            Assert.AreEqual(format, SurfaceFormat.Color);
            var bytes = content.Faces[0][0].GetPixelData();

            Assert.AreEqual(bytes[0], 208);
            Assert.AreEqual(bytes[2], 62);
            // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
            try
            {
                Directory.Delete(intermediateDirectory, true);
                Directory.Delete(outputDirectory, true);
            }
            catch (DirectoryNotFoundException)
            { }
        }
Example #6
0
        public void ImportDdsMipMap()
        {
            //ImportStandard("Assets/Textures/LogoOnly_64px-mipmaps.dds", SurfaceFormat.Color);
            var importer = new TextureImporter();
            var context  = new TestImporterContext(intermediateDirectory, outputDirectory);
            var content  = importer.Import("Assets/Textures/LogoOnly_64px-mipmaps.dds", context);

            Assert.NotNull(content);
            Assert.AreEqual(content.Faces.Count, 1);
            CheckDdsFace(content, 0, 7, 64, 64);

            SurfaceFormat format;

            Assert.True(content.Faces[0][0].TryGetFormat(out format));
            Assert.AreEqual(format, SurfaceFormat.Dxt3);
            // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
            try
            {
                Directory.Delete(intermediateDirectory, true);
                Directory.Delete(outputDirectory, true);
            }
            catch (DirectoryNotFoundException)
            {
            }
        }
Example #7
0
        public void ImportRGBA16Png()
        {
            var   importer           = new TextureImporter();
            var   context            = new TestImporterContext(intermediateDirectory, outputDirectory);
            var   content            = importer.Import("Assets/Textures/RGBA16.png", context);
            ulong expectedPixelValue = 5714832815570484476;

            Assert.NotNull(content);
            Assert.AreEqual(content.Faces.Count, 1);
            Assert.AreEqual(content.Faces[0].Count, 1);
            Assert.AreEqual(content.Faces[0][0].Width, 126);
            Assert.AreEqual(content.Faces[0][0].Height, 240);
            SurfaceFormat format;

            Assert.True(content.Faces[0][0].TryGetFormat(out format));
            Assert.AreEqual(SurfaceFormat.Rgba64, format);
            Assert.AreEqual(expectedPixelValue, ((PixelBitmapContent <Rgba64>)content.Faces[0][0]).GetRow(1)[12].PackedValue);
            // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
            try
            {
                Directory.Delete(intermediateDirectory, true);
                Directory.Delete(outputDirectory, true);
            }
            catch (DirectoryNotFoundException)
            {
            }
        }
Example #8
0
        public override ParticleDesignerProcessorResult Process(ParticleDesignerContent input, ContentProcessorContext context)
        {
            logger = context.Logger;
            var result = new ParticleDesignerProcessorResult();

            // check for an embedded tiff texture
            if (input.emitterConfig.texture.data != null)
            {
                context.Logger.LogMessage("pex file has an embedded tiff. Extracting now.");
                using (var memoryStream = new MemoryStream(Convert.FromBase64String(input.emitterConfig.texture.data), writable: false))
                {
                    using (var stream = new GZipStream(memoryStream, CompressionMode.Decompress))
                    {
                        const int size   = 4096;
                        byte[]    buffer = new byte[size];
                        using (var memory = new MemoryStream())
                        {
                            int count = 0;
                            do
                            {
                                count = stream.Read(buffer, 0, size);
                                if (count > 0)
                                {
                                    memory.Write(buffer, 0, count);
                                }
                            } while(count > 0);

                            result.textureTiffData = memory.ToArray();
                        }
                    }
                }

                var tempFile = Path.Combine(Path.GetTempPath(), "tempParticleTexture.tif");
                File.WriteAllBytes(tempFile, result.textureTiffData);
                context.Logger.LogMessage("writing tiff to temp file: {0}", tempFile);

                context.Logger.LogMessage("running TextureImportor on tiff");
                var textureImporter = new TextureImporter();
                result.texture      = textureImporter.Import(tempFile, input.context) as Texture2DContent;
                result.texture.Name = input.emitterConfig.texture.name;

                context.Logger.LogMessage("deleting temp file");
                File.Delete(tempFile);

                // process
                context.Logger.LogMessage("processing TextureContent");
                var textureProcessor = new TextureProcessor {
                    GenerateMipmaps = false,
                    TextureFormat   = TextureProcessorOutputFormat.Color
                };
                result.texture = (Texture2DContent)textureProcessor.Process(result.texture, context);
                context.Logger.LogMessage("TextureContent processed");
            }

            result.particleEmitterConfig = input.emitterConfig;

            return(result);
        }
Example #9
0
        private static List <SpriteContent> ImportTileset(XmlNode tileset, ContentImporterContext context, string baseDirectory)
        {
            List <SpriteContent> images = new List <SpriteContent>();

            if (tileset["tileoffset"] != null)
            {
                throw new InvalidContentException("tileoffset is not supported.");
            }

            foreach (XmlNode tileNode in tileset.ChildNodes)
            {
                if (tileNode.Name != "tile")
                {
                    continue;
                }
                var tileId = GetAttributeAsInt(tileNode, "id").Value;
                if (tileId != images.Count)
                {
                    throw new InvalidContentException("Invalid id");
                }
                XmlNode imageNode = tileNode["image"];


                //var format = GetAttribute(imageNode, "format");
                var             imageSource     = GetAttribute(imageNode, "source");
                var             fullImageSource = Path.Combine(baseDirectory, imageSource);
                TextureImporter txImporter      = new TextureImporter();
                var             textureContent  = (Texture2DContent)txImporter.Import(fullImageSource, context);
                textureContent.Name = Path.GetFileNameWithoutExtension(fullImageSource);

                var source = new SpriteContent();
                source.Texture         = textureContent;
                source.Bounds.Location = Point.Zero;
                source.Bounds.Width    = textureContent.Mipmaps[0].Width;
                source.Bounds.Height   = textureContent.Mipmaps[0].Height;

                var transKeyColor = GetAttributeAsColor(imageNode, "trans");
                if (transKeyColor != null)
                {
                    foreach (var mips in textureContent.Faces)
                    {
                        foreach (var mip in mips)
                        {
                            ((PixelBitmapContent <Color>)mip).ReplaceColor(transKeyColor.Value, Color.Transparent);
                        }
                    }
                }

                images.Add(source);
            }

            return(images);
        }
        /// <summary>
        /// The compile.
        /// </summary>
        /// <param name="asset">
        /// The asset.
        /// </param>
        /// <param name="platform">
        /// The platform.
        /// </param>
        public void Compile(TextureAsset asset, TargetPlatform platform)
        {
            if (asset.RawData == null)
            {
                return;
            }

            var tempPath = System.IO.Path.GetTempFileName();

            try
            {
                using (var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    stream.Write(asset.RawData, 0, asset.RawData.Length);
                }

                var importer = new TextureImporter();
                var output   = importer.Import(tempPath, new DummyContentImporterContext());

                var manager = new PipelineManager(
                    Environment.CurrentDirectory,
                    Environment.CurrentDirectory,
                    Environment.CurrentDirectory);
                var dictionary = new OpaqueDataDictionary();
                var processor  = manager.CreateProcessor("TextureProcessor", dictionary);
                var context    = new DummyContentProcessorContext(TargetPlatformCast.ToMonoGamePlatform(platform));
                var content    = processor.Process(output, context);

                asset.PlatformData = new PlatformData {
                    Platform = platform, Data = this.CompileAndGetBytes(content)
                };

                try
                {
                    asset.ReadyOnGameThread();
                }
                catch (NoAssetContentManagerException)
                {
                }
            }
            finally
            {
                try
                {
                    File.Delete(tempPath);
                }
                catch
                {
                }
            }
        }
Example #11
0
        private void CreateExEnOutput(Texture2DContent input, ContentProcessorContext context)
        {
            ExEnFontWriter.CreateOutputDirectory(input.Identity);

            // Put the processor in a format suitable for outputting to PNG
            var originalPremultiply = PremultiplyAlpha;
            var originalFormat      = TextureFormat;

            PremultiplyAlpha = false;
            TextureFormat    = TextureProcessorOutputFormat.Color;

            // Build normal size:
            SpriteFontContent spriteFontContent = base.Process(input, context);

            ExEnFontWriter.WriteTexture(spriteFontContent, false, context,
                                        ExEnFontWriter.AssetOutputFilename(input.Identity, context, "-exenfont.png"));
            ExEnFontWriter.WriteMetrics(spriteFontContent, context,
                                        ExEnFontWriter.AssetOutputFilename(input.Identity, context, "-exenfont.exenfont"));

            // Check for retina size:
            string pathAt2x = Path.Combine(Path.GetDirectoryName(input.Identity.SourceFilename),
                                           Path.GetFileNameWithoutExtension(input.Identity.SourceFilename) + "@2x"
                                           + Path.GetExtension(input.Identity.SourceFilename));

            if (File.Exists(pathAt2x))
            {
                var textureImporter = new TextureImporter();
                var textureAt2x     = (Texture2DContent)textureImporter.Import(pathAt2x, null);
                context.AddDependency(pathAt2x);

                var spriteFontContentAt2x = base.Process(textureAt2x, context);
                ExEnFontWriter.WriteTexture(spriteFontContentAt2x, false, context,
                                            ExEnFontWriter.AssetOutputFilename(input.Identity, context, "*****@*****.**"));
                ExEnFontWriter.WriteMetrics(spriteFontContentAt2x, context,
                                            ExEnFontWriter.AssetOutputFilename(input.Identity, context, "*****@*****.**"));
            }

            PremultiplyAlpha = originalPremultiply;
            TextureFormat    = originalFormat;
        }
        public void Import64BitPngCheckColorChannels()
        {
            var importer = new TextureImporter();
            var context  = new TestImporterContext(intermediateDirectory, outputDirectory);
            var content  = importer.Import("Assets/Textures/color_64bit.png", context);

            var bitmap = (PixelBitmapContent <Rgba64>)content.Faces[0][0];
            var pixel  = bitmap.GetPixel(0, 0).ToVector4();

            AssertFloatsAreEqual(1.0f, pixel.X);
            AssertFloatsAreEqual(0.5f, pixel.Y);
            AssertFloatsAreEqual(0.25f, pixel.Z);

            try
            {
                Directory.Delete(intermediateDirectory, true);
                Directory.Delete(outputDirectory, true);
            }
            catch (DirectoryNotFoundException)
            {
            }
        }
        public void Import32BitPngCheckColorChannels()
        {
            var importer = new TextureImporter();
            var context  = new TestImporterContext(intermediateDirectory, outputDirectory);
            var content  = importer.Import("Assets/Textures/color_32bit.png", context);

            var bitmap = (PixelBitmapContent <Color>)content.Faces[0][0];
            var pixel  = bitmap.GetPixel(0, 0);

            Assert.AreEqual(255, pixel.R);
            Assert.AreEqual(128, pixel.G);
            Assert.AreEqual(64, pixel.B);

            try
            {
                Directory.Delete(intermediateDirectory, true);
                Directory.Delete(outputDirectory, true);
            }
            catch (DirectoryNotFoundException)
            {
            }
        }
Example #14
0
 void ImportStandard(string filename, SurfaceFormat expectedSurfaceFormat)
 {
     var importer = new TextureImporter( );
     var context = new TestImporterContext(intermediateDirectory, outputDirectory);
     var content = importer.Import(filename, context);
     Assert.NotNull(content);
     Assert.AreEqual(content.Faces.Count, 1);
     Assert.AreEqual(content.Faces[0].Count, 1);
     Assert.AreEqual(content.Faces[0][0].Width, 64);
     Assert.AreEqual(content.Faces[0][0].Height, 64);
     SurfaceFormat format;
     Assert.True(content.Faces[0][0].TryGetFormat(out format));
     Assert.AreEqual(expectedSurfaceFormat, format);
     // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
     try
     {
         Directory.Delete(intermediateDirectory, true);
         Directory.Delete(outputDirectory, true);
     }
     catch(DirectoryNotFoundException)
     {
     }
 }
Example #15
0
        private static TextureAtlasContent ImportTMX(string filename, ContentImporterContext context)
        {
            TextureAtlasContent output = new TextureAtlasContent();

            output.Identity = new ContentIdentity(filename);

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(filename);

            var map         = xmlDoc.DocumentElement;
            var orientation = GetAttribute(map, "orientation");

            if (orientation != "orthogonal")
            {
                throw new InvalidContentException("Invalid orientation. Only 'orthogonal' is supported for atlases.");
            }
            var renderorder = GetAttribute(map, "renderorder");
            var mapColumns  = GetAttributeAsInt(map, "width").Value;
            var mapRows     = GetAttributeAsInt(map, "height").Value;
            var tileWidth   = GetAttributeAsInt(map, "tilewidth").Value;
            var tileHeight  = GetAttributeAsInt(map, "tileheight").Value;

            output.Width  = mapColumns * tileWidth;
            output.Height = mapRows * tileHeight;

            XmlNode tileset = map["tileset"];

            if (tileset.Attributes["source"] != null)
            {
                throw new InvalidContentException("External Tileset is not supported.");
            }
            if (tileset["tileoffset"] != null)
            {
                throw new InvalidContentException("tileoffset is not supported.");
            }
            var firstgid = GetAttributeAsInt(tileset, "firstgid").Value;

            Dictionary <int, SourceContent> images = new Dictionary <int, SourceContent>();
            TextureImporter txImporter             = new TextureImporter();

            foreach (XmlNode tileNode in tileset.ChildNodes)
            {
                if (tileNode.Name != "tile")
                {
                    continue;
                }
                var     tileId    = GetAttributeAsInt(tileNode, "id").Value;
                XmlNode imageNode = tileNode["image"];

                var source = new SourceContent();

                //var format = GetAttribute(imageNode, "format");
                var imageSource     = GetAttribute(imageNode, "source");
                var fullImageSource = Path.Combine(Path.GetDirectoryName(filename), imageSource);
                var textureContent  = (Texture2DContent)txImporter.Import(fullImageSource, context);
                textureContent.Name = Path.GetFileNameWithoutExtension(fullImageSource);

                source.Texture = textureContent;

                var width  = GetAttributeAsInt(imageNode, "width");
                var height = GetAttributeAsInt(imageNode, "height");

                source.Width  = width ?? textureContent.Mipmaps[0].Width;
                source.Height = height ?? textureContent.Mipmaps[0].Height;

                var transKeyColor = GetAttributeAsColor(imageNode, "trans");
                if (transKeyColor != null)
                {
                    foreach (var mips in textureContent.Faces)
                    {
                        foreach (var mip in mips)
                        {
                            ((PixelBitmapContent <Color>)mip).ReplaceColor(transKeyColor.Value, Color.Transparent);
                        }
                    }
                }

                images.Add(firstgid + tileId, source);
            }

            output.Textures.AddRange(images.Values);

            XmlNode layerNode    = map["layer"];
            var     layerColumns = Convert.ToInt32(map.Attributes["width"].Value, CultureInfo.InvariantCulture);
            var     layerRows    = Convert.ToInt32(map.Attributes["height"].Value, CultureInfo.InvariantCulture);

            XmlNode layerDataNode = layerNode["data"];
            var     encoding      = layerDataNode.Attributes["encoding"].Value;

            if (encoding != "csv")
            {
                throw new InvalidContentException("Invalid encoding. Only 'csv' is supported for data.");
            }
            var data     = layerDataNode.InnerText;
            var dataList = data.Split(',');

            for (int i = 0; i < dataList.Length; i++)
            {
                dataList[i] = dataList[i].Trim();
            }

            for (int y = 0; y < layerRows; y++)
            {
                for (int x = 0; x < layerColumns; x++)
                {
                    var posX = x * tileWidth;
                    var posY = y * tileHeight;

                    var           tilegId = Convert.ToInt32(dataList[y * layerColumns + x], CultureInfo.InvariantCulture);
                    SourceContent image;
                    if (!images.TryGetValue(tilegId, out image))
                    {
                        continue;
                    }

                    if (renderorder == "right-down" || renderorder == "right-up")
                    {
                        posX += (tileWidth - image.Width);
                    }
                    if (renderorder == "right-down" || renderorder == "left-down")
                    {
                        posY += (tileHeight - image.Height);
                    }

                    var sprite = new SpriteContent();
                    sprite.Name    = image.Texture.Name;
                    sprite.Texture = image.Texture;
                    sprite.DestinationRectangle = new Rectangle(posX, posY, image.Width, image.Height);

                    output.Sprites.Add(sprite);
                }
            }

            return(output);
        }
Example #16
0
        private void CreateExEnOutput(Texture2DContent input, ContentProcessorContext context)
        {
            ExEnFontWriter.CreateOutputDirectory(input.Identity);

            // Put the processor in a format suitable for outputting to PNG
            var originalPremultiply = PremultiplyAlpha;
            var originalFormat = TextureFormat;
            PremultiplyAlpha = false;
            TextureFormat = TextureProcessorOutputFormat.Color;

            // Build normal size:
            SpriteFontContent spriteFontContent = base.Process(input, context);
            ExEnFontWriter.WriteTexture(spriteFontContent, false, context,
                    ExEnFontWriter.AssetOutputFilename(input.Identity, context, "-exenfont.png"));
            ExEnFontWriter.WriteMetrics(spriteFontContent, context,
                    ExEnFontWriter.AssetOutputFilename(input.Identity, context, "-exenfont.exenfont"));

            // Check for retina size:
            string pathAt2x = Path.Combine(Path.GetDirectoryName(input.Identity.SourceFilename),
                    Path.GetFileNameWithoutExtension(input.Identity.SourceFilename) + "@2x"
                    + Path.GetExtension(input.Identity.SourceFilename));
            if(File.Exists(pathAt2x))
            {
                var textureImporter = new TextureImporter();
                var textureAt2x = (Texture2DContent)textureImporter.Import(pathAt2x, null);
                context.AddDependency(pathAt2x);

                var spriteFontContentAt2x = base.Process(textureAt2x, context);
                ExEnFontWriter.WriteTexture(spriteFontContentAt2x, false, context,
                        ExEnFontWriter.AssetOutputFilename(input.Identity, context, "*****@*****.**"));
                ExEnFontWriter.WriteMetrics(spriteFontContentAt2x, context,
                        ExEnFontWriter.AssetOutputFilename(input.Identity, context, "*****@*****.**"));
            }

            PremultiplyAlpha = originalPremultiply;
            TextureFormat = originalFormat;
        }
        public async Task CompileAsync(IAssetFsFile assetFile, IAssetDependencies assetDependencies, TargetPlatform platform, IWritableSerializedAsset output)
        {
            var tempPath = System.IO.Path.GetTempFileName();

            try
            {
                using (var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    using (var sourceStream = await assetFile.GetContentStream().ConfigureAwait(false))
                    {
                        await sourceStream.CopyToAsync(stream).ConfigureAwait(false);
                    }
                }

                var importer       = new TextureImporter();
                var monogameOutput = importer.Import(tempPath, new DummyContentImporterContext());

                var originalWidth  = monogameOutput.Faces[0][0].Width;
                var originalHeight = monogameOutput.Faces[0][0].Height;

                var nameComponents = assetFile.Name.Split('.');
                nameComponents[nameComponents.Length - 1] = "_FolderOptions";
                var folderOptionsFile = await assetDependencies.GetOptionalCompileTimeFileDependency(string.Join(".", nameComponents)).ConfigureAwait(false);

                string[] importFolderOptions = null;
                if (folderOptionsFile != null)
                {
                    using (var optionsReader = new StreamReader(await folderOptionsFile.GetContentStream().ConfigureAwait(false)))
                    {
                        importFolderOptions = optionsReader.ReadToEnd()
                                              .Trim()
                                              .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                                              .Select(x => x.Trim())
                                              .Where(x => !x.StartsWith("#"))
                                              .ToArray();
                    }
                }

                var optionsFile = await assetDependencies.GetOptionalCompileTimeFileDependency(assetFile.Name + ".Options").ConfigureAwait(false);

                string[] importOptions = null;
                if (optionsFile != null)
                {
                    using (var optionsReader = new StreamReader(await optionsFile.GetContentStream().ConfigureAwait(false)))
                    {
                        importOptions = optionsReader.ReadToEnd()
                                        .Trim()
                                        .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(x => x.Trim())
                                        .Where(x => !x.StartsWith("#"))
                                        .ToArray();
                    }
                }

                if (importOptions == null)
                {
                    importOptions = importFolderOptions;
                }
                if (importOptions == null)
                {
                    importOptions = new string[0];
                }

                var allowResizeToPowerOfTwo = !IsPowerOfTwo((ulong)originalWidth) || !IsPowerOfTwo((ulong)originalHeight);
                var allowMakeSquare         = originalWidth != originalHeight;

                var manager = new PipelineManager(
                    Environment.CurrentDirectory,
                    Environment.CurrentDirectory,
                    Environment.CurrentDirectory);
                TextureContent content = CompileTexture(assetFile, platform, monogameOutput, importOptions, allowResizeToPowerOfTwo, allowMakeSquare, manager);

                Console.WriteLine("Texture " + assetFile.Name + " resized " + originalWidth + "x" + originalHeight + " -> " + content.Faces[0][0].Width + "x" + content.Faces[0][0].Height);

                output.SetLoader <IAssetLoader <TextureAsset> >();
                output.SetPlatform(platform);
                output.SetByteArray("Data", CompileAndGetBytes(content));
                output.SetInt32("OriginalWidth", originalWidth);
                output.SetInt32("OriginalHeight", originalHeight);
            }
            finally
            {
                try
                {
                    File.Delete(tempPath);
                }
                catch
                {
                }
            }
        }
Example #18
0
 public void ImportRGBA16Png()
 {
     var importer = new TextureImporter();
     var context = new TestImporterContext(intermediateDirectory, outputDirectory);
     var content = importer.Import("Assets/Textures/RGBA16.png", context);
     Assert.NotNull(content);
     Assert.AreEqual(content.Faces.Count, 1);
     Assert.AreEqual(content.Faces[0].Count, 1);
     Assert.AreEqual(content.Faces[0][0].Width, 126);
     Assert.AreEqual(content.Faces[0][0].Height, 240);
     SurfaceFormat format;
     Assert.True(content.Faces[0][0].TryGetFormat(out format));
     Assert.AreEqual(SurfaceFormat.Rgba64, format);
     // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
     try
     {
         Directory.Delete(intermediateDirectory, true);
         Directory.Delete(outputDirectory, true);
     }
     catch (DirectoryNotFoundException)
     {
     }
 }
Example #19
0
 public void ImportDdsCubemapDxt1()
 {
     var importer = new TextureImporter();
     var context = new TestImporterContext(intermediateDirectory, outputDirectory);
     var content = importer.Import("Assets/Textures/SampleCube64DXT1Mips.dds", context);
     Assert.NotNull(content);
     Assert.AreEqual(content.Faces.Count, 6);
     for (int f = 0; f < 6; ++f)
     {
         CheckDdsFace(content, f);
     }
     SurfaceFormat format;
     Assert.True(content.Faces[0][0].TryGetFormat(out format));
     Assert.AreEqual(format, SurfaceFormat.Dxt1);
     // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
     try
     {
         Directory.Delete(intermediateDirectory, true);
         Directory.Delete(outputDirectory, true);
     }
     catch (DirectoryNotFoundException)
     { }
 }
Example #20
0
 public void ImportDdsMipMap()
 {
     //ImportStandard("Assets/Textures/LogoOnly_64px-mipmaps.dds", SurfaceFormat.Color);
     var importer = new TextureImporter();
     var context = new TestImporterContext(intermediateDirectory, outputDirectory);
     var content = importer.Import("Assets/Textures/LogoOnly_64px-mipmaps.dds", context);
     Assert.NotNull(content);
     Assert.AreEqual(content.Faces.Count, 1);
     CheckDdsFace(content, 0);
     
     SurfaceFormat format;
     Assert.True(content.Faces[0][0].TryGetFormat(out format));
     Assert.AreEqual(format, SurfaceFormat.Dxt3);
     // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions
     try
     {
         Directory.Delete(intermediateDirectory, true);
         Directory.Delete(outputDirectory, true);
     }
     catch(DirectoryNotFoundException)
     {
     }
 }
        public override ParticleDesignerProcessorResult Process(ParticleDesignerContent input, ContentProcessorContext context)
        {
            logger = context.Logger;
            var result = new ParticleDesignerProcessorResult();

            // check for an embedded tiff texture
            if (input.emitterConfig.texture.data != null)
            {
                context.Logger.LogMessage("pex file has an embedded tiff. Extracting now.");
                using (var memoryStream = new MemoryStream(Convert.FromBase64String(input.emitterConfig.texture.data), writable: false))
                {
                    using (var stream = new GZipStream(memoryStream, CompressionMode.Decompress))
                    {
                        const int size   = 4096;
                        byte[]    buffer = new byte[size];
                        using (var memory = new MemoryStream())
                        {
                            int count = 0;
                            do
                            {
                                count = stream.Read(buffer, 0, size);
                                if (count > 0)
                                {
                                    memory.Write(buffer, 0, count);
                                }
                            } while(count > 0);

                            result.textureTiffData = memory.ToArray();
                        }
                    }
                }

                var tempFile = Path.Combine(Path.GetTempPath(), "tempParticleTexture.tif");
                File.WriteAllBytes(tempFile, result.textureTiffData);
                context.Logger.LogMessage("writing tiff to temp file: {0}", tempFile);

                context.Logger.LogMessage("running TextureImportor on tiff");
                var textureImporter = new TextureImporter();
                result.texture      = textureImporter.Import(tempFile, input.context) as Texture2DContent;
                result.texture.Name = input.emitterConfig.texture.name;

                context.Logger.LogMessage("deleting temp file");
                File.Delete(tempFile);

                // process
                context.Logger.LogMessage("processing TextureContent");
                var textureProcessor = new TextureProcessor
                {
                    GenerateMipmaps = false,
                    TextureFormat   = TextureProcessorOutputFormat.Color
                };
                result.texture = (Texture2DContent)textureProcessor.Process(result.texture, context);
                context.Logger.LogMessage("TextureContent processed");
            }
            else             // no tiff data, so let's try loading the texture with the texture name, from the same directory as the particle file
            {
                string fileDirectory = Path.GetDirectoryName(input.path);
                string fullPath      = Path.Combine(fileDirectory, input.emitterConfig.texture.name);
                context.Logger.LogMessage("Looking for texture file at {0}", fullPath);
                result.texture = context.BuildAndLoadAsset <string, Texture2DContent>(new ExternalReference <string>(fullPath), "TextureProcessor");
                context.Logger.LogMessage("Texture file loaded.");
            }

            result.particleEmitterConfig = input.emitterConfig;
            context.Logger.LogMessage("Emitter configuration loaded.");

            return(result);
        }