scene_forward.glsl 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293
  1. #[vertex]
  2. #version 450
  3. VERSION_DEFINES
  4. #include "scene_forward_inc.glsl"
  5. /* INPUT ATTRIBS */
  6. layout(location = 0) in vec3 vertex_attrib;
  7. //only for pure render depth when normal is not used
  8. #ifdef NORMAL_USED
  9. layout(location = 1) in vec3 normal_attrib;
  10. #endif
  11. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  12. layout(location = 2) in vec4 tangent_attrib;
  13. #endif
  14. #if defined(COLOR_USED)
  15. layout(location = 3) in vec4 color_attrib;
  16. #endif
  17. #ifdef UV_USED
  18. layout(location = 4) in vec2 uv_attrib;
  19. #endif
  20. #if defined(UV2_USED) || defined(USE_LIGHTMAP) || defined(MODE_RENDER_MATERIAL)
  21. layout(location = 5) in vec2 uv2_attrib;
  22. #endif
  23. #if defined(CUSTOM0_USED)
  24. layout(location = 6) in vec4 custom0_attrib;
  25. #endif
  26. #if defined(CUSTOM1_USED)
  27. layout(location = 7) in vec4 custom1_attrib;
  28. #endif
  29. #if defined(CUSTOM2_USED)
  30. layout(location = 8) in vec4 custom2_attrib;
  31. #endif
  32. #if defined(CUSTOM3_USED)
  33. layout(location = 9) in vec4 custom3_attrib;
  34. #endif
  35. #if defined(BONES_USED)
  36. layout(location = 10) in uvec4 bone_attrib;
  37. #endif
  38. #if defined(WEIGHTS_USED)
  39. layout(location = 11) in vec4 weight_attrib;
  40. #endif
  41. /* Varyings */
  42. layout(location = 0) out vec3 vertex_interp;
  43. #ifdef NORMAL_USED
  44. layout(location = 1) out vec3 normal_interp;
  45. #endif
  46. #if defined(COLOR_USED)
  47. layout(location = 2) out vec4 color_interp;
  48. #endif
  49. #ifdef UV_USED
  50. layout(location = 3) out vec2 uv_interp;
  51. #endif
  52. #if defined(UV2_USED) || defined(USE_LIGHTMAP)
  53. layout(location = 4) out vec2 uv2_interp;
  54. #endif
  55. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  56. layout(location = 5) out vec3 tangent_interp;
  57. layout(location = 6) out vec3 binormal_interp;
  58. #endif
  59. #ifdef USE_MATERIAL_UNIFORMS
  60. layout(set = MATERIAL_UNIFORM_SET, binding = 0, std140) uniform MaterialUniforms{
  61. /* clang-format off */
  62. MATERIAL_UNIFORMS
  63. /* clang-format on */
  64. } material;
  65. #endif
  66. invariant gl_Position;
  67. #ifdef MODE_DUAL_PARABOLOID
  68. layout(location = 8) out float dp_clip;
  69. #endif
  70. layout(location = 9) out flat uint instance_index;
  71. /* clang-format off */
  72. VERTEX_SHADER_GLOBALS
  73. /* clang-format on */
  74. void main() {
  75. vec4 instance_custom = vec4(0.0);
  76. #if defined(COLOR_USED)
  77. color_interp = color_attrib;
  78. #endif
  79. instance_index = draw_call.instance_index;
  80. bool is_multimesh = bool(instances.data[instance_index].flags & INSTANCE_FLAGS_MULTIMESH);
  81. if (!is_multimesh) {
  82. instance_index += gl_InstanceIndex;
  83. }
  84. mat4 world_matrix = instances.data[instance_index].transform;
  85. mat3 world_normal_matrix;
  86. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_NON_UNIFORM_SCALE)) {
  87. world_normal_matrix = inverse(mat3(world_matrix));
  88. } else {
  89. world_normal_matrix = mat3(world_matrix);
  90. }
  91. if (is_multimesh) {
  92. //multimesh, instances are for it
  93. uint offset = (instances.data[instance_index].flags >> INSTANCE_FLAGS_MULTIMESH_STRIDE_SHIFT) & INSTANCE_FLAGS_MULTIMESH_STRIDE_MASK;
  94. offset *= gl_InstanceIndex;
  95. mat4 matrix;
  96. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_MULTIMESH_FORMAT_2D)) {
  97. matrix = mat4(transforms.data[offset + 0], transforms.data[offset + 1], vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0));
  98. offset += 2;
  99. } else {
  100. matrix = mat4(transforms.data[offset + 0], transforms.data[offset + 1], transforms.data[offset + 2], vec4(0.0, 0.0, 0.0, 1.0));
  101. offset += 3;
  102. }
  103. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_MULTIMESH_HAS_COLOR)) {
  104. #ifdef COLOR_USED
  105. color_interp *= transforms.data[offset];
  106. #endif
  107. offset += 1;
  108. }
  109. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_MULTIMESH_HAS_CUSTOM_DATA)) {
  110. instance_custom = transforms.data[offset];
  111. }
  112. //transpose
  113. matrix = transpose(matrix);
  114. world_matrix = world_matrix * matrix;
  115. world_normal_matrix = world_normal_matrix * mat3(matrix);
  116. }
  117. vec3 vertex = vertex_attrib;
  118. #ifdef NORMAL_USED
  119. vec3 normal = normal_attrib * 2.0 - 1.0;
  120. #endif
  121. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  122. vec3 tangent = tangent_attrib.xyz * 2.0 - 1.0;
  123. float binormalf = tangent_attrib.a * 2.0 - 1.0;
  124. vec3 binormal = normalize(cross(normal, tangent) * binormalf);
  125. #endif
  126. #if 0
  127. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_SKELETON)) {
  128. //multimesh, instances are for it
  129. uvec2 bones_01 = uvec2(bone_attrib.x & 0xFFFF, bone_attrib.x >> 16) * 3;
  130. uvec2 bones_23 = uvec2(bone_attrib.y & 0xFFFF, bone_attrib.y >> 16) * 3;
  131. vec2 weights_01 = unpackUnorm2x16(bone_attrib.z);
  132. vec2 weights_23 = unpackUnorm2x16(bone_attrib.w);
  133. mat4 m = mat4(transforms.data[bones_01.x], transforms.data[bones_01.x + 1], transforms.data[bones_01.x + 2], vec4(0.0, 0.0, 0.0, 1.0)) * weights_01.x;
  134. m += mat4(transforms.data[bones_01.y], transforms.data[bones_01.y + 1], transforms.data[bones_01.y + 2], vec4(0.0, 0.0, 0.0, 1.0)) * weights_01.y;
  135. m += mat4(transforms.data[bones_23.x], transforms.data[bones_23.x + 1], transforms.data[bones_23.x + 2], vec4(0.0, 0.0, 0.0, 1.0)) * weights_23.x;
  136. m += mat4(transforms.data[bones_23.y], transforms.data[bones_23.y + 1], transforms.data[bones_23.y + 2], vec4(0.0, 0.0, 0.0, 1.0)) * weights_23.y;
  137. //reverse order because its transposed
  138. vertex = (vec4(vertex, 1.0) * m).xyz;
  139. normal = (vec4(normal, 0.0) * m).xyz;
  140. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  141. tangent = (vec4(tangent, 0.0) * m).xyz;
  142. binormal = (vec4(binormal, 0.0) * m).xyz;
  143. #endif
  144. }
  145. #endif
  146. #ifdef UV_USED
  147. uv_interp = uv_attrib;
  148. #endif
  149. #if defined(UV2_USED) || defined(USE_LIGHTMAP)
  150. uv2_interp = uv2_attrib;
  151. #endif
  152. #ifdef OVERRIDE_POSITION
  153. vec4 position;
  154. #endif
  155. mat4 projection_matrix = scene_data.projection_matrix;
  156. //using world coordinates
  157. #if !defined(SKIP_TRANSFORM_USED) && defined(VERTEX_WORLD_COORDS_USED)
  158. vertex = (world_matrix * vec4(vertex, 1.0)).xyz;
  159. normal = world_normal_matrix * normal;
  160. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  161. tangent = world_normal_matrix * tangent;
  162. binormal = world_normal_matrix * binormal;
  163. #endif
  164. #endif
  165. float roughness = 1.0;
  166. mat4 modelview = scene_data.inv_camera_matrix * world_matrix;
  167. mat3 modelview_normal = mat3(scene_data.inv_camera_matrix) * world_normal_matrix;
  168. {
  169. /* clang-format off */
  170. VERTEX_SHADER_CODE
  171. /* clang-format on */
  172. }
  173. // using local coordinates (default)
  174. #if !defined(SKIP_TRANSFORM_USED) && !defined(VERTEX_WORLD_COORDS_USED)
  175. vertex = (modelview * vec4(vertex, 1.0)).xyz;
  176. #ifdef NORMAL_USED
  177. normal = modelview_normal * normal;
  178. #endif
  179. #endif
  180. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  181. binormal = modelview_normal * binormal;
  182. tangent = modelview_normal * tangent;
  183. #endif
  184. //using world coordinates
  185. #if !defined(SKIP_TRANSFORM_USED) && defined(VERTEX_WORLD_COORDS_USED)
  186. vertex = (scene_data.inv_camera_matrix * vec4(vertex, 1.0)).xyz;
  187. normal = mat3(scene_data.inverse_normal_matrix) * normal;
  188. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  189. binormal = mat3(scene_data.camera_inverse_binormal_matrix) * binormal;
  190. tangent = mat3(scene_data.camera_inverse_tangent_matrix) * tangent;
  191. #endif
  192. #endif
  193. vertex_interp = vertex;
  194. #ifdef NORMAL_USED
  195. normal_interp = normal;
  196. #endif
  197. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  198. tangent_interp = tangent;
  199. binormal_interp = binormal;
  200. #endif
  201. #ifdef MODE_RENDER_DEPTH
  202. #ifdef MODE_DUAL_PARABOLOID
  203. vertex_interp.z *= scene_data.dual_paraboloid_side;
  204. dp_clip = vertex_interp.z; //this attempts to avoid noise caused by objects sent to the other parabolloid side due to bias
  205. //for dual paraboloid shadow mapping, this is the fastest but least correct way, as it curves straight edges
  206. vec3 vtx = vertex_interp;
  207. float distance = length(vtx);
  208. vtx = normalize(vtx);
  209. vtx.xy /= 1.0 - vtx.z;
  210. vtx.z = (distance / scene_data.z_far);
  211. vtx.z = vtx.z * 2.0 - 1.0;
  212. vertex_interp = vtx;
  213. #endif
  214. #endif //MODE_RENDER_DEPTH
  215. #ifdef OVERRIDE_POSITION
  216. gl_Position = position;
  217. #else
  218. gl_Position = projection_matrix * vec4(vertex_interp, 1.0);
  219. #endif
  220. #ifdef MODE_RENDER_DEPTH
  221. if (scene_data.pancake_shadows) {
  222. if (gl_Position.z <= 0.00001) {
  223. gl_Position.z = 0.00001;
  224. }
  225. }
  226. #endif
  227. #ifdef MODE_RENDER_MATERIAL
  228. if (scene_data.material_uv2_mode) {
  229. vec2 uv_offset = unpackHalf2x16(draw_call.uv_offset);
  230. gl_Position.xy = (uv2_attrib.xy + uv_offset) * 2.0 - 1.0;
  231. gl_Position.z = 0.00001;
  232. gl_Position.w = 1.0;
  233. }
  234. #endif
  235. }
  236. #[fragment]
  237. #version 450
  238. VERSION_DEFINES
  239. #include "scene_forward_inc.glsl"
  240. /* Varyings */
  241. layout(location = 0) in vec3 vertex_interp;
  242. #ifdef NORMAL_USED
  243. layout(location = 1) in vec3 normal_interp;
  244. #endif
  245. #if defined(COLOR_USED)
  246. layout(location = 2) in vec4 color_interp;
  247. #endif
  248. #ifdef UV_USED
  249. layout(location = 3) in vec2 uv_interp;
  250. #endif
  251. #if defined(UV2_USED) || defined(USE_LIGHTMAP)
  252. layout(location = 4) in vec2 uv2_interp;
  253. #endif
  254. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  255. layout(location = 5) in vec3 tangent_interp;
  256. layout(location = 6) in vec3 binormal_interp;
  257. #endif
  258. #ifdef MODE_DUAL_PARABOLOID
  259. layout(location = 8) in float dp_clip;
  260. #endif
  261. layout(location = 9) in flat uint instance_index;
  262. //defines to keep compatibility with vertex
  263. #define world_matrix instances.data[instance_index].transform
  264. #define projection_matrix scene_data.projection_matrix
  265. #if defined(ENABLE_SSS) && defined(ENABLE_TRANSMITTANCE)
  266. //both required for transmittance to be enabled
  267. #define LIGHT_TRANSMITTANCE_USED
  268. #endif
  269. #ifdef USE_MATERIAL_UNIFORMS
  270. layout(set = MATERIAL_UNIFORM_SET, binding = 0, std140) uniform MaterialUniforms{
  271. /* clang-format off */
  272. MATERIAL_UNIFORMS
  273. /* clang-format on */
  274. } material;
  275. #endif
  276. /* clang-format off */
  277. FRAGMENT_SHADER_GLOBALS
  278. /* clang-format on */
  279. #ifdef MODE_RENDER_DEPTH
  280. #ifdef MODE_RENDER_MATERIAL
  281. layout(location = 0) out vec4 albedo_output_buffer;
  282. layout(location = 1) out vec4 normal_output_buffer;
  283. layout(location = 2) out vec4 orm_output_buffer;
  284. layout(location = 3) out vec4 emission_output_buffer;
  285. layout(location = 4) out float depth_output_buffer;
  286. #endif
  287. #ifdef MODE_RENDER_NORMAL_ROUGHNESS
  288. layout(location = 0) out vec4 normal_roughness_output_buffer;
  289. #ifdef MODE_RENDER_GIPROBE
  290. layout(location = 1) out uvec2 giprobe_buffer;
  291. #endif
  292. #endif //MODE_RENDER_NORMAL
  293. #else // RENDER DEPTH
  294. #ifdef MODE_MULTIPLE_RENDER_TARGETS
  295. layout(location = 0) out vec4 diffuse_buffer; //diffuse (rgb) and roughness
  296. layout(location = 1) out vec4 specular_buffer; //specular and SSS (subsurface scatter)
  297. #else
  298. layout(location = 0) out vec4 frag_color;
  299. #endif
  300. #endif // RENDER DEPTH
  301. #ifdef ALPHA_HASH_USED
  302. float hash_2d(vec2 p) {
  303. return fract(1.0e4 * sin(17.0 * p.x + 0.1 * p.y) *
  304. (0.1 + abs(sin(13.0 * p.y + p.x))));
  305. }
  306. float hash_3d(vec3 p) {
  307. return hash_2d(vec2(hash_2d(p.xy), p.z));
  308. }
  309. float compute_alpha_hash_threshold(vec3 pos, float hash_scale) {
  310. vec3 dx = dFdx(pos);
  311. vec3 dy = dFdx(pos);
  312. float delta_max_sqr = max(length(dx), length(dy));
  313. float pix_scale = 1.0 / (hash_scale * delta_max_sqr);
  314. vec2 pix_scales =
  315. vec2(exp2(floor(log2(pix_scale))), exp2(ceil(log2(pix_scale))));
  316. vec2 a_thresh = vec2(hash_3d(floor(pix_scales.x * pos.xyz)),
  317. hash_3d(floor(pix_scales.y * pos.xyz)));
  318. float lerp_factor = fract(log2(pix_scale));
  319. float a_interp = (1.0 - lerp_factor) * a_thresh.x + lerp_factor * a_thresh.y;
  320. float min_lerp = min(lerp_factor, 1.0 - lerp_factor);
  321. vec3 cases = vec3(a_interp * a_interp / (2.0 * min_lerp * (1.0 - min_lerp)),
  322. (a_interp - 0.5 * min_lerp) / (1.0 - min_lerp),
  323. 1.0 - ((1.0 - a_interp) * (1.0 - a_interp) /
  324. (2.0 * min_lerp * (1.0 - min_lerp))));
  325. float alpha_hash_threshold =
  326. (lerp_factor < (1.0 - min_lerp)) ? ((lerp_factor < min_lerp) ? cases.x : cases.y) : cases.z;
  327. return clamp(alpha_hash_threshold, 0.0, 1.0);
  328. }
  329. #endif // ALPHA_HASH_USED
  330. #ifdef ALPHA_ANTIALIASING_EDGE_USED
  331. float calc_mip_level(vec2 texture_coord) {
  332. vec2 dx = dFdx(texture_coord);
  333. vec2 dy = dFdy(texture_coord);
  334. float delta_max_sqr = max(dot(dx, dx), dot(dy, dy));
  335. return max(0.0, 0.5 * log2(delta_max_sqr));
  336. }
  337. float compute_alpha_antialiasing_edge(float input_alpha, vec2 texture_coord, float alpha_edge) {
  338. input_alpha *= 1.0 + max(0, calc_mip_level(texture_coord)) * 0.25; // 0.25 mip scale, magic number
  339. input_alpha = (input_alpha - alpha_edge) / max(fwidth(input_alpha), 0.0001) + 0.5;
  340. return clamp(input_alpha, 0.0, 1.0);
  341. }
  342. #endif // ALPHA_ANTIALIASING_USED
  343. // This returns the G_GGX function divided by 2 cos_theta_m, where in practice cos_theta_m is either N.L or N.V.
  344. // We're dividing this factor off because the overall term we'll end up looks like
  345. // (see, for example, the first unnumbered equation in B. Burley, "Physically Based Shading at Disney", SIGGRAPH 2012):
  346. //
  347. // F(L.V) D(N.H) G(N.L) G(N.V) / (4 N.L N.V)
  348. //
  349. // We're basically regouping this as
  350. //
  351. // F(L.V) D(N.H) [G(N.L)/(2 N.L)] [G(N.V) / (2 N.V)]
  352. //
  353. // and thus, this function implements the [G(N.m)/(2 N.m)] part with m = L or V.
  354. //
  355. // The contents of the D and G (G1) functions (GGX) are taken from
  356. // E. Heitz, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs", J. Comp. Graph. Tech. 3 (2) (2014).
  357. // Eqns 71-72 and 85-86 (see also Eqns 43 and 80).
  358. #if !defined(MODE_RENDER_DEPTH) && !defined(MODE_UNSHADED)
  359. float G_GGX_2cos(float cos_theta_m, float alpha) {
  360. // Schlick's approximation
  361. // C. Schlick, "An Inexpensive BRDF Model for Physically-based Rendering", Computer Graphics Forum. 13 (3): 233 (1994)
  362. // Eq. (19), although see Heitz (2014) the about the problems with his derivation.
  363. // It nevertheless approximates GGX well with k = alpha/2.
  364. float k = 0.5 * alpha;
  365. return 0.5 / (cos_theta_m * (1.0 - k) + k);
  366. // float cos2 = cos_theta_m * cos_theta_m;
  367. // float sin2 = (1.0 - cos2);
  368. // return 1.0 / (cos_theta_m + sqrt(cos2 + alpha * alpha * sin2));
  369. }
  370. float D_GGX(float cos_theta_m, float alpha) {
  371. float alpha2 = alpha * alpha;
  372. float d = 1.0 + (alpha2 - 1.0) * cos_theta_m * cos_theta_m;
  373. return alpha2 / (M_PI * d * d);
  374. }
  375. float G_GGX_anisotropic_2cos(float cos_theta_m, float alpha_x, float alpha_y, float cos_phi, float sin_phi) {
  376. float cos2 = cos_theta_m * cos_theta_m;
  377. float sin2 = (1.0 - cos2);
  378. float s_x = alpha_x * cos_phi;
  379. float s_y = alpha_y * sin_phi;
  380. return 1.0 / max(cos_theta_m + sqrt(cos2 + (s_x * s_x + s_y * s_y) * sin2), 0.001);
  381. }
  382. float D_GGX_anisotropic(float cos_theta_m, float alpha_x, float alpha_y, float cos_phi, float sin_phi) {
  383. float cos2 = cos_theta_m * cos_theta_m;
  384. float sin2 = (1.0 - cos2);
  385. float r_x = cos_phi / alpha_x;
  386. float r_y = sin_phi / alpha_y;
  387. float d = cos2 + sin2 * (r_x * r_x + r_y * r_y);
  388. return 1.0 / max(M_PI * alpha_x * alpha_y * d * d, 0.001);
  389. }
  390. float SchlickFresnel(float u) {
  391. float m = 1.0 - u;
  392. float m2 = m * m;
  393. return m2 * m2 * m; // pow(m,5)
  394. }
  395. float GTR1(float NdotH, float a) {
  396. if (a >= 1.0)
  397. return 1.0 / M_PI;
  398. float a2 = a * a;
  399. float t = 1.0 + (a2 - 1.0) * NdotH * NdotH;
  400. return (a2 - 1.0) / (M_PI * log(a2) * t);
  401. }
  402. vec3 F0(float metallic, float specular, vec3 albedo) {
  403. float dielectric = 0.16 * specular * specular;
  404. // use albedo * metallic as colored specular reflectance at 0 angle for metallic materials;
  405. // see https://google.github.io/filament/Filament.md.html
  406. return mix(vec3(dielectric), albedo, vec3(metallic));
  407. }
  408. void light_compute(vec3 N, vec3 L, vec3 V, vec3 light_color, float attenuation, vec3 f0, uint orms, float specular_amount,
  409. #ifdef LIGHT_BACKLIGHT_USED
  410. vec3 backlight,
  411. #endif
  412. #ifdef LIGHT_TRANSMITTANCE_USED
  413. vec4 transmittance_color,
  414. float transmittance_depth,
  415. float transmittance_curve,
  416. float transmittance_boost,
  417. float transmittance_z,
  418. #endif
  419. #ifdef LIGHT_RIM_USED
  420. float rim, float rim_tint, vec3 rim_color,
  421. #endif
  422. #ifdef LIGHT_CLEARCOAT_USED
  423. float clearcoat, float clearcoat_gloss,
  424. #endif
  425. #ifdef LIGHT_ANISOTROPY_USED
  426. vec3 B, vec3 T, float anisotropy,
  427. #endif
  428. #ifdef USE_SOFT_SHADOWS
  429. float A,
  430. #endif
  431. #ifdef USE_SHADOW_TO_OPACITY
  432. inout float alpha,
  433. #endif
  434. inout vec3 diffuse_light, inout vec3 specular_light) {
  435. #if defined(USE_LIGHT_SHADER_CODE)
  436. // light is written by the light shader
  437. vec3 normal = N;
  438. vec3 light = L;
  439. vec3 view = V;
  440. /* clang-format off */
  441. LIGHT_SHADER_CODE
  442. /* clang-format on */
  443. #else
  444. #ifdef USE_SOFT_SHADOWS
  445. float NdotL = min(A + dot(N, L), 1.0);
  446. #else
  447. float NdotL = dot(N, L);
  448. #endif
  449. float cNdotL = max(NdotL, 0.0); // clamped NdotL
  450. float NdotV = dot(N, V);
  451. float cNdotV = max(NdotV, 0.0);
  452. #if defined(DIFFUSE_BURLEY) || defined(SPECULAR_BLINN) || defined(SPECULAR_SCHLICK_GGX) || defined(LIGHT_CLEARCOAT_USED)
  453. vec3 H = normalize(V + L);
  454. #endif
  455. #if defined(SPECULAR_BLINN) || defined(SPECULAR_SCHLICK_GGX) || defined(LIGHT_CLEARCOAT_USED)
  456. #ifdef USE_SOFT_SHADOWS
  457. float cNdotH = clamp(A + dot(N, H), 0.0, 1.0);
  458. #else
  459. float cNdotH = clamp(dot(N, H), 0.0, 1.0);
  460. #endif
  461. #endif
  462. #if defined(DIFFUSE_BURLEY) || defined(SPECULAR_SCHLICK_GGX) || defined(LIGHT_CLEARCOAT_USED)
  463. #ifdef USE_SOFT_SHADOWS
  464. float cLdotH = clamp(A + dot(L, H), 0.0, 1.0);
  465. #else
  466. float cLdotH = clamp(dot(L, H), 0.0, 1.0);
  467. #endif
  468. #endif
  469. float metallic = unpackUnorm4x8(orms).z;
  470. if (metallic < 1.0) {
  471. float roughness = unpackUnorm4x8(orms).y;
  472. #if defined(DIFFUSE_OREN_NAYAR)
  473. vec3 diffuse_brdf_NL;
  474. #else
  475. float diffuse_brdf_NL; // BRDF times N.L for calculating diffuse radiance
  476. #endif
  477. #if defined(DIFFUSE_LAMBERT_WRAP)
  478. // energy conserving lambert wrap shader
  479. diffuse_brdf_NL = max(0.0, (NdotL + roughness) / ((1.0 + roughness) * (1.0 + roughness)));
  480. #elif defined(DIFFUSE_TOON)
  481. diffuse_brdf_NL = smoothstep(-roughness, max(roughness, 0.01), NdotL);
  482. #elif defined(DIFFUSE_BURLEY)
  483. {
  484. float FD90_minus_1 = 2.0 * cLdotH * cLdotH * roughness - 0.5;
  485. float FdV = 1.0 + FD90_minus_1 * SchlickFresnel(cNdotV);
  486. float FdL = 1.0 + FD90_minus_1 * SchlickFresnel(cNdotL);
  487. diffuse_brdf_NL = (1.0 / M_PI) * FdV * FdL * cNdotL;
  488. /*
  489. float energyBias = mix(roughness, 0.0, 0.5);
  490. float energyFactor = mix(roughness, 1.0, 1.0 / 1.51);
  491. float fd90 = energyBias + 2.0 * VoH * VoH * roughness;
  492. float f0 = 1.0;
  493. float lightScatter = f0 + (fd90 - f0) * pow(1.0 - cNdotL, 5.0);
  494. float viewScatter = f0 + (fd90 - f0) * pow(1.0 - cNdotV, 5.0);
  495. diffuse_brdf_NL = lightScatter * viewScatter * energyFactor;
  496. */
  497. }
  498. #else
  499. // lambert
  500. diffuse_brdf_NL = cNdotL * (1.0 / M_PI);
  501. #endif
  502. diffuse_light += light_color * diffuse_brdf_NL * attenuation;
  503. #if defined(LIGHT_BACKLIGHT_USED)
  504. diffuse_light += light_color * (vec3(1.0 / M_PI) - diffuse_brdf_NL) * backlight * attenuation;
  505. #endif
  506. #if defined(LIGHT_RIM_USED)
  507. float rim_light = pow(max(0.0, 1.0 - cNdotV), max(0.0, (1.0 - roughness) * 16.0));
  508. diffuse_light += rim_light * rim * mix(vec3(1.0), rim_color, rim_tint) * light_color;
  509. #endif
  510. #ifdef LIGHT_TRANSMITTANCE_USED
  511. #ifdef SSS_MODE_SKIN
  512. {
  513. float scale = 8.25 / transmittance_depth;
  514. float d = scale * abs(transmittance_z);
  515. float dd = -d * d;
  516. vec3 profile = vec3(0.233, 0.455, 0.649) * exp(dd / 0.0064) +
  517. vec3(0.1, 0.336, 0.344) * exp(dd / 0.0484) +
  518. vec3(0.118, 0.198, 0.0) * exp(dd / 0.187) +
  519. vec3(0.113, 0.007, 0.007) * exp(dd / 0.567) +
  520. vec3(0.358, 0.004, 0.0) * exp(dd / 1.99) +
  521. vec3(0.078, 0.0, 0.0) * exp(dd / 7.41);
  522. diffuse_light += profile * transmittance_color.a * light_color * clamp(transmittance_boost - NdotL, 0.0, 1.0) * (1.0 / M_PI);
  523. }
  524. #else
  525. if (transmittance_depth > 0.0) {
  526. float fade = clamp(abs(transmittance_z / transmittance_depth), 0.0, 1.0);
  527. fade = pow(max(0.0, 1.0 - fade), transmittance_curve);
  528. fade *= clamp(transmittance_boost - NdotL, 0.0, 1.0);
  529. diffuse_light += transmittance_color.rgb * light_color * (1.0 / M_PI) * transmittance_color.a * fade;
  530. }
  531. #endif //SSS_MODE_SKIN
  532. #endif //LIGHT_TRANSMITTANCE_USED
  533. }
  534. float roughness = unpackUnorm4x8(orms).y;
  535. if (roughness > 0.0) { // FIXME: roughness == 0 should not disable specular light entirely
  536. // D
  537. #if defined(SPECULAR_BLINN)
  538. //normalized blinn
  539. float shininess = exp2(15.0 * (1.0 - roughness) + 1.0) * 0.25;
  540. float blinn = pow(cNdotH, shininess) * cNdotL;
  541. blinn *= (shininess + 8.0) * (1.0 / (8.0 * M_PI));
  542. float intensity = blinn;
  543. specular_light += light_color * intensity * attenuation * specular_amount;
  544. #elif defined(SPECULAR_PHONG)
  545. vec3 R = normalize(-reflect(L, N));
  546. float cRdotV = clamp(A + dot(R, V), 0.0, 1.0);
  547. float shininess = exp2(15.0 * (1.0 - roughness) + 1.0) * 0.25;
  548. float phong = pow(cRdotV, shininess);
  549. phong *= (shininess + 8.0) * (1.0 / (8.0 * M_PI));
  550. float intensity = (phong) / max(4.0 * cNdotV * cNdotL, 0.75);
  551. specular_light += light_color * intensity * attenuation * specular_amount;
  552. #elif defined(SPECULAR_TOON)
  553. vec3 R = normalize(-reflect(L, N));
  554. float RdotV = dot(R, V);
  555. float mid = 1.0 - roughness;
  556. mid *= mid;
  557. float intensity = smoothstep(mid - roughness * 0.5, mid + roughness * 0.5, RdotV) * mid;
  558. diffuse_light += light_color * intensity * attenuation * specular_amount; // write to diffuse_light, as in toon shading you generally want no reflection
  559. #elif defined(SPECULAR_DISABLED)
  560. // none..
  561. #elif defined(SPECULAR_SCHLICK_GGX)
  562. // shlick+ggx as default
  563. #if defined(LIGHT_ANISOTROPY_USED)
  564. float alpha_ggx = roughness * roughness;
  565. float aspect = sqrt(1.0 - anisotropy * 0.9);
  566. float ax = alpha_ggx / aspect;
  567. float ay = alpha_ggx * aspect;
  568. float XdotH = dot(T, H);
  569. float YdotH = dot(B, H);
  570. float D = D_GGX_anisotropic(cNdotH, ax, ay, XdotH, YdotH);
  571. float G = G_GGX_anisotropic_2cos(cNdotL, ax, ay, XdotH, YdotH) * G_GGX_anisotropic_2cos(cNdotV, ax, ay, XdotH, YdotH);
  572. #else
  573. float alpha_ggx = roughness * roughness;
  574. float D = D_GGX(cNdotH, alpha_ggx);
  575. float G = G_GGX_2cos(cNdotL, alpha_ggx) * G_GGX_2cos(cNdotV, alpha_ggx);
  576. #endif
  577. // F
  578. float cLdotH5 = SchlickFresnel(cLdotH);
  579. vec3 F = mix(vec3(cLdotH5), vec3(1.0), f0);
  580. vec3 specular_brdf_NL = cNdotL * D * F * G;
  581. specular_light += specular_brdf_NL * light_color * attenuation * specular_amount;
  582. #endif
  583. #if defined(LIGHT_CLEARCOAT_USED)
  584. #if !defined(SPECULAR_SCHLICK_GGX)
  585. float cLdotH5 = SchlickFresnel(cLdotH);
  586. #endif
  587. float Dr = GTR1(cNdotH, mix(.1, .001, clearcoat_gloss));
  588. float Fr = mix(.04, 1.0, cLdotH5);
  589. float Gr = G_GGX_2cos(cNdotL, .25) * G_GGX_2cos(cNdotV, .25);
  590. float clearcoat_specular_brdf_NL = 0.25 * clearcoat * Gr * Fr * Dr * cNdotL;
  591. specular_light += clearcoat_specular_brdf_NL * light_color * attenuation * specular_amount;
  592. #endif
  593. }
  594. #ifdef USE_SHADOW_TO_OPACITY
  595. alpha = min(alpha, clamp(1.0 - attenuation), 0.0, 1.0));
  596. #endif
  597. #endif //defined(USE_LIGHT_SHADER_CODE)
  598. }
  599. #ifndef USE_NO_SHADOWS
  600. // Interleaved Gradient Noise
  601. // http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare
  602. float quick_hash(vec2 pos) {
  603. const vec3 magic = vec3(0.06711056f, 0.00583715f, 52.9829189f);
  604. return fract(magic.z * fract(dot(pos, magic.xy)));
  605. }
  606. float sample_directional_pcf_shadow(texture2D shadow, vec2 shadow_pixel_size, vec4 coord) {
  607. vec2 pos = coord.xy;
  608. float depth = coord.z;
  609. //if only one sample is taken, take it from the center
  610. if (scene_data.directional_soft_shadow_samples == 1) {
  611. return textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(pos, depth, 1.0));
  612. }
  613. mat2 disk_rotation;
  614. {
  615. float r = quick_hash(gl_FragCoord.xy) * 2.0 * M_PI;
  616. float sr = sin(r);
  617. float cr = cos(r);
  618. disk_rotation = mat2(vec2(cr, -sr), vec2(sr, cr));
  619. }
  620. float avg = 0.0;
  621. for (uint i = 0; i < scene_data.directional_soft_shadow_samples; i++) {
  622. avg += textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(pos + shadow_pixel_size * (disk_rotation * scene_data.directional_soft_shadow_kernel[i].xy), depth, 1.0));
  623. }
  624. return avg * (1.0 / float(scene_data.directional_soft_shadow_samples));
  625. }
  626. float sample_pcf_shadow(texture2D shadow, vec2 shadow_pixel_size, vec4 coord) {
  627. vec2 pos = coord.xy;
  628. float depth = coord.z;
  629. //if only one sample is taken, take it from the center
  630. if (scene_data.soft_shadow_samples == 1) {
  631. return textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(pos, depth, 1.0));
  632. }
  633. mat2 disk_rotation;
  634. {
  635. float r = quick_hash(gl_FragCoord.xy) * 2.0 * M_PI;
  636. float sr = sin(r);
  637. float cr = cos(r);
  638. disk_rotation = mat2(vec2(cr, -sr), vec2(sr, cr));
  639. }
  640. float avg = 0.0;
  641. for (uint i = 0; i < scene_data.soft_shadow_samples; i++) {
  642. avg += textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(pos + shadow_pixel_size * (disk_rotation * scene_data.soft_shadow_kernel[i].xy), depth, 1.0));
  643. }
  644. return avg * (1.0 / float(scene_data.soft_shadow_samples));
  645. }
  646. float sample_directional_soft_shadow(texture2D shadow, vec3 pssm_coord, vec2 tex_scale) {
  647. //find blocker
  648. float blocker_count = 0.0;
  649. float blocker_average = 0.0;
  650. mat2 disk_rotation;
  651. {
  652. float r = quick_hash(gl_FragCoord.xy) * 2.0 * M_PI;
  653. float sr = sin(r);
  654. float cr = cos(r);
  655. disk_rotation = mat2(vec2(cr, -sr), vec2(sr, cr));
  656. }
  657. for (uint i = 0; i < scene_data.directional_penumbra_shadow_samples; i++) {
  658. vec2 suv = pssm_coord.xy + (disk_rotation * scene_data.directional_penumbra_shadow_kernel[i].xy) * tex_scale;
  659. float d = textureLod(sampler2D(shadow, material_samplers[SAMPLER_LINEAR_CLAMP]), suv, 0.0).r;
  660. if (d < pssm_coord.z) {
  661. blocker_average += d;
  662. blocker_count += 1.0;
  663. }
  664. }
  665. if (blocker_count > 0.0) {
  666. //blockers found, do soft shadow
  667. blocker_average /= blocker_count;
  668. float penumbra = (pssm_coord.z - blocker_average) / blocker_average;
  669. tex_scale *= penumbra;
  670. float s = 0.0;
  671. for (uint i = 0; i < scene_data.directional_penumbra_shadow_samples; i++) {
  672. vec2 suv = pssm_coord.xy + (disk_rotation * scene_data.directional_penumbra_shadow_kernel[i].xy) * tex_scale;
  673. s += textureProj(sampler2DShadow(shadow, shadow_sampler), vec4(suv, pssm_coord.z, 1.0));
  674. }
  675. return s / float(scene_data.directional_penumbra_shadow_samples);
  676. } else {
  677. //no blockers found, so no shadow
  678. return 1.0;
  679. }
  680. }
  681. #endif //USE_NO_SHADOWS
  682. float get_omni_attenuation(float distance, float inv_range, float decay) {
  683. float nd = distance * inv_range;
  684. nd *= nd;
  685. nd *= nd; // nd^4
  686. nd = max(1.0 - nd, 0.0);
  687. nd *= nd; // nd^2
  688. return nd * pow(max(distance, 0.0001), -decay);
  689. }
  690. float light_process_omni_shadow(uint idx, vec3 vertex, vec3 normal) {
  691. #ifndef USE_NO_SHADOWS
  692. if (omni_lights.data[idx].shadow_enabled) {
  693. // there is a shadowmap
  694. vec3 light_rel_vec = omni_lights.data[idx].position - vertex;
  695. float light_length = length(light_rel_vec);
  696. vec4 v = vec4(vertex, 1.0);
  697. vec4 splane = (omni_lights.data[idx].shadow_matrix * v);
  698. float shadow_len = length(splane.xyz); //need to remember shadow len from here
  699. {
  700. vec3 nofs = normal_interp * omni_lights.data[idx].shadow_normal_bias / omni_lights.data[idx].inv_radius;
  701. nofs *= (1.0 - max(0.0, dot(normalize(light_rel_vec), normalize(normal_interp))));
  702. v.xyz += nofs;
  703. splane = (omni_lights.data[idx].shadow_matrix * v);
  704. }
  705. float shadow;
  706. #ifdef USE_SOFT_SHADOWS
  707. if (omni_lights.data[idx].soft_shadow_size > 0.0) {
  708. //soft shadow
  709. //find blocker
  710. float blocker_count = 0.0;
  711. float blocker_average = 0.0;
  712. mat2 disk_rotation;
  713. {
  714. float r = quick_hash(gl_FragCoord.xy) * 2.0 * M_PI;
  715. float sr = sin(r);
  716. float cr = cos(r);
  717. disk_rotation = mat2(vec2(cr, -sr), vec2(sr, cr));
  718. }
  719. vec3 normal = normalize(splane.xyz);
  720. vec3 v0 = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
  721. vec3 tangent = normalize(cross(v0, normal));
  722. vec3 bitangent = normalize(cross(tangent, normal));
  723. float z_norm = shadow_len * omni_lights.data[idx].inv_radius;
  724. tangent *= omni_lights.data[idx].soft_shadow_size * omni_lights.data[idx].soft_shadow_scale;
  725. bitangent *= omni_lights.data[idx].soft_shadow_size * omni_lights.data[idx].soft_shadow_scale;
  726. for (uint i = 0; i < scene_data.penumbra_shadow_samples; i++) {
  727. vec2 disk = disk_rotation * scene_data.penumbra_shadow_kernel[i].xy;
  728. vec3 pos = splane.xyz + tangent * disk.x + bitangent * disk.y;
  729. pos = normalize(pos);
  730. vec4 uv_rect = omni_lights.data[idx].atlas_rect;
  731. if (pos.z >= 0.0) {
  732. pos.z += 1.0;
  733. uv_rect.y += uv_rect.w;
  734. } else {
  735. pos.z = 1.0 - pos.z;
  736. }
  737. pos.xy /= pos.z;
  738. pos.xy = pos.xy * 0.5 + 0.5;
  739. pos.xy = uv_rect.xy + pos.xy * uv_rect.zw;
  740. float d = textureLod(sampler2D(shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), pos.xy, 0.0).r;
  741. if (d < z_norm) {
  742. blocker_average += d;
  743. blocker_count += 1.0;
  744. }
  745. }
  746. if (blocker_count > 0.0) {
  747. //blockers found, do soft shadow
  748. blocker_average /= blocker_count;
  749. float penumbra = (z_norm - blocker_average) / blocker_average;
  750. tangent *= penumbra;
  751. bitangent *= penumbra;
  752. z_norm -= omni_lights.data[idx].inv_radius * omni_lights.data[idx].shadow_bias;
  753. shadow = 0.0;
  754. for (uint i = 0; i < scene_data.penumbra_shadow_samples; i++) {
  755. vec2 disk = disk_rotation * scene_data.penumbra_shadow_kernel[i].xy;
  756. vec3 pos = splane.xyz + tangent * disk.x + bitangent * disk.y;
  757. pos = normalize(pos);
  758. vec4 uv_rect = omni_lights.data[idx].atlas_rect;
  759. if (pos.z >= 0.0) {
  760. pos.z += 1.0;
  761. uv_rect.y += uv_rect.w;
  762. } else {
  763. pos.z = 1.0 - pos.z;
  764. }
  765. pos.xy /= pos.z;
  766. pos.xy = pos.xy * 0.5 + 0.5;
  767. pos.xy = uv_rect.xy + pos.xy * uv_rect.zw;
  768. shadow += textureProj(sampler2DShadow(shadow_atlas, shadow_sampler), vec4(pos.xy, z_norm, 1.0));
  769. }
  770. shadow /= float(scene_data.penumbra_shadow_samples);
  771. } else {
  772. //no blockers found, so no shadow
  773. shadow = 1.0;
  774. }
  775. } else {
  776. #endif
  777. splane.xyz = normalize(splane.xyz);
  778. vec4 clamp_rect = omni_lights.data[idx].atlas_rect;
  779. if (splane.z >= 0.0) {
  780. splane.z += 1.0;
  781. clamp_rect.y += clamp_rect.w;
  782. } else {
  783. splane.z = 1.0 - splane.z;
  784. }
  785. splane.xy /= splane.z;
  786. splane.xy = splane.xy * 0.5 + 0.5;
  787. splane.z = (shadow_len - omni_lights.data[idx].shadow_bias) * omni_lights.data[idx].inv_radius;
  788. splane.xy = clamp_rect.xy + splane.xy * clamp_rect.zw;
  789. splane.w = 1.0; //needed? i think it should be 1 already
  790. shadow = sample_pcf_shadow(shadow_atlas, omni_lights.data[idx].soft_shadow_scale * scene_data.shadow_atlas_pixel_size, splane);
  791. #ifdef USE_SOFT_SHADOWS
  792. }
  793. #endif
  794. return shadow;
  795. }
  796. #endif
  797. return 1.0;
  798. }
  799. void light_process_omni(uint idx, vec3 vertex, vec3 eye_vec, vec3 normal, vec3 vertex_ddx, vec3 vertex_ddy, vec3 f0, uint orms, float shadow,
  800. #ifdef LIGHT_BACKLIGHT_USED
  801. vec3 backlight,
  802. #endif
  803. #ifdef LIGHT_TRANSMITTANCE_USED
  804. vec4 transmittance_color,
  805. float transmittance_depth,
  806. float transmittance_curve,
  807. float transmittance_boost,
  808. #endif
  809. #ifdef LIGHT_RIM_USED
  810. float rim, float rim_tint, vec3 rim_color,
  811. #endif
  812. #ifdef LIGHT_CLEARCOAT_USED
  813. float clearcoat, float clearcoat_gloss,
  814. #endif
  815. #ifdef LIGHT_ANISOTROPY_USED
  816. vec3 binormal, vec3 tangent, float anisotropy,
  817. #endif
  818. #ifdef USE_SHADOW_TO_OPACITY
  819. inout float alpha,
  820. #endif
  821. inout vec3 diffuse_light, inout vec3 specular_light) {
  822. vec3 light_rel_vec = omni_lights.data[idx].position - vertex;
  823. float light_length = length(light_rel_vec);
  824. float omni_attenuation = get_omni_attenuation(light_length, omni_lights.data[idx].inv_radius, omni_lights.data[idx].attenuation);
  825. float light_attenuation = omni_attenuation;
  826. vec3 color = omni_lights.data[idx].color;
  827. #ifdef USE_SOFT_SHADOWS
  828. float size_A = 0.0;
  829. if (omni_lights.data[idx].size > 0.0) {
  830. float t = omni_lights.data[idx].size / max(0.001, light_length);
  831. size_A = max(0.0, 1.0 - 1 / sqrt(1 + t * t));
  832. }
  833. #endif
  834. #ifdef LIGHT_TRANSMITTANCE_USED
  835. float transmittance_z = transmittance_depth; //no transmittance by default
  836. transmittance_color.a *= light_attenuation;
  837. {
  838. vec4 clamp_rect = omni_lights.data[idx].atlas_rect;
  839. //redo shadowmapping, but shrink the model a bit to avoid arctifacts
  840. vec4 splane = (omni_lights.data[idx].shadow_matrix * vec4(vertex - normalize(normal_interp) * omni_lights.data[idx].transmittance_bias, 1.0));
  841. shadow_len = length(splane.xyz);
  842. splane = normalize(splane.xyz);
  843. if (splane.z >= 0.0) {
  844. splane.z += 1.0;
  845. } else {
  846. splane.z = 1.0 - splane.z;
  847. }
  848. splane.xy /= splane.z;
  849. splane.xy = splane.xy * 0.5 + 0.5;
  850. splane.z = shadow_len * omni_lights.data[idx].inv_radius;
  851. splane.xy = clamp_rect.xy + splane.xy * clamp_rect.zw;
  852. splane.w = 1.0; //needed? i think it should be 1 already
  853. float shadow_z = textureLod(sampler2D(shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), splane.xy, 0.0).r;
  854. transmittance_z = (splane.z - shadow_z) / omni_lights.data[idx].inv_radius;
  855. }
  856. #endif
  857. #if 0
  858. if (omni_lights.data[idx].projector_rect != vec4(0.0)) {
  859. vec3 local_v = (omni_lights.data[idx].shadow_matrix * vec4(vertex, 1.0)).xyz;
  860. local_v = normalize(local_v);
  861. vec4 atlas_rect = omni_lights.data[idx].projector_rect;
  862. if (local_v.z >= 0.0) {
  863. local_v.z += 1.0;
  864. atlas_rect.y += atlas_rect.w;
  865. } else {
  866. local_v.z = 1.0 - local_v.z;
  867. }
  868. local_v.xy /= local_v.z;
  869. local_v.xy = local_v.xy * 0.5 + 0.5;
  870. vec2 proj_uv = local_v.xy * atlas_rect.zw;
  871. vec2 proj_uv_ddx;
  872. vec2 proj_uv_ddy;
  873. {
  874. vec3 local_v_ddx = (omni_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddx, 1.0)).xyz;
  875. local_v_ddx = normalize(local_v_ddx);
  876. if (local_v_ddx.z >= 0.0) {
  877. local_v_ddx.z += 1.0;
  878. } else {
  879. local_v_ddx.z = 1.0 - local_v_ddx.z;
  880. }
  881. local_v_ddx.xy /= local_v_ddx.z;
  882. local_v_ddx.xy = local_v_ddx.xy * 0.5 + 0.5;
  883. proj_uv_ddx = local_v_ddx.xy * atlas_rect.zw - proj_uv;
  884. vec3 local_v_ddy = (omni_lights.data[idx].shadow_matrix * vec4(vertex + vertex_ddy, 1.0)).xyz;
  885. local_v_ddy = normalize(local_v_ddy);
  886. if (local_v_ddy.z >= 0.0) {
  887. local_v_ddy.z += 1.0;
  888. } else {
  889. local_v_ddy.z = 1.0 - local_v_ddy.z;
  890. }
  891. local_v_ddy.xy /= local_v_ddy.z;
  892. local_v_ddy.xy = local_v_ddy.xy * 0.5 + 0.5;
  893. proj_uv_ddy = local_v_ddy.xy * atlas_rect.zw - proj_uv;
  894. }
  895. vec4 proj = textureGrad(sampler2D(decal_atlas_srgb, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), proj_uv + atlas_rect.xy, proj_uv_ddx, proj_uv_ddy);
  896. no_shadow = mix(no_shadow, proj.rgb, proj.a);
  897. }
  898. #endif
  899. light_attenuation *= shadow;
  900. light_compute(normal, normalize(light_rel_vec), eye_vec, color, light_attenuation, f0, orms, omni_lights.data[idx].specular_amount,
  901. #ifdef LIGHT_BACKLIGHT_USED
  902. backlight,
  903. #endif
  904. #ifdef LIGHT_TRANSMITTANCE_USED
  905. transmittance_color,
  906. transmittance_depth,
  907. transmittance_curve,
  908. transmittance_boost,
  909. transmittance_z,
  910. #endif
  911. #ifdef LIGHT_RIM_USED
  912. rim * omni_attenuation, rim_tint, rim_color,
  913. #endif
  914. #ifdef LIGHT_CLEARCOAT_USED
  915. clearcoat, clearcoat_gloss,
  916. #endif
  917. #ifdef LIGHT_ANISOTROPY_USED
  918. binormal, tangent, anisotropy,
  919. #endif
  920. #ifdef USE_SOFT_SHADOWS
  921. size_A,
  922. #endif
  923. #ifdef USE_SHADOW_TO_OPACITY
  924. alpha,
  925. #endif
  926. diffuse_light,
  927. specular_light);
  928. }
  929. float light_process_spot_shadow(uint idx, vec3 vertex, vec3 normal) {
  930. #ifndef USE_NO_SHADOWS
  931. if (spot_lights.data[idx].shadow_enabled) {
  932. vec3 light_rel_vec = spot_lights.data[idx].position - vertex;
  933. float light_length = length(light_rel_vec);
  934. vec3 spot_dir = spot_lights.data[idx].direction;
  935. //there is a shadowmap
  936. vec4 v = vec4(vertex, 1.0);
  937. v.xyz -= spot_dir * spot_lights.data[idx].shadow_bias;
  938. float z_norm = dot(spot_dir, -light_rel_vec) * spot_lights.data[idx].inv_radius;
  939. float depth_bias_scale = 1.0 / (max(0.0001, z_norm)); //the closer to the light origin, the more you have to offset to reach 1px in the map
  940. vec3 normal_bias = normalize(normal_interp) * (1.0 - max(0.0, dot(spot_dir, -normalize(normal_interp)))) * spot_lights.data[idx].shadow_normal_bias * depth_bias_scale;
  941. normal_bias -= spot_dir * dot(spot_dir, normal_bias); //only XY, no Z
  942. v.xyz += normal_bias;
  943. //adjust with bias
  944. z_norm = dot(spot_dir, v.xyz - spot_lights.data[idx].position) * spot_lights.data[idx].inv_radius;
  945. float shadow;
  946. vec4 splane = (spot_lights.data[idx].shadow_matrix * v);
  947. splane /= splane.w;
  948. #ifdef USE_SOFT_SHADOWS
  949. if (spot_lights.data[idx].soft_shadow_size > 0.0) {
  950. //soft shadow
  951. //find blocker
  952. vec2 shadow_uv = splane.xy * spot_lights.data[idx].atlas_rect.zw + spot_lights.data[idx].atlas_rect.xy;
  953. float blocker_count = 0.0;
  954. float blocker_average = 0.0;
  955. mat2 disk_rotation;
  956. {
  957. float r = quick_hash(gl_FragCoord.xy) * 2.0 * M_PI;
  958. float sr = sin(r);
  959. float cr = cos(r);
  960. disk_rotation = mat2(vec2(cr, -sr), vec2(sr, cr));
  961. }
  962. float uv_size = spot_lights.data[idx].soft_shadow_size * z_norm * spot_lights.data[idx].soft_shadow_scale;
  963. vec2 clamp_max = spot_lights.data[idx].atlas_rect.xy + spot_lights.data[idx].atlas_rect.zw;
  964. for (uint i = 0; i < scene_data.penumbra_shadow_samples; i++) {
  965. vec2 suv = shadow_uv + (disk_rotation * scene_data.penumbra_shadow_kernel[i].xy) * uv_size;
  966. suv = clamp(suv, spot_lights.data[idx].atlas_rect.xy, clamp_max);
  967. float d = textureLod(sampler2D(shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), suv, 0.0).r;
  968. if (d < z_norm) {
  969. blocker_average += d;
  970. blocker_count += 1.0;
  971. }
  972. }
  973. if (blocker_count > 0.0) {
  974. //blockers found, do soft shadow
  975. blocker_average /= blocker_count;
  976. float penumbra = (z_norm - blocker_average) / blocker_average;
  977. uv_size *= penumbra;
  978. shadow = 0.0;
  979. for (uint i = 0; i < scene_data.penumbra_shadow_samples; i++) {
  980. vec2 suv = shadow_uv + (disk_rotation * scene_data.penumbra_shadow_kernel[i].xy) * uv_size;
  981. suv = clamp(suv, spot_lights.data[idx].atlas_rect.xy, clamp_max);
  982. shadow += textureProj(sampler2DShadow(shadow_atlas, shadow_sampler), vec4(suv, z_norm, 1.0));
  983. }
  984. shadow /= float(scene_data.penumbra_shadow_samples);
  985. } else {
  986. //no blockers found, so no shadow
  987. shadow = 1.0;
  988. }
  989. } else {
  990. #endif
  991. //hard shadow
  992. vec4 shadow_uv = vec4(splane.xy * spot_lights.data[idx].atlas_rect.zw + spot_lights.data[idx].atlas_rect.xy, splane.z, 1.0);
  993. shadow = sample_pcf_shadow(shadow_atlas, spot_lights.data[idx].soft_shadow_scale * scene_data.shadow_atlas_pixel_size, shadow_uv);
  994. #ifdef USE_SOFT_SHADOWS
  995. }
  996. #endif
  997. return shadow;
  998. }
  999. #endif //USE_NO_SHADOWS
  1000. return 1.0;
  1001. }
  1002. void light_process_spot(uint idx, vec3 vertex, vec3 eye_vec, vec3 normal, vec3 vertex_ddx, vec3 vertex_ddy, vec3 f0, uint orms, float shadow,
  1003. #ifdef LIGHT_BACKLIGHT_USED
  1004. vec3 backlight,
  1005. #endif
  1006. #ifdef LIGHT_TRANSMITTANCE_USED
  1007. vec4 transmittance_color,
  1008. float transmittance_depth,
  1009. float transmittance_curve,
  1010. float transmittance_boost,
  1011. #endif
  1012. #ifdef LIGHT_RIM_USED
  1013. float rim, float rim_tint, vec3 rim_color,
  1014. #endif
  1015. #ifdef LIGHT_CLEARCOAT_USED
  1016. float clearcoat, float clearcoat_gloss,
  1017. #endif
  1018. #ifdef LIGHT_ANISOTROPY_USED
  1019. vec3 binormal, vec3 tangent, float anisotropy,
  1020. #endif
  1021. #ifdef USE_SHADOW_TO_OPACITY
  1022. inout float alpha,
  1023. #endif
  1024. inout vec3 diffuse_light,
  1025. inout vec3 specular_light) {
  1026. vec3 light_rel_vec = spot_lights.data[idx].position - vertex;
  1027. float light_length = length(light_rel_vec);
  1028. float spot_attenuation = get_omni_attenuation(light_length, spot_lights.data[idx].inv_radius, spot_lights.data[idx].attenuation);
  1029. vec3 spot_dir = spot_lights.data[idx].direction;
  1030. float scos = max(dot(-normalize(light_rel_vec), spot_dir), spot_lights.data[idx].cone_angle);
  1031. float spot_rim = max(0.0001, (1.0 - scos) / (1.0 - spot_lights.data[idx].cone_angle));
  1032. spot_attenuation *= 1.0 - pow(spot_rim, spot_lights.data[idx].cone_attenuation);
  1033. float light_attenuation = spot_attenuation;
  1034. vec3 color = spot_lights.data[idx].color;
  1035. float specular_amount = spot_lights.data[idx].specular_amount;
  1036. #ifdef USE_SOFT_SHADOWS
  1037. float size_A = 0.0;
  1038. if (spot_lights.data[idx].size > 0.0) {
  1039. float t = spot_lights.data[idx].size / max(0.001, light_length);
  1040. size_A = max(0.0, 1.0 - 1 / sqrt(1 + t * t));
  1041. }
  1042. #endif
  1043. /*
  1044. if (spot_lights.data[idx].atlas_rect!=vec4(0.0)) {
  1045. //use projector texture
  1046. }
  1047. */
  1048. #ifdef LIGHT_TRANSMITTANCE_USED
  1049. float transmittance_z = transmittance_depth;
  1050. transmittance_color.a *= light_attenuation;
  1051. {
  1052. splane = (spot_lights.data[idx].shadow_matrix * vec4(vertex - normalize(normal_interp) * spot_lights.data[idx].transmittance_bias, 1.0));
  1053. splane /= splane.w;
  1054. splane.xy = splane.xy * spot_lights.data[idx].atlas_rect.zw + spot_lights.data[idx].atlas_rect.xy;
  1055. float shadow_z = textureLod(sampler2D(shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), splane.xy, 0.0).r;
  1056. //reconstruct depth
  1057. shadow_z /= spot_lights.data[idx].inv_radius;
  1058. //distance to light plane
  1059. float z = dot(spot_dir, -light_rel_vec);
  1060. transmittance_z = z - shadow_z;
  1061. }
  1062. #endif //LIGHT_TRANSMITTANCE_USED
  1063. light_attenuation *= shadow;
  1064. light_compute(normal, normalize(light_rel_vec), eye_vec, color, light_attenuation, f0, orms, spot_lights.data[idx].specular_amount,
  1065. #ifdef LIGHT_BACKLIGHT_USED
  1066. backlight,
  1067. #endif
  1068. #ifdef LIGHT_TRANSMITTANCE_USED
  1069. transmittance_color,
  1070. transmittance_depth,
  1071. transmittance_curve,
  1072. transmittance_boost,
  1073. transmittance_z,
  1074. #endif
  1075. #ifdef LIGHT_RIM_USED
  1076. rim * spot_attenuation, rim_tint, rim_color,
  1077. #endif
  1078. #ifdef LIGHT_CLEARCOAT_USED
  1079. clearcoat, clearcoat_gloss,
  1080. #endif
  1081. #ifdef LIGHT_ANISOTROPY_USED
  1082. binormal, tangent, anisotropy,
  1083. #endif
  1084. #ifdef USE_SOFT_SHADOW
  1085. size_A,
  1086. #endif
  1087. #ifdef USE_SHADOW_TO_OPACITY
  1088. alpha,
  1089. #endif
  1090. diffuse_light, specular_light);
  1091. }
  1092. void reflection_process(uint ref_index, vec3 vertex, vec3 normal, float roughness, vec3 ambient_light, vec3 specular_light, inout vec4 ambient_accum, inout vec4 reflection_accum) {
  1093. vec3 box_extents = reflections.data[ref_index].box_extents;
  1094. vec3 local_pos = (reflections.data[ref_index].local_matrix * vec4(vertex, 1.0)).xyz;
  1095. if (any(greaterThan(abs(local_pos), box_extents))) { //out of the reflection box
  1096. return;
  1097. }
  1098. vec3 ref_vec = normalize(reflect(vertex, normal));
  1099. vec3 inner_pos = abs(local_pos / box_extents);
  1100. float blend = max(inner_pos.x, max(inner_pos.y, inner_pos.z));
  1101. //make blend more rounded
  1102. blend = mix(length(inner_pos), blend, blend);
  1103. blend *= blend;
  1104. blend = max(0.0, 1.0 - blend);
  1105. if (reflections.data[ref_index].intensity > 0.0) { // compute reflection
  1106. vec3 local_ref_vec = (reflections.data[ref_index].local_matrix * vec4(ref_vec, 0.0)).xyz;
  1107. if (reflections.data[ref_index].box_project) { //box project
  1108. vec3 nrdir = normalize(local_ref_vec);
  1109. vec3 rbmax = (box_extents - local_pos) / nrdir;
  1110. vec3 rbmin = (-box_extents - local_pos) / nrdir;
  1111. vec3 rbminmax = mix(rbmin, rbmax, greaterThan(nrdir, vec3(0.0, 0.0, 0.0)));
  1112. float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);
  1113. vec3 posonbox = local_pos + nrdir * fa;
  1114. local_ref_vec = posonbox - reflections.data[ref_index].box_offset;
  1115. }
  1116. vec4 reflection;
  1117. reflection.rgb = textureLod(samplerCubeArray(reflection_atlas, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), vec4(local_ref_vec, reflections.data[ref_index].index), roughness * MAX_ROUGHNESS_LOD).rgb;
  1118. if (reflections.data[ref_index].exterior) {
  1119. reflection.rgb = mix(specular_light, reflection.rgb, blend);
  1120. }
  1121. reflection.rgb *= reflections.data[ref_index].intensity; //intensity
  1122. reflection.a = blend;
  1123. reflection.rgb *= reflection.a;
  1124. reflection_accum += reflection;
  1125. }
  1126. switch (reflections.data[ref_index].ambient_mode) {
  1127. case REFLECTION_AMBIENT_DISABLED: {
  1128. //do nothing
  1129. } break;
  1130. case REFLECTION_AMBIENT_ENVIRONMENT: {
  1131. //do nothing
  1132. vec3 local_amb_vec = (reflections.data[ref_index].local_matrix * vec4(normal, 0.0)).xyz;
  1133. vec4 ambient_out;
  1134. ambient_out.rgb = textureLod(samplerCubeArray(reflection_atlas, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), vec4(local_amb_vec, reflections.data[ref_index].index), MAX_ROUGHNESS_LOD).rgb;
  1135. ambient_out.a = blend;
  1136. if (reflections.data[ref_index].exterior) {
  1137. ambient_out.rgb = mix(ambient_light, ambient_out.rgb, blend);
  1138. }
  1139. ambient_out.rgb *= ambient_out.a;
  1140. ambient_accum += ambient_out;
  1141. } break;
  1142. case REFLECTION_AMBIENT_COLOR: {
  1143. vec4 ambient_out;
  1144. ambient_out.a = blend;
  1145. ambient_out.rgb = reflections.data[ref_index].ambient;
  1146. if (reflections.data[ref_index].exterior) {
  1147. ambient_out.rgb = mix(ambient_light, ambient_out.rgb, blend);
  1148. }
  1149. ambient_out.rgb *= ambient_out.a;
  1150. ambient_accum += ambient_out;
  1151. } break;
  1152. }
  1153. }
  1154. #ifdef USE_FORWARD_GI
  1155. //standard voxel cone trace
  1156. vec4 voxel_cone_trace(texture3D probe, vec3 cell_size, vec3 pos, vec3 direction, float tan_half_angle, float max_distance, float p_bias) {
  1157. float dist = p_bias;
  1158. vec4 color = vec4(0.0);
  1159. while (dist < max_distance && color.a < 0.95) {
  1160. float diameter = max(1.0, 2.0 * tan_half_angle * dist);
  1161. vec3 uvw_pos = (pos + dist * direction) * cell_size;
  1162. float half_diameter = diameter * 0.5;
  1163. //check if outside, then break
  1164. if (any(greaterThan(abs(uvw_pos - 0.5), vec3(0.5f + half_diameter * cell_size)))) {
  1165. break;
  1166. }
  1167. vec4 scolor = textureLod(sampler3D(probe, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uvw_pos, log2(diameter));
  1168. float a = (1.0 - color.a);
  1169. color += a * scolor;
  1170. dist += half_diameter;
  1171. }
  1172. return color;
  1173. }
  1174. vec4 voxel_cone_trace_45_degrees(texture3D probe, vec3 cell_size, vec3 pos, vec3 direction, float tan_half_angle, float max_distance, float p_bias) {
  1175. float dist = p_bias;
  1176. vec4 color = vec4(0.0);
  1177. float radius = max(0.5, tan_half_angle * dist);
  1178. float lod_level = log2(radius * 2.0);
  1179. while (dist < max_distance && color.a < 0.95) {
  1180. vec3 uvw_pos = (pos + dist * direction) * cell_size;
  1181. //check if outside, then break
  1182. if (any(greaterThan(abs(uvw_pos - 0.5), vec3(0.5f + radius * cell_size)))) {
  1183. break;
  1184. }
  1185. vec4 scolor = textureLod(sampler3D(probe, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uvw_pos, lod_level);
  1186. lod_level += 1.0;
  1187. float a = (1.0 - color.a);
  1188. scolor *= a;
  1189. color += scolor;
  1190. dist += radius;
  1191. radius = max(0.5, tan_half_angle * dist);
  1192. }
  1193. return color;
  1194. }
  1195. void gi_probe_compute(uint index, vec3 position, vec3 normal, vec3 ref_vec, mat3 normal_xform, float roughness, vec3 ambient, vec3 environment, inout vec4 out_spec, inout vec4 out_diff) {
  1196. position = (gi_probes.data[index].xform * vec4(position, 1.0)).xyz;
  1197. ref_vec = normalize((gi_probes.data[index].xform * vec4(ref_vec, 0.0)).xyz);
  1198. normal = normalize((gi_probes.data[index].xform * vec4(normal, 0.0)).xyz);
  1199. position += normal * gi_probes.data[index].normal_bias;
  1200. //this causes corrupted pixels, i have no idea why..
  1201. if (any(bvec2(any(lessThan(position, vec3(0.0))), any(greaterThan(position, gi_probes.data[index].bounds))))) {
  1202. return;
  1203. }
  1204. vec3 blendv = abs(position / gi_probes.data[index].bounds * 2.0 - 1.0);
  1205. float blend = clamp(1.0 - max(blendv.x, max(blendv.y, blendv.z)), 0.0, 1.0);
  1206. //float blend=1.0;
  1207. float max_distance = length(gi_probes.data[index].bounds);
  1208. vec3 cell_size = 1.0 / gi_probes.data[index].bounds;
  1209. //radiance
  1210. #define MAX_CONE_DIRS 4
  1211. vec3 cone_dirs[MAX_CONE_DIRS] = vec3[](
  1212. vec3(0.707107, 0.0, 0.707107),
  1213. vec3(0.0, 0.707107, 0.707107),
  1214. vec3(-0.707107, 0.0, 0.707107),
  1215. vec3(0.0, -0.707107, 0.707107));
  1216. float cone_weights[MAX_CONE_DIRS] = float[](0.25, 0.25, 0.25, 0.25);
  1217. float cone_angle_tan = 0.98269;
  1218. vec3 light = vec3(0.0);
  1219. for (int i = 0; i < MAX_CONE_DIRS; i++) {
  1220. vec3 dir = normalize((gi_probes.data[index].xform * vec4(normal_xform * cone_dirs[i], 0.0)).xyz);
  1221. vec4 cone_light = voxel_cone_trace_45_degrees(gi_probe_textures[index], cell_size, position, dir, cone_angle_tan, max_distance, gi_probes.data[index].bias);
  1222. if (gi_probes.data[index].blend_ambient) {
  1223. cone_light.rgb = mix(ambient, cone_light.rgb, min(1.0, cone_light.a / 0.95));
  1224. }
  1225. light += cone_weights[i] * cone_light.rgb;
  1226. }
  1227. light *= gi_probes.data[index].dynamic_range;
  1228. out_diff += vec4(light * blend, blend);
  1229. //irradiance
  1230. vec4 irr_light = voxel_cone_trace(gi_probe_textures[index], cell_size, position, ref_vec, tan(roughness * 0.5 * M_PI * 0.99), max_distance, gi_probes.data[index].bias);
  1231. if (gi_probes.data[index].blend_ambient) {
  1232. irr_light.rgb = mix(environment, irr_light.rgb, min(1.0, irr_light.a / 0.95));
  1233. }
  1234. irr_light.rgb *= gi_probes.data[index].dynamic_range;
  1235. //irr_light=vec3(0.0);
  1236. out_spec += vec4(irr_light.rgb * blend, blend);
  1237. }
  1238. vec2 octahedron_wrap(vec2 v) {
  1239. vec2 signVal;
  1240. signVal.x = v.x >= 0.0 ? 1.0 : -1.0;
  1241. signVal.y = v.y >= 0.0 ? 1.0 : -1.0;
  1242. return (1.0 - abs(v.yx)) * signVal;
  1243. }
  1244. vec2 octahedron_encode(vec3 n) {
  1245. // https://twitter.com/Stubbesaurus/status/937994790553227264
  1246. n /= (abs(n.x) + abs(n.y) + abs(n.z));
  1247. n.xy = n.z >= 0.0 ? n.xy : octahedron_wrap(n.xy);
  1248. n.xy = n.xy * 0.5 + 0.5;
  1249. return n.xy;
  1250. }
  1251. void sdfgi_process(uint cascade, vec3 cascade_pos, vec3 cam_pos, vec3 cam_normal, vec3 cam_specular_normal, bool use_specular, float roughness, out vec3 diffuse_light, out vec3 specular_light, out float blend) {
  1252. cascade_pos += cam_normal * sdfgi.normal_bias;
  1253. vec3 base_pos = floor(cascade_pos);
  1254. //cascade_pos += mix(vec3(0.0),vec3(0.01),lessThan(abs(cascade_pos-base_pos),vec3(0.01))) * cam_normal;
  1255. ivec3 probe_base_pos = ivec3(base_pos);
  1256. vec4 diffuse_accum = vec4(0.0);
  1257. vec3 specular_accum;
  1258. ivec3 tex_pos = ivec3(probe_base_pos.xy, int(cascade));
  1259. tex_pos.x += probe_base_pos.z * sdfgi.probe_axis_size;
  1260. tex_pos.xy = tex_pos.xy * (SDFGI_OCT_SIZE + 2) + ivec2(1);
  1261. vec3 diffuse_posf = (vec3(tex_pos) + vec3(octahedron_encode(cam_normal) * float(SDFGI_OCT_SIZE), 0.0)) * sdfgi.lightprobe_tex_pixel_size;
  1262. vec3 specular_posf;
  1263. if (use_specular) {
  1264. specular_accum = vec3(0.0);
  1265. specular_posf = (vec3(tex_pos) + vec3(octahedron_encode(cam_specular_normal) * float(SDFGI_OCT_SIZE), 0.0)) * sdfgi.lightprobe_tex_pixel_size;
  1266. }
  1267. vec4 light_accum = vec4(0.0);
  1268. float weight_accum = 0.0;
  1269. for (uint j = 0; j < 8; j++) {
  1270. ivec3 offset = (ivec3(j) >> ivec3(0, 1, 2)) & ivec3(1, 1, 1);
  1271. ivec3 probe_posi = probe_base_pos;
  1272. probe_posi += offset;
  1273. // Compute weight
  1274. vec3 probe_pos = vec3(probe_posi);
  1275. vec3 probe_to_pos = cascade_pos - probe_pos;
  1276. vec3 probe_dir = normalize(-probe_to_pos);
  1277. vec3 trilinear = vec3(1.0) - abs(probe_to_pos);
  1278. float weight = trilinear.x * trilinear.y * trilinear.z * max(0.005, dot(cam_normal, probe_dir));
  1279. // Compute lightprobe occlusion
  1280. if (sdfgi.use_occlusion) {
  1281. ivec3 occ_indexv = abs((sdfgi.cascades[cascade].probe_world_offset + probe_posi) & ivec3(1, 1, 1)) * ivec3(1, 2, 4);
  1282. vec4 occ_mask = mix(vec4(0.0), vec4(1.0), equal(ivec4(occ_indexv.x | occ_indexv.y), ivec4(0, 1, 2, 3)));
  1283. vec3 occ_pos = clamp(cascade_pos, probe_pos - sdfgi.occlusion_clamp, probe_pos + sdfgi.occlusion_clamp) * sdfgi.probe_to_uvw;
  1284. occ_pos.z += float(cascade);
  1285. if (occ_indexv.z != 0) { //z bit is on, means index is >=4, so make it switch to the other half of textures
  1286. occ_pos.x += 1.0;
  1287. }
  1288. occ_pos *= sdfgi.occlusion_renormalize;
  1289. float occlusion = dot(textureLod(sampler3D(sdfgi_occlusion_cascades, material_samplers[SAMPLER_LINEAR_CLAMP]), occ_pos, 0.0), occ_mask);
  1290. weight *= max(occlusion, 0.01);
  1291. }
  1292. // Compute lightprobe texture position
  1293. vec3 diffuse;
  1294. vec3 pos_uvw = diffuse_posf;
  1295. pos_uvw.xy += vec2(offset.xy) * sdfgi.lightprobe_uv_offset.xy;
  1296. pos_uvw.x += float(offset.z) * sdfgi.lightprobe_uv_offset.z;
  1297. diffuse = textureLod(sampler2DArray(sdfgi_lightprobe_texture, material_samplers[SAMPLER_LINEAR_CLAMP]), pos_uvw, 0.0).rgb;
  1298. diffuse_accum += vec4(diffuse * weight, weight);
  1299. if (use_specular) {
  1300. vec3 specular = vec3(0.0);
  1301. vec3 pos_uvw = specular_posf;
  1302. pos_uvw.xy += vec2(offset.xy) * sdfgi.lightprobe_uv_offset.xy;
  1303. pos_uvw.x += float(offset.z) * sdfgi.lightprobe_uv_offset.z;
  1304. if (roughness < 0.99) {
  1305. specular = textureLod(sampler2DArray(sdfgi_lightprobe_texture, material_samplers[SAMPLER_LINEAR_CLAMP]), pos_uvw + vec3(0, 0, float(sdfgi.max_cascades)), 0.0).rgb;
  1306. }
  1307. if (roughness > 0.5) {
  1308. specular = mix(specular, textureLod(sampler2DArray(sdfgi_lightprobe_texture, material_samplers[SAMPLER_LINEAR_CLAMP]), pos_uvw, 0.0).rgb, (roughness - 0.5) * 2.0);
  1309. }
  1310. specular_accum += specular * weight;
  1311. }
  1312. }
  1313. if (diffuse_accum.a > 0.0) {
  1314. diffuse_accum.rgb /= diffuse_accum.a;
  1315. }
  1316. diffuse_light = diffuse_accum.rgb;
  1317. if (use_specular) {
  1318. if (diffuse_accum.a > 0.0) {
  1319. specular_accum /= diffuse_accum.a;
  1320. }
  1321. specular_light = specular_accum;
  1322. }
  1323. {
  1324. //process blend
  1325. float blend_from = (float(sdfgi.probe_axis_size - 1) / 2.0) - 2.5;
  1326. float blend_to = blend_from + 2.0;
  1327. vec3 inner_pos = cam_pos * sdfgi.cascades[cascade].to_probe;
  1328. float len = length(inner_pos);
  1329. inner_pos = abs(normalize(inner_pos));
  1330. len *= max(inner_pos.x, max(inner_pos.y, inner_pos.z));
  1331. if (len >= blend_from) {
  1332. blend = smoothstep(blend_from, blend_to, len);
  1333. } else {
  1334. blend = 0.0;
  1335. }
  1336. }
  1337. }
  1338. #endif //USE_FORWARD_GI
  1339. #endif //!defined(MODE_RENDER_DEPTH) && !defined(MODE_UNSHADED)
  1340. #ifndef MODE_RENDER_DEPTH
  1341. #ifndef LOW_END_MODE
  1342. vec4 volumetric_fog_process(vec2 screen_uv, float z) {
  1343. vec3 fog_pos = vec3(screen_uv, z * scene_data.volumetric_fog_inv_length);
  1344. if (fog_pos.z < 0.0) {
  1345. return vec4(0.0);
  1346. } else if (fog_pos.z < 1.0) {
  1347. fog_pos.z = pow(fog_pos.z, scene_data.volumetric_fog_detail_spread);
  1348. }
  1349. return texture(sampler3D(volumetric_fog_texture, material_samplers[SAMPLER_LINEAR_CLAMP]), fog_pos);
  1350. }
  1351. #endif
  1352. vec4 fog_process(vec3 vertex) {
  1353. vec3 fog_color = scene_data.fog_light_color;
  1354. if (scene_data.fog_aerial_perspective > 0.0) {
  1355. vec3 sky_fog_color = vec3(0.0);
  1356. vec3 cube_view = scene_data.radiance_inverse_xform * vertex;
  1357. // mip_level always reads from the second mipmap and higher so the fog is always slightly blurred
  1358. float mip_level = mix(1.0 / MAX_ROUGHNESS_LOD, 1.0, 1.0 - (abs(vertex.z) - scene_data.z_near) / (scene_data.z_far - scene_data.z_near));
  1359. #ifdef USE_RADIANCE_CUBEMAP_ARRAY
  1360. float lod, blend;
  1361. blend = modf(mip_level * MAX_ROUGHNESS_LOD, lod);
  1362. sky_fog_color = texture(samplerCubeArray(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), vec4(cube_view, lod)).rgb;
  1363. sky_fog_color = mix(sky_fog_color, texture(samplerCubeArray(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), vec4(cube_view, lod + 1)).rgb, blend);
  1364. #else
  1365. sky_fog_color = textureLod(samplerCube(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), cube_view, mip_level * MAX_ROUGHNESS_LOD).rgb;
  1366. #endif //USE_RADIANCE_CUBEMAP_ARRAY
  1367. fog_color = mix(fog_color, sky_fog_color, scene_data.fog_aerial_perspective);
  1368. }
  1369. if (scene_data.fog_sun_scatter > 0.001) {
  1370. vec4 sun_scatter = vec4(0.0);
  1371. float sun_total = 0.0;
  1372. vec3 view = normalize(vertex);
  1373. for (uint i = 0; i < scene_data.directional_light_count; i++) {
  1374. vec3 light_color = directional_lights.data[i].color * directional_lights.data[i].energy;
  1375. float light_amount = pow(max(dot(view, directional_lights.data[i].direction), 0.0), 8.0);
  1376. fog_color += light_color * light_amount * scene_data.fog_sun_scatter;
  1377. }
  1378. }
  1379. float fog_amount = 1.0 - exp(min(0.0, vertex.z * scene_data.fog_density));
  1380. if (abs(scene_data.fog_height_density) > 0.001) {
  1381. float y = (scene_data.camera_matrix * vec4(vertex, 1.0)).y;
  1382. float y_dist = scene_data.fog_height - y;
  1383. float vfog_amount = clamp(exp(y_dist * scene_data.fog_height_density), 0.0, 1.0);
  1384. fog_amount = max(vfog_amount, fog_amount);
  1385. }
  1386. return vec4(fog_color, fog_amount);
  1387. }
  1388. void cluster_get_item_range(uint p_offset, out uint item_min, out uint item_max, out uint item_from, out uint item_to) {
  1389. uint item_min_max = cluster_buffer.data[p_offset];
  1390. item_min = item_min_max & 0xFFFF;
  1391. item_max = item_min_max >> 16;
  1392. ;
  1393. item_from = item_min >> 5;
  1394. item_to = (item_max == 0) ? 0 : ((item_max - 1) >> 5) + 1; //side effect of how it is stored, as item_max 0 means no elements
  1395. }
  1396. uint cluster_get_range_clip_mask(uint i, uint z_min, uint z_max) {
  1397. int local_min = clamp(int(z_min) - int(i) * 32, 0, 31);
  1398. int mask_width = min(int(z_max) - int(z_min), 32 - local_min);
  1399. return bitfieldInsert(uint(0), uint(0xFFFFFFFF), local_min, mask_width);
  1400. }
  1401. float blur_shadow(float shadow) {
  1402. return shadow;
  1403. #if 0
  1404. //disabling for now, will investigate later
  1405. float interp_shadow = shadow;
  1406. if (gl_HelperInvocation) {
  1407. interp_shadow = -4.0; // technically anything below -4 will do but just to make sure
  1408. }
  1409. uvec2 fc2 = uvec2(gl_FragCoord.xy);
  1410. interp_shadow -= dFdx(interp_shadow) * (float(fc2.x & 1) - 0.5);
  1411. interp_shadow -= dFdy(interp_shadow) * (float(fc2.y & 1) - 0.5);
  1412. if (interp_shadow >= 0.0) {
  1413. shadow = interp_shadow;
  1414. }
  1415. return shadow;
  1416. #endif
  1417. }
  1418. #endif //!MODE_RENDER DEPTH
  1419. void main() {
  1420. #ifdef MODE_DUAL_PARABOLOID
  1421. if (dp_clip > 0.0)
  1422. discard;
  1423. #endif
  1424. //lay out everything, whathever is unused is optimized away anyway
  1425. vec3 vertex = vertex_interp;
  1426. vec3 view = -normalize(vertex_interp);
  1427. vec3 albedo = vec3(1.0);
  1428. vec3 backlight = vec3(0.0);
  1429. vec4 transmittance_color = vec4(0.0);
  1430. float transmittance_depth = 0.0;
  1431. float transmittance_curve = 1.0;
  1432. float transmittance_boost = 0.0;
  1433. float metallic = 0.0;
  1434. float specular = 0.5;
  1435. vec3 emission = vec3(0.0);
  1436. float roughness = 1.0;
  1437. float rim = 0.0;
  1438. float rim_tint = 0.0;
  1439. float clearcoat = 0.0;
  1440. float clearcoat_gloss = 0.0;
  1441. float anisotropy = 0.0;
  1442. vec2 anisotropy_flow = vec2(1.0, 0.0);
  1443. vec4 fog = vec4(0.0);
  1444. #if defined(CUSTOM_RADIANCE_USED)
  1445. vec4 custom_radiance = vec4(0.0);
  1446. #endif
  1447. #if defined(CUSTOM_IRRADIANCE_USED)
  1448. vec4 custom_irradiance = vec4(0.0);
  1449. #endif
  1450. float ao = 1.0;
  1451. float ao_light_affect = 0.0;
  1452. float alpha = 1.0;
  1453. #if defined(TANGENT_USED) || defined(NORMAL_MAP_USED) || defined(LIGHT_ANISOTROPY_USED)
  1454. vec3 binormal = normalize(binormal_interp);
  1455. vec3 tangent = normalize(tangent_interp);
  1456. #else
  1457. vec3 binormal = vec3(0.0);
  1458. vec3 tangent = vec3(0.0);
  1459. #endif
  1460. #ifdef NORMAL_USED
  1461. vec3 normal = normalize(normal_interp);
  1462. #if defined(DO_SIDE_CHECK)
  1463. if (!gl_FrontFacing) {
  1464. normal = -normal;
  1465. }
  1466. #endif
  1467. #endif //NORMAL_USED
  1468. #ifdef UV_USED
  1469. vec2 uv = uv_interp;
  1470. #endif
  1471. #if defined(UV2_USED) || defined(USE_LIGHTMAP)
  1472. vec2 uv2 = uv2_interp;
  1473. #endif
  1474. #if defined(COLOR_USED)
  1475. vec4 color = color_interp;
  1476. #endif
  1477. #if defined(NORMAL_MAP_USED)
  1478. vec3 normal_map = vec3(0.5);
  1479. #endif
  1480. float normal_map_depth = 1.0;
  1481. vec2 screen_uv = gl_FragCoord.xy * scene_data.screen_pixel_size + scene_data.screen_pixel_size * 0.5; //account for center
  1482. float sss_strength = 0.0;
  1483. #ifdef ALPHA_SCISSOR_USED
  1484. float alpha_scissor_threshold = 1.0;
  1485. #endif // ALPHA_SCISSOR_USED
  1486. #ifdef ALPHA_HASH_USED
  1487. float alpha_hash_scale = 1.0;
  1488. #endif // ALPHA_HASH_USED
  1489. #ifdef ALPHA_ANTIALIASING_EDGE_USED
  1490. float alpha_antialiasing_edge = 0.0;
  1491. vec2 alpha_texture_coordinate = vec2(0.0, 0.0);
  1492. #endif // ALPHA_ANTIALIASING_EDGE_USED
  1493. {
  1494. /* clang-format off */
  1495. FRAGMENT_SHADER_CODE
  1496. /* clang-format on */
  1497. }
  1498. #ifdef LIGHT_TRANSMITTANCE_USED
  1499. #ifdef SSS_MODE_SKIN
  1500. transmittance_color.a = sss_strength;
  1501. #else
  1502. transmittance_color.a *= sss_strength;
  1503. #endif
  1504. #endif
  1505. #ifndef USE_SHADOW_TO_OPACITY
  1506. #ifdef ALPHA_SCISSOR_USED
  1507. if (alpha < alpha_scissor_threshold) {
  1508. discard;
  1509. }
  1510. #endif // ALPHA_SCISSOR_USED
  1511. // alpha hash can be used in unison with alpha antialiasing
  1512. #ifdef ALPHA_HASH_USED
  1513. if (alpha < compute_alpha_hash_threshold(vertex, alpha_hash_scale)) {
  1514. discard;
  1515. }
  1516. #endif // ALPHA_HASH_USED
  1517. // If we are not edge antialiasing, we need to remove the output alpha channel from scissor and hash
  1518. #if (defined(ALPHA_SCISSOR_USED) || defined(ALPHA_HASH_USED)) && !defined(ALPHA_ANTIALIASING_EDGE_USED)
  1519. alpha = 1.0;
  1520. #endif
  1521. #ifdef ALPHA_ANTIALIASING_EDGE_USED
  1522. // If alpha scissor is used, we must further the edge threshold, otherwise we wont get any edge feather
  1523. #ifdef ALPHA_SCISSOR_USED
  1524. alpha_antialiasing_edge = clamp(alpha_scissor_threshold + alpha_antialiasing_edge, 0.0, 1.0);
  1525. #endif
  1526. alpha = compute_alpha_antialiasing_edge(alpha, alpha_texture_coordinate, alpha_antialiasing_edge);
  1527. #endif // ALPHA_ANTIALIASING_EDGE_USED
  1528. #ifdef USE_OPAQUE_PREPASS
  1529. if (alpha < opaque_prepass_threshold) {
  1530. discard;
  1531. }
  1532. #endif // USE_OPAQUE_PREPASS
  1533. #endif // !USE_SHADOW_TO_OPACITY
  1534. #ifdef NORMAL_MAP_USED
  1535. normal_map.xy = normal_map.xy * 2.0 - 1.0;
  1536. normal_map.z = sqrt(max(0.0, 1.0 - dot(normal_map.xy, normal_map.xy))); //always ignore Z, as it can be RG packed, Z may be pos/neg, etc.
  1537. normal = normalize(mix(normal, tangent * normal_map.x + binormal * normal_map.y + normal * normal_map.z, normal_map_depth));
  1538. #endif
  1539. #ifdef LIGHT_ANISOTROPY_USED
  1540. if (anisotropy > 0.01) {
  1541. //rotation matrix
  1542. mat3 rot = mat3(tangent, binormal, normal);
  1543. //make local to space
  1544. tangent = normalize(rot * vec3(anisotropy_flow.x, anisotropy_flow.y, 0.0));
  1545. binormal = normalize(rot * vec3(-anisotropy_flow.y, anisotropy_flow.x, 0.0));
  1546. }
  1547. #endif
  1548. #ifdef ENABLE_CLIP_ALPHA
  1549. if (albedo.a < 0.99) {
  1550. //used for doublepass and shadowmapping
  1551. discard;
  1552. }
  1553. #endif
  1554. /////////////////////// FOG //////////////////////
  1555. #ifndef MODE_RENDER_DEPTH
  1556. #ifndef CUSTOM_FOG_USED
  1557. // fog must be processed as early as possible and then packed.
  1558. // to maximize VGPR usage
  1559. // Draw "fixed" fog before volumetric fog to ensure volumetric fog can appear in front of the sky.
  1560. if (scene_data.fog_enabled) {
  1561. fog = fog_process(vertex);
  1562. }
  1563. #ifndef LOW_END_MODE
  1564. if (scene_data.volumetric_fog_enabled) {
  1565. vec4 volumetric_fog = volumetric_fog_process(screen_uv, -vertex.z);
  1566. if (scene_data.fog_enabled) {
  1567. //must use the full blending equation here to blend fogs
  1568. vec4 res;
  1569. float sa = 1.0 - volumetric_fog.a;
  1570. res.a = fog.a * sa + volumetric_fog.a;
  1571. if (res.a == 0.0) {
  1572. res.rgb = vec3(0.0);
  1573. } else {
  1574. res.rgb = (fog.rgb * fog.a * sa + volumetric_fog.rgb * volumetric_fog.a) / res.a;
  1575. }
  1576. fog = res;
  1577. } else {
  1578. fog = volumetric_fog;
  1579. }
  1580. }
  1581. #endif //!LOW_END_MODE
  1582. #endif //!CUSTOM_FOG_USED
  1583. uint fog_rg = packHalf2x16(fog.rg);
  1584. uint fog_ba = packHalf2x16(fog.ba);
  1585. #endif //!MODE_RENDER_DEPTH
  1586. /////////////////////// DECALS ////////////////////////////////
  1587. #ifndef MODE_RENDER_DEPTH
  1588. uvec2 cluster_pos = uvec2(gl_FragCoord.xy) >> scene_data.cluster_shift;
  1589. uint cluster_offset = (scene_data.cluster_width * cluster_pos.y + cluster_pos.x) * (scene_data.max_cluster_element_count_div_32 + 32);
  1590. uint cluster_z = uint(clamp((-vertex.z / scene_data.z_far) * 32.0, 0.0, 31.0));
  1591. //used for interpolating anything cluster related
  1592. vec3 vertex_ddx = dFdx(vertex);
  1593. vec3 vertex_ddy = dFdy(vertex);
  1594. { // process decals
  1595. uint cluster_decal_offset = cluster_offset + scene_data.cluster_type_size * 2;
  1596. uint item_min;
  1597. uint item_max;
  1598. uint item_from;
  1599. uint item_to;
  1600. cluster_get_item_range(cluster_decal_offset + scene_data.max_cluster_element_count_div_32 + cluster_z, item_min, item_max, item_from, item_to);
  1601. #ifdef USE_SUBGROUPS
  1602. item_from = subgroupBroadcastFirst(subgroupMin(item_from));
  1603. item_to = subgroupBroadcastFirst(subgroupMax(item_to));
  1604. #endif
  1605. for (uint i = item_from; i < item_to; i++) {
  1606. uint mask = cluster_buffer.data[cluster_decal_offset + i];
  1607. mask &= cluster_get_range_clip_mask(i, item_min, item_max);
  1608. #ifdef USE_SUBGROUPS
  1609. uint merged_mask = subgroupBroadcastFirst(subgroupOr(mask));
  1610. #else
  1611. uint merged_mask = mask;
  1612. #endif
  1613. while (merged_mask != 0) {
  1614. uint bit = findMSB(merged_mask);
  1615. merged_mask &= ~(1 << bit);
  1616. #ifdef USE_SUBGROUPS
  1617. if (((1 << bit) & mask) == 0) { //do not process if not originally here
  1618. continue;
  1619. }
  1620. #endif
  1621. uint decal_index = 32 * i + bit;
  1622. if (!bool(decals.data[decal_index].mask & instances.data[instance_index].layer_mask)) {
  1623. continue; //not masked
  1624. }
  1625. vec3 uv_local = (decals.data[decal_index].xform * vec4(vertex, 1.0)).xyz;
  1626. if (any(lessThan(uv_local, vec3(0.0, -1.0, 0.0))) || any(greaterThan(uv_local, vec3(1.0)))) {
  1627. continue; //out of decal
  1628. }
  1629. //we need ddx/ddy for mipmaps, so simulate them
  1630. vec2 ddx = (decals.data[decal_index].xform * vec4(vertex_ddx, 0.0)).xz;
  1631. vec2 ddy = (decals.data[decal_index].xform * vec4(vertex_ddy, 0.0)).xz;
  1632. float fade = pow(1.0 - (uv_local.y > 0.0 ? uv_local.y : -uv_local.y), uv_local.y > 0.0 ? decals.data[decal_index].upper_fade : decals.data[decal_index].lower_fade);
  1633. if (decals.data[decal_index].normal_fade > 0.0) {
  1634. fade *= smoothstep(decals.data[decal_index].normal_fade, 1.0, dot(normal_interp, decals.data[decal_index].normal) * 0.5 + 0.5);
  1635. }
  1636. if (decals.data[decal_index].albedo_rect != vec4(0.0)) {
  1637. //has albedo
  1638. vec4 decal_albedo = textureGrad(sampler2D(decal_atlas_srgb, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uv_local.xz * decals.data[decal_index].albedo_rect.zw + decals.data[decal_index].albedo_rect.xy, ddx * decals.data[decal_index].albedo_rect.zw, ddy * decals.data[decal_index].albedo_rect.zw);
  1639. decal_albedo *= decals.data[decal_index].modulate;
  1640. decal_albedo.a *= fade;
  1641. albedo = mix(albedo, decal_albedo.rgb, decal_albedo.a * decals.data[decal_index].albedo_mix);
  1642. if (decals.data[decal_index].normal_rect != vec4(0.0)) {
  1643. vec3 decal_normal = textureGrad(sampler2D(decal_atlas, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uv_local.xz * decals.data[decal_index].normal_rect.zw + decals.data[decal_index].normal_rect.xy, ddx * decals.data[decal_index].normal_rect.zw, ddy * decals.data[decal_index].normal_rect.zw).xyz;
  1644. decal_normal.xy = decal_normal.xy * vec2(2.0, -2.0) - vec2(1.0, -1.0); //users prefer flipped y normal maps in most authoring software
  1645. decal_normal.z = sqrt(max(0.0, 1.0 - dot(decal_normal.xy, decal_normal.xy)));
  1646. //convert to view space, use xzy because y is up
  1647. decal_normal = (decals.data[decal_index].normal_xform * decal_normal.xzy).xyz;
  1648. normal = normalize(mix(normal, decal_normal, decal_albedo.a));
  1649. }
  1650. if (decals.data[decal_index].orm_rect != vec4(0.0)) {
  1651. vec3 decal_orm = textureGrad(sampler2D(decal_atlas, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uv_local.xz * decals.data[decal_index].orm_rect.zw + decals.data[decal_index].orm_rect.xy, ddx * decals.data[decal_index].orm_rect.zw, ddy * decals.data[decal_index].orm_rect.zw).xyz;
  1652. ao = mix(ao, decal_orm.r, decal_albedo.a);
  1653. roughness = mix(roughness, decal_orm.g, decal_albedo.a);
  1654. metallic = mix(metallic, decal_orm.b, decal_albedo.a);
  1655. }
  1656. }
  1657. if (decals.data[decal_index].emission_rect != vec4(0.0)) {
  1658. //emission is additive, so its independent from albedo
  1659. emission += textureGrad(sampler2D(decal_atlas_srgb, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), uv_local.xz * decals.data[decal_index].emission_rect.zw + decals.data[decal_index].emission_rect.xy, ddx * decals.data[decal_index].emission_rect.zw, ddy * decals.data[decal_index].emission_rect.zw).xyz * decals.data[decal_index].emission_energy * fade;
  1660. }
  1661. }
  1662. }
  1663. }
  1664. //pack albedo until needed again, saves 2 VGPRs in the meantime
  1665. #endif //not render depth
  1666. /////////////////////// LIGHTING //////////////////////////////
  1667. #ifdef NORMAL_USED
  1668. if (scene_data.roughness_limiter_enabled) {
  1669. //http://www.jp.square-enix.com/tech/library/pdf/ImprovedGeometricSpecularAA.pdf
  1670. float roughness2 = roughness * roughness;
  1671. vec3 dndu = dFdx(normal), dndv = dFdx(normal);
  1672. float variance = scene_data.roughness_limiter_amount * (dot(dndu, dndu) + dot(dndv, dndv));
  1673. float kernelRoughness2 = min(2.0 * variance, scene_data.roughness_limiter_limit); //limit effect
  1674. float filteredRoughness2 = min(1.0, roughness2 + kernelRoughness2);
  1675. roughness = sqrt(filteredRoughness2);
  1676. }
  1677. #endif
  1678. //apply energy conservation
  1679. vec3 specular_light = vec3(0.0, 0.0, 0.0);
  1680. vec3 diffuse_light = vec3(0.0, 0.0, 0.0);
  1681. vec3 ambient_light = vec3(0.0, 0.0, 0.0);
  1682. #if !defined(MODE_RENDER_DEPTH) && !defined(MODE_UNSHADED)
  1683. if (scene_data.use_reflection_cubemap) {
  1684. vec3 ref_vec = reflect(-view, normal);
  1685. ref_vec = scene_data.radiance_inverse_xform * ref_vec;
  1686. #ifdef USE_RADIANCE_CUBEMAP_ARRAY
  1687. float lod, blend;
  1688. blend = modf(roughness * MAX_ROUGHNESS_LOD, lod);
  1689. specular_light = texture(samplerCubeArray(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), vec4(ref_vec, lod)).rgb;
  1690. specular_light = mix(specular_light, texture(samplerCubeArray(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), vec4(ref_vec, lod + 1)).rgb, blend);
  1691. #else
  1692. specular_light = textureLod(samplerCube(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), ref_vec, roughness * MAX_ROUGHNESS_LOD).rgb;
  1693. #endif //USE_RADIANCE_CUBEMAP_ARRAY
  1694. specular_light *= scene_data.ambient_light_color_energy.a;
  1695. }
  1696. #if defined(CUSTOM_RADIANCE_USED)
  1697. specular_light = mix(specular_light, custom_radiance.rgb, custom_radiance.a);
  1698. #endif
  1699. #ifndef USE_LIGHTMAP
  1700. //lightmap overrides everything
  1701. if (scene_data.use_ambient_light) {
  1702. ambient_light = scene_data.ambient_light_color_energy.rgb;
  1703. if (scene_data.use_ambient_cubemap) {
  1704. vec3 ambient_dir = scene_data.radiance_inverse_xform * normal;
  1705. #ifdef USE_RADIANCE_CUBEMAP_ARRAY
  1706. vec3 cubemap_ambient = texture(samplerCubeArray(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), vec4(ambient_dir, MAX_ROUGHNESS_LOD)).rgb;
  1707. #else
  1708. vec3 cubemap_ambient = textureLod(samplerCube(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), ambient_dir, MAX_ROUGHNESS_LOD).rgb;
  1709. #endif //USE_RADIANCE_CUBEMAP_ARRAY
  1710. ambient_light = mix(ambient_light, cubemap_ambient * scene_data.ambient_light_color_energy.a, scene_data.ambient_color_sky_mix);
  1711. }
  1712. }
  1713. #endif // USE_LIGHTMAP
  1714. #if defined(CUSTOM_IRRADIANCE_USED)
  1715. ambient_light = mix(specular_light, custom_irradiance.rgb, custom_irradiance.a);
  1716. #endif
  1717. #endif //!defined(MODE_RENDER_DEPTH) && !defined(MODE_UNSHADED)
  1718. //radiance
  1719. /// GI ///
  1720. #if !defined(MODE_RENDER_DEPTH) && !defined(MODE_UNSHADED)
  1721. #ifdef USE_LIGHTMAP
  1722. //lightmap
  1723. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_USE_LIGHTMAP_CAPTURE)) { //has lightmap capture
  1724. uint index = instances.data[instance_index].gi_offset;
  1725. vec3 wnormal = mat3(scene_data.camera_matrix) * normal;
  1726. const float c1 = 0.429043;
  1727. const float c2 = 0.511664;
  1728. const float c3 = 0.743125;
  1729. const float c4 = 0.886227;
  1730. const float c5 = 0.247708;
  1731. ambient_light += (c1 * lightmap_captures.data[index].sh[8].rgb * (wnormal.x * wnormal.x - wnormal.y * wnormal.y) +
  1732. c3 * lightmap_captures.data[index].sh[6].rgb * wnormal.z * wnormal.z +
  1733. c4 * lightmap_captures.data[index].sh[0].rgb -
  1734. c5 * lightmap_captures.data[index].sh[6].rgb +
  1735. 2.0 * c1 * lightmap_captures.data[index].sh[4].rgb * wnormal.x * wnormal.y +
  1736. 2.0 * c1 * lightmap_captures.data[index].sh[7].rgb * wnormal.x * wnormal.z +
  1737. 2.0 * c1 * lightmap_captures.data[index].sh[5].rgb * wnormal.y * wnormal.z +
  1738. 2.0 * c2 * lightmap_captures.data[index].sh[3].rgb * wnormal.x +
  1739. 2.0 * c2 * lightmap_captures.data[index].sh[1].rgb * wnormal.y +
  1740. 2.0 * c2 * lightmap_captures.data[index].sh[2].rgb * wnormal.z);
  1741. } else if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_USE_LIGHTMAP)) { // has actual lightmap
  1742. bool uses_sh = bool(instances.data[instance_index].flags & INSTANCE_FLAGS_USE_SH_LIGHTMAP);
  1743. uint ofs = instances.data[instance_index].gi_offset & 0xFFFF;
  1744. vec3 uvw;
  1745. uvw.xy = uv2 * instances.data[instance_index].lightmap_uv_scale.zw + instances.data[instance_index].lightmap_uv_scale.xy;
  1746. uvw.z = float((instances.data[instance_index].gi_offset >> 16) & 0xFFFF);
  1747. if (uses_sh) {
  1748. uvw.z *= 4.0; //SH textures use 4 times more data
  1749. vec3 lm_light_l0 = textureLod(sampler2DArray(lightmap_textures[ofs], material_samplers[SAMPLER_LINEAR_CLAMP]), uvw + vec3(0.0, 0.0, 0.0), 0.0).rgb;
  1750. vec3 lm_light_l1n1 = textureLod(sampler2DArray(lightmap_textures[ofs], material_samplers[SAMPLER_LINEAR_CLAMP]), uvw + vec3(0.0, 0.0, 1.0), 0.0).rgb;
  1751. vec3 lm_light_l1_0 = textureLod(sampler2DArray(lightmap_textures[ofs], material_samplers[SAMPLER_LINEAR_CLAMP]), uvw + vec3(0.0, 0.0, 2.0), 0.0).rgb;
  1752. vec3 lm_light_l1p1 = textureLod(sampler2DArray(lightmap_textures[ofs], material_samplers[SAMPLER_LINEAR_CLAMP]), uvw + vec3(0.0, 0.0, 3.0), 0.0).rgb;
  1753. uint idx = instances.data[instance_index].gi_offset >> 20;
  1754. vec3 n = normalize(lightmaps.data[idx].normal_xform * normal);
  1755. ambient_light += lm_light_l0 * 0.282095f;
  1756. ambient_light += lm_light_l1n1 * 0.32573 * n.y;
  1757. ambient_light += lm_light_l1_0 * 0.32573 * n.z;
  1758. ambient_light += lm_light_l1p1 * 0.32573 * n.x;
  1759. if (metallic > 0.01) { // since the more direct bounced light is lost, we can kind of fake it with this trick
  1760. vec3 r = reflect(normalize(-vertex), normal);
  1761. specular_light += lm_light_l1n1 * 0.32573 * r.y;
  1762. specular_light += lm_light_l1_0 * 0.32573 * r.z;
  1763. specular_light += lm_light_l1p1 * 0.32573 * r.x;
  1764. }
  1765. } else {
  1766. ambient_light += textureLod(sampler2DArray(lightmap_textures[ofs], material_samplers[SAMPLER_LINEAR_CLAMP]), uvw, 0.0).rgb;
  1767. }
  1768. }
  1769. #elif defined(USE_FORWARD_GI)
  1770. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_USE_SDFGI)) { //has lightmap capture
  1771. //make vertex orientation the world one, but still align to camera
  1772. vec3 cam_pos = mat3(scene_data.camera_matrix) * vertex;
  1773. vec3 cam_normal = mat3(scene_data.camera_matrix) * normal;
  1774. vec3 cam_reflection = mat3(scene_data.camera_matrix) * reflect(-view, normal);
  1775. //apply y-mult
  1776. cam_pos.y *= sdfgi.y_mult;
  1777. cam_normal.y *= sdfgi.y_mult;
  1778. cam_normal = normalize(cam_normal);
  1779. cam_reflection.y *= sdfgi.y_mult;
  1780. cam_normal = normalize(cam_normal);
  1781. cam_reflection = normalize(cam_reflection);
  1782. vec4 light_accum = vec4(0.0);
  1783. float weight_accum = 0.0;
  1784. vec4 light_blend_accum = vec4(0.0);
  1785. float weight_blend_accum = 0.0;
  1786. float blend = -1.0;
  1787. // helper constants, compute once
  1788. uint cascade = 0xFFFFFFFF;
  1789. vec3 cascade_pos;
  1790. vec3 cascade_normal;
  1791. for (uint i = 0; i < sdfgi.max_cascades; i++) {
  1792. cascade_pos = (cam_pos - sdfgi.cascades[i].position) * sdfgi.cascades[i].to_probe;
  1793. if (any(lessThan(cascade_pos, vec3(0.0))) || any(greaterThanEqual(cascade_pos, sdfgi.cascade_probe_size))) {
  1794. continue; //skip cascade
  1795. }
  1796. cascade = i;
  1797. break;
  1798. }
  1799. if (cascade < SDFGI_MAX_CASCADES) {
  1800. bool use_specular = true;
  1801. float blend;
  1802. vec3 diffuse, specular;
  1803. sdfgi_process(cascade, cascade_pos, cam_pos, cam_normal, cam_reflection, use_specular, roughness, diffuse, specular, blend);
  1804. if (blend > 0.0) {
  1805. //blend
  1806. if (cascade == sdfgi.max_cascades - 1) {
  1807. diffuse = mix(diffuse, ambient_light, blend);
  1808. if (use_specular) {
  1809. specular = mix(specular, specular_light, blend);
  1810. }
  1811. } else {
  1812. vec3 diffuse2, specular2;
  1813. float blend2;
  1814. cascade_pos = (cam_pos - sdfgi.cascades[cascade + 1].position) * sdfgi.cascades[cascade + 1].to_probe;
  1815. sdfgi_process(cascade + 1, cascade_pos, cam_pos, cam_normal, cam_reflection, use_specular, roughness, diffuse2, specular2, blend2);
  1816. diffuse = mix(diffuse, diffuse2, blend);
  1817. if (use_specular) {
  1818. specular = mix(specular, specular2, blend);
  1819. }
  1820. }
  1821. }
  1822. ambient_light = diffuse;
  1823. if (use_specular) {
  1824. specular_light = specular;
  1825. }
  1826. }
  1827. }
  1828. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_USE_GIPROBE)) { // process giprobes
  1829. uint index1 = instances.data[instance_index].gi_offset & 0xFFFF;
  1830. vec3 ref_vec = normalize(reflect(normalize(vertex), normal));
  1831. //find arbitrary tangent and bitangent, then build a matrix
  1832. vec3 v0 = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
  1833. vec3 tangent = normalize(cross(v0, normal));
  1834. vec3 bitangent = normalize(cross(tangent, normal));
  1835. mat3 normal_mat = mat3(tangent, bitangent, normal);
  1836. vec4 amb_accum = vec4(0.0);
  1837. vec4 spec_accum = vec4(0.0);
  1838. gi_probe_compute(index1, vertex, normal, ref_vec, normal_mat, roughness * roughness, ambient_light, specular_light, spec_accum, amb_accum);
  1839. uint index2 = instances.data[instance_index].gi_offset >> 16;
  1840. if (index2 != 0xFFFF) {
  1841. gi_probe_compute(index2, vertex, normal, ref_vec, normal_mat, roughness * roughness, ambient_light, specular_light, spec_accum, amb_accum);
  1842. }
  1843. if (amb_accum.a > 0.0) {
  1844. amb_accum.rgb /= amb_accum.a;
  1845. }
  1846. if (spec_accum.a > 0.0) {
  1847. spec_accum.rgb /= spec_accum.a;
  1848. }
  1849. specular_light = spec_accum.rgb;
  1850. ambient_light = amb_accum.rgb;
  1851. }
  1852. #elif !defined(LOW_END_MODE)
  1853. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_USE_GI_BUFFERS)) { //use GI buffers
  1854. vec2 coord;
  1855. if (scene_data.gi_upscale_for_msaa) {
  1856. vec2 base_coord = screen_uv;
  1857. vec2 closest_coord = base_coord;
  1858. float closest_ang = dot(normal, textureLod(sampler2D(normal_roughness_buffer, material_samplers[SAMPLER_LINEAR_CLAMP]), base_coord, 0.0).xyz * 2.0 - 1.0);
  1859. for (int i = 0; i < 4; i++) {
  1860. const vec2 neighbours[4] = vec2[](vec2(-1, 0), vec2(1, 0), vec2(0, -1), vec2(0, 1));
  1861. vec2 neighbour_coord = base_coord + neighbours[i] * scene_data.screen_pixel_size;
  1862. float neighbour_ang = dot(normal, textureLod(sampler2D(normal_roughness_buffer, material_samplers[SAMPLER_LINEAR_CLAMP]), neighbour_coord, 0.0).xyz * 2.0 - 1.0);
  1863. if (neighbour_ang > closest_ang) {
  1864. closest_ang = neighbour_ang;
  1865. closest_coord = neighbour_coord;
  1866. }
  1867. }
  1868. coord = closest_coord;
  1869. } else {
  1870. coord = screen_uv;
  1871. }
  1872. vec4 buffer_ambient = textureLod(sampler2D(ambient_buffer, material_samplers[SAMPLER_LINEAR_CLAMP]), coord, 0.0);
  1873. vec4 buffer_reflection = textureLod(sampler2D(reflection_buffer, material_samplers[SAMPLER_LINEAR_CLAMP]), coord, 0.0);
  1874. ambient_light = mix(ambient_light, buffer_ambient.rgb, buffer_ambient.a);
  1875. specular_light = mix(specular_light, buffer_reflection.rgb, buffer_reflection.a);
  1876. }
  1877. #endif
  1878. #ifndef LOW_END_MODE
  1879. if (scene_data.ssao_enabled) {
  1880. float ssao = texture(sampler2D(ao_buffer, material_samplers[SAMPLER_LINEAR_CLAMP]), screen_uv).r;
  1881. ao = min(ao, ssao);
  1882. ao_light_affect = mix(ao_light_affect, max(ao_light_affect, scene_data.ssao_light_affect), scene_data.ssao_ao_affect);
  1883. }
  1884. #endif //LOW_END_MODE
  1885. { // process reflections
  1886. vec4 reflection_accum = vec4(0.0, 0.0, 0.0, 0.0);
  1887. vec4 ambient_accum = vec4(0.0, 0.0, 0.0, 0.0);
  1888. uint cluster_reflection_offset = cluster_offset + scene_data.cluster_type_size * 3;
  1889. uint item_min;
  1890. uint item_max;
  1891. uint item_from;
  1892. uint item_to;
  1893. cluster_get_item_range(cluster_reflection_offset + scene_data.max_cluster_element_count_div_32 + cluster_z, item_min, item_max, item_from, item_to);
  1894. #ifdef USE_SUBGROUPS
  1895. item_from = subgroupBroadcastFirst(subgroupMin(item_from));
  1896. item_to = subgroupBroadcastFirst(subgroupMax(item_to));
  1897. #endif
  1898. for (uint i = item_from; i < item_to; i++) {
  1899. uint mask = cluster_buffer.data[cluster_reflection_offset + i];
  1900. mask &= cluster_get_range_clip_mask(i, item_min, item_max);
  1901. #ifdef USE_SUBGROUPS
  1902. uint merged_mask = subgroupBroadcastFirst(subgroupOr(mask));
  1903. #else
  1904. uint merged_mask = mask;
  1905. #endif
  1906. while (merged_mask != 0) {
  1907. uint bit = findMSB(merged_mask);
  1908. merged_mask &= ~(1 << bit);
  1909. #ifdef USE_SUBGROUPS
  1910. if (((1 << bit) & mask) == 0) { //do not process if not originally here
  1911. continue;
  1912. }
  1913. #endif
  1914. uint reflection_index = 32 * i + bit;
  1915. if (!bool(reflections.data[reflection_index].mask & instances.data[instance_index].layer_mask)) {
  1916. continue; //not masked
  1917. }
  1918. reflection_process(reflection_index, vertex, normal, roughness, ambient_light, specular_light, ambient_accum, reflection_accum);
  1919. }
  1920. }
  1921. if (reflection_accum.a > 0.0) {
  1922. specular_light = reflection_accum.rgb / reflection_accum.a;
  1923. }
  1924. #if !defined(USE_LIGHTMAP)
  1925. if (ambient_accum.a > 0.0) {
  1926. ambient_light = ambient_accum.rgb / ambient_accum.a;
  1927. }
  1928. #endif
  1929. }
  1930. //finalize ambient light here
  1931. ambient_light *= albedo.rgb;
  1932. ambient_light *= ao;
  1933. // convert ao to direct light ao
  1934. ao = mix(1.0, ao, ao_light_affect);
  1935. //this saves some VGPRs
  1936. vec3 f0 = F0(metallic, specular, albedo);
  1937. {
  1938. #if defined(DIFFUSE_TOON)
  1939. //simplify for toon, as
  1940. specular_light *= specular * metallic * albedo * 2.0;
  1941. #else
  1942. // scales the specular reflections, needs to be be computed before lighting happens,
  1943. // but after environment, GI, and reflection probes are added
  1944. // Environment brdf approximation (Lazarov 2013)
  1945. // see https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile
  1946. const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);
  1947. const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);
  1948. vec4 r = roughness * c0 + c1;
  1949. float ndotv = clamp(dot(normal, view), 0.0, 1.0);
  1950. float a004 = min(r.x * r.x, exp2(-9.28 * ndotv)) * r.x + r.y;
  1951. vec2 env = vec2(-1.04, 1.04) * a004 + r.zw;
  1952. specular_light *= env.x * f0 + env.y;
  1953. #endif
  1954. }
  1955. #endif //GI !defined(MODE_RENDER_DEPTH) && !defined(MODE_UNSHADED)
  1956. #if !defined(MODE_RENDER_DEPTH)
  1957. //this saves some VGPRs
  1958. uint orms = packUnorm4x8(vec4(ao, roughness, metallic, specular));
  1959. #endif
  1960. // LIGHTING
  1961. #if !defined(MODE_RENDER_DEPTH) && !defined(MODE_UNSHADED)
  1962. { //directional light
  1963. // Do shadow and lighting in two passes to reduce register pressure
  1964. uint shadow0 = 0;
  1965. uint shadow1 = 0;
  1966. for (uint i = 0; i < 8; i++) {
  1967. if (i >= scene_data.directional_light_count) {
  1968. break;
  1969. }
  1970. if (!bool(directional_lights.data[i].mask & instances.data[instance_index].layer_mask)) {
  1971. continue; //not masked
  1972. }
  1973. float shadow = 1.0;
  1974. #ifdef USE_SOFT_SHADOWS
  1975. //version with soft shadows, more expensive
  1976. if (directional_lights.data[i].shadow_enabled) {
  1977. float depth_z = -vertex.z;
  1978. vec4 pssm_coord;
  1979. vec3 shadow_color = vec3(0.0);
  1980. vec3 light_dir = directional_lights.data[i].direction;
  1981. #define BIAS_FUNC(m_var, m_idx) \
  1982. m_var.xyz += light_dir * directional_lights.data[i].shadow_bias[m_idx]; \
  1983. vec3 normal_bias = normalize(normal_interp) * (1.0 - max(0.0, dot(light_dir, -normalize(normal_interp)))) * directional_lights.data[i].shadow_normal_bias[m_idx]; \
  1984. normal_bias -= light_dir * dot(light_dir, normal_bias); \
  1985. m_var.xyz += normal_bias;
  1986. if (depth_z < directional_lights.data[i].shadow_split_offsets.x) {
  1987. vec4 v = vec4(vertex, 1.0);
  1988. BIAS_FUNC(v, 0)
  1989. pssm_coord = (directional_lights.data[i].shadow_matrix1 * v);
  1990. pssm_coord /= pssm_coord.w;
  1991. if (directional_lights.data[i].softshadow_angle > 0) {
  1992. float range_pos = dot(directional_lights.data[i].direction, v.xyz);
  1993. float range_begin = directional_lights.data[i].shadow_range_begin.x;
  1994. float test_radius = (range_pos - range_begin) * directional_lights.data[i].softshadow_angle;
  1995. vec2 tex_scale = directional_lights.data[i].uv_scale1 * test_radius;
  1996. shadow = sample_directional_soft_shadow(directional_shadow_atlas, pssm_coord.xyz, tex_scale * directional_lights.data[i].soft_shadow_scale);
  1997. } else {
  1998. shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  1999. }
  2000. shadow_color = directional_lights.data[i].shadow_color1.rgb;
  2001. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) {
  2002. vec4 v = vec4(vertex, 1.0);
  2003. BIAS_FUNC(v, 1)
  2004. pssm_coord = (directional_lights.data[i].shadow_matrix2 * v);
  2005. pssm_coord /= pssm_coord.w;
  2006. if (directional_lights.data[i].softshadow_angle > 0) {
  2007. float range_pos = dot(directional_lights.data[i].direction, v.xyz);
  2008. float range_begin = directional_lights.data[i].shadow_range_begin.y;
  2009. float test_radius = (range_pos - range_begin) * directional_lights.data[i].softshadow_angle;
  2010. vec2 tex_scale = directional_lights.data[i].uv_scale2 * test_radius;
  2011. shadow = sample_directional_soft_shadow(directional_shadow_atlas, pssm_coord.xyz, tex_scale * directional_lights.data[i].soft_shadow_scale);
  2012. } else {
  2013. shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  2014. }
  2015. shadow_color = directional_lights.data[i].shadow_color2.rgb;
  2016. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) {
  2017. vec4 v = vec4(vertex, 1.0);
  2018. BIAS_FUNC(v, 2)
  2019. pssm_coord = (directional_lights.data[i].shadow_matrix3 * v);
  2020. pssm_coord /= pssm_coord.w;
  2021. if (directional_lights.data[i].softshadow_angle > 0) {
  2022. float range_pos = dot(directional_lights.data[i].direction, v.xyz);
  2023. float range_begin = directional_lights.data[i].shadow_range_begin.z;
  2024. float test_radius = (range_pos - range_begin) * directional_lights.data[i].softshadow_angle;
  2025. vec2 tex_scale = directional_lights.data[i].uv_scale3 * test_radius;
  2026. shadow = sample_directional_soft_shadow(directional_shadow_atlas, pssm_coord.xyz, tex_scale * directional_lights.data[i].soft_shadow_scale);
  2027. } else {
  2028. shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  2029. }
  2030. shadow_color = directional_lights.data[i].shadow_color3.rgb;
  2031. } else {
  2032. vec4 v = vec4(vertex, 1.0);
  2033. BIAS_FUNC(v, 3)
  2034. pssm_coord = (directional_lights.data[i].shadow_matrix4 * v);
  2035. pssm_coord /= pssm_coord.w;
  2036. if (directional_lights.data[i].softshadow_angle > 0) {
  2037. float range_pos = dot(directional_lights.data[i].direction, v.xyz);
  2038. float range_begin = directional_lights.data[i].shadow_range_begin.w;
  2039. float test_radius = (range_pos - range_begin) * directional_lights.data[i].softshadow_angle;
  2040. vec2 tex_scale = directional_lights.data[i].uv_scale4 * test_radius;
  2041. shadow = sample_directional_soft_shadow(directional_shadow_atlas, pssm_coord.xyz, tex_scale * directional_lights.data[i].soft_shadow_scale);
  2042. } else {
  2043. shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  2044. }
  2045. shadow_color = directional_lights.data[i].shadow_color4.rgb;
  2046. }
  2047. if (directional_lights.data[i].blend_splits) {
  2048. vec3 shadow_color_blend = vec3(0.0);
  2049. float pssm_blend;
  2050. float shadow2;
  2051. if (depth_z < directional_lights.data[i].shadow_split_offsets.x) {
  2052. vec4 v = vec4(vertex, 1.0);
  2053. BIAS_FUNC(v, 1)
  2054. pssm_coord = (directional_lights.data[i].shadow_matrix2 * v);
  2055. pssm_coord /= pssm_coord.w;
  2056. if (directional_lights.data[i].softshadow_angle > 0) {
  2057. float range_pos = dot(directional_lights.data[i].direction, v.xyz);
  2058. float range_begin = directional_lights.data[i].shadow_range_begin.y;
  2059. float test_radius = (range_pos - range_begin) * directional_lights.data[i].softshadow_angle;
  2060. vec2 tex_scale = directional_lights.data[i].uv_scale2 * test_radius;
  2061. shadow2 = sample_directional_soft_shadow(directional_shadow_atlas, pssm_coord.xyz, tex_scale * directional_lights.data[i].soft_shadow_scale);
  2062. } else {
  2063. shadow2 = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  2064. }
  2065. pssm_blend = smoothstep(0.0, directional_lights.data[i].shadow_split_offsets.x, depth_z);
  2066. shadow_color_blend = directional_lights.data[i].shadow_color2.rgb;
  2067. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) {
  2068. vec4 v = vec4(vertex, 1.0);
  2069. BIAS_FUNC(v, 2)
  2070. pssm_coord = (directional_lights.data[i].shadow_matrix3 * v);
  2071. pssm_coord /= pssm_coord.w;
  2072. if (directional_lights.data[i].softshadow_angle > 0) {
  2073. float range_pos = dot(directional_lights.data[i].direction, v.xyz);
  2074. float range_begin = directional_lights.data[i].shadow_range_begin.z;
  2075. float test_radius = (range_pos - range_begin) * directional_lights.data[i].softshadow_angle;
  2076. vec2 tex_scale = directional_lights.data[i].uv_scale3 * test_radius;
  2077. shadow2 = sample_directional_soft_shadow(directional_shadow_atlas, pssm_coord.xyz, tex_scale * directional_lights.data[i].soft_shadow_scale);
  2078. } else {
  2079. shadow2 = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  2080. }
  2081. pssm_blend = smoothstep(directional_lights.data[i].shadow_split_offsets.x, directional_lights.data[i].shadow_split_offsets.y, depth_z);
  2082. shadow_color_blend = directional_lights.data[i].shadow_color3.rgb;
  2083. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) {
  2084. vec4 v = vec4(vertex, 1.0);
  2085. BIAS_FUNC(v, 3)
  2086. pssm_coord = (directional_lights.data[i].shadow_matrix4 * v);
  2087. pssm_coord /= pssm_coord.w;
  2088. if (directional_lights.data[i].softshadow_angle > 0) {
  2089. float range_pos = dot(directional_lights.data[i].direction, v.xyz);
  2090. float range_begin = directional_lights.data[i].shadow_range_begin.w;
  2091. float test_radius = (range_pos - range_begin) * directional_lights.data[i].softshadow_angle;
  2092. vec2 tex_scale = directional_lights.data[i].uv_scale4 * test_radius;
  2093. shadow2 = sample_directional_soft_shadow(directional_shadow_atlas, pssm_coord.xyz, tex_scale * directional_lights.data[i].soft_shadow_scale);
  2094. } else {
  2095. shadow2 = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  2096. }
  2097. pssm_blend = smoothstep(directional_lights.data[i].shadow_split_offsets.y, directional_lights.data[i].shadow_split_offsets.z, depth_z);
  2098. shadow_color_blend = directional_lights.data[i].shadow_color4.rgb;
  2099. } else {
  2100. pssm_blend = 0.0; //if no blend, same coord will be used (divide by z will result in same value, and already cached)
  2101. }
  2102. pssm_blend = sqrt(pssm_blend);
  2103. shadow = mix(shadow, shadow2, pssm_blend);
  2104. shadow_color = mix(shadow_color, shadow_color_blend, pssm_blend);
  2105. }
  2106. shadow = mix(shadow, 1.0, smoothstep(directional_lights.data[i].fade_from, directional_lights.data[i].fade_to, vertex.z)); //done with negative values for performance
  2107. #undef BIAS_FUNC
  2108. }
  2109. #else
  2110. // Soft shadow disabled version
  2111. if (directional_lights.data[i].shadow_enabled) {
  2112. float depth_z = -vertex.z;
  2113. vec4 pssm_coord;
  2114. vec3 light_dir = directional_lights.data[i].direction;
  2115. vec3 base_normal_bias = normalize(normal_interp) * (1.0 - max(0.0, dot(light_dir, -normalize(normal_interp))));
  2116. #define BIAS_FUNC(m_var, m_idx) \
  2117. m_var.xyz += light_dir * directional_lights.data[i].shadow_bias[m_idx]; \
  2118. vec3 normal_bias = base_normal_bias * directional_lights.data[i].shadow_normal_bias[m_idx]; \
  2119. normal_bias -= light_dir * dot(light_dir, normal_bias); \
  2120. m_var.xyz += normal_bias;
  2121. if (depth_z < directional_lights.data[i].shadow_split_offsets.x) {
  2122. vec4 v = vec4(vertex, 1.0);
  2123. BIAS_FUNC(v, 0)
  2124. pssm_coord = (directional_lights.data[i].shadow_matrix1 * v);
  2125. #ifdef LIGHT_TRANSMITTANCE_USED
  2126. {
  2127. vec4 trans_vertex = vec4(vertex - normalize(normal_interp) * directional_lights.data[i].shadow_transmittance_bias.x, 1.0);
  2128. vec4 trans_coord = directional_lights.data[i].shadow_matrix1 * trans_vertex;
  2129. trans_coord /= trans_coord.w;
  2130. float shadow_z = textureLod(sampler2D(directional_shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), trans_coord.xy, 0.0).r;
  2131. shadow_z *= directional_lights.data[i].shadow_transmittance_z_scale.x;
  2132. float z = trans_coord.z * directional_lights.data[i].shadow_transmittance_z_scale.x;
  2133. transmittance_z = z - shadow_z;
  2134. }
  2135. #endif
  2136. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) {
  2137. vec4 v = vec4(vertex, 1.0);
  2138. BIAS_FUNC(v, 1)
  2139. pssm_coord = (directional_lights.data[i].shadow_matrix2 * v);
  2140. #ifdef LIGHT_TRANSMITTANCE_USED
  2141. {
  2142. vec4 trans_vertex = vec4(vertex - normalize(normal_interp) * directional_lights.data[i].shadow_transmittance_bias.y, 1.0);
  2143. vec4 trans_coord = directional_lights.data[i].shadow_matrix2 * trans_vertex;
  2144. trans_coord /= trans_coord.w;
  2145. float shadow_z = textureLod(sampler2D(directional_shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), trans_coord.xy, 0.0).r;
  2146. shadow_z *= directional_lights.data[i].shadow_transmittance_z_scale.y;
  2147. float z = trans_coord.z * directional_lights.data[i].shadow_transmittance_z_scale.y;
  2148. transmittance_z = z - shadow_z;
  2149. }
  2150. #endif
  2151. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) {
  2152. vec4 v = vec4(vertex, 1.0);
  2153. BIAS_FUNC(v, 2)
  2154. pssm_coord = (directional_lights.data[i].shadow_matrix3 * v);
  2155. #ifdef LIGHT_TRANSMITTANCE_USED
  2156. {
  2157. vec4 trans_vertex = vec4(vertex - normalize(normal_interp) * directional_lights.data[i].shadow_transmittance_bias.z, 1.0);
  2158. vec4 trans_coord = directional_lights.data[i].shadow_matrix3 * trans_vertex;
  2159. trans_coord /= trans_coord.w;
  2160. float shadow_z = textureLod(sampler2D(directional_shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), trans_coord.xy, 0.0).r;
  2161. shadow_z *= directional_lights.data[i].shadow_transmittance_z_scale.z;
  2162. float z = trans_coord.z * directional_lights.data[i].shadow_transmittance_z_scale.z;
  2163. transmittance_z = z - shadow_z;
  2164. }
  2165. #endif
  2166. } else {
  2167. vec4 v = vec4(vertex, 1.0);
  2168. BIAS_FUNC(v, 3)
  2169. pssm_coord = (directional_lights.data[i].shadow_matrix4 * v);
  2170. #ifdef LIGHT_TRANSMITTANCE_USED
  2171. {
  2172. vec4 trans_vertex = vec4(vertex - normalize(normal_interp) * directional_lights.data[i].shadow_transmittance_bias.w, 1.0);
  2173. vec4 trans_coord = directional_lights.data[i].shadow_matrix4 * trans_vertex;
  2174. trans_coord /= trans_coord.w;
  2175. float shadow_z = textureLod(sampler2D(directional_shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), trans_coord.xy, 0.0).r;
  2176. shadow_z *= directional_lights.data[i].shadow_transmittance_z_scale.w;
  2177. float z = trans_coord.z * directional_lights.data[i].shadow_transmittance_z_scale.w;
  2178. transmittance_z = z - shadow_z;
  2179. }
  2180. #endif
  2181. }
  2182. pssm_coord /= pssm_coord.w;
  2183. shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  2184. if (directional_lights.data[i].blend_splits) {
  2185. float pssm_blend;
  2186. if (depth_z < directional_lights.data[i].shadow_split_offsets.x) {
  2187. vec4 v = vec4(vertex, 1.0);
  2188. BIAS_FUNC(v, 1)
  2189. pssm_coord = (directional_lights.data[i].shadow_matrix2 * v);
  2190. pssm_blend = smoothstep(0.0, directional_lights.data[i].shadow_split_offsets.x, depth_z);
  2191. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) {
  2192. vec4 v = vec4(vertex, 1.0);
  2193. BIAS_FUNC(v, 2)
  2194. pssm_coord = (directional_lights.data[i].shadow_matrix3 * v);
  2195. pssm_blend = smoothstep(directional_lights.data[i].shadow_split_offsets.x, directional_lights.data[i].shadow_split_offsets.y, depth_z);
  2196. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) {
  2197. vec4 v = vec4(vertex, 1.0);
  2198. BIAS_FUNC(v, 3)
  2199. pssm_coord = (directional_lights.data[i].shadow_matrix4 * v);
  2200. pssm_blend = smoothstep(directional_lights.data[i].shadow_split_offsets.y, directional_lights.data[i].shadow_split_offsets.z, depth_z);
  2201. } else {
  2202. pssm_blend = 0.0; //if no blend, same coord will be used (divide by z will result in same value, and already cached)
  2203. }
  2204. pssm_coord /= pssm_coord.w;
  2205. float shadow2 = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord);
  2206. shadow = mix(shadow, shadow2, pssm_blend);
  2207. }
  2208. shadow = mix(shadow, 1.0, smoothstep(directional_lights.data[i].fade_from, directional_lights.data[i].fade_to, vertex.z)); //done with negative values for performance
  2209. #undef BIAS_FUNC
  2210. }
  2211. #endif
  2212. if (i < 4) {
  2213. shadow0 |= uint(clamp(shadow * 255.0, 0.0, 255.0)) << (i * 8);
  2214. } else {
  2215. shadow1 |= uint(clamp(shadow * 255.0, 0.0, 255.0)) << ((i - 4) * 8);
  2216. }
  2217. }
  2218. for (uint i = 0; i < 8; i++) {
  2219. if (i >= scene_data.directional_light_count) {
  2220. break;
  2221. }
  2222. if (!bool(directional_lights.data[i].mask & instances.data[instance_index].layer_mask)) {
  2223. continue; //not masked
  2224. }
  2225. #ifdef LIGHT_TRANSMITTANCE_USED
  2226. float transmittance_z = transmittance_depth;
  2227. if (directional_lights.data[i].shadow_enabled) {
  2228. float depth_z = -vertex.z;
  2229. if (depth_z < directional_lights.data[i].shadow_split_offsets.x) {
  2230. vec4 trans_vertex = vec4(vertex - normalize(normal_interp) * directional_lights.data[i].shadow_transmittance_bias.x, 1.0);
  2231. vec4 trans_coord = directional_lights.data[i].shadow_matrix1 * trans_vertex;
  2232. trans_coord /= trans_coord.w;
  2233. float shadow_z = textureLod(sampler2D(directional_shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), trans_coord.xy, 0.0).r;
  2234. shadow_z *= directional_lights.data[i].shadow_transmittance_z_scale.x;
  2235. float z = trans_coord.z * directional_lights.data[i].shadow_transmittance_z_scale.x;
  2236. transmittance_z = z - shadow_z;
  2237. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) {
  2238. vec4 trans_vertex = vec4(vertex - normalize(normal_interp) * directional_lights.data[i].shadow_transmittance_bias.y, 1.0);
  2239. vec4 trans_coord = directional_lights.data[i].shadow_matrix2 * trans_vertex;
  2240. trans_coord /= trans_coord.w;
  2241. float shadow_z = textureLod(sampler2D(directional_shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), trans_coord.xy, 0.0).r;
  2242. shadow_z *= directional_lights.data[i].shadow_transmittance_z_scale.y;
  2243. float z = trans_coord.z * directional_lights.data[i].shadow_transmittance_z_scale.y;
  2244. transmittance_z = z - shadow_z;
  2245. } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) {
  2246. vec4 trans_vertex = vec4(vertex - normalize(normal_interp) * directional_lights.data[i].shadow_transmittance_bias.z, 1.0);
  2247. vec4 trans_coord = directional_lights.data[i].shadow_matrix3 * trans_vertex;
  2248. trans_coord /= trans_coord.w;
  2249. float shadow_z = textureLod(sampler2D(directional_shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), trans_coord.xy, 0.0).r;
  2250. shadow_z *= directional_lights.data[i].shadow_transmittance_z_scale.z;
  2251. float z = trans_coord.z * directional_lights.data[i].shadow_transmittance_z_scale.z;
  2252. transmittance_z = z - shadow_z;
  2253. } else {
  2254. vec4 trans_vertex = vec4(vertex - normalize(normal_interp) * directional_lights.data[i].shadow_transmittance_bias.w, 1.0);
  2255. vec4 trans_coord = directional_lights.data[i].shadow_matrix4 * trans_vertex;
  2256. trans_coord /= trans_coord.w;
  2257. float shadow_z = textureLod(sampler2D(directional_shadow_atlas, material_samplers[SAMPLER_LINEAR_CLAMP]), trans_coord.xy, 0.0).r;
  2258. shadow_z *= directional_lights.data[i].shadow_transmittance_z_scale.w;
  2259. float z = trans_coord.z * directional_lights.data[i].shadow_transmittance_z_scale.w;
  2260. transmittance_z = z - shadow_z;
  2261. }
  2262. #endif
  2263. float shadow = 1.0;
  2264. if (i < 4) {
  2265. shadow = float(shadow0 >> (i * 8) & 0xFF) / 255.0;
  2266. } else {
  2267. shadow = float(shadow1 >> ((i - 4) * 8) & 0xFF) / 255.0;
  2268. }
  2269. blur_shadow(shadow);
  2270. light_compute(normal, directional_lights.data[i].direction, normalize(view), directional_lights.data[i].color * directional_lights.data[i].energy, shadow, f0, orms, 1.0,
  2271. #ifdef LIGHT_BACKLIGHT_USED
  2272. backlight,
  2273. #endif
  2274. #ifdef LIGHT_TRANSMITTANCE_USED
  2275. transmittance_color,
  2276. transmittance_depth,
  2277. transmittance_curve,
  2278. transmittance_boost,
  2279. transmittance_z,
  2280. #endif
  2281. #ifdef LIGHT_RIM_USED
  2282. rim, rim_tint, albedo,
  2283. #endif
  2284. #ifdef LIGHT_CLEARCOAT_USED
  2285. clearcoat, clearcoat_gloss,
  2286. #endif
  2287. #ifdef LIGHT_ANISOTROPY_USED
  2288. binormal, tangent, anisotropy,
  2289. #endif
  2290. #ifdef USE_SOFT_SHADOW
  2291. directional_lights.data[i].size,
  2292. #endif
  2293. #ifdef USE_SHADOW_TO_OPACITY
  2294. alpha,
  2295. #endif
  2296. diffuse_light,
  2297. specular_light);
  2298. }
  2299. }
  2300. { //omni lights
  2301. uint cluster_omni_offset = cluster_offset;
  2302. uint item_min;
  2303. uint item_max;
  2304. uint item_from;
  2305. uint item_to;
  2306. cluster_get_item_range(cluster_omni_offset + scene_data.max_cluster_element_count_div_32 + cluster_z, item_min, item_max, item_from, item_to);
  2307. #ifdef USE_SUBGROUPS
  2308. item_from = subgroupBroadcastFirst(subgroupMin(item_from));
  2309. item_to = subgroupBroadcastFirst(subgroupMax(item_to));
  2310. #endif
  2311. for (uint i = item_from; i < item_to; i++) {
  2312. uint mask = cluster_buffer.data[cluster_omni_offset + i];
  2313. mask &= cluster_get_range_clip_mask(i, item_min, item_max);
  2314. #ifdef USE_SUBGROUPS
  2315. uint merged_mask = subgroupBroadcastFirst(subgroupOr(mask));
  2316. #else
  2317. uint merged_mask = mask;
  2318. #endif
  2319. while (merged_mask != 0) {
  2320. uint bit = findMSB(merged_mask);
  2321. merged_mask &= ~(1 << bit);
  2322. #ifdef USE_SUBGROUPS
  2323. if (((1 << bit) & mask) == 0) { //do not process if not originally here
  2324. continue;
  2325. }
  2326. #endif
  2327. uint light_index = 32 * i + bit;
  2328. if (!bool(omni_lights.data[light_index].mask & instances.data[instance_index].layer_mask)) {
  2329. continue; //not masked
  2330. }
  2331. float shadow = light_process_omni_shadow(light_index, vertex, view);
  2332. shadow = blur_shadow(shadow);
  2333. light_process_omni(light_index, vertex, view, normal, vertex_ddx, vertex_ddy, f0, orms, shadow,
  2334. #ifdef LIGHT_BACKLIGHT_USED
  2335. backlight,
  2336. #endif
  2337. #ifdef LIGHT_TRANSMITTANCE_USED
  2338. transmittance_color,
  2339. transmittance_depth,
  2340. transmittance_curve,
  2341. transmittance_boost,
  2342. #endif
  2343. #ifdef LIGHT_RIM_USED
  2344. rim,
  2345. rim_tint,
  2346. albedo,
  2347. #endif
  2348. #ifdef LIGHT_CLEARCOAT_USED
  2349. clearcoat, clearcoat_gloss,
  2350. #endif
  2351. #ifdef LIGHT_ANISOTROPY_USED
  2352. tangent, binormal, anisotropy,
  2353. #endif
  2354. #ifdef USE_SHADOW_TO_OPACITY
  2355. alpha,
  2356. #endif
  2357. diffuse_light, specular_light);
  2358. }
  2359. }
  2360. }
  2361. { //spot lights
  2362. uint cluster_spot_offset = cluster_offset + scene_data.cluster_type_size;
  2363. uint item_min;
  2364. uint item_max;
  2365. uint item_from;
  2366. uint item_to;
  2367. cluster_get_item_range(cluster_spot_offset + scene_data.max_cluster_element_count_div_32 + cluster_z, item_min, item_max, item_from, item_to);
  2368. #ifdef USE_SUBGROUPS
  2369. item_from = subgroupBroadcastFirst(subgroupMin(item_from));
  2370. item_to = subgroupBroadcastFirst(subgroupMax(item_to));
  2371. #endif
  2372. for (uint i = item_from; i < item_to; i++) {
  2373. uint mask = cluster_buffer.data[cluster_spot_offset + i];
  2374. mask &= cluster_get_range_clip_mask(i, item_min, item_max);
  2375. #ifdef USE_SUBGROUPS
  2376. uint merged_mask = subgroupBroadcastFirst(subgroupOr(mask));
  2377. #else
  2378. uint merged_mask = mask;
  2379. #endif
  2380. while (merged_mask != 0) {
  2381. uint bit = findMSB(merged_mask);
  2382. merged_mask &= ~(1 << bit);
  2383. #ifdef USE_SUBGROUPS
  2384. if (((1 << bit) & mask) == 0) { //do not process if not originally here
  2385. continue;
  2386. }
  2387. #endif
  2388. uint light_index = 32 * i + bit;
  2389. if (!bool(spot_lights.data[light_index].mask & instances.data[instance_index].layer_mask)) {
  2390. continue; //not masked
  2391. }
  2392. float shadow = light_process_spot_shadow(light_index, vertex, view);
  2393. shadow = blur_shadow(shadow);
  2394. light_process_spot(light_index, vertex, view, normal, vertex_ddx, vertex_ddy, f0, orms, shadow,
  2395. #ifdef LIGHT_BACKLIGHT_USED
  2396. backlight,
  2397. #endif
  2398. #ifdef LIGHT_TRANSMITTANCE_USED
  2399. transmittance_color,
  2400. transmittance_depth,
  2401. transmittance_curve,
  2402. transmittance_boost,
  2403. #endif
  2404. #ifdef LIGHT_RIM_USED
  2405. rim,
  2406. rim_tint,
  2407. albedo,
  2408. #endif
  2409. #ifdef LIGHT_CLEARCOAT_USED
  2410. clearcoat, clearcoat_gloss,
  2411. #endif
  2412. #ifdef LIGHT_ANISOTROPY_USED
  2413. tangent, binormal, anisotropy,
  2414. #endif
  2415. #ifdef USE_SHADOW_TO_OPACITY
  2416. alpha,
  2417. #endif
  2418. diffuse_light, specular_light);
  2419. }
  2420. }
  2421. }
  2422. #ifdef USE_SHADOW_TO_OPACITY
  2423. alpha = min(alpha, clamp(length(ambient_light), 0.0, 1.0));
  2424. #if defined(ALPHA_SCISSOR_USED)
  2425. if (alpha < alpha_scissor) {
  2426. discard;
  2427. }
  2428. #endif // ALPHA_SCISSOR_USED
  2429. #ifdef USE_OPAQUE_PREPASS
  2430. if (alpha < opaque_prepass_threshold) {
  2431. discard;
  2432. }
  2433. #endif // USE_OPAQUE_PREPASS
  2434. #endif // USE_SHADOW_TO_OPACITY
  2435. #endif //!defined(MODE_RENDER_DEPTH) && !defined(MODE_UNSHADED)
  2436. #ifdef MODE_RENDER_DEPTH
  2437. #ifdef MODE_RENDER_SDF
  2438. {
  2439. vec3 local_pos = (scene_data.sdf_to_bounds * vec4(vertex, 1.0)).xyz;
  2440. ivec3 grid_pos = scene_data.sdf_offset + ivec3(local_pos * vec3(scene_data.sdf_size));
  2441. uint albedo16 = 0x1; //solid flag
  2442. albedo16 |= clamp(uint(albedo.r * 31.0), 0, 31) << 11;
  2443. albedo16 |= clamp(uint(albedo.g * 31.0), 0, 31) << 6;
  2444. albedo16 |= clamp(uint(albedo.b * 31.0), 0, 31) << 1;
  2445. imageStore(albedo_volume_grid, grid_pos, uvec4(albedo16));
  2446. uint facing_bits = 0;
  2447. const vec3 aniso_dir[6] = vec3[](
  2448. vec3(1, 0, 0),
  2449. vec3(0, 1, 0),
  2450. vec3(0, 0, 1),
  2451. vec3(-1, 0, 0),
  2452. vec3(0, -1, 0),
  2453. vec3(0, 0, -1));
  2454. vec3 cam_normal = mat3(scene_data.camera_matrix) * normalize(normal_interp);
  2455. float closest_dist = -1e20;
  2456. for (uint i = 0; i < 6; i++) {
  2457. float d = dot(cam_normal, aniso_dir[i]);
  2458. if (d > closest_dist) {
  2459. closest_dist = d;
  2460. facing_bits = (1 << i);
  2461. }
  2462. }
  2463. imageAtomicOr(geom_facing_grid, grid_pos, facing_bits); //store facing bits
  2464. if (length(emission) > 0.001) {
  2465. float lumas[6];
  2466. vec3 light_total = vec3(0);
  2467. for (int i = 0; i < 6; i++) {
  2468. float strength = max(0.0, dot(cam_normal, aniso_dir[i]));
  2469. vec3 light = emission * strength;
  2470. light_total += light;
  2471. lumas[i] = max(light.r, max(light.g, light.b));
  2472. }
  2473. float luma_total = max(light_total.r, max(light_total.g, light_total.b));
  2474. uint light_aniso = 0;
  2475. for (int i = 0; i < 6; i++) {
  2476. light_aniso |= min(31, uint((lumas[i] / luma_total) * 31.0)) << (i * 5);
  2477. }
  2478. //compress to RGBE9995 to save space
  2479. const float pow2to9 = 512.0f;
  2480. const float B = 15.0f;
  2481. const float N = 9.0f;
  2482. const float LN2 = 0.6931471805599453094172321215;
  2483. float cRed = clamp(light_total.r, 0.0, 65408.0);
  2484. float cGreen = clamp(light_total.g, 0.0, 65408.0);
  2485. float cBlue = clamp(light_total.b, 0.0, 65408.0);
  2486. float cMax = max(cRed, max(cGreen, cBlue));
  2487. float expp = max(-B - 1.0f, floor(log(cMax) / LN2)) + 1.0f + B;
  2488. float sMax = floor((cMax / pow(2.0f, expp - B - N)) + 0.5f);
  2489. float exps = expp + 1.0f;
  2490. if (0.0 <= sMax && sMax < pow2to9) {
  2491. exps = expp;
  2492. }
  2493. float sRed = floor((cRed / pow(2.0f, exps - B - N)) + 0.5f);
  2494. float sGreen = floor((cGreen / pow(2.0f, exps - B - N)) + 0.5f);
  2495. float sBlue = floor((cBlue / pow(2.0f, exps - B - N)) + 0.5f);
  2496. //store as 8985 to have 2 extra neighbour bits
  2497. uint light_rgbe = ((uint(sRed) & 0x1FF) >> 1) | ((uint(sGreen) & 0x1FF) << 8) | (((uint(sBlue) & 0x1FF) >> 1) << 17) | ((uint(exps) & 0x1F) << 25);
  2498. imageStore(emission_grid, grid_pos, uvec4(light_rgbe));
  2499. imageStore(emission_aniso_grid, grid_pos, uvec4(light_aniso));
  2500. }
  2501. }
  2502. #endif
  2503. #ifdef MODE_RENDER_MATERIAL
  2504. albedo_output_buffer.rgb = albedo;
  2505. albedo_output_buffer.a = alpha;
  2506. normal_output_buffer.rgb = normal * 0.5 + 0.5;
  2507. normal_output_buffer.a = 0.0;
  2508. depth_output_buffer.r = -vertex.z;
  2509. orm_output_buffer.r = ao;
  2510. orm_output_buffer.g = roughness;
  2511. orm_output_buffer.b = metallic;
  2512. orm_output_buffer.a = sss_strength;
  2513. emission_output_buffer.rgb = emission;
  2514. emission_output_buffer.a = 0.0;
  2515. #endif
  2516. #ifdef MODE_RENDER_NORMAL_ROUGHNESS
  2517. normal_roughness_output_buffer = vec4(normal * 0.5 + 0.5, roughness);
  2518. #ifdef MODE_RENDER_GIPROBE
  2519. if (bool(instances.data[instance_index].flags & INSTANCE_FLAGS_USE_GIPROBE)) { // process giprobes
  2520. uint index1 = instances.data[instance_index].gi_offset & 0xFFFF;
  2521. uint index2 = instances.data[instance_index].gi_offset >> 16;
  2522. giprobe_buffer.x = index1 & 0xFF;
  2523. giprobe_buffer.y = index2 & 0xFF;
  2524. } else {
  2525. giprobe_buffer.x = 0xFF;
  2526. giprobe_buffer.y = 0xFF;
  2527. }
  2528. #endif
  2529. #endif //MODE_RENDER_NORMAL_ROUGHNESS
  2530. //nothing happens, so a tree-ssa optimizer will result in no fragment shader :)
  2531. #else
  2532. // multiply by albedo
  2533. diffuse_light *= albedo; // ambient must be multiplied by albedo at the end
  2534. // apply direct light AO
  2535. ao = unpackUnorm4x8(orms).x;
  2536. specular_light *= ao;
  2537. diffuse_light *= ao;
  2538. // apply metallic
  2539. metallic = unpackUnorm4x8(orms).z;
  2540. diffuse_light *= 1.0 - metallic;
  2541. ambient_light *= 1.0 - metallic;
  2542. //restore fog
  2543. fog = vec4(unpackHalf2x16(fog_rg), unpackHalf2x16(fog_ba));
  2544. #ifdef MODE_MULTIPLE_RENDER_TARGETS
  2545. #ifdef MODE_UNSHADED
  2546. diffuse_buffer = vec4(albedo.rgb, 0.0);
  2547. specular_buffer = vec4(0.0);
  2548. #else
  2549. #ifdef SSS_MODE_SKIN
  2550. sss_strength = -sss_strength;
  2551. #endif
  2552. diffuse_buffer = vec4(emission + diffuse_light + ambient_light, sss_strength);
  2553. specular_buffer = vec4(specular_light, metallic);
  2554. #endif
  2555. diffuse_buffer.rgb = mix(diffuse_buffer.rgb, fog.rgb, fog.a);
  2556. specular_buffer.rgb = mix(specular_buffer.rgb, vec3(0.0), fog.a);
  2557. #else //MODE_MULTIPLE_RENDER_TARGETS
  2558. #ifdef MODE_UNSHADED
  2559. frag_color = vec4(albedo, alpha);
  2560. #else
  2561. frag_color = vec4(emission + ambient_light + diffuse_light + specular_light, alpha);
  2562. //frag_color = vec4(1.0);
  2563. #endif //USE_NO_SHADING
  2564. // Draw "fixed" fog before volumetric fog to ensure volumetric fog can appear in front of the sky.
  2565. frag_color.rgb = mix(frag_color.rgb, fog.rgb, fog.a);
  2566. ;
  2567. #endif //MODE_MULTIPLE_RENDER_TARGETS
  2568. #endif //MODE_RENDER_DEPTH
  2569. }