TiledDeferredLighting.bsl 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #include "$ENGINE$\GBufferInput.bslinc"
  2. #include "$ENGINE$\PerCameraData.bslinc"
  3. #define USE_COMPUTE_INDICES
  4. #include "$ENGINE$\LightingCommon.bslinc"
  5. #include "$ENGINE$\ReflectionCubemapCommon.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. Pass =
  15. {
  16. Compute =
  17. {
  18. cbuffer Params : register(b0)
  19. {
  20. // Offsets at which specific light types begin in gLights buffer
  21. // Assumed directional lights start at 0
  22. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  23. uint3 gLightOffsets;
  24. uint2 gFramebufferSize;
  25. }
  26. #if MSAA_COUNT > 1
  27. RWBuffer<float4> gOutput : register(u0);
  28. uint getLinearAddress(uint2 coord, uint sampleIndex)
  29. {
  30. return (coord.y * gFramebufferSize.x + coord.x) * MSAA_COUNT + sampleIndex;
  31. }
  32. void writeBufferSample(uint2 coord, uint sampleIndex, float4 color)
  33. {
  34. uint idx = getLinearAddress(coord, sampleIndex);
  35. gOutput[idx] = color;
  36. }
  37. #else
  38. RWTexture2D<float4> gOutput : register(u0);
  39. #endif
  40. groupshared uint sTileMinZ;
  41. groupshared uint sTileMaxZ;
  42. groupshared uint sNumLightsPerType[2];
  43. groupshared uint sTotalNumLights;
  44. float4 getLighting(float2 clipSpacePos, SurfaceData surfaceData)
  45. {
  46. // x, y are now in clip space, z, w are in view space
  47. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  48. // z, w eliminated (since they are already in view space)
  49. // Note: Multiply by depth should be avoided if using ortographic projection
  50. float4 mixedSpacePos = float4(clipSpacePos * -surfaceData.depth, surfaceData.depth, 1);
  51. float4 worldPosition4D = mul(gMatScreenToWorld, mixedSpacePos);
  52. float3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  53. uint4 lightOffsets;
  54. lightOffsets.x = gLightOffsets[0];
  55. lightOffsets.y = 0;
  56. lightOffsets.z = sNumLightsPerType[0];
  57. lightOffsets.w = sTotalNumLights;
  58. float3 V = normalize(gViewOrigin - worldPosition);
  59. float3 N = surfaceData.worldNormal.xyz;
  60. float3 R = 2 * dot(V, N) * N - V;
  61. float3 specR = getSpecularDominantDir(N, R, surfaceData.roughness);
  62. return getDirectLighting(worldPosition, V, specR, surfaceData, lightOffsets);
  63. }
  64. [numthreads(TILE_SIZE, TILE_SIZE, 1)]
  65. void main(
  66. uint3 groupId : SV_GroupID,
  67. uint3 groupThreadId : SV_GroupThreadID,
  68. uint3 dispatchThreadId : SV_DispatchThreadID)
  69. {
  70. uint threadIndex = groupThreadId.y * TILE_SIZE + groupThreadId.x;
  71. uint2 pixelPos = dispatchThreadId.xy + gViewportRectangle.xy;
  72. // Note: To improve performance perhaps:
  73. // - Use halfZ (split depth range into two regions for better culling)
  74. // - Use parallel reduction instead of atomics
  75. // - Use AABB instead of frustum (no false positives)
  76. // - Increase tile size to 32x32 to amortize the cost of AABB calc (2x if using halfZ)
  77. // Get data for all samples, and determine per-pixel minimum and maximum depth values
  78. SurfaceData surfaceData[MSAA_COUNT];
  79. uint sampleMinZ = 0x7F7FFFFF;
  80. uint sampleMaxZ = 0;
  81. #if MSAA_COUNT > 1
  82. [unroll]
  83. for(uint i = 0; i < MSAA_COUNT; ++i)
  84. {
  85. surfaceData[i] = getGBufferData(pixelPos, i);
  86. sampleMinZ = min(sampleMinZ, asuint(-surfaceData[i].depth));
  87. sampleMaxZ = max(sampleMaxZ, asuint(-surfaceData[i].depth));
  88. }
  89. #else
  90. surfaceData[0] = getGBufferData(pixelPos);
  91. sampleMinZ = asuint(-surfaceData[0].depth);
  92. sampleMaxZ = asuint(-surfaceData[0].depth);
  93. #endif
  94. // Set initial values
  95. if(threadIndex == 0)
  96. {
  97. sTileMinZ = 0x7F7FFFFF;
  98. sTileMaxZ = 0;
  99. sNumLightsPerType[0] = 0;
  100. sNumLightsPerType[1] = 0;
  101. sTotalNumLights = 0;
  102. }
  103. GroupMemoryBarrierWithGroupSync();
  104. // Determine minimum and maximum depth values for a tile
  105. InterlockedMin(sTileMinZ, sampleMinZ);
  106. InterlockedMax(sTileMaxZ, sampleMaxZ);
  107. GroupMemoryBarrierWithGroupSync();
  108. float minTileZ = asfloat(sTileMinZ);
  109. float maxTileZ = asfloat(sTileMaxZ);
  110. // Create a frustum for the current tile
  111. // First determine a scale of the tile compared to the viewport
  112. float2 tileScale = gViewportRectangle.zw * rcp(float2(TILE_SIZE, TILE_SIZE));
  113. // Now we need to use that scale to scale down the frustum.
  114. // Assume a projection matrix:
  115. // A, 0, C, 0
  116. // 0, B, D, 0
  117. // 0, 0, Q, QN
  118. // 0, 0, -1, 0
  119. //
  120. // Where A is = 2*n / (r - l)
  121. // and C = (r + l) / (r - l)
  122. //
  123. // Q & QN are used for Z value which we don't need to scale. B & D are equivalent for the
  124. // Y value, we'll only consider the X values (A & C) from now on.
  125. //
  126. // Both and A and C are inversely proportional to the size of the frustum (r - l). Larger scale mean that
  127. // tiles are that much smaller than the viewport. This means as our scale increases, (r - l) decreases,
  128. // which means A & C as a whole increase. Therefore:
  129. // A' = A * tileScale.x
  130. // C' = C * tileScale.x
  131. // Aside from scaling, we also need to offset the frustum to the center of the tile.
  132. // For this we calculate the bias value which we add to the C & D factors (which control
  133. // the offset in the projection matrix).
  134. float2 tileBias = tileScale - 1 - groupId.xy * 2;
  135. // This will yield a bias ranging from [-(tileScale - 1), tileScale - 1]. Every second bias is skipped as
  136. // corresponds to a point in-between two tiles, overlapping existing frustums.
  137. float flipSign = 1.0f;
  138. // Adjust for OpenGL's upside down texture system
  139. #if OPENGL
  140. flipSign = -1;
  141. #endif
  142. float At = gMatProj[0][0] * tileScale.x;
  143. float Ctt = gMatProj[0][2] * tileScale.x - tileBias.x;
  144. float Bt = gMatProj[1][1] * tileScale.y * flipSign;
  145. float Dtt = (gMatProj[1][2] * tileScale.y + flipSign * tileBias.y) * flipSign;
  146. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  147. // Note: Do this on the CPU? Since they're shared among all entries in a tile. Plus they don't change across frames.
  148. float4 frustumPlanes[6];
  149. frustumPlanes[0] = float4(At, 0.0f, gMatProj[3][2] + Ctt, 0.0f);
  150. frustumPlanes[1] = float4(-At, 0.0f, gMatProj[3][2] - Ctt, 0.0f);
  151. frustumPlanes[2] = float4(0.0f, -Bt, gMatProj[3][2] - Dtt, 0.0f);
  152. frustumPlanes[3] = float4(0.0f, Bt, gMatProj[3][2] + Dtt, 0.0f);
  153. // Normalize
  154. [unroll]
  155. for (uint i = 0; i < 4; ++i)
  156. frustumPlanes[i] *= rcp(length(frustumPlanes[i].xyz));
  157. // Generate near/far frustum planes
  158. // Note: d gets negated in plane equation, this is why its in opposite direction than it intuitively should be
  159. frustumPlanes[4] = float4(0.0f, 0.0f, -1.0f, -minTileZ);
  160. frustumPlanes[5] = float4(0.0f, 0.0f, 1.0f, maxTileZ);
  161. // Find radial & spot lights overlapping the tile
  162. for(uint type = 0; type < 2; type++)
  163. {
  164. uint lightOffset = threadIndex + gLightOffsets[type];
  165. uint lightsEnd = gLightOffsets[type + 1];
  166. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  167. {
  168. float4 lightPosition = mul(gMatView, float4(gLights[i].position, 1.0f));
  169. float lightRadius = gLights[i].attRadius;
  170. // Note: The cull method can have false positives. In case of large light bounds and small tiles, it
  171. // can end up being quite a lot. Consider adding an extra heuristic to check a separating plane.
  172. bool lightInTile = true;
  173. // First check side planes as this will cull majority of the lights
  174. [unroll]
  175. for (uint j = 0; j < 4; ++j)
  176. {
  177. float dist = dot(frustumPlanes[j], lightPosition);
  178. lightInTile = lightInTile && (dist >= -lightRadius);
  179. }
  180. // Make sure to do an actual branch, since it's quite likely an entire warp will have the same value
  181. [branch]
  182. if (lightInTile)
  183. {
  184. bool inDepthRange = true;
  185. // Check near/far planes
  186. [unroll]
  187. for (uint j = 4; j < 6; ++j)
  188. {
  189. float dist = dot(frustumPlanes[j], lightPosition);
  190. inDepthRange = inDepthRange && (dist >= -lightRadius);
  191. }
  192. // In tile, add to branch
  193. [branch]
  194. if (inDepthRange)
  195. {
  196. InterlockedAdd(sNumLightsPerType[type], 1U);
  197. uint idx;
  198. InterlockedAdd(sTotalNumLights, 1U, idx);
  199. gLightIndices[idx] = i;
  200. }
  201. }
  202. }
  203. }
  204. GroupMemoryBarrierWithGroupSync();
  205. // Generate world position
  206. float2 screenUv = ((float2)(gViewportRectangle.xy + pixelPos) + 0.5f) / (float2)gViewportRectangle.zw;
  207. float2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  208. uint2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  209. // Ignore pixels out of valid range
  210. if (all(dispatchThreadId.xy < viewportMax))
  211. {
  212. #if MSAA_COUNT > 1
  213. float4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  214. writeBufferSample(pixelPos, 0, lighting);
  215. bool doPerSampleShading = needsPerSampleShading(surfaceData);
  216. if(doPerSampleShading)
  217. {
  218. [unroll]
  219. for(uint i = 1; i < MSAA_COUNT; ++i)
  220. {
  221. lighting = getLighting(clipSpacePos.xy, surfaceData[i]);
  222. writeBufferSample(pixelPos, i, lighting);
  223. }
  224. }
  225. else // Splat same information to all samples
  226. {
  227. [unroll]
  228. for(uint i = 1; i < MSAA_COUNT; ++i)
  229. writeBufferSample(pixelPos, i, lighting);
  230. }
  231. #else
  232. float4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  233. gOutput[pixelPos] = lighting;
  234. #endif
  235. }
  236. }
  237. };
  238. };
  239. };