TiledDeferredLighting.bsl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 gDepthBufferSamp : alias("gDepthBufferTex");
  9. Texture2D gGBufferATex : auto("GBufferA");
  10. Texture2D gGBufferBTex : auto("GBufferB");
  11. Texture2D gDepthBufferTex : auto("GBufferDepth");
  12. };
  13. Blocks =
  14. {
  15. Block PerCamera : auto("PerCamera");
  16. };
  17. Technique
  18. : inherits("GBuffer")
  19. : inherits("PerCameraData")
  20. : inherits("LightingCommon") =
  21. {
  22. Language = "HLSL11";
  23. Pass =
  24. {
  25. Compute =
  26. {
  27. // Arbitrary limit, increase if needed
  28. #define MAX_LIGHTS 512
  29. SamplerState gGBufferASamp : register(s0);
  30. SamplerState gGBufferBSamp : register(s1);
  31. SamplerState gDepthBufferSamp : register(s2);
  32. Texture2D gGBufferATex : register(t0);
  33. Texture2D gGBufferBTex : register(t1);
  34. Texture2D gDepthBufferTex : register(t2);
  35. SurfaceData decodeGBuffer(float4 GBufferAData, float4 GBufferBData, float deviceZ)
  36. {
  37. SurfaceData output;
  38. output.albedo.xyz = GBufferAData.xyz;
  39. output.albedo.w = 1.0f;
  40. output.worldNormal = GBufferBData * float4(2, 2, 2, 1) - float4(1, 1, 1, 0);
  41. output.worldNormal.xyz = normalize(output.worldNormal.xyz);
  42. output.depth = convertFromDeviceZ(deviceZ);
  43. return output;
  44. }
  45. SurfaceData getGBufferData(float2 uv)
  46. {
  47. float4 GBufferAData = gGBufferATex.SampleLevel(gGBufferASamp, uv, 0);
  48. float4 GBufferBData = gGBufferBTex.SampleLevel(gGBufferBSamp, uv, 0);
  49. float deviceZ = gDepthBufferTex.SampleLevel(gDepthBufferSamp, uv, 0).r;
  50. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  51. }
  52. SurfaceData getGBufferData(uint2 pixelPos)
  53. {
  54. float4 GBufferAData = gGBufferATex.Load(int3(pixelPos, 0));
  55. float4 GBufferBData = gGBufferBTex.Load(int3(pixelPos, 0));
  56. float deviceZ = gDepthBufferTex.Load(int3(pixelPos, 0)).r;
  57. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  58. }
  59. StructuredBuffer<LightData> gLights : register(t3);
  60. RWTexture2D<float4> gOutput : register(u0);
  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. }
  68. groupshared uint sTileMinZ;
  69. groupshared uint sTileMaxZ;
  70. groupshared uint sNumLightsPerType[2];
  71. groupshared uint sTotalNumLights;
  72. groupshared uint sLightIndices[MAX_LIGHTS];
  73. [numthreads(TILE_SIZE, TILE_SIZE, 1)]
  74. void main(
  75. uint3 groupId : SV_GroupID,
  76. uint3 groupThreadId : SV_GroupThreadID,
  77. uint3 dispatchThreadId : SV_DispatchThreadID)
  78. {
  79. uint threadIndex = groupThreadId.y * TILE_SIZE + groupThreadId.x;
  80. uint2 pixelPos = dispatchThreadId.xy + gViewportRectangle.xy;
  81. float deviceZ = gDepthBufferTex.Load(int3(pixelPos, 0)).r;
  82. float depth = convertFromDeviceZ(deviceZ);
  83. // Set initial values
  84. if(threadIndex == 0)
  85. {
  86. sTileMinZ = 0x7F7FFFFF;
  87. sTileMaxZ = 0;
  88. sNumLightsPerType[0] = 0;
  89. sNumLightsPerType[0] = 0;
  90. sTotalNumLights = 0;
  91. }
  92. GroupMemoryBarrierWithGroupSync();
  93. // Determine minimum and maximum depth values
  94. InterlockedMin(sTileMinZ, asuint(-depth));
  95. InterlockedMax(sTileMaxZ, asuint(-depth));
  96. GroupMemoryBarrierWithGroupSync();
  97. float minTileZ = asfloat(sTileMinZ);
  98. float maxTileZ = asfloat(sTileMaxZ);
  99. // Create a frustum for the current tile
  100. // First determine a scale of the tile compared to the viewport
  101. float2 tileScale = gViewportRectangle.zw * rcp(float2(TILE_SIZE, TILE_SIZE));
  102. // Now we need to use that scale to scale down the frustum.
  103. // Assume a projection matrix:
  104. // A, 0, C, 0
  105. // 0, B, D, 0
  106. // 0, 0, Q, QN
  107. // 0, 0, -1, 0
  108. //
  109. // Where A is = 2*n / (r - l)
  110. // and C = (r + l) / (r - l)
  111. //
  112. // Q & QN are used for Z value which we don't need to scale. B & D are equivalent for the
  113. // Y value, we'll only consider the X values (A & C) from now on.
  114. //
  115. // Both and A and C are inversely proportional to the size of the frustum (r - l). Larger scale mean that
  116. // tiles are that much smaller than the viewport. This means as our scale increases, (r - l) decreases,
  117. // which means A & C as a whole increase. Therefore:
  118. // A' = A * tileScale.x
  119. // C' = C * tileScale.x
  120. // Aside from scaling, we also need to offset the frustum to the center of the tile.
  121. // For this we calculate the bias value which we add to the C & D factors (which control
  122. // the offset in the projection matrix).
  123. float2 tileBias = tileScale - 1 - groupId.xy * 2;
  124. // This will yield a bias ranging from [-(tileScale - 1), tileScale - 1]. Every second bias is skipped as
  125. // corresponds to a point in-between two tiles, overlapping existing frustums.
  126. float At = gMatProj[0][0] * tileScale.x;
  127. float Ctt = gMatProj[0][2] * tileScale.x - tileBias.x;
  128. float Bt = gMatProj[1][1] * tileScale.y;
  129. float Dtt = gMatProj[1][2] * tileScale.y + tileBias.y;
  130. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  131. // Note: Do this on the CPU? Since they're shared among all entries in a tile. Plus they don't change across frames.
  132. float4 frustumPlanes[6];
  133. frustumPlanes[0] = float4(At, 0.0f, gMatProj[3][2] + Ctt, 0.0f);
  134. frustumPlanes[1] = float4(-At, 0.0f, gMatProj[3][2] - Ctt, 0.0f);
  135. frustumPlanes[2] = float4(0.0f, -Bt, gMatProj[3][2] - Dtt, 0.0f);
  136. frustumPlanes[3] = float4(0.0f, Bt, gMatProj[3][2] + Dtt, 0.0f);
  137. // Normalize
  138. [unroll]
  139. for (uint i = 0; i < 4; ++i)
  140. frustumPlanes[i] *= rcp(length(frustumPlanes[i].xyz));
  141. // Generate near/far frustum planes
  142. // Note: d gets negated in plane equation, this is why its in opposite direction than it intuitively should be
  143. frustumPlanes[4] = float4(0.0f, 0.0f, -1.0f, -minTileZ);
  144. frustumPlanes[5] = float4(0.0f, 0.0f, 1.0f, maxTileZ);
  145. // Generate world position
  146. float2 screenUv = ((float2)(gViewportRectangle.xy + pixelPos) + 0.5f) / (float2)gViewportRectangle.zw;
  147. float2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  148. // x, y are now in clip space, z, w are in view space
  149. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  150. // z, w eliminated (since they are already in view space)
  151. // Note: Multiply by depth should be avoided if using ortographic projection
  152. float4 mixedSpacePos = float4(clipSpacePos.xy * -depth, depth, 1);
  153. float4 worldPosition4D = mul(gMatScreenToWorld, mixedSpacePos);
  154. float3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  155. // Find radial & spot lights overlapping the tile
  156. for(uint type = 0; type < 2; type++)
  157. {
  158. uint lightOffset = threadIndex + gLightOffsets[type];
  159. uint lightsEnd = gLightOffsets[type + 1];
  160. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  161. {
  162. float4 lightPosition = mul(gMatView, float4(gLights[i].position, 1.0f));
  163. float lightRadius = gLights[i].radius;
  164. // Note: The cull method can have false positives. In case of large light bounds and small tiles, it
  165. // can end up being quite a lot. Consider adding an extra heuristic to check a separating plane.
  166. bool lightInTile = true;
  167. // First check side planes as this will cull majority of the lights
  168. [unroll]
  169. for (uint j = 0; j < 4; ++j)
  170. {
  171. float dist = dot(frustumPlanes[j], lightPosition);
  172. lightInTile = lightInTile && (dist >= -lightRadius);
  173. }
  174. // Make sure to do an actual branch, since it's quite likely an entire warp will have the same value
  175. [branch]
  176. if (lightInTile)
  177. {
  178. bool inDepthRange = true;
  179. // Check near/far planes
  180. [unroll]
  181. for (uint j = 4; j < 6; ++j)
  182. {
  183. float dist = dot(frustumPlanes[j], lightPosition);
  184. inDepthRange = inDepthRange && (dist >= -lightRadius);
  185. }
  186. // In tile, add to branch
  187. [branch]
  188. if (inDepthRange)
  189. {
  190. InterlockedAdd(sNumLightsPerType[type], 1U);
  191. uint idx;
  192. InterlockedAdd(sTotalNumLights, 1U, idx);
  193. sLightIndices[idx] = i;
  194. }
  195. }
  196. }
  197. }
  198. GroupMemoryBarrierWithGroupSync();
  199. // Note: This unnecessarily samples depth again
  200. SurfaceData surfaceData = getGBufferData(pixelPos);
  201. float3 lightAccumulator = 0;
  202. float alpha = 0.0f;
  203. if(surfaceData.worldNormal.w > 0.0f)
  204. {
  205. for(uint i = 0; i < gLightOffsets[0]; ++i)
  206. lightAccumulator += getDirLightContibution(surfaceData, gLights[i]);
  207. for (uint i = 0; i < sNumLightsPerType[0]; ++i)
  208. {
  209. uint lightIdx = sLightIndices[i];
  210. lightAccumulator += getPointLightContribution(worldPosition, surfaceData, gLights[lightIdx]);
  211. }
  212. for(uint i = sNumLightsPerType[0]; i < sTotalNumLights; ++i)
  213. {
  214. uint lightIdx = sLightIndices[i];
  215. lightAccumulator += getSpotLightContribution(worldPosition, surfaceData, gLights[lightIdx]);
  216. }
  217. alpha = 1.0f;
  218. }
  219. float3 diffuse = surfaceData.albedo.xyz / PI; // TODO - Add better lighting model later
  220. uint2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  221. // Ignore pixels out of valid range
  222. if (all(dispatchThreadId.xy < viewportMax))
  223. gOutput[pixelPos] = float4(gOutput[pixelPos].xyz + diffuse * lightAccumulator, alpha);
  224. }
  225. };
  226. };
  227. };
  228. Technique
  229. : inherits("GBuffer")
  230. : inherits("PerCameraData")
  231. : inherits("LightingCommon") =
  232. {
  233. Language = "GLSL";
  234. Pass =
  235. {
  236. Compute =
  237. {
  238. // Arbitrary limit, increase if needed
  239. #define MAX_LIGHTS 512
  240. layout (local_size_x = TILE_SIZE, local_size_y = TILE_SIZE) in;
  241. layout(binding = 1) uniform sampler2D gGBufferATex;
  242. layout(binding = 2) uniform sampler2D gGBufferBTex;
  243. layout(binding = 3) uniform sampler2D gDepthBufferTex;
  244. SurfaceData decodeGBuffer(vec4 GBufferAData, vec4 GBufferBData, float deviceZ)
  245. {
  246. SurfaceData surfaceData;
  247. surfaceData.albedo.xyz = GBufferAData.xyz;
  248. surfaceData.albedo.w = 1.0f;
  249. surfaceData.worldNormal = GBufferBData * vec4(2, 2, 2, 1) - vec4(1, 1, 1, 0);
  250. surfaceData.worldNormal.xyz = normalize(surfaceData.worldNormal.xyz);
  251. surfaceData.depth = convertFromDeviceZ(deviceZ);
  252. return surfaceData;
  253. }
  254. SurfaceData getGBufferData(vec2 uv)
  255. {
  256. vec4 GBufferAData = textureLod(gGBufferATex, uv, 0);
  257. vec4 GBufferBData = textureLod(gGBufferBTex, uv, 0);
  258. float deviceZ = textureLod(gDepthBufferTex, uv, 0).r;
  259. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  260. }
  261. SurfaceData getGBufferData(ivec2 pixelPos)
  262. {
  263. vec4 GBufferAData = texelFetch(gGBufferATex, pixelPos, 0);
  264. vec4 GBufferBData = texelFetch(gGBufferBTex, pixelPos, 0);
  265. float deviceZ = texelFetch(gDepthBufferTex, pixelPos, 0).r;
  266. return decodeGBuffer(GBufferAData, GBufferBData, deviceZ);
  267. }
  268. layout(std430, binding = 4) buffer gLights
  269. {
  270. LightData[] gLightsData;
  271. };
  272. layout(binding = 5, rgba16f) uniform image2D gOutput;
  273. layout(binding = 6, std140) uniform Params
  274. {
  275. // Offsets at which specific light types begin in gLights buffer
  276. // Assumed directional lights start at 0
  277. // x - offset to point lights, y - offset to spot lights, z - total number of lights
  278. uvec3 gLightOffsets;
  279. };
  280. shared uint sTileMinZ;
  281. shared uint sTileMaxZ;
  282. shared uint sNumLightsPerType[2];
  283. shared uint sTotalNumLights;
  284. shared uint sLightIndices[MAX_LIGHTS];
  285. void main()
  286. {
  287. uint threadIndex = gl_LocalInvocationID.y * TILE_SIZE + gl_LocalInvocationID.x;
  288. ivec2 pixelPos = ivec2(gl_GlobalInvocationID.xy) + gViewportRectangle.xy;
  289. SurfaceData surfaceData = getGBufferData(pixelPos);
  290. // Set initial values
  291. if(threadIndex == 0)
  292. {
  293. sTileMinZ = 0x7F7FFFFF;
  294. sTileMaxZ = 0;
  295. sNumLightsPerType[0] = 0;
  296. sNumLightsPerType[0] = 0;
  297. sTotalNumLights = 0;
  298. }
  299. groupMemoryBarrier();
  300. barrier();
  301. atomicMin(sTileMinZ, floatBitsToUint(-surfaceData.depth));
  302. atomicMax(sTileMaxZ, floatBitsToUint(-surfaceData.depth));
  303. groupMemoryBarrier();
  304. barrier();
  305. float minTileZ = uintBitsToFloat(sTileMinZ);
  306. float maxTileZ = uintBitsToFloat(sTileMaxZ);
  307. // Create a frustum for the current tile
  308. // See HLSL version for an explanation of the math
  309. vec2 tileScale = gViewportRectangle.zw / vec2(TILE_SIZE, TILE_SIZE);
  310. vec2 tileBias = tileScale - 1 - gl_WorkGroupID.xy * 2;
  311. float At = gMatProj[0][0] * tileScale.x;
  312. float Ctt = gMatProj[2][0] * tileScale.x - tileBias.x;
  313. float Bt = gMatProj[1][1] * tileScale.y;
  314. float Dtt = gMatProj[2][1] * tileScale.y + tileBias.y;
  315. // Extract left/right/top/bottom frustum planes from scaled projection matrix
  316. vec4 frustumPlanes[6];
  317. frustumPlanes[0] = vec4(At, 0.0f, gMatProj[2][3] + Ctt, 0.0f);
  318. frustumPlanes[1] = vec4(-At, 0.0f, gMatProj[2][3] - Ctt, 0.0f);
  319. frustumPlanes[2] = vec4(0.0f, -Bt, gMatProj[2][3] - Dtt, 0.0f);
  320. frustumPlanes[3] = vec4(0.0f, Bt, gMatProj[2][3] + Dtt, 0.0f);
  321. // Normalize
  322. for (uint i = 0; i < 4; ++i)
  323. frustumPlanes[i] /= length(frustumPlanes[i].xyz);
  324. // Generate near/far frustum planes
  325. frustumPlanes[4] = vec4(0.0f, 0.0f, -1.0f, -minTileZ);
  326. frustumPlanes[5] = vec4(0.0f, 0.0f, 1.0f, maxTileZ);
  327. vec2 screenUv = (vec2(gViewportRectangle.xy + pixelPos) + 0.5f) / vec2(gViewportRectangle.zw);
  328. vec2 clipSpacePos = (screenUv - gClipToUVScaleOffset.zw) / gClipToUVScaleOffset.xy;
  329. // x, y are now in clip space, z, w are in view space
  330. // We multiply them by a special inverse view-projection matrix, that had the projection entries that effect
  331. // z, w eliminated (since they are already in view space)
  332. // Note: Multiply by depth should be avoided if using ortographic projection
  333. vec4 mixedSpacePos = vec4(clipSpacePos.xy * -surfaceData.depth, surfaceData.depth, 1);
  334. vec4 worldPosition4D = gMatScreenToWorld * mixedSpacePos;
  335. vec3 worldPosition = worldPosition4D.xyz / worldPosition4D.w;
  336. // Find radial & spot lights overlapping the tile
  337. for(uint type = 0; type < 2; type++)
  338. {
  339. uint lightOffset = threadIndex + gLightOffsets[type];
  340. uint lightsEnd = gLightOffsets[type + 1];
  341. for (uint i = lightOffset; i < lightsEnd && i < MAX_LIGHTS; i += TILE_SIZE)
  342. {
  343. vec4 lightPosition = gMatView * vec4(gLightsData[i].position, 1.0f);
  344. float lightRadius = gLightsData[i].radius;
  345. bool lightInTile = true;
  346. // First check side planes as this will cull majority of the lights
  347. for (uint j = 0; j < 4; ++j)
  348. {
  349. float dist = dot(frustumPlanes[j], lightPosition);
  350. lightInTile = lightInTile && (dist >= -lightRadius);
  351. }
  352. if (lightInTile)
  353. {
  354. bool inDepthRange = true;
  355. // Check near/far planes
  356. for (uint j = 4; j < 6; ++j)
  357. {
  358. float dist = dot(frustumPlanes[j], lightPosition);
  359. inDepthRange = inDepthRange && (dist >= -lightRadius);
  360. }
  361. // In tile, add to branch
  362. if (inDepthRange)
  363. {
  364. atomicAdd(sNumLightsPerType[type], 1U);
  365. uint idx = atomicAdd(sTotalNumLights, 1U);
  366. sLightIndices[idx] = i;
  367. }
  368. }
  369. }
  370. }
  371. groupMemoryBarrier();
  372. barrier();
  373. float alpha = 0.0f;
  374. vec3 lightAccumulator = vec3(0, 0, 0);
  375. if(surfaceData.worldNormal.w > 0.0f)
  376. {
  377. for(uint i = 0; i < gLightOffsets[0]; ++i)
  378. {
  379. LightData lightData = gLightsData[i];
  380. lightAccumulator += getDirLightContibution(surfaceData, lightData);
  381. }
  382. for (uint i = 0; i < sNumLightsPerType[0]; ++i)
  383. {
  384. uint lightIdx = sLightIndices[i];
  385. LightData lightData = gLightsData[lightIdx];
  386. lightAccumulator += getPointLightContribution(worldPosition, surfaceData, lightData);
  387. }
  388. for(uint i = sNumLightsPerType[0]; i < sTotalNumLights; ++i)
  389. {
  390. uint lightIdx = sLightIndices[i];
  391. LightData lightData = gLightsData[lightIdx];
  392. lightAccumulator += getSpotLightContribution(worldPosition, surfaceData, lightData);
  393. }
  394. alpha = 1.0f;
  395. }
  396. vec3 diffuse = surfaceData.albedo.xyz / PI; // TODO - Add better lighting model later
  397. uvec2 viewportMax = gViewportRectangle.xy + gViewportRectangle.zw;
  398. // Ignore pixels out of valid range
  399. if (all(lessThan(gl_GlobalInvocationID.xy, viewportMax)))
  400. {
  401. vec4 existingValue = imageLoad(gOutput, pixelPos);
  402. imageStore(gOutput, pixelPos, vec4(diffuse * lightAccumulator + existingValue.xyz, alpha));
  403. }
  404. }
  405. };
  406. };
  407. };