Search Unity

Mask Shader

Discussion in 'Shaders' started by Perceive, Nov 12, 2014.

  1. Perceive

    Perceive

    Joined:
    Aug 2, 2013
    Posts:
    10
    Hello. I'm new to writing shaders (I dabbled in WebGL a few years ago for about six months prior to my attraction to Unity), but I'm trying to learn how they work now. I was looking to make a mask shader that holds an alpha texture only, with the goal being to "see through" parts of objects (used for fading in text and GUI elements, mainly). The mask shader would move across the stage, reducing the alpha of pixels below it according to its alpha mask texture. The alpha of the texture sets the alpha of the objects underneath, so a pixel underneath the mask's alpha of 0.5 would have its alpha halved. I was looking to have multiple of these on screen at once, but overlapping isn't an issue. (The objects "below" these objects are rendered by a separate camera.)

    Here's an example of what I was looking to have, and it lowering the opacity of an object (with a completely different shader) rendered before it.


    I quickly found this DepthMask shader, but I needed to be able to use different alpha masks with transparency, so it won't work. I also didn't want to change the render queue of all the objects since I didn't know what problems could arise from that (especially shaders that already render in specific orders).

    I also found this solution, but I needed the shader to be able to work on atlases and animate within the scene, so it can't be attached directly to the textures it will be affecting.

    After looking for a few hours to find a solution, I ended up starting to make one. I tried blending since I figured it would do exactly what I needed (and it's cheaper than grabbing/fetching pixels), but it wasn't giving the results needed. I'm thinking what the shader needs to do is:
    • Render last, so Tags { "Queue" = "Transparent+10" }. Also means that render order/z-depth don't matter
    • Write to z-buffer
    • Get current pixel below, either with GrabPass() or texelFetch
    • Get alpha value in mask texture
    • Output grabbed/fetched texture's rgb with multiplication of mask's alpha and grabbed/fetched texture's alpha
    Am I on the right track? I'm actually interested in learning shaders, so if any of this isn't possible—or if any of this reasoning is incorrect—I'd appreciate being told.

    Thanks for your time.