Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

Question DXR Raytracing Effect from Scratch

Discussion in 'HDRP Ray Tracing' started by GeneralLee_, Dec 16, 2019.

  1. GeneralLee_

    GeneralLee_

    Joined:
    Dec 16, 2019
    Posts:
    4
    Hi,
    I am trying to simulate a simple lidar scanner with DXR. I am running this in a custom pass volume. The problem I have is that the closestHit shader never gets triggered. I am only getting misses. I am guessing my accelerationStructure is somehow messed up. Can somebody give me a hint what I am doing wrong? I am stuck on this for 3 hours now.
    To build the AS I just loop through some tagged objects and add their MeshRenderers. I then call build and pass the AS to the shader.

    Custom Pass Execute Function:

    Code (CSharp):
    1. protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera camera, CullingResults cullingResult)
    2.         {
    3.             if (scanner != null)
    4.             {
    5.                 if (EditorApplication.isPlaying)
    6.                 {          
    7.                     RayTracingAccelerationStructure accelerationStructure = new RayTracingAccelerationStructure();
    8.                     GameObject[] obstacles = GameObject.FindGameObjectsWithTag("ObstacleRaytraced");
    9.  
    10.                     foreach(GameObject obj in obstacles) {
    11.                         MeshRenderer ren = obj.GetComponent<MeshRenderer>();
    12.                         accelerationStructure.AddInstance(ren);
    13.                     }
    14.  
    15.                     //accelerationStructure.Update();
    16.                     accelerationStructure.Build();
    17.  
    18.                     //cmd.BuildRayTracingAccelerationStructure(accelerationStructure);
    19.                     cmd.SetRayTracingAccelerationStructure(shader, "_RaytracingAccelerationStructure", accelerationStructure);
    20.                     cmd.SetRayTracingShaderPass(shader, "LidarPass");
    21.  
    22.                     cmd.SetRayTracingTextureParam(shader, Shader.PropertyToID("RenderTarget"), m_renderTex);
    23.                     Vector4 position = scanner.RayOrigin.position;
    24.                     Vector4 dir  = scanner.RayOrigin.forward;
    25.  
    26.                     cmd.SetRayTracingVectorParam(shader, Shader.PropertyToID("originPos"), position);
    27.                     cmd.SetRayTracingVectorParam(shader, Shader.PropertyToID("originDir"), dir);
    28.  
    29.                     cmd.DispatchRays(shader, "MyRaygenShader", scanner.SamplesPerScan, 1, 1);
    30.  
    31.                     RenderTexture.active = m_renderTex;
    32.  
    33.                     m_resultTex.ReadPixels(new Rect(0, 0, scanner.SamplesPerScan, 1), 0, 0);
    34.                     var data = m_resultTex.GetPixels();
    35.  
    36.                     RenderTexture.active = null;
    37.                     if (debug)
    38.                     {
    39.                         //Debug.Log("Size: " + m_resultTex.width);
    40.                         for (int x = 0; x < m_resultTex.width; x++)
    41.                         {
    42.                             if (data[x] != new Color(0, 0, 0, 0))
    43.                                 Debug.Log(data[x]);
    44.                         }
    45.                     }
    46.                 }
    47.             }
    48.         }
    Raytrace Shader:

    Code (csharp):
    1. RWTexture2D<float4> RenderTarget;
    2. float4 originPos;
    3. float4 originDir;
    4.  
    5. #pragma max_recursion_depth 1
    6.  
    7. //Includes omitted
    8. //...
    9.  
    10. struct RayPayload { float4 color; uint2 launchIdx; float3 position;};
    11.  
    12. [shader("raygeneration")]
    13. void MyRaygenShader(){
    14.  
    15.     uint2 launchIdx = DispatchRaysIndex().xy;
    16.     //uint2 launchDim = DispatchRaysDimensions().xy;
    17.  
    18.     RayDesc ray;
    19.     ray.Origin = originPos;
    20.     ray.Direction = normalize(originDir);
    21.     ray.TMin = 0;  
    22.     ray.TMax = _RaytracingRayMaxLength;
    23.  
    24.     RayPayload payload;
    25.     payload.color = float4(0, 0, 0, 0);
    26.     payload.position = float3(0,0,0);
    27.     TraceRay(_RaytracingAccelerationStructure, RAY_FLAG_NONE, 0xFF, 0, 1, 0, ray, payload);
    28.     RenderTarget[launchIdx] = payload.color;
    29.  
    30. }
    31.  
    32. [shader("miss")]
    33. void Miss(inout RayPayload payload : SV_RayPayload){
    34.     //rayDirection = WorldRayDirection();
    35.     payload.color = float4(0,0,0,0);
    36. }
    37.  
    38.  
    39. [shader("closesthit")]
    40. void ClosestHit(inout RayPayload payload : SV_RayPayload, AttributeData attributeData : SV_IntersectionAttributes)
    41. {
    42.     payload.color= float4(1, 1, 1, 1);
    43. }
    44.  
    Thanks a lot for your help!
     
  2. GeneralLee_

    GeneralLee_

    Joined:
    Dec 16, 2019
    Posts:
    4
    Okay, small success: I managed to validate that my AS is correct. I can see that the Miss Shader does NOT get called when the ray intersects with geometry, but the closestHitShader does not get called either. The payload is unmodified in this case. Does the ClosestHitShader have to enabled somewhere? I can only see the flag to disable it, which I assume means its enabled by default...
     
  3. auzaiffe

    auzaiffe

    Unity Technologies

    Joined:
    Sep 4, 2018
    Posts:
    255
    @GeneralLee_ Yes, closest hit is enabled by default. The problem is probably because you are using _RaytracingRayMaxLength but never setting its value
     
  4. INedelcu

    INedelcu

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    173
    Acceleration structure build is a GPU operation meaning that it has to be done in the same command buffer where this is actually used. Could you try replacing accelerationStructure.Build(); with cmd.BuildRayTracingAccelerationStructure(accelerationStructure).

    ClosestHit shaders in the same raytrace file don't work currently. It needs to be a pass named "LidarPass" in your case in the actual *.shader file that your materials use.
     
  5. TheLazyEngineer

    TheLazyEngineer

    Joined:
    Jul 22, 2019
    Posts:
    12
    Is there any documentation that explains how to do what OP asked about? I am looking for similar information. It seems I am even unable to define a Miss shader in my .raytrace file underneath my Ray Generation shader. An example project that demonstrates how to include your own custom raygen shader, hit shader, anyhit shader, intersection shader, and miss shader would be incredibly helpful! I am working on a project where I need to use nonlinear raytracing where the ray follows a parametric curve, so I need explicit control over the raytracing process through these different shaders. Unfortunately, I have not found documentation that has helped me do this in Unity yet!

    Also, this presentation :

    https://on-demand.gputechconf.com/s...started-with-directx-ray-tracing-in-unity.pdf

    seems to have some conflicting info. Their closesthit shader does not use "LidarPass," so I'm confused on what info is up to date / valid and what isn't. I think this all can be cleared up with a simple demo project that implements these different shaders. I'd be happy to help put that demo project together with the help of this community.
     
  6. INedelcu

    INedelcu

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    173
    Hi, @TheLazyEngineer

    I attached a very simple project that I use for testing. In Game View it generates a ray tracing image. You can click on Play to make the teapot rotate and use WASD + hold right mouse button to navigate. Scene View doesn't look great because the shaders used in normal rendering don't do anything. I tested the project in Unity 2020.1.2f1.

    The scene should look like this:



    - ray tracing setup and execution is in RayTracingTest.cs.
    - check the main camera in the hierarchy where the script above is specified + the raytrace shader.
    - the raygeneration shader is in RayTracingTest.raytrace
    - there are different materials each with its own ray tracing shader.
    - there is also a procedural intersection material (using an intersection shader) - the red sphere.

    All the ray tracing shaders use a ShaderPass called Test. That name is specified in RayTracingTest.cs before ray tracing execution with SetShaderPass.

    Have fun!
     

    Attached Files:

  7. TheLazyEngineer

    TheLazyEngineer

    Joined:
    Jul 22, 2019
    Posts:
    12
    @INedelcu this is exactly what I had in mind. Thank you for sharing this, it will be very helpful to me and others.



    I have another question that I'd love to get your insights on:



    I want to implement a non linear ray tracing shader. Basically, I want to ray trace along a parametric curve. So, I want to generate a ray with a small fixed length (TMax - TMin is small), and incrementally advance the ray along the curve until the total distance traveled by the ray reaches some threshold. At each step, the ray must check for intersections, and if there is a Miss, then the ray should calculate its new origin and direction and try again. So, kind of like ray marching along a curve.


    I suppose I could implement this in an intersection shader where use the ray from the generation shader is used and updated in a loop, and checked for intersection at each iteration. However, I think this would mean I need to re-implement the optimized DX built in Triangle intersection routine because the intersection checks will now be in my own custom intersection shader which is now also responsible for curving the ray. I'd rather not do this because I want to use the optimized DX built in triangle intersection shader. Is this a callable shader? I could see this working if I am able to call the built in triangle intersection shader from my custom intersection shader at each iteration of the loop.


    I could also recursively call TraceRay() in a miss shader. The ray generation shader would produce a small ray, and if the miss shader is called, it will recast the next ray with the updated direction and origin. However, it looks like there is a recursion depth limit of 31, and I do not think it will be enough, so I don't think this will work.



    Maybe there's a more appropriate way of achieving this effect? Any ideas on the best way to proceed?



    Thanks!
     
  8. INedelcu

    INedelcu

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    173
    If I understood correctly what you are trying to achieve, I would suggest you to write this algorithm in the raygeneration shader. One benefit is that you can have as many iterations as you want. Do you wish to continue the curved ray after it intersects a geometry or it will stop?

    Using a for loop to trace along the curve would look like this (I didn't try this in Unity!!!)

    Code (CSharp):
    1. struct RayMarchPayload
    2. {
    3.      bool missed;
    4. };
    5.  
    6. [shader("miss")]
    7. void MissShader0(inout RayMarchPayload payload : SV_RayPayload)
    8. {
    9.     payload.missed = true;
    10. }
    11.  
    12. struct RayShadingPayload
    13. {
    14.      float3 color;
    15. };
    16.  
    17. void MissShader1(inout RayShadingPayload payload : SV_RayPayload)
    18. {
    19.     payload.color = float3(0, 0, 0);   // or some sky color.
    20. }
    21.  
    22. [shader("raygeneration")]
    23. void MainRayGenShader()
    24. {
    25.  
    26.     ...
    27.  
    28.     const uint steps = 128;
    29.  
    30.     RayDesc ray;
    31.     ray.TMin = 0;
    32.     ray.TMax = maxRayLength / steps;     // the incremental step along the curved ray.
    33.     ray.Origin = curvedRayOrigin;
    34.     // ray.Direction is computed inside the loop;
    35.    
    36.     RayMarchPayload payload;
    37.     payload.missed = false;
    38.  
    39.     // This loop detects which ray segment will intersect the geometry.
    40.     for (uint i = 1; i < steps; i++)
    41.     {
    42.           float t = (float)i / (float)(steps - 1);   // you can use this t in [0, 1] to evaluate the curve.
    43.  
    44.           float3 pointOnCurve = EvaluateCurve(..., t, ...)
    45.  
    46.           ray.Direction = normalize(pointOnCurve - ray.Origin);
    47.  
    48.           payload.missed = false;
    49.  
    50.           const uint missShaderIndex = 0;
    51.           TraceRay(g_SceneAccelStruct, RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH | RAY_FLAG_SKIP_CLOSEST_HIT_SHADER, 0xFF, 0, 1, missShaderIndex,  ray, payload);
    52.  
    53.          // if payload.missed is still false after TraceRay it means it actually hit some geometry inside the current segment. Note that MissShader0 is setting it to true.
    54.          if (payload.missed == false)
    55.               break;
    56.  
    57.           ray.Origin = pointOnCurve; // new origin for the next iteration;
    58.     }
    59.  
    60.     // Now you can use ray again in a new TraceRay to do the actual shading. If you wish to execute a closest hit shader then it will look like this:
    61.    if (payload.missed == false)
    62.    {
    63.            RayShadingPayload payloadShading;
    64.            payloadShading.color = float3(0, 0, 0);
    65.  
    66.            const uint missShaderIndex = 1;
    67.            TraceRay(g_SceneAccelStruct, 0, 0xFF, 0, 1, missShaderIndex,  ray, payloadShading);
    68.  
    69.            // write payloadShading.color to a texture
    70.    }  
    71. }
     
  9. TheLazyEngineer

    TheLazyEngineer

    Joined:
    Jul 22, 2019
    Posts:
    12
    @INedelcu , yes this will work. Thank you for the help.
     
    INedelcu likes this.
  10. INedelcu

    INedelcu

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    173
  11. INedelcu

    INedelcu

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    173
    vx4, chap-unity and m0nsky like this.
  12. vx4

    vx4

    Joined:
    Dec 11, 2012
    Posts:
    181
  13. INedelcu

    INedelcu

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    173
    Binding multiple RayTracingAccelerationStructures to the same DispatchRays command is not supported and will probably never be supported.
     
    vx4 likes this.
  14. Sunday14

    Sunday14

    Joined:
    Jun 7, 2018
    Posts:
    4
    hello, I have tried using Ray Tracing in built-in pipline, it works,but when I use TraceRay in closesthit shader, the unity crashed, I tried in many versions from 2019.4 to 2021,everytime I use the TraceRay func in closesthit shader, unity crashed, is this a bug?
     
  15. INedelcu

    INedelcu

    Unity Technologies

    Joined:
    Jul 14, 2015
    Posts:
    173
    Hi @Sunday14 !

    Unfortunately with ray tracing is very easy to make the GPU crash and Unity will crash with it.

    You can paste your closest hit shader here to have a look.

    You should be aware of a few important things when calling TraceRay in a closest hit shader. One is that you can't exceed the maximum recursion depth that is declared in the raytrace shader - #pragma max_recursion_depth 10. So your shader logic has to ensure that. In that example I use that payload.bounceIndex. You can use it. You also have to use exactly the same ray payload structure that the raytrace shader used (the primary TraceRay). If you already do these then it might be a bug and you can fill a bug report and attach your project to it.