TiledDeferredLighting.bsl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. #include "$ENGINE$\GBuffer.bslinc"
  2. #include "$ENGINE$\PerCameraData.bslinc"
  3. #define USE_COMPUTE_INDICES
  4. #include "$ENGINE$\LightingCommon.bslinc"
  5. #include "$ENGINE$\ReflectionCubemapCommon.bslinc"
  6. #include "$ENGINE$\ReflectionCubemapSampling.bslinc"
  7. Parameters =
  8. {
  9. Sampler2D gGBufferASamp : alias("gGBufferATex");
  10. Sampler2D gGBufferBSamp : alias("gGBufferBTex");
  11. Sampler2D gGBufferCSamp : alias("gGBufferCTex");
  12. Sampler2D gDepthBufferSamp : alias("gDepthBufferTex");
  13. Texture2D gGBufferATex : auto("GBufferA");
  14. Texture2D gGBufferBTex : auto("GBufferB");
  15. Texture2D gGBufferCTex : auto("GBufferC");
  16. Texture2D gDepthBufferTex : auto("GBufferDepth");
  17. };
  18. Blocks =
  19. {
  20. Block PerCamera : auto("PerCamera");
  21. };
  22. Technique
  23. : inherits("GBuffer")
  24. : inherits("PerCameraData")
  25. : inherits("LightingCommon")
  26. : inherits("ReflectionCubemapCommon")
  27. : inherits("ReflectionCubemapSampling") =
  28. {
  29. Language = "HLSL11";
  30. Pass =
  31. {
  32. Compute =
  33. {
  34. SamplerState gGBufferASamp : register(s0);
  35. SamplerState gGBufferBSamp : register(s1);
  36. SamplerState gGBufferCSamp : register(s2);
  37. SamplerState gDepthBufferSamp : register(s3);
  38. #if MSAA_COUNT > 1
  39. Texture2DMS<float4, MSAA_COUNT> gGBufferATex : register(t0);
  40. Texture2DMS<float4, MSAA_COUNT> gGBufferBTex : register(t1);
  41. Texture2DMS<float2, MSAA_COUNT> gGBufferCTex : register(t2);
  42. Texture2DMS<float4, MSAA_COUNT> gDepthBufferTex : register(t3);
  43. #else
  44. Texture2D gGBufferATex : register(t0);
  45. Texture2D gGBufferBTex : register(t1);
  46. Texture2D gGBufferCTex : register(t2);
  47. Texture2D gDepthBufferTex : register(t3);
  48. #endif
  49. SurfaceData decodeGBuffer(float4 GBufferAData, float4 GBufferBData, float2 GBufferCData, float deviceZ)
  50. {
  51. SurfaceData output;
  52. output.albedo.xyz = GBufferAData.xyz;
  53. output.albedo.w = 1.0f;
  54. output.worldNormal = GBufferBData * float4(2, 2, 2, 1) - float4(1, 1, 1, 0);
  55. output.worldNormal.xyz = normalize(output.worldNormal.xyz);
  56. output.depth = convertFromDeviceZ(deviceZ);
  57. output.roughness = GBufferCData.x;
  58. output.metalness = GBufferCData.y;
  59. return output;
  60. }
  61. cbuffer Params : register(b0)
  62. {
  63. // Offsets at which specific light types begin in gLights buffer
  64. // Assumed directional lights start at 0
  65. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  66. uint3 gLightOffsets;
  67. uint2 gFramebufferSize;
  68. }
  69. #if MSAA_COUNT > 1
  70. RWBuffer<float4> gOutput : register(u0);
  71. uint getLinearAddress(uint2 coord, uint sampleIndex)
  72. {
  73. return (coord.y * gFramebufferSize.x + coord.x) * MSAA_COUNT + sampleIndex;
  74. }
  75. void writeBufferSample(uint2 coord, uint sampleIndex, float4 color)
  76. {
  77. uint idx = getLinearAddress(coord, sampleIndex);
  78. gOutput[idx] = color;
  79. }
  80. bool needsPerSampleShading(SurfaceData samples[MSAA_COUNT])
  81. {
  82. float3 albedo = samples[0].albedo.xyz;
  83. float3 normal = samples[0].worldNormal.xyz;
  84. float depth = samples[0].depth;
  85. [unroll]
  86. for(int i = 1; i < MSAA_COUNT; i++)
  87. {
  88. float3 otherAlbedo = samples[i].albedo.xyz;
  89. float3 otherNormal = samples[i].worldNormal.xyz;
  90. float otherDepth = samples[i].depth;
  91. [branch]
  92. if(abs(depth - otherDepth) > 0.1f || abs(dot(abs(normal - otherNormal), float3(1, 1, 1))) > 0.1f || abs(dot(albedo - otherAlbedo, float3(1, 1, 1))) > 0.1f)
  93. {
  94. return true;
  95. }
  96. }
  97. return false;
  98. }
  99. SurfaceData getGBufferData(uint2 pixelPos, uint sampleIndex)
  100. {
  101. float4 GBufferAData = gGBufferATex.Load(pixelPos, sampleIndex);
  102. float4 GBufferBData = gGBufferBTex.Load(pixelPos, sampleIndex);
  103. float2 GBufferCData = gGBufferCTex.Load(pixelPos, sampleIndex).rg;
  104. float deviceZ = gDepthBufferTex.Load(pixelPos, sampleIndex).r;
  105. return decodeGBuffer(GBufferAData, GBufferBData, GBufferCData, deviceZ);
  106. }
  107. #else
  108. RWTexture2D<float4> gOutput : register(u0);
  109. SurfaceData getGBufferData(uint2 pixelPos)
  110. {
  111. float4 GBufferAData = gGBufferATex.Load(int3(pixelPos, 0));
  112. float4 GBufferBData = gGBufferBTex.Load(int3(pixelPos, 0));
  113. float2 GBufferCData = gGBufferCTex.Load(int3(pixelPos, 0)).rg;
  114. float deviceZ = gDepthBufferTex.Load(int3(pixelPos, 0)).r;
  115. return decodeGBuffer(GBufferAData, GBufferBData, GBufferCData, deviceZ);
  116. }
  117. #endif
  118. groupshared uint sTileMinZ;
  119. groupshared uint sTileMaxZ;
  120. groupshared uint sNumLightsPerType[2];
  121. groupshared uint sTotalNumLights;
  122. float4 getLighting(float2 clipSpacePos, SurfaceData surfaceData)
  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. uint4 lightOffsets;
  132. lightOffsets.x = gLightOffsets[0];
  133. lightOffsets.y = 0;
  134. lightOffsets.z = sNumLightsPerType[0];
  135. lightOffsets.w = sTotalNumLights;
  136. float4 directLighting = getDirectLighting(worldPosition, surfaceData, lightOffsets);
  137. float3 imageBasedSpecular = getImageBasedSpecular(worldPosition, gViewDir, surfaceData);
  138. float4 totalLighting = directLighting;
  139. totalLighting.rgb += imageBasedSpecular;
  140. return totalLighting;
  141. }
  142. [numthreads(TILE_SIZE, TILE_SIZE, 1)]
  143. void main(
  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, and determine per-pixel minimum and maximum depth values
  151. SurfaceData surfaceData[MSAA_COUNT];
  152. uint sampleMinZ = 0x7F7FFFFF;
  153. uint sampleMaxZ = 0;
  154. #if MSAA_COUNT > 1
  155. [unroll]
  156. for(uint i = 0; i < MSAA_COUNT; ++i)
  157. {
  158. surfaceData[i] = getGBufferData(pixelPos, i);
  159. sampleMinZ = min(sampleMinZ, asuint(-surfaceData[i].depth));
  160. sampleMaxZ = max(sampleMaxZ, asuint(-surfaceData[i].depth));
  161. }
  162. #else
  163. surfaceData[0] = getGBufferData(pixelPos);
  164. sampleMinZ = asuint(-surfaceData[0].depth);
  165. sampleMaxZ = asuint(-surfaceData[0].depth);
  166. #endif
  167. // Set initial values
  168. if(threadIndex == 0)
  169. {
  170. sTileMinZ = 0x7F7FFFFF;
  171. sTileMaxZ = 0;
  172. sNumLightsPerType[0] = 0;
  173. sNumLightsPerType[1] = 0;
  174. sTotalNumLights = 0;
  175. }
  176. GroupMemoryBarrierWithGroupSync();
  177. // Determine minimum and maximum depth values for a tile
  178. InterlockedMin(sTileMinZ, sampleMinZ);
  179. InterlockedMax(sTileMaxZ, sampleMaxZ);
  180. GroupMemoryBarrierWithGroupSync();
  181. float minTileZ = asfloat(sTileMinZ);
  182. float maxTileZ = asfloat(sTileMaxZ);
  183. // Create a frustum for the current tile
  184. // First determine a scale of the tile compared to the viewport
  185. float2 tileScale = gViewportRectangle.zw * rcp(float2(TILE_SIZE, TILE_SIZE));
  186. // Now we need to use that scale to scale down the frustum.
  187. // Assume a projection matrix:
  188. // A, 0, C, 0
  189. // 0, B, D, 0
  190. // 0, 0, Q, QN
  191. // 0, 0, -1, 0
  192. //
  193. // Where A is = 2*n / (r - l)
  194. // and C = (r + l) / (r - l)
  195. //
  196. // Q & QN are used for Z value which we don't need to scale. B & D are equivalent for the
  197. // Y value, we'll only consider the X values (A & C) from now on.
  198. //
  199. // Both and A and C are inversely proportional to the size of the frustum (r - l). Larger scale mean that
  200. // tiles are that much smaller than the viewport. This means as our scale increases, (r - l) decreases,
  201. // which means A & C as a whole increase. Therefore:
  202. // A' = A * tileScale.x
  203. // C' = C * tileScale.x
  204. // Aside from scaling, we also need to offset the frustum to the center of the tile.
  205. // For this we calculate the bias value which we add to the C & D factors (which control
  206. // the offset in the projection matrix).
  207. float2 tileBias = tileScale - 1 - groupId.xy * 2;
  208. // This will yield a bias ranging from [-(tileScale - 1), tileScale - 1]. Every second bias is skipped as
  209. // corresponds to a point in-between two tiles, overlapping existing frustums.
  210. float At = gMatProj[0][0] * tileScale.x;
  211. float Ctt = gMatProj[0][2] * tileScale.x - tileBias.x;
  212. float Bt = gMatProj[1][1] * tileScale.y;
  213. float Dtt = gMatProj[1][2] * tileScale.y + tileBias.y;
  214. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  215. // Note: Do this on the CPU? Since they're shared among all entries in a tile. Plus they don't change across frames.
  216. float4 frustumPlanes[6];
  217. frustumPlanes[0] = float4(At, 0.0f, gMatProj[3][2] + Ctt, 0.0f);
  218. frustumPlanes[1] = float4(-At, 0.0f, gMatProj[3][2] - Ctt, 0.0f);
  219. frustumPlanes[2] = float4(0.0f, -Bt, gMatProj[3][2] - Dtt, 0.0f);
  220. frustumPlanes[3] = float4(0.0f, Bt, gMatProj[3][2] + Dtt, 0.0f);
  221. // Normalize
  222. [unroll]
  223. for (uint i = 0; i < 4; ++i)
  224. frustumPlanes[i] *= rcp(length(frustumPlanes[i].xyz));
  225. // Generate near/far frustum planes
  226. // Note: d gets negated in plane equation, this is why its in opposite direction than it intuitively should be
  227. frustumPlanes[4] = float4(0.0f, 0.0f, -1.0f, -minTileZ);
  228. frustumPlanes[5] = float4(0.0f, 0.0f, 1.0f, maxTileZ);
  229. // Find radial & spot lights overlapping the tile
  230. for(uint type = 0; type < 2; type++)
  231. {
  232. uint lightOffset = threadIndex + gLightOffsets[type];
  233. uint lightsEnd = gLightOffsets[type + 1];
  234. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  235. {
  236. float4 lightPosition = mul(gMatView, float4(gLights[i].position, 1.0f));
  237. float lightRadius = gLights[i].radius;
  238. // Note: The cull method can have false positives. In case of large light bounds and small tiles, it
  239. // can end up being quite a lot. Consider adding an extra heuristic to check a separating plane.
  240. bool lightInTile = true;
  241. // First check side planes as this will cull majority of the lights
  242. [unroll]
  243. for (uint j = 0; j < 4; ++j)
  244. {
  245. float dist = dot(frustumPlanes[j], lightPosition);
  246. lightInTile = lightInTile && (dist >= -lightRadius);
  247. }
  248. // Make sure to do an actual branch, since it's quite likely an entire warp will have the same value
  249. [branch]
  250. if (lightInTile)
  251. {
  252. bool inDepthRange = true;
  253. // Check near/far planes
  254. [unroll]
  255. for (uint j = 4; j < 6; ++j)
  256. {
  257. float dist = dot(frustumPlanes[j], lightPosition);
  258. inDepthRange = inDepthRange && (dist >= -lightRadius);
  259. }
  260. // In tile, add to branch
  261. [branch]
  262. if (inDepthRange)
  263. {
  264. InterlockedAdd(sNumLightsPerType[type], 1U);
  265. uint idx;
  266. InterlockedAdd(sTotalNumLights, 1U, idx);
  267. gLightIndices[idx] = i;
  268. }
  269. }
  270. }
  271. }
  272. GroupMemoryBarrierWithGroupSync();
  273. // Generate world position
  274. float2 screenUv = ((float2)(gViewportRectangle.xy + pixelPos) + 0.5f) / (float2)gViewportRectangle.zw;
  275. float2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  276. uint2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  277. // Ignore pixels out of valid range
  278. if (all(dispatchThreadId.xy < viewportMax))
  279. {
  280. #if MSAA_COUNT > 1
  281. float4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  282. writeBufferSample(pixelPos, 0, lighting);
  283. bool doPerSampleShading = needsPerSampleShading(surfaceData);
  284. if(doPerSampleShading)
  285. {
  286. [unroll]
  287. for(uint i = 1; i < MSAA_COUNT; ++i)
  288. {
  289. lighting = getLighting(clipSpacePos.xy, surfaceData[i]);
  290. writeBufferSample(pixelPos, i, lighting);
  291. }
  292. }
  293. else // Splat same information to all samples
  294. {
  295. [unroll]
  296. for(uint i = 1; i < MSAA_COUNT; ++i)
  297. writeBufferSample(pixelPos, i, lighting);
  298. }
  299. #else
  300. float4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  301. gOutput[pixelPos] = lighting;
  302. #endif
  303. }
  304. }
  305. };
  306. };
  307. };
  308. Technique
  309. : inherits("GBuffer")
  310. : inherits("PerCameraData")
  311. : inherits("LightingCommon") =
  312. {
  313. Language = "GLSL";
  314. Pass =
  315. {
  316. Compute =
  317. {
  318. // Arbitrary limit, increase if needed
  319. #define MAX_LIGHTS 512
  320. layout (local_size_x = TILE_SIZE, local_size_y = TILE_SIZE) in;
  321. #if MSAA_COUNT > 1
  322. layout(binding = 1) uniform sampler2DMS gGBufferATex;
  323. layout(binding = 2) uniform sampler2DMS gGBufferBTex;
  324. layout(binding = 3) uniform sampler2DMS gGBufferCTex;
  325. layout(binding = 4) uniform sampler2DMS gDepthBufferTex;
  326. #else
  327. layout(binding = 1) uniform sampler2D gGBufferATex;
  328. layout(binding = 2) uniform sampler2D gGBufferBTex;
  329. layout(binding = 3) uniform sampler2D gGBufferCTex;
  330. layout(binding = 4) uniform sampler2D gDepthBufferTex;
  331. #endif
  332. SurfaceData decodeGBuffer(vec4 GBufferAData, vec4 GBufferBData, vec2 GBufferCData, float deviceZ)
  333. {
  334. SurfaceData surfaceData;
  335. surfaceData.albedo.xyz = GBufferAData.xyz;
  336. surfaceData.albedo.w = 1.0f;
  337. surfaceData.worldNormal = GBufferBData * vec4(2, 2, 2, 1) - vec4(1, 1, 1, 0);
  338. surfaceData.worldNormal.xyz = normalize(surfaceData.worldNormal.xyz);
  339. surfaceData.depth = convertFromDeviceZ(deviceZ);
  340. surfaceData.roughness = GBufferCData.x;
  341. surfaceData.metalness = GBufferCData.y;
  342. return surfaceData;
  343. }
  344. #if MSAA_COUNT > 1
  345. layout(binding = 5, rgba16f) uniform image2DMS gOutput;
  346. bool needsPerSampleShading(SurfaceData samples[MSAA_COUNT])
  347. {
  348. vec3 albedo = samples[0].albedo.xyz;
  349. vec3 normal = samples[0].worldNormal.xyz;
  350. float depth = samples[0].depth;
  351. for(int i = 1; i < MSAA_COUNT; i++)
  352. {
  353. vec3 otherAlbedo = samples[i].albedo.xyz;
  354. vec3 otherNormal = samples[i].worldNormal.xyz;
  355. float otherDepth = samples[i].depth;
  356. if(abs(depth - otherDepth) > 0.1f || abs(dot(abs(normal - otherNormal), vec3(1, 1, 1))) > 0.1f || abs(dot(albedo - otherAlbedo, vec3(1, 1, 1))) > 0.1f)
  357. {
  358. return true;
  359. }
  360. }
  361. return false;
  362. }
  363. SurfaceData getGBufferData(ivec2 pixelPos, int sampleIndex)
  364. {
  365. vec4 GBufferAData = texelFetch(gGBufferATex, pixelPos, sampleIndex);
  366. vec4 GBufferBData = texelFetch(gGBufferBTex, pixelPos, sampleIndex);
  367. vec2 GBufferCData = texelFetch(gGBufferCTex, pixelPos, sampleIndex).rg;
  368. float deviceZ = texelFetch(gDepthBufferTex, pixelPos, sampleIndex).r;
  369. return decodeGBuffer(GBufferAData, GBufferBData, GBufferCData, deviceZ);
  370. }
  371. #else
  372. layout(binding = 5, rgba16f) uniform image2D gOutput;
  373. SurfaceData getGBufferData(ivec2 pixelPos)
  374. {
  375. vec4 GBufferAData = texelFetch(gGBufferATex, pixelPos, 0);
  376. vec4 GBufferBData = texelFetch(gGBufferBTex, pixelPos, 0);
  377. vec2 GBufferCData = texelFetch(gGBufferCTex, pixelPos, 0).rg;
  378. float deviceZ = texelFetch(gDepthBufferTex, pixelPos, 0).r;
  379. return decodeGBuffer(GBufferAData, GBufferBData, GBufferCData, deviceZ);
  380. }
  381. #endif
  382. layout(std430, binding = 6) readonly buffer gLights
  383. {
  384. LightData gLightsData[];
  385. };
  386. layout(binding = 7, std140) uniform Params
  387. {
  388. // Offsets at which specific light types begin in gLights buffer
  389. // Assumed directional lights start at 0
  390. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  391. uvec3 gLightOffsets;
  392. uvec2 gFramebufferSize;
  393. };
  394. shared uint sTileMinZ;
  395. shared uint sTileMaxZ;
  396. shared uint sNumLightsPerType[2];
  397. shared uint sTotalNumLights;
  398. shared uint sLightIndices[MAX_LIGHTS];
  399. vec4 getLighting(vec2 clipSpacePos, SurfaceData surfaceData)
  400. {
  401. // x, y are now in clip space, z, w are in view space
  402. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  403. // z, w eliminated (since they are already in view space)
  404. // Note: Multiply by depth should be avoided if using ortographic projection
  405. vec4 mixedSpacePos = vec4(clipSpacePos.xy * -surfaceData.depth, surfaceData.depth, 1);
  406. vec4 worldPosition4D = gMatScreenToWorld * mixedSpacePos;
  407. vec3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  408. float alpha = 0.0f;
  409. vec3 lightAccumulator = vec3(0, 0, 0);
  410. if(surfaceData.worldNormal.w > 0.0f)
  411. {
  412. for(uint i = 0; i < gLightOffsets[0]; ++i)
  413. {
  414. LightData lightData = gLightsData[i];
  415. lightAccumulator += getDirLightContibution(surfaceData, lightData);
  416. }
  417. for (uint i = 0; i < sNumLightsPerType[0]; ++i)
  418. {
  419. uint lightIdx = sLightIndices[i];
  420. LightData lightData = gLightsData[lightIdx];
  421. lightAccumulator += getPointLightContribution(worldPosition, surfaceData, lightData);
  422. }
  423. for(uint i = sNumLightsPerType[0]; i < sTotalNumLights; ++i)
  424. {
  425. uint lightIdx = sLightIndices[i];
  426. LightData lightData = gLightsData[lightIdx];
  427. lightAccumulator += getSpotLightContribution(worldPosition, surfaceData, lightData);
  428. }
  429. lightAccumulator += surfaceData.albedo.rgb * gAmbientFactor;
  430. alpha = 1.0f;
  431. }
  432. vec3 diffuse = surfaceData.albedo.xyz / PI; // TODO - Add better lighting model later
  433. return vec4(lightAccumulator * diffuse, alpha);
  434. }
  435. void main()
  436. {
  437. uint threadIndex = gl_LocalInvocationID.y * TILE_SIZE + gl_LocalInvocationID.x;
  438. ivec2 pixelPos = ivec2(gl_GlobalInvocationID.xy) + gViewportRectangle.xy;
  439. // Get data for all samples, and determine per-pixel minimum and maximum depth values
  440. SurfaceData surfaceData[MSAA_COUNT];
  441. uint sampleMinZ = 0x7F7FFFFF;
  442. uint sampleMaxZ = 0;
  443. #if MSAA_COUNT > 1
  444. for(int i = 0; i < MSAA_COUNT; ++i)
  445. {
  446. surfaceData[i] = getGBufferData(pixelPos, i);
  447. sampleMinZ = min(sampleMinZ, floatBitsToUint(-surfaceData[i].depth));
  448. sampleMaxZ = max(sampleMaxZ, floatBitsToUint(-surfaceData[i].depth));
  449. }
  450. #else
  451. surfaceData[0] = getGBufferData(pixelPos);
  452. sampleMinZ = floatBitsToUint(-surfaceData[0].depth);
  453. sampleMaxZ = floatBitsToUint(-surfaceData[0].depth);
  454. #endif
  455. // Set initial values
  456. if(threadIndex == 0)
  457. {
  458. sTileMinZ = 0x7F7FFFFF;
  459. sTileMaxZ = 0;
  460. sNumLightsPerType[0] = 0;
  461. sNumLightsPerType[1] = 0;
  462. sTotalNumLights = 0;
  463. }
  464. groupMemoryBarrier();
  465. barrier();
  466. atomicMin(sTileMinZ, sampleMinZ);
  467. atomicMax(sTileMaxZ, sampleMaxZ);
  468. groupMemoryBarrier();
  469. barrier();
  470. float minTileZ = uintBitsToFloat(sTileMinZ);
  471. float maxTileZ = uintBitsToFloat(sTileMaxZ);
  472. // Create a frustum for the current tile
  473. // See HLSL version for an explanation of the math
  474. vec2 tileScale = gViewportRectangle.zw / vec2(TILE_SIZE, TILE_SIZE);
  475. vec2 tileBias = tileScale - 1 - gl_WorkGroupID.xy * 2;
  476. float At = gMatProj[0][0] * tileScale.x;
  477. float Ctt = gMatProj[2][0] * tileScale.x - tileBias.x;
  478. float Bt = gMatProj[1][1] * tileScale.y;
  479. float Dtt = gMatProj[2][1] * tileScale.y + tileBias.y;
  480. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  481. vec4 frustumPlanes[6];
  482. frustumPlanes[0] = vec4(At, 0.0f, gMatProj[2][3] + Ctt, 0.0f);
  483. frustumPlanes[1] = vec4(-At, 0.0f, gMatProj[2][3] - Ctt, 0.0f);
  484. frustumPlanes[2] = vec4(0.0f, -Bt, gMatProj[2][3] - Dtt, 0.0f);
  485. frustumPlanes[3] = vec4(0.0f, Bt, gMatProj[2][3] + Dtt, 0.0f);
  486. // Normalize
  487. for (uint i = 0; i < 4; ++i)
  488. frustumPlanes[i] /= length(frustumPlanes[i].xyz);
  489. // Generate near/far frustum planes
  490. frustumPlanes[4] = vec4(0.0f, 0.0f, -1.0f, -minTileZ);
  491. frustumPlanes[5] = vec4(0.0f, 0.0f, 1.0f, maxTileZ);
  492. // Find radial & spot lights overlapping the tile
  493. for(uint type = 0; type < 2; type++)
  494. {
  495. uint lightOffset = threadIndex + gLightOffsets[type];
  496. uint lightsEnd = gLightOffsets[type + 1];
  497. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  498. {
  499. LightData lightData = gLightsData[i];
  500. vec4 lightPosition = gMatView * vec4(lightData.position, 1.0f);
  501. float lightRadius = lightData.radius;
  502. bool lightInTile = true;
  503. // First check side planes as this will cull majority of the lights
  504. for (uint j = 0; j < 4; ++j)
  505. {
  506. float dist = dot(frustumPlanes[j], lightPosition);
  507. lightInTile = lightInTile && (dist >= -lightRadius);
  508. }
  509. if (lightInTile)
  510. {
  511. bool inDepthRange = true;
  512. // Check near/far planes
  513. for (uint j = 4; j < 6; ++j)
  514. {
  515. float dist = dot(frustumPlanes[j], lightPosition);
  516. inDepthRange = inDepthRange && (dist >= -lightRadius);
  517. }
  518. // In tile, add to branch
  519. if (inDepthRange)
  520. {
  521. atomicAdd(sNumLightsPerType[type], 1U);
  522. uint idx = atomicAdd(sTotalNumLights, 1U);
  523. sLightIndices[idx] = i;
  524. }
  525. }
  526. }
  527. }
  528. groupMemoryBarrier();
  529. barrier();
  530. vec2 screenUv = (vec2(gViewportRectangle.xy + pixelPos) + 0.5f) / vec2(gViewportRectangle.zw);
  531. vec2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  532. uvec2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  533. // Ignore pixels out of valid range
  534. if (all(lessThan(gl_GlobalInvocationID.xy, viewportMax)))
  535. {
  536. #if MSAA_COUNT > 1
  537. vec4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  538. imageStore(gOutput, pixelPos, 0, lighting);
  539. bool doPerSampleShading = needsPerSampleShading(surfaceData);
  540. if(doPerSampleShading)
  541. {
  542. for(int i = 1; i < MSAA_COUNT; ++i)
  543. {
  544. lighting = getLighting(clipSpacePos.xy, surfaceData[i]);
  545. imageStore(gOutput, pixelPos, i, lighting);
  546. }
  547. }
  548. else // Splat same information to all samples
  549. {
  550. for(int i = 1; i < MSAA_COUNT; ++i)
  551. imageStore(gOutput, pixelPos, i, lighting);
  552. }
  553. #else
  554. vec4 lighting = getLighting(clipSpacePos.xy, surfaceData[0]);
  555. imageStore(gOutput, pixelPos, lighting);
  556. #endif
  557. }
  558. }
  559. };
  560. };
  561. };