2
0

TiledDeferredLighting.bsl 10.0 KB

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