CustomRayGen.hlsl 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "Common.hlsl"
  2. [shader("raygeneration")]
  3. void RayGen()
  4. {
  5. // Initialize the ray payload
  6. RayHits rayPayload;
  7. rayPayload.hitCount = 0;
  8. SingleHit hitInitial;
  9. hitInitial.color = float4(0, 0, 0, 0);
  10. hitInitial.normal = float3(0, 0, 0);
  11. hitInitial.distance = 0.f;
  12. hitInitial.dayLight = 0;
  13. hitInitial.dynamicLight = 0;
  14. for (int index = 0; index < MAX_TRANSPACENT_HITS; index++)
  15. {
  16. rayPayload.hits[index] = hitInitial;
  17. }
  18. float3 color = float3(0, 0, 0);
  19. // Get the location within the dispatched 2D grid of work items
  20. // (often maps to pixels, so this could represent a pixel coordinate).
  21. float2 dispatchDimensions = float2(DispatchRaysDimensions().xy);
  22. uint2 dispatchIndex = DispatchRaysIndex().xy;
  23. float2 dispatchPercentage = (dispatchIndex + 0.5) / dispatchDimensions;
  24. if (useRays)
  25. {
  26. float2 d = (dispatchPercentage * 2.f - 1.f);
  27. RayDesc ray;
  28. ray.Origin = mul(inverseView, float4(0, 0, 0, 1)).xyz;
  29. float4 target = mul(inverseProjection, float4(d.x, -d.y, -1, 1));
  30. target.w = 1;
  31. ray.Direction = mul(inverseView, target).xyz - ray.Origin;
  32. ray.TMin = minDistance;
  33. ray.TMax = maxDistance;
  34. TraceRay(TLAS, /*RayFlags*/0, /*InstanceInclusionMask*/0xFF, /*RayContributionToHitGroupIndex*/0,
  35. /*MultiplierForGeometryContributionToHitGroupIndex*/0, /*MissShaderIndex*/0, ray, rayPayload);
  36. if (rayPayload.hitCount > 0)
  37. {
  38. float3 minLight = float3(0.1f, 0.1f, 0.1f);
  39. SingleHit lastHit = rayPayload.hits[rayPayload.hitCount - 1];
  40. float3 dayLight = unpackLight(lastHit.dayLight);
  41. float3 dynamicLight = unpackLight(lastHit.dynamicLight);
  42. float3 light = max(minLight, max(dynamicLight, dayLight));
  43. color = lastHit.color.rgb * light;
  44. for (int i = rayPayload.hitCount - 2; i >= 0; i--)
  45. {
  46. SingleHit currentHit = rayPayload.hits[i];
  47. dayLight = unpackLight(currentHit.dayLight);
  48. dynamicLight = unpackLight(currentHit.dynamicLight);
  49. light = max(minLight, max(dynamicLight, dayLight));
  50. color = currentHit.color.rgb * light * currentHit.color.a + color * (1 - currentHit.color.a);
  51. }
  52. }
  53. }
  54. uint outWidth, outHeight;
  55. gOutput.GetDimensions(outWidth, outHeight);
  56. uint2 outputIndex = uint2(dispatchPercentage * float2(outWidth, outHeight));
  57. if (renderGui)
  58. {
  59. uint guiWidth, guiHeight;
  60. guiTexture.GetDimensions(guiWidth, guiHeight);
  61. uint2 guiIndex = uint2(dispatchPercentage * float2(guiWidth, guiHeight));
  62. float4 guiColor = guiTexture[guiIndex];
  63. color = color * (1 - guiColor.a) + guiColor.rgb * guiColor.a;
  64. }
  65. gOutput[outputIndex] = float4(color, 1.f);
  66. }