CPass.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  1. #include "CPass.h"
  2. #include <algorithm>
  3. #include <cctype>
  4. #include <cmath>
  5. #include <cstdlib>
  6. #include <ranges>
  7. #include <sstream>
  8. #include <type_traits>
  9. #include <utility>
  10. #include "WallpaperEngine/Desktop/UserShortcut.h"
  11. #include "WallpaperEngine/Render/Helpers/ContextAware.h"
  12. #include "WallpaperEngine/Data/Model/Effect.h"
  13. #include "WallpaperEngine/Data/Model/Material.h"
  14. #include "WallpaperEngine/Data/Model/Project.h"
  15. #include "WallpaperEngine/Data/Model/Property.h"
  16. #include "WallpaperEngine/Render/Wallpapers/CScene.h"
  17. #include "WallpaperEngine/Render/CFBO.h"
  18. #include "WallpaperEngine/Render/Objects/CImage.h"
  19. #include "WallpaperEngine/Render/Shaders/ShaderCache.h"
  20. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariable.h"
  21. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableFloat.h"
  22. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableInteger.h"
  23. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector2.h"
  24. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector3.h"
  25. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector4.h"
  26. #include "WallpaperEngine/Logging/Log.h"
  27. using namespace WallpaperEngine;
  28. using namespace WallpaperEngine::Render;
  29. using namespace WallpaperEngine::Render::Objects;
  30. using namespace WallpaperEngine::Render::Shaders::Variables;
  31. using namespace WallpaperEngine::Render::Objects::Effects;
  32. extern float g_Time;
  33. extern float g_Daytime;
  34. CPass::UniformEntry::~UniformEntry () {
  35. if (!this->owned) {
  36. return;
  37. }
  38. switch (this->type) {
  39. case Double:
  40. delete static_cast<const double*> (this->value);
  41. break;
  42. case Float:
  43. delete static_cast<const float*> (this->value);
  44. break;
  45. case Integer:
  46. delete static_cast<const int*> (this->value);
  47. break;
  48. case Vector4:
  49. delete static_cast<const glm::vec4*> (this->value);
  50. break;
  51. case Vector3:
  52. delete static_cast<const glm::vec3*> (this->value);
  53. break;
  54. case Vector2:
  55. delete static_cast<const glm::vec2*> (this->value);
  56. break;
  57. case Matrix4:
  58. delete static_cast<const glm::mat4*> (this->value);
  59. break;
  60. case Matrix3:
  61. delete static_cast<const glm::mat3*> (this->value);
  62. break;
  63. }
  64. }
  65. const TextureMap DEFAULT_BINDS = {};
  66. const ImageEffectPassOverride DEFAULT_OVERRIDE = {};
  67. // objects that don't provide their own layer-to-screen mapping (text, particles) keep the old identity
  68. const glm::mat4 IDENTITY_MATRIX = glm::mat4 (1.0);
  69. const glm::mat3 IDENTITY_MATRIX3 = glm::mat3 (1.0);
  70. namespace {
  71. std::string textureSizeLabel (const std::shared_ptr<const TextureProvider>& texture) {
  72. if (texture == nullptr) {
  73. return "<null>";
  74. }
  75. return std::to_string (texture->getRealWidth ()) + "x" + std::to_string (texture->getRealHeight ());
  76. }
  77. // shader used by Wallpaper Engine's built-in "X-Ray" interactive effect (effects/xray/effect.json)
  78. const std::string XRAY_EFFECT_SHADER = "effects/xray";
  79. // The xray shader gates its reveal on a halo sprite sample around the pointer, so no uniform can make it cover
  80. // the screen. g_XrayReveal replaces that sample when >= 0: 1 everywhere (full), 0 never (disabled)
  81. const std::string XRAY_MULTIPLY_UNIFORM = "uniform float g_Multiply;";
  82. const std::string XRAY_REVEAL_UNIFORM_DECL = "uniform float g_Multiply;\nuniform float g_XrayReveal;";
  83. const std::string XRAY_BLEND_LINE = "blend *= (blendSample.x * blendSample.y);";
  84. const std::string XRAY_BLEND_LINE_PATCHED
  85. = "blend *= (g_XrayReveal < 0.0 ? blendSample.x * blendSample.y : g_XrayReveal);";
  86. // false (source untouched) if the anchors weren't found, xray modes then do nothing
  87. bool patchXrayRevealOverride (std::string& fragmentSource) {
  88. const auto blendPos = fragmentSource.find (XRAY_BLEND_LINE);
  89. const auto uniformPos = fragmentSource.find (XRAY_MULTIPLY_UNIFORM);
  90. if (blendPos == std::string::npos || uniformPos == std::string::npos) {
  91. return false;
  92. }
  93. // replace the later occurrence first so the earlier one's position stays valid
  94. fragmentSource.replace (blendPos, XRAY_BLEND_LINE.size (), XRAY_BLEND_LINE_PATCHED);
  95. fragmentSource.replace (uniformPos, XRAY_MULTIPLY_UNIFORM.size (), XRAY_REVEAL_UNIFORM_DECL);
  96. return true;
  97. }
  98. }
  99. CPass::CPass (
  100. CRenderable& renderable, std::shared_ptr<const FBOProvider> fboProvider, const MaterialPass& pass,
  101. std::optional<std::reference_wrapper<const ImageEffectPassOverride>> override,
  102. std::optional<std::reference_wrapper<const TextureMap>> binds,
  103. std::optional<std::reference_wrapper<std::string>> target
  104. ) :
  105. Helpers::ContextAware (renderable), m_renderable (renderable), m_fboProvider (std::move (fboProvider)),
  106. m_pass (pass), m_binds (binds.has_value () ? binds.value ().get () : DEFAULT_BINDS),
  107. m_override (override.has_value () ? override.value ().get () : DEFAULT_OVERRIDE), m_target (target),
  108. m_blendingmode (pass.blending), m_vao (GL_NONE) {
  109. this->m_effectTextureProjectionMatrix = &IDENTITY_MATRIX;
  110. this->m_effectTextureProjectionMatrixInverse = &IDENTITY_MATRIX;
  111. this->m_lightingModelMatrix = &IDENTITY_MATRIX;
  112. this->m_lightingNormalMatrix = &IDENTITY_MATRIX3;
  113. this->m_lightingViewProjectionMatrix = &IDENTITY_MATRIX;
  114. this->setupShaders ();
  115. glGenVertexArrays (1, &m_vao);
  116. }
  117. CPass::~CPass () {
  118. for (const auto& texture : this->m_playbackTextures) {
  119. texture->decrementUsageCount ();
  120. }
  121. for (const auto& value : this->m_uniforms | std::views::values) {
  122. delete value;
  123. }
  124. for (const auto& value : this->m_referenceUniforms | std::views::values) {
  125. delete value;
  126. }
  127. for (const auto* attrib : this->m_attribs) {
  128. delete attrib;
  129. }
  130. // text layers rebuild their passes on every glyph texture resize, so this can't be left to leak
  131. this->m_shader = nullptr;
  132. this->m_compiled = nullptr;
  133. glDeleteVertexArrays (1, &m_vao);
  134. this->m_vao = GL_NONE;
  135. if (this->releaseSharedProgram ()) {
  136. return;
  137. }
  138. if (!glIsProgram (this->m_programID)) {
  139. return; // program already invalid or deleted
  140. }
  141. GLint shaderCount = 0;
  142. glGetProgramiv (this->m_programID, GL_ATTACHED_SHADERS, &shaderCount);
  143. if (shaderCount > 0) {
  144. std::vector<GLuint> attachedShaders (shaderCount);
  145. glGetAttachedShaders (this->m_programID, shaderCount, nullptr, attachedShaders.data ());
  146. for (GLuint s : attachedShaders) {
  147. if (glIsShader (s)) {
  148. glDeleteShader (s);
  149. }
  150. }
  151. }
  152. glDeleteProgram (this->m_programID);
  153. this->m_programID = 0;
  154. }
  155. std::shared_ptr<const TextureProvider> CPass::resolveTexture (
  156. std::shared_ptr<const TextureProvider> expected, int index, std::shared_ptr<const TextureProvider> previous
  157. ) {
  158. if (expected == nullptr) {
  159. if (const auto it = this->m_fbos.find (index); it != this->m_fbos.end ()) {
  160. expected = it->second;
  161. }
  162. }
  163. const auto it = this->m_binds.find (index);
  164. if (it == this->m_binds.end ()) {
  165. return expected;
  166. }
  167. // a bind named "previous" is just another way of telling it to use whatever texture there was already
  168. if (it->second == "previous") {
  169. return this->m_previousInput ?: (previous ?: expected);
  170. }
  171. return this->resolveFBO (it->second);
  172. }
  173. void CPass::trackPlayback (const std::shared_ptr<const TextureProvider>& texture) {
  174. // the renderable already counts its own texture, and frame buffers have nothing to play back
  175. if (texture == nullptr || texture == this->m_renderable.getTexture ()
  176. || std::ranges::find (this->m_playbackTextures, texture) != this->m_playbackTextures.end ()) {
  177. return;
  178. }
  179. texture->incrementUsageCount ();
  180. this->m_playbackTextures.push_back (texture);
  181. }
  182. void CPass::updatePlaybackTextures () const {
  183. for (const auto& texture : this->m_playbackTextures) {
  184. texture->update ();
  185. }
  186. }
  187. std::optional<std::string> CPass::resolveUserTextureName (const std::string& propertyName) const {
  188. const auto& properties = this->m_renderable.getScene ().getScene ().project.properties;
  189. const auto it = properties.find (propertyName);
  190. if (it != properties.end ()) {
  191. it->second->pin ();
  192. }
  193. if (it == properties.end ()) {
  194. // not actually a property reference, treat it as a literal texture name like before
  195. return propertyName;
  196. }
  197. // an assigned shortcut shows its icon, TextureCache loads it from outside the wallpaper
  198. if (it->second->is<PropertyUserShortcut> ()) {
  199. const auto shortcut = Desktop::UserShortcut::parse (it->second->getString ());
  200. const auto icon = shortcut.has_value () ? shortcut->iconPath () : std::nullopt;
  201. return icon.has_value () ? std::optional<std::string> ("$usershortcut:" + icon->string ()) : std::nullopt;
  202. }
  203. const std::string& value = it->second->getString ();
  204. if (value.empty ()) {
  205. // the "scenetexture" property exists but the user hasn't imported an image for it -
  206. // this is the normal state for most wallpapers that expose this as an optional slot
  207. return std::nullopt;
  208. }
  209. return value;
  210. }
  211. std::shared_ptr<const TextureProvider> CPass::resolveNamedTexture (const std::string& name) const {
  212. // lit materials sample every cookie spot through one alias, the scene's light cookie (sub_140190C80)
  213. if (name == "_alias_lightCookie") {
  214. return this->m_renderable.getScene ().getLightCookie ();
  215. }
  216. // WE finds only _a of a named layer buffer by name (sub_1401EA500), anything else binds the checker
  217. // (sub_1400EEF70). A layer's own buffers stay reachable
  218. constexpr std::string_view compositePrefix = "_rt_imageLayerComposite_";
  219. if (name.starts_with (compositePrefix)) {
  220. const auto separator = name.rfind ('_');
  221. const std::string id = name.substr (compositePrefix.size (), separator - compositePrefix.size ());
  222. char* end = nullptr;
  223. const long value = std::strtol (id.c_str (), &end, 10);
  224. const bool numeric = !id.empty () && end != nullptr && *end == '\0';
  225. if (numeric && value == this->m_renderable.getId ()) {
  226. return this->resolveFBO (name);
  227. }
  228. if (!numeric || name.substr (separator + 1) != "a"
  229. || !this->m_renderable.getScene ().hasNamedLayerBuffer (static_cast<int> (value))) {
  230. return this->m_renderable.getScene ().getMissingTexture ();
  231. }
  232. }
  233. if (name.starts_with ("_rt_") || name.starts_with ("_alias_")) {
  234. return this->resolveFBO (name);
  235. }
  236. return this->getContext ().resolveTexture (name, this->m_renderable.getScene ().getScene ().project);
  237. }
  238. void CPass::bindMissingTexture (int index) {
  239. // WE's missing texture (sub_1400EEF70)
  240. const auto it = this->m_textures.find (index);
  241. this->m_textures[index] = std::make_shared<TextureChainEntry> (TextureChainEntry {
  242. .texture = this->m_renderable.getScene ().getMissingTexture (),
  243. .next = it != this->m_textures.end () ? it->second : nullptr,
  244. });
  245. }
  246. std::shared_ptr<const CFBO> CPass::resolveFBO (const std::string& name) const {
  247. std::shared_ptr<const CFBO> fbo = this->m_fboProvider->find (name);
  248. if (fbo == nullptr && name == "_rt_MipMappedFrameBuffer") {
  249. fbo = this->m_renderable.getScene ().requireMipMappedFrameBuffer ();
  250. }
  251. if (fbo == nullptr && name == "_rt_Reflection") {
  252. fbo = this->m_renderable.getScene ().requireReflectionFrameBuffer ();
  253. }
  254. if (fbo == nullptr) {
  255. sLog.exception ("Tried to resolve and FBO without any luck: ", name);
  256. }
  257. return fbo;
  258. }
  259. void CPass::setupRenderFramebuffer () const {
  260. // what would go onto the scene goes into the passthrough layer drawing its children right now
  261. const auto* layerTarget = this->m_drawTo == this->m_renderable.getScene ().getFBO ()
  262. ? this->m_renderable.getScene ().getLayerTarget ()
  263. : nullptr;
  264. const auto& target = layerTarget != nullptr ? layerTarget->fbo : this->m_drawTo;
  265. glBindFramebuffer (
  266. GL_FRAMEBUFFER,
  267. target == this->m_renderable.getScene ().getFBO () ? this->m_renderable.getScene ().getSceneDrawFramebuffer ()
  268. : target->getFramebuffer ()
  269. );
  270. // Private per-object FBOs are never cleared elsewhere, so a blending pass would otherwise
  271. // accumulate stale alpha across frames. The shared scene FBO must not be cleared here though,
  272. // since it accumulates every object drawn this frame.
  273. if (this->m_drawTo != this->m_renderable.getScene ().getFBO () && !this->m_keepDestination) {
  274. GLfloat previousClearColor[4] = {};
  275. glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
  276. if (this->m_clearColor != nullptr) {
  277. glClearColor (this->m_clearColor->r, this->m_clearColor->g, this->m_clearColor->b, this->m_clearColor->a);
  278. } else {
  279. glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
  280. }
  281. glColorMask (true, true, true, true);
  282. glClear (GL_COLOR_BUFFER_BIT);
  283. glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
  284. }
  285. glViewport (0, 0, target->getRealWidth (), target->getRealHeight ());
  286. // D3D11 unbinds a resource that is also the render target, WE reads 0 there (pooled buffer shared with the target).
  287. // Not for the scene buffer, WE samples a copy
  288. this->m_boundTargetTexture
  289. = target == this->m_renderable.getScene ().getFBO () ? GL_NONE : target->getTextureID (0);
  290. const BlendingMode blending = this->m_scriptBlending.value_or (this->m_blendingmode);
  291. const auto depth = this->m_scriptDepth.value_or (
  292. this->m_depthState.value_or (std::make_pair (this->m_pass.depthtest, this->m_pass.depthwrite))
  293. );
  294. // WE's blend desc uses the colour factors for alpha too, so translucent leaves alpha squared (sub_140099F60)
  295. switch (blending) {
  296. case BlendingMode_Translucent:
  297. glEnable (GL_BLEND);
  298. glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  299. break;
  300. case BlendingMode_Additive:
  301. glEnable (GL_BLEND);
  302. glBlendFunc (GL_SRC_ALPHA, GL_ONE);
  303. break;
  304. // WE's blend state builder (sub_140099F60) turns blending off for normal on every target, the scene's
  305. // alpha is masked off anyway, so the pass's RGB replaces what's below regardless of its alpha
  306. case BlendingMode_Normal:
  307. default:
  308. glDisable (GL_BLEND);
  309. break;
  310. }
  311. // AlphaToCoverageEnable only matters on the multisampled scene target (sub_140099F60)
  312. if (blending == BlendingMode_AlphaToCoverage) {
  313. glEnable (GL_SAMPLE_ALPHA_TO_COVERAGE);
  314. }
  315. // no alpha writes onto the scene target unless the material's alphawriting overrides it (sub_140155FC0)
  316. const auto& alphaWriting = this->m_pass.alphawriting;
  317. glColorMask (
  318. true, true, true,
  319. alphaWriting == "enabled"
  320. || (alphaWriting != "disabled" && this->m_drawTo != this->m_renderable.getScene ().getFBO ())
  321. );
  322. // sub_140099F60 with renderer state flag 0x10: alpha op MAX and all four channels written, the color blend stays
  323. if (layerTarget != nullptr && layerTarget->alphaMax) {
  324. glBlendEquationSeparate (GL_FUNC_ADD, GL_MAX);
  325. glColorMask (true, true, true, true);
  326. }
  327. switch (depth.first) {
  328. case DepthtestMode_Enabled:
  329. glEnable (GL_DEPTH_TEST);
  330. glDepthFunc (GL_LEQUAL);
  331. break;
  332. case DepthtestMode_Disabled:
  333. default:
  334. glDisable (GL_DEPTH_TEST);
  335. break;
  336. }
  337. switch (this->m_scriptCulling.value_or (this->m_pass.cullmode)) {
  338. case CullingMode_Normal:
  339. glEnable (GL_CULL_FACE);
  340. // the mirrored reflection pass flips every triangle's winding
  341. glCullFace (this->m_renderable.getScene ().isRenderingReflection () ? GL_FRONT : GL_BACK);
  342. break;
  343. case CullingMode_Disable:
  344. default:
  345. glDisable (GL_CULL_FACE);
  346. break;
  347. }
  348. switch (depth.second) {
  349. case DepthwriteMode_Enabled:
  350. glDepthMask (true);
  351. break;
  352. case DepthwriteMode_Disabled:
  353. default:
  354. glDepthMask (false);
  355. break;
  356. }
  357. // WE picks the no-write depth state for translucent and additive blending whatever the material says
  358. // (sub_140099F60: state index | 1 when the blend mode isn't normal or alphatocoverage)
  359. if (blending == BlendingMode_Translucent || blending == BlendingMode_Additive) {
  360. glDepthMask (false);
  361. }
  362. }
  363. void CPass::setupRenderTexture () {
  364. glUseProgram (this->m_programID);
  365. auto texture0 = this->resolveTexture0 ();
  366. const auto animation = this->resolveTextureAnimationState (texture0);
  367. this->bindTextureUnit (0, texture0, animation.currentTexture);
  368. this->bindTextureOverrides (animation.currentTexture, texture0);
  369. if (texture0 != nullptr) {
  370. this->m_texture0Resolution = *texture0->getResolution ();
  371. }
  372. // used in animations when one of the frames is vertical instead of horizontal
  373. // rotation with translation = origin and end of the image to display
  374. if (this->g_Texture0Rotation != -1) {
  375. glUniform4f (
  376. this->g_Texture0Rotation, animation.rotation.x, animation.rotation.y, animation.rotation.z,
  377. animation.rotation.w
  378. );
  379. }
  380. // this actually picks the origin point of the image from the atlast
  381. if (this->g_Texture0Translation != -1) {
  382. glUniform2f (this->g_Texture0Translation, animation.translation.x, animation.translation.y);
  383. }
  384. }
  385. std::shared_ptr<const TextureProvider> CPass::resolveTexture0 () {
  386. auto texture0 = this->resolveTexture (this->m_input, 0, this->m_input);
  387. const auto it = this->m_textures.find (0);
  388. if (it == this->m_textures.end ()) {
  389. return texture0;
  390. }
  391. auto& chain = it->second;
  392. do {
  393. texture0 = chain->texture;
  394. if (texture0 == nullptr) {
  395. if (this->m_previousInput != nullptr && this->m_previousInput->isReady ()) {
  396. return this->m_previousInput;
  397. }
  398. if (this->m_input != nullptr && this->m_input->isReady ()) {
  399. return this->m_input;
  400. }
  401. } else if (texture0->isReady ()) {
  402. return texture0;
  403. }
  404. chain = chain->next;
  405. } while (chain != nullptr);
  406. // got to the end of the chain, use previous input or current input if available
  407. if (this->m_previousInput != nullptr && this->m_previousInput->isReady ()) {
  408. return this->m_previousInput;
  409. }
  410. // last resort, doesn't matter if the input is ready or not
  411. return this->m_input;
  412. }
  413. CPass::TextureAnimationState
  414. CPass::resolveTextureAnimationState (const std::shared_ptr<const TextureProvider>& texture) const {
  415. TextureAnimationState state;
  416. if (texture == nullptr || !texture->isAnimated ()) {
  417. return state;
  418. }
  419. const auto& frames = texture->getFrames ();
  420. const auto setFrame = [&state, &texture] (const auto& frameCur) {
  421. state.currentTexture = frameCur->frameNumber;
  422. state.translation.x = frameCur->x / texture->getTextureWidth (state.currentTexture);
  423. state.translation.y = frameCur->y / texture->getTextureHeight (state.currentTexture);
  424. state.rotation.x = frameCur->width1 / static_cast<float> (texture->getTextureWidth (state.currentTexture));
  425. state.rotation.y = frameCur->width2 / static_cast<float> (texture->getTextureWidth (state.currentTexture));
  426. state.rotation.z = frameCur->height2 / static_cast<float> (texture->getTextureHeight (state.currentTexture));
  427. state.rotation.w = frameCur->height1 / static_cast<float> (texture->getTextureHeight (state.currentTexture));
  428. };
  429. // a layer's own texture animation picks the frame, past the end is the first (sub_14015F0D0)
  430. if (const auto frame = this->m_renderable.getTextureFrameOverride (); frame.has_value () && !frames.empty ()) {
  431. setFrame (frames[static_cast<size_t> (*frame) < frames.size () ? *frame : 0]);
  432. return state;
  433. }
  434. // scene time like every other animation, so --speed, --disable-animations and pausing apply
  435. double currentRenderTime = fmod (static_cast<double> (g_Time), this->m_renderable.getAnimationTime ());
  436. for (const auto& frameCur : frames) {
  437. currentRenderTime -= frameCur->frametime;
  438. if (currentRenderTime > 0.0f) {
  439. continue;
  440. }
  441. setFrame (frameCur);
  442. break;
  443. }
  444. return state;
  445. }
  446. void CPass::bindTextureUnit (int index, const std::shared_ptr<const TextureProvider>& texture, uint32_t frame) const {
  447. if (texture == nullptr) {
  448. return;
  449. }
  450. // reading the scene buffer while the objects draw multisampled gets what they drew so far, WE resolves the bound
  451. // target into _rt_FullFrameBuffer (sub_1400D3310)
  452. if (texture == this->m_renderable.getScene ().getFBO ()) {
  453. this->m_renderable.getScene ().resolveMultisample ();
  454. }
  455. const GLuint id = texture->getTextureID (frame);
  456. glActiveTexture (GL_TEXTURE0 + index);
  457. glBindTexture (
  458. GL_TEXTURE_2D,
  459. id != GL_NONE && id == this->m_boundTargetTexture ? this->m_renderable.getScene ().getNullTexture () : id
  460. );
  461. }
  462. void CPass::bindTextureOverrides (uint32_t currentTexture, std::shared_ptr<const TextureProvider>& texture0) const {
  463. for (auto [index, chain] : this->m_textures) {
  464. auto expectedTexture = chain->texture;
  465. do {
  466. if (expectedTexture == nullptr) {
  467. if (this->m_previousInput != nullptr && this->m_previousInput->isReady ()) {
  468. expectedTexture = this->m_previousInput;
  469. break;
  470. }
  471. if (this->m_input != nullptr && this->m_input->isReady ()) {
  472. expectedTexture = this->m_input;
  473. break;
  474. }
  475. } else if (expectedTexture->isReady ()) {
  476. break;
  477. }
  478. chain = chain->next;
  479. expectedTexture = chain == nullptr ? nullptr : chain->texture;
  480. } while (chain != nullptr);
  481. if (expectedTexture == nullptr && this->m_previousInput != nullptr && this->m_previousInput->isReady ()) {
  482. expectedTexture = this->m_previousInput;
  483. }
  484. if (expectedTexture == nullptr) {
  485. expectedTexture = this->m_input;
  486. }
  487. this->bindTextureUnit (index, expectedTexture, index == 0 ? currentTexture : 0);
  488. if (index == 0) {
  489. texture0 = expectedTexture;
  490. }
  491. }
  492. }
  493. void CPass::setupRenderReferenceUniforms () {
  494. for (const auto& value : this->m_referenceUniforms | std::views::values) {
  495. switch (value->type) {
  496. case Double:
  497. glUniform1d (value->id, *static_cast<const double*> (*value->value));
  498. break;
  499. case Float:
  500. glUniform1f (value->id, *static_cast<const float*> (*value->value));
  501. break;
  502. case Integer:
  503. glUniform1i (value->id, *static_cast<const int*> (*value->value));
  504. break;
  505. case Vector4:
  506. glUniform4fv (value->id, 1, glm::value_ptr (*static_cast<const glm::vec4*> (*value->value)));
  507. break;
  508. case Vector3:
  509. glUniform3fv (value->id, 1, glm::value_ptr (*static_cast<const glm::vec3*> (*value->value)));
  510. break;
  511. case Vector2:
  512. glUniform2fv (value->id, 1, glm::value_ptr (*static_cast<const glm::vec2*> (*value->value)));
  513. break;
  514. case Matrix4:
  515. glUniformMatrix4fv (
  516. value->id, 1, GL_FALSE, glm::value_ptr (*static_cast<const glm::mat4*> (*value->value))
  517. );
  518. break;
  519. case Matrix3:
  520. glUniformMatrix3fv (
  521. value->id, 1, GL_FALSE, glm::value_ptr (*static_cast<const glm::mat3*> (*value->value))
  522. );
  523. break;
  524. }
  525. }
  526. }
  527. void CPass::setupRenderUniforms () {
  528. for (const auto& value : this->m_uniforms | std::views::values) {
  529. switch (value->type) {
  530. case Double:
  531. glUniform1dv (value->id, value->count, static_cast<const double*> (value->value));
  532. break;
  533. case Float:
  534. glUniform1fv (value->id, value->count, static_cast<const float*> (value->value));
  535. break;
  536. case Integer:
  537. glUniform1iv (value->id, value->count, static_cast<const int*> (value->value));
  538. break;
  539. case Vector4:
  540. glUniform4fv (value->id, value->count, glm::value_ptr (*static_cast<const glm::vec4*> (value->value)));
  541. break;
  542. case Vector3:
  543. glUniform3fv (value->id, value->count, glm::value_ptr (*static_cast<const glm::vec3*> (value->value)));
  544. break;
  545. case Vector2:
  546. glUniform2fv (value->id, value->count, glm::value_ptr (*static_cast<const glm::vec2*> (value->value)));
  547. break;
  548. case Matrix4:
  549. glUniformMatrix4fv (
  550. value->id, value->count, GL_FALSE, glm::value_ptr (*static_cast<const glm::mat4*> (value->value))
  551. );
  552. break;
  553. case Matrix3:
  554. glUniformMatrix3fv (
  555. value->id, value->count, GL_FALSE, glm::value_ptr (*static_cast<const glm::mat3*> (value->value))
  556. );
  557. break;
  558. }
  559. }
  560. }
  561. void CPass::setupRenderAttributes () const {
  562. if (this->m_setupAttribsCallback) {
  563. this->m_setupAttribsCallback ();
  564. return;
  565. }
  566. for (const auto& cur : this->m_attribs) {
  567. glEnableVertexAttribArray (cur->id);
  568. glBindBuffer (GL_ARRAY_BUFFER, *cur->value);
  569. glVertexAttribPointer (cur->id, cur->elements, cur->type, GL_FALSE, 0, nullptr);
  570. #if !NDEBUG
  571. glObjectLabel (
  572. GL_BUFFER, *cur->value, -1,
  573. ("Image " + std::to_string (this->m_renderable.getId ()) + " Pass " + this->m_pass.shader + " " + cur->name)
  574. .c_str ()
  575. );
  576. #endif /* DEBUG */
  577. }
  578. }
  579. void CPass::renderGeometry () const {
  580. if (this->m_drawGeometryCallback) {
  581. this->m_drawGeometryCallback ();
  582. return;
  583. }
  584. glBindBuffer (GL_ARRAY_BUFFER, this->a_Position);
  585. glDrawArrays (GL_TRIANGLES, 0, 6);
  586. }
  587. void CPass::cleanupRenderSetup () {
  588. glDisable (GL_SAMPLE_ALPHA_TO_COVERAGE);
  589. if (this->m_cleanupAttribsCallback) {
  590. this->m_cleanupAttribsCallback ();
  591. } else {
  592. for (const auto& cur : this->m_attribs) {
  593. glDisableVertexAttribArray (cur->id);
  594. }
  595. }
  596. glActiveTexture (GL_TEXTURE0);
  597. glBindTexture (GL_TEXTURE_2D, 0);
  598. for (const auto& index : this->m_textures | std::views::keys) {
  599. glActiveTexture (GL_TEXTURE0 + index);
  600. glBindTexture (GL_TEXTURE_2D, 0);
  601. }
  602. }
  603. void CPass::refreshRenderableUniforms () {
  604. const auto update = [this] (const char* name, const auto& value) {
  605. const auto it = this->m_uniforms.find (name);
  606. if (it != this->m_uniforms.end () && it->second->owned && !this->m_constantUniforms.contains (name)) {
  607. using Value = std::remove_cvref_t<decltype (value)>;
  608. *static_cast<Value*> (const_cast<void*> (it->second->value)) = value;
  609. }
  610. };
  611. update ("g_UserAlpha", this->m_renderable.getUserAlpha ());
  612. update ("g_Alpha", this->m_renderable.getAlpha ());
  613. update ("g_Color", this->m_renderable.getColor ());
  614. update ("g_Color4", this->m_neutralColor ? glm::vec4 (1.0f) : this->m_renderable.getColor4 ());
  615. }
  616. void CPass::render () {
  617. glBindVertexArray (this->m_vao);
  618. // copied when the pass was built, color and alpha scripts or animations change them every frame
  619. this->refreshRenderableUniforms ();
  620. if (this->m_pass.shader == XRAY_EFFECT_SHADER) {
  621. const auto mode = this->getContext ().getApp ().getContext ().state.xray.mode;
  622. this->m_xrayReveal = mode == Application::XrayMode::Full ? 1.0f
  623. : mode == Application::XrayMode::Disabled ? 0.0f
  624. : -1.0f;
  625. }
  626. const auto& debug = this->getContext ().getApp ().getContext ().settings.render.debug;
  627. if (debug.passLog) {
  628. sLog.out (
  629. "Render pass object=", this->m_renderable.getId (), " shader=", this->m_pass.shader,
  630. " target=", this->m_target.has_value () ? this->m_target.value ().get () : std::string ("<screen/local>"),
  631. " drawTo=", this->m_drawTo ? this->m_drawTo->getName () : std::string ("<null>"),
  632. " drawSize=", textureSizeLabel (this->m_drawTo), " inputSize=", textureSizeLabel (this->m_input)
  633. );
  634. for (const auto* uniformName : { "g_TintColor", "g_CompositeColor", "g_BlendAlpha", "g_CompositeAlpha" }) {
  635. const auto uniform = this->m_uniforms.find (uniformName);
  636. if (uniform == this->m_uniforms.end ()) {
  637. continue;
  638. }
  639. switch (uniform->second->type) {
  640. case Vector3:
  641. {
  642. const auto* v = static_cast<const glm::vec3*> (uniform->second->value);
  643. sLog.out (" uniform ", uniformName, "=", v->x, " ", v->y, " ", v->z);
  644. break;
  645. }
  646. case Float:
  647. {
  648. const auto* v = static_cast<const float*> (uniform->second->value);
  649. sLog.out (" uniform ", uniformName, "=", *v);
  650. break;
  651. }
  652. default:
  653. break;
  654. }
  655. }
  656. }
  657. if (this->m_drawTo == nullptr) {
  658. sLog.error ("Skipping render pass for object ", this->m_renderable.getId (), ": no destination FBO set");
  659. return;
  660. }
  661. if (this->m_input == nullptr) {
  662. sLog.error ("Skipping render pass for object ", this->m_renderable.getId (), ": no input texture set");
  663. return;
  664. }
  665. // a passthrough layer draws its children into its buffer: model = inverse (layer world), view = identity and an
  666. // ortho of the layer's size (sub_1401ECB20), which comes down to remapping the scene's clip space
  667. const auto* layerTarget = this->m_drawTo == this->m_renderable.getScene ().getFBO () || this->m_followLayerTarget
  668. ? this->m_renderable.getScene ().getLayerTarget ()
  669. : nullptr;
  670. const glm::mat4* modelViewProjection = this->m_modelViewProjectionMatrix;
  671. const glm::mat4* modelViewProjectionInverse = this->m_modelViewProjectionMatrixInverse;
  672. const glm::mat4* viewProjection = this->m_viewProjectionMatrix;
  673. if (layerTarget != nullptr) {
  674. if (modelViewProjection != nullptr) {
  675. this->m_layerModelViewProjection = layerTarget->transform * *modelViewProjection;
  676. this->m_layerModelViewProjectionInverse = glm::inverse (this->m_layerModelViewProjection);
  677. this->m_modelViewProjectionMatrix = &this->m_layerModelViewProjection;
  678. this->m_modelViewProjectionMatrixInverse = &this->m_layerModelViewProjectionInverse;
  679. }
  680. if (viewProjection != nullptr) {
  681. this->m_layerViewProjection = layerTarget->transform * *viewProjection;
  682. this->m_viewProjectionMatrix = &this->m_layerViewProjection;
  683. }
  684. }
  685. // effectcomposebackground (refraction, ...) samples _rt_FullFrameBuffer where the layer is on screen
  686. this->m_effectModelViewProjectionMatrix = this->m_effectModelViewProjectionOverride != nullptr
  687. ? this->m_effectModelViewProjectionOverride
  688. : this->m_modelViewProjectionMatrix;
  689. this->setupRenderFramebuffer ();
  690. this->setupRenderTexture ();
  691. for (const auto& [slot, resolution] : this->m_texelSources) {
  692. if (resolution->x > 0.0f && resolution->y > 0.0f) {
  693. this->m_texels[slot] = glm::vec4 (1.0f / resolution->x, 1.0f / resolution->y, resolution->x, resolution->y);
  694. }
  695. }
  696. this->setupRenderUniforms ();
  697. this->setupRenderReferenceUniforms ();
  698. this->setupRenderAttributes ();
  699. this->renderGeometry ();
  700. this->cleanupRenderSetup ();
  701. if (layerTarget != nullptr) {
  702. this->m_modelViewProjectionMatrix = modelViewProjection;
  703. this->m_modelViewProjectionMatrixInverse = modelViewProjectionInverse;
  704. this->m_viewProjectionMatrix = viewProjection;
  705. if (layerTarget->alphaMax && this->m_drawTo == this->m_renderable.getScene ().getFBO ()) {
  706. glBlendEquation (GL_FUNC_ADD);
  707. }
  708. }
  709. }
  710. void CPass::clearDestination () const {
  711. if (this->m_drawTo == nullptr) {
  712. return;
  713. }
  714. GLfloat previousClearColor[4] = {};
  715. glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
  716. glBindFramebuffer (GL_FRAMEBUFFER, this->m_drawTo->getFramebuffer ());
  717. glViewport (0, 0, this->m_drawTo->getRealWidth (), this->m_drawTo->getRealHeight ());
  718. glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
  719. glColorMask (true, true, true, true);
  720. glClear (GL_COLOR_BUFFER_BIT);
  721. glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
  722. }
  723. std::shared_ptr<const FBOProvider> CPass::getFBOProvider () const { return this->m_fboProvider; }
  724. const CRenderable& CPass::getRenderable () const { return this->m_renderable; }
  725. void CPass::copyBindings (const CPass& other) {
  726. this->m_drawTo = other.m_drawTo;
  727. this->m_input = other.m_input;
  728. this->m_previousInput = other.m_previousInput;
  729. this->a_Position = other.a_Position;
  730. this->a_TexCoord = other.a_TexCoord;
  731. this->m_modelViewProjectionMatrix = other.m_modelViewProjectionMatrix;
  732. this->m_modelViewProjectionMatrixInverse = other.m_modelViewProjectionMatrixInverse;
  733. this->m_effectModelViewProjectionOverride = other.m_effectModelViewProjectionOverride;
  734. this->m_modelMatrix = other.m_modelMatrix;
  735. this->m_layerModelMatrix = other.m_layerModelMatrix;
  736. this->m_viewProjectionMatrix = other.m_viewProjectionMatrix;
  737. this->m_lightingModelMatrix = other.m_lightingModelMatrix;
  738. this->m_lightingNormalMatrix = other.m_lightingNormalMatrix;
  739. this->m_lightingViewProjectionMatrix = other.m_lightingViewProjectionMatrix;
  740. this->m_effectTextureProjectionMatrix = other.m_effectTextureProjectionMatrix;
  741. this->m_effectTextureProjectionMatrixInverse = other.m_effectTextureProjectionMatrixInverse;
  742. }
  743. void CPass::setDestination (std::shared_ptr<const CFBO> drawTo) { this->m_drawTo = std::move (drawTo); }
  744. void CPass::setInput (std::shared_ptr<const TextureProvider> input) { this->m_input = std::move (input); }
  745. void CPass::setPreviousInput (std::shared_ptr<const TextureProvider> input) {
  746. this->m_previousInput = std::move (input);
  747. }
  748. void CPass::setTexture (int index, std::shared_ptr<const TextureProvider> texture) {
  749. const auto it = this->m_textures.find (index);
  750. // the uniforms were set up with the pass, a texture set afterwards brings its own size
  751. if (texture != nullptr) {
  752. this->addUniform ("g_Texture" + std::to_string (index) + "Resolution", texture->getResolution ());
  753. if (index > 0) {
  754. this->m_texelSources[index] = texture->getResolution ();
  755. }
  756. }
  757. this->m_textures[index] = std::make_shared<TextureChainEntry> (TextureChainEntry {
  758. .texture = std::move (texture),
  759. .next = it != this->m_textures.end () ? it->second : nullptr,
  760. });
  761. }
  762. void CPass::setEffectModelViewProjectionMatrix (const glm::mat4* projection) {
  763. this->m_effectModelViewProjectionOverride = projection;
  764. }
  765. void CPass::setModelViewProjectionMatrix (const glm::mat4* projection) {
  766. this->m_modelViewProjectionMatrix = projection;
  767. }
  768. void CPass::setModelViewProjectionMatrixInverse (const glm::mat4* projection) {
  769. this->m_modelViewProjectionMatrixInverse = projection;
  770. }
  771. const glm::mat4 CPass::s_identity { 1.0f };
  772. void CPass::setModelMatrix (const glm::mat4* model) { this->m_modelMatrix = model; }
  773. void CPass::setLayerModelMatrix (const glm::mat4* model) { this->m_layerModelMatrix = model; }
  774. void CPass::setFogWorld (const bool world) {
  775. this->m_fogWorld = world;
  776. const auto& fog = this->m_renderable.getScene ().getFog ();
  777. this->addUniform ("g_FogHeightParams", world ? &fog.heightParamsWorld : &fog.heightParamsLocal);
  778. if (world) {
  779. this->addUniform ("g_EyePosition", &fog.eyeWorld);
  780. }
  781. }
  782. void CPass::setViewProjectionMatrix (const glm::mat4* viewProjection) { this->m_viewProjectionMatrix = viewProjection; }
  783. void CPass::setLightingTransform (const glm::mat4* model, const glm::mat3* normal, const glm::mat4* viewProjection) {
  784. this->m_lightingModelMatrix = model;
  785. this->m_lightingNormalMatrix = normal;
  786. this->m_lightingViewProjectionMatrix = viewProjection;
  787. }
  788. void CPass::setEffectTextureProjectionMatrix (const glm::mat4* projection, const glm::mat4* inverse) {
  789. this->m_effectTextureProjectionMatrix = projection;
  790. this->m_effectTextureProjectionMatrixInverse = inverse;
  791. }
  792. void CPass::setBlendingMode (BlendingMode blendingmode) { this->m_blendingmode = blendingmode; }
  793. void CPass::setDepthState (std::optional<std::pair<DepthtestMode, DepthwriteMode>> state) {
  794. this->m_depthState = state;
  795. }
  796. BlendingMode CPass::getBlendingMode () const { return this->m_blendingmode; }
  797. void CPass::setTexCoord (GLuint texcoord) { this->a_TexCoord = texcoord; }
  798. void CPass::setClearColor (const glm::vec4* color) { this->m_clearColor = color; }
  799. void CPass::setKeepDestination (bool keep) { this->m_keepDestination = keep; }
  800. void CPass::setFollowLayerTarget (bool follow) { this->m_followLayerTarget = follow; }
  801. void CPass::setNeutralColor (bool neutral) { this->m_neutralColor = neutral; }
  802. void CPass::setPosition (GLuint position) { this->a_Position = position; }
  803. const MaterialPass& CPass::getPass () const { return this->m_pass; }
  804. std::optional<std::reference_wrapper<std::string>> CPass::getTarget () const { return this->m_target; }
  805. Render::Shaders::Shader* CPass::getShader () const { return this->m_shader; }
  806. bool CPass::hasGeometryStage () const { return this->m_compiled != nullptr && !this->m_compiled->geometry.empty (); }
  807. GLuint CPass::getProgramID () const { return this->m_programID; }
  808. void CPass::setGeometryCallback (
  809. GeometryCallback setupAttribs, GeometryCallback drawGeometry, GeometryCallback cleanupAttribs
  810. ) {
  811. this->m_setupAttribsCallback = std::move (setupAttribs);
  812. this->m_drawGeometryCallback = std::move (drawGeometry);
  813. this->m_cleanupAttribsCallback = std::move (cleanupAttribs);
  814. }
  815. namespace {
  816. // Mesa mis-reads a vec3 uniform followed by a float used as vec4(vec3, float), use g_Color4
  817. std::string patchColorAlpha (const std::string& shader) {
  818. std::string patched = shader;
  819. const std::string declarations = "uniform vec3 g_Color;\nuniform float g_Alpha;";
  820. const std::string construction = "vec4(g_Color, g_Alpha)";
  821. const auto declarationsAt = patched.find (declarations);
  822. const auto constructionAt = patched.find (construction);
  823. if (declarationsAt == std::string::npos || constructionAt == std::string::npos) {
  824. return patched;
  825. }
  826. patched.replace (constructionAt, construction.size (), "g_Color4");
  827. patched.replace (declarationsAt, declarations.size (), "uniform vec4 g_Color4;");
  828. // only safe when that was the sole use of both, the trailing "#if 0" copy doesn't count
  829. const size_t codeEnd = std::min (patched.size (), patched.find ("#if 0"));
  830. const auto stillUsed = [&patched, codeEnd] (const std::string& name) {
  831. size_t pos = 0;
  832. while ((pos = patched.find (name, pos)) != std::string::npos && pos < codeEnd) {
  833. const bool wordStart = pos == 0
  834. || !(std::isalnum (static_cast<unsigned char> (patched[pos - 1])) || patched[pos - 1] == '_');
  835. const size_t end = pos + name.size ();
  836. const bool wordEnd = end >= patched.size ()
  837. || !(std::isalnum (static_cast<unsigned char> (patched[end])) || patched[end] == '_');
  838. if (wordStart && wordEnd) {
  839. return true;
  840. }
  841. pos = end;
  842. }
  843. return false;
  844. };
  845. if (stillUsed ("g_Color") || stillUsed ("g_Alpha")) {
  846. return shader;
  847. }
  848. return patched;
  849. }
  850. } // namespace
  851. GLuint CPass::compileShader (const char* shader, GLuint type) {
  852. const GLuint shaderID = glCreateShader (type);
  853. glShaderSource (shaderID, 1, &shader, nullptr);
  854. glCompileShader (shaderID);
  855. GLint result = GL_FALSE;
  856. int infoLogLength = 0;
  857. glGetShaderiv (shaderID, GL_COMPILE_STATUS, &result);
  858. glGetShaderiv (shaderID, GL_INFO_LOG_LENGTH, &infoLogLength);
  859. if (infoLogLength > 0) {
  860. const auto logBuffer = new char[infoLogLength + 1];
  861. memset (logBuffer, 0, infoLogLength + 1);
  862. glGetShaderInfoLog (shaderID, infoLogLength, nullptr, logBuffer);
  863. std::stringstream buffer;
  864. buffer << logBuffer << std::endl << "Compiled source code:" << std::endl << shader;
  865. delete[] logBuffer;
  866. if (result == GL_FALSE) {
  867. sLog.exception (buffer.str ());
  868. } else {
  869. sLog.error (buffer.str ());
  870. }
  871. }
  872. return shaderID;
  873. }
  874. void CPass::setupShaders () {
  875. const auto texture0 = this->m_renderable.getTexture ();
  876. this->m_combos.insert (this->m_pass.combos.begin (), this->m_pass.combos.end ());
  877. const auto comboEnabled = [this] (const std::string& name) {
  878. const auto override = this->m_override.combos.find (name);
  879. if (override != this->m_override.combos.end ()) {
  880. return override->second != 0;
  881. }
  882. const auto combo = this->m_combos.find (name);
  883. return combo != this->m_combos.end () && combo->second != 0;
  884. };
  885. // a lit layer drawn straight onto the scene overrides this off
  886. if ((comboEnabled ("LIGHTING") || comboEnabled ("REFLECTION"))
  887. && !this->m_override.combos.contains ("PRELIGHTING")) {
  888. this->m_combos.insert_or_assign ("PRELIGHTING", 1);
  889. }
  890. // HDR scene rendering defines HDR for every pass (sub_1401A5C40)
  891. if (this->m_renderable.getScene ().isHDR ()) {
  892. this->m_combos.insert_or_assign ("HDR", 1);
  893. }
  894. // an alphatocoverage pass gets ALPHATOCOVERAGE (sub_140154480), the shaders' GLSL path discards below 0.5 alpha
  895. // there (3734636606's invisible "alpha": 0 collider boxes)
  896. if (this->m_pass.blending == BlendingMode_AlphaToCoverage) {
  897. this->m_combos.insert_or_assign ("ALPHATOCOVERAGE", 1);
  898. }
  899. // particle shaders read TEX0FORMAT without a formatcombo sampler, the other slots are handled below
  900. if (texture0 != nullptr) {
  901. if (texture0->getFormat () == TextureFormat_RG88) {
  902. this->m_combos.insert_or_assign ("TEX0FORMAT", 8);
  903. } else if (texture0->getFormat () == TextureFormat_R8) {
  904. this->m_combos.insert_or_assign ("TEX0FORMAT", 9);
  905. }
  906. }
  907. // TODO: review the shader textures here; ones passed to the shader shouldn't be in this list
  908. // (used later to build the textures)
  909. // use the combos copied from the pass so it includes the texture format
  910. const std::string& shaderName
  911. = this->m_override.shaderOverride.has_value () ? this->m_override.shaderOverride.value () : this->m_pass.shader;
  912. TextureMap passTextures = this->m_pass.textures;
  913. for (const auto& [index, propertyName] : this->m_pass.usertextures) {
  914. // leave the default texture (if any) in place when the user hasn't provided an override,
  915. // same rule applied when the actual texture chain gets built in setupTextureUniforms()
  916. if (const auto resolved = this->resolveUserTextureName (propertyName); resolved.has_value ()) {
  917. passTextures.insert_or_assign (index, *resolved);
  918. }
  919. }
  920. // same for the object's own user textures, otherwise the combo that enables their slot stays off
  921. TextureMap overrideTextures = this->m_override.textures;
  922. for (const auto& [index, propertyName] : this->m_override.usertextures) {
  923. if (const auto resolved = this->resolveUserTextureName (propertyName); resolved.has_value ()) {
  924. overrideTextures.insert_or_assign (index, *resolved);
  925. }
  926. }
  927. // every pass of an orthographic scene gets SCENE_ORTHO (renderer flag 0x400, sub_1401A5C40)
  928. if (this->m_renderable.getScene ().getCamera ().isOrthogonal ()) {
  929. this->m_combos.insert_or_assign ("SCENE_ORTHO", 1);
  930. }
  931. this->m_compiled = this->compileShaderSources (shaderName, passTextures, overrideTextures);
  932. this->m_shader = this->m_compiled->shader.get ();
  933. // samplers marked "formatcombo" get TEX<slot>FORMAT set to their texture's format, like wallpaper64.exe
  934. // (sub_14015EC30). Which slots those are is only known once the shader is parsed, so rebuild it when one changed
  935. if (this->applyFormatCombos (passTextures, overrideTextures)) {
  936. this->m_compiled = this->compileShaderSources (shaderName, passTextures, overrideTextures);
  937. this->m_shader = this->m_compiled->shader.get ();
  938. }
  939. // fog turns into FOG_DIST/FOG_HEIGHT for every pass whose FOG combo (the shader default included) is on
  940. // (sub_1401A5C40); that default is only known once the shader is parsed
  941. const auto& scene = this->m_renderable.getScene ();
  942. const auto comboValue = [this] (const std::string& name) {
  943. for (const ComboMap* combos :
  944. std::initializer_list<const ComboMap*> { &this->m_override.combos, &this->m_combos }) {
  945. if (const auto it = combos->find (name); it != combos->end ()) {
  946. return it->second;
  947. }
  948. }
  949. for (const auto* unit : { &this->m_shader->getFragment (), &this->m_shader->getVertex () }) {
  950. if (const auto it = unit->getDiscoveredCombos ().find (name); it != unit->getDiscoveredCombos ().end ()) {
  951. return it->second;
  952. }
  953. }
  954. return 0;
  955. };
  956. // same for LIGHTING: the light counts of the scene's lightconfig, which the LightingV1 module is generated from
  957. // (sub_1401A5C40). The shadow counts are 0 with WE's shadow setting off
  958. if (comboValue ("LIGHTING") != 0) {
  959. const auto& lighting = scene.getLightingV1 ();
  960. this->m_combos.insert_or_assign ("LIGHTS_POINT", lighting.points);
  961. this->m_combos.insert_or_assign ("LIGHTS_SPOT", lighting.spots);
  962. this->m_combos.insert_or_assign ("LIGHTS_TUBE", lighting.tubes);
  963. this->m_combos.insert_or_assign ("LIGHTS_DIRECTIONAL", lighting.directionals);
  964. this->m_combos.insert_or_assign ("LIGHTS_SPOT_SHADOW_COOKIE", lighting.spotShadowCookies);
  965. this->m_combos.insert_or_assign ("LIGHTS_SPOT_SHADOW", lighting.spotShadows);
  966. this->m_combos.insert_or_assign ("LIGHTS_SPOT_COOKIE", lighting.spotCookies);
  967. this->m_combos.insert_or_assign ("LIGHTS_DIRECTIONAL_SHADOW", lighting.directionalShadows);
  968. this->m_combos.insert_or_assign ("LIGHTS_POINT_SHADOW", lighting.pointShadows);
  969. if (lighting.spotShadowCookies + lighting.spotShadows + lighting.directionalShadows + lighting.pointShadows) {
  970. this->m_combos.insert_or_assign ("LIGHTS_SHADOW_MAPPING", 1);
  971. this->m_combos.insert_or_assign ("LIGHTS_SHADOW_MAPPING_QUALITY", scene.getShadowQuality ());
  972. }
  973. if (lighting.spotShadowCookies + lighting.spotCookies != 0) {
  974. this->m_combos.insert_or_assign ("LIGHTS_COOKIE", 1);
  975. }
  976. // WE's renderer always has flag 0x1000 (sub_140110630), so every pass gets REVERSEDEPTH. Of the shaders drawn
  977. // through here only the shadow cascades of common_pbr_2.h read it, the shadow matrices do use reversed depth
  978. this->m_combos.insert_or_assign ("REVERSEDEPTH", 1);
  979. this->m_compiled = this->compileShaderSources (shaderName, passTextures, overrideTextures);
  980. this->m_shader = this->m_compiled->shader.get ();
  981. }
  982. if (scene.hasDistanceFog () || scene.hasHeightFog ()) {
  983. if (comboValue ("FOG") != 0) {
  984. if (scene.hasDistanceFog ()) {
  985. this->m_combos.insert_or_assign ("FOG_DIST", 1);
  986. }
  987. if (scene.hasHeightFog ()) {
  988. this->m_combos.insert_or_assign ("FOG_HEIGHT", 1);
  989. }
  990. this->m_compiled = this->compileShaderSources (shaderName, passTextures, overrideTextures);
  991. this->m_shader = this->m_compiled->shader.get ();
  992. }
  993. }
  994. std::string vertex = this->m_compiled->vertex;
  995. std::string fragment = this->m_compiled->fragment;
  996. if (shaderName == XRAY_EFFECT_SHADER) {
  997. this->m_xrayRevealPatched = patchXrayRevealOverride (fragment);
  998. if (!this->m_xrayRevealPatched) {
  999. sLog.error (
  1000. "Full/disabled xray unavailable: couldn't find the expected reveal blend line in the "
  1001. "compiled effects/xray shader (spirv-cross output format may have changed)"
  1002. );
  1003. }
  1004. }
  1005. // passes with the same sources share one program (every particle system instance of a child would link its own
  1006. // otherwise, hundreds in the first seconds of a rain wallpaper). Uniforms are uploaded on every draw, the sampler
  1007. // units below are the same for all of them
  1008. this->m_programKey = vertex + '\0' + fragment + '\0' + this->m_compiled->geometry;
  1009. if (const auto cached = sharedPrograms ().find (this->m_programKey); cached != sharedPrograms ().end ()) {
  1010. this->m_programID = cached->second.program;
  1011. cached->second.users++;
  1012. } else {
  1013. this->m_programID = this->linkProgram (vertex, fragment, this->m_compiled->geometry, shaderName);
  1014. sharedPrograms ().emplace (this->m_programKey, SharedProgram { this->m_programID, 1 });
  1015. }
  1016. // bind each g_TextureN sampler to unit N explicitly, the translated GLSL collapses every layout(binding) to 0
  1017. {
  1018. glUseProgram (this->m_programID);
  1019. for (int index = 0; index <= 9; index++) {
  1020. const std::string name = "g_Texture" + std::to_string (index);
  1021. const GLint loc = glGetUniformLocation (this->m_programID, name.c_str ());
  1022. if (loc != -1) {
  1023. glUniform1i (loc, index);
  1024. }
  1025. }
  1026. }
  1027. // first setup the default values, these will be overwritten by future values
  1028. this->setupShaderVariables ();
  1029. this->setupUniforms ();
  1030. this->setupAttributes ();
  1031. this->g_Texture0Rotation = glGetUniformLocation (this->m_programID, "g_Texture0Rotation");
  1032. this->g_Texture0Translation = glGetUniformLocation (this->m_programID, "g_Texture0Translation");
  1033. }
  1034. std::unordered_map<std::string, std::weak_ptr<CPass::CompiledShader>>& CPass::sharedShaders () {
  1035. static std::unordered_map<std::string, std::weak_ptr<CompiledShader>> shaders;
  1036. return shaders;
  1037. }
  1038. std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
  1039. const std::string& shaderName, const TextureMap& passTextures, const TextureMap& overrideTextures
  1040. ) {
  1041. // parsing and translating a shader takes a few ms, and every instance of a child particle system builds the same
  1042. // one. Override constants can change the parsed defaults, those passes keep a shader of their own
  1043. const bool shareable = this->m_override.constants.empty ();
  1044. std::string key;
  1045. if (shareable) {
  1046. std::ostringstream stream;
  1047. stream << shaderName << '\0' << &this->m_renderable.getAssetLocator ();
  1048. const ComboMap* comboMaps[] = { &this->m_combos, &this->m_override.combos };
  1049. for (const ComboMap* combos : comboMaps) {
  1050. stream << '\1';
  1051. for (const auto& [name, value] : *combos) {
  1052. stream << name << '=' << value << ';';
  1053. }
  1054. }
  1055. for (const TextureMap* textures : { &passTextures, &overrideTextures }) {
  1056. stream << '\1';
  1057. for (const auto& [index, name] : *textures) {
  1058. stream << index << '=' << name << ';';
  1059. }
  1060. }
  1061. key = stream.str ();
  1062. if (const auto it = sharedShaders ().find (key); it != sharedShaders ().end ()) {
  1063. if (auto cached = it->second.lock ()) {
  1064. return cached;
  1065. }
  1066. }
  1067. }
  1068. static const ShaderConstantMap noConstants;
  1069. auto compiled = std::make_shared<CompiledShader> ();
  1070. compiled->combos = this->m_combos;
  1071. compiled->overrideCombos = this->m_override.combos;
  1072. compiled->passTextures = passTextures;
  1073. compiled->overrideTextures = overrideTextures;
  1074. compiled->shader = std::make_unique<Render::Shaders::Shader> (
  1075. this->m_renderable.getAssetLocator (), shaderName, compiled->combos, compiled->overrideCombos,
  1076. compiled->passTextures, compiled->overrideTextures, shareable ? noConstants : this->m_override.constants
  1077. );
  1078. auto sources = Shaders::GLSLContext::get ().toGlsl (
  1079. compiled->shader->vertex (), compiled->shader->fragment (), shaderName, compiled->shader->geometry ()
  1080. );
  1081. compiled->vertex = std::move (sources.vertex);
  1082. compiled->fragment = std::move (sources.fragment);
  1083. compiled->geometry = std::move (sources.geometry);
  1084. if (shareable) {
  1085. std::erase_if (sharedShaders (), [] (const auto& entry) { return entry.second.expired (); });
  1086. sharedShaders ().insert_or_assign (key, compiled);
  1087. }
  1088. return compiled;
  1089. }
  1090. std::unordered_map<std::string, CPass::SharedProgram>& CPass::sharedPrograms () {
  1091. static std::unordered_map<std::string, SharedProgram> programs;
  1092. return programs;
  1093. }
  1094. bool CPass::releaseSharedProgram () {
  1095. const auto it = sharedPrograms ().find (this->m_programKey);
  1096. if (this->m_programKey.empty () || it == sharedPrograms ().end ()) {
  1097. return false;
  1098. }
  1099. if (--it->second.users == 0) {
  1100. glDeleteProgram (it->second.program);
  1101. sharedPrograms ().erase (it);
  1102. }
  1103. this->m_programID = 0;
  1104. return true;
  1105. }
  1106. GLuint CPass::linkProgram (
  1107. const std::string& vertex, const std::string& unpatchedFragment, const std::string& geometry,
  1108. const std::string& shaderName
  1109. ) {
  1110. const std::string fragment = patchColorAlpha (unpatchedFragment);
  1111. auto& cache = Shaders::ShaderCache::get ();
  1112. const std::string cacheKey = vertex + '\0' + fragment + '\0' + geometry;
  1113. if (const GLuint cached = cache.loadProgram (cacheKey); cached != 0) {
  1114. #if !NDEBUG
  1115. glObjectLabel (GL_PROGRAM, cached, -1, shaderName.c_str ());
  1116. #endif /* DEBUG */
  1117. return cached;
  1118. }
  1119. const GLuint vertexShaderID = compileShader (vertex.c_str (), GL_VERTEX_SHADER);
  1120. const GLuint fragmentShaderID = compileShader (fragment.c_str (), GL_FRAGMENT_SHADER);
  1121. const GLuint geometryShaderID = geometry.empty () ? 0 : compileShader (geometry.c_str (), GL_GEOMETRY_SHADER);
  1122. const GLuint program = glCreateProgram ();
  1123. glAttachShader (program, vertexShaderID);
  1124. glAttachShader (program, fragmentShaderID);
  1125. if (geometryShaderID != 0) {
  1126. glAttachShader (program, geometryShaderID);
  1127. }
  1128. if (cache.programsSupported ()) {
  1129. glProgramParameteri (program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
  1130. }
  1131. glLinkProgram (program);
  1132. GLint result = GL_FALSE;
  1133. int infoLogLength = 0;
  1134. glGetProgramiv (program, GL_LINK_STATUS, &result);
  1135. glGetProgramiv (program, GL_INFO_LOG_LENGTH, &infoLogLength);
  1136. if (infoLogLength > 0) {
  1137. const auto logBuffer = new char[infoLogLength + 1];
  1138. memset (logBuffer, 0, infoLogLength + 1);
  1139. glGetProgramInfoLog (program, infoLogLength, nullptr, logBuffer);
  1140. const std::string message = logBuffer;
  1141. delete[] logBuffer;
  1142. if (result == GL_FALSE) {
  1143. sLog.exception (message);
  1144. } else {
  1145. sLog.error (message);
  1146. }
  1147. }
  1148. #if !NDEBUG
  1149. glObjectLabel (GL_PROGRAM, program, -1, shaderName.c_str ());
  1150. glObjectLabel (GL_SHADER, vertexShaderID, -1, (shaderName + ".vert").c_str ());
  1151. glObjectLabel (GL_SHADER, fragmentShaderID, -1, (shaderName + ".frag").c_str ());
  1152. #endif /* DEBUG */
  1153. // once linked, the shaders themselves are no longer needed and can be detached/deleted
  1154. glDetachShader (program, vertexShaderID);
  1155. glDetachShader (program, fragmentShaderID);
  1156. glDeleteShader (vertexShaderID);
  1157. glDeleteShader (fragmentShaderID);
  1158. if (geometryShaderID != 0) {
  1159. glDetachShader (program, geometryShaderID);
  1160. glDeleteShader (geometryShaderID);
  1161. }
  1162. cache.storeProgram (cacheKey, program);
  1163. return program;
  1164. }
  1165. bool CPass::applyFormatCombos (const TextureMap& passTextures, const TextureMap& overrideTextures) {
  1166. const auto& fragment = this->m_shader->getFragment ();
  1167. const auto& componentCombos = fragment.getComponentCombos ();
  1168. bool changed = false;
  1169. std::set<int> slots = fragment.getFormatComboSlots ();
  1170. for (const auto& [slot, combos] : componentCombos) {
  1171. slots.insert (slot);
  1172. }
  1173. for (const int slot : slots) {
  1174. std::shared_ptr<const TextureProvider> texture;
  1175. if (slot == 0) {
  1176. texture = this->m_renderable.getTexture ();
  1177. } else {
  1178. std::optional<std::string> name;
  1179. for (const TextureMap* map : { &overrideTextures, &passTextures, &fragment.getTextures () }) {
  1180. if (const auto it = map->find (slot); it != map->end () && !it->second.empty ()) {
  1181. name = it->second;
  1182. break;
  1183. }
  1184. }
  1185. if (!name.has_value () || name->starts_with ("_rt_") || name->starts_with ("_alias_")) {
  1186. continue;
  1187. }
  1188. try {
  1189. texture
  1190. = this->getContext ().resolveTexture (*name, this->m_renderable.getScene ().getScene ().project);
  1191. } catch (const std::exception&) {
  1192. continue;
  1193. }
  1194. }
  1195. if (texture == nullptr) {
  1196. continue;
  1197. }
  1198. // a bound mask turns on the combos of the components its flags mark as painted (sub_14016C800)
  1199. if (const auto it = componentCombos.find (slot); it != componentCombos.end ()) {
  1200. for (size_t i = 0; i < it->second.size () && i < 4; i++) {
  1201. if (it->second[i].empty () || (texture->getFlags () & (0x100000u << i)) == 0) {
  1202. continue;
  1203. }
  1204. if (const auto combo = this->m_combos.find (it->second[i]);
  1205. combo == this->m_combos.end () || combo->second != 1) {
  1206. this->m_combos.insert_or_assign (it->second[i], 1);
  1207. changed = true;
  1208. }
  1209. }
  1210. }
  1211. if (!fragment.getFormatComboSlots ().contains (slot) || texture->getFormat () == TextureFormat_UNKNOWN) {
  1212. continue;
  1213. }
  1214. const std::string combo = "TEX" + std::to_string (slot) + "FORMAT";
  1215. const int format = static_cast<int> (texture->getFormat ());
  1216. if (const auto it = this->m_combos.find (combo); it == this->m_combos.end () || it->second != format) {
  1217. this->m_combos.insert_or_assign (combo, format);
  1218. changed = true;
  1219. }
  1220. }
  1221. return changed;
  1222. }
  1223. void CPass::setupAttributes () {
  1224. this->addAttribute ("a_TexCoord", GL_FLOAT, 2, &this->a_TexCoord);
  1225. this->addAttribute ("a_Position", GL_FLOAT, 3, &this->a_Position);
  1226. }
  1227. void CPass::setupTextureUniforms () {
  1228. // Vertex shaders don't carry texture info in practice, but check them first anyway;
  1229. // fragment textures are checked after and override/extend the chain.
  1230. for (const auto& [index, textureName] : this->m_shader->getVertex ().getTextures ()) {
  1231. try {
  1232. auto texture = this->resolveNamedTexture (textureName);
  1233. this->m_textures[index] = std::make_shared<TextureChainEntry> (TextureChainEntry {
  1234. .texture = texture,
  1235. .next = nullptr,
  1236. });
  1237. } catch (std::runtime_error& ex) {
  1238. sLog.error (
  1239. "Cannot resolve texture '", textureName, "' (index=", index,
  1240. ", object id=", this->m_renderable.getId (), ") for fragment shader ", ex.what ()
  1241. );
  1242. }
  1243. }
  1244. for (const auto& [index, textureName] : this->m_shader->getFragment ().getTextures ()) {
  1245. try {
  1246. auto texture = this->resolveNamedTexture (textureName);
  1247. const auto it = this->m_textures.find (index);
  1248. const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
  1249. .texture = texture,
  1250. .next = it != this->m_textures.end () ? it->second : nullptr,
  1251. });
  1252. this->m_textures[index] = chain;
  1253. } catch (std::runtime_error& ex) {
  1254. sLog.error (
  1255. "Cannot resolve texture '", textureName, "' (index=", index,
  1256. ", object id=", this->m_renderable.getId (), ") for fragment shader ", ex.what ()
  1257. );
  1258. this->bindMissingTexture (index);
  1259. }
  1260. }
  1261. for (const auto& [index, textureName] : this->m_pass.textures) {
  1262. try {
  1263. auto texture = this->resolveNamedTexture (textureName);
  1264. const auto it = this->m_textures.find (index);
  1265. const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
  1266. .texture = texture,
  1267. .next = it != this->m_textures.end () ? it->second : nullptr,
  1268. });
  1269. this->m_textures[index] = chain;
  1270. if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
  1271. this->trackPlayback (texture);
  1272. }
  1273. } catch (std::runtime_error& ex) {
  1274. sLog.error (
  1275. "Cannot resolve texture '", textureName, "' (index=", index,
  1276. ", object id=", this->m_renderable.getId (), ") for pass ", ex.what ()
  1277. );
  1278. this->bindMissingTexture (index);
  1279. }
  1280. }
  1281. for (const auto& [index, propertyName] : this->m_pass.usertextures) {
  1282. const auto resolvedName = this->resolveUserTextureName (propertyName);
  1283. if (!resolvedName.has_value ()) {
  1284. // optional user-provided texture slot, nothing configured - keep whatever the
  1285. // regular "textures" entry already set for this index (if any)
  1286. continue;
  1287. }
  1288. const std::string& textureName = *resolvedName;
  1289. try {
  1290. auto texture = this->resolveNamedTexture (textureName);
  1291. const auto it = this->m_textures.find (index);
  1292. const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
  1293. .texture = texture,
  1294. .next = it != this->m_textures.end () ? it->second : nullptr,
  1295. });
  1296. this->m_textures[index] = chain;
  1297. if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
  1298. this->trackPlayback (texture);
  1299. }
  1300. } catch (std::runtime_error& ex) {
  1301. sLog.error (
  1302. "Cannot resolve user texture '", textureName, "' (index=", index,
  1303. ", object id=", this->m_renderable.getId (), ") for pass ", ex.what ()
  1304. );
  1305. }
  1306. }
  1307. // override any texture
  1308. for (const auto& [index, textureName] : this->m_override.textures) {
  1309. // WE writes every bound FBO into its slot on each draw (sub_1401EBF60), so overrides there are never sampled
  1310. if (const auto bind = this->m_binds.find (index); bind != this->m_binds.end () && bind->second != "previous") {
  1311. continue;
  1312. }
  1313. // same for slot 0 of a pass without binds (3736099508)
  1314. if (index == 0 && this->m_binds.empty ()) {
  1315. continue;
  1316. }
  1317. try {
  1318. auto texture = this->resolveNamedTexture (textureName);
  1319. const auto it = this->m_textures.find (index);
  1320. const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
  1321. .texture = texture,
  1322. .next = it != this->m_textures.end () ? it->second : nullptr,
  1323. });
  1324. this->m_textures[index] = chain;
  1325. if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
  1326. this->trackPlayback (texture);
  1327. }
  1328. } catch (std::runtime_error& ex) {
  1329. sLog.error (
  1330. "Cannot resolve texture '", textureName, "' (index=", index,
  1331. ", object id=", this->m_renderable.getId (), ") for override ", ex.what ()
  1332. );
  1333. }
  1334. }
  1335. for (const auto& [index, propertyName] : this->m_override.usertextures) {
  1336. const auto resolvedName = this->resolveUserTextureName (propertyName);
  1337. if (!resolvedName.has_value ()) {
  1338. continue;
  1339. }
  1340. const std::string& textureName = *resolvedName;
  1341. try {
  1342. auto texture = this->resolveNamedTexture (textureName);
  1343. const auto it = this->m_textures.find (index);
  1344. const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
  1345. .texture = texture,
  1346. .next = it != this->m_textures.end () ? it->second : nullptr,
  1347. });
  1348. this->m_textures[index] = chain;
  1349. if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
  1350. this->trackPlayback (texture);
  1351. }
  1352. } catch (std::runtime_error& ex) {
  1353. sLog.error (
  1354. "Cannot resolve user texture '", textureName, "' (index=", index,
  1355. ", object id=", this->m_renderable.getId (), ") for override ", ex.what ()
  1356. );
  1357. }
  1358. }
  1359. // binds are set last as they're the most important to be set
  1360. for (const auto& [index, bind] : this->m_binds) {
  1361. const auto texture = bind == "previous" ? nullptr : this->resolveFBO (bind);
  1362. const auto it = this->m_textures.find (index);
  1363. const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
  1364. .texture = texture,
  1365. .next = it != this->m_textures.end () ? it->second : nullptr,
  1366. });
  1367. this->m_textures[index] = chain;
  1368. }
  1369. std::shared_ptr<const TextureProvider> texture = this->resolveTexture (this->m_renderable.getTexture (), 0);
  1370. this->addUniform ("g_Texture0", 0);
  1371. this->addUniform ("g_Texture1", 1);
  1372. this->addUniform ("g_Texture2", 2);
  1373. this->addUniform ("g_Texture3", 3);
  1374. this->addUniform ("g_Texture4", 4);
  1375. this->addUniform ("g_Texture5", 5);
  1376. this->addUniform ("g_Texture6", 6);
  1377. this->addUniform ("g_Texture7", 7);
  1378. this->addUniform ("g_TextureReductionScale", 1.0f);
  1379. // a particle whose material failed to load has no texture at all
  1380. if (texture != nullptr) {
  1381. this->m_texture0Resolution = *texture->getResolution ();
  1382. }
  1383. this->addUniform ("g_Texture0Resolution", &this->m_texture0Resolution);
  1384. // g_TextureNTexel (uniforms 71..80, sub_1400D8300): (1 / width, 1 / height, width, height) of the bound texture,
  1385. // (0.5, 0.5, 2, 2) for an empty slot. Sizes can change (the shadow atlas grows), so it's refreshed every draw
  1386. for (int slot = 0; slot < 10; slot++) {
  1387. this->m_texels[slot] = glm::vec4 (0.5f, 0.5f, 2.0f, 2.0f);
  1388. this->addUniform ("g_Texture" + std::to_string (slot) + "Texel", &this->m_texels[slot]);
  1389. }
  1390. this->m_texelSources[0] = &this->m_texture0Resolution;
  1391. for (const auto& [textureIndex, expectedTexture] : this->m_textures) {
  1392. std::ostringstream namestream;
  1393. namestream << "g_Texture" << textureIndex << "Resolution";
  1394. texture = this->resolveTexture (expectedTexture->texture, textureIndex, texture);
  1395. if (texture == nullptr) {
  1396. continue;
  1397. }
  1398. this->addUniform (namestream.str (), texture->getResolution ());
  1399. if (textureIndex != 0) {
  1400. this->m_texelSources[textureIndex] = texture->getResolution ();
  1401. }
  1402. // the mip count of a mipmapped frame buffer, REFLECTION scales its roughness LOD by it
  1403. if (const auto fbo = std::dynamic_pointer_cast<const CFBO> (texture);
  1404. fbo != nullptr && fbo->getMipLevels () > 1) {
  1405. this->addUniform (
  1406. "g_Texture" + std::to_string (textureIndex) + "MipMapInfo", static_cast<float> (fbo->getMipLevels ())
  1407. );
  1408. }
  1409. }
  1410. this->addUniform ("g_Texture0Resolution", &this->m_texture0Resolution);
  1411. // WE ORs the requirement of every texture slot the compiled program uses into the pass (sub_1401515B0); a sampled
  1412. // _rt_Reflection turns on the scene's reflection pass and keeps this object out of it (object flag 8)
  1413. auto& scene = this->m_renderable.getScene ();
  1414. const auto reflection = scene.find ("_rt_Reflection");
  1415. for (const auto& [index, chain] : this->m_textures) {
  1416. if (reflection == nullptr || chain == nullptr
  1417. || chain->texture.get () != static_cast<const TextureProvider*> (reflection.get ())) {
  1418. continue;
  1419. }
  1420. if (glGetUniformLocation (this->m_programID, ("g_Texture" + std::to_string (index)).c_str ()) != -1) {
  1421. scene.addReflectionReceiver (this->m_renderable.getId ());
  1422. }
  1423. }
  1424. }
  1425. void CPass::setupUniforms () {
  1426. this->setupTextureUniforms ();
  1427. const auto& renderable = this->m_renderable;
  1428. const auto& scene = this->m_renderable.getScene ();
  1429. const auto& sceneData = this->m_renderable.getScene ().getScene ();
  1430. const auto& recorder = this->m_renderable.getScene ().getAudioContext ().getRecorder ();
  1431. // lighting variables
  1432. this->addUniform ("g_LightAmbientColor", &sceneData.colors.ambient->value->getVec3 ());
  1433. this->addUniform ("g_LightSkylightColor", &sceneData.colors.skylight->value->getVec3 ());
  1434. this->addUniform ("g_LightsPosition", UniformType::Vector3, scene.getLightsPosition (), 4);
  1435. this->addUniform ("g_LightsColorPremultiplied", UniformType::Vector4, scene.getLightsColorPremultiplied (), 3);
  1436. this->addUniform ("g_LightsColorRadius", UniformType::Vector4, scene.getLightsColorRadius (), 4);
  1437. // LightingV1, the arrays are as long as the scene's lightconfig counts
  1438. const auto& lighting = scene.getLightingV1 ();
  1439. const auto addLights = [this] (const char* name, const glm::vec4* values, const int count) {
  1440. if (count > 0) {
  1441. this->addUniform (name, UniformType::Vector4, values, count);
  1442. }
  1443. };
  1444. addLights ("g_LPoint_Color", lighting.pointColor, lighting.points);
  1445. addLights ("g_LPoint_Origin", lighting.pointOrigin, lighting.points);
  1446. addLights ("g_LSpot_Color", lighting.spotColor, lighting.spots);
  1447. addLights ("g_LSpot_Origin", lighting.spotOrigin, lighting.spots);
  1448. addLights ("g_LSpot_Direction", lighting.spotDirection, lighting.spots);
  1449. addLights ("g_LSpot_Exponent", lighting.spotExponent, lighting.spots);
  1450. addLights ("g_LTube_Color", lighting.tubeColor, lighting.tubes);
  1451. addLights ("g_LTube_OriginA", lighting.tubeOriginA, lighting.tubes);
  1452. addLights ("g_LTube_OriginB", lighting.tubeOriginB, lighting.tubes);
  1453. addLights ("g_LDirectional_Color", lighting.directionalColor, lighting.directionals);
  1454. addLights ("g_LDirectional_Direction", lighting.directionalDirection, lighting.directionals);
  1455. // WE binds the renderer's eye (+104) for every pass; lit ones get it here in the world their lighting works in
  1456. // (models, particles and text set their own afterwards), without it the view vector points at the origin
  1457. if (this->m_combos.contains ("LIGHTS_POINT")) {
  1458. this->addUniform ("g_EyePosition", &scene.getFog ().eyeWorld);
  1459. }
  1460. if (const int features = lighting.features (); features > 0) {
  1461. this->addUniform ("g_LFeature_ShadowProjection", UniformType::Matrix4, lighting.featureProjection, features);
  1462. addLights ("g_LFeature_ShadowProjectionTransform", lighting.featureProjectionTransform, features);
  1463. }
  1464. addLights ("g_LFeature_ShadowPointProjection", lighting.pointShadowProjection, lighting.pointShadows);
  1465. addLights (
  1466. "g_LFeature_ShadowPointProjectionTransform", lighting.pointShadowProjectionTransform, lighting.pointShadows
  1467. );
  1468. this->addUniform ("g_FogDistanceColor", &scene.getFog ().distanceColor);
  1469. this->addUniform ("g_FogDistanceParams", &scene.getFog ().distanceParams);
  1470. this->addUniform ("g_FogHeightColor", &scene.getFog ().heightColor);
  1471. this->addUniform (
  1472. "g_FogHeightParams", this->m_fogWorld ? &scene.getFog ().heightParamsWorld : &scene.getFog ().heightParamsLocal
  1473. );
  1474. this->addUniform ("g_AltModelMatrix", &this->m_lightingModelMatrix);
  1475. this->addUniform ("g_AltNormalModelMatrix", &this->m_lightingNormalMatrix);
  1476. this->addUniform ("g_AltViewProjectionMatrix", &this->m_lightingViewProjectionMatrix);
  1477. this->addUniform (
  1478. "g_Screen",
  1479. glm::vec3 (
  1480. scene.getWidth (), scene.getHeight (),
  1481. static_cast<float> (scene.getWidth ()) / static_cast<float> (std::max (scene.getHeight (), 1))
  1482. )
  1483. );
  1484. // register variables like brightness and alpha with the layer's values, unless the pass sets them itself
  1485. const auto addRenderableUniform = [this] (const char* name, const auto& value) {
  1486. if (!this->m_constantUniforms.contains (name)) {
  1487. this->addUniform (name, value);
  1488. }
  1489. };
  1490. addRenderableUniform ("g_Brightness", renderable.getBrightness ());
  1491. addRenderableUniform ("g_UserAlpha", renderable.getUserAlpha ());
  1492. addRenderableUniform ("g_Alpha", renderable.getAlpha ());
  1493. addRenderableUniform ("g_Color", renderable.getColor ());
  1494. addRenderableUniform ("g_Color4", renderable.getColor4 ());
  1495. if (!this->m_uniforms.contains ("g_CompositeColor")) {
  1496. this->addUniform ("g_CompositeColor", renderable.getCompositeColor ());
  1497. }
  1498. this->addUniform ("g_Time", &g_Time);
  1499. this->addUniform ("g_Daytime", &g_Daytime);
  1500. this->addUniform ("g_ModelViewProjectionMatrixInverse", &this->m_modelViewProjectionMatrixInverse);
  1501. this->addUniform ("g_ModelViewProjectionMatrix", &this->m_modelViewProjectionMatrix);
  1502. this->addUniform ("g_EffectModelViewProjectionMatrix", &this->m_effectModelViewProjectionMatrix);
  1503. this->addUniform ("g_ModelMatrix", &this->m_modelMatrix);
  1504. this->addUniform ("g_EffectModelMatrix", &this->m_modelMatrix);
  1505. this->addUniform ("g_LayerModelMatrix", &this->m_layerModelMatrix);
  1506. this->addUniform ("g_NormalModelMatrix", glm::identity<glm::mat3> ());
  1507. this->addUniform ("g_ViewProjectionMatrix", &this->m_viewProjectionMatrix);
  1508. this->addUniform ("g_PointerPosition", scene.getPointerPosition ());
  1509. this->addUniform ("g_PointerPositionLast", scene.getPointerPositionLast ());
  1510. this->addUniform ("g_ParallaxPosition", scene.getParallaxPosition ());
  1511. this->addUniform ("g_EffectTextureProjectionMatrix", &this->m_effectTextureProjectionMatrix);
  1512. this->addUniform ("g_EffectTextureProjectionMatrixInverse", &this->m_effectTextureProjectionMatrixInverse);
  1513. this->addUniform ("g_TexelSize", scene.getTexelSize ());
  1514. this->addUniform ("g_TexelSizeHalf", scene.getTexelSizeHalf ());
  1515. this->addUniform ("g_AudioSpectrum16Left", recorder.audio16, 16);
  1516. this->addUniform ("g_AudioSpectrum16Right", recorder.audio16 + 16, 16);
  1517. this->addUniform ("g_AudioSpectrum32Left", recorder.audio32, 32);
  1518. this->addUniform ("g_AudioSpectrum32Right", recorder.audio32 + 32, 32);
  1519. this->addUniform ("g_AudioSpectrum64Left", recorder.audio64, 64);
  1520. this->addUniform ("g_AudioSpectrum64Right", recorder.audio64 + 64, 64);
  1521. }
  1522. void CPass::addAttribute (const std::string& name, GLint type, GLint elements, const GLuint* value) {
  1523. const GLint id = glGetAttribLocation (this->m_programID, name.c_str ());
  1524. if (id == -1) {
  1525. return;
  1526. }
  1527. this->m_attribs.emplace_back (new AttribEntry (id, name, type, elements, value));
  1528. }
  1529. template <typename T> void CPass::addUniform (const std::string& name, UniformType type, T value) {
  1530. GLint id = glGetUniformLocation (this->m_programID, name.c_str ());
  1531. if (id == -1) {
  1532. return;
  1533. }
  1534. // frees any previously registered value for this uniform name
  1535. const auto it = this->m_uniforms.find (name);
  1536. if (it != this->m_uniforms.end ()) {
  1537. delete it->second;
  1538. }
  1539. T* newValue = new T (value);
  1540. this->m_uniforms.insert_or_assign (name, new UniformEntry (id, name, type, newValue, 1, true));
  1541. }
  1542. template <typename T> void CPass::addUniform (const std::string& name, UniformType type, T* value, int count) {
  1543. // this version is used to reference to system variables so things like g_Time works fine
  1544. GLint id = glGetUniformLocation (this->m_programID, name.c_str ());
  1545. if (id == -1) {
  1546. return;
  1547. }
  1548. if (const auto it = this->m_uniforms.find (name); it != this->m_uniforms.end ()) {
  1549. delete it->second;
  1550. }
  1551. this->m_uniforms.insert_or_assign (name, new UniformEntry (id, name, type, value, count));
  1552. }
  1553. template <typename T> void CPass::addUniform (const std::string& name, UniformType type, T** value) {
  1554. // this version is used to reference to system variables so things like g_Time works fine
  1555. const GLint id = glGetUniformLocation (this->m_programID, name.c_str ());
  1556. if (id == -1) {
  1557. return;
  1558. }
  1559. if (const auto it = this->m_uniforms.find (name); it != this->m_uniforms.end ()) {
  1560. delete it->second;
  1561. }
  1562. this->m_referenceUniforms.insert_or_assign (
  1563. name, new ReferenceUniformEntry (id, name, type, reinterpret_cast<const void**> (value))
  1564. );
  1565. }
  1566. namespace {
  1567. int componentCount (const ShaderVariable& var) {
  1568. if (var.is<ShaderVariableVector4> ()) {
  1569. return 4;
  1570. }
  1571. if (var.is<ShaderVariableVector3> ()) {
  1572. return 3;
  1573. }
  1574. if (var.is<ShaderVariableVector2> ()) {
  1575. return 2;
  1576. }
  1577. return 1;
  1578. }
  1579. int componentCount (GLenum type) {
  1580. switch (type) {
  1581. case GL_FLOAT_VEC4:
  1582. return 4;
  1583. case GL_FLOAT_VEC3:
  1584. return 3;
  1585. case GL_FLOAT_VEC2:
  1586. return 2;
  1587. default:
  1588. return 1;
  1589. }
  1590. }
  1591. } // namespace
  1592. int CPass::getMaterialConstantSize (const std::string& name) const {
  1593. const ShaderVariable* var = this->m_materialConstants.contains (name) ? this->findActiveParameter (name) : nullptr;
  1594. return var == nullptr ? 0 : componentCount (*var);
  1595. }
  1596. bool CPass::isMaterialConstantInDegrees (const std::string& name) const {
  1597. const ShaderVariable* var = this->m_materialConstants.contains (name) ? this->findActiveParameter (name) : nullptr;
  1598. return var != nullptr && var->isInDegrees ();
  1599. }
  1600. void CPass::setupShaderVariables () {
  1601. // a uniform declared differently per stage takes the linked program's type
  1602. for (const auto& cur : this->m_shader->getVertex ().getParameters ()) {
  1603. if (this->m_uniforms.contains (cur->getName ())) {
  1604. continue;
  1605. }
  1606. ShaderVariable* var = cur;
  1607. for (const auto& other : this->m_shader->getFragment ().getParameters ()) {
  1608. if (other->getName () == cur->getName () && componentCount (*other) != componentCount (*cur)
  1609. && componentCount (this->getDeclaredUniformType (cur->getName ())) == componentCount (*other)) {
  1610. var = other;
  1611. break;
  1612. }
  1613. }
  1614. this->addUniform (var);
  1615. }
  1616. for (const auto& cur : this->m_shader->getFragment ().getParameters ()) {
  1617. if (!this->m_uniforms.contains (cur->getName ())) {
  1618. this->addUniform (cur);
  1619. }
  1620. }
  1621. // shader defaults as scripts see them
  1622. for (const auto* unit : { &this->m_shader->getVertex (), &this->m_shader->getFragment () }) {
  1623. for (const auto* cur : unit->getParameters ()) {
  1624. if (!cur->getIdentifierName ().empty () && this->m_uniforms.contains (cur->getName ())) {
  1625. this->m_materialConstants.try_emplace (cur->getIdentifierName (), cur);
  1626. }
  1627. }
  1628. }
  1629. // material constants, then override constants, which win
  1630. for (const auto* constants : { &this->m_pass.constants, &this->m_override.constants }) {
  1631. for (const auto& [name, value] : *constants) {
  1632. ShaderVariable* var = this->findActiveParameter (name);
  1633. if (var == nullptr) {
  1634. continue;
  1635. }
  1636. this->addConstantUniform (var, *value);
  1637. this->m_constantUniforms.insert (var->getName ());
  1638. if (this->m_materialConstants.contains (name)) {
  1639. this->m_materialConstants[name] = value->value.get ();
  1640. }
  1641. }
  1642. }
  1643. // no-op when patchXrayRevealOverride() didn't find its anchors
  1644. if (this->m_pass.shader == XRAY_EFFECT_SHADER) {
  1645. this->addUniform ("g_XrayReveal", &this->m_xrayReveal);
  1646. }
  1647. }
  1648. std::vector<std::string> CPass::getMaterialConstantNames () const {
  1649. std::vector<std::pair<std::string, std::string>> byUniform;
  1650. for (const auto& name : this->m_materialConstants | std::views::keys) {
  1651. if (const auto* var = this->findActiveParameter (name)) {
  1652. byUniform.emplace_back (var->getName (), name);
  1653. }
  1654. }
  1655. std::ranges::sort (byUniform, std::greater {});
  1656. std::vector<std::string> names;
  1657. for (const auto& name : byUniform | std::views::values) {
  1658. names.push_back (name);
  1659. }
  1660. return names;
  1661. }
  1662. const DynamicValue* CPass::getMaterialConstant (const std::string& name) const {
  1663. const auto it = this->m_materialConstants.find (name);
  1664. return it == this->m_materialConstants.end () ? nullptr : it->second;
  1665. }
  1666. DynamicValue* CPass::getScriptConstant (const std::string& name) {
  1667. if (const auto it = this->m_scriptConstants.find (name); it != this->m_scriptConstants.end ()) {
  1668. return it->second.get ();
  1669. }
  1670. ShaderVariable* var = this->findActiveParameter (name);
  1671. const DynamicValue* current = this->getMaterialConstant (name);
  1672. if (var == nullptr || current == nullptr) {
  1673. return nullptr;
  1674. }
  1675. // typed like the uniform (sub_140154480), vectors get padded
  1676. const bool scalar = current->getType () == DynamicValue::Float || current->getType () == DynamicValue::Int;
  1677. const glm::vec4 value = scalar ? glm::vec4 (current->getFloat (), 0.0f, 0.0f, 0.0f) : current->getVec4 ();
  1678. std::unique_ptr<DynamicValue> copy;
  1679. if (var->is<ShaderVariableVector2> ()) {
  1680. copy = std::make_unique<DynamicValue> (glm::vec2 (value));
  1681. } else if (var->is<ShaderVariableVector3> ()) {
  1682. copy = std::make_unique<DynamicValue> (glm::vec3 (value));
  1683. } else if (var->is<ShaderVariableVector4> ()) {
  1684. copy = std::make_unique<DynamicValue> (value);
  1685. } else {
  1686. copy = std::make_unique<DynamicValue> (current->getFloat ());
  1687. }
  1688. auto* result = copy.get ();
  1689. this->addUniform (var, result);
  1690. this->m_constantUniforms.insert (var->getName ());
  1691. this->m_materialConstants[name] = result;
  1692. this->m_scriptConstants.emplace (name, std::move (copy));
  1693. return result;
  1694. }
  1695. void CPass::setScriptMaterialState (
  1696. const BlendingMode blending, const std::pair<DepthtestMode, DepthwriteMode> depth, const CullingMode culling
  1697. ) {
  1698. this->m_scriptBlending = blending;
  1699. this->m_scriptDepth = depth;
  1700. this->m_scriptCulling = culling;
  1701. }
  1702. CPass::ScriptState CPass::getScriptState () const {
  1703. ScriptState state {
  1704. .blending = this->m_scriptBlending,
  1705. .depth = this->m_scriptDepth,
  1706. .culling = this->m_scriptCulling,
  1707. };
  1708. for (const auto& [name, value] : this->m_scriptConstants) {
  1709. state.constants.emplace (name, *value);
  1710. }
  1711. return state;
  1712. }
  1713. void CPass::restoreScriptState (const ScriptState& state) {
  1714. this->m_scriptBlending = state.blending;
  1715. this->m_scriptDepth = state.depth;
  1716. this->m_scriptCulling = state.culling;
  1717. for (const auto& [name, value] : state.constants) {
  1718. if (auto* target = this->getScriptConstant (name)) {
  1719. target->update (value, DynamicValue::UpdateSource::Script);
  1720. }
  1721. }
  1722. }
  1723. ShaderVariable* CPass::findActiveParameter (const std::string& name) const {
  1724. const auto [vertex, fragment] = this->m_shader->findParameter (name);
  1725. if (vertex == nullptr || fragment == nullptr || componentCount (*vertex) == componentCount (*fragment)) {
  1726. return vertex == nullptr ? fragment : vertex;
  1727. }
  1728. const GLenum declared = this->getDeclaredUniformType (fragment->getName ());
  1729. return declared != GL_NONE && componentCount (declared) == componentCount (*fragment) ? fragment : vertex;
  1730. }
  1731. void CPass::addConstantUniform (ShaderVariable* var, const UserSetting& setting) {
  1732. const DynamicValue& value = *setting.value;
  1733. const bool scalar = value.getType () == DynamicValue::UnderlyingType::Float
  1734. || value.getType () == DynamicValue::UnderlyingType::Int;
  1735. // WE zero-pads constants ("0.7" on a vec4 is 0.7 0 0 0, tests/vecpad); bound user properties still spread
  1736. if (scalar && componentCount (*var) > 1 && setting.property == nullptr && value.getAnimation () == nullptr) {
  1737. auto& padded = this->m_paddedConstants.emplace_back (value.getFloat (), 0.0f, 0.0f, 0.0f);
  1738. if (var->is<ShaderVariableVector2> ()) {
  1739. this->addUniform (var->getName (), reinterpret_cast<const glm::vec2*> (&padded));
  1740. } else if (var->is<ShaderVariableVector3> ()) {
  1741. this->addUniform (var->getName (), reinterpret_cast<const glm::vec3*> (&padded));
  1742. } else {
  1743. this->addUniform (var->getName (), static_cast<const glm::vec4*> (&padded));
  1744. }
  1745. return;
  1746. }
  1747. this->addUniform (var, &value);
  1748. }
  1749. void CPass::addUniform (ShaderVariable* value) {
  1750. // delegates to the (ShaderVariable*, DynamicValue*) overload, which handles the casting
  1751. this->addUniform (value, value);
  1752. }
  1753. void CPass::addUniform (const ShaderVariable* value, const DynamicValue* setting) {
  1754. if (value->is<ShaderVariableFloat> ()) {
  1755. this->addUniform (value->getName (), &setting->getFloat ());
  1756. } else if (value->is<ShaderVariableInteger> ()) {
  1757. this->addUniform (value->getName (), &setting->getInt ());
  1758. } else if (value->is<ShaderVariableVector2> ()) {
  1759. this->addUniform (value->getName (), &setting->getVec2 ());
  1760. } else if (value->is<ShaderVariableVector3> ()) {
  1761. this->addUniform (value->getName (), &setting->getVec3 ());
  1762. } else if (value->is<ShaderVariableVector4> ()) {
  1763. this->addUniform (value->getName (), &setting->getVec4 ());
  1764. } else {
  1765. sLog.error ("Cannot convert setting dynamic value to ", value->getName (), ". Using default value");
  1766. }
  1767. }
  1768. void CPass::addUniform (const std::string& name, int value) { this->addUniform (name, UniformType::Integer, value); }
  1769. void CPass::addUniform (const std::string& name, const int* value, int count) {
  1770. this->addUniform (name, UniformType::Integer, value, count);
  1771. }
  1772. void CPass::addUniform (const std::string& name, const int** value) {
  1773. this->addUniform (name, UniformType::Integer, value);
  1774. }
  1775. void CPass::addUniform (const std::string& name, double value) { this->addUniform (name, UniformType::Double, value); }
  1776. void CPass::addUniform (const std::string& name, const double* value, int count) {
  1777. this->addUniform (name, UniformType::Double, value, count);
  1778. }
  1779. void CPass::addUniform (const std::string& name, const double** value) {
  1780. this->addUniform (name, UniformType::Double, value);
  1781. }
  1782. void CPass::addUniform (const std::string& name, float value) { this->addUniform (name, UniformType::Float, value); }
  1783. void CPass::addUniform (const std::string& name, const float* value, int count) {
  1784. this->addUniform (name, UniformType::Float, value, count);
  1785. }
  1786. void CPass::addUniform (const std::string& name, const float** value) {
  1787. this->addUniform (name, UniformType::Float, value);
  1788. }
  1789. void CPass::addUniform (const std::string& name, glm::vec2 value) {
  1790. this->addUniform (name, UniformType::Vector2, value);
  1791. }
  1792. void CPass::addUniform (const std::string& name, const glm::vec2* value) {
  1793. this->addUniform (name, UniformType::Vector2, value, 1);
  1794. }
  1795. void CPass::addUniform (const std::string& name, const glm::vec2** value) {
  1796. this->addUniform (name, UniformType::Vector2, value, 1);
  1797. }
  1798. void CPass::addUniform (const std::string& name, glm::vec3 value) {
  1799. this->addUniform (name, UniformType::Vector3, value);
  1800. }
  1801. void CPass::addUniform (const std::string& name, const glm::vec3* value) {
  1802. this->addUniform (name, UniformType::Vector3, value, 1);
  1803. }
  1804. void CPass::addUniform (const std::string& name, const glm::vec3** value) {
  1805. this->addUniform (name, UniformType::Vector3, value);
  1806. }
  1807. void CPass::addUniform (const std::string& name, const glm::vec4 value) {
  1808. this->addUniform (name, UniformType::Vector4, value);
  1809. }
  1810. GLenum CPass::getDeclaredUniformType (const std::string& name) const {
  1811. GLint count = 0;
  1812. glGetProgramiv (this->m_programID, GL_ACTIVE_UNIFORMS, &count);
  1813. for (GLint index = 0; index < count; index++) {
  1814. char buffer[256];
  1815. GLsizei length = 0;
  1816. GLint size = 0;
  1817. GLenum type = GL_NONE;
  1818. glGetActiveUniform (this->m_programID, index, sizeof (buffer), &length, &size, &type, buffer);
  1819. if (name == buffer) {
  1820. return type;
  1821. }
  1822. }
  1823. return GL_NONE;
  1824. }
  1825. void CPass::addUniform (const std::string& name, const glm::vec4* value) {
  1826. // resolution uniforms are always kept as a vec4 (texture size + real size), but shaders often declare
  1827. // them as a vec2 and glUniform4 on that is a GL error that leaves the uniform at 0 (color_key_plus
  1828. // then divides by a zero resolution and the whole layer comes out NaN)
  1829. switch (this->getDeclaredUniformType (name)) {
  1830. case GL_FLOAT_VEC2:
  1831. this->addUniform (name, UniformType::Vector2, reinterpret_cast<const glm::vec2*> (value), 1);
  1832. return;
  1833. case GL_FLOAT_VEC3:
  1834. this->addUniform (name, UniformType::Vector3, reinterpret_cast<const glm::vec3*> (value), 1);
  1835. return;
  1836. default:
  1837. break;
  1838. }
  1839. this->addUniform (name, UniformType::Vector4, value, 1);
  1840. }
  1841. void CPass::addUniform (const std::string& name, const glm::vec4** value) {
  1842. this->addUniform (name, UniformType::Vector4, value);
  1843. }
  1844. void CPass::addUniform (const std::string& name, const glm::mat3& value) {
  1845. this->addUniform (name, UniformType::Matrix3, value);
  1846. }
  1847. void CPass::addUniform (const std::string& name, const glm::mat3* value) {
  1848. this->addUniform (name, UniformType::Matrix3, value, 1);
  1849. }
  1850. void CPass::addUniform (const std::string& name, const glm::mat3** value) {
  1851. this->addUniform (name, UniformType::Matrix3, value);
  1852. }
  1853. void CPass::addUniform (const std::string& name, const glm::mat4 value) {
  1854. this->addUniform (name, UniformType::Matrix4, value);
  1855. }
  1856. void CPass::addUniform (const std::string& name, const glm::mat4* value) {
  1857. this->addUniform (name, UniformType::Matrix4, value, 1);
  1858. }
  1859. void CPass::addUniform (const std::string& name, const glm::mat4** value) {
  1860. this->addUniform (name, UniformType::Matrix4, value);
  1861. }