示例#1
0
        /// <summary>
        /// Processes a PaletteInfo object into a PaletteMaterialContent object.
        /// </summary>
        /// <param name="input">The PaletteInfo to process.</param>
        /// <param name="context">The processor context.</param>
        /// <returns>The processed PaletteMaterialContent</returns>
        public override PaletteMaterialContent Process(PaletteInfo input,
                                                       ContentProcessorContext context)
        {
#if XNA4
            throw new NotImplementedException();
#else
            // Set all the variables based on the input.
            EffectProcessor effectProcessor = new EffectProcessor();
            EffectContent   effectContent   = new EffectContent();
            effectContent.EffectCode = input.SourceCode;
            CompiledEffect compiled;
            if (context.TargetPlatform == TargetPlatform.Xbox360)
            {
                compiled = Effect.CompileEffectFromSource(
                    input.SourceCode, null, null, CompilerOptions.None, TargetPlatform.Xbox360);
            }
            else
            {
                compiled = effectProcessor.Process(effectContent, context);
            }
            PaletteMaterialContent content = new PaletteMaterialContent();
            content.PaletteSize = input.PaletteSize;
            content.ByteCode    = compiled.GetEffectCode();
            BasicMaterialContent basic = input.BasicContent;
            content.Alpha              = basic.Alpha;
            content.DiffuseColor       = basic.DiffuseColor;
            content.EmissiveColor      = basic.EmissiveColor;
            content.Name               = basic.Name;
            content.SpecularColor      = basic.SpecularColor;
            content.SpecularPower      = basic.SpecularPower;
            content.Texture            = basic.Texture;
            content.VertexColorEnabled = basic.VertexColorEnabled;
            return(content);
#endif
        }
示例#2
0
        internal static Effect ReadAndCompile(string filePath)
        {
            var fullPath = AssetManager.GetFullPath(filePath, ".fx");

            if (!string.IsNullOrEmpty(fullPath))
            {
                var importer        = new EffectImporter();
                var processor       = new EffectProcessor();
                var pipelineManager = new PipelineManager("", "", "")
                {
                    Profile  = Runner.Application.Game.Graphics.GraphicsProfile,
                    Platform = GetTargetPlatform()
                };

                var processorContext = new PipelineProcessorContext(
                    pipelineManager,
                    new PipelineBuildEvent());
                var content         = importer.Import(fullPath, null);
                var compiledContent = processor.Process(content, processorContext);
                var graphicsDevice  = Runner.Application.Game.GraphicsDevice;

                return(new Effect(graphicsDevice, compiledContent.GetEffectCode()));
            }

            return(null);
        }
示例#3
0
        static byte[] GetEffectCode(string filename)
        {
            var basePath       = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Content");
            var effectFileName = System.IO.Path.Combine(basePath, filename + ".fx");

            EffectContent effectSource = new EffectContent
            {
                Identity   = new ContentIdentity(effectFileName),
                EffectCode = File.ReadAllText(effectFileName),
            };
            EffectProcessor       processor      = new EffectProcessor();
            CompiledEffectContent compiledEffect = processor.Process(effectSource, new ProcessorContext());

            return(compiledEffect.GetEffectCode());

#if DEBUG_SHADER_CODE
            // NOTE: We may need to implement a CompilerIncludeHandler here if we ever use #include in our shaders.
            var compiledEffect = Effect.CompileEffectFromFile(effectFileName, null, null, CompilerOptions.Debug, TargetPlatform.Windows);
            if (!compiledEffect.Success)
            {
                throw new InvalidOperationException(compiledEffect.ErrorsAndWarnings);
            }
            return(compiledEffect.GetEffectCode());
#else
            // We have to use a file stream instead of passing the file name directly because the latter method just botches up non-ASCII paths. :(
            //using (var effectFileStream = File.OpenRead(effectFileName))
            //{
            //    // NOTE: We may need to implement a CompilerIncludeHandler here if we ever use #include in our shaders.
            //    var compiledEffect = Effect.CompileEffectFromFile(effectFileStream, null, null, CompilerOptions.None, TargetPlatform.Windows);
            //    if (!compiledEffect.Success)
            //        throw new InvalidOperationException(compiledEffect.ErrorsAndWarnings);
            //    return compiledEffect.GetEffectCode();
            //}
#endif
        }
示例#4
0
        public static byte[] GetEffectCodeBytes(string filename)
        {
            EffectContent         content  = importer.Import("./" + filename, new CustomImporterContext( ));
            CompiledEffectContent compiled = processor.Process(content, new CustomProcessorContext( ));

            return(compiled.GetEffectCode( ));
        }
