grama.shader 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. Shader "Custom/GammaSpaceAlphaBlend"
  2. {
  3. Properties
  4. {
  5. _MainTex ("Base Texture", 2D) = "white" {}
  6. _AlphaTex ("Alpha Texture", 2D) = "white" {} // 透明度纹理
  7. _Color ("Color", Color) = (1,1,1,1) // 输入的颜色
  8. }
  9. SubShader
  10. {
  11. Tags { "RenderType"="Opaque" }
  12. Pass
  13. {
  14. // 使用 alpha blend 模式
  15. Blend SrcAlpha OneMinusSrcAlpha
  16. ZWrite On
  17. Cull Front
  18. CGPROGRAM
  19. #pragma vertex vert
  20. #pragma fragment frag
  21. #include "UnityCG.cginc"
  22. struct appdata_t
  23. {
  24. float4 vertex : POSITION;
  25. float2 uv : TEXCOORD0;
  26. };
  27. struct v2f
  28. {
  29. float4 pos : SV_POSITION;
  30. float2 uv : TEXCOORD0;
  31. };
  32. // Shader 需要的属性
  33. sampler2D _MainTex;
  34. sampler2D _AlphaTex;
  35. float4 _Color; // 混合时使用的颜色
  36. // Gamma -> Linear 转换
  37. float GammaToLinear(float c)
  38. {
  39. return pow(c, 2.2); // 伽马到线性空间的转换
  40. }
  41. // Linear -> Gamma 转换
  42. float GammaToGammaSpace(float c)
  43. {
  44. return pow(c, 1.0 / 2.2); // 线性到伽马空间的转换
  45. }
  46. // 顶点着色器
  47. v2f vert(appdata_t v)
  48. {
  49. v2f o;
  50. o.pos = UnityObjectToClipPos(v.vertex);
  51. o.uv = v.uv;
  52. return o;
  53. }
  54. // 片段着色器
  55. float4 frag(v2f i) : SV_Target
  56. {
  57. // 获取基础纹理颜色和透明度纹理
  58. float3 baseColor = tex2D(_MainTex, i.uv).rgb;
  59. float alpha = tex2D(_AlphaTex, i.uv).r;
  60. // 伽马 -> 线性 转换
  61. float3 linearBaseColor = GammaToLinear(baseColor);
  62. float linearAlpha = GammaToLinear(alpha);
  63. // 混合颜色和透明度(线性空间)
  64. float3 blendedColor = lerp(linearBaseColor, _Color.rgb, linearAlpha);
  65. // 线性 -> 伽马 转换
  66. blendedColor = GammaToGammaSpace(blendedColor);
  67. // 返回最终的颜色(带有透明度)
  68. return float4(blendedColor, 1.0);
  69. }
  70. ENDCG
  71. }
  72. }
  73. FallBack "Diffuse"
  74. }