Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How to render objects to a RenderTexture with custom render feature?

Discussion in 'Universal Render Pipeline' started by ryanflees, Feb 27, 2023.

  1. ryanflees

    ryanflees

    Joined:
    Nov 15, 2014
    Posts:
    59
    Hi, I want to have a sphere in the scene to draw a mask texture on the screen. The sphere should have correct culling by depth of other opaque objects.

    upload_2023-2-27_17-12-15.png
    I've done it in HDRP with custom pass, which is doable.
    (The left is scene view of the sphere, the right is the post processing using mask texture created with the sphere, the lower right is the mask texture of the sphere)

    I tried to do similiar thing in URP but very frastrating.
    I used context.DrawRenderers but it seems that it can't draw into a RenderTexture. cmd.SetRenderTarget has no effect with context.DrawRenderers.
    I also tried this
    Code (CSharp):
    1.             cmd.SetRenderTarget(m_RenderTexture.colorBuffer, m_RenderTexture.depthBuffer);
    2.                         Matrix4x4 mat = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one);
    3.                         int pass = m_MaskMaterial.FindPass("Unlit");
    4.                         cmd.DrawMesh(m_SphereMesh, mat, m_MaskMaterial, 0, pass);
    5.                        
    The result is drawn into RenderTexture, but the projection seems not correct either, and it doesn't consider the depth of the scene.

    So what should be correct way to draw a sphere in the a RenderTexture in URP like HDRP above?
     
  2. jiaozi158

    jiaozi158

    Joined:
    May 24, 2020
    Posts:
    23
    Hi, I think it's because the matrix isn't correctly set. You can check the documentation and provide a correct matrix to it.

    Also, you need to copy the camera's depth to m_RenderTexture.depthBuffer so that the depth comparison in shader (ZTest) will work.

    But depth copy will cost performance. If you'd like to avoid it, you can set the depth render target to the camera's.

    According to your use case (post-processing), I think you don't need to preserve original scene depth, so you can try the latter method.
     
    ryanflees likes this.
  3. jiaozi158

    jiaozi158

    Joined:
    May 24, 2020
    Posts:
    23
    You need to provide pass names (the Light Mode tag) to DrawRenderers.

    A simple example is that assuming there's a Light Mode tag named "UniversalForward1".

    URP won't render it by default, but you can use the DrawRenderers to draw all objects that have this pass (to any render target).
     
    ryanflees likes this.