Volumetrics.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. #include "Volumetrics.h"
  2. #include <bit>
  3. #include <cmath>
  4. #include <string>
  5. #include <glm/gtc/matrix_transform.hpp>
  6. #include "WallpaperEngine/Application/ApplicationContext.h"
  7. #include "WallpaperEngine/Application/WallpaperApplication.h"
  8. #include "WallpaperEngine/Data/Model/Object.h"
  9. #include "WallpaperEngine/Logging/Log.h"
  10. #include "WallpaperEngine/Render/RenderContext.h"
  11. #include "WallpaperEngine/Render/Wallpapers/CScene.h"
  12. using namespace WallpaperEngine::Render;
  13. namespace {
  14. const char* kVolumeVertex = R"(
  15. uniform mat4 u_ViewProjection;
  16. uniform mat4 u_Volume;
  17. uniform vec3 u_MeshScale;
  18. layout (location = 0) in vec3 a_Position;
  19. out vec4 v_ScreenPos;
  20. void main () {
  21. gl_Position = u_ViewProjection * u_Volume * vec4 (a_Position * u_MeshScale, 1.0);
  22. #if FULLSCREEN
  23. gl_Position = vec4 (a_Position.xy, -1.0, 1.0);
  24. #endif
  25. v_ScreenPos = gl_Position;
  26. }
  27. )";
  28. // the far side of the volume, as normalized depth
  29. const char* kBackFragment = R"(
  30. in vec4 v_ScreenPos;
  31. out vec4 fragColor;
  32. void main () {
  33. fragColor = vec4 (v_ScreenPos.z / v_ScreenPos.w, 0.0, 0.0, 1.0);
  34. }
  35. )";
  36. // assets/shaders/volumetricsfront.frag: from the near side of the volume to the far one (or the scene's depth in front
  37. // of it), the light's falloff summed over a few samples. With SHADOW each sample is compared against the light's tile
  38. // of _rt_shadowAtlas (g_Texture0), spots through the light's matrix scaled by 0.525 like the cookie, point lights
  39. // through common_pbr_2.h's CalculateProjectedCoordsPoint (copied below)
  40. const char* kFrontFragment = R"(
  41. #define mul(x, y) ((y) * (x))
  42. uniform sampler2D u_Back;
  43. uniform sampler2D u_SceneDepth;
  44. uniform mat4 u_InverseViewProjection;
  45. uniform vec2 u_BufferSize;
  46. uniform vec3 u_LightOrigin;
  47. uniform float u_Radius;
  48. uniform float u_Intensity;
  49. uniform float u_Density;
  50. uniform float u_Exponent;
  51. uniform vec3 u_Color;
  52. uniform vec3 u_SpotForward;
  53. uniform float u_SpotInner;
  54. uniform float u_SpotOuter;
  55. uniform sampler2D u_Cookie;
  56. uniform mat4 u_LightViewProjection;
  57. uniform vec3 u_EyePosition;
  58. uniform vec3 g_FogDistanceColor;
  59. uniform vec4 g_FogDistanceParams;
  60. uniform vec3 g_FogHeightColor;
  61. uniform vec4 g_FogHeightParams;
  62. uniform sampler2DShadow u_ShadowAtlas;
  63. uniform bool u_ShadowValid;
  64. uniform mat4 u_ShadowMatrix;
  65. uniform vec4 u_ShadowTransform;
  66. uniform vec4 u_PointProjection;
  67. in vec4 v_ScreenPos;
  68. out vec4 fragColor;
  69. #if SHADOW && POINTLIGHT
  70. vec4 CalculateProjectedCoordsPoint(vec3 worldPos, vec3 lightOrigin, vec4 projectionInfo, vec4 atlasTransform)
  71. {
  72. vec3 lightDelta = worldPos - lightOrigin;
  73. vec3 lightDeltaAbs = abs(lightDelta);
  74. vec2 viewportScale = vec2(0.5, 0.3333);
  75. #if LIGHTS_SHADOW_MAPPING_QUALITY == 2 || LIGHTS_SHADOW_MAPPING_QUALITY == 1
  76. vec2 viewportPointCompensation = vec2(0.47, -0.47);
  77. #elif LIGHTS_SHADOW_MAPPING_QUALITY == 3
  78. vec2 viewportPointCompensation = vec2(0.48, -0.48);
  79. #else
  80. vec2 viewportPointCompensation = vec2(0.49, -0.49);
  81. #endif
  82. vec2 viewportOffset;
  83. vec2 viewportOffsetSteps = atlasTransform.zw * viewportScale;
  84. mat4 viewMatrix;
  85. if (lightDeltaAbs.x >= lightDeltaAbs.y && lightDeltaAbs.x >= lightDeltaAbs.z)
  86. {
  87. if (lightDelta.x >= 0.0)
  88. {
  89. viewMatrix = mat4(
  90. 0, 0, -1, 0,
  91. 0, 1, 0, 0,
  92. 1, 0, 0, 0,
  93. -lightOrigin.z, -lightOrigin.y, lightOrigin.x, 1
  94. );
  95. viewportOffset = vec2(0.0, 0.0);
  96. }
  97. else
  98. {
  99. viewMatrix = mat4(
  100. 0, 0, 1, 0,
  101. 0, 1, 0, 0,
  102. -1, 0, 0, 0,
  103. lightOrigin.z, -lightOrigin.y, -lightOrigin.x, 1
  104. );
  105. viewportOffset = vec2(viewportOffsetSteps.x, 0.0);
  106. }
  107. }
  108. else if (lightDeltaAbs.y >= lightDeltaAbs.x && lightDeltaAbs.y >= lightDeltaAbs.z)
  109. {
  110. if (lightDelta.y >= 0.0)
  111. {
  112. viewMatrix = mat4(
  113. 1, 0, 0, 0,
  114. 0, 0, -1, 0,
  115. 0, 1, 0, 0,
  116. -lightOrigin.x, -lightOrigin.z, lightOrigin.y, 1
  117. );
  118. viewportOffset = vec2(0.0, viewportOffsetSteps.y);
  119. }
  120. else
  121. {
  122. viewMatrix = mat4(
  123. 1, 0, 0, 0,
  124. 0, 0, 1, 0,
  125. 0, -1, 0, 0,
  126. -lightOrigin.x, lightOrigin.z, -lightOrigin.y, 1
  127. );
  128. viewportOffset = vec2(viewportOffsetSteps.x, viewportOffsetSteps.y);
  129. }
  130. }
  131. else
  132. {
  133. if (lightDelta.z >= 0.0)
  134. {
  135. viewMatrix = mat4(
  136. -1, 0, 0, 0,
  137. 0, 1, 0, 0,
  138. 0, 0, -1, 0,
  139. lightOrigin.x, -lightOrigin.y, lightOrigin.z, 1
  140. );
  141. viewportOffset = vec2(0.0, viewportOffsetSteps.y * 2);
  142. }
  143. else
  144. {
  145. viewMatrix = mat4(
  146. 1, 0, 0, 0,
  147. 0, 1, 0, 0,
  148. 0, 0, 1, 0,
  149. -lightOrigin.x, -lightOrigin.y, -lightOrigin.z, 1
  150. );
  151. viewportOffset = vec2(viewportOffsetSteps.x, viewportOffsetSteps.y * 2);
  152. }
  153. }
  154. mat4 project = mat4(
  155. 1, 0, 0, 0,
  156. 0, 1, 0, 0,
  157. 0, 0, projectionInfo.x, projectionInfo.z,
  158. 0, 0, projectionInfo.y, projectionInfo.w
  159. );
  160. vec4 projectedCoords = mul(mul(vec4(worldPos, 1.0), viewMatrix), project);
  161. projectedCoords.xyz /= projectedCoords.w;
  162. projectedCoords.xy = projectedCoords.xy * viewportPointCompensation + vec2(0.5);
  163. projectedCoords.y = mix(projectedCoords.y, 2.0, step(projectedCoords.w, 0.0));
  164. projectedCoords.xy *= atlasTransform.zw * viewportScale;
  165. projectedCoords.xy += atlasTransform.xy + viewportOffset;
  166. return projectedCoords;
  167. }
  168. #endif
  169. float hash12 (vec2 p) {
  170. vec3 p3 = fract (vec3 (p.xyx) * 43758.5453);
  171. p3 += vec3 (dot (p3, p3.yzx + 19.19));
  172. return fract ((p3.x + p3.y) * p3.z);
  173. }
  174. float fogAlpha (float alpha, float viewLength, float height) {
  175. float fogDistance = 0.0;
  176. float fogHeight = 0.0;
  177. #if FOG_DIST
  178. fogDistance = clamp ((viewLength - g_FogDistanceParams.x) / g_FogDistanceParams.y, 0.0, 1.0);
  179. fogDistance = g_FogDistanceParams.z + g_FogDistanceParams.w * fogDistance * fogDistance;
  180. #endif
  181. #if FOG_HEIGHT
  182. fogHeight = clamp ((height - g_FogHeightParams.x) / g_FogHeightParams.y, 0.0, 1.0);
  183. fogHeight = g_FogHeightParams.z + g_FogHeightParams.w * fogHeight * fogHeight;
  184. #endif
  185. float fogFactor = clamp (max (fogDistance, fogHeight), 0.0, 1.0);
  186. return alpha * (1.0 - fogFactor * fogFactor);
  187. }
  188. void main () {
  189. vec3 screenDepth = v_ScreenPos.xyz / v_ScreenPos.w;
  190. vec2 screenUV = gl_FragCoord.xy / u_BufferSize;
  191. float backDepth = texture (u_SceneDepth, screenUV).r * 2.0 - 1.0;
  192. float limitDepth = texture (u_Back, screenUV).r;
  193. if (backDepth - screenDepth.z < 0.0) {
  194. discard;
  195. }
  196. backDepth = min (backDepth, limitDepth);
  197. vec4 worldStart = u_InverseViewProjection * vec4 (screenDepth, 1.0);
  198. vec4 worldEnd = u_InverseViewProjection * vec4 (screenDepth.xy, backDepth, 1.0);
  199. worldStart.xyz /= worldStart.w;
  200. worldEnd.xyz /= worldEnd.w;
  201. const float sampleCount = float (SAMPLES);
  202. vec3 worldStep = (worldEnd.xyz - worldStart.xyz) / (sampleCount + 1.0);
  203. float invRadius = 1.0 / u_Radius;
  204. float maxLightScale = u_Intensity * length (worldEnd.xyz - worldStart.xyz) * invRadius;
  205. #if POINTLIGHT
  206. maxLightScale *= 0.5;
  207. #endif
  208. #if SHADOW
  209. // WE's screen UV runs top down, this buffer bottom up
  210. worldStart.xyz += worldStep * hash12 (screenDepth.xy * 0.5 + 0.5);
  211. #endif
  212. #if COOKIE
  213. vec3 shadowFactor = vec3 (0.0);
  214. #else
  215. float shadowFactor = 0.0;
  216. #endif
  217. for (int s = 0; s < SAMPLES; ++s) {
  218. worldStart.xyz += worldStep;
  219. vec3 lightDelta = worldStart.xyz - u_LightOrigin;
  220. float sampleValue = pow (clamp (1.0 - length (lightDelta) * invRadius, 0.0, 1.0), u_Exponent);
  221. #if SHADOW
  222. if (u_ShadowValid) {
  223. #if POINTLIGHT
  224. vec4 shadowCoords = CalculateProjectedCoordsPoint (worldStart.xyz, u_LightOrigin, u_PointProjection, u_ShadowTransform);
  225. #else
  226. vec4 shadowCoords = u_ShadowMatrix * vec4 (worldStart.xyz, 1.0);
  227. shadowCoords.xyz /= shadowCoords.w;
  228. shadowCoords.xy = (shadowCoords.xy * vec2 (0.525, -0.525) + vec2 (0.5)) * u_ShadowTransform.zw + u_ShadowTransform.xy;
  229. #endif
  230. sampleValue *= texture (u_ShadowAtlas, shadowCoords.xyz);
  231. }
  232. #endif
  233. #if COOKIE
  234. // the cookie is projected through the light's own camera, a little bigger than its frustum
  235. vec4 uvs = u_LightViewProjection * vec4 (worldStart.xyz, 1.0);
  236. uvs.xyz /= uvs.w;
  237. vec3 cookieColor = texture (u_Cookie, uvs.xy * vec2 (0.525, -0.525) + vec2 (0.5)).rgb;
  238. #elif !POINTLIGHT
  239. sampleValue *= smoothstep (u_SpotOuter, u_SpotInner, dot (normalize (lightDelta), u_SpotForward));
  240. #endif
  241. #if FOG_DIST || FOG_HEIGHT
  242. sampleValue *= fogAlpha (sampleValue, length (u_EyePosition - worldStart.xyz), worldStart.y);
  243. #endif
  244. #if COOKIE
  245. shadowFactor += sampleValue * cookieColor;
  246. #else
  247. shadowFactor += sampleValue;
  248. #endif
  249. }
  250. shadowFactor /= sampleCount;
  251. fragColor = vec4 (u_Density * maxLightScale * shadowFactor * u_Color * 0.1, 1.0);
  252. }
  253. )";
  254. const char* kQuadVertex = R"(
  255. out vec2 v_TexCoord;
  256. void main () {
  257. vec2 corner = vec2 ((gl_VertexID << 1) & 2, gl_VertexID & 2);
  258. v_TexCoord = corner;
  259. gl_Position = vec4 (corner * 2.0 - 1.0, 0.0, 1.0);
  260. }
  261. )";
  262. // assets/shaders/blur_k3.frag
  263. const char* kBlurFragment = R"(
  264. uniform sampler2D g_Texture0;
  265. uniform vec2 u_Direction;
  266. in vec2 v_TexCoord;
  267. out vec4 fragColor;
  268. void main () {
  269. vec3 albedo = texture (g_Texture0, v_TexCoord + u_Direction).rgb * 0.25 + texture (g_Texture0, v_TexCoord).rgb * 0.5
  270. + texture (g_Texture0, v_TexCoord - u_Direction).rgb * 0.25;
  271. fragColor = vec4 (albedo, 1.0);
  272. }
  273. )";
  274. const char* kCompositeFragment = R"(
  275. uniform sampler2D g_Texture0;
  276. in vec2 v_TexCoord;
  277. out vec4 fragColor;
  278. void main () {
  279. fragColor = texture (g_Texture0, v_TexCoord);
  280. }
  281. )";
  282. GLuint compile (const std::string& defines, const char* vertex, const char* fragment) {
  283. const std::string header = "#version 330\n" + defines;
  284. const std::string vertexSource = header + vertex;
  285. const std::string fragmentSource = header + fragment;
  286. const char* sources[] = { vertexSource.c_str (), fragmentSource.c_str () };
  287. const GLenum types[] = { GL_VERTEX_SHADER, GL_FRAGMENT_SHADER };
  288. const GLuint program = glCreateProgram ();
  289. for (int unit = 0; unit < 2; unit++) {
  290. const GLuint shader = glCreateShader (types[unit]);
  291. glShaderSource (shader, 1, &sources[unit], nullptr);
  292. glCompileShader (shader);
  293. GLint compiled = GL_FALSE;
  294. glGetShaderiv (shader, GL_COMPILE_STATUS, &compiled);
  295. if (compiled == GL_FALSE) {
  296. char log[2048] = {};
  297. glGetShaderInfoLog (shader, sizeof (log) - 1, nullptr, log);
  298. sLog.error ("Volumetrics shader failed to compile: ", log);
  299. }
  300. glAttachShader (program, shader);
  301. glDeleteShader (shader);
  302. }
  303. glLinkProgram (program);
  304. return program;
  305. }
  306. // +1 when the triangles wind counterclockwise seen from outside the (convex) mesh, -1 when clockwise
  307. float outwardWinding (
  308. const std::vector<glm::vec3>& vertices, const std::vector<GLushort>& indices, const glm::vec3& inside
  309. ) {
  310. float sum = 0.0f;
  311. for (size_t i = 0; i + 2 < indices.size (); i += 3) {
  312. const glm::vec3& a = vertices[indices[i]];
  313. const glm::vec3 normal = glm::cross (vertices[indices[i + 1]] - a, vertices[indices[i + 2]] - a);
  314. sum += glm::dot (normal, a - inside) > 0.0f ? 1.0f : -1.0f;
  315. }
  316. return sum >= 0.0f ? 1.0f : -1.0f;
  317. }
  318. void createTarget (auto& target, const glm::ivec2 size, const GLenum format, const GLenum type, const GLenum layout) {
  319. glGenTextures (1, &target.texture);
  320. glBindTexture (GL_TEXTURE_2D, target.texture);
  321. glTexImage2D (GL_TEXTURE_2D, 0, format, size.x, size.y, 0, layout, type, nullptr);
  322. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  323. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  324. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  325. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  326. glGenFramebuffers (1, &target.framebuffer);
  327. glBindFramebuffer (GL_FRAMEBUFFER, target.framebuffer);
  328. glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target.texture, 0);
  329. }
  330. void destroyTarget (auto& target) {
  331. glDeleteFramebuffers (1, &target.framebuffer);
  332. glDeleteTextures (1, &target.texture);
  333. target = {};
  334. }
  335. } // namespace
  336. Volumetrics::Volumetrics (Wallpapers::CScene& scene) :
  337. m_scene (scene), m_quality (scene.getContext ().getApp ().getContext ().settings.general.volumetricsQuality) { }
  338. Volumetrics::~Volumetrics () {
  339. this->release ();
  340. for (const GLuint program : { this->m_backProgram, this->m_blurProgram, this->m_compositeProgram }) {
  341. if (program != GL_NONE) {
  342. glDeleteProgram (program);
  343. }
  344. }
  345. for (const auto& type : this->m_frontPrograms) {
  346. for (const auto& shadow : type) {
  347. for (const GLuint program : shadow) {
  348. if (program != GL_NONE) {
  349. glDeleteProgram (program);
  350. }
  351. }
  352. }
  353. }
  354. if (this->m_sceneDepth.texture != GL_NONE) {
  355. destroyTarget (this->m_sceneDepth);
  356. }
  357. for (auto* mesh : { &this->m_sphere, &this->m_cone, &this->m_box, &this->m_fullscreen }) {
  358. if (mesh->vao != GL_NONE) {
  359. glDeleteBuffers (1, &mesh->vertices);
  360. glDeleteBuffers (1, &mesh->indices);
  361. glDeleteVertexArrays (1, &mesh->vao);
  362. }
  363. }
  364. }
  365. void Volumetrics::upload (Mesh& mesh, const std::vector<glm::vec3>& vertices, const std::vector<GLushort>& indices) {
  366. glGenVertexArrays (1, &mesh.vao);
  367. glBindVertexArray (mesh.vao);
  368. glGenBuffers (1, &mesh.vertices);
  369. glBindBuffer (GL_ARRAY_BUFFER, mesh.vertices);
  370. glBufferData (
  371. GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (vertices.size () * sizeof (glm::vec3)), vertices.data (),
  372. GL_STATIC_DRAW
  373. );
  374. glGenBuffers (1, &mesh.indices);
  375. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, mesh.indices);
  376. glBufferData (
  377. GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (indices.size () * sizeof (GLushort)), indices.data (),
  378. GL_STATIC_DRAW
  379. );
  380. mesh.indexCount = static_cast<GLsizei> (indices.size ());
  381. glEnableVertexAttribArray (0);
  382. glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, sizeof (glm::vec3), nullptr);
  383. }
  384. void Volumetrics::setup () {
  385. // the light's volume, a unit sphere (sub_14025C660): poles, then 23 rings of 25 vertices (seam doubled) every 7.5
  386. // degrees from the top, 24 slices
  387. std::vector<glm::vec3> vertices = { { 0.0f, 1.0f, 0.0f }, { 0.0f, -1.0f, 0.0f } };
  388. for (int ring = 1; ring < 24; ring++) {
  389. const float latitude = static_cast<float> (ring) * 0.1308997f;
  390. for (int slice = 0; slice <= 24; slice++) {
  391. const float longitude = static_cast<float> (slice) * 0.2617994f;
  392. vertices.emplace_back (
  393. std::cos (longitude) * std::sin (latitude), std::cos (latitude),
  394. std::sin (longitude) * std::sin (latitude)
  395. );
  396. }
  397. }
  398. std::vector<GLushort> indices;
  399. for (int ring = 0; ring < 22; ring++) {
  400. for (int slice = 0; slice < 24; slice++) {
  401. const auto a = static_cast<GLushort> (2 + 25 * ring + slice);
  402. const auto c = static_cast<GLushort> (a + 25);
  403. indices.insert (
  404. indices.end (),
  405. { a, static_cast<GLushort> (a + 1), c, static_cast<GLushort> (a + 1), static_cast<GLushort> (c + 1), c }
  406. );
  407. }
  408. }
  409. for (int slice = 0; slice < 24; slice++) {
  410. indices.insert (indices.end (), { 0, static_cast<GLushort> (3 + slice), static_cast<GLushort> (2 + slice) });
  411. indices.insert (
  412. indices.end (), { 1, static_cast<GLushort> (552 + slice), static_cast<GLushort> (553 + slice) }
  413. );
  414. }
  415. this->upload (this->m_sphere, vertices, indices);
  416. this->m_sphere.winding = outwardWinding (vertices, indices, glm::vec3 (0.0f));
  417. // spot lights without a cookie: a cylinder in the light's clip space (a cone in the world) with 32 sides, depth 0
  418. // at the near plane and 1 at the far one, the caps fanned out from (0.5, 0.5) (sub_140196CE0)
  419. vertices = { { 0.5f, 0.5f, 0.0f }, { 0.5f, 0.5f, 1.0f } };
  420. indices.clear ();
  421. for (int side = 0; side < 32; side++) {
  422. const float angle = static_cast<float> (side) * 0.03125f * 6.2831855f;
  423. const float next = angle + 0.19634955f;
  424. const auto base = static_cast<GLushort> (vertices.size ());
  425. vertices.emplace_back (std::sin (angle), -std::cos (angle), 1.0f);
  426. vertices.emplace_back (std::sin (next), -std::cos (next), 1.0f);
  427. vertices.emplace_back (std::sin (angle), -std::cos (angle), 0.0f);
  428. vertices.emplace_back (std::sin (next), -std::cos (next), 0.0f);
  429. indices.insert (
  430. indices.end (),
  431. { static_cast<GLushort> (base + 2), base, static_cast<GLushort> (base + 1),
  432. static_cast<GLushort> (base + 2), static_cast<GLushort> (base + 1), static_cast<GLushort> (base + 3), 1,
  433. static_cast<GLushort> (base + 1), base, 0, static_cast<GLushort> (base + 2),
  434. static_cast<GLushort> (base + 3) }
  435. );
  436. }
  437. this->upload (this->m_cone, vertices, indices);
  438. this->m_cone.winding = outwardWinding (vertices, indices, glm::vec3 (0.0f, 0.0f, 0.5f));
  439. // cookie spots: the whole frustum as a box in the light's clip space (sub_140196CE0)
  440. vertices = { { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
  441. { -1.0f, -1.0f, 0.0f }, { 1.0f, -1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f }, { -1.0f, 1.0f, 0.0f } };
  442. indices = { 1, 0, 2, 2, 0, 3, 4, 5, 6, 4, 6, 7, 3, 0, 4, 3, 4, 7,
  443. 1, 2, 5, 5, 2, 6, 2, 3, 6, 6, 3, 7, 0, 1, 5, 0, 5, 4 };
  444. this->upload (this->m_box, vertices, indices);
  445. this->m_box.winding = outwardWinding (vertices, indices, glm::vec3 (0.0f, 0.0f, 0.5f));
  446. this->upload (
  447. this->m_fullscreen, { { -1.0f, 1.0f, 0.0f }, { -1.0f, -3.0f, 0.0f }, { 3.0f, 1.0f, 0.0f } }, { 0, 1, 2 }
  448. );
  449. // sample counts per quality, lights casting shadows take more and jitter the start (volumetricsfront.frag)
  450. const int quality = std::clamp (this->m_quality, 1, 4);
  451. const int plain[] = { 2, 3, 5, 8 };
  452. const int shadowed[] = { 12, 24, 32, 64 };
  453. std::string fog;
  454. if (this->m_scene.hasDistanceFog ()) {
  455. fog += "#define FOG_DIST 1\n";
  456. }
  457. if (this->m_scene.hasHeightFog ()) {
  458. fog += "#define FOG_HEIGHT 1\n";
  459. }
  460. const std::string samples = "#define SAMPLES " + std::to_string (plain[quality - 1]) + "\n";
  461. // LIGHTS_SHADOW_MAPPING_QUALITY only goes to point lights (renderer +428), the other shaders don't read it
  462. const std::string shadowSamples = "#define SHADOW 1\n#define SAMPLES " + std::to_string (shadowed[quality - 1])
  463. + "\n#define LIGHTS_SHADOW_MAPPING_QUALITY "
  464. + std::to_string (this->m_scene.getContext ().getApp ().getContext ().settings.general.shadowQuality) + "\n";
  465. this->m_backProgram = compile ("", kVolumeVertex, kBackFragment);
  466. // cookie lights take the shadowed sample counts too, but don't jitter
  467. const std::string cookieSamples
  468. = "#define COOKIE 1\n#define SAMPLES " + std::to_string (shadowed[quality - 1]) + "\n";
  469. for (int kind = 0; kind < 3; kind++) {
  470. for (int shadow = 0; shadow < 2; shadow++) {
  471. for (int fullscreen = 0; fullscreen < 2; fullscreen++) {
  472. std::string defines = fog + (shadow ? shadowSamples : kind == 2 ? cookieSamples : samples);
  473. if (shadow && kind == 2) {
  474. defines += "#define COOKIE 1\n";
  475. }
  476. if (kind == 0) {
  477. defines += "#define POINTLIGHT 1\n";
  478. }
  479. if (fullscreen) {
  480. defines += "#define FULLSCREEN 1\n";
  481. }
  482. this->m_frontPrograms[kind][shadow][fullscreen] = compile (defines, kVolumeVertex, kFrontFragment);
  483. }
  484. }
  485. }
  486. this->m_blurProgram = compile ("", kQuadVertex, kBlurFragment);
  487. this->m_compositeProgram = compile ("", kQuadVertex, kCompositeFragment);
  488. }
  489. void Volumetrics::allocate (const glm::ivec2 size) {
  490. this->release ();
  491. this->m_size = size;
  492. // the light buffer is 8 bit unless the scene renders in HDR (format 1 or 15, sub_140196CE0)
  493. const bool hdr = this->m_scene.isHDR ();
  494. createTarget (this->m_light, size, hdr ? GL_RGBA16F : GL_RGBA8, hdr ? GL_HALF_FLOAT : GL_UNSIGNED_BYTE, GL_RGBA);
  495. createTarget (this->m_lightB, size, hdr ? GL_RGBA16F : GL_RGBA8, hdr ? GL_HALF_FLOAT : GL_UNSIGNED_BYTE, GL_RGBA);
  496. createTarget (this->m_back, size, GL_R32F, GL_FLOAT, GL_RED);
  497. glBindTexture (GL_TEXTURE_2D, this->m_back.texture);
  498. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  499. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  500. // shared by the back pass and the light buffer
  501. glGenRenderbuffers (1, &this->m_backDepth);
  502. glBindRenderbuffer (GL_RENDERBUFFER, this->m_backDepth);
  503. glRenderbufferStorage (GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size.x, size.y);
  504. glBindFramebuffer (GL_FRAMEBUFFER, this->m_back.framebuffer);
  505. glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->m_backDepth);
  506. glBindFramebuffer (GL_FRAMEBUFFER, this->m_light.framebuffer);
  507. glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->m_backDepth);
  508. }
  509. void Volumetrics::release () {
  510. if (this->m_light.texture == GL_NONE) {
  511. return;
  512. }
  513. destroyTarget (this->m_light);
  514. destroyTarget (this->m_lightB);
  515. destroyTarget (this->m_back);
  516. glDeleteRenderbuffers (1, &this->m_backDepth);
  517. this->m_backDepth = GL_NONE;
  518. }
  519. glm::vec3 Volumetrics::approximateNormalize (const glm::vec3& vector) {
  520. const float lengthSquared = glm::dot (vector, vector);
  521. const float guess = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (lengthSquared) >> 1));
  522. const float inverse = (1.5f - lengthSquared * 0.5f * guess * guess) * guess;
  523. return vector * inverse;
  524. }
  525. glm::mat4
  526. Volumetrics::spotViewProjection (const Data::Model::Light& light, const glm::mat4& world, const bool orthographic) {
  527. // sub_14025D420: the light looks down its x axis (view rows z, y, -x of the normalized world axes) through a
  528. // right handed PerspectiveFov (sub_14009A360) of twice the outer cone, aspect 1, near 0.05 (1 in orthographic
  529. // scenes), far the radius. Depth runs 0..1 like Direct3D, the cone mesh is built in that space
  530. const glm::vec3 x = approximateNormalize (glm::vec3 (world[0]));
  531. const glm::vec3 y = approximateNormalize (glm::vec3 (world[1]));
  532. const glm::vec3 z = approximateNormalize (glm::vec3 (world[2]));
  533. const glm::vec3 origin (world[3]);
  534. glm::mat4 view (1.0f);
  535. for (int i = 0; i < 3; i++) {
  536. view[i][0] = z[i];
  537. view[i][1] = y[i];
  538. view[i][2] = -x[i];
  539. }
  540. view[3][0] = -glm::dot (z, origin);
  541. view[3][1] = -glm::dot (y, origin);
  542. view[3][2] = glm::dot (x, origin);
  543. const float near = orthographic ? 1.0f : 0.05f;
  544. const float far = std::max (light.radius->value->getFloat (), near + 0.01f);
  545. const float height = 1.0f / std::tan (light.outerCone->value->getFloat () * 0.017453292f);
  546. const float range = far / (near - far);
  547. glm::mat4 projection (0.0f);
  548. projection[0][0] = height;
  549. projection[1][1] = height;
  550. projection[2][2] = range;
  551. projection[2][3] = -1.0f;
  552. projection[3][2] = range * near;
  553. return projection * view;
  554. }
  555. void Volumetrics::copySceneDepth (const GLint framebuffer) {
  556. // _rt_volumetricsBack is a depth only target the size of the output, filled from the bound target's depth before
  557. // every light (render target vtable slot 8 -> CopyResource). A target of another size (a layer buffer) can't be
  558. // copied, the texture keeps what it had
  559. const auto fbo = this->m_scene.getFBO ();
  560. const glm::ivec2 size (fbo->getRealWidth (), fbo->getRealHeight ());
  561. if (size != this->m_sceneDepthSize) {
  562. if (this->m_sceneDepth.texture != GL_NONE) {
  563. destroyTarget (this->m_sceneDepth);
  564. }
  565. this->m_sceneDepthSize = size;
  566. glGenTextures (1, &this->m_sceneDepth.texture);
  567. glBindTexture (GL_TEXTURE_2D, this->m_sceneDepth.texture);
  568. glTexImage2D (
  569. GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, size.x, size.y, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr
  570. );
  571. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  572. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  573. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  574. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  575. glGenFramebuffers (1, &this->m_sceneDepth.framebuffer);
  576. glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneDepth.framebuffer);
  577. glFramebufferTexture2D (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, this->m_sceneDepth.texture, 0);
  578. glDrawBuffer (GL_NONE);
  579. glReadBuffer (GL_NONE);
  580. // passes leave their own depthwrite behind, and glClear honors it
  581. glDepthMask (GL_TRUE);
  582. glClearDepth (1.0);
  583. glClear (GL_DEPTH_BUFFER_BIT);
  584. glBindFramebuffer (GL_FRAMEBUFFER, framebuffer);
  585. }
  586. GLint type = GL_NONE;
  587. GLint renderbuffer = GL_NONE;
  588. glGetFramebufferAttachmentParameteriv (
  589. GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type
  590. );
  591. if (framebuffer == 0 || type != GL_RENDERBUFFER) {
  592. return;
  593. }
  594. glGetFramebufferAttachmentParameteriv (
  595. GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &renderbuffer
  596. );
  597. GLint previousRenderbuffer = 0;
  598. GLint width = 0;
  599. GLint height = 0;
  600. glGetIntegerv (GL_RENDERBUFFER_BINDING, &previousRenderbuffer);
  601. glBindRenderbuffer (GL_RENDERBUFFER, renderbuffer);
  602. glGetRenderbufferParameteriv (GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
  603. glGetRenderbufferParameteriv (GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
  604. glBindRenderbuffer (GL_RENDERBUFFER, previousRenderbuffer);
  605. if (glm::ivec2 (width, height) != size) {
  606. return;
  607. }
  608. glBindFramebuffer (GL_READ_FRAMEBUFFER, framebuffer);
  609. glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_sceneDepth.framebuffer);
  610. glBlitFramebuffer (0, 0, size.x, size.y, 0, 0, size.x, size.y, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  611. glBindFramebuffer (GL_FRAMEBUFFER, framebuffer);
  612. }
  613. void Volumetrics::renderLight (
  614. const Data::Model::Light& light, const glm::mat4& world, const glm::mat4& viewProjection, const Shadow* shadow
  615. ) {
  616. if (this->m_quality <= 0) {
  617. return;
  618. }
  619. if (this->m_sphere.vao == GL_NONE) {
  620. this->setup ();
  621. }
  622. // light buffer at an eighth of the output resolution, a quarter from high quality up
  623. const glm::ivec2 size
  624. = glm::max (this->m_scene.getOutputResolution () / (this->m_quality >= 3 ? 4 : 8), glm::ivec2 (1));
  625. if (size != this->m_size) {
  626. this->allocate (size);
  627. }
  628. GLint previousFramebuffer = 0;
  629. GLint previousVao = 0;
  630. GLint previousViewport[4] = {};
  631. glGetIntegerv (GL_FRAMEBUFFER_BINDING, &previousFramebuffer);
  632. glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVao);
  633. glGetIntegerv (GL_VIEWPORT, previousViewport);
  634. this->copySceneDepth (previousFramebuffer);
  635. const bool spot = light.type == Data::Model::LightType::Spot;
  636. const bool cookie = spot && light.useCookie->value->getBool ();
  637. const float radius = light.radius->value->getFloat ();
  638. const glm::vec3 origin (world[3]);
  639. const auto& fog = this->m_scene.getFog ();
  640. const auto& camera = this->m_scene.getCamera ();
  641. const glm::vec3 forward = camera.isOrthogonal ()
  642. ? glm::vec3 (0.0f, 0.0f, -1.0f)
  643. : -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
  644. const glm::vec3 probe = fog.eyeWorld + forward * 0.2f - origin;
  645. const bool shadowed = light.castShadow->value->getBool ()
  646. && this->m_scene.getContext ().getApp ().getContext ().settings.general.shadowQuality > 0;
  647. glm::mat4 volume;
  648. bool inside;
  649. const glm::mat4 lightViewProjection
  650. = spot ? spotViewProjection (light, world, camera.isOrthogonal ()) : glm::mat4 (1.0f);
  651. if (cookie) {
  652. // the eye is inside the frustum's planes (sub_1401849E0: x+w, w-x, y+w, w-y, z+w, w-z all >= 0) of the light's
  653. // +824 matrix, which has reversed depth (z' = w - z here). That gives 0 <= z <= 2w: the near plane counts, the
  654. // far one practically never does (2w lies past the camera's infinite distance once far > 2 near)
  655. volume = glm::inverse (lightViewProjection);
  656. const glm::vec4 clip = lightViewProjection * glm::vec4 (fog.eyeWorld + forward * 0.1f, 1.0f);
  657. inside
  658. = std::abs (clip.x) <= clip.w && std::abs (clip.y) <= clip.w && clip.z >= 0.0f && clip.z <= 2.0f * clip.w;
  659. } else if (spot) {
  660. // the cone is drawn from the light's clip space, whose inverse also gives the cone's radius at the far plane.
  661. // The eye is inside when it's in front of the light, no further than the radius and within the cone there
  662. volume = glm::inverse (lightViewProjection);
  663. const glm::vec3 direction = glm::normalize (glm::vec3 (world[0]));
  664. const float along = glm::dot (direction, probe);
  665. const float across = glm::length (probe - direction * along);
  666. const glm::vec4 center = volume * glm::vec4 (0.0f, 0.0f, 1.0f, 1.0f);
  667. const glm::vec4 edge = volume * glm::vec4 (0.0f, 1.0f, 1.0f, 1.0f);
  668. const float farRadius = glm::length (glm::vec3 (edge) / edge.w - glm::vec3 (center) / center.w);
  669. inside = along > 0.0f && radius >= along && along / radius * farRadius >= across;
  670. } else {
  671. volume = world * glm::scale (glm::mat4 (1.0f), glm::vec3 (radius));
  672. inside = radius * radius > glm::dot (probe, probe);
  673. }
  674. const Mesh& mesh = cookie ? this->m_box : spot ? this->m_cone : this->m_sphere;
  675. // volumetrics_back and volumetrics_front cull (cullmode normal): the back pass only draws the far side of the
  676. // volume and the front pass only the near one, so where the scene's depth range clips the far side off the ray
  677. // runs to the far plane. The near side faces the viewer when the mesh's outward winding, flipped by a mirroring
  678. // transform, comes out clockwise on screen
  679. const bool nearIsFront = mesh.winding * glm::determinant (viewProjection * volume) < 0.0f;
  680. glBindVertexArray (mesh.vao);
  681. glViewport (0, 0, size.x, size.y);
  682. glEnable (GL_CULL_FACE);
  683. glFrontFace (GL_CCW);
  684. glCullFace (nearIsFront ? GL_FRONT : GL_BACK);
  685. glDisable (GL_BLEND);
  686. glEnable (GL_DEPTH_TEST);
  687. glDepthMask (GL_TRUE);
  688. glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  689. // far side of the volume
  690. glBindFramebuffer (GL_FRAMEBUFFER, this->m_back.framebuffer);
  691. glClearColor (1.0f, 0.0f, 0.0f, 0.0f);
  692. glClearDepth (0.0);
  693. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  694. glDepthFunc (GL_GREATER);
  695. glUseProgram (this->m_backProgram);
  696. glUniformMatrix4fv (
  697. glGetUniformLocation (this->m_backProgram, "u_ViewProjection"), 1, GL_FALSE, &viewProjection[0][0]
  698. );
  699. glUniformMatrix4fv (glGetUniformLocation (this->m_backProgram, "u_Volume"), 1, GL_FALSE, &volume[0][0]);
  700. glUniform3f (glGetUniformLocation (this->m_backProgram, "u_MeshScale"), 1.0f, 1.0f, 1.0f);
  701. glDrawElements (GL_TRIANGLES, mesh.indexCount, GL_UNSIGNED_SHORT, nullptr);
  702. // near side, added into the light buffer. Cleared by the first light since the last composite
  703. glBindFramebuffer (GL_FRAMEBUFFER, this->m_light.framebuffer);
  704. glClearDepth (1.0);
  705. if (!this->m_pending) {
  706. glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
  707. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  708. this->m_pending = true;
  709. } else {
  710. glClear (GL_DEPTH_BUFFER_BIT);
  711. }
  712. glDepthFunc (GL_LESS);
  713. glCullFace (nearIsFront ? GL_BACK : GL_FRONT);
  714. glEnable (GL_BLEND);
  715. glBlendEquation (GL_FUNC_ADD);
  716. glBlendFunc (GL_ONE, GL_ONE);
  717. const GLuint program = this->m_frontPrograms[cookie ? 2 : spot ? 1 : 0][shadowed][inside];
  718. const glm::mat4 inverse = glm::inverse (viewProjection);
  719. const glm::vec3 color = light.color->value->getVec3 ();
  720. const glm::vec3 spotForward (world[0]);
  721. glUseProgram (program);
  722. glActiveTexture (GL_TEXTURE1);
  723. glBindTexture (GL_TEXTURE_2D, this->m_sceneDepth.texture);
  724. glActiveTexture (GL_TEXTURE0);
  725. glBindTexture (GL_TEXTURE_2D, this->m_back.texture);
  726. glUniform1i (glGetUniformLocation (program, "u_Back"), 0);
  727. glUniform1i (glGetUniformLocation (program, "u_SceneDepth"), 1);
  728. glUniformMatrix4fv (
  729. glGetUniformLocation (program, "u_LightViewProjection"), 1, GL_FALSE, &lightViewProjection[0][0]
  730. );
  731. if (cookie) {
  732. // the light's own cookie texture (light +816, sub_14025D080)
  733. const auto texture = this->m_scene.getContext ().resolveTexture (
  734. light.cookie.empty () ? "cookie/flashlight1" : light.cookie, this->m_scene.getScene ().project
  735. );
  736. glActiveTexture (GL_TEXTURE2);
  737. glBindTexture (GL_TEXTURE_2D, texture->getTextureID (0));
  738. glActiveTexture (GL_TEXTURE0);
  739. glUniform1i (glGetUniformLocation (program, "u_Cookie"), 2);
  740. }
  741. // g_RenderVar0 = the tile's atlas transform, g_RenderVar3 = the point projection, g_AltModelMatrix = the spot's
  742. // matrix, the atlas on g_Texture0 with WE's comparison sampler (CFBO::setupDepthOnly)
  743. const bool shadowValid = shadowed && shadow != nullptr && shadow->atlasTransform != nullptr;
  744. glUniform1i (glGetUniformLocation (program, "u_ShadowValid"), shadowValid ? 1 : 0);
  745. if (shadowValid) {
  746. glActiveTexture (GL_TEXTURE3);
  747. glBindTexture (GL_TEXTURE_2D, this->m_scene.getShadowAtlas ()->getTextureID (0));
  748. glActiveTexture (GL_TEXTURE0);
  749. glUniform1i (glGetUniformLocation (program, "u_ShadowAtlas"), 3);
  750. glUniformMatrix4fv (glGetUniformLocation (program, "u_ShadowMatrix"), 1, GL_FALSE, &shadow->matrix[0][0]);
  751. glUniform4fv (glGetUniformLocation (program, "u_ShadowTransform"), 1, &(*shadow->atlasTransform)[0]);
  752. glUniform4fv (glGetUniformLocation (program, "u_PointProjection"), 1, &shadow->pointProjection[0]);
  753. }
  754. glUniformMatrix4fv (glGetUniformLocation (program, "u_ViewProjection"), 1, GL_FALSE, &viewProjection[0][0]);
  755. glUniformMatrix4fv (glGetUniformLocation (program, "u_Volume"), 1, GL_FALSE, &volume[0][0]);
  756. glUniformMatrix4fv (glGetUniformLocation (program, "u_InverseViewProjection"), 1, GL_FALSE, &inverse[0][0]);
  757. // volumetricsfront.vert pulls the cone's sides in a little, the sphere stays as it is
  758. glUniform3f (glGetUniformLocation (program, "u_MeshScale"), spot ? 0.99f : 1.0f, spot ? 0.99f : 1.0f, 1.0f);
  759. glUniform2f (
  760. glGetUniformLocation (program, "u_BufferSize"), static_cast<float> (size.x), static_cast<float> (size.y)
  761. );
  762. glUniform3fv (glGetUniformLocation (program, "u_LightOrigin"), 1, &origin[0]);
  763. // g_RenderVar1.x is 99% of the radius, the falloff ends just inside the mesh
  764. glUniform1f (glGetUniformLocation (program, "u_Radius"), radius * 0.99f);
  765. glUniform1f (glGetUniformLocation (program, "u_Intensity"), light.intensity->value->getFloat ());
  766. glUniform1f (glGetUniformLocation (program, "u_Density"), light.density->value->getFloat ());
  767. glUniform1f (glGetUniformLocation (program, "u_Exponent"), light.volumetricsExponent->value->getFloat ());
  768. glUniform3fv (glGetUniformLocation (program, "u_Color"), 1, &color[0]);
  769. // g_RenderVar1.yz are the cosines of the cone angles, g_RenderVar3 the world matrix's x row as it is
  770. glUniform1f (
  771. glGetUniformLocation (program, "u_SpotInner"), std::cos (light.innerCone->value->getFloat () * 0.017453292f)
  772. );
  773. glUniform1f (
  774. glGetUniformLocation (program, "u_SpotOuter"), std::cos (light.outerCone->value->getFloat () * 0.017453292f)
  775. );
  776. glUniform3fv (glGetUniformLocation (program, "u_SpotForward"), 1, &spotForward[0]);
  777. glUniform3fv (glGetUniformLocation (program, "u_EyePosition"), 1, &fog.eyeWorld[0]);
  778. glUniform3fv (glGetUniformLocation (program, "g_FogDistanceColor"), 1, &fog.distanceColor[0]);
  779. glUniform4fv (glGetUniformLocation (program, "g_FogDistanceParams"), 1, &fog.distanceParams[0]);
  780. glUniform3fv (glGetUniformLocation (program, "g_FogHeightColor"), 1, &fog.heightColor[0]);
  781. glUniform4fv (glGetUniformLocation (program, "g_FogHeightParams"), 1, &fog.heightParamsWorld[0]);
  782. // from inside the volume a triangle covering the screen (-1,1 / -1,-3 / 3,1) goes through volumetrics_fullscreen
  783. if (inside) {
  784. glDisable (GL_CULL_FACE);
  785. glBindVertexArray (this->m_fullscreen.vao);
  786. glDrawElements (GL_TRIANGLES, this->m_fullscreen.indexCount, GL_UNSIGNED_SHORT, nullptr);
  787. } else {
  788. glDrawElements (GL_TRIANGLES, mesh.indexCount, GL_UNSIGNED_SHORT, nullptr);
  789. }
  790. // passes only switch culling on and off, they expect the back faces to go
  791. glCullFace (GL_BACK);
  792. glFrontFace (GL_CCW);
  793. glDisable (GL_CULL_FACE);
  794. glDisable (GL_DEPTH_TEST);
  795. glDepthFunc (GL_LESS);
  796. glDisable (GL_BLEND);
  797. glBindFramebuffer (GL_FRAMEBUFFER, previousFramebuffer);
  798. glBindVertexArray (previousVao);
  799. glViewport (previousViewport[0], previousViewport[1], previousViewport[2], previousViewport[3]);
  800. }
  801. void Volumetrics::composite () {
  802. if (!this->m_pending) {
  803. return;
  804. }
  805. this->m_pending = false;
  806. GLint previousFramebuffer = 0;
  807. GLint previousVao = 0;
  808. GLint previousViewport[4] = {};
  809. glGetIntegerv (GL_FRAMEBUFFER_BINDING, &previousFramebuffer);
  810. glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVao);
  811. glGetIntegerv (GL_VIEWPORT, previousViewport);
  812. glBindVertexArray (this->m_fullscreen.vao);
  813. glDisable (GL_DEPTH_TEST);
  814. glDisable (GL_CULL_FACE);
  815. glDisable (GL_BLEND);
  816. glActiveTexture (GL_TEXTURE0);
  817. // volumetrics_blur_h/_v below high quality, buffer A -> B -> A
  818. if (this->m_quality < 3) {
  819. glViewport (0, 0, this->m_size.x, this->m_size.y);
  820. glUseProgram (this->m_blurProgram);
  821. glUniform1i (glGetUniformLocation (this->m_blurProgram, "g_Texture0"), 0);
  822. glBindFramebuffer (GL_FRAMEBUFFER, this->m_lightB.framebuffer);
  823. glBindTexture (GL_TEXTURE_2D, this->m_light.texture);
  824. glUniform2f (
  825. glGetUniformLocation (this->m_blurProgram, "u_Direction"), 1.0f / static_cast<float> (this->m_size.x), 0.0f
  826. );
  827. glDrawArrays (GL_TRIANGLES, 0, 3);
  828. glBindFramebuffer (GL_FRAMEBUFFER, this->m_light.framebuffer);
  829. glBindTexture (GL_TEXTURE_2D, this->m_lightB.texture);
  830. glUniform2f (
  831. glGetUniformLocation (this->m_blurProgram, "u_Direction"), 0.0f, 1.0f / static_cast<float> (this->m_size.y)
  832. );
  833. glDrawArrays (GL_TRIANGLES, 0, 3);
  834. }
  835. // volumetrics_combine: added onto the scene
  836. glBindFramebuffer (GL_FRAMEBUFFER, previousFramebuffer);
  837. glViewport (previousViewport[0], previousViewport[1], previousViewport[2], previousViewport[3]);
  838. glEnable (GL_BLEND);
  839. glBlendEquation (GL_FUNC_ADD);
  840. glBlendFuncSeparate (GL_ONE, GL_ONE, GL_ZERO, GL_ONE);
  841. glUseProgram (this->m_compositeProgram);
  842. glUniform1i (glGetUniformLocation (this->m_compositeProgram, "g_Texture0"), 0);
  843. glBindTexture (GL_TEXTURE_2D, this->m_light.texture);
  844. glDrawArrays (GL_TRIANGLES, 0, 3);
  845. glDisable (GL_BLEND);
  846. glBindVertexArray (previousVao);
  847. }