Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Transparent RenderTexture with PostProcessing

Discussion in 'Universal Render Pipeline' started by robrab2000-aa, Apr 11, 2022.

  1. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Hi, we recently upgraded from URP 7.5.3 (2019.4) to URP 12.1.6 (2021.2) and are getting some strange behaviour from a RenderTexture which we are using to implement a form of Camera Stacking. This was working great in 2019.4 but that was using PostProcessingV2 so...

    We're essentially trying to have two separate layers of colour grading, one for subject and another for background. To achieve this we have two cameras in the same position/orientation, the first renders the background with its post processing. We then output our second camera (subject) with its own post processing onto a render texture which we then place in front of the first camera. We cull everything but the subject with the second camera and output it to a RenderTexture which we place in front of the first camera (using a Screen Space - Camera UI canvas) so that the two layers are drawn with the subject in front of the background.

    The problem is that if we enable PostProcessing on the second camera, we lose the ability to have a transparent background.

    Post processing on the layered camera disabled:
    Screenshot 2022-04-11 at 12.58.05.png Screenshot 2022-04-11 at 12.58.21.png

    Here is what that looks like when I enable post processing on the layered camera (outputted to render texture):
    Screenshot 2022-04-11 at 12.58.11.png Screenshot 2022-04-11 at 12.58.30.png

    Initially I thought it was the format of the RenderTexture but I've tried different options to no avail. These are the settings we currently use:
    Screenshot 2022-04-11 at 13.09.47.png

    I read here (https://forum.unity.com/threads/ren...-in-urp-coming-from-lwrp.749441/#post-5674399) that others have had similar issues and that assigning a material of type URP/Particles/Simple Lit might help but this hasn't worked for us.
     
  2. Kichang-Kim

    Kichang-Kim

    Joined:
    Oct 19, 2010
    Posts:
    1,008
    FaithlessOne likes this.
  3. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Right, thank you! I haven't done much HLSL before. is this a relatively trivial change to make? (I'm assuming its not and that by adjusting the uber shader, there will be many tertiary considerations/complications)
     
  4. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    If I manually adjust that alpha value to 0.25 then I get this:
    Screenshot 2022-04-11 at 17.30.44.png

    I've done this by duplicating the UberPost.shader file into my project, referencing the duplicated shader in my Forward Renderer Data object and changing the return of this function to this:
    return half4(color, 0.25);


    All of this is in line with what you've explained to me. So I expect that if I can grab the alpha value from the input to this shader, then I can pass it through. I don't know how to reference the alpha value.

    It looks like the rest of the colours are fetched using this on line 141:
    color = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted).xyz;


    Rider doesn't seem to let me check the declaration of this function to work out if I can use it to get at the alpha value.

    Any ideas for how I can get the alpha values?
     
  5. Kichang-Kim

    Kichang-Kim

    Joined:
    Oct 19, 2010
    Posts:
    1,008
    You can get original alpha value by using
    half alpha = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted).w;


    Then return it
    return half4(color, alpha)


    (This is sample code for explanation, not ideal solution. Because it takes 2 texture sampling. You can get alpha from original SAMPLE_TXETURE2D_X by storing it to half4 without extra texture sampling)
     
  6. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Hooray! Thank you!
     
    shibi2017 likes this.
  7. Master_Davicous

    Master_Davicous

    Joined:
    Apr 29, 2016
    Posts:
    11
    Could you share your final shader code and how you went about adding it to the Forward Renderer Data? I'm having trouble with it.
     
    --julian95-- likes this.
  8. --julian95--

    --julian95--

    Joined:
    Nov 2, 2015
    Posts:
    6
    Yeah it would be awesome if you could share your final solution. Even more awesome it would be if Unity could fix this.
     
    Radivarig likes this.
  9. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Ah, sorry I've only just seen this, here you go!

    Code (CSharp):
    1. Shader "Artificial Artists/Universal Render Pipeline/AA_UberPost"
    2. {
    3.     HLSLINCLUDE
    4.         #pragma exclude_renderers gles
    5.         #pragma multi_compile_local_fragment _ _DISTORTION
    6.         #pragma multi_compile_local_fragment _ _CHROMATIC_ABERRATION
    7.         #pragma multi_compile_local_fragment _ _BLOOM_LQ _BLOOM_HQ _BLOOM_LQ_DIRT _BLOOM_HQ_DIRT
    8.         #pragma multi_compile_local_fragment _ _HDR_GRADING _TONEMAP_ACES _TONEMAP_NEUTRAL
    9.         #pragma multi_compile_local_fragment _ _FILM_GRAIN
    10.         #pragma multi_compile_local_fragment _ _DITHERING
    11.         #pragma multi_compile_local_fragment _ _GAMMA_20 _LINEAR_TO_SRGB_CONVERSION
    12.         #pragma multi_compile_local_fragment _ _USE_FAST_SRGB_LINEAR_CONVERSION
    13.         #pragma multi_compile _ _USE_DRAW_PROCEDURAL
    14.         #pragma multi_compile_fragment _ DEBUG_DISPLAY
    15.  
    16.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
    17.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Filtering.hlsl"
    18.         #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
    19.         #include "Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/Common.hlsl"
    20.         #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/DebuggingFullscreen.hlsl"
    21.  
    22.         // Hardcoded dependencies to reduce the number of variants
    23.         #if _BLOOM_LQ || _BLOOM_HQ || _BLOOM_LQ_DIRT || _BLOOM_HQ_DIRT
    24.             #define BLOOM
    25.             #if _BLOOM_LQ_DIRT || _BLOOM_HQ_DIRT
    26.                 #define BLOOM_DIRT
    27.             #endif
    28.         #endif
    29.  
    30.         TEXTURE2D_X(_SourceTex);
    31.         TEXTURE2D_X(_Bloom_Texture);
    32.         TEXTURE2D(_LensDirt_Texture);
    33.         TEXTURE2D(_Grain_Texture);
    34.         TEXTURE2D(_InternalLut);
    35.         TEXTURE2D(_UserLut);
    36.         TEXTURE2D(_BlueNoise_Texture);
    37.  
    38.         float4 _Lut_Params;
    39.         float4 _UserLut_Params;
    40.         float4 _Bloom_Params;
    41.         float _Bloom_RGBM;
    42.         float4 _LensDirt_Params;
    43.         float _LensDirt_Intensity;
    44.         float4 _Distortion_Params1;
    45.         float4 _Distortion_Params2;
    46.         float _Chroma_Params;
    47.         half4 _Vignette_Params1;
    48.         float4 _Vignette_Params2;
    49.         float2 _Grain_Params;
    50.         float4 _Grain_TilingParams;
    51.         float4 _Bloom_Texture_TexelSize;
    52.         float4 _Dithering_Params;
    53.  
    54.         #define DistCenter              _Distortion_Params1.xy
    55.         #define DistAxis                _Distortion_Params1.zw
    56.         #define DistTheta               _Distortion_Params2.x
    57.         #define DistSigma               _Distortion_Params2.y
    58.         #define DistScale               _Distortion_Params2.z
    59.         #define DistIntensity           _Distortion_Params2.w
    60.  
    61.         #define ChromaAmount            _Chroma_Params.x
    62.  
    63.         #define BloomIntensity          _Bloom_Params.x
    64.         #define BloomTint               _Bloom_Params.yzw
    65.         #define BloomRGBM               _Bloom_RGBM.x
    66.         #define LensDirtScale           _LensDirt_Params.xy
    67.         #define LensDirtOffset          _LensDirt_Params.zw
    68.         #define LensDirtIntensity       _LensDirt_Intensity.x
    69.  
    70.         #define VignetteColor           _Vignette_Params1.xyz
    71.         #define VignetteCenter          _Vignette_Params2.xy
    72.         #define VignetteIntensity       _Vignette_Params2.z
    73.         #define VignetteSmoothness      _Vignette_Params2.w
    74.         #define VignetteRoundness       _Vignette_Params1.w
    75.  
    76.         #define LutParams               _Lut_Params.xyz
    77.         #define PostExposure            _Lut_Params.w
    78.         #define UserLutParams           _UserLut_Params.xyz
    79.         #define UserLutContribution     _UserLut_Params.w
    80.  
    81.         #define GrainIntensity          _Grain_Params.x
    82.         #define GrainResponse           _Grain_Params.y
    83.         #define GrainScale              _Grain_TilingParams.xy
    84.         #define GrainOffset             _Grain_TilingParams.zw
    85.  
    86.         #define DitheringScale          _Dithering_Params.xy
    87.         #define DitheringOffset         _Dithering_Params.zw
    88.  
    89.         float2 DistortUV(float2 uv)
    90.         {
    91.             // Note: this variant should never be set with XR
    92.             #if _DISTORTION
    93.             {
    94.                 uv = (uv - 0.5) * DistScale + 0.5;
    95.                 float2 ruv = DistAxis * (uv - 0.5 - DistCenter);
    96.                 float ru = length(float2(ruv));
    97.  
    98.                 UNITY_BRANCH
    99.                 if (DistIntensity > 0.0)
    100.                 {
    101.                     float wu = ru * DistTheta;
    102.                     ru = tan(wu) * (rcp(ru * DistSigma));
    103.                     uv = uv + ruv * (ru - 1.0);
    104.                 }
    105.                 else
    106.                 {
    107.                     ru = rcp(ru) * DistTheta * atan(ru * DistSigma);
    108.                     uv = uv + ruv * (ru - 1.0);
    109.                 }
    110.             }
    111.             #endif
    112.  
    113.             return uv;
    114.         }
    115.  
    116.         half4 Frag(Varyings input) : SV_Target
    117.         {
    118.             UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
    119.  
    120.             float2 uv = UnityStereoTransformScreenSpaceTex(input.uv);
    121.             float2 uvDistorted = DistortUV(uv);
    122.  
    123.             half3 color = (0.0).xxx;
    124.  
    125.             #if _CHROMATIC_ABERRATION
    126.             {
    127.                 // Very fast version of chromatic aberration from HDRP using 3 samples and hardcoded
    128.                 // spectral lut. Performs significantly better on lower end GPUs.
    129.                 float2 coords = 2.0 * uv - 1.0;
    130.                 float2 end = uv - coords * dot(coords, coords) * ChromaAmount;
    131.                 float2 delta = (end - uv) / 3.0;
    132.  
    133.                 half r = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted                ).x;
    134.                 half g = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, DistortUV(delta + uv)      ).y;
    135.                 half b = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, DistortUV(delta * 2.0 + uv)).z;
    136.  
    137.                 color = half3(r, g, b);
    138.             }
    139.             #else
    140.             {
    141.                 color = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted).xyz;
    142.             }
    143.             #endif
    144.  
    145.             // Gamma space... Just do the rest of Uber in linear and convert back to sRGB at the end
    146.             #if UNITY_COLORSPACE_GAMMA
    147.             {
    148.                 color = GetSRGBToLinear(color);
    149.             }
    150.             #endif
    151.  
    152.             #if defined(BLOOM)
    153.             {
    154.                 #if _BLOOM_HQ && !defined(SHADER_API_GLES)
    155.                 half4 bloom = SampleTexture2DBicubic(TEXTURE2D_X_ARGS(_Bloom_Texture, sampler_LinearClamp), uvDistorted, _Bloom_Texture_TexelSize.zwxy, (1.0).xx, unity_StereoEyeIndex);
    156.                 #else
    157.                 half4 bloom = SAMPLE_TEXTURE2D_X(_Bloom_Texture, sampler_LinearClamp, uvDistorted);
    158.                 #endif
    159.  
    160.                 #if UNITY_COLORSPACE_GAMMA
    161.                 bloom.xyz *= bloom.xyz; // γ to linear
    162.                 #endif
    163.  
    164.                 UNITY_BRANCH
    165.                 if (BloomRGBM > 0)
    166.                 {
    167.                     bloom.xyz = DecodeRGBM(bloom);
    168.                 }
    169.  
    170.                 bloom.xyz *= BloomIntensity;
    171.                 color += bloom.xyz * BloomTint;
    172.  
    173.                 #if defined(BLOOM_DIRT)
    174.                 {
    175.                     // UVs for the dirt texture should be DistortUV(uv * DirtScale + DirtOffset) but
    176.                     // considering we use a cover-style scale on the dirt texture the difference
    177.                     // isn't massive so we chose to save a few ALUs here instead in case lens
    178.                     // distortion is active.
    179.                     half3 dirt = SAMPLE_TEXTURE2D(_LensDirt_Texture, sampler_LinearClamp, uvDistorted * LensDirtScale + LensDirtOffset).xyz;
    180.                     dirt *= LensDirtIntensity;
    181.                     color += dirt * bloom.xyz;
    182.                 }
    183.                 #endif
    184.             }
    185.             #endif
    186.  
    187.             // To save on variants we'll use an uniform branch for vignette. Lower end platforms
    188.             // don't like these but if we're running Uber it means we're running more expensive
    189.             // effects anyway. Lower-end devices would limit themselves to on-tile compatible effect
    190.             // and thus this shouldn't too much of a problem (famous last words).
    191.             UNITY_BRANCH
    192.             if (VignetteIntensity > 0)
    193.             {
    194.                 color = ApplyVignette(color, uvDistorted, VignetteCenter, VignetteIntensity, VignetteRoundness, VignetteSmoothness, VignetteColor);
    195.             }
    196.  
    197.             // Color grading is always enabled when post-processing/uber is active
    198.             {
    199.                 color = ApplyColorGrading(color, PostExposure, TEXTURE2D_ARGS(_InternalLut, sampler_LinearClamp), LutParams, TEXTURE2D_ARGS(_UserLut, sampler_LinearClamp), UserLutParams, UserLutContribution);
    200.             }
    201.  
    202.             #if _FILM_GRAIN
    203.             {
    204.                 color = ApplyGrain(color, uv, TEXTURE2D_ARGS(_Grain_Texture, sampler_LinearRepeat), GrainIntensity, GrainResponse, GrainScale, GrainOffset);
    205.             }
    206.             #endif
    207.  
    208.             // When Unity is configured to use gamma color encoding, we ignore the request to convert to gamma 2.0 and instead fall back to sRGB encoding
    209.             #if _GAMMA_20 && !UNITY_COLORSPACE_GAMMA
    210.             {
    211.                 color = LinearToGamma20(color);
    212.             }
    213.             // Back to sRGB
    214.             #elif UNITY_COLORSPACE_GAMMA || _LINEAR_TO_SRGB_CONVERSION
    215.             {
    216.                 color = GetLinearToSRGB(color);
    217.             }
    218.             #endif
    219.  
    220.             #if _DITHERING
    221.             {
    222.                 color = ApplyDithering(color, uv, TEXTURE2D_ARGS(_BlueNoise_Texture, sampler_PointRepeat), DitheringScale, DitheringOffset);
    223.                 // Assume color > 0 and prevent 0 - ditherNoise.
    224.                 // Negative colors can cause problems if fed back to the postprocess via render to FP16 texture.
    225.                 color = max(color, 0);
    226.             }
    227.             #endif
    228.  
    229.             #if defined(DEBUG_DISPLAY)
    230.             half4 debugColor = 0;
    231.  
    232.             if(CanDebugOverrideOutputColor(half4(color, 1), uv, debugColor))
    233.             {
    234.                 return debugColor;
    235.             }
    236.             #endif
    237.  
    238.             half alpha = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted).w;
    239.             return half4(color, alpha);
    240.         }
    241.  
    242.     ENDHLSL
    243.  
    244.     SubShader
    245.     {
    246.         Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline"}
    247.         LOD 100
    248.         ZTest Always ZWrite Off Cull Off
    249.  
    250.         Pass
    251.         {
    252.             Name "UberPost"
    253.  
    254.             HLSLPROGRAM
    255.                 #pragma vertex FullscreenVert
    256.                 #pragma fragment Frag
    257.             ENDHLSL
    258.         }
    259.     }
    260. }
    261.  
     
  10. StanSi

    StanSi

    Joined:
    Jan 16, 2017
    Posts:
    2
    I can't find where to reference the shader which you give at yesterday in my Forward Renderer Data object. I used unity 2021.3.4f1c1. There is nothing displayed on the inspector of my PostProcessData.asset.
     

    Attached Files:

    unity_KLb5YtVHF55zzA likes this.
  11. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Heya, you need to replace which shader gets used as the uber post processing shader. In mine this is exposed using this gist: https://gist.github.com/tomkail/ba4136e6aa990f4dc94e0d39ec6a058c
    It basically lets you see the details of a scriptable object without having to go into the object directly.

    From there you just replace the shader being used:
    Screenshot 2022-07-15 at 10.43.30.png
     
    FaithlessOne, milox777 and Kouta-kyun like this.
  12. JudahMantell

    JudahMantell

    Joined:
    Feb 28, 2017
    Posts:
    476
    I know this is an older thread, but I just wanted to say that @robrab2000-aa saved me with his solution!
    I wish Unity would make PP transparency optional because in some cases it's important!
    Thanks again :)
     
    robrab2000-aa likes this.
  13. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Ah, thanks! You just made my day!
     
    Yoraiz0r and JudahMantell like this.
  14. FrankfurtOceanic

    FrankfurtOceanic

    Joined:
    Feb 23, 2022
    Posts:
    1
    Hey I know this was a month ago but I was hoping you could help me out. When I place the ExtendedScriptableObjectDrawer.cs file in the Packages/Universal RP/editor, it doesn't expose the other variables. Is there a different location it should go in? Thanks
     
  15. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Hey, I don't think ExtendedScriptableObjectDrawer.cs should be in the Packages folder. Just put it somewhere in your project in a folder called `Editor`.
     
  16. Radivarig

    Radivarig

    Joined:
    May 15, 2013
    Posts:
    120
    Is this still the only solution? Has someone opened a bug/request ticket?
     
  17. DrViJ

    DrViJ

    Joined:
    Feb 9, 2013
    Posts:
    158
    Hope it can help someone, another way to show the list of shaders is switching inspector debug mode

    Screenshot 2023-04-30 at 10.53.07.png
     
  18. StripeGuy

    StripeGuy

    Joined:
    Dec 30, 2016
    Posts:
    52

    Unfortunately I get an error in the console when I drag your new shader file in the UberPostPS spot:

    Code (CSharp):
    1. The package cache was invalidated and rebuilt because the following immutable asset(s) were unexpectedly altered:
    2.   Packages/com.unity.render-pipelines.universal/Runtime/Data/PostProcessData.asset
    Is there anyway to override it? I've noticed you also changed the main Post Processing file in there as well (AA_PostProcessData).
     
  19. StripeGuy

    StripeGuy

    Joined:
    Dec 30, 2016
    Posts:
    52
    Btw, this doesn't show the shader we need for some reason (UberPost). Still need robrab2000-aa's git script he linked for it to show.
     
  20. Radivarig

    Radivarig

    Joined:
    May 15, 2013
    Posts:
    120
    @StripeGuy I've not tried it yet, but from the screenshots it seems that both are showing "Uber Post PS". Is that not the one?
     
  21. StripeGuy

    StripeGuy

    Joined:
    Dec 30, 2016
    Posts:
    52
    Yes, his screenshot does show it for some reason, but when you actually try it, it doesn't show. Might be the version I'm using that's causing it (2022.2.18)?
     
    Radivarig likes this.
  22. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    I'm not on 2022 yet so I'm not sure if that is an issue but it's not impossible that the UberShader has been updated. The key part of the ubershader we've updated is this (lines 238/239 in the code I posted before):

    Code (CSharp):
    1. half alpha = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted).w;
    2.             return half4(color, alpha);
    So probably what you would like to do is just replace this bit in whatever the current version of the ubershader is.. The important thing is that we're asking the ubershader to pass the alpha value through the shader rather than just sending a hard coded '1' for the alpha value.
     
    FaithlessOne likes this.
  23. FaithlessOne

    FaithlessOne

    Joined:
    Jun 19, 2017
    Posts:
    313
    Thanks to @robrab2000-aa! Worked for me in URP 14.0.8 using the following change at the end of the shader (seems to be changes to the UberPost.shader since URP 12):
    Code (CSharp):
    1. half alpha = SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_LinearClamp, uvDistorted).w;
    2. return half4(color, alpha);
    Code (CSharp):
    1.  
    2. Shader "Custom/AlphaUberPost"
    3. {
    4.     HLSLINCLUDE
    5.         #pragma exclude_renderers gles
    6.         #pragma multi_compile_local_fragment _ _DISTORTION
    7.         #pragma multi_compile_local_fragment _ _CHROMATIC_ABERRATION
    8.         #pragma multi_compile_local_fragment _ _BLOOM_LQ _BLOOM_HQ _BLOOM_LQ_DIRT _BLOOM_HQ_DIRT
    9.         #pragma multi_compile_local_fragment _ _HDR_GRADING _TONEMAP_ACES _TONEMAP_NEUTRAL
    10.         #pragma multi_compile_local_fragment _ _FILM_GRAIN
    11.         #pragma multi_compile_local_fragment _ _DITHERING
    12.         #pragma multi_compile_local_fragment _ _GAMMA_20 _LINEAR_TO_SRGB_CONVERSION
    13.         #pragma multi_compile_local_fragment _ _USE_FAST_SRGB_LINEAR_CONVERSION
    14.         #pragma multi_compile_fragment _ _FOVEATED_RENDERING_NON_UNIFORM_RASTER
    15.         // Foveated rendering currently not supported in dxc on metal
    16.         #pragma never_use_dxc metal
    17.         #pragma multi_compile_fragment _ DEBUG_DISPLAY
    18.         #pragma multi_compile_fragment _ SCREEN_COORD_OVERRIDE
    19.         #pragma multi_compile_local_fragment _ HDR_INPUT HDR_ENCODING
    20.  
    21.         #ifdef HDR_ENCODING
    22.         #define HDR_INPUT 1 // this should be defined when HDR_ENCODING is defined
    23.         #endif
    24.  
    25.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
    26.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Filtering.hlsl"
    27.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ScreenCoordOverride.hlsl"
    28. #if defined(HDR_ENCODING)
    29.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
    30.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/HDROutput.hlsl"
    31. #endif
    32.  
    33.         #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
    34.         #include "Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/Common.hlsl"
    35.         #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/DebuggingFullscreen.hlsl"
    36.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRendering.hlsl"
    37.  
    38.         // Hardcoded dependencies to reduce the number of variants
    39.         #if _BLOOM_LQ || _BLOOM_HQ || _BLOOM_LQ_DIRT || _BLOOM_HQ_DIRT
    40.             #define BLOOM
    41.             #if _BLOOM_LQ_DIRT || _BLOOM_HQ_DIRT
    42.                 #define BLOOM_DIRT
    43.             #endif
    44.         #endif
    45.  
    46.         TEXTURE2D_X(_Bloom_Texture);
    47.         TEXTURE2D(_LensDirt_Texture);
    48.         TEXTURE2D(_Grain_Texture);
    49.         TEXTURE2D(_InternalLut);
    50.         TEXTURE2D(_UserLut);
    51.         TEXTURE2D(_BlueNoise_Texture);
    52.         TEXTURE2D_X(_OverlayUITexture);
    53.  
    54.         float4 _Lut_Params;
    55.         float4 _UserLut_Params;
    56.         float4 _Bloom_Params;
    57.         float _Bloom_RGBM;
    58.         float4 _LensDirt_Params;
    59.         float _LensDirt_Intensity;
    60.         float4 _Distortion_Params1;
    61.         float4 _Distortion_Params2;
    62.         float _Chroma_Params;
    63.         half4 _Vignette_Params1;
    64.         float4 _Vignette_Params2;
    65.     #ifdef USING_STEREO_MATRICES
    66.         float4 _Vignette_ParamsXR;
    67.     #endif
    68.         float2 _Grain_Params;
    69.         float4 _Grain_TilingParams;
    70.         float4 _Bloom_Texture_TexelSize;
    71.         float4 _Dithering_Params;
    72.         float4 _HDROutputLuminanceParams;
    73.  
    74.         #define DistCenter              _Distortion_Params1.xy
    75.         #define DistAxis                _Distortion_Params1.zw
    76.         #define DistTheta               _Distortion_Params2.x
    77.         #define DistSigma               _Distortion_Params2.y
    78.         #define DistScale               _Distortion_Params2.z
    79.         #define DistIntensity           _Distortion_Params2.w
    80.  
    81.         #define ChromaAmount            _Chroma_Params.x
    82.  
    83.         #define BloomIntensity          _Bloom_Params.x
    84.         #define BloomTint               _Bloom_Params.yzw
    85.         #define BloomRGBM               _Bloom_RGBM.x
    86.         #define LensDirtScale           _LensDirt_Params.xy
    87.         #define LensDirtOffset          _LensDirt_Params.zw
    88.         #define LensDirtIntensity       _LensDirt_Intensity.x
    89.  
    90.         #define VignetteColor           _Vignette_Params1.xyz
    91.     #ifdef USING_STEREO_MATRICES
    92.         #define VignetteCenterEye0      _Vignette_ParamsXR.xy
    93.         #define VignetteCenterEye1      _Vignette_ParamsXR.zw
    94.     #else
    95.         #define VignetteCenter          _Vignette_Params2.xy
    96.     #endif
    97.         #define VignetteIntensity       _Vignette_Params2.z
    98.         #define VignetteSmoothness      _Vignette_Params2.w
    99.         #define VignetteRoundness       _Vignette_Params1.w
    100.  
    101.         #define LutParams               _Lut_Params.xyz
    102.         #define PostExposure            _Lut_Params.w
    103.         #define UserLutParams           _UserLut_Params.xyz
    104.         #define UserLutContribution     _UserLut_Params.w
    105.  
    106.         #define GrainIntensity          _Grain_Params.x
    107.         #define GrainResponse           _Grain_Params.y
    108.         #define GrainScale              _Grain_TilingParams.xy
    109.         #define GrainOffset             _Grain_TilingParams.zw
    110.  
    111.         #define DitheringScale          _Dithering_Params.xy
    112.         #define DitheringOffset         _Dithering_Params.zw
    113.  
    114.         #define MinNits                 _HDROutputLuminanceParams.x
    115.         #define MaxNits                 _HDROutputLuminanceParams.y
    116.         #define PaperWhite              _HDROutputLuminanceParams.z
    117.         #define OneOverPaperWhite       _HDROutputLuminanceParams.w
    118.  
    119.         float2 DistortUV(float2 uv)
    120.         {
    121.             // Note: this variant should never be set with XR
    122.             #if _DISTORTION
    123.             {
    124.                 uv = (uv - 0.5) * DistScale + 0.5;
    125.                 float2 ruv = DistAxis * (uv - 0.5 - DistCenter);
    126.                 float ru = length(float2(ruv));
    127.  
    128.                 UNITY_BRANCH
    129.                 if (DistIntensity > 0.0)
    130.                 {
    131.                     float wu = ru * DistTheta;
    132.                     ru = tan(wu) * (rcp(ru * DistSigma));
    133.                     uv = uv + ruv * (ru - 1.0);
    134.                 }
    135.                 else
    136.                 {
    137.                     ru = rcp(ru) * DistTheta * atan(ru * DistSigma);
    138.                     uv = uv + ruv * (ru - 1.0);
    139.                 }
    140.             }
    141.             #endif
    142.  
    143.             return uv;
    144.         }
    145.  
    146.         half4 FragUberPost(Varyings input) : SV_Target
    147.         {
    148.             UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
    149.  
    150.             float2 uv = SCREEN_COORD_APPLY_SCALEBIAS(UnityStereoTransformScreenSpaceTex(input.texcoord));
    151.             float2 uvDistorted = DistortUV(uv);
    152.  
    153.             half3 color = (0.0).xxx;
    154.  
    155.             #if _CHROMATIC_ABERRATION
    156.             {
    157.                 // Very fast version of chromatic aberration from HDRP using 3 samples and hardcoded
    158.                 // spectral lut. Performs significantly better on lower end GPUs.
    159.                 float2 coords = 2.0 * uv - 1.0;
    160.                 float2 end = uv - coords * dot(coords, coords) * ChromaAmount;
    161.                 float2 delta = (end - uv) / 3.0;
    162.  
    163.                 half r = SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_LinearClamp, SCREEN_COORD_REMOVE_SCALEBIAS(uvDistorted)                ).x;
    164.                 half g = SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_LinearClamp, SCREEN_COORD_REMOVE_SCALEBIAS(DistortUV(delta + uv)      )).y;
    165.                 half b = SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_LinearClamp, SCREEN_COORD_REMOVE_SCALEBIAS(DistortUV(delta * 2.0 + uv))).z;
    166.  
    167.                 color = half3(r, g, b);
    168.             }
    169.             #else
    170.             {
    171.                 color = SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_LinearClamp, SCREEN_COORD_REMOVE_SCALEBIAS(uvDistorted)).xyz;
    172.             }
    173.             #endif
    174.  
    175.             // Gamma space... Just do the rest of Uber in linear and convert back to sRGB at the end
    176.             #if UNITY_COLORSPACE_GAMMA
    177.             {
    178.                 color = GetSRGBToLinear(color);
    179.             }
    180.             #endif
    181.  
    182.             #if defined(BLOOM)
    183.             {
    184.                 float2 uvBloom = uvDistorted;
    185.                 #if defined(_FOVEATED_RENDERING_NON_UNIFORM_RASTER)
    186.                     uvBloom = RemapFoveatedRenderingDistort(uvBloom);
    187.                 #endif
    188.  
    189.                 #if _BLOOM_HQ && !defined(SHADER_API_GLES)
    190.                 half4 bloom = SampleTexture2DBicubic(TEXTURE2D_X_ARGS(_Bloom_Texture, sampler_LinearClamp), SCREEN_COORD_REMOVE_SCALEBIAS(uvBloom), _Bloom_Texture_TexelSize.zwxy, (1.0).xx, unity_StereoEyeIndex);
    191.                 #else
    192.                 half4 bloom = SAMPLE_TEXTURE2D_X(_Bloom_Texture, sampler_LinearClamp, SCREEN_COORD_REMOVE_SCALEBIAS(uvBloom));
    193.                 #endif
    194.  
    195.                 #if UNITY_COLORSPACE_GAMMA
    196.                 bloom.xyz *= bloom.xyz; // γ to linear
    197.                 #endif
    198.  
    199.                 UNITY_BRANCH
    200.                 if (BloomRGBM > 0)
    201.                 {
    202.                     bloom.xyz = DecodeRGBM(bloom);
    203.                 }
    204.  
    205.                 bloom.xyz *= BloomIntensity;
    206.                 color += bloom.xyz * BloomTint;
    207.  
    208.                 #if defined(BLOOM_DIRT)
    209.                 {
    210.                     // UVs for the dirt texture should be DistortUV(uv * DirtScale + DirtOffset) but
    211.                     // considering we use a cover-style scale on the dirt texture the difference
    212.                     // isn't massive so we chose to save a few ALUs here instead in case lens
    213.                     // distortion is active.
    214.                     half3 dirt = SAMPLE_TEXTURE2D(_LensDirt_Texture, sampler_LinearClamp, uvDistorted * LensDirtScale + LensDirtOffset).xyz;
    215.                     dirt *= LensDirtIntensity;
    216.                     color += dirt * bloom.xyz;
    217.                 }
    218.                 #endif
    219.             }
    220.             #endif
    221.  
    222.             // To save on variants we'll use an uniform branch for vignette. Lower end platforms
    223.             // don't like these but if we're running Uber it means we're running more expensive
    224.             // effects anyway. Lower-end devices would limit themselves to on-tile compatible effect
    225.             // and thus this shouldn't too much of a problem (famous last words).
    226.             UNITY_BRANCH
    227.             if (VignetteIntensity > 0)
    228.             {
    229.             #ifdef USING_STEREO_MATRICES
    230.                 // With XR, the views can use asymmetric FOV which will have the center of each
    231.                 // view be at a different location.
    232.                 const float2 VignetteCenter = unity_StereoEyeIndex == 0 ? VignetteCenterEye0 : VignetteCenterEye1;
    233.             #endif
    234.  
    235.                 color = ApplyVignette(color, uvDistorted, VignetteCenter, VignetteIntensity, VignetteRoundness, VignetteSmoothness, VignetteColor);
    236.             }
    237.  
    238.             // Color grading is always enabled when post-processing/uber is active
    239.             {
    240.                 color = ApplyColorGrading(color, PostExposure, TEXTURE2D_ARGS(_InternalLut, sampler_LinearClamp), LutParams, TEXTURE2D_ARGS(_UserLut, sampler_LinearClamp), UserLutParams, UserLutContribution);
    241.             }
    242.  
    243.             #if _FILM_GRAIN
    244.             {
    245.                 color = ApplyGrain(color, uv, TEXTURE2D_ARGS(_Grain_Texture, sampler_LinearRepeat), GrainIntensity, GrainResponse, GrainScale, GrainOffset, OneOverPaperWhite);
    246.             }
    247.             #endif
    248.  
    249.             // When Unity is configured to use gamma color encoding, we ignore the request to convert to gamma 2.0 and instead fall back to sRGB encoding
    250.             #if _GAMMA_20 && !UNITY_COLORSPACE_GAMMA
    251.             {
    252.                 color = LinearToGamma20(color);
    253.             }
    254.             // Back to sRGB
    255.             #elif UNITY_COLORSPACE_GAMMA || _LINEAR_TO_SRGB_CONVERSION
    256.             {
    257.                 color = GetLinearToSRGB(color);
    258.             }
    259.             #endif
    260.  
    261.             #if _DITHERING
    262.             {
    263.                 color = ApplyDithering(color, uv, TEXTURE2D_ARGS(_BlueNoise_Texture, sampler_PointRepeat), DitheringScale, DitheringOffset, PaperWhite, OneOverPaperWhite);
    264.                 // Assume color > 0 and prevent 0 - ditherNoise.
    265.                 // Negative colors can cause problems if fed back to the postprocess via render to FP16 texture.
    266.                 color = max(color, 0);
    267.             }
    268.             #endif
    269.  
    270.             #ifdef HDR_ENCODING
    271.             {
    272.                 float4 uiSample = SAMPLE_TEXTURE2D_X(_OverlayUITexture, sampler_PointClamp, input.texcoord);
    273.                 color.rgb = SceneUIComposition(uiSample, color.rgb, PaperWhite, MaxNits);
    274.                 color.rgb = OETF(color.rgb);
    275.             }
    276.             #endif
    277.  
    278.             #if defined(DEBUG_DISPLAY)
    279.             half4 debugColor = 0;
    280.  
    281.             if(CanDebugOverrideOutputColor(half4(color, 1), uv, debugColor))
    282.             {
    283.                 return debugColor;
    284.             }
    285.             #endif
    286.  
    287.             half alpha = SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_LinearClamp, uvDistorted).w;
    288.             return half4(color, alpha);
    289.         }
    290.     ENDHLSL
    291.  
    292.     SubShader
    293.     {
    294.         Tags
    295.         {
    296.             "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline"
    297.         }
    298.         LOD 100
    299.         ZTest Always ZWrite Off Cull Off
    300.  
    301.         Pass
    302.         {
    303.             Name "UberPost"
    304.  
    305.             HLSLPROGRAM
    306.                 #pragma vertex Vert
    307.                 #pragma fragment FragUberPost
    308.             ENDHLSL
    309.         }
    310.     }
    311. }
     
    PolyCrusher and robrab2000-aa like this.
  24. unity_4IQi75wZq_MD6g

    unity_4IQi75wZq_MD6g

    Joined:
    Jul 15, 2019
    Posts:
    4
    Not sure if Im doing something wrong, but any changes made to the Forward Renderer shaders either break post processing completely, or it gets reverted to the original UberPost shader with the error:
    "The package cache was invalidated and rebuilt because the following immutable asset(s) were unexpectedly altered:
    Packages/com.unity.render-pipelines.universal/Runtime/Data/PostProcessData.asset". Anybody found a fix for this??
     
  25. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Have you tried turning URP into a local package in your asset folder? if you don't then your changes will get overwritten by the package system
     
  26. unity_4IQi75wZq_MD6g

    unity_4IQi75wZq_MD6g

    Joined:
    Jul 15, 2019
    Posts:
    4
    I dont really know how to do that, but I did everything else just like you did. Its very strange, sometimes it doesnt revert but still has no effect when I change the alpha value in script. Have you changed anything else other than "return half4(color, alpha);" in UberPost shader?
     
  27. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    have you assigned it like this: screenshot-2022-07-15-at-10-43-30-png.1085277

    A
    lso make sure you are working from a duplicate shader, not the original or it will get overwritten every time: "I've done this by duplicating the UberPost.shader file into my project, referencing the duplicated shader in my Forward Renderer Data object and changing the return of this function to this:
    return half4(color, 0.25);"
     
  28. unity_4IQi75wZq_MD6g

    unity_4IQi75wZq_MD6g

    Joined:
    Jul 15, 2019
    Posts:
    4
    Yep I did it all right, even moved the UniversalRP folder out of PackageCache so it wouldnt get overwritten but it still has no effect. Only thing that does have any effect is changing the alpha value in the FinalPost shader, but it makes the whole image transparent and not just the background.
    head1.png
    On the left there is no post processing, on the right its on. The camera for the render texture is set to solid color and alpha is at 0. Everything else I did just like you said. Could it be a version problem? I am using 2021.3.22.
     
  29. robrab2000-aa

    robrab2000-aa

    Joined:
    Feb 8, 2019
    Posts:
    117
    Hmm, I don't think its a version thing as that's the same version we're on..
     
  30. FaithlessOne

    FaithlessOne

    Joined:
    Jun 19, 2017
    Posts:
    313
    I am only guessing: Does the shader, which is rendering the post processed texture having the alpha values into camera view, uses the correct alpha blending modes, so transparency is applied? When yes, double check that the post processed texture is really having the alpha values. When both is true, it should be rendered fine.
     
  31. Radivarig

    Radivarig

    Joined:
    May 15, 2013
    Posts:
    120
    From this post I've found the feature request for preserving alpha state when using postprocess in URP.

    Let's please vote there so they consider fixing it faster.
     
    Schiznitz3301 and FaithlessOne like this.
  32. LinaEagle

    LinaEagle

    Joined:
    Mar 15, 2018
    Posts:
    6

    Thank for your piece of code! Unfortunately, it seems not working in my case, since this addition of alpha reduced bloom effect. I was thinking, we'd better use alpha channel along all transformations, this way the actual bloom effect can work, inasmuch is its alpha will be transformed as well.

    But I'm not sure how to edit shader code in order to force it work properly.
     
  33. FaithlessOne

    FaithlessOne

    Joined:
    Jun 19, 2017
    Posts:
    313
    I have implemented a shader to blit the post-processed texture respecting the alpha values especially for bloom. I have only limited knowledge about HLSL so it requires two passes for appropriate blending (cost more performance than one pass). The shader works in conjunction with the customized UberPost.shader at least I tested it in URP 14. Here is the shader code:
    Code (CSharp):
    1. Shader "Custom/SH_EffectsRenderPass_Default"
    2. {
    3.     Properties
    4.     {
    5.         _MainTex ("Texture", 2D) = "white" {}
    6.     }
    7.     SubShader
    8.     {
    9.         Tags { "Queue"="Transparent" "RenderType"="Transparent" }
    10.         LOD 100
    11.  
    12.         Pass
    13.         {
    14.             Blend SrcAlpha OneMinusSrcAlpha
    15.             ZWrite Off
    16.             Cull Back
    17.            
    18.             CGPROGRAM
    19.             #pragma vertex vert
    20.             #pragma fragment frag
    21.  
    22.             #include "UnityCG.cginc"
    23.  
    24.             struct appdata
    25.             {
    26.                 float4 vertex : POSITION;
    27.                 float2 uv : TEXCOORD0;
    28.             };
    29.  
    30.             struct v2f
    31.             {
    32.                 float2 uv : TEXCOORD0;
    33.                 float4 vertex : SV_POSITION;
    34.             };
    35.  
    36.             sampler2D _MainTex;
    37.             float4 _MainTex_ST;
    38.  
    39.             v2f vert (appdata v)
    40.             {
    41.                 v2f o;
    42.                 o.vertex = UnityObjectToClipPos(v.vertex);
    43.                 o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    44.                 return o;
    45.             }
    46.  
    47.             half4 frag (v2f i) : SV_Target
    48.             {
    49.                 half4 col = tex2D(_MainTex, i.uv);
    50.                 return col;    
    51.             }          
    52.             ENDCG
    53.         }
    54.        
    55.         Pass
    56.         {
    57.             Blend SrcAlpha One
    58.             ZWrite Off
    59.             Cull Back
    60.            
    61.             CGPROGRAM
    62.             #pragma vertex vert
    63.             #pragma fragment frag
    64.  
    65.             #include "UnityCG.cginc"
    66.  
    67.             struct appdata
    68.             {
    69.                 float4 vertex : POSITION;
    70.                 float2 uv : TEXCOORD0;
    71.             };
    72.  
    73.             struct v2f
    74.             {
    75.                 float2 uv : TEXCOORD0;
    76.                 float4 vertex : SV_POSITION;
    77.             };
    78.  
    79.             sampler2D _MainTex;
    80.             float4 _MainTex_ST;
    81.  
    82.             v2f vert (appdata v)
    83.             {
    84.                 v2f o;
    85.                 o.vertex = UnityObjectToClipPos(v.vertex);
    86.                 o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    87.                 return o;
    88.             }
    89.  
    90.             half4 frag (v2f i) : SV_Target
    91.             {
    92.                 half4 col = tex2D(_MainTex, i.uv);
    93.                 col.a = col.a < 1 ? 1.0 : 0.0;
    94.                
    95.                 return col;        
    96.             }          
    97.             ENDCG
    98.         }
    99.     }
    100. }
    When blitting the post-processed texture you have to use the shader/material of the shader for the operation.
     
    robrab2000-aa likes this.
  34. TCYeh

    TCYeh

    Joined:
    Jul 25, 2022
    Posts:
    55
    Hi,
    I encountered a problem while attempting to make the RenderTexture transparent. Despite following the steps provided, I still couldn't achieve the desired result. Here's a summary of the steps I took:

    1. Copied the UberPost shader and added two lines of code to it.
    Code (CSharp):
    1. Shader "Custom/Universal Render Pipeline/UberPost_Alpha"
    2. {
    3.     HLSLINCLUDE
    4.         #pragma exclude_renderers gles
    5.         #pragma multi_compile_local_fragment _ _DISTORTION
    6.         #pragma multi_compile_local_fragment _ _CHROMATIC_ABERRATION
    7.         #pragma multi_compile_local_fragment _ _BLOOM_LQ _BLOOM_HQ _BLOOM_LQ_DIRT _BLOOM_HQ_DIRT
    8.         #pragma multi_compile_local_fragment _ _HDR_GRADING _TONEMAP_ACES _TONEMAP_NEUTRAL
    9.         #pragma multi_compile_local_fragment _ _FILM_GRAIN
    10.         #pragma multi_compile_local_fragment _ _DITHERING
    11.         #pragma multi_compile_local_fragment _ _GAMMA_20 _LINEAR_TO_SRGB_CONVERSION
    12.         #pragma multi_compile_local_fragment _ _USE_FAST_SRGB_LINEAR_CONVERSION
    13.         #pragma multi_compile _ _USE_DRAW_PROCEDURAL
    14.         #pragma multi_compile_fragment _ DEBUG_DISPLAY
    15.  
    16.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
    17.         #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Filtering.hlsl"
    18.         #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
    19.         #include "Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/Common.hlsl"
    20.         #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/DebuggingFullscreen.hlsl"
    21.  
    22.         // Hardcoded dependencies to reduce the number of variants
    23.         #if _BLOOM_LQ || _BLOOM_HQ || _BLOOM_LQ_DIRT || _BLOOM_HQ_DIRT
    24.             #define BLOOM
    25.             #if _BLOOM_LQ_DIRT || _BLOOM_HQ_DIRT
    26.                 #define BLOOM_DIRT
    27.             #endif
    28.         #endif
    29.  
    30.         TEXTURE2D_X(_SourceTex);
    31.         TEXTURE2D_X(_Bloom_Texture);
    32.         TEXTURE2D(_LensDirt_Texture);
    33.         TEXTURE2D(_Grain_Texture);
    34.         TEXTURE2D(_InternalLut);
    35.         TEXTURE2D(_UserLut);
    36.         TEXTURE2D(_BlueNoise_Texture);
    37.  
    38.         float4 _Lut_Params;
    39.         float4 _UserLut_Params;
    40.         float4 _Bloom_Params;
    41.         float _Bloom_RGBM;
    42.         float4 _LensDirt_Params;
    43.         float _LensDirt_Intensity;
    44.         float4 _Distortion_Params1;
    45.         float4 _Distortion_Params2;
    46.         float _Chroma_Params;
    47.         half4 _Vignette_Params1;
    48.         float4 _Vignette_Params2;
    49.         float2 _Grain_Params;
    50.         float4 _Grain_TilingParams;
    51.         float4 _Bloom_Texture_TexelSize;
    52.         float4 _Dithering_Params;
    53.  
    54.         #define DistCenter              _Distortion_Params1.xy
    55.         #define DistAxis                _Distortion_Params1.zw
    56.         #define DistTheta               _Distortion_Params2.x
    57.         #define DistSigma               _Distortion_Params2.y
    58.         #define DistScale               _Distortion_Params2.z
    59.         #define DistIntensity           _Distortion_Params2.w
    60.  
    61.         #define ChromaAmount            _Chroma_Params.x
    62.  
    63.         #define BloomIntensity          _Bloom_Params.x
    64.         #define BloomTint               _Bloom_Params.yzw
    65.         #define BloomRGBM               _Bloom_RGBM.x
    66.         #define LensDirtScale           _LensDirt_Params.xy
    67.         #define LensDirtOffset          _LensDirt_Params.zw
    68.         #define LensDirtIntensity       _LensDirt_Intensity.x
    69.  
    70.         #define VignetteColor           _Vignette_Params1.xyz
    71.         #define VignetteCenter          _Vignette_Params2.xy
    72.         #define VignetteIntensity       _Vignette_Params2.z
    73.         #define VignetteSmoothness      _Vignette_Params2.w
    74.         #define VignetteRoundness       _Vignette_Params1.w
    75.  
    76.         #define LutParams               _Lut_Params.xyz
    77.         #define PostExposure            _Lut_Params.w
    78.         #define UserLutParams           _UserLut_Params.xyz
    79.         #define UserLutContribution     _UserLut_Params.w
    80.  
    81.         #define GrainIntensity          _Grain_Params.x
    82.         #define GrainResponse           _Grain_Params.y
    83.         #define GrainScale              _Grain_TilingParams.xy
    84.         #define GrainOffset             _Grain_TilingParams.zw
    85.  
    86.         #define DitheringScale          _Dithering_Params.xy
    87.         #define DitheringOffset         _Dithering_Params.zw
    88.  
    89.         float2 DistortUV(float2 uv)
    90.         {
    91.             // Note: this variant should never be set with XR
    92.             #if _DISTORTION
    93.             {
    94.                 uv = (uv - 0.5) * DistScale + 0.5;
    95.                 float2 ruv = DistAxis * (uv - 0.5 - DistCenter);
    96.                 float ru = length(float2(ruv));
    97.  
    98.                 UNITY_BRANCH
    99.                 if (DistIntensity > 0.0)
    100.                 {
    101.                     float wu = ru * DistTheta;
    102.                     ru = tan(wu) * (rcp(ru * DistSigma));
    103.                     uv = uv + ruv * (ru - 1.0);
    104.                 }
    105.                 else
    106.                 {
    107.                     ru = rcp(ru) * DistTheta * atan(ru * DistSigma);
    108.                     uv = uv + ruv * (ru - 1.0);
    109.                 }
    110.             }
    111.             #endif
    112.  
    113.             return uv;
    114.         }
    115.  
    116.         half4 Frag(Varyings input) : SV_Target
    117.         {
    118.             UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
    119.  
    120.             float2 uv = UnityStereoTransformScreenSpaceTex(input.uv);
    121.             float2 uvDistorted = DistortUV(uv);
    122.  
    123.             half3 color = (0.0).xxx;
    124.  
    125.             #if _CHROMATIC_ABERRATION
    126.             {
    127.                 // Very fast version of chromatic aberration from HDRP using 3 samples and hardcoded
    128.                 // spectral lut. Performs significantly better on lower end GPUs.
    129.                 float2 coords = 2.0 * uv - 1.0;
    130.                 float2 end = uv - coords * dot(coords, coords) * ChromaAmount;
    131.                 float2 delta = (end - uv) / 3.0;
    132.  
    133.                 half r = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted                ).x;
    134.                 half g = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, DistortUV(delta + uv)      ).y;
    135.                 half b = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, DistortUV(delta * 2.0 + uv)).z;
    136.  
    137.                 color = half3(r, g, b);
    138.             }
    139.             #else
    140.             {
    141.                 color = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted).xyz;
    142.             }
    143.             #endif
    144.  
    145.             // Gamma space... Just do the rest of Uber in linear and convert back to sRGB at the end
    146.             #if UNITY_COLORSPACE_GAMMA
    147.             {
    148.                 color = GetSRGBToLinear(color);
    149.             }
    150.             #endif
    151.  
    152.             #if defined(BLOOM)
    153.             {
    154.                 #if _BLOOM_HQ && !defined(SHADER_API_GLES)
    155.                 half4 bloom = SampleTexture2DBicubic(TEXTURE2D_X_ARGS(_Bloom_Texture, sampler_LinearClamp), uvDistorted, _Bloom_Texture_TexelSize.zwxy, (1.0).xx, unity_StereoEyeIndex);
    156.                 #else
    157.                 half4 bloom = SAMPLE_TEXTURE2D_X(_Bloom_Texture, sampler_LinearClamp, uvDistorted);
    158.                 #endif
    159.  
    160.                 #if UNITY_COLORSPACE_GAMMA
    161.                 bloom.xyz *= bloom.xyz; // γ to linear
    162.                 #endif
    163.  
    164.                 UNITY_BRANCH
    165.                 if (BloomRGBM > 0)
    166.                 {
    167.                     bloom.xyz = DecodeRGBM(bloom);
    168.                 }
    169.  
    170.                 bloom.xyz *= BloomIntensity;
    171.                 color += bloom.xyz * BloomTint;
    172.  
    173.                 #if defined(BLOOM_DIRT)
    174.                 {
    175.                     // UVs for the dirt texture should be DistortUV(uv * DirtScale + DirtOffset) but
    176.                     // considering we use a cover-style scale on the dirt texture the difference
    177.                     // isn't massive so we chose to save a few ALUs here instead in case lens
    178.                     // distortion is active.
    179.                     half3 dirt = SAMPLE_TEXTURE2D(_LensDirt_Texture, sampler_LinearClamp, uvDistorted * LensDirtScale + LensDirtOffset).xyz;
    180.                     dirt *= LensDirtIntensity;
    181.                     color += dirt * bloom.xyz;
    182.                 }
    183.                 #endif
    184.             }
    185.             #endif
    186.  
    187.             // To save on variants we'll use an uniform branch for vignette. Lower end platforms
    188.             // don't like these but if we're running Uber it means we're running more expensive
    189.             // effects anyway. Lower-end devices would limit themselves to on-tile compatible effect
    190.             // and thus this shouldn't too much of a problem (famous last words).
    191.             UNITY_BRANCH
    192.             if (VignetteIntensity > 0)
    193.             {
    194.                 color = ApplyVignette(color, uvDistorted, VignetteCenter, VignetteIntensity, VignetteRoundness, VignetteSmoothness, VignetteColor);
    195.             }
    196.  
    197.             // Color grading is always enabled when post-processing/uber is active
    198.             {
    199.                 color = ApplyColorGrading(color, PostExposure, TEXTURE2D_ARGS(_InternalLut, sampler_LinearClamp), LutParams, TEXTURE2D_ARGS(_UserLut, sampler_LinearClamp), UserLutParams, UserLutContribution);
    200.             }
    201.  
    202.             #if _FILM_GRAIN
    203.             {
    204.                 color = ApplyGrain(color, uv, TEXTURE2D_ARGS(_Grain_Texture, sampler_LinearRepeat), GrainIntensity, GrainResponse, GrainScale, GrainOffset);
    205.             }
    206.             #endif
    207.  
    208.             // When Unity is configured to use gamma color encoding, we ignore the request to convert to gamma 2.0 and instead fall back to sRGB encoding
    209.             #if _GAMMA_20 && !UNITY_COLORSPACE_GAMMA
    210.             {
    211.                 color = LinearToGamma20(color);
    212.             }
    213.             // Back to sRGB
    214.             #elif UNITY_COLORSPACE_GAMMA || _LINEAR_TO_SRGB_CONVERSION
    215.             {
    216.                 color = GetLinearToSRGB(color);
    217.             }
    218.             #endif
    219.  
    220.             #if _DITHERING
    221.             {
    222.                 color = ApplyDithering(color, uv, TEXTURE2D_ARGS(_BlueNoise_Texture, sampler_PointRepeat), DitheringScale, DitheringOffset);
    223.                 // Assume color > 0 and prevent 0 - ditherNoise.
    224.                 // Negative colors can cause problems if fed back to the postprocess via render to FP16 texture.
    225.                 color = max(color, 0);
    226.             }
    227.             #endif
    228.  
    229.             #if defined(DEBUG_DISPLAY)
    230.             half4 debugColor = 0;
    231.  
    232.             if(CanDebugOverrideOutputColor(half4(color, 1), uv, debugColor))
    233.             {
    234.                 return debugColor;
    235.             }
    236.             #endif
    237.  
    238.             half alpha = SAMPLE_TEXTURE2D_X(_SourceTex, sampler_LinearClamp, uvDistorted).w;
    239.             return half4(color, alpha);
    240.         }
    241.  
    242.     ENDHLSL
    243.  
    244.     SubShader
    245.     {
    246.         Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline"}
    247.         LOD 100
    248.         ZTest Always ZWrite Off Cull Off
    249.  
    250.         Pass
    251.         {
    252.             Name "UberPost"
    253.  
    254.             HLSLPROGRAM
    255.                 #pragma vertex FullscreenVert
    256.                 #pragma fragment Frag
    257.             ENDHLSL
    258.         }
    259.     }
    260. }
    261.  
    2. Changed UberPost to the alpha version by customizing the PostProcessData and setting it to the URP Asset > Universal Renderer Data.

    To give you an idea, my camera is set to Solid Color with an alpha value of 0, and the RenderTexture is R8G8B8A8_UNORM + D24_UNORM (the only one that works on my target machine, unfortunately).

    However, despite following these steps, the RenderTexture is still not transparent as expected. Am I missing something crucial here?
    If you've got any ideas or solutions, I'd be more than grateful. Thanks!
     
  35. FaithlessOne

    FaithlessOne

    Joined:
    Jun 19, 2017
    Posts:
    313
    Yes, you should use the clear color (https://docs.unity3d.com/ScriptReference/Color-clear.html) with BackgroundType "Solid Color" on the camera rendering the post-processing effects and using the customized UberPost.shader. Especially ensure the customized UberPost.shader is used via the assigned Renderer of the camera:
    upload_2023-8-2_11-13-53.png
    In the settings of the Renderer ensure your cusomized Post Process Data is used which contains the cusomized UberPost.shader:
    upload_2023-8-2_11-15-47.png
    When checking the preview of the RenderTexture of the effects camera then you always see black pixels instead of transparent ones at least in Unity 2022.3 and URP 14, so it looks something like this:
    upload_2023-8-2_11-20-19.png
    Try exporting the RenderTexture to PNG to see the transparency. Here is a code snipped for an export function of a RenderTexture to PNG:
    Code (CSharp):
    1. #nullable enable
    2.  
    3. using System.IO;
    4.  
    5. using UnityEditor;
    6.  
    7. using UnityEngine;
    8.  
    9. using File = UnityEngine.Windows.File;
    10.  
    11. namespace My.Common.Scripts.Editor
    12. {
    13.   /// <summary>
    14.   /// Class for exporting PNG from textures.
    15.   /// </summary>
    16.   public static class TexturePngExport
    17.   {
    18.     /// <summary>
    19.     /// Exports the selected <see cref="RenderTexture" /> to PNG file.
    20.     /// </summary>
    21.     [MenuItem("Tools/Export/Texture To PNG")]
    22.     public static void ExportToPng()
    23.     {
    24.       if (Selection.activeObject is RenderTexture renderTexture)
    25.       {
    26.         var assetPath = AssetDatabase.GetAssetPath(renderTexture);
    27.         var fullPath = Path.Combine(Application.dataPath, "..", assetPath);
    28.         fullPath = Path.ChangeExtension(Path.GetFullPath(fullPath), "png");
    29.  
    30.         if (!File.Exists(fullPath) || !EditorUtility.DisplayDialog("Confirmation", $"File for export '{fullPath}' already exists. Continue overriding?", "No", "Yes"))
    31.         {
    32.           var activeRenderTexture = RenderTexture.active;
    33.           RenderTexture.active = renderTexture;
    34.           var texture2D = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBA32, false);
    35.           texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
    36.           texture2D.Apply(); // This line is necessary to make the pixel changes take effect
    37.           RenderTexture.active = activeRenderTexture;
    38.  
    39.           var bytes = texture2D.EncodeToPNG();
    40.           File.WriteAllBytes(fullPath, bytes);
    41.  
    42.           // Refresh AssetDatabase
    43.           AssetDatabase.Refresh();
    44.  
    45.           Debug.Log($"Exported render texture as PNG using path '{fullPath}'");
    46.         }
    47.         else
    48.         {
    49.           Debug.Log("Use cancelled exported of the render texture as PNG");
    50.         }
    51.       }
    52.       else
    53.       {
    54.         Debug.LogError("Not a render texture selected");
    55.       }
    56.     }
    57.   }
    58. }
    Select the RenderTexture in the Project Hierarchy of the Unity Editor and use Menu -> Tools -> Export -> Export To PNG. Then a PNG file is created. Thats how it looks then, the transparency can be seen when all steps have been done correctly:
    upload_2023-8-2_11-28-7.png

    I also tested with the graphics format you mentioned and it works also like the settings I used. Be aware that your graphics format settings causing restrictions when using the bloom post-processing effect, because you don't have a HDR color range on the RenderTexture then.
     
  36. TCYeh

    TCYeh

    Joined:
    Jul 25, 2022
    Posts:
    55
    @FaithlessOne Thank you very much for your response!

    Despite making the changes as per your advice, I am still facing difficulties in generating a transparent render texture.
    I have attached the settings I used for your reference.
    upload_2023-8-4_11-49-0.png

    upload_2023-8-4_11-52-10.png

    The exported png file:
    New Render Texture.png

    However, the exported PNG file retains a red background, which is not the desired outcome.

    I have been working on this issue for two days without any progress.
    I would greatly appreciate any further assistance or possible solutions you may have.
    Thank you in advance for your help!
     
  37. FaithlessOne

    FaithlessOne

    Joined:
    Jun 19, 2017
    Posts:
    313
    @TCYeh
    I tested using your camera settings and I can reproduce your result, the RenderTexture does not contain the alpha values anymore. The reason is the usage of Anti-Aliasing. The post-processing AA techniques including FXAA, SMAA and TAA, but not MSAA (which is geometry based and applied earlier) are applied after other post-processing effects. The nature of these techniques is working on opaque textures and not on textures having transparency, so it is not surprising that they do not maintain alpha values in general. Interesstingly in URP 14 and on Windows platform SMAA seems to respect the alpha values, but this is far beyond my knowledge why it is like that and also if its like that on other platforms. So a safe solution would be not using AA post-processing techniques or using your own customized AA shader which respects transparency.
     
    brunoliveiraaraujo and Radivarig like this.
  38. Radivarig

    Radivarig

    Joined:
    May 15, 2013
    Posts:
    120
    Would anyone know how to fix the issue of transparent materials or opaque ones without alpha when rendering to a texture? I'm having the result being see through while ideally if an effect has transparency it should be applied to the previous color while keeping the alpha value intact, and same for opaques that should output alpha 1 but they output 0.

    If I return this from the UberPost
    Code (CSharp):
    1. half4 alpha = SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_LinearClamp, uvDistorted).w;
    I get the this result where anything transparent or opaque with alpha 0 is see through.
    Screenshot 2023-08-16 132610.png

    If I then add
    Code (CSharp):
    1. alpha = alpha > 0.0 ? 1.0 : 0.0;
    I get the this result but that does not work on the edges where the transparency between 0 and 1 is needed.
    Screenshot 2023-08-16 133154.png

    I understand that it could be due to each shader not doing the right thing but maybe there's something that could be patched to make this work regardless in UberPost or other shaders there, like the way each Blit is blended?
     
  39. mnenad

    mnenad

    Joined:
    Dec 7, 2015
    Posts:
    18
    I had to disable Motion Blur in PostProcessing to get the desired result in the Editor while not in Play Mode. It seems to be not compliant with transparency for render textures.

    Nevertheless: As soon as I start the game, the problem persists. Followed all advice here...
     
    Last edited: Sep 1, 2023