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

来源:https://www.cnblogs.com/lenkaset/archive/2019/07/27/WPF_PixelShader.html
-Advertisement-
Play Games

(此文章只是在對WPF的Effect產生興趣才稍微研究了一點後面的知識;需要瞭解更多可參考https://archive.codeplex.com/?p=shazzam的源代碼以及WPF基礎知識) 1.之前一直使用blend里自帶的幾個特效,突然有一天比較好奇這些特效是怎麼來的。 然後就聽說了sha ...


(此文章只是在對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圖標來自easyicon)


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
一周排行
    -Advertisement-
    Play Games
  • 問題 有很多應用程式在驗證JSON數據的時候用到了JSON Schema。 在微服務架構下,有時候各個微服務由於各種歷史原因,它們所生成的數據對JSON Object屬性名的大小寫規則可能並不統一,它們需要消費的JSON數據的屬性名可能需要大小寫無關。 遺憾的是,目前的JSON Schema沒有這方 ...
  • 首先下載centos07鏡像,建議使用阿裡雲推薦的地址: https://mirrors.aliyun.com/centos/7.9.2009/isos/x86_64/?spm=a2c6h.25603864.0.0.59b5f5ad5Nfr0X 其實這裡就已經出現第一個坑了 centos 07 /u ...
  • 相信很多.NETer看了標題,都會忍不住好奇,點進來看看,並且順便準備要噴作者! 這裡,首先要申明一下,作者本人也非常喜歡Linq,也在各個項目中常用Linq。 我愛Linq,Linq優雅萬歲!!!(PS:順便吐槽一下,隔壁Java從8.0版本推出的Streams API,抄了個四不像,一點都不優雅 ...
  • 在人生的重要時刻,我站在了畢業的門檻上,望著前方的道路,心中涌動著對未來的無限憧憬與些許忐忑。面前,兩條道路蜿蜒伸展:一是繼續在職場中尋求穩定,一是勇敢地走出一條屬於自己的創新之路。儘管面臨年齡和現實的挑戰,我仍舊選擇勇往直前,用技術這把鑰匙,開啟新的人生篇章。 迴首過去,我深知時間寶貴,精力有限。 ...
  • 單元測試 前言 時隔多個月,終於抽空學習了點新知識,那麼這次來記錄一下C#怎麼進行單元測試,單元測試是做什麼的。 我相信大部分剛畢業的都很疑惑單元測試是乾什麼的?在小廠實習了6個月後,我發現每天除了寫CRUD就是寫CRUD,幾乎用不到單元測試。寫完一個功能直接上手去測,當然這隻是我個人感受,僅供參考 ...
  • 一:背景 1. 講故事 最近在分析dump時,發現有程式的卡死和WeakReference有關,在以前只知道怎麼用,但不清楚底層邏輯走向是什麼樣的,藉著這個dump的契機來簡單研究下。 二:弱引用的玩法 1. 一些基礎概念 用過WeakReference的朋友都知道這裡面又可以分為弱短和弱長兩個概念 ...
  • 最近想把ET打表工具的報錯提示直接調用win系統彈窗,好讓策劃明顯的知道表格哪裡填錯數據,彈窗需要調用System.Windows.Forms庫。操作如下: 需要在 .csproj 文件中添加: <UseWindowsForms>true</UseWindowsForms> 須將目標平臺設置為 Wi ...
  • 從C#3開始,拓展方法這一特性就得到了廣泛的應用。 此功能允許你能夠使用實例方法的語法調用某個靜態方法,以下是一個獲取/創建文件的靜態方法: public static async Task<StorageFile> GetOrCreateFileAsync(this StorageFolder f ...
  • 在Windows 11下,使用WinUI2.6以上版本的ListView長這樣: 然而到了Win10上,儘管其他控制項的樣式沒有改變,但ListViewItem變成了預設樣式(初代Fluent) 最重大的問題是,Win10上的HorizontalAlignment未被設置成Stretch,可能造成嚴重 ...
  • 前言 周六在公司加班,幹完活後越顯無聊,想著下載RabbiitMQ做個小項目玩玩。然而這一下就下載了2個小時,真讓人頭痛。 簡單的講一下如何安裝吧,網上教程和踩坑文章還是很多的,我講我感覺有用的文章放在本文末尾。 安裝地址 erlang 下載 - Erlang/OTP https://www.erl ...