TiledDeferredImageBasedLighting.bsl 9.2 KB

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