1. 程式人生 > >仿製shazzam的簡單功能,將hlsl轉換為WPF中的ShaderEffect

仿製shazzam的簡單功能,將hlsl轉換為WPF中的ShaderEffect

(此文章只是在對WPF的Effect產生興趣才稍微研究了一點後面的知識;需要了解更多可參考https://archive.codeplex.com/?p=shazzam的原始碼以及WPF基礎知識)

1.之前一直使用blend裡自帶的幾個特效,突然有一天比較好奇這些特效是怎麼來的。

  然後就聽說了shazzam並看到更多的特效

2.在參考網址下載了shazzam的程式碼來研究研究,只抽取出裡面【如何將.fx檔案編譯為.ps,再產生一個呼叫.ps檔案的.cs檔案,然後就可以像正常使用其它自帶Effect一樣使用了】這一過程

3.HLSL語法網上有很多教程啊,目前就直接拿一些寫好的來用就行,一個簡單的ToonShader.fx

/// <description>An effect that applies cartoon-like shading (posterization).</description>

sampler2D inputSampler : register(S0);

//-----------------------------------------------------------------------------------------
// Shader constant register mappings (scalars - float, double, Point, Color, Point3D, etc.)
//-----------------------------------------------------------------------------------------

/// <summary>The number of color levels to use.</summary>
/// <minValue>3</minValue>
/// <maxValue>15</maxValue>
/// <defaultValue>5</defaultValue>
float Levels : register(C0);

float4 main(float2 uv : TEXCOORD) : COLOR
{
    float4 color = tex2D( inputSampler, uv );
    color.rgb /= color.a;

    int levels = floor(Levels);
    color.rgb *= levels;
    color.rgb = floor(color.rgb);
    color.rgb /= levels;
    color.rgb *= color.a;
    return color;
}
ToonShader

4.ShaderCompiler:利用dxd的D3DXCompileShader將.fx檔案轉換為.ps檔案

    public void Compile(string codeText, string output, string fxName, ShaderProfile shaderProfile = ShaderProfile.ps_2_0)
    {
        IsCompiled = false;
        string path = output;
        IntPtr defines = IntPtr.Zero;
        IntPtr includes = IntPtr.Zero;
        IntPtr ppConstantTable = IntPtr.Zero;
        string methodName = "main";
        string targetProfile2 = "ps_2_0";
        targetProfile2 = ((shaderProfile != ShaderProfile.ps_3_0) ? "ps_2_0" : "ps_3_0");
        bool useDx10 = false;
        int hr2 = 0;
        ID3DXBuffer ppShader2;
        ID3DXBuffer ppErrorMsgs2;
        if (!useDx10)
        {
            hr2 = ((IntPtr.Size != 8) ?
                DxHelper.D3DXCompileShader(codeText, codeText.Length, defines, includes, methodName, targetProfile2, 0, out ppShader2, out ppErrorMsgs2, out ppConstantTable)
                :
                DxHelper.D3DXCompileShader64Bit(codeText, codeText.Length, defines, includes, methodName, targetProfile2, 0, out ppShader2, out ppErrorMsgs2, out ppConstantTable));
        }
        else
        {
            int pHr = 0;
            hr2 = DxHelper.D3DX10CompileFromMemory(codeText, codeText.Length, string.Empty, IntPtr.Zero, IntPtr.Zero, methodName, targetProfile2, 0, 0, IntPtr.Zero, out ppShader2, out ppErrorMsgs2, ref pHr);
        }
        if (hr2 != 0)
        {
            IntPtr errors = ppErrorMsgs2.GetBufferPointer();
            ppErrorMsgs2.GetBufferSize();
            ErrorText = Marshal.PtrToStringAnsi(errors);
            IsCompiled = false;
        }
        else
        {
            ErrorText = "";
            IsCompiled = true;
            string psPath = path + fxName;
            IntPtr pCompiledPs = ppShader2.GetBufferPointer();
            int compiledPsSize = ppShader2.GetBufferSize();
            byte[] compiledPs = new byte[compiledPsSize];
            Marshal.Copy(pCompiledPs, compiledPs, 0, compiledPs.Length);
            using (FileStream psFile = File.Open(psPath, FileMode.Create, FileAccess.Write))
            {
                psFile.Write(compiledPs, 0, compiledPs.Length);
            }
        }
        if (ppShader2 != null)
        {
            Marshal.ReleaseComObject(ppShader2);
        }
        ppShader2 = null;
        if (ppErrorMsgs2 != null)
        {
            Marshal.ReleaseComObject(ppErrorMsgs2);
        }
        ppErrorMsgs2 = null;
        CompileFinished();
    }
Compile(string codeText, string output, string fxName, ShaderProfile shaderProfile)

 

5.CodeGenerator:生成引用.ps檔案的effect.cs檔案

private static string GenerateCode(CodeDomProvider provider, CodeCompileUnit compileUnit)
    {
        // Generate source code using the code generator.
        using (StringWriter writer = new StringWriter())
        {
            string indentString = IndentUsingTabs ? "\t" : String.Format("{0," + IndentSpaces.ToString() + "}", " ");
            CodeGeneratorOptions options = new CodeGeneratorOptions { IndentString = indentString, BlankLinesBetweenMembers = true, BracingStyle = "C" };
            provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
            string text = writer.ToString();
            // Fix up code: make static DP fields readonly, and use triple-slash or triple-quote comments for XML doc comments.
            if (provider.FileExtension == "cs")
            {
                text = text.Replace("public static DependencyProperty", "public static readonly DependencyProperty");
                text = Regex.Replace(text, @"// <(?!/?auto-generated)", @"/// <");
            }
            else
                if (provider.FileExtension == "vb")
            {
                text = text.Replace("Public Shared ", "Public Shared ReadOnly ");
                text = text.Replace("'<", "'''<");
            }
            return text;
        }
    }
GenerateCode(CodeDomProvider provider, CodeCompileUnit compileUnit)

 

生成的cs檔案內容如下:

//------------------------------------------------------------------------------
// <auto-generated>
//     此程式碼由工具生成。
//     執行時版本:4.0.30319.42000
//
//     對此檔案的更改可能會導致不正確的行為,並且如果
//     重新生成程式碼,這些更改將會丟失。
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;


namespace ShaderPan
{
    
    
    /// <summary>An effect that applies cartoon-like shading (posterization).</summary>
    public class ToonShaderEffect : ShaderEffect
    {
        
        public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(ToonShaderEffect), 0);
        
        public static readonly DependencyProperty LevelsProperty = DependencyProperty.Register("Levels", typeof(double), typeof(ToonShaderEffect), new UIPropertyMetadata(((double)(5D)), PixelShaderConstantCallback(0)));
        
        public ToonShaderEffect()
        {
            PixelShader pixelShader = new PixelShader();
            pixelShader.UriSource = new Uri("C:\\Users\\Administrator\\Desktop\\WpfTPL\\shader\\ToonShader.ps", UriKind.Absolute);
            this.PixelShader = pixelShader;

            this.UpdateShaderValue(InputProperty);
            this.UpdateShaderValue(LevelsProperty);
        }
        
        public Brush Input
        {
            get
            {
                return ((Brush)(this.GetValue(InputProperty)));
            }
            set
            {
                this.SetValue(InputProperty, value);
            }
        }
        
        /// <summary>The number of color levels to use.</summary>
        public double Levels
        {
            get
            {
                return ((double)(this.GetValue(LevelsProperty)));
            }
            set
            {
                this.SetValue(LevelsProperty, value);
            }
        }
    }
}
ToonShaderEffect : ShaderEffect

6.ShaderPanTest:測試功能--運用C#動態編譯生成來使用Effect

 public static Assembly CompileInMemory(string code)
    {
        var provider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });

        CompilerParameters options = new CompilerParameters();
        options.ReferencedAssemblies.Add("System.dll");
        options.ReferencedAssemblies.Add("System.Core.dll");
        options.ReferencedAssemblies.Add("WindowsBase.dll");
        options.ReferencedAssemblies.Add("PresentationFramework.dll");
        options.ReferencedAssemblies.Add("PresentationCore.dll");
        options.IncludeDebugInformation = false;
        options.GenerateExecutable = false;
        options.GenerateInMemory = true;
        CompilerResults results = provider.CompileAssemblyFromSource(options, code);
        provider.Dispose();
        if (results.Errors.Count == 0)
            return results.CompiledAssembly;
        else
            return null;
    }
CompileInMemory(string code)

7.原始碼: https://github.com/lenkasetGitHub/Song_WPF_PixelShader (exe圖示來自easyico