示例#5
0
        /// <summary>
        /// Processes a PaletteInfo object into a PaletteMaterialContent object.
        /// </summary>
        /// <param name="input">The PaletteInfo to process.</param>
        /// <param name="context">The processor context.</param>
        /// <returns>The processed PaletteMaterialContent</returns>
        public override PaletteMaterialContent Process(PaletteInfo input,
                                                       ContentProcessorContext context)
        {
            // Set all the variables based on the input.
            EffectProcessor effectProcessor = new EffectProcessor();
            EffectContent   effectContent   = new EffectContent();

            effectContent.EffectCode = input.SourceCode;
            CompiledEffect         compiled = effectProcessor.Process(effectContent, context);
            PaletteMaterialContent content  = new PaletteMaterialContent();

            content.PaletteSize = input.PaletteSize;
            content.ByteCode    = compiled.GetEffectCode();
            BasicMaterialContent basic = input.BasicContent;

            content.Alpha              = basic.Alpha;
            content.DiffuseColor       = basic.DiffuseColor;
            content.EmissiveColor      = basic.EmissiveColor;
            content.Name               = basic.Name;
            content.SpecularColor      = basic.SpecularColor;
            content.SpecularPower      = basic.SpecularPower;
            content.Texture            = basic.Texture;
            content.VertexColorEnabled = basic.VertexColorEnabled;
            return(content);
        }
示例#6
0
        public static Effect Compile(GraphicsDevice g, string file)
        {
            EffectImporter  ei  = new EffectImporter();
            EffectContent   ec  = ei.Import(file, new XNADynImporterContext());
            EffectProcessor ep  = new EffectProcessor();
            var             cec = ep.Process(ec, new XNADynProcessorContext());

            return(new Effect(g, cec.GetEffectCode()));
        }
示例#7
0
        static int Main(string[] args)
        {
            // Make sure we have the right number of commandline arguments.
            if (args.Length != 4)
            {
                Console.Error.WriteLine("Usage: CompileEffect <targetPlatform> <targetProfile> <input.fx> <output.bin>");
                return(1);
            }

            // Parse the commandline arguments.
            TargetPlatform targetPlatform;

            if (!Enum.TryParse(args[0], true, out targetPlatform))
            {
                Console.Error.WriteLine("Invalid target platform {0}. Valid options are {1}.", args[0], GetEnumValues <TargetPlatform>());
                return(1);
            }

            GraphicsProfile targetProfile;

            if (!Enum.TryParse(args[1], true, out targetProfile))
            {
                Console.Error.WriteLine("Invalid target profile {0}. Valid options are {1}.", args[1], GetEnumValues <GraphicsProfile>());
                return(1);
            }

            string inputFilename  = args[2];
            string outputFilename = args[3];

            try
            {
                Console.WriteLine("Compiling {0} -> {1} for {2}, {3}", Path.GetFileName(inputFilename), outputFilename, targetPlatform, targetProfile);

                ContentBuildLogger logger = new CustomLogger();

                // Import the effect source code.
                EffectImporter         importer        = new EffectImporter();
                ContentImporterContext importerContext = new CustomImporterContext(logger);
                EffectContent          sourceEffect    = importer.Import(inputFilename, importerContext);

                // Compile the effect.
                EffectProcessor         processor        = new EffectProcessor();
                ContentProcessorContext processorContext = new CustomProcessorContext(targetPlatform, targetProfile, logger);
                CompiledEffectContent   compiledEffect   = processor.Process(sourceEffect, processorContext);

                // Write out the compiled effect code.
                File.WriteAllBytes(outputFilename, compiledEffect.GetEffectCode());
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error: {0}", e.Message);
                return(1);
            }

            return(0);
        }
示例#8
0
        public static byte[] ReadBytesFromSourceFile(string fileName)
        {
            EffectImporter  importer  = new EffectImporter( );
            EffectProcessor processor = new EffectProcessor( );

            EffectContent         content  = importer.Import(fileName, new ShaderImporterContext( ));
            CompiledEffectContent compiled = processor.Process(content, new ShaderProcessorContext( ));

            return(compiled.GetEffectCode( ));
        }
 public static CompiledEffectContent Compile(EffectContent output, string tempOutputPath, TargetPlatform platform, bool isDebug, string defines)
 {
     var processor = new EffectProcessor();
     var context = new DummyContentProcessorContext(TargetPlatformCast.ToMonoGamePlatform(platform));
     context.ActualOutputFilename = tempOutputPath;
     processor.DebugMode = isDebug
         ? EffectProcessorDebugMode.Debug
         : EffectProcessorDebugMode.Optimize;
     processor.Defines = defines + ";" + GetPlatformDefineForEffect(platform) + ";" +
                         (isDebug ? "CONFIGURATION_DEBUG" : "CONFIGURATION_RELEASE");
     return processor.Process(output, context);
 }
示例#10
0
        private static bool AttemptEffectCompilation(
            ContentProcessorContext context, StitchedEffectContent input,
            StitchedEffectSymbol stitchedEffect, ShaderProfile shaderProfile,
            out CompiledEffectContent compiledEffect)
        {
            // Generate effect code.
            StringWriter        writer        = new StringWriter();
            EffectCodeGenerator codeGenerator = new EffectCodeGenerator(stitchedEffect, shaderProfile, writer);

            codeGenerator.GenerateCode();
            string effectCode = writer.ToString();

            // Save effect code so that if there are errors, we'll be able to view the generated .fx file.
            string tempEffectFile = GetTempEffectFileName(input);

            File.WriteAllText(tempEffectFile, effectCode, Encoding.GetEncoding(1252));

            // Process effect code.
            EffectProcessor effectProcessor = new EffectProcessor
            {
                DebugMode = EffectProcessorDebugMode.Auto,
                Defines   = null
            };

            EffectContent effectContent = new EffectContent
            {
                EffectCode = effectCode,
                Identity   = new ContentIdentity(tempEffectFile),
                Name       = input.Name
            };

            try
            {
                compiledEffect = effectProcessor.Process(effectContent, context);

                // This is only needed if the compilation was successful - if it failed,
                // a more specific error message (with link to the generated file)
                // will be shown to the user.
                context.Logger.LogImportantMessage(string.Format("{0} : Stitched effect generated (double-click this message to view).", tempEffectFile));

                return(true);
            }
            catch (InvalidContentException ex)
            {
                if (ErrorIndicatesNeedForShaderModel3(ex.Message))
                {
                    compiledEffect = null;
                    return(false);
                }
                throw;
            }
        }
