TiledDeferredLighting.bsl 23 KB

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