Draw renderers into render texture with sorted 2d sprite mask

Hello, dear unity forum!
I have a pretty hard to solve issue - I can’t get around with rendering my custom mask into render texture with respect of scene geometry (sprites)
I would like to make a 2d water shader using hand-drawn heightmaps - I put them into the scene, set sorting layer to “water” , set appropriate order in layer,then animate verticies with shader, hide rendering from the renderer asset and draw them through scriptable renderer feature with method

context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref _filteringSettings, ref _renderStateBlock);

It gives me a really nice heightmap to sample for post-processing water

Unfortunately, it did not take into account another scene sprites. At the very least, after applying post processing I get this overlapping issue


So…if I render everything as is - without hiding “water” layer - the result is perfect. I would like to keep only the pixels occupied by heightmap shader after the whole scene is rendered. Is there a good approach for this?

For anyone interested in future… I could not get better solution then create custom rendering order through c# scripting…
So the idea is that -

  1. Setup 2 cameras. Set culling mask for for one of them - everything except water layer, another should draw everything.
  2. Use custom c# scripting solution. You have to collect all renderers in the scene and sort them BY YOUR OWN
allRenderers.OrderByDescending(x => x.transform.position.z).ThenBy(x => x.sortingOrder);

ofc, you need to include sorting layer here if you want to draw like unity does.

Actually, here I do my own sorting, but refer to this page if you want to have exact replica

  1. In renderer feature use the resulting collection with commandBuffer.DrawRenderers().
    before that, I check if renderer I want to draw is inside layer “water” - so I draw it with assigned shader, otherwise (in any other renderer except water), I draw with shader that outputs just black color (0,0,0,0)

This solution works with 2D painter drawing algorithm. For 3D you can check something better, for example