示例#11
0
        public static Effect CompileEffect(GraphicsDevice graphicsDevice, params string[] pathParts)
        {
            var effectProcessor = new EffectProcessor();
            var context         = new TestProcessorContext(TargetPlatform.Windows, "notused.xnb");
            var effectPath      = Paths.Effect(pathParts);
            var compiledEffect  = effectProcessor.Process(new EffectContent
            {
                EffectCode = File.ReadAllText(effectPath),
                Identity   = new ContentIdentity(effectPath)
            }, context);

            return(new Effect(graphicsDevice, compiledEffect.GetEffectCode()));
        }
示例#12
0
        public static Effect CompileEffect(GraphicsDevice graphicsDevice, params string[] pathParts)
        {
            var effectProcessor = new EffectProcessor();
            var context = new TestProcessorContext(TargetPlatform.Windows, "notused.xnb");
            var effectPath = Paths.Effect(pathParts);
            var compiledEffect = effectProcessor.Process(new EffectContent
            {
                EffectCode = File.ReadAllText(effectPath),
                Identity = new ContentIdentity(effectPath)
            }, context);

            return new Effect(graphicsDevice, compiledEffect.GetEffectCode());
        }
        public static CompiledEffectContent Compile(EffectContent output, string tempOutputPath, TargetPlatform platform, bool isDebug, string defines)
        {
            var processor = new EffectProcessor();
            var context   = new DummyContentProcessorContext(TargetPlatformCast.ToMonoGamePlatform(platform));

            context.ActualOutputFilename = tempOutputPath;
            processor.DebugMode          = isDebug
                ? EffectProcessorDebugMode.Debug
                : EffectProcessorDebugMode.Optimize;
            processor.Defines = defines + ";" + GetPlatformDefineForEffect(platform) + ";" +
                                (isDebug ? "CONFIGURATION_DEBUG" : "CONFIGURATION_RELEASE");
            return(processor.Process(output, context));
        }
示例#14
0
        public static Microsoft.Xna.Framework.Graphics.Effect CompileEffect(GraphicsDevice graphicsDevice, string effectPath)
        {
#if !WINDOWS || DIRECTX || XNA
            var effectProcessor = new EffectProcessor();
            var context         = new TestProcessorContext(TargetPlatform.Windows, "notused.xnb");
            var compiledEffect  = effectProcessor.Process(new EffectContent
            {
                EffectCode = File.ReadAllText(effectPath),
                Identity   = new ContentIdentity(effectPath)
            }, context);

            return(new Microsoft.Xna.Framework.Graphics.Effect(graphicsDevice, compiledEffect.GetEffectCode()));
#else // OpenGL
            throw new NotImplementedException();
#endif
        }
示例#15
0
        private void BuildEffect(string effectFile, TargetPlatform targetPlatform)
        {
            var importerContext = new ImporterContext();
            var importer        = new EffectImporter();
            var input           = importer.Import(effectFile, importerContext);

            Assert.NotNull(input);

            var processorContext = new ProcessorContext(targetPlatform, Path.ChangeExtension(effectFile, ".xnb"));
            var processor        = new EffectProcessor();
            var output           = processor.Process(input, processorContext);

            Assert.NotNull(output);

            // TODO: Should we test the writer?
        }
        private void BuildEffect(string effectFile, TargetPlatform targetPlatform, string defines = null)
        {
            var importerContext = new ImporterContext();
            var importer = new EffectImporter();
            var input = importer.Import(effectFile, importerContext);

            Assert.NotNull(input);

            var processorContext = new TestProcessorContext(targetPlatform, Path.ChangeExtension(effectFile, ".xnb"));
            var processor = new EffectProcessor { Defines = defines };
            var output = processor.Process(input, processorContext);

            Assert.NotNull(output);

            // TODO: Should we test the writer?
        }
示例#17
0
        static byte[] GetEffectCode(string filename)
        {
            var basePath       = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Content");
            var effectFileName = System.IO.Path.Combine(basePath, filename + ".fx");

            var input = new EffectContent()
            {
                // Bizarrely, MonoGame loads the content from the identity's filename and ignores the EffectCode property, so we don't need to bother loading the file ourselves
                Identity = new ContentIdentity(effectFileName),
            };
            var context   = new ProcessorContext();
            var processor = new EffectProcessor();
            var effect    = processor.Process(input, context);

            return(effect.GetEffectCode());
        }
