TiledDeferredImageBasedLighting.bsl 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #include "$ENGINE$\GBufferInput.bslinc"
  2. #include "$ENGINE$\PerCameraData.bslinc"
  3. #include "$ENGINE$\ReflectionCubemapCommon.bslinc"
  4. #define USE_COMPUTE_INDICES 1
  5. #include "$ENGINE$\LightingCommon.bslinc"
  6. #include "$ENGINE$\ImageBasedLighting.bslinc"
  7. technique TiledDeferredImageBasedLighting
  8. {
  9. mixin GBufferInput;
  10. mixin PerCameraData;
  11. mixin LightingCommon;
  12. mixin ReflectionCubemapCommon;
  13. mixin ImageBasedLighting;
  14. code
  15. {
  16. [internal]
  17. cbuffer Params : register(b0)
  18. {
  19. uint2 gFramebufferSize;
  20. }
  21. #if MSAA_COUNT > 1
  22. Texture2DMS<float4> gInColor;
  23. RWBuffer<float4> gOutput;
  24. uint getLinearAddress(uint2 coord, uint sampleIndex)
  25. {
  26. return (coord.y * gFramebufferSize.x + coord.x) * MSAA_COUNT + sampleIndex;
  27. }
  28. void writeBufferSample(uint2 coord, uint sampleIndex, float4 color)
  29. {
  30. uint idx = getLinearAddress(coord, sampleIndex);
  31. gOutput[idx] = color;
  32. }
  33. #else
  34. Texture2D<float4> gInColor;
  35. RWTexture2D<float4> gOutput;
  36. #endif
  37. groupshared uint sTileMinZ;
  38. groupshared uint sTileMaxZ;
  39. void getTileZBounds(uint threadIndex, SurfaceData surfaceData[MSAA_COUNT], out float minTileZ, out float maxTileZ)
  40. {
  41. // Note: To improve performance perhaps:
  42. // - Use halfZ (split depth range into two regions for better culling)
  43. // - Use parallel reduction instead of atomics
  44. uint sampleMinZ = 0x7F7FFFFF;
  45. uint sampleMaxZ = 0;
  46. #if MSAA_COUNT > 1
  47. [unroll]
  48. for(uint i = 0; i < MSAA_COUNT; ++i)
  49. {
  50. sampleMinZ = min(sampleMinZ, asuint(-surfaceData[i].depth));
  51. sampleMaxZ = max(sampleMaxZ, asuint(-surfaceData[i].depth));
  52. }
  53. #else
  54. sampleMinZ = asuint(-surfaceData[0].depth);
  55. sampleMaxZ = asuint(-surfaceData[0].depth);
  56. #endif
  57. // Set initial values
  58. if(threadIndex == 0)
  59. {
  60. sTileMinZ = 0x7F7FFFFF;
  61. sTileMaxZ = 0;
  62. }
  63. GroupMemoryBarrierWithGroupSync();
  64. // Determine minimum and maximum depth values for a tile
  65. InterlockedMin(sTileMinZ, sampleMinZ);
  66. InterlockedMax(sTileMaxZ, sampleMaxZ);
  67. GroupMemoryBarrierWithGroupSync();
  68. minTileZ = asfloat(sTileMinZ);
  69. maxTileZ = asfloat(sTileMaxZ);
  70. }
  71. void calcTileAABB(uint2 tileId, float viewZMin, float viewZMax, out float3 center, out float3 extent)
  72. {
  73. uint2 pixelPos = tileId * TILE_SIZE;
  74. // Convert threat XY coordinates to NDC coordinates
  75. float2 uvTopLeft = (pixelPos + 0.5f) / gFramebufferSize;
  76. float2 uvBottomRight = (pixelPos + uint2(TILE_SIZE, TILE_SIZE) - 0.5f) / gFramebufferSize;
  77. float3 ndcMin;
  78. float3 ndcMax;
  79. ndcMin.xy = uvTopLeft * 2.0f - float2(1.0f, 1.0f);
  80. ndcMax.xy = uvBottomRight * 2.0f - float2(1.0f, 1.0f);
  81. // Flip Y depending on render API, depending if Y in NDC is facing up or down
  82. // (We negate the value because we want NDC with Y flipped, so origin is top left)
  83. float flipY = -sign(gMatProj[1][1]);
  84. ndcMin.y *= flipY;
  85. ndcMax.y *= flipY;
  86. // Camera is looking along negative z, therefore min in view space is max in NDC
  87. ndcMin.z = convertToNDCZ(viewZMax);
  88. ndcMax.z = convertToNDCZ(viewZMin);
  89. float4 corner[5];
  90. // Far
  91. corner[0] = mul(gMatInvProj, float4(ndcMin.x, ndcMin.y, ndcMax.z, 1.0f));
  92. corner[1] = mul(gMatInvProj, float4(ndcMax.x, ndcMin.y, ndcMax.z, 1.0f));
  93. corner[2] = mul(gMatInvProj, float4(ndcMax.x, ndcMax.y, ndcMax.z, 1.0f));
  94. corner[3] = mul(gMatInvProj, float4(ndcMin.x, ndcMax.y, ndcMax.z, 1.0f));
  95. // Near (only one point, as the far away face is guaranteed to be larger in XY extents)
  96. corner[4] = mul(gMatInvProj, float4(ndcMin.x, ndcMin.y, ndcMin.z, 1.0f));
  97. [unroll]
  98. for(uint i = 0; i < 5; ++i)
  99. corner[i].xy /= corner[i].w;
  100. float3 viewMin = float3(corner[0].xy, viewZMin);
  101. float3 viewMax = float3(corner[0].xy, viewZMax);
  102. [unroll]
  103. for(uint i = 1; i < 4; ++i)
  104. {
  105. viewMin.xy = min(viewMin.xy, corner[i].xy);
  106. viewMax.xy = max(viewMax.xy, corner[i].xy);
  107. }
  108. extent = (viewMax - viewMin) * 0.5f;
  109. center = viewMin + extent;
  110. }
  111. bool intersectSphereBox(float3 sCenter, float sRadius, float3 bCenter, float3 bExtents)
  112. {
  113. float3 closestOnBox = max(0, abs(bCenter - sCenter) - bExtents);
  114. return dot(closestOnBox, closestOnBox) < sRadius * sRadius;
  115. }
  116. float4 getLighting(uint2 pixelPos, uint sampleIdx, float2 clipSpacePos, SurfaceData surfaceData, uint probeOffset, uint numProbes)
  117. {
  118. // x, y are now in clip space, z, w are in view space
  119. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  120. // z, w eliminated (since they are already in view space)
  121. // Note: Multiply by depth should be avoided if using ortographic projection
  122. float4 mixedSpacePos = float4(clipSpacePos * -surfaceData.depth, surfaceData.depth, 1);
  123. float4 worldPosition4D = mul(gMatScreenToWorld, mixedSpacePos);
  124. float3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  125. float3 V = normalize(gViewOrigin - worldPosition);
  126. float3 N = surfaceData.worldNormal.xyz;
  127. float3 R = 2 * dot(V, N) * N - V;
  128. float3 specR = getSpecularDominantDir(N, R, surfaceData.roughness);
  129. float4 existingColor;
  130. #if MSAA_COUNT > 1
  131. existingColor = gInColor.Load(pixelPos.xy, sampleIdx);
  132. #else
  133. existingColor = gInColor.Load(int3(pixelPos.xy, 0));
  134. #endif
  135. float3 imageBasedSpecular = getImageBasedSpecular(worldPosition, V, specR, surfaceData, probeOffset, numProbes);
  136. float4 totalLighting = existingColor;
  137. totalLighting.rgb += imageBasedSpecular;
  138. return totalLighting;
  139. }
  140. groupshared uint gUnsortedProbeIndices[MAX_PROBES];
  141. groupshared uint sNumProbes;
  142. [numthreads(TILE_SIZE, TILE_SIZE, 1)]
  143. void csmain(
  144. uint3 groupId : SV_GroupID,
  145. uint3 groupThreadId : SV_GroupThreadID,
  146. uint3 dispatchThreadId : SV_DispatchThreadID)
  147. {
  148. uint threadIndex = groupThreadId.y * TILE_SIZE + groupThreadId.x;
  149. uint2 pixelPos = dispatchThreadId.xy + gViewportRectangle.xy;
  150. // Get data for all samples
  151. SurfaceData surfaceData[MSAA_COUNT];
  152. #if MSAA_COUNT > 1
  153. [unroll]
  154. for(uint i = 0; i < MSAA_COUNT; ++i)
  155. surfaceData[i] = getGBufferData(pixelPos, i);
  156. #else
  157. surfaceData[0] = getGBufferData(pixelPos);
  158. #endif
  159. // Set initial values
  160. if(threadIndex == 0)
  161. sNumProbes = 0;
  162. // Determine per-pixel minimum and maximum depth values
  163. float minTileZ, maxTileZ;
  164. getTileZBounds(threadIndex, surfaceData, minTileZ, maxTileZ);
  165. // Create AABB for the current tile
  166. float3 center, extent;
  167. calcTileAABB(groupId.xy, minTileZ, maxTileZ, center, extent);
  168. // Find probes overlapping the tile
  169. for (uint i = 0; i < gNumProbes && i < MAX_LIGHTS; i += TILE_SIZE)
  170. {
  171. float4 probePosition = mul(gMatView, float4(gReflectionProbes[i].position, 1.0f));
  172. float probeRadius = gReflectionProbes[i].radius;
  173. if(intersectSphereBox(probePosition, probeRadius, center, extent))
  174. {
  175. uint idx;
  176. InterlockedAdd(sNumProbes, 1U, idx);
  177. gUnsortedProbeIndices[idx] = i;
  178. }
  179. }
  180. GroupMemoryBarrierWithGroupSync();
  181. // Sort based on original indices. Using parallel enumeration sort (n^2) - could be faster
  182. const uint numThreads = TILE_SIZE * TILE_SIZE;
  183. for (uint i = threadIndex; i < sNumProbes; i += numThreads)
  184. {
  185. int idx = gUnsortedProbeIndices[i];
  186. uint smallerCount = 0;
  187. for (uint j = 0; j < sNumProbes; j++)
  188. {
  189. int otherIdx = gUnsortedProbeIndices[j];
  190. if (otherIdx < idx)
  191. smallerCount++;
  192. }
  193. gReflectionProbeIndices[smallerCount] = gUnsortedProbeIndices[i];
  194. }
  195. GroupMemoryBarrierWithGroupSync();
  196. // Generate world position
  197. float2 screenUv = ((float2)(gViewportRectangle.xy + pixelPos) + 0.5f) / (float2)gViewportRectangle.zw;
  198. float2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  199. uint2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  200. // Ignore pixels out of valid range
  201. if (all(dispatchThreadId.xy < viewportMax))
  202. {
  203. #if MSAA_COUNT > 1
  204. float4 lighting = getLighting(pixelPos, 0, clipSpacePos.xy, surfaceData[0], 0, gNumProbes);
  205. writeBufferSample(pixelPos, 0, lighting);
  206. bool doPerSampleShading = needsPerSampleShading(surfaceData);
  207. if(doPerSampleShading)
  208. {
  209. [unroll]
  210. for(uint i = 1; i < MSAA_COUNT; ++i)
  211. {
  212. lighting = getLighting(pixelPos, i, clipSpacePos.xy, surfaceData[i], 0, gNumProbes);
  213. writeBufferSample(pixelPos, i, lighting);
  214. }
  215. }
  216. else // Splat same information to all samples
  217. {
  218. [unroll]
  219. for(uint i = 1; i < MSAA_COUNT; ++i)
  220. writeBufferSample(pixelPos, i, lighting);
  221. }
  222. #else
  223. float4 lighting = getLighting(pixelPos, 0, clipSpacePos.xy, surfaceData[0], 0, gNumProbes);
  224. gOutput[pixelPos] = lighting;
  225. #endif
  226. }
  227. }
  228. };
  229. };