Search Unity

Help Wanted Making comparisons with previous frame data?

Discussion in 'Shader Graph' started by carcasanchez, Feb 12, 2020 at 2:25 PM.

  1. carcasanchez


    Jul 15, 2018
    Hello there:
    In the current shader I am working on, I need to check if a float3 has changed since the last frame. Obvioulsy, I cannot store variables from one frame to another, so my question is: what is the most straightforward/performant way of storing a variable to check in the next frame?
    Things I have read, but not sure about how to implement:
    -Storing the data to a texture (viable, but I don't know if writing to a texture is possible inside Shader Graph without compromising the Master output)
    -Storing it into a buffer from a custom HLSL function (don't know if buffers allow to be changed from GPU every frame)
  2. bgolus


    Dec 7, 2012
    That's totally possible. There's no limit on how often a buffer can be changed really. However.

    That's going to be a problem.

    If you write to a buffer from a shader, you're going to write to it from every pixel or vertex the shader runs on. For vertex shaders you can kind of manage this by only writing from the first vertex index, or writing to a buffer that has as many indices as the mesh has vertices. But for the fragment shader there's not a clean way to do that since there's no "first" pixel that's guaranteed to be rendered. Also because Shader Graph has no way to ensure code only runs in the vertex shader. This means the buffer will get written to by every single visible, and doing so is both a potential performance issue (since every pixel on screen is all trying to write to the same bit of memory), and has a high chance of essentially ended up as a random value as there's no way to know which pixel is the last one that will render & write to that buffer.

    So the only real solution to this problem is don't do it! Find another way to solve the problem that doesn't involve trying to get values out of the shader that renders your object. That might be rendering your object manually using a hand written vertex fragment shader to a render texture, and processing that image using a compute shader. Or it might be computing everything you need on the CPU instead. But whatever it is, those options will be better.

    Also leave Shader Graph out of it, as it's really not the kind of thing it's intended to handle, so it'll only cause you more headache than it's worth.