示例#18
0
        public static Effect CompileEffect(GraphicsDevice graphicsDevice, params string[] pathParts)
        {
#if !WINDOWS || DIRECTX || XNA
            var effectProcessor = new EffectProcessor();
            var context = new TestProcessorContext(TargetPlatform.Windows, "notused.xnb");
            var effectPath = Paths.Effect(pathParts);
            var compiledEffect = effectProcessor.Process(new EffectContent
            {
                EffectCode = File.ReadAllText(effectPath),
                Identity = new ContentIdentity(effectPath)
            }, context);

            return new Effect(graphicsDevice, compiledEffect.GetEffectCode());
#else // OpenGL
            throw new NotImplementedException();
#endif
        }
示例#19
0
        private void LoadByteCodeFromSource(string text)
        {
            try
            {
                EffectImporter importer = new EffectImporter();
                EffectContent effectContent = new EffectContent
                {
                    Identity = new ContentIdentity { SourceFilename = "myshader.fx" },
                    EffectCode = text,
                };

                EffectProcessor processor = new EffectProcessor();
                processor.DebugMode = EffectProcessorDebugMode.Optimize;
                CompiledEffectContent compiledEffect = processor.Process(effectContent, new FlaiProcessorContext((GraphicsProfile)_targetProfile.SelectedValue, (TargetPlatform)_targetPlatform.SelectedValue));

                byte[] bytes = compiledEffect.GetEffectCode();
                StringBuilder sb = new StringBuilder(bytes.Length * 3);

                sb.AppendLine("#region Effect Byte Code");
                sb.AppendLine();

                sb.Append("byte[] ByteCode = new byte[]").Append(Environment.NewLine).Append("{").Append(Environment.NewLine);
                for (int i = 0; i < bytes.Length;)
                {
                    sb.Append('\t');
                    int max = Math.Min(i + 8, bytes.Length);
                    for (; i < max; i++)
                    {
                        sb.Append(bytes[i]).Append(", ");
                    }

                    sb.Append(Environment.NewLine);
                }

                sb.Append("};").Append(Environment.NewLine);

                sb.AppendLine();
                sb.Append("#endregion");

                _byteCodeTextBox.Text = sb.ToString();
            }
            catch (InvalidContentException e)
            {
                _byteCodeTextBox.Text = e.Message;
            }
        }
示例#20
0
        /// <summary>
        /// The compile.
        /// </summary>
        /// <param name="asset">
        /// The asset.
        /// </param>
        /// <param name="platform">
        /// The platform.
        /// </param>
        public void Compile(EffectAsset asset, TargetPlatform platform)
        {
            if (string.IsNullOrEmpty(asset.Code))
            {
                return;
            }

            var output = new EffectContent();

            output.EffectCode = this.GetEffectPrefixCode() + asset.Code;

            var tempPath = Path.GetTempFileName();

            using (var writer = new StreamWriter(tempPath))
            {
                writer.Write(output.EffectCode);
            }

            output.Identity = new ContentIdentity(tempPath);

            var tempOutputPath = Path.GetTempFileName();

            var processor = new EffectProcessor();
            var context   = new DummyContentProcessorContext(TargetPlatformCast.ToMonoGamePlatform(platform));

            context.ActualOutputFilename = tempOutputPath;
            var content = processor.Process(output, context);

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

            File.Delete(tempPath);
            File.Delete(tempOutputPath);

            try
            {
                asset.ReloadEffect();
            }
            catch (NoAssetContentManagerException)
            {
            }
        }
示例#21
0
        public override Effect Load(IResource resource, LoaderParameters parameters)
        {
            FileInfo info = new FileInfo(resource.FullName);

            if (!info.Exists)
            {
                throw new FileNotFoundException("Effect file does not exist in directory");
            }
            EffectContent content = new EffectContent();

            content.Identity   = new ContentIdentity(resource.FullName);
            content.EffectCode = File.ReadAllText(resource.FullName);

            CompiledEffectContent compiled = _processor.Process(content, _xnaContext);

            Effect effect = new Effect(compiled.GetEffectCode());

            effect.Name = resource.Name;
            return(effect);
        }
        public override H3DMaterialContent Process(H3DMaterialContent input, ContentProcessorContext context)
        {
            context.Logger.LogMessage($"Processing H3D Effect {input.Name}");
            var tmpPath = Path.GetTempFileName();

            try
            {
                input.Effect.Identity = new ContentIdentity(tmpPath);
                File.WriteAllText(tmpPath, input.Effect.EffectCode);
                context.Logger.LogMessage($"Using temp file {tmpPath} for compilation");
                var effectProcessor = new EffectProcessor();
                input.EffectCompiled = effectProcessor.Process(input.Effect, context);

                // We don't need to do anything - the textures are imported from the binary file
                return(input);
            }
            catch (Exception ex)
            {
                context.Logger.LogMessage("Error {0}", ex);
                throw;
            }
            finally { File.Delete(tmpPath); }
        }
