Search Unity

Question How to use lookup texture to perform offset for texture in fragment shader

Discussion in 'Shader Graph' started by Tainted_Lemon, Apr 9, 2021.

  1. Tainted_Lemon

    Tainted_Lemon

    Joined:
    Aug 25, 2013
    Posts:
    5
    Hi,

    Trying to wrap my head around how fragment shaders work. I have the following scenario:

    2D shader with parameters

    Main Texture
    Lookup Texture

    I am attempting to shift UVs by X amount to the right based on the red channel of the lookup texture.

    Am I correct in assuming this is impossible to do in a fragment shader?

    I am able to perform an offset of the entire UV by X easy enough, but doing it by a variable amount per pixel escapes me.

    Thanks
     
  2. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    Hi,

    Here is one way how you can offset an UV in one dimension varying amount.

    I made the example procedurally but you can equally well replace the procedural part with an image (i.e. your lookup texture).

    So basically you just add an offset to the U or V (or both) dimensions of your UV, and that in turn "deforms" the image as it is it not sampled with a linear UV.

    20210410_UV_offset.png
     
  3. Tainted_Lemon

    Tainted_Lemon

    Joined:
    Aug 25, 2013
    Posts:
    5
    Hi Olmi,

    What I've become confused about is whether this shift is possible at a variable rate per column.

    In your example all pixels in the 5th row would be moved to the right by X pixels. I was attempting to move only some of them by X pixels.

    I assume that this still will not work, as you need to identify in the destination pixel how far it should have moved. Consider this example:

    3 blue pixels represent the image. 3 red to black pixels represent the lookup. The topmost pixel needs to be moved over by 2 units. Therefore the UV in the destination (2,2) needs to sample the texture at (0,2), but I can't figure out how you would adjust the UVs by the lookup.
     

    Attached Files:

  4. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    Well, you are thinking it a bit backwards considering how shaders function.You really can't "move" the blocks, but you can create the illusion that the tile has moved by rendering different content to the tile map you are trying to create there. i.e. if you got the first row in your pattern, to the first two tiles you render something else, and then to the third you render the blue tile. And so on.
     
  5. Tainted_Lemon

    Tainted_Lemon

    Joined:
    Aug 25, 2013
    Posts:
    5
    Thanks Olmi, you're right still trying to wrap my head around how to think about shaders. Appreciate your example.