public override CompiledEffectContent Process(EffectContent input, ContentProcessorContext context)
        {
            //System.Diagnostics.Debugger.Launch();

            // If this isn't a MonoGame platform then do the default processing.
            var platform = ContentHelper.GetMonoGamePlatform();
            if (platform == MonoGamePlatform.None)
                return base.Process(input, context);

            var options = new Options();
            options.SourceFile = input.Identity.SourceFilename;
            options.Profile = platform == MonoGamePlatform.Windows8 ? ShaderProfile.DirectX_11 : ShaderProfile.OpenGL;
            options.Debug = DebugMode == EffectProcessorDebugMode.Debug;
            options.OutputFile = context.OutputFilename;

            // Parse the MGFX file expanding includes, macros, and returning the techniques.
            ShaderInfo shaderInfo;
            try
            {
                shaderInfo = ShaderInfo.FromFile(options.SourceFile, options);
                foreach (var dep in shaderInfo.Dependencies)
                    context.AddDependency(dep);
            }
            catch (Exception ex)
            {
                // TODO: Extract good line numbers from mgfx parser!
                throw new InvalidContentException(ex.Message, input.Identity, ex);
            }

            // Create the effect object.
            EffectObject effect = null;
            var shaderErrorsAndWarnings = string.Empty;
            try
            {
                effect = EffectObject.CompileEffect(shaderInfo, out shaderErrorsAndWarnings);
            }
            catch (ShaderCompilerException)
            {
                throw ProcessErrorsAndWarnings(shaderErrorsAndWarnings, input, context);
            }

            // Write out the effect to a runtime format.
            CompiledEffectContent result;
            try
            {
                using (var stream = new MemoryStream())
                {
                    using (var writer = new BinaryWriter(stream))
                        effect.Write(writer, options);

                    result = new CompiledEffectContent(stream.GetBuffer());
                }
            }
            catch (Exception ex)
            {
                throw new InvalidContentException("Failed to serialize the effect!", input.Identity, ex);
            }

            return result;
        }
        private Exception ProcessErrorsAndWarnings(string errorsAndWarnings, EffectContent input, ContentProcessorContext context)
        {
            // Split the errors by lines.
            var errors = errorsAndWarnings.Split('\n');

            // Process each error line extracting the location and message information.
            for (var i = 0; i < errors.Length; i++)
            {
                // Skip blank lines.
                if (errors[i].StartsWith(Environment.NewLine))
                    break;

                // find some unique characters in the error string
                var openIndex = errors[i].IndexOf('(');
                var closeIndex = errors[i].IndexOf(')');

                // can't process the message if it has no line counter
                if (openIndex == -1 || closeIndex == -1)
                    continue;

                // find the error number, then move forward into the message
                var errorIndex = errors[i].IndexOf('X', closeIndex);
                if (errorIndex < 0)
                    return new InvalidContentException(errors[i], input.Identity);

                // trim out the data we need to feed the logger
                var fileName = errors[i].Remove(openIndex);
                var lineAndColumn = errors[i].Substring(openIndex + 1, closeIndex - openIndex - 1);
                var description = errors[i].Substring(errorIndex);

                // when the file name is not present, the error can be found in the root file
                if (string.IsNullOrEmpty(fileName))
                    fileName = input.Identity.SourceFilename;

                // ensure that the file data points toward the correct file
                var fileInfo = new FileInfo(fileName);
                if (!fileInfo.Exists)
                {
                    var parentFile = new FileInfo(input.Identity.SourceFilename);
                    fileInfo = new FileInfo(Path.Combine(parentFile.Directory.FullName, fileName));
                }
                fileName = fileInfo.FullName;

                // construct the temporary content identity and file the error or warning
                var identity = new ContentIdentity(fileName, input.Identity.SourceTool, lineAndColumn);
                if (errors[i].Contains("warning"))
                {
                    description = "A warning was generated when compiling the effect.\n" + description;
                    context.Logger.LogWarning(string.Empty, identity, description, string.Empty);
                }
                else if (errors[i].Contains("error"))
                {
                    description = "Unable to compile the effect.\n" + description;
                    return new InvalidContentException(description, identity);
                }
            }

            // if no exceptions were created in the above loop, generate a generic one here
            return new InvalidContentException(errorsAndWarnings, input.Identity);
        }
        public override CompiledEffectContent Process(EffectContent input, ContentProcessorContext context)
        {
            //System.Diagnostics.Debugger.Launch();

            // If this isn't a MonoGame platform then do the default processing.
            var platform = ContentHelper.GetMonoGamePlatform();
            if (platform == MonoGamePlatform.None)
                return base.Process(input, context);

            var options = new Options();
            options.SourceFile = input.Identity.SourceFilename;
            options.DX11Profile = platform == MonoGamePlatform.Windows8 ? true : false;
            options.OutputFile = context.OutputFilename;

            // Parse the MGFX file expanding includes, macros, and returning the techniques.
            ShaderInfo shaderInfo;
            try
            {
                shaderInfo = ShaderInfo.FromFile(options.SourceFile, options);
            }
            catch (Exception ex)
            {
                throw new InvalidContentException("Failed to parse the effect!", ex);
            }

            // Create the effect object.
            DXEffectObject effect;
            try
            {
                effect = DXEffectObject.FromShaderInfo(shaderInfo);
            }
            catch (Exception ex)
            {
                throw new InvalidContentException("Failed to create the effect!", ex);
            }

            // Write out the effect to a runtime format.
            CompiledEffectContent result;
            try
            {
                using (var stream = new MemoryStream())
                {
                    using (var writer = new BinaryWriter(stream))
                        effect.Write(writer, options);

                    result = new CompiledEffectContent(stream.GetBuffer());
                }
            }
            catch (Exception ex)
            {
                throw new InvalidContentException("Failed to serialize the effect!", ex);
            }

            return result;
        }
 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);
 }
        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;
            }
        }
Beispiel #6
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);
            }
        }
        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);
                }
            }
        }