2
0

TiledDeferredImageBasedLighting.bsl 9.6 KB

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