示例#23
0
        public IProgram Link(Shader shader, IEnumerable <object> units)
        {
            var sources = units.Cast <Tuple <ShaderType, SourceDescription> >();
            //var frag = sources.Where(t => t.Item1 == ShaderType.FragmentShader).Select(t => t.Item2);
            //var vert = sources.Where(t => t.Item1 == ShaderType.VertexShader).Select(t => t.Item2);
            var all = sources.Select(t => t.Item2);

            var merged = all.Skip(1).Aggregate(all.First(), (current, d) => current.Merge(d));


            // XNA doesnt support shader compilation so we have to generate a .fx file
            // with everything merged

            var cp = new SLContentProcessorContext();
            var ep = new EffectProcessor();
            var ec = new EffectContent {
                EffectCode = merged.ToHlslFx()
            };

            var compiledEffect = ep.Process(ec, cp);

            return(new Program(compiledEffect));
        }
示例#24
0
        public override void Load()
        {
            try
            {
                using (StreamReader reader = new StreamReader(Settings.GetLocation(typeof(Shader)) + filename))
                {
                    EffectContent effectSource = new EffectContent();

                    effectSource.Name = name;
                    effectSource.Identity = new ContentIdentity(filename);
                    effectSource.EffectCode = reader.ReadToEnd();

                    EffectProcessor processor = new EffectProcessor();
                    CompiledEffectContent compiledEffect = processor.Process(effectSource, new ProcessorContext());

                    HLSL_Shader = new Effect(Bootstrap.graphics.GraphicsDevice, compiledEffect.GetEffectCode());
                }
                this.loaded = true;
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.Message);
            }
        }
示例#25
0
        public Effect?Build(GraphicsDevice device, string path)
        {
            var content = new EffectContent
            {
                Identity   = new ContentIdentity(path),
                EffectCode = File.ReadAllText(path)
            };

            var processor = new EffectProcessor();

            try
            {
                var compiled = processor.Process(content, new ProcessorContext(this.Logger, path));
                return(new Effect(device, compiled.GetEffectCode()));
            }
            catch (InvalidContentException cex)
            {
                var match = this.EffectCompilerPattern.Match(cex.Message);
                if (match.Success)
                {
                    var line    = match.Captures[0].Value;
                    var message = $"At {line}";
                    this.Logger.Error($"Failed to reload {path}\n\n{message}");
                }
                else
                {
                    this.Logger.Error(cex, "Failed to reload {@file}", path);
                }
            }
            catch (Exception ex)
            {
                this.Logger.Error(ex, "Failed to reload {@file}", path);
            }

            return(null);
        }
示例#26
0
        private static Dictionary <string, Dictionary <int, SpriteFont> > Fonts = new Dictionary <string, Dictionary <int, SpriteFont> >(); //Ref, size to font
        static void InitStatic(GraphicsControl control)
        {
            if (StaticInitialized)
            {
                return;
            }
            StaticInitialized = true;

            //Load effect

            /*
             * string code = Properties.Resources.horizontalBorderEffect;
             *
             * CompiledEffect cEffect =
             *  Effect.CompileEffectFromSource(code, null, null,
             *                                 CompilerOptions.None, TargetPlatform.Windows);
             * if (!cEffect.Success)
             *  cEffect = cEffect;
             *
             * Effect = new Effect(control.GraphicsDevice, cEffect.GetEffectCode(), CompilerOptions.None, null);
             * //Save effect code
             * byte[] effectCode = cEffect.GetEffectCode();
             * FileStream stream = File.Open("compiledEffect", FileMode.Create);
             * stream.Write(effectCode, 0, effectCode.Length);
             * stream.Close();
             * stream.Dispose();*/
            //Effect = new Effect(control.GraphicsDevice, Properties.Resources.compiledEffect, CompilerOptions.None, null);
            //byte[] ce = Properties.Resources.compiledEffect;
            //Effect = new Effect(control.GraphicsDevice, ce);

            //windywell load effect
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            string code = enc.GetString(
                util.Util.ReadAllBytes(File.Open("Effects\\Effects_ps3.0.fx", FileMode.Open))    // Properties.Resources.horizontalBorderEffect;
                );

            code = code.Remove(0, 3);
            EffectProcessor ep     = new EffectProcessor();
            var             effect = ep.Process(new EffectContent {
                EffectCode = code
            }, new CatalogContext());

            byte[] ec = effect.GetEffectCode();
            Effect = new Effect(control.GraphicsDevice, ec);

            //Load fonts
            string[] fontRefferences = new[]
            {
                @"UI\Fonts\Eurostile-Bol.otf",
                @"UI\Fonts\Eurostile-Reg.otf",
                @"UI\Fonts\EurostileExt-Med.otf",
                @"UI\Fonts\EurostileExt-Reg.otf",
                @"UI\Fonts\bl.ttf"
            };
            string[] fontNames = new[]
            {
                "FontHeader",
                "FontStandard",
                "FontHeaderExtended",
                "FontStandardExtended",
                "FontInternational"
            };
            int[] fontSizes = new[] { 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 43, 44, 47, 48, 50, 52, 56, 60, 62, 64, 68 };
            //{ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 32, 34, 35, 36, 38, 40, 42, 48, 50, 52, 56, 60, 62, 64, 68 };

            ContentManager contentManager = new ContentManager(control.Services);

            for (int i = 0; i < fontRefferences.Length; i++)
            {
                FontNames[fontRefferences[i]] = fontNames[i];
                Fonts[fontRefferences[i]]     = new Dictionary <int, SpriteFont>();
                foreach (int fontSize in fontSizes)
                {
                    string name = fontNames[i] + fontSize;
                    if (File.Exists("Fonts\\" + name + ".xnb"))
                    {
                        Fonts[fontRefferences[i]][fontSize] = contentManager.Load <SpriteFont>("Fonts\\" + name);
                    }
                }
            }

            //defaultTexture = new Texture2D(control.GraphicsDevice, 1, 1, true, TextureUsage.None, SurfaceFormat.Color);
            defaultTexture = new Texture2D(control.GraphicsDevice, 1, 1, true, SurfaceFormat.Color);
            defaultTexture.SetData(new[] { new Color(0.5f, 0.5f, 1, 1) });
        }
        protected virtual void ProcessMaterial(MaterialContent input, 
            MaterialContent output, ContentProcessorContext context)
        {
            BasicMaterialContent basicMaterial = input as BasicMaterialContent;

            if (basicMaterial != null)
            {
                if (output is SkinnedModelMaterialContent)
                {
                    SkinnedModelMaterialContent skinnedModelMaterial = output as SkinnedModelMaterialContent;

                    skinnedModelMaterial.EmissiveColor = basicMaterial.EmissiveColor.GetValueOrDefault(
                        Vector3.Zero);
                    skinnedModelMaterial.DiffuseColor = basicMaterial.DiffuseColor.GetValueOrDefault(
                        Vector3.One);
                    skinnedModelMaterial.SpecularColor = basicMaterial.SpecularColor.GetValueOrDefault(
                        Vector3.One);
                    skinnedModelMaterial.SpecularPower = basicMaterial.SpecularPower.GetValueOrDefault(
                        16);

                    EffectContent effectContent = new EffectContent();
                    effectContent.EffectCode = Resources.SkinnedModelEffect;

                    EffectProcessor effectProcessor = new EffectProcessor();
                    skinnedModelMaterial.SkinnedEffectContent = effectProcessor.Process(effectContent, context);
                }
                else if (output is SkinnedMaterialContent)
                {
                    SkinnedMaterialContent skinnedModelMaterial = output as SkinnedMaterialContent;

                    skinnedModelMaterial.EmissiveColor = basicMaterial.EmissiveColor.GetValueOrDefault(
                        Vector3.Zero);
                    skinnedModelMaterial.DiffuseColor = basicMaterial.DiffuseColor.GetValueOrDefault(
                        Vector3.One);
                    skinnedModelMaterial.SpecularColor = basicMaterial.SpecularColor.GetValueOrDefault(
                        Vector3.One);
                    skinnedModelMaterial.SpecularPower = basicMaterial.SpecularPower.GetValueOrDefault(
                        16);
                }
            }
        }
示例#28
0
        static void Main(string[] args)
        {
            Log("Effect farm compiler to efb {0}.", EFParser.EfbVersion);

            if (args.Length < 2)
            {
                Log("Usage: efc <input_file> <config_file> [output_file]");
                return;
            }

            try
            {
                var inputFile = args[0];
                if (!File.Exists(inputFile))
                {
                    Log("Could not find '0'.", inputFile);
                    return;
                }

                var configFile = args[1];
                if (!File.Exists(inputFile))
                {
                    Log("Could not find '0'.", inputFile);
                    return;
                }
                var doc = XDocument.Parse(File.ReadAllText(configFile));

                // Parse config
                var config = new Config
                {
                    Targets = ParseTargets(doc)
                };
                if (config.Targets.Length == 0)
                {
                    GenerateError("No target platforms.");
                }

                var rootEntry = (from n in doc.Descendants("RootEntry") select n).FirstOrDefault();
                if (rootEntry == null)
                {
                    GenerateError("Could not find 'RootEntry' node.");
                }

                config.Root = ParseEntry(rootEntry);

                var variants = config.BuildVariants().ToArray();

                var outputFile = string.Empty;

                if (args.Length < 3)
                {
                    outputFile = Path.ChangeExtension(inputFile, "efb");
                }
                else
                {
                    outputFile = Path.ChangeExtension(args[2], "efb");
                }

                var outputLwt = File.GetLastWriteTime(outputFile);
                if (File.Exists(outputFile) &&
                    outputLwt > File.GetLastWriteTime(inputFile) &&
                    outputLwt > File.GetLastWriteTime(configFile))
                {
                    var resultVariants = Substract(variants, outputFile);
                    if (resultVariants.Length == 0)
                    {
                        Log("{0} is up to date.", Path.GetFileName(outputFile));
                        return;
                    }
                }

                var workingFolder = Path.GetDirectoryName(inputFile);
                var includeFx     = new IncludeFX(workingFolder);

                var importerContext  = new ImporterContext();
                var processorContext = new ProcessorContext();

                var effectImporter = new EffectImporter();
                var effectProcesor = new EffectProcessor();

                Log("{0} variants of effects are going to be compiled.", variants.Length);
                using (var stream = File.Open(outputFile, FileMode.Create))
                    using (var writer = new BinaryWriter(stream))
                    {
                        writer.Write(Encoding.UTF8.GetBytes(EFParser.EfbSignature));
                        writer.Write(EFParser.EfbVersion);

                        var idx = 0;
                        foreach (var variant in variants)
                        {
                            Log("#" + idx + ": " + variant.ToString());

                            switch (variant.Platform)
                            {
                            case EFPlatform.MonoGameDirectX:
                            case EFPlatform.MonoGameOpenGL:
                            {
                                var content = effectImporter.Import(inputFile, importerContext);

                                processorContext._targetPlatform = variant.Platform == EFPlatform.MonoGameDirectX ?
                                                                   TargetPlatform.Windows : TargetPlatform.DesktopGL;
                                effectProcesor.Defines = EFVariant.BuildKey(variant.Defines);

                                var result = effectProcesor.Process(content, processorContext);

                                WriteOutput(writer, variant, result.GetEffectCode());
                            }
                            break;

                            case EFPlatform.FNA:
                            {
                                var result = ShaderBytecode.CompileFromFile(inputFile,
                                                                            "fx_2_0",
                                                                            ShaderFlags.OptimizationLevel3,
                                                                            EffectFlags.None,
                                                                            ToMacroses(variant),
                                                                            includeFx);

                                if (result.ResultCode != Result.Ok)
                                {
                                    GenerateError(result.Message);
                                }

                                WriteOutput(writer, variant, result.Bytecode);
                            }
                            break;
                            }

                            ++idx;
                        }
                    }

                Log("Compilation to {0} was succesful.", Path.GetFileName(outputFile));
            }
            catch (Exception ex)
            {
                Log(ex.ToString());
            }
        }
示例#29
0
        public override EffectBinary Process(EffectSourceCode input, ContentProcessorContext context)
        {
            // Remove comments
            Regex  commentRegex = new Regex("//.*$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            string effectCode   = commentRegex.Replace(input.EffectCode, "");

            // Remove carriage returns and line feeds
            commentRegex = new Regex(@"(\r\n)|\n", RegexOptions.IgnoreCase);
            effectCode   = commentRegex.Replace(effectCode, "");

            // Check effect validity
            // EffectProcessor should check almost all potential errors in the effect code
            EffectContent content = new EffectContent {
                EffectCode = effectCode
            };
            EffectProcessor compiler = new EffectProcessor {
                DebugMode = EffectProcessorDebugMode.Auto
            };

            compiler.Process(content, context);

            // If we are here, the effect is assumed to be ok!

            // Extract techniques
            IEnumerable <EffectTechnique> techniques = ExtractTechniques(effectCode);

            // Now we have to find entry points for each pass and compile them
            Compiler     helper = new Compiler();
            EffectBinary result = new EffectBinary();

            foreach (var technique in techniques)
            {
                EffectTechniqueBinary effectTechniqueBinary = new EffectTechniqueBinary {
                    Name = technique.Name
                };

                foreach (var pass in technique.Passes)
                {
                    List <string> errors = new List <string>();

                    // Compiling vertex shader
                    CompilerResult vsResult = helper.Process(effectCode, errors, "vs_2_0", pass.VertexShaderEntryPoint, 3, false, true);

                    // This should not happen but...
                    if (errors.Count > 0)
                    {
                        ExceptionHelper.RaiseException(String.Join("\n", errors));
                    }

                    // Compiling pixel shader
                    CompilerResult psResult = helper.Process(effectCode, errors, "ps_2_0", pass.PixelShaderEntryPoint, 3, false, true);

                    // This should not happen but...
                    if (errors.Count > 0)
                    {
                        ExceptionHelper.RaiseException(String.Join("\n", errors));
                    }

                    // Generating a pass binary
                    EffectPassBinary passBinary = new EffectPassBinary
                    {
                        Name                   = pass.Name,
                        RenderStates           = pass.RenderStates,
                        VertexShaderByteCode   = vsResult.ShaderCode,
                        VertexShaderParameters = Encoding.Unicode.GetBytes(vsResult.ConstantsDefinition),
                        PixelShaderByteCode    = psResult.ShaderCode,
                        PixelShaderParameters  = Encoding.Unicode.GetBytes(psResult.ConstantsDefinition)
                    };

                    effectTechniqueBinary.PassBinaries.Add(passBinary);
                }

                result.TechniquesBinaries.Add(effectTechniqueBinary);
            }

            return(result);
        }
示例#30
0
        public override T Load <T>(string assetName)
        {
            var g = (IGraphicsDeviceService)ServiceProvider.GetService(typeof(IGraphicsDeviceService));

            if (typeof(T) == typeof(Texture2D))
            {
                if (_textures.ContainsKey(assetName))
                {
                    return((T)(object)_textures[assetName]);
                }

                using (var img = Image.FromFile(ContentProjectManager.GetTexturePath(assetName)))
                {
                    var bmp  = new Bitmap(img);
                    var data = new uint[bmp.Width * bmp.Height];
                    for (var y = 0; y < bmp.Height; ++y)
                    {
                        for (var x = 0; x < bmp.Width; ++x)
                        {
                            var pixel = bmp.GetPixel(x, y);
                            data[x + y * bmp.Width] =
                                Microsoft.Xna.Framework.Color.FromNonPremultiplied(pixel.R, pixel.G, pixel.B, pixel.A).
                                PackedValue;
                        }
                    }
                    if (g != null)
                    {
                        var t = new Texture2D(g.GraphicsDevice, img.Width, img.Height);
                        t.SetData(data);
                        _textures.Add(assetName, t);
                        return((T)(object)t);
                    }
                    else
                    {
                        throw new InvalidOperationException("Must wait with loading until graphics device is initialized.");
                    }
                }
            }
            else if (typeof(T) == typeof(Effect))
            {
                if (_shaders.ContainsKey(assetName))
                {
                    return((T)(object)_shaders[assetName]);
                }

                var shaderPath = ContentProjectManager.GetShaderPath(assetName);
                if (shaderPath != null)
                {
                    using (var file = File.OpenText(shaderPath))
                    {
                        var sourceCode = file.ReadToEnd();

                        var effectSource = new EffectContent
                        {
                            EffectCode = sourceCode,
                            Identity   = new ContentIdentity {
                                SourceFilename = assetName
                            }
                        };
                        var processor      = new EffectProcessor();
                        var compiledEffect = processor.Process(effectSource, new DummyProcessorContext());
                        var effect         = new Effect(g.GraphicsDevice, compiledEffect.GetEffectCode());
                        _shaders.Add(assetName, effect);
                        return((T)(object)effect);
                    }
                }
            }
            else if (typeof(T) == typeof(ParticleEffect))
            {
                using (var xmlReader = XmlReader.Create(ContentProjectManager.GetEffectPath(assetName)))
                {
                    var effect = IntermediateSerializer.Deserialize <ParticleEffect>(xmlReader, null);
                    effect.Initialise();
                    effect.LoadContent(this);
                    return((T)(object)effect);
                }
            }
            else if (typeof(T) == typeof(IFactory[]))
            {
                return((T)(object)FactoryManager.GetFactoriesFromFile(assetName).ToArray());
            }
            else if (typeof(T) == typeof(ItemPool[]))
            {
                return((T)(object)ItemPoolManager.GetItemPools().ToArray());
            }
            else if (typeof(T) == typeof(AttributePool[]))
            {
                return((T)(object)AttributePoolManager.GetAttributePools().ToArray());
            }
            return(default(T));
        }
示例#31
0
        public override TOutput Process(TInput input, ContentProcessorContext context)
        {
            Dictionary <string, Q3BSPMaterialContent> processedDictionary = new Dictionary <string, Q3BSPMaterialContent>();

            #region Initialize StreamWriter, if necessary
#if DEBUG
            StreamWriter sw = new StreamWriter(context.OutputFilename.Substring(0, context.OutputFilename.LastIndexOf('.')) + ".compiled.txt");
#else
            StreamWriter sw = null;
#endif
            #endregion

            for (int i = 0; i < input.Count; i++)
            {
                Q3BSPMaterialContent shader = input[i];

                #region Throw any errors in the parsed shader
                if (shader.stages.Count > 8)
                {
                    throw new InvalidContentException(shader.shaderName + " has " + shader.stages.Count + " stages, but the maximum supported is 8.");
                }
                if (processedDictionary.ContainsKey(shader.shaderName))
                {
                    context.Logger.LogWarning("", new ContentIdentity(), "Material " + shader.shaderName + " is defined more than once.");
                    continue;
                    //throw new InvalidContentException("Material " + shader.shaderName + " is defined more than once.");
                }
                #endregion

                #region Log any needed warnings
                if (shader.stages.Count > 4 && shaderModel == ShaderModel.ShaderModel1)
                {
                    context.Logger.LogWarning("", new ContentIdentity(), shader.shaderName + " has more than 4 stages, Shader Model 2.0 is required.");
                }
                #endregion
                EffectProcessor processor = new EffectProcessor();
                processor.DebugMode = EffectProcessorDebugMode.Debug;
                EffectContent effectContent = new EffectContent();
                effectContent.EffectCode = GenerateEffectFromShader(shader, sw);
                #region Compile the Effect
#if DEBUG
                CompiledEffectContent compiledEffect = processor.Process(effectContent, context);
                //CompiledEffect compiledEffect = Effect.CompileEffectFromSource(GenerateEffectFromShader(shader, sw), null, null, CompilerOptions.Debug, TargetPlatform.Windows);
#else
                processor.DebugMode = EffectProcessorDebugMode.Auto;
                CompiledEffectContent compiledEffect = processor.Process(effectContent, context);
                //CompiledEffect compiledEffect = Effect.CompileEffectFromSource(GenerateEffectFromShader(shader, sw), null, null, CompilerOptions.None, TargetPlatform.Windows);
#endif
                #endregion

                /*
                 * if (compiledEffect.ErrorsAndWarnings.Contains("error"))
                 * {
                 *  throw new InvalidContentException(shader.shaderName + ": " + compiledEffect.ErrorsAndWarnings);
                 * }
                 */
                shader.compiledEffect = compiledEffect;
                shader.ShaderCode     = compiledEffect.GetEffectCode();
                processedDictionary.Add(shader.shaderName, shader);
            }
#if DEBUG
            sw.Flush();
            sw.Dispose();
#endif

            return(processedDictionary);
        }