Search Unity

Question How to use compute shaders to compute enclosed regions within a texture

Discussion in 'General Graphics' started by KuanMi, Dec 28, 2022.

  1. KuanMi

    KuanMi

    Joined:
    Feb 25, 2020
    Posts:
    41
    As shown in the figure below, a basic line drawing function is realized through the renderFeature of URP.
    And when there is an enclosed area, turn it white.

    Currently I am getting data through tex.ReadPixels and tex.GetPixels. Use the CPU to traverse each pixel through BFS to determine whether the closed area exists and use tex.SetPixel to cover the pixel.

    This is too slow. Since I have almost no experience with compute shaders, I was wondering if it is possible to achieve the same functionality with compute shaders? If possible, can someone give me some keywords for me to search?
    upload_2022-12-28_10-47-5.gif
     
  2. joshuacwilde

    joshuacwilde

    Joined:
    Feb 4, 2018
    Posts:
    727
    search for "compute shader flood fill" or "gpu compute flood fill"
     
    KuanMi and ignarmezh like this.
  3. KuanMi

    KuanMi

    Joined:
    Feb 25, 2020
    Posts:
    41
    Thank you so much, I think I finally found the right direction to solve the problem.
     
    joshuacwilde likes this.
  4. KuanMi

    KuanMi

    Joined:
    Feb 25, 2020
    Posts:
    41
    It works! And much faster than the CPU! But I still want to ask greedily, assuming that the texture has a resolution of 1024*1024, it is necessary to dispatch 1024 times to calculate the shader. Is there any way to optimize it?
    Code (CSharp):
    1.          
    2. for (int i = 0; i < splatmapWidth; i++)
    3.     {
    4.         shader.Dispatch(kernel, splatmapWidth / 8, splatmapWidth / 8, 1);
    5.     }
    6.  
    upload_2022-12-29_9-46-36.gif
     
  5. moos_unity

    moos_unity

    Joined:
    Mar 12, 2019
    Posts:
    5
    Mind sharing your implementation or the resources you found useful?
     
  6. KuanMi

    KuanMi

    Joined:
    Feb 25, 2020
    Posts:
    41
    Of course, this is a little summary written in Chinese, and there are all the codes in it.
    https://www.kuanmi.top/2022/12/26/draw/