CImage.cpp 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674
  1. #include "CImage.h"
  2. #include "WallpaperEngine/Data/Model/Property.h"
  3. #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
  4. #include "WallpaperEngine/Render/DepthRange.h"
  5. #include "CMesh.h"
  6. #include "CRenderable.h"
  7. #include "PuppetMeshFile.h"
  8. #include <algorithm>
  9. #include <array>
  10. #include <bit>
  11. #include <cmath>
  12. #include <cstdio>
  13. #include <cstdlib>
  14. #include <cstring>
  15. #include <iterator>
  16. #include <limits>
  17. #include <optional>
  18. #include <sstream>
  19. #include <strings.h>
  20. #include <tuple>
  21. #include <vector>
  22. #include <glm/glm.hpp>
  23. #include <glm/gtc/matrix_transform.hpp>
  24. #define GLM_ENABLE_EXPERIMENTAL
  25. #include <glm/gtx/rotate_vector.hpp>
  26. #undef GLM_ENABLE_EXPERIMENTAL
  27. #include "WallpaperEngine/Assets/AssetLoadException.h"
  28. #include "WallpaperEngine/Data/Model/DynamicValue.h"
  29. #include "WallpaperEngine/Data/Model/Material.h"
  30. #include "WallpaperEngine/Data/Model/Object.h"
  31. #include "WallpaperEngine/Data/Model/UserSetting.h"
  32. #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
  33. #include "WallpaperEngine/Data/Utils/BinaryReader.h"
  34. #include "WallpaperEngine/Data/Utils/MemoryStream.h"
  35. #include "WallpaperEngine/Logging/Log.h"
  36. #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
  37. #include "WallpaperEngine/Scripting/ScriptEngine.h"
  38. using namespace WallpaperEngine;
  39. using namespace WallpaperEngine::Render::Objects;
  40. using namespace WallpaperEngine::Render::Objects::Effects;
  41. using namespace WallpaperEngine::Data::Parsers;
  42. using namespace WallpaperEngine::Data::Builders;
  43. using namespace WallpaperEngine::Data::Utils;
  44. extern float g_Time;
  45. extern float g_TimeLast;
  46. namespace {
  47. bool isMagentaNeonTint (const glm::vec3& color) { return color.r > 0.55f && color.g < 0.25f && color.b > 0.45f; }
  48. std::optional<glm::vec3> findMagentaCompositeTint (const Image& image, const std::vector<int>& skippedEffectIds) {
  49. for (const auto& effect : image.effects) {
  50. if (std::find (skippedEffectIds.begin (), skippedEffectIds.end (), static_cast<int> (effect->id))
  51. != skippedEffectIds.end ()) {
  52. continue;
  53. }
  54. if (!effect->visible->value->getBool ()) {
  55. continue;
  56. }
  57. for (const auto& passOverride : effect->passOverrides) {
  58. const auto compositeCombo = passOverride->combos.find ("COMPOSITE");
  59. if (compositeCombo == passOverride->combos.end () || compositeCombo->second != 2) {
  60. continue;
  61. }
  62. const auto compositeColor = passOverride->constants.find ("compositecolor");
  63. if (compositeColor == passOverride->constants.end () || compositeColor->second == nullptr
  64. || compositeColor->second->value == nullptr) {
  65. continue;
  66. }
  67. const auto tint = compositeColor->second->value->getVec3 ();
  68. if (isMagentaNeonTint (tint)) {
  69. return tint;
  70. }
  71. }
  72. }
  73. return std::nullopt;
  74. }
  75. // float4x3 per bone
  76. void packPuppetBones (const std::vector<glm::mat4>& skin, std::vector<GLfloat>& out) {
  77. out.assign (skin.size () * 12, 0.0f);
  78. for (size_t bone = 0; bone < skin.size (); bone++) {
  79. for (int column = 0; column < 4; column++) {
  80. for (int row = 0; row < 3; row++) {
  81. out[bone * 12 + column * 3 + row] = skin[bone][column][row];
  82. }
  83. }
  84. }
  85. }
  86. // first mesh with flag 2 (sub_1401FBAE0, puppet +912), BLENDROWCOUNT = the u32 after its flags (sub_140209540)
  87. std::optional<PuppetBlendMesh> readPuppetBlendMesh (const std::vector<char>& data) {
  88. PuppetFileReader reader (data, 0);
  89. reader.string ();
  90. const int version = std::atoi (data.data () + strlen ("MDLV"));
  91. if (version < 4) {
  92. return std::nullopt;
  93. }
  94. const auto defaultFormat = reader.next<uint32_t> ();
  95. const auto materials = reader.next<uint32_t> ();
  96. const auto meshes = reader.next<uint32_t> ();
  97. for (uint32_t mesh = 0; mesh < meshes; mesh++) {
  98. PuppetBlendMesh result;
  99. for (uint32_t material = 0; material < materials; material++) {
  100. const std::string name = reader.text ();
  101. if (material == 0) {
  102. result.material = name;
  103. }
  104. }
  105. const auto flags = reader.next<uint32_t> ();
  106. if (flags & 2) {
  107. result.rows = reader.next<uint32_t> ();
  108. }
  109. if (version >= 17) {
  110. reader.skip (sizeof (float) * 6);
  111. }
  112. result.format = version >= 15 ? reader.next<uint32_t> () : defaultFormat;
  113. std::tie (result.vertices, result.vertexBytes) = reader.blob ();
  114. std::tie (result.indices, result.indexBytes) = reader.blob ();
  115. if (flags & 2) {
  116. return result;
  117. }
  118. if (version >= 21) {
  119. if (reader.next<uint8_t> () != 0) {
  120. (void)reader.next<uint32_t> ();
  121. (void)reader.blob ();
  122. }
  123. if (reader.next<uint8_t> () != 0) {
  124. (void)reader.blob ();
  125. }
  126. }
  127. if (version >= 23) {
  128. const auto records = reader.next<uint32_t> ();
  129. for (uint32_t record = 0; record < records; record++) {
  130. reader.skip (sizeof (uint64_t));
  131. reader.string ();
  132. (void)reader.next<uint32_t> ();
  133. reader.skip (sizeof (uint32_t) * reader.next<uint32_t> ());
  134. reader.skip (sizeof (uint32_t) * reader.next<uint32_t> ());
  135. }
  136. }
  137. }
  138. return std::nullopt;
  139. }
  140. // MDMP per mesh (sub_140261880): u16 targets, scale, vertex count, then per target u64, name and 16 bit blobs:
  141. // positions, normals (0x400), 3 more (0x800), alpha (0x1000), bone rule (0x2000, u32 u32 f32 f32)
  142. std::optional<PuppetMorphTargets>
  143. readPuppetMorphTargets (const std::vector<char>& data, size_t section, uint32_t flags) {
  144. PuppetFileReader reader (data, section);
  145. reader.string ();
  146. (void)reader.next<uint32_t> ();
  147. const auto targets = reader.next<uint16_t> ();
  148. if (targets == 0) {
  149. return std::nullopt;
  150. }
  151. PuppetMorphTargets morph;
  152. morph.scale = reader.next<float> ();
  153. morph.vertexCount = reader.next<uint32_t> ();
  154. std::vector<size_t> positions;
  155. std::vector<size_t> alphas;
  156. for (uint16_t target = 0; target < targets; target++) {
  157. (void)reader.next<uint64_t> ();
  158. morph.names.push_back (reader.text ());
  159. const auto [position, positionBytes] = reader.blob ();
  160. morph.vertexCount = std::min (morph.vertexCount, positionBytes / 6);
  161. if (positionBytes != morph.vertexCount * 6) {
  162. throw std::runtime_error ("morph target positions don't match the vertex count");
  163. }
  164. positions.push_back (position);
  165. for (const uint32_t flag : { 0x400u, 0x800u }) {
  166. if ((flags & flag) && reader.blob ().second != positionBytes) {
  167. throw std::runtime_error ("morph target normals don't match the vertex count");
  168. }
  169. }
  170. if (flags & 0x1000) {
  171. const auto [alpha, alphaBytes] = reader.blob ();
  172. if (alphaBytes != morph.vertexCount * 2) {
  173. throw std::runtime_error ("morph target alphas don't match the vertex count");
  174. }
  175. alphas.push_back (alpha);
  176. }
  177. if (flags & 0x2000) {
  178. PuppetMorphTargets::BoneRule rule;
  179. rule.bone = reader.next<uint32_t> ();
  180. rule.axis = (reader.next<uint32_t> () & 2) ? 1.0f : 0.0f;
  181. rule.edge0 = reader.next<float> ();
  182. rule.edge1 = reader.next<float> ();
  183. morph.boneRules.push_back (rule);
  184. }
  185. }
  186. // square of vertexCount * targets + 1 texels, texel 0 is (0, 0, 0, 1)
  187. const uint32_t texels = morph.vertexCount * targets + 1;
  188. auto side = static_cast<uint32_t> (std::sqrt (static_cast<float> (texels)));
  189. if (side * side < texels) {
  190. side++;
  191. }
  192. const auto snorm = [&data] (size_t offset) {
  193. int16_t value;
  194. std::memcpy (&value, data.data () + offset, sizeof (value));
  195. return std::max (static_cast<float> (value) / 32767.0f, -1.0f);
  196. };
  197. morph.texels.assign (static_cast<size_t> (side) * side, glm::vec4 (0.0f));
  198. morph.texels[0] = glm::vec4 (0.0f, 0.0f, 0.0f, 1.0f);
  199. // without 0x1000 morphed vertices read alpha 0
  200. morph.alpha = (flags & 0x1000) == 0;
  201. size_t out = 1;
  202. for (size_t target = 0; target < alphas.size (); target++) {
  203. for (uint32_t vertex = 0; vertex < morph.vertexCount; vertex++) {
  204. const size_t position = positions[target] + vertex * 6;
  205. morph.texels[out] = glm::vec4 (
  206. snorm (position), snorm (position + 2), snorm (position + 4), snorm (alphas[target] + vertex * 2)
  207. );
  208. morph.alpha = morph.alpha || morph.texels[out].w != 1.0f;
  209. out++;
  210. }
  211. }
  212. return morph;
  213. }
  214. }
  215. CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
  216. CObject (scene, image), CRenderable (scene, image, *image.model->material), ScriptableObject (scene, image),
  217. m_sceneSpacePosition (GL_NONE), m_copySpacePosition (GL_NONE), m_passSpacePosition (GL_NONE),
  218. m_texcoordCopy (GL_NONE), m_texcoordPass (GL_NONE), m_modelViewProjectionScreen (),
  219. m_modelViewProjectionPass (glm::mat4 (1.0)), m_modelViewProjectionCopy (), m_modelViewProjectionScreenInverse (),
  220. m_modelViewProjectionPassInverse (glm::inverse (m_modelViewProjectionPass)), m_modelViewProjectionCopyInverse (),
  221. m_modelMatrix (), m_viewProjectionMatrix (), m_image (image), m_pos (), m_initialized (false) {
  222. this->registerProperty ("origin", *image.origin->value);
  223. this->registerProperty ("scale", *image.scale->value);
  224. this->registerProperty ("angles", *image.angles->value);
  225. this->registerProperty ("visible", *image.visible->value);
  226. this->registerProperty ("copybackground", *image.copyBackground->value);
  227. this->registerProperty ("alpha", *image.alpha->value);
  228. this->registerProperty ("color", *image.color->value);
  229. this->registerProperty ("parallaxDepth", *image.parallaxDepth->value);
  230. this->registerProperty ("alignment", *image.alignmentName->value);
  231. this->registerRenderableProperties (image.renderable, *image.colorBlendMode, *image.brightness);
  232. this->registerEffectConstants (image.effects);
  233. // animation layers carry their own property scripts, WE runs them with the layer as thisObject (the JSON loader
  234. // sub_1401730D0 binds them to the IAnimationLayer object, sub_14026C980 lists its properties and methods)
  235. for (size_t layerIndex = 0; layerIndex < image.animationLayers.size (); layerIndex++) {
  236. this->registerAnimationLayerProperties (layerIndex, *image.animationLayers[layerIndex]);
  237. }
  238. auto scene_width = static_cast<float> (scene.getWidth ());
  239. auto scene_height = static_cast<float> (scene.getHeight ());
  240. glm::vec2 size = this->getSize ();
  241. // a shape's quad is a square of the scene height (shape load sub_14025FAC0, renderer +136)
  242. if (this->getImage ().shape) {
  243. size = { scene_height, scene_height };
  244. }
  245. try {
  246. this->detectTexture ();
  247. } catch (const Assets::AssetLoadException& e) {
  248. // live WE loads the scene anyway and draws the layer empty
  249. sLog.error ("Image ", image.id, " has no texture, drawing it empty: ", e.what ());
  250. }
  251. // WE skips "" texture names (sub_1401556E0), the sampler falls back to "error" (sub_1401515B0): a 6x6 checker
  252. // that autosize shrinks the layer to (2282018774). --repair-assets loads materials/.tex instead
  253. if (this->m_texture == nullptr && !this->m_image.model->solidlayer
  254. && !image.model->material->passes.front ()->textures.contains (0)) {
  255. if (this->getContext ().getApp ().getContext ().settings.general.repairAssets) {
  256. try {
  257. this->m_texture = this->getContext ().resolveTexture ("", scene.getScene ().project);
  258. } catch (const Assets::AssetLoadException&) {
  259. // nothing shipped under the empty name either
  260. }
  261. }
  262. if (this->m_texture == nullptr) {
  263. sLog.error ("Image ", image.id, " material has no albedo texture, drawing the missing texture");
  264. this->m_texture = scene.getMissingTexture ();
  265. }
  266. }
  267. const bool placeholderTexture = this->m_texture == nullptr;
  268. if (this->m_texture == nullptr) {
  269. if (this->m_image.model->solidlayer && size.x == 0.0f && size.y == 0.0f) {
  270. size.x = static_cast<float> (scene.getCanvasWidth ());
  271. size.y = static_cast<float> (scene.getCanvasHeight ());
  272. }
  273. // solid layers are often declared far larger than the scene, nothing samples past the canvas
  274. const glm::vec2 placeholderSize = { std::min (size.x, static_cast<float> (scene.getCanvasWidth ())),
  275. std::min (size.y, static_cast<float> (scene.getCanvasHeight ())) };
  276. this->m_texture = std::make_shared<CFBO> (
  277. "", TextureFormat_ARGB8888, TextureFlags_NoFlags, 1, size.x, size.y, placeholderSize.x, placeholderSize.y
  278. );
  279. }
  280. if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
  281. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  282. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  283. } else if (
  284. (size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
  285. && this->getImage ().model->height.has_value ()
  286. ) {
  287. size.x = static_cast<float> (this->getImage ().model->width.value ());
  288. size.y = static_cast<float> (this->getImage ().model->height.value ());
  289. }
  290. // autosize takes the size of the loaded texture (a single frame for sprite sheets) over the
  291. // declared one, or the scene's for project layers. fullscreen still wins over it
  292. if (this->getImage ().model->autosize && this->getImage ().model->projectlayer) {
  293. size = { scene_width, scene_height };
  294. } else if (
  295. this->getImage ().model->autosize && !placeholderTexture
  296. && std::dynamic_pointer_cast<const CFBO> (this->m_texture) == nullptr
  297. ) {
  298. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  299. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  300. }
  301. if (this->getImage ().model->fullscreen) {
  302. size = { static_cast<float> (scene.getCanvasWidth ()), static_cast<float> (scene.getCanvasHeight ()) };
  303. }
  304. this->m_size = size;
  305. // taken after the texture/model/fullscreen fallbacks above, unsized layers would otherwise get 0x0 buffers
  306. glm::vec2 bufferSize = size;
  307. if (placeholderTexture) {
  308. bufferSize = glm::min (bufferSize, glm::vec2 (scene.getCanvasWidth (), scene.getCanvasHeight ()));
  309. }
  310. this->updateScenePosition (size);
  311. std::ostringstream nameA, nameB;
  312. // WE renders layers with LIGHTING or REFLECTION unlit into _rt_imageLayerAlbedo_<id> when they have offscreen
  313. // passes and lights them last (sub_1401914B0); here the first pass is lit instead, through PRELIGHTING
  314. nameA << "_rt_imageLayerComposite_" << this->getImage ().id << "_a";
  315. nameB << "_rt_imageLayerComposite_" << this->getImage ().id << "_b";
  316. // sub_1401E8AA0: buffer flags are the object's clampuvs/nointerpolation (else the texture's)
  317. const auto& renderable = this->getImage ().renderable;
  318. const bool noInterpolation = renderable.noInterpolation->value->getBool ()
  319. || (this->m_texture->getFlags () & TextureFlags_NoInterpolation) != 0;
  320. const uint32_t compositeFlags = (renderable.clampUVs->value->getBool () ? TextureFlags_ClampUVs : 0)
  321. | (noInterpolation ? TextureFlags_NoInterpolation : 0);
  322. // layer buffers are 16 bit float in HDR scene rendering (sub_1401E7170)
  323. const TextureFormat layerFormat = this->getScene ().isHDR () ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888;
  324. const auto mainFBO = scene.create (
  325. nameA.str (), layerFormat, compositeFlags, 1, { bufferSize.x, bufferSize.y }, { bufferSize.x, bufferSize.y }
  326. );
  327. const auto subFBO = scene.create (
  328. nameB.str (), layerFormat, compositeFlags, 1, { bufferSize.x, bufferSize.y }, { bufferSize.x, bufferSize.y }
  329. );
  330. if (this->followsOutputSize ()) {
  331. scene.followOutputSize (mainFBO, 1);
  332. scene.followOutputSize (subFBO, 1);
  333. }
  334. this->m_currentMainFBO = this->m_mainFBO = this->m_namedMainFBO = mainFBO;
  335. this->m_currentSubFBO = this->m_subFBO = this->m_namedSubFBO = subFBO;
  336. this->m_layerBufferConfig = { .size = bufferSize, .format = layerFormat, .flags = compositeFlags };
  337. GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
  338. this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
  339. this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
  340. float width = 1.0f;
  341. float height = 1.0f;
  342. if (this->getTexture ()->isAnimated ()) {
  343. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  344. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  345. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  346. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  347. } else if (
  348. this->getTexture () != nullptr
  349. && (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
  350. || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())
  351. ) {
  352. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  353. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  354. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  355. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  356. }
  357. float x = 0.0f;
  358. float y = 0.0f;
  359. if (this->getTexture ()->isAnimated ()) {
  360. x = 0.0f;
  361. y = 0.0f;
  362. width = 1.0f;
  363. height = 1.0f;
  364. }
  365. GLfloat realWidth = size.x;
  366. GLfloat realHeight = size.y;
  367. GLfloat realX = 0.0;
  368. GLfloat realY = 0.0;
  369. if (this->getImage ().model->passthrough) {
  370. // Passthrough shaders fill the destination FBO from texcoords and sample the scene using positions.
  371. // Keep the destination quad full-screen in local FBO space, but pass scene-space positions through.
  372. x = 0.0f;
  373. y = 0.0f;
  374. width = 1.0f;
  375. height = 1.0f;
  376. realX = this->m_pos.x;
  377. realY = this->m_pos.w;
  378. realWidth = this->m_pos.z;
  379. realHeight = this->m_pos.y;
  380. if (this->getImage ().model->fullscreen) {
  381. realX = -1.0;
  382. realY = -1.0;
  383. realWidth = 1.0;
  384. realHeight = 1.0;
  385. }
  386. }
  387. GLfloat texcoordCopy[] = { x, height, x, y, width, height, width, height, x, y, width, y };
  388. GLfloat copySpacePosition[] = { realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f,
  389. realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f };
  390. GLfloat texcoordPass[] = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f };
  391. GLfloat passSpacePosition[]
  392. = { -1.0, 1.0, 0.0f, -1.0, -1.0, 0.0f, 1.0, 1.0, 0.0f, 1.0, 1.0, 0.0f, -1.0, -1.0, 0.0f, 1.0, -1.0, 0.0f };
  393. glGenBuffers (1, &this->m_sceneSpacePosition);
  394. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  395. glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_STATIC_DRAW);
  396. glGenBuffers (1, &this->m_copySpacePosition);
  397. glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
  398. glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_STATIC_DRAW);
  399. glGenBuffers (1, &this->m_passSpacePosition);
  400. glBindBuffer (GL_ARRAY_BUFFER, this->m_passSpacePosition);
  401. glBufferData (GL_ARRAY_BUFFER, sizeof (passSpacePosition), passSpacePosition, GL_STATIC_DRAW);
  402. glGenBuffers (1, &this->m_texcoordCopy);
  403. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
  404. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_STATIC_DRAW);
  405. glGenBuffers (1, &this->m_texcoordPass);
  406. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordPass);
  407. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordPass), texcoordPass, GL_STATIC_DRAW);
  408. this->uploadSceneTexCoords ({ x, y, width, height });
  409. this->m_hasPuppetMesh = this->loadPuppetMesh (size);
  410. this->m_modelViewProjectionScreen = this->getViewProjection ();
  411. // must match m_modelViewProjectionScreen - updateScreenSpacePosition() may skip recomputing it
  412. this->m_modelViewProjectionScreenInverse = glm::inverse (this->m_modelViewProjectionScreen);
  413. this->updateEffectTextureProjection ();
  414. if (this->getImage ().model->passthrough) {
  415. this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
  416. } else {
  417. this->m_modelViewProjectionCopy = DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y));
  418. }
  419. this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
  420. this->m_modelMatrix = DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y));
  421. this->m_viewProjectionMatrix = glm::mat4 (1.0);
  422. this->m_texture->incrementUsageCount ();
  423. }
  424. void CImage::updateTextures () const {
  425. this->getTexture ()->update ();
  426. for (const auto* pass : this->m_passes) {
  427. pass->updatePlaybackTextures ();
  428. }
  429. }
  430. void CImage::renderPassthroughChildren (const std::shared_ptr<const CFBO>& buffer) {
  431. // the buffer holds the layer's quad (m_pos, copy pass texcoords: v = 1 at m_pos.y), children land in it through
  432. // model = inverse (layer world), view = identity, ortho (-w/2, w/2, -h/2, h/2, -1000, 1000) (sub_1401ECB20).
  433. // Fullscreen layers keep the scene's camera
  434. glm::mat4 transform (1.0f);
  435. glm::mat4 viewProjection = this->getScene ().getWorldViewProjection ();
  436. if (!this->getImage ().model->fullscreen) {
  437. const glm::vec3 center ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  438. const glm::vec3 halfExtent (
  439. (this->m_pos.z - this->m_pos.x) / 2.0f, (this->m_pos.y - this->m_pos.w) / 2.0f, 1000.0f
  440. );
  441. transform = DepthRange::toClip (
  442. glm::inverse (glm::scale (glm::translate (this->m_modelViewProjectionScreen, center), halfExtent))
  443. );
  444. // lights skip the model stack (volumetricsfront.vert only has g_ViewProjectionMatrix), so they see the bare
  445. // ortho with the scene's y flip: their world position lands in the layer as if the layer sat at the origin
  446. const glm::vec2 size = this->getSize ();
  447. viewProjection
  448. = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  449. * DepthRange::toClip (
  450. glm::ortho (-size.x / 2.0f, size.x / 2.0f, -size.y / 2.0f, size.y / 2.0f, -1000.0f, 1000.0f)
  451. );
  452. }
  453. this->getScene ().renderPassthroughChildren (
  454. this->getId (),
  455. {
  456. .fbo = buffer,
  457. .transform = transform,
  458. .alphaMax = !this->m_image.copyBackground->value->getBool (),
  459. .viewProjection = viewProjection,
  460. }
  461. );
  462. }
  463. bool CImage::usesPooledBuffer () const {
  464. const int colorBlendMode = this->m_image.colorBlendMode->value->getInt ();
  465. // puppets only with effects, an animated texture, a blend map or a prelighting material (sub_14020AE00)
  466. const bool namedPuppet = this->m_hasPuppetMesh
  467. && (!this->m_image.effects.empty () || (this->m_texture != nullptr && this->m_texture->isAnimated ())
  468. || this->m_blendMap.pass != nullptr || this->m_puppetPrelight.pass != nullptr);
  469. // 0x800000 / 0x1000000 are distance / height fog (sub_140186440), dependencies and layerimage sources get 0x1010
  470. return (colorBlendMode == 0 || colorBlendMode == 31) && !this->m_image.renderable.ledSource->value->getBool ()
  471. && !namedPuppet && !this->m_readByOtherLayer && !this->m_emitterImageSource
  472. && !this->getScene ().hasDistanceFog () && !this->getScene ().hasHeightFog ();
  473. }
  474. int CImage::effectBufferPasses () const {
  475. int passes = 0;
  476. for (const auto& effect : this->m_image.effects) {
  477. const auto visibility = this->getScene ().getContext ().getApp ().getContext ().resolveEffectVisibility (
  478. static_cast<int> (effect->id), effect->name
  479. );
  480. if (!visibility.value_or (effect->visible->value->getBool ())) {
  481. continue;
  482. }
  483. passes += this->getImage ().shape ? 0 : 1;
  484. for (const auto& pass : effect->effect->passes) {
  485. passes += pass->compose ? 1 : 0;
  486. }
  487. }
  488. return passes;
  489. }
  490. std::string CImage::layerBufferName (const int index) const {
  491. // flag 0x10 adds a buffer, a passthrough layer with children gets at least one, at most two
  492. const bool named = !this->usesPooledBuffer ();
  493. const int passes = this->effectBufferPasses () + (named ? 1 : 0);
  494. const int buffers = passes == 0 && this->m_hasPassthroughChildren ? 1 : std::min (passes, 2);
  495. if (index >= buffers) {
  496. return "";
  497. }
  498. // only the first buffer can be named, the second comes from the pool
  499. if (named && index == 0) {
  500. return "_rt_imageLayerComposite_" + std::to_string (this->getImage ().id) + "_a";
  501. }
  502. const auto& config = this->m_layerBufferConfig;
  503. const std::string name = "sb." + std::to_string (std::max (static_cast<int> (config.size.x), 4)) + "."
  504. + std::to_string (std::max (static_cast<int> (config.size.y), 4)) + "."
  505. + ((config.flags & TextureFlags_NoInterpolation) ? "n" : "b") + "."
  506. + ((config.flags & TextureFlags_ClampUVs) ? "c" : "r") + "." + std::to_string (index);
  507. int matches = 0;
  508. // every passthrough ancestor whose last offscreen buffer has this name adds one. Without effects WE reads index -1,
  509. // never a match
  510. for (auto parent = this->getImage ().parent; parent.has_value ();) {
  511. const auto* object = this->getScene ().getObject (*parent);
  512. if (object == nullptr) {
  513. break;
  514. }
  515. if (const auto* image = object->is<CImage> () ? object->as<CImage> () : nullptr;
  516. image != nullptr && image->m_image.model->passthrough) {
  517. const int last = image->effectBufferPasses () - (image->usesPooledBuffer () ? 1 : 0);
  518. if (last >= 0 && image->layerBufferName (last % 2) == name) {
  519. matches++;
  520. }
  521. }
  522. parent = object->getObject ().parent;
  523. }
  524. return matches > 0 ? name + std::to_string (matches) : name;
  525. }
  526. void CImage::assignLayerBuffers () {
  527. if (this->m_namedMainFBO == nullptr) {
  528. return;
  529. }
  530. auto& scene = this->getScene ();
  531. const auto& config = this->m_layerBufferConfig;
  532. const auto pooled = [&] (const int index, const std::shared_ptr<const CFBO>& named) -> std::shared_ptr<const CFBO> {
  533. const std::string name = this->layerBufferName (index);
  534. // named and _rt_ buffers stay the layer's own
  535. if (name.empty () || name.starts_with ("_rt_")) {
  536. return named;
  537. }
  538. if (auto existing = scene.find (name); existing != nullptr) {
  539. return existing;
  540. }
  541. auto fbo = scene.create (name, config.format, config.flags, 1, config.size, config.size);
  542. if (this->followsOutputSize ()) {
  543. scene.followOutputSize (fbo, 1);
  544. }
  545. return fbo;
  546. };
  547. this->m_mainFBO = pooled (0, this->m_namedMainFBO);
  548. this->m_subFBO = pooled (1, this->m_namedSubFBO);
  549. }
  550. bool CImage::hitTest (const glm::vec2& ndc) {
  551. if (this->getImage ().model->fullscreen) {
  552. return true;
  553. }
  554. this->updateScreenSpacePosition ();
  555. const glm::vec3 center ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  556. const glm::vec2 half (
  557. std::abs (this->m_pos.z - this->m_pos.x) / 2.0f, std::abs (this->m_pos.w - this->m_pos.y) / 2.0f
  558. );
  559. return Wallpapers::CScene::quadContainsPoint (
  560. glm::translate (this->m_modelViewProjectionScreen, center), half, ndc
  561. );
  562. }
  563. glm::vec2 CImage::cursorLocalPosition (const glm::vec2& ndc) {
  564. this->updateScreenSpacePosition ();
  565. const glm::vec3 center ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  566. const auto point
  567. = Wallpapers::CScene::quadPlanePoint (glm::translate (this->m_modelViewProjectionScreen, center), ndc);
  568. const glm::vec2 extent (this->m_pos.z - this->m_pos.x, this->m_pos.y - this->m_pos.w);
  569. if (!point.has_value () || extent.x == 0.0f || extent.y == 0.0f) {
  570. return glm::vec2 (0.0f);
  571. }
  572. // m_pos runs y down from the top edge (.w), x from the texture's left edge (.x)
  573. const glm::vec2 u (
  574. (point->x + center.x - this->m_pos.x) / extent.x, (point->y + center.y - this->m_pos.w) / extent.y
  575. );
  576. return u * this->m_displaySize;
  577. }
  578. std::optional<std::string> CImage::cursorHitBox (const glm::vec2& ndc) const {
  579. if (!this->m_hasPuppetMesh) {
  580. return std::nullopt;
  581. }
  582. glm::vec3 origin;
  583. glm::vec3 direction;
  584. this->getScene ().cursorLine (ndc, this->getImage ().perspective->value->getBool (), origin, direction);
  585. return this->m_rig.imageHitBox (origin, direction);
  586. }
  587. CImage::~CImage () {
  588. this->m_texture->decrementUsageCount ();
  589. // delete passes first as they depend on the image's data
  590. for (auto* pass : this->m_allPasses.empty () ? this->m_passes : this->m_allPasses) {
  591. delete pass;
  592. }
  593. this->m_passes.clear ();
  594. this->m_allPasses.clear ();
  595. for (auto* pass : this->m_puppetClipMaskPasses) {
  596. delete pass;
  597. }
  598. delete this->m_puppetClipTargetPass;
  599. delete this->m_puppetClipComposePass;
  600. glDeleteBuffers (1, &this->m_sceneSpacePosition);
  601. glDeleteBuffers (1, &this->m_copySpacePosition);
  602. glDeleteBuffers (1, &this->m_passSpacePosition);
  603. glDeleteBuffers (1, &this->m_texcoordCopy);
  604. glDeleteBuffers (1, &this->m_texcoordPass);
  605. glDeleteBuffers (1, &this->m_texcoordDirect);
  606. glDeleteBuffers (1, &this->m_texcoordFinal);
  607. if (this->m_puppetSpacePosition != GL_NONE) {
  608. glDeleteBuffers (1, &this->m_puppetSpacePosition);
  609. }
  610. if (this->m_puppetTexCoord != GL_NONE) {
  611. glDeleteBuffers (1, &this->m_puppetTexCoord);
  612. }
  613. if (this->m_puppetVertexAlphaWeights != GL_NONE) {
  614. glDeleteBuffers (1, &this->m_puppetVertexAlphaWeights);
  615. }
  616. if (this->m_puppetIndices != GL_NONE) {
  617. glDeleteBuffers (1, &this->m_puppetIndices);
  618. }
  619. delete this->m_blendMap.copyPass;
  620. delete this->m_blendMap.pass;
  621. for (const GLuint buffer :
  622. { this->m_puppetPrelight.bindPositions, this->m_puppetPrelight.morphedPositions,
  623. this->m_puppetPrelight.flatPositions, this->m_puppetPrelight.normals, this->m_puppetPrelight.tangents,
  624. this->m_puppetPrelight.blendIndices, this->m_puppetPrelight.blendWeights, this->m_puppetClipIndices,
  625. this->m_puppetClipComposePosition, this->m_puppetClipComposeTexCoord, this->m_blendMap.vertices,
  626. this->m_blendMap.indices, this->m_blendMap.quad }) {
  627. if (buffer != GL_NONE) {
  628. glDeleteBuffers (1, &buffer);
  629. }
  630. }
  631. }
  632. bool CImage::loadPuppetMesh (const glm::vec2& size) {
  633. if (!this->getImage ().model->puppet.has_value ()) {
  634. return false;
  635. }
  636. const auto& name = *this->getImage ().model->puppet;
  637. try {
  638. const auto file = this->getScene ().readModelFile (name);
  639. const std::vector<char>& data = *file;
  640. auto mesh = readPuppetMeshFile (data);
  641. if (!mesh.has_value ()) {
  642. sLog.error ("Could not find a usable MDLV mesh block in ", name);
  643. return false;
  644. }
  645. for (const auto& warning : mesh->warnings) {
  646. sLog.error ("Puppet ", name, ": ", warning);
  647. }
  648. this->m_puppetRawPositions = mesh->positions;
  649. this->updatePuppetPositionBuffer (size);
  650. glGenBuffers (1, &this->m_puppetTexCoord);
  651. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
  652. glBufferData (
  653. GL_ARRAY_BUFFER, mesh->texcoords.size () * sizeof (GLfloat), mesh->texcoords.data (), GL_STATIC_DRAW
  654. );
  655. glGenBuffers (1, &this->m_puppetIndices);
  656. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
  657. glBufferData (
  658. GL_ELEMENT_ARRAY_BUFFER, mesh->indices.size () * sizeof (GLushort), mesh->indices.data (), GL_STATIC_DRAW
  659. );
  660. this->m_puppetIndexCount = static_cast<GLsizei> (mesh->indices.size ());
  661. this->m_puppetDrawBuffer = this->m_puppetIndices;
  662. this->m_puppetDrawCount = this->m_puppetIndexCount;
  663. this->loadPuppetBlendMesh (data);
  664. const int version = mesh->version;
  665. const size_t indexEnd = mesh->indexEnd;
  666. this->m_puppetClipping.reset ();
  667. this->m_puppetParts.clear ();
  668. this->m_puppetPartOrder.clear ();
  669. this->m_puppetMeshIndices.clear ();
  670. // 4 bone alpha, 8 draw order, 0x1000 morph alpha
  671. this->m_puppetMeshFlags = mesh->flags;
  672. this->m_puppetMeshFormat = mesh->format;
  673. const uint32_t meshFlags = this->m_puppetMeshFlags;
  674. this->m_puppetPrelight.auxPositions = std::move (mesh->auxPositions);
  675. this->m_puppetPrelight.normalData = std::move (mesh->normals);
  676. this->m_puppetPrelight.tangentData = std::move (mesh->tangents);
  677. this->m_puppetMorph.reset ();
  678. this->m_puppetMorphIndices = std::move (mesh->morphIndices);
  679. if (meshFlags & 8) {
  680. try {
  681. this->m_puppetParts = PuppetClipping::readParts (data, indexEnd, version, mesh->indices.size ());
  682. } catch (const std::exception& ex) {
  683. sLog.error ("Ignoring the part ranges of ", *this->getImage ().model->puppet, ": ", ex.what ());
  684. }
  685. if (!this->m_puppetParts.empty ()) {
  686. this->m_puppetMeshIndices = mesh->indices;
  687. this->m_puppetPartOrder.resize (this->m_puppetParts.size ());
  688. for (uint32_t index = 0; index < this->m_puppetPartOrder.size (); index++) {
  689. this->m_puppetPartOrder[index] = index;
  690. }
  691. }
  692. }
  693. try {
  694. auto clipping = PuppetClipping::read (data, indexEnd, version, mesh->indices.size ());
  695. if (clipping.has_value ()) {
  696. clipping->build (mesh->indices);
  697. glGenBuffers (1, &this->m_puppetClipIndices);
  698. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
  699. glBufferData (
  700. GL_ELEMENT_ARRAY_BUFFER, clipping->indices.size () * sizeof (GLushort), clipping->indices.data (),
  701. GL_STATIC_DRAW
  702. );
  703. sLog.out (
  704. "Puppet ", *this->getImage ().model->puppet, " clipping: ", clipping->records.size (), " masks, ",
  705. clipping->parts.size (), " parts, ", clipping->draws.size (), " draws"
  706. );
  707. this->m_puppetClipping = std::move (clipping);
  708. }
  709. } catch (const std::exception& ex) {
  710. sLog.error ("Ignoring the clipping masks of ", *this->getImage ().model->puppet, ": ", ex.what ());
  711. }
  712. sLog.out (
  713. "Loaded puppet mesh ", name, " version=", mesh->tag, " stride=", mesh->layout.vertexStride,
  714. mesh->declaredLayout ? "" : " (guessed)", " vertices=", this->m_puppetRawPositions.size () / 3,
  715. " indices=", this->m_puppetIndexCount
  716. );
  717. this->m_rig.clear ();
  718. this->m_puppetBlendIndices.clear ();
  719. this->m_puppetBlendWeights.clear ();
  720. this->m_puppetSkinnedPositions.clear ();
  721. this->m_puppetBlendIndices = std::move (mesh->blendIndices);
  722. this->m_puppetBlendWeights = std::move (mesh->blendWeights);
  723. if (mesh->skeleton < data.size () && !this->m_puppetBlendIndices.empty ()) {
  724. try {
  725. this->m_rig.load (data, mesh->sections, mesh->meshCount, name);
  726. this->m_rig.drawOrderEnabled = !this->m_puppetParts.empty ();
  727. this->m_rig.boneAlphaEnabled = (meshFlags & 4) != 0;
  728. this->m_rig.morphBlendClamped = false;
  729. this->m_rig.addSceneLayers (this->getImage ().animationLayers);
  730. if ((this->m_puppetMeshFormat & 0x10000) && this->m_rig.getMorphSection () != 0) {
  731. try {
  732. this->m_puppetMorph = readPuppetMorphTargets (data, this->m_rig.getMorphSection (), meshFlags);
  733. } catch (const std::exception& ex) {
  734. sLog.error (
  735. "Ignoring the morph targets of ", *this->getImage ().model->puppet, ": ", ex.what ()
  736. );
  737. }
  738. if (this->m_puppetMorph.has_value ()
  739. && std::ranges::any_of (this->m_puppetMorph->boneRules, [this] (const auto& rule) {
  740. return rule.bone >= this->m_rig.bones.size ();
  741. })) {
  742. sLog.error (
  743. "Puppet ", *this->getImage ().model->puppet,
  744. " has a morph target bone rule past its skeleton, drawing it without morphs"
  745. );
  746. this->m_puppetMorph.reset ();
  747. }
  748. }
  749. } catch (const std::exception& ex) {
  750. sLog.error (
  751. "Could not load puppet skeleton/animation from ", *this->getImage ().model->puppet, ": ",
  752. ex.what (), " (falling back to the static bind pose)"
  753. );
  754. this->m_rig.clear ();
  755. }
  756. }
  757. // vertex alpha via SKINNING_ALPHA (flag 4) or morph alpha < 1, both need the skinned material
  758. this->m_puppetVertexAlpha = !this->m_rig.bones.empty ()
  759. && ((meshFlags & 4) != 0 || (this->m_puppetMorph.has_value () && this->m_puppetMorph->alpha));
  760. if (this->m_puppetVertexAlpha) {
  761. this->updatePuppetVertexAlpha ({});
  762. }
  763. return true;
  764. } catch (const std::exception& ex) {
  765. sLog.error ("Could not load puppet mesh ", *this->getImage ().model->puppet, ": ", ex.what ());
  766. return false;
  767. }
  768. }
  769. void CImage::updatePuppetPositionBuffer (const glm::vec2& size) {
  770. // an animation clip's skinned output replaces the bind pose, skinning starts from the bind pose every frame
  771. const auto& source
  772. = !this->m_puppetSkinnedPositions.empty () ? this->m_puppetSkinnedPositions : this->m_puppetRawPositions;
  773. if (source.empty ()) {
  774. return;
  775. }
  776. // on the scene the puppet keeps its own y down vertices placed by m_modelViewProjectionScreen, the first effect
  777. // pass draws into the buffer through m_modelViewProjectionCopy
  778. const bool drawsOnScene = this->m_passes.size () <= 1 || this->m_puppetMeshLast;
  779. const glm::vec2 bufferOffset = drawsOnScene ? glm::vec2 (0.0f) : size / 2.0f;
  780. std::vector<GLfloat> positions;
  781. positions.reserve (source.size ());
  782. for (size_t index = 0; index + 2 < source.size (); index += 3) {
  783. positions.push_back (bufferOffset.x + source[index]);
  784. positions.push_back (bufferOffset.y - source[index + 1]);
  785. // depth isn't used for puppets and glm::ortho would clip their real mesh depth, so zero it
  786. positions.push_back (0.0f);
  787. }
  788. // not during the constructor, m_passes isn't resolved yet
  789. if (!this->m_puppetPositionDiagnosticLogged && !this->m_passes.empty ()) {
  790. this->m_puppetPositionDiagnosticLogged = true;
  791. glm::vec3 boundsMin (std::numeric_limits<float>::max ());
  792. glm::vec3 boundsMax (std::numeric_limits<float>::lowest ());
  793. for (size_t i = 0; i + 2 < positions.size (); i += 3) {
  794. const glm::vec3 p (positions[i], positions[i + 1], positions[i + 2]);
  795. boundsMin = glm::min (boundsMin, p);
  796. boundsMax = glm::max (boundsMax, p);
  797. }
  798. sLog.out (
  799. "Puppet position bake for ", this->getImage ().name, " (", this->getId (), "): drawsOnScene=", drawsOnScene,
  800. " passes=", this->m_passes.size (), " vertexCount=", positions.size () / 3, " boundsMin=(", boundsMin.x,
  801. ",", boundsMin.y, ",", boundsMin.z, ") boundsMax=(", boundsMax.x, ",", boundsMax.y, ",", boundsMax.z, ")"
  802. );
  803. }
  804. if (this->m_puppetSpacePosition == GL_NONE) {
  805. glGenBuffers (1, &this->m_puppetSpacePosition);
  806. }
  807. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
  808. glBufferData (GL_ARRAY_BUFFER, positions.size () * sizeof (GLfloat), positions.data (), GL_DYNAMIC_DRAW);
  809. }
  810. PuppetActiveAnimation* CImage::findPuppetAnimationLayer (size_t serial) { return this->m_rig.findLayer (serial); }
  811. size_t CImage::getPuppetAnimationLayerCount () const { return this->m_rig.getLayerCount (); }
  812. std::optional<size_t> CImage::getPuppetAnimationLayerAt (int64_t index) const { return this->m_rig.getLayerAt (index); }
  813. std::optional<size_t> CImage::findPuppetAnimationLayerByName (const std::string& name) const {
  814. return this->m_rig.findLayerByName (name);
  815. }
  816. std::optional<size_t> CImage::createPuppetAnimationLayer (
  817. const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove
  818. ) {
  819. return this->m_rig.createLayer (animation, config, autoRemove, this->getScene ().getScene ().project);
  820. }
  821. bool CImage::destroyPuppetAnimationLayersByName (const std::string& name) {
  822. return this->m_rig.destroyLayersByName (name);
  823. }
  824. bool CImage::destroyPuppetAnimationLayer (size_t serial) { return this->m_rig.destroyLayer (serial); }
  825. void CImage::updatePuppetPose () {
  826. if (!this->m_hasPuppetMesh || this->m_rig.bones.empty ()) {
  827. return;
  828. }
  829. if (this->getScene ().getContext ().getApp ().getContext ().settings.render.debug.noPuppetAnimation) {
  830. return;
  831. }
  832. this->m_rig.ropeEnvironment = this->getScene ().getRopeEnvironment ();
  833. this->m_rig.updatePose (this->puppetObjectWorld ());
  834. this->updatePuppetDrawOrder ();
  835. for (const auto& payload : this->m_rig.takeFiredEvents ()) {
  836. this->getScene ().getScriptEngine ().dispatchClipEvent (*this, payload);
  837. }
  838. this->m_rig.finishEndedLayers ([this] (size_t serial) {
  839. this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
  840. });
  841. for (const auto& removed : this->m_rig.takeRemovedLayers ()) {
  842. this->unregisterAnimationLayerProperties (removed.serial);
  843. }
  844. }
  845. void CImage::updatePuppetDrawOrder () {
  846. if (!this->m_rig.drawOrderTouched || this->m_puppetParts.empty ()) {
  847. return;
  848. }
  849. // a part's key is (int) (its order + its bone's MDLS order, made when the parts are, + the bone's animated value)
  850. const auto& boneOrder = this->m_rig.boneDrawOrder;
  851. const auto& animated = this->m_rig.drawOrder;
  852. std::vector<int> keys (this->m_puppetParts.size (), 0);
  853. for (size_t index = 0; index < this->m_puppetParts.size (); index++) {
  854. const auto& part = this->m_puppetParts[index];
  855. const int base = static_cast<int> (part.order) + (part.bone < boneOrder.size () ? boneOrder[part.bone] : 0);
  856. keys[index] = static_cast<int> (
  857. static_cast<float> (base) + (part.bone < animated.size () ? animated[part.bone] : 0.0f)
  858. );
  859. }
  860. const auto byKey = [&keys] (uint32_t a, uint32_t b) { return keys[a] < keys[b]; };
  861. if (std::ranges::is_sorted (this->m_puppetPartOrder, byKey)) {
  862. return;
  863. }
  864. // MSVC's std::sort (sub_1402154D0) is an insertion sort up to 32 elements, which keeps equal keys in order
  865. std::ranges::stable_sort (this->m_puppetPartOrder, byKey);
  866. if (this->m_puppetClipping.has_value ()) {
  867. this->m_puppetClipping->order = this->m_puppetPartOrder;
  868. this->m_puppetClipping->build (this->m_puppetMeshIndices);
  869. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
  870. glBufferData (
  871. GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipping->indices.size () * sizeof (GLushort),
  872. this->m_puppetClipping->indices.data (), GL_DYNAMIC_DRAW
  873. );
  874. return;
  875. }
  876. std::vector<uint16_t> indices;
  877. indices.reserve (this->m_puppetMeshIndices.size ());
  878. for (const uint32_t index : this->m_puppetPartOrder) {
  879. const auto& part = this->m_puppetParts[index];
  880. indices.insert (
  881. indices.end (), this->m_puppetMeshIndices.begin () + part.firstIndex,
  882. this->m_puppetMeshIndices.begin () + part.firstIndex + part.indexCount
  883. );
  884. }
  885. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
  886. glBufferData (GL_ELEMENT_ARRAY_BUFFER, indices.size () * sizeof (GLushort), indices.data (), GL_DYNAMIC_DRAW);
  887. this->m_puppetIndexCount = static_cast<GLsizei> (indices.size ());
  888. this->m_puppetDrawCount = this->m_puppetIndexCount;
  889. }
  890. void CImage::updatePuppetSkinning () {
  891. if (!this->m_rig.poseAnimated || this->m_rig.boneModel.size () != this->m_rig.bones.size ()) {
  892. return;
  893. }
  894. const auto& worldAnimated = this->m_rig.boneModel;
  895. std::vector<glm::mat4> skinMatrices (this->m_rig.bones.size ());
  896. for (size_t i = 0; i < this->m_rig.bones.size (); i++) {
  897. skinMatrices[i] = worldAnimated[i] * this->m_rig.bones[i].inverseBindWorld;
  898. }
  899. // sub_14020CFF0: up to 11 active targets, stable sorted by weight descending
  900. std::vector<std::pair<uint32_t, float>> targets;
  901. if (this->m_puppetMorph.has_value () && this->m_puppetMorphShader && !this->m_rig.morphWeights.empty ()) {
  902. const auto& state = this->m_rig.morphWeights.front ();
  903. for (uint32_t target = 0; target < state.weights.size () && target < 64 && targets.size () < 11; target++) {
  904. if (state.active & (uint64_t (1) << target)) {
  905. targets.emplace_back (target, state.weights[target]);
  906. }
  907. }
  908. std::ranges::stable_sort (targets, std::ranges::greater {}, &std::pair<uint32_t, float>::second);
  909. }
  910. // inverse of the rule bone's model matrix. Animation tracks can name targets past the mesh's own (up to 64),
  911. // those have no rule and no texels
  912. const bool boneRules = !targets.empty () && !this->m_puppetMorph->boneRules.empty ();
  913. std::vector<const PuppetMorphTargets::BoneRule*> rules;
  914. std::vector<glm::mat4> ruleInverse;
  915. if (boneRules) {
  916. const auto& all = this->m_puppetMorph->boneRules;
  917. for (const auto& [target, weight] : targets) {
  918. const auto* rule
  919. = target < all.size () && all[target].bone < worldAnimated.size () ? &all[target] : nullptr;
  920. rules.push_back (rule);
  921. ruleInverse.push_back (rule != nullptr ? glm::inverse (worldAnimated[rule->bone]) : glm::mat4 (1.0f));
  922. }
  923. }
  924. const auto skin = [this, &skinMatrices] (size_t v, const glm::vec4& position) {
  925. glm::vec3 skinned (0.0f);
  926. const glm::uvec4& indices
  927. = v < this->m_puppetBlendIndices.size () ? this->m_puppetBlendIndices[v] : glm::uvec4 (0);
  928. const glm::vec4& weights
  929. = v < this->m_puppetBlendWeights.size () ? this->m_puppetBlendWeights[v] : glm::vec4 (0.0f);
  930. for (int influence = 0; influence < 4; influence++) {
  931. const float weight = weights[influence];
  932. if (weight == 0.0f) {
  933. continue;
  934. }
  935. const uint32_t boneIndex = indices[influence];
  936. if (boneIndex >= skinMatrices.size ()) {
  937. continue;
  938. }
  939. skinned += weight * glm::vec3 (skinMatrices[boneIndex] * position);
  940. }
  941. return skinned;
  942. };
  943. // HLSL: a zero width range gives NaN, saturate makes it 0
  944. const auto smoothstep = [] (float edge0, float edge1, float x) {
  945. float t = (x - edge0) / (edge1 - edge0);
  946. t = std::isnan (t) ? 0.0f : std::clamp (t, 0.0f, 1.0f);
  947. return t * t * (3.0f - 2.0f * t);
  948. };
  949. const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
  950. std::vector<float> morphAlpha;
  951. if (this->m_puppetVertexAlpha && !targets.empty ()) {
  952. morphAlpha.assign (vertexCount, 1.0f);
  953. }
  954. this->m_puppetSkinnedPositions.assign (this->m_puppetRawPositions.size (), 0.0f);
  955. auto& prelight = this->m_puppetPrelight;
  956. const bool prelightMorphs = prelight.pass != nullptr && !targets.empty ();
  957. if (prelightMorphs) {
  958. prelight.morphedData = this->m_puppetRawPositions;
  959. } else {
  960. prelight.morphedData.clear ();
  961. }
  962. for (size_t v = 0; v < vertexCount; v++) {
  963. glm::vec4 bindPos (
  964. this->m_puppetRawPositions[v * 3], this->m_puppetRawPositions[v * 3 + 1],
  965. this->m_puppetRawPositions[v * 3 + 2], 1.0f
  966. );
  967. if (!targets.empty () && v < this->m_puppetMorphIndices.size () && this->m_puppetMorphIndices[v].has_value ()) {
  968. const auto& morph = *this->m_puppetMorph;
  969. glm::vec3 delta (0.0f);
  970. float alpha = 1.0f;
  971. // MORPHING_MODIFIERS: skinned unmorphed position in the rule bone's space scales each target
  972. const glm::vec4 preMorph = boneRules ? glm::vec4 (skin (v, bindPos), 1.0f) : glm::vec4 (0.0f);
  973. for (size_t i = 0; i < targets.size (); i++) {
  974. const auto target = targets[i].first;
  975. float weight = targets[i].second;
  976. const size_t texel = *this->m_puppetMorphIndices[v] + static_cast<size_t> (morph.vertexCount) * target;
  977. const glm::vec4 value = texel < morph.texels.size () ? morph.texels[texel] : glm::vec4 (0.0f);
  978. if (boneRules && rules[i] != nullptr) {
  979. const auto& rule = *rules[i];
  980. const glm::vec3 local (ruleInverse[i] * preMorph);
  981. const float point = smoothstep (rule.edge0, rule.edge1, glm::length (glm::vec2 (local)));
  982. const float axis = smoothstep (rule.edge0, rule.edge1, local.x);
  983. weight *= glm::mix (point, axis, rule.axis);
  984. }
  985. delta += glm::vec3 (value) * weight;
  986. alpha *= value.w * weight + (1.0f - weight);
  987. }
  988. bindPos += glm::vec4 (delta * morph.scale, 0.0f);
  989. if (prelightMorphs) {
  990. prelight.morphedData[v * 3] = bindPos.x;
  991. prelight.morphedData[v * 3 + 1] = bindPos.y;
  992. prelight.morphedData[v * 3 + 2] = bindPos.z;
  993. }
  994. if (!morphAlpha.empty ()) {
  995. morphAlpha[v] = alpha;
  996. }
  997. }
  998. const glm::vec3 skinned = skin (v, bindPos);
  999. this->m_puppetSkinnedPositions[v * 3] = skinned.x;
  1000. this->m_puppetSkinnedPositions[v * 3 + 1] = skinned.y;
  1001. this->m_puppetSkinnedPositions[v * 3 + 2] = skinned.z;
  1002. }
  1003. this->updatePuppetPositionBuffer (this->m_size);
  1004. if (this->m_puppetVertexAlpha) {
  1005. this->updatePuppetVertexAlpha (morphAlpha);
  1006. }
  1007. if (prelight.pass != nullptr) {
  1008. packPuppetBones (skinMatrices, prelight.bones);
  1009. if (prelightMorphs) {
  1010. glBindBuffer (GL_ARRAY_BUFFER, prelight.morphedPositions);
  1011. glBufferData (
  1012. GL_ARRAY_BUFFER, prelight.morphedData.size () * sizeof (GLfloat), prelight.morphedData.data (),
  1013. GL_DYNAMIC_DRAW
  1014. );
  1015. }
  1016. }
  1017. }
  1018. void CImage::updatePuppetVertexAlpha (const std::vector<float>& morphAlpha) {
  1019. // morph alpha * saturate (sum of bone alpha * weight), sub_140206430
  1020. const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
  1021. const auto& boneAlpha = this->m_rig.boneAlpha;
  1022. this->m_puppetVertexAlphaData.assign (vertexCount * 4, 0.0f);
  1023. for (size_t v = 0; v < vertexCount; v++) {
  1024. float alpha = v < morphAlpha.size () ? morphAlpha[v] : 1.0f;
  1025. if (this->m_puppetMeshFlags & 4) {
  1026. const glm::uvec4& indices
  1027. = v < this->m_puppetBlendIndices.size () ? this->m_puppetBlendIndices[v] : glm::uvec4 (0);
  1028. const glm::vec4& weights
  1029. = v < this->m_puppetBlendWeights.size () ? this->m_puppetBlendWeights[v] : glm::vec4 (0.0f);
  1030. float bones = 0.0f;
  1031. for (int influence = 0; influence < 4; influence++) {
  1032. if (indices[influence] < this->m_rig.bones.size ()) {
  1033. bones += (indices[influence] < boneAlpha.size () ? boneAlpha[indices[influence]] : 1.0f)
  1034. * weights[influence];
  1035. }
  1036. }
  1037. alpha *= std::clamp (bones, 0.0f, 1.0f);
  1038. }
  1039. this->m_puppetVertexAlphaData[v * 4] = alpha;
  1040. this->m_puppetVertexAlphaData[v * 4 + 1] = 1.0f - alpha;
  1041. }
  1042. if (this->m_puppetVertexAlphaWeights == GL_NONE) {
  1043. glGenBuffers (1, &this->m_puppetVertexAlphaWeights);
  1044. }
  1045. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetVertexAlphaWeights);
  1046. glBufferData (
  1047. GL_ARRAY_BUFFER, this->m_puppetVertexAlphaData.size () * sizeof (GLfloat),
  1048. this->m_puppetVertexAlphaData.data (), GL_DYNAMIC_DRAW
  1049. );
  1050. }
  1051. ComboMap CImage::puppetVertexAlphaCombos () const {
  1052. if (!this->m_puppetVertexAlpha) {
  1053. return {};
  1054. }
  1055. // sub_140209540; BONECOUNT at least 2 for the alpha trick below
  1056. return {
  1057. { "SKINNING", 1 },
  1058. { "BONECOUNT", std::max<int> (2, static_cast<int> (this->m_rig.bones.size ())) },
  1059. { "SKINNING_ALPHA", 1 },
  1060. };
  1061. }
  1062. glm::mat4 CImage::worldMatrix () const {
  1063. const glm::mat4 world = this->getScene ().objectWorldMatrix (this->getObject ());
  1064. const uint32_t alignment
  1065. = Data::Parsers::ObjectParser::parseAlignment (this->getImage ().alignmentName->value->getString ());
  1066. if (alignment == ImageAlignment_Center) {
  1067. return world;
  1068. }
  1069. // sub_1402066A0 takes half the object size (+752, truncated to int, 2x2 for fullscreen layers via
  1070. // sub_140209360), puppets included, in the layer's own scaled and rotated space
  1071. const glm::vec2 size = this->getImage ().model->fullscreen ? glm::vec2 (2.0f) : glm::trunc (this->m_displaySize);
  1072. glm::vec3 offset (0.0f);
  1073. if (alignment & ImageAlignment_Left) {
  1074. offset.x = size.x * 0.5f;
  1075. } else if (alignment & ImageAlignment_Right) {
  1076. offset.x = -size.x * 0.5f;
  1077. }
  1078. if (alignment & ImageAlignment_Top) {
  1079. offset.y = -size.y * 0.5f;
  1080. } else if (alignment & ImageAlignment_Bottom) {
  1081. offset.y = size.y * 0.5f;
  1082. }
  1083. return glm::translate (world, offset);
  1084. }
  1085. glm::mat4 CImage::puppetObjectWorld () const { return this->worldMatrix (); }
  1086. CImage::TextureAnimation* CImage::getTextureAnimation () {
  1087. if (!this->m_textureAnimation.has_value ()) {
  1088. if (this->m_texture == nullptr || !this->m_texture->isAnimated () || this->m_texture->getFrames ().empty ()) {
  1089. return nullptr;
  1090. }
  1091. this->m_textureAnimation = TextureAnimation {};
  1092. }
  1093. return &*this->m_textureAnimation;
  1094. }
  1095. std::pair<int, float> CImage::sharedTextureFrame () const {
  1096. if (this->m_texture == nullptr || !this->m_texture->isAnimated ()) {
  1097. return { 0, 0.0f };
  1098. }
  1099. // the same walk CPass::resolveTextureAnimationState does on the scene clock
  1100. const auto& frames = this->m_texture->getFrames ();
  1101. double time = fmod (static_cast<double> (g_Time), this->getAnimationTime ());
  1102. for (size_t i = 0; i < frames.size (); i++) {
  1103. if (time - frames[i]->frametime <= 0.0) {
  1104. return { static_cast<int> (i), static_cast<float> (time) };
  1105. }
  1106. time -= frames[i]->frametime;
  1107. }
  1108. return { 0, 0.0f };
  1109. }
  1110. int CImage::getTextureFrameCount () const {
  1111. return this->m_texture != nullptr && this->m_texture->isAnimated ()
  1112. ? static_cast<int> (this->m_texture->getFrames ().size ())
  1113. : 0;
  1114. }
  1115. float CImage::getTextureDuration () const {
  1116. return this->m_texture != nullptr && this->m_texture->isAnimated () ? static_cast<float> (this->getAnimationTime ())
  1117. : 0.0f;
  1118. }
  1119. void CImage::updateTextureAnimation (float frametime) {
  1120. // a scene drawn on several outputs updates its objects once per output
  1121. if (this->m_textureAnimationClock == g_Time) {
  1122. return;
  1123. }
  1124. this->m_textureAnimationClock = g_Time;
  1125. if (!this->m_textureAnimation.has_value () || !this->m_textureAnimation->detached
  1126. || !this->m_textureAnimation->playing || this->m_texture == nullptr || !this->m_texture->isAnimated ()) {
  1127. return;
  1128. }
  1129. // sub_14015FDD0: forwards wraps to the first frame, backwards to the last, the time stays inside the frame
  1130. auto& animation = *this->m_textureAnimation;
  1131. const auto& frames = this->m_texture->getFrames ();
  1132. const int count = static_cast<int> (frames.size ());
  1133. const float step = frametime * animation.rate;
  1134. const auto frameTime = [&frames, count] (int index) {
  1135. return static_cast<float> (frames[index >= 0 && index < count ? index : 0]->frametime);
  1136. };
  1137. if (count == 0 || step == 0.0f) {
  1138. return;
  1139. }
  1140. animation.time += step;
  1141. if (step > 0.0f) {
  1142. const float current = frameTime (animation.frame);
  1143. if (animation.time >= current) {
  1144. const float rest = animation.time - current;
  1145. // compared unsigned, a negative frame wraps to the first one too
  1146. animation.frame = animation.frame + 1 < 0 || animation.frame + 1 >= count ? 0 : animation.frame + 1;
  1147. animation.time = std::min (rest, frameTime (animation.frame));
  1148. }
  1149. } else if (animation.time <= 0.0f) {
  1150. animation.frame = animation.frame - 1 >= 0 ? animation.frame - 1 : count - 1;
  1151. animation.time = std::max (animation.time + frameTime (animation.frame), 0.0f);
  1152. }
  1153. }
  1154. std::optional<int> CImage::getTextureFrameOverride () const {
  1155. // a negative frame leaves the texture on its shared clock
  1156. if (!this->m_textureAnimation.has_value () || !this->m_textureAnimation->detached
  1157. || this->m_textureAnimation->frame < 0) {
  1158. return std::nullopt;
  1159. }
  1160. return this->m_textureAnimation->frame;
  1161. }
  1162. bool CImage::hasPuppetPose () const { return this->m_rig.hasPose (); }
  1163. int CImage::getBlendShapeIndex (const std::string& name) const {
  1164. if (!this->m_puppetMorph.has_value () || name.empty ()) {
  1165. return -1;
  1166. }
  1167. const auto& names = this->m_puppetMorph->names;
  1168. const auto it = std::ranges::find (names, name);
  1169. return it == names.end () ? -1 : static_cast<int> (it - names.begin ());
  1170. }
  1171. float CImage::getBlendShapeWeight (int target) const {
  1172. if (target < 0 || this->m_rig.morphWeights.empty ()) {
  1173. return 0.0f;
  1174. }
  1175. const auto& weights = this->m_rig.morphWeights.front ().weights;
  1176. return static_cast<size_t> (target) < weights.size () ? weights[target] : 0.0f;
  1177. }
  1178. void CImage::setBlendShapeWeight (int target, float weight) {
  1179. if (target < 0 || !this->m_puppetMorph.has_value ()
  1180. || static_cast<size_t> (target) >= this->m_puppetMorph->names.size ()) {
  1181. return;
  1182. }
  1183. if (this->m_rig.morphWeights.empty ()) {
  1184. this->m_rig.morphWeights.resize (1);
  1185. }
  1186. auto& state = this->m_rig.morphWeights.front ();
  1187. if (state.weights.size () <= static_cast<size_t> (target)) {
  1188. state.weights.resize (this->m_puppetMorph->names.size (), 0.0f);
  1189. }
  1190. state.weights[target] = weight;
  1191. // WE sign-extends the 32 bit (1 << target)
  1192. const auto bit = static_cast<uint64_t> (static_cast<int64_t> (static_cast<int32_t> (1u << (target & 31))));
  1193. if (std::abs (weight) >= 1.1920929e-7f) {
  1194. state.active |= bit;
  1195. } else {
  1196. state.active &= ~bit;
  1197. }
  1198. }
  1199. int CImage::findPuppetBone (const std::string& name) const { return this->m_rig.findBone (name); }
  1200. const glm::mat4& CImage::getPuppetBoneTransform (int bone) const { return this->m_rig.getBoneTransform (bone); }
  1201. void CImage::setPuppetBoneTransform (int bone, const glm::mat4& transform) {
  1202. this->m_rig.setBoneTransform (bone, transform, this->puppetObjectWorld ());
  1203. }
  1204. const glm::mat4& CImage::getPuppetLocalBoneTransform (int bone) const {
  1205. return this->m_rig.getLocalBoneTransform (bone);
  1206. }
  1207. void CImage::setPuppetLocalBoneTransform (int bone, const glm::mat4& transform) {
  1208. this->m_rig.setLocalBoneTransform (bone, transform, this->puppetObjectWorld ());
  1209. }
  1210. void CImage::applyPuppetBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees) {
  1211. this->m_rig.applyBonePhysicsImpulse (bone, directional, angularDegrees);
  1212. }
  1213. void CImage::resetPuppetBonePhysics (int bone) { this->m_rig.resetBonePhysics (bone); }
  1214. std::optional<glm::mat4> CImage::getAttachmentMatrix (const std::string& name) const {
  1215. return this->m_rig.attachmentMatrix (this->m_rig.findAttachment (name));
  1216. }
  1217. void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
  1218. pass->setGeometryCallback (
  1219. [this, pass] () {
  1220. const GLint position = glGetAttribLocation (pass->getProgramID (), "a_Position");
  1221. const GLint texCoord = glGetAttribLocation (pass->getProgramID (), "a_TexCoord");
  1222. if (!this->m_puppetDrawDiagnosticLogged) {
  1223. this->m_puppetDrawDiagnosticLogged = true;
  1224. sLog.out (
  1225. "Puppet draw setup for ", this->getImage ().name, " (", this->getId (),
  1226. "): programID=", pass->getProgramID (), " a_Position=", position, " a_TexCoord=", texCoord,
  1227. " indexCount=", this->m_puppetIndexCount, " size=", this->m_size.x, "x", this->m_size.y
  1228. );
  1229. }
  1230. if (position >= 0) {
  1231. glEnableVertexAttribArray (position);
  1232. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
  1233. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  1234. }
  1235. if (texCoord >= 0) {
  1236. glEnableVertexAttribArray (texCoord);
  1237. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
  1238. glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
  1239. }
  1240. // skinning is on the CPU; two identity bones with alpha 1 and 0, weighted (alpha, 1 - alpha), carry the
  1241. // vertex alpha through SKINNING_ALPHA
  1242. if (this->m_puppetVertexAlpha && this->m_puppetVertexAlphaWeights != GL_NONE) {
  1243. const GLuint program = pass->getProgramID ();
  1244. const GLint blendWeights = glGetAttribLocation (program, "a_BlendWeights");
  1245. const GLint blendIndices = glGetAttribLocation (program, "a_BlendIndices");
  1246. const GLint normal = glGetAttribLocation (program, "a_Normal");
  1247. const GLint tangent = glGetAttribLocation (program, "a_Tangent4");
  1248. if (blendWeights >= 0) {
  1249. glEnableVertexAttribArray (blendWeights);
  1250. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetVertexAlphaWeights);
  1251. glVertexAttribPointer (blendWeights, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
  1252. }
  1253. if (blendIndices >= 0) {
  1254. glDisableVertexAttribArray (blendIndices);
  1255. glVertexAttribI4ui (blendIndices, 0, 1, 0, 0);
  1256. }
  1257. if (normal >= 0) {
  1258. glDisableVertexAttribArray (normal);
  1259. glVertexAttrib3f (normal, 0.0f, 0.0f, 1.0f);
  1260. }
  1261. if (tangent >= 0) {
  1262. glDisableVertexAttribArray (tangent);
  1263. glVertexAttrib4f (tangent, 1.0f, 0.0f, 0.0f, 1.0f);
  1264. }
  1265. constexpr GLfloat bones[24]
  1266. = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
  1267. 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f };
  1268. constexpr GLfloat bonesAlpha[2] = { 1.0f, 0.0f };
  1269. if (const GLint location = glGetUniformLocation (program, "g_Bones"); location >= 0) {
  1270. glUniformMatrix4x3fv (location, 2, GL_FALSE, bones);
  1271. }
  1272. if (const GLint location = glGetUniformLocation (program, "g_BonesAlpha"); location >= 0) {
  1273. glUniform1fv (location, 2, bonesAlpha);
  1274. }
  1275. }
  1276. // the y flip reverses winding, not even uniformly since puppet meshes aren't consistently wound; flat 2D
  1277. // art, so never cull
  1278. glDisable (GL_CULL_FACE);
  1279. },
  1280. [this, pass] () {
  1281. // a mesh pass into the layer's own buffer starts it fresh, one meant for the scene may be going into a
  1282. // passthrough layer's buffer right now, which holds its other children
  1283. if (pass == this->m_puppetMeshPass && !this->m_puppetDrawKeep
  1284. && pass->getDestination () != this->getScene ().getFBO ()) {
  1285. GLfloat previousClearColor[4] = {};
  1286. glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
  1287. glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
  1288. glClear (GL_COLOR_BUFFER_BIT);
  1289. glClearColor (
  1290. previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]
  1291. );
  1292. }
  1293. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetDrawBuffer);
  1294. glDrawElements (
  1295. GL_TRIANGLES, this->m_puppetDrawCount, GL_UNSIGNED_SHORT,
  1296. reinterpret_cast<const void*> (static_cast<uintptr_t> (this->m_puppetDrawOffset) * sizeof (GLushort))
  1297. );
  1298. if (!this->m_puppetDrawErrorChecked) {
  1299. this->m_puppetDrawErrorChecked = true;
  1300. GLint boundFBO = 0;
  1301. GLint viewport[4] = {};
  1302. GLint boundTexture = 0;
  1303. glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &boundFBO);
  1304. glGetIntegerv (GL_VIEWPORT, viewport);
  1305. glActiveTexture (GL_TEXTURE0);
  1306. glGetIntegerv (GL_TEXTURE_BINDING_2D, &boundTexture);
  1307. const GLenum err = glGetError ();
  1308. const GLboolean cullEnabled = glIsEnabled (GL_CULL_FACE);
  1309. const GLboolean depthEnabled = glIsEnabled (GL_DEPTH_TEST);
  1310. const GLboolean scissorEnabled = glIsEnabled (GL_SCISSOR_TEST);
  1311. const GLboolean blendEnabled = glIsEnabled (GL_BLEND);
  1312. GLint cullFaceMode = 0, frontFace = 0;
  1313. glGetIntegerv (GL_CULL_FACE_MODE, &cullFaceMode);
  1314. glGetIntegerv (GL_FRONT_FACE, &frontFace);
  1315. GLboolean colorMask[4] = {};
  1316. glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
  1317. sLog.out (
  1318. "Puppet draw result for ", this->getImage ().name, " (", this->getId (), "): glError=", err,
  1319. " boundFBO=", boundFBO, " sceneFBO=", this->getScene ().getFBO ()->getFramebuffer (), " viewport=(",
  1320. viewport[0], ",", viewport[1], ",", viewport[2], ",", viewport[3], ") boundTexture=", boundTexture,
  1321. " ownTextureReady=", (this->getTexture () != nullptr && this->getTexture ()->isReady ()),
  1322. " ownTextureID=", (this->getTexture () != nullptr ? this->getTexture ()->getTextureID (0) : 0),
  1323. " color4=(", this->getColor4 ().r, ",", this->getColor4 ().g, ",", this->getColor4 ().b, ",",
  1324. this->getColor4 ().a, ") alpha=", this->getUserAlpha (), " brightness=", this->getBrightness (),
  1325. " cullEnabled=", (int)cullEnabled, " cullFaceMode=", cullFaceMode, " frontFace=", frontFace,
  1326. " depthEnabled=", (int)depthEnabled, " scissorEnabled=", (int)scissorEnabled,
  1327. " blendEnabled=", (int)blendEnabled, " colorMask=(", (int)colorMask[0], ",", (int)colorMask[1], ",",
  1328. (int)colorMask[2], ",", (int)colorMask[3], ")"
  1329. );
  1330. }
  1331. },
  1332. [pass] () {
  1333. for (const char* name : { "a_Position", "a_TexCoord", "a_BlendWeights" }) {
  1334. if (const GLint location = glGetAttribLocation (pass->getProgramID (), name); location >= 0) {
  1335. glDisableVertexAttribArray (location);
  1336. }
  1337. }
  1338. }
  1339. );
  1340. }
  1341. bool CImage::litDrawsDirect () const {
  1342. return this->hasLitMaterial () && !this->getImage ().shape && this->m_passes.size () == 1
  1343. && this->m_passes.front () == this->m_allPasses.front () && this->m_passesDrawToScreen
  1344. && this->m_blendMap.pass == nullptr && this->m_puppetPrelight.pass == nullptr
  1345. && this->m_puppetClipTargetPass == nullptr;
  1346. }
  1347. void CImage::setupDirectLitPass () {
  1348. if (!this->litDrawsDirect ()) {
  1349. return;
  1350. }
  1351. auto* base = this->m_allPasses.front ();
  1352. const bool meshPass = base == this->m_puppetMeshPass;
  1353. ComboMap combos;
  1354. if (meshPass && this->m_materials.puppetVertexAlpha != nullptr) {
  1355. combos = this->m_materials.puppetVertexAlpha->combos;
  1356. }
  1357. combos.insert_or_assign ("PRELIGHTING", 0);
  1358. this->m_materials.directLit = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1359. .id = -1,
  1360. .combos = std::move (combos),
  1361. .constants = {},
  1362. .textures = {},
  1363. });
  1364. auto* pass = new CPass (
  1365. *this, std::make_shared<FBOProvider> (this), base->getPass (), *this->m_materials.directLit, std::nullopt,
  1366. std::nullopt
  1367. );
  1368. pass->addUniform ("g_NormalModelMatrix", &this->m_lightingNormal);
  1369. delete base;
  1370. this->m_allPasses.front () = pass;
  1371. this->m_directLitPass = pass;
  1372. if (meshPass) {
  1373. this->m_puppetMeshPass = pass;
  1374. }
  1375. this->rebuildActivePasses ();
  1376. }
  1377. // sub_140209540: lit layers drawn again later get a PRELIGHTING/SKINNING/MORPHING draw into the layer buffer, placed by
  1378. // a_PositionC1 (sub_140207B50); morphs on the CPU
  1379. void CImage::setupPuppetPrelight () {
  1380. this->m_puppetPrelight.pass = nullptr;
  1381. if (!this->m_hasPuppetMesh || this->m_passes.empty () || this->m_puppetMeshPass == this->m_passes.front ()
  1382. || !this->hasLitMaterial () || this->m_rig.bones.empty () || this->m_puppetBlendIndices.empty ()
  1383. || this->getImage ().model->passthrough) {
  1384. return;
  1385. }
  1386. this->m_materials.puppetPrelight = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1387. .id = -1,
  1388. .combos = {
  1389. { "SKINNING", 1 },
  1390. { "BONECOUNT", static_cast<int> (this->m_rig.bones.size ()) },
  1391. { "PRELIGHTINGDUALVERTEX", 1 },
  1392. },
  1393. .constants = {},
  1394. .textures = {},
  1395. });
  1396. auto* pass = new CPass (
  1397. *this, std::make_shared<FBOProvider> (this), this->m_passes.front ()->getPass (),
  1398. *this->m_materials.puppetPrelight, std::nullopt, std::nullopt
  1399. );
  1400. delete this->m_passes.front ();
  1401. this->m_passes.front () = pass;
  1402. this->m_puppetPrelight.pass = pass;
  1403. packPuppetBones (
  1404. std::vector<glm::mat4> (this->m_rig.bones.size (), glm::mat4 (1.0f)), this->m_puppetPrelight.bones
  1405. );
  1406. this->uploadPuppetPrelightBuffers ();
  1407. pass->setGeometryCallback (
  1408. [this, pass] () {
  1409. const auto& prelight = this->m_puppetPrelight;
  1410. const GLuint program = pass->getProgramID ();
  1411. const GLint flat = glGetAttribLocation (program, "a_PositionC1");
  1412. const auto bind = [program] (const char* name, GLuint buffer, GLint size) {
  1413. const GLint location = glGetAttribLocation (program, name);
  1414. if (location >= 0) {
  1415. glEnableVertexAttribArray (location);
  1416. glBindBuffer (GL_ARRAY_BUFFER, buffer);
  1417. glVertexAttribPointer (location, size, GL_FLOAT, GL_FALSE, 0, nullptr);
  1418. }
  1419. };
  1420. bind (
  1421. "a_Position",
  1422. flat >= 0 && !prelight.morphedData.empty () ? prelight.morphedPositions : prelight.bindPositions, 3
  1423. );
  1424. bind ("a_PositionC1", prelight.flatPositions, 3);
  1425. bind ("a_TexCoord", this->m_puppetTexCoord, 2);
  1426. bind ("a_BlendWeights", prelight.blendWeights, 4);
  1427. if (const GLint location = glGetAttribLocation (program, "a_BlendIndices"); location >= 0) {
  1428. glEnableVertexAttribArray (location);
  1429. glBindBuffer (GL_ARRAY_BUFFER, prelight.blendIndices);
  1430. glVertexAttribIPointer (location, 4, GL_UNSIGNED_INT, 0, nullptr);
  1431. }
  1432. if (const GLint location = glGetAttribLocation (program, "a_Normal"); location >= 0) {
  1433. if (prelight.normals != GL_NONE) {
  1434. bind ("a_Normal", prelight.normals, 3);
  1435. } else {
  1436. glDisableVertexAttribArray (location);
  1437. glVertexAttrib3f (location, 0.0f, 0.0f, 1.0f);
  1438. }
  1439. }
  1440. if (const GLint location = glGetAttribLocation (program, "a_Tangent4"); location >= 0) {
  1441. if (prelight.tangents != GL_NONE) {
  1442. bind ("a_Tangent4", prelight.tangents, 4);
  1443. } else {
  1444. glDisableVertexAttribArray (location);
  1445. glVertexAttrib4f (location, 1.0f, 0.0f, 0.0f, 1.0f);
  1446. }
  1447. }
  1448. if (const GLint location = glGetUniformLocation (program, "g_Bones"); location >= 0) {
  1449. glUniformMatrix4x3fv (
  1450. location, static_cast<GLsizei> (prelight.bones.size () / 12), GL_FALSE, prelight.bones.data ()
  1451. );
  1452. }
  1453. glDisable (GL_CULL_FACE);
  1454. },
  1455. [this] () {
  1456. GLfloat previousClearColor[4] = {};
  1457. glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
  1458. glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
  1459. glClear (GL_COLOR_BUFFER_BIT);
  1460. glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
  1461. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
  1462. glDrawElements (GL_TRIANGLES, this->m_puppetIndexCount, GL_UNSIGNED_SHORT, nullptr);
  1463. },
  1464. [pass] () {
  1465. for (const char* name : { "a_Position", "a_PositionC1", "a_TexCoord", "a_BlendWeights", "a_BlendIndices",
  1466. "a_Normal", "a_Tangent4" }) {
  1467. if (const GLint location = glGetAttribLocation (pass->getProgramID (), name); location >= 0) {
  1468. glDisableVertexAttribArray (location);
  1469. }
  1470. }
  1471. }
  1472. );
  1473. }
  1474. void CImage::uploadPuppetPrelightBuffers () {
  1475. auto& prelight = this->m_puppetPrelight;
  1476. const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
  1477. const auto upload = [] (GLuint& buffer, const void* data, size_t bytes, GLenum usage) {
  1478. if (buffer == GL_NONE) {
  1479. glGenBuffers (1, &buffer);
  1480. }
  1481. glBindBuffer (GL_ARRAY_BUFFER, buffer);
  1482. glBufferData (GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (bytes), data, usage);
  1483. };
  1484. const auto& raw = this->m_puppetRawPositions;
  1485. const auto& flat = prelight.auxPositions.size () == raw.size () ? prelight.auxPositions : raw;
  1486. upload (prelight.bindPositions, raw.data (), raw.size () * sizeof (GLfloat), GL_STATIC_DRAW);
  1487. upload (prelight.morphedPositions, raw.data (), raw.size () * sizeof (GLfloat), GL_DYNAMIC_DRAW);
  1488. upload (prelight.flatPositions, flat.data (), flat.size () * sizeof (GLfloat), GL_STATIC_DRAW);
  1489. if (prelight.normalData.size () == vertexCount * 3) {
  1490. upload (
  1491. prelight.normals, prelight.normalData.data (), prelight.normalData.size () * sizeof (GLfloat),
  1492. GL_STATIC_DRAW
  1493. );
  1494. }
  1495. if (prelight.tangentData.size () == vertexCount * 4) {
  1496. upload (
  1497. prelight.tangents, prelight.tangentData.data (), prelight.tangentData.size () * sizeof (GLfloat),
  1498. GL_STATIC_DRAW
  1499. );
  1500. }
  1501. std::vector<glm::uvec4> indices (vertexCount, glm::uvec4 (0));
  1502. std::vector<glm::vec4> weights (vertexCount, glm::vec4 (0.0f));
  1503. std::copy_n (
  1504. this->m_puppetBlendIndices.begin (), std::min (vertexCount, this->m_puppetBlendIndices.size ()),
  1505. indices.begin ()
  1506. );
  1507. std::copy_n (
  1508. this->m_puppetBlendWeights.begin (), std::min (vertexCount, this->m_puppetBlendWeights.size ()),
  1509. weights.begin ()
  1510. );
  1511. upload (prelight.blendIndices, indices.data (), indices.size () * sizeof (glm::uvec4), GL_STATIC_DRAW);
  1512. upload (prelight.blendWeights, weights.data (), weights.size () * sizeof (glm::vec4), GL_STATIC_DRAW);
  1513. }
  1514. // sub_140209540 / sub_140206AE0: a puppet with clipping records gets clippingmaskimage4 for its masks and its own
  1515. // material again with CLIPPINGUVS and CLIPPINGTARGET for what they clip
  1516. void CImage::setupPuppetClipping () {
  1517. if (!this->m_puppetClipping.has_value () || this->m_puppetMeshPass == nullptr) {
  1518. return;
  1519. }
  1520. const auto& project = this->getScene ().getScene ().project;
  1521. const auto& records = this->m_puppetClipping->records;
  1522. auto& overrides = this->m_materials.clippingOverrides;
  1523. const auto fboProvider = std::make_shared<FBOProvider> (this);
  1524. // the mesh pass's combos, sub_140209540 adds the clipping ones
  1525. overrides.push_back (
  1526. std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1527. .id = -1,
  1528. .combos = this->m_materials.puppetVertexAlpha != nullptr ? this->m_materials.puppetVertexAlpha->combos
  1529. : this->puppetVertexAlphaCombos (),
  1530. .constants = {},
  1531. .textures = {},
  1532. })
  1533. );
  1534. overrides.back ()->combos.insert_or_assign ("CLIPPINGUVS", 1);
  1535. overrides.back ()->combos.insert_or_assign ("CLIPPINGTARGET", 1);
  1536. this->m_puppetClipTargetPass = new CPass (
  1537. *this, fboProvider, this->m_puppetMeshPass->getPass (), *overrides.back (), std::nullopt, std::nullopt
  1538. );
  1539. this->m_puppetClipTargetPass->setTexture (8, this->getScene ().requireAlphaMaskFrameBuffer (false));
  1540. this->setupPuppetGeometryCallback (this->m_puppetClipTargetPass);
  1541. ComboMap maskCombos = this->puppetVertexAlphaCombos ();
  1542. const auto& imagePasses = this->getImage ().model->material->passes;
  1543. if (!imagePasses.empty () && imagePasses.front ()->blending == BlendingMode_AlphaToCoverage) {
  1544. maskCombos.emplace ("ALPHATOCOVERAGE", 1);
  1545. }
  1546. this->m_materials.clippingMask = MaterialParser::load (project, "materials/util/clippingmaskimage4.json");
  1547. for (const auto& record : records) {
  1548. overrides.push_back (
  1549. std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1550. .id = -1,
  1551. .combos = maskCombos,
  1552. .constants = {},
  1553. .textures = { { 1, record.mask } },
  1554. })
  1555. );
  1556. auto* pass = new CPass (
  1557. *this, fboProvider, **this->m_materials.clippingMask->passes.begin (), *overrides.back (), std::nullopt,
  1558. std::nullopt
  1559. );
  1560. pass->addUniform ("g_RenderVar0", &this->m_puppetClipRenderVar0);
  1561. pass->setClearColor (&this->m_puppetClipClearColor);
  1562. this->setupPuppetGeometryCallback (pass);
  1563. this->m_puppetClipMaskPasses.push_back (pass);
  1564. }
  1565. if (std::ranges::none_of (records, [] (const PuppetClipping::Record& record) { return record.parent != -1; })) {
  1566. return;
  1567. }
  1568. // nested masks: the intermediate goes through flattexture onto _rt_FullAlphaMask with identity matrices
  1569. constexpr GLfloat positions[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f };
  1570. constexpr GLfloat texcoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f };
  1571. glGenBuffers (1, &this->m_puppetClipComposePosition);
  1572. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposePosition);
  1573. glBufferData (GL_ARRAY_BUFFER, sizeof (positions), positions, GL_STATIC_DRAW);
  1574. glGenBuffers (1, &this->m_puppetClipComposeTexCoord);
  1575. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposeTexCoord);
  1576. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoords), texcoords, GL_STATIC_DRAW);
  1577. this->m_materials.clippingCompose = MaterialParser::load (project, "materials/util/flattexture.json");
  1578. auto* compose = new CPass (
  1579. *this, fboProvider, **this->m_materials.clippingCompose->passes.begin (), std::nullopt, std::nullopt,
  1580. std::nullopt
  1581. );
  1582. compose->setDestination (this->getScene ().requireAlphaMaskFrameBuffer (false));
  1583. compose->setInput (this->getScene ().requireAlphaMaskFrameBuffer (true));
  1584. compose->setKeepDestination (true);
  1585. compose->setModelViewProjectionMatrix (&this->m_puppetClipIdentity);
  1586. compose->setModelViewProjectionMatrixInverse (&this->m_puppetClipIdentity);
  1587. compose->setModelMatrix (&this->m_puppetClipIdentity);
  1588. compose->setViewProjectionMatrix (&this->m_puppetClipIdentity);
  1589. static const glm::mat3 identityNormal (1.0f);
  1590. compose->setLightingTransform (&this->m_puppetClipIdentity, &identityNormal, &this->m_puppetClipIdentity);
  1591. compose->setEffectTextureProjectionMatrix (&this->m_puppetClipIdentity, &this->m_puppetClipIdentity);
  1592. // sub_14020D6A0 sets the renderer alpha to 1 for it
  1593. compose->addUniform ("g_Alpha", &this->m_puppetClipComposeAlpha);
  1594. compose->setGeometryCallback (
  1595. [this, compose] () {
  1596. const GLint position = glGetAttribLocation (compose->getProgramID (), "a_Position");
  1597. const GLint texCoord = glGetAttribLocation (compose->getProgramID (), "a_TexCoord");
  1598. if (position >= 0) {
  1599. glEnableVertexAttribArray (position);
  1600. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposePosition);
  1601. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  1602. }
  1603. if (texCoord >= 0) {
  1604. glEnableVertexAttribArray (texCoord);
  1605. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposeTexCoord);
  1606. glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
  1607. }
  1608. },
  1609. [] () {
  1610. // translucent with renderer flag 0x100 (sub_140099F60): the source color becomes DEST_COLOR, alpha ONE/ONE,
  1611. // rgb written only, so the intermediate multiplies into the mask
  1612. GLboolean colorMask[4] = {};
  1613. glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
  1614. glEnable (GL_BLEND);
  1615. glBlendFuncSeparate (GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
  1616. glColorMask (true, true, true, false);
  1617. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  1618. glColorMask (colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  1619. },
  1620. [compose] () {
  1621. for (const char* name : { "a_Position", "a_TexCoord" }) {
  1622. const GLint location = glGetAttribLocation (compose->getProgramID (), name);
  1623. if (location >= 0) {
  1624. glDisableVertexAttribArray (location);
  1625. }
  1626. }
  1627. }
  1628. );
  1629. this->m_puppetClipComposePass = compose;
  1630. }
  1631. void CImage::loadPuppetBlendMesh (const std::vector<char>& data) {
  1632. std::optional<PuppetBlendMesh> mesh;
  1633. try {
  1634. mesh = readPuppetBlendMesh (data);
  1635. } catch (const std::exception& ex) {
  1636. sLog.error ("Could not read the blend map mesh of ", *this->getImage ().model->puppet, ": ", ex.what ());
  1637. return;
  1638. }
  1639. if (!mesh.has_value ()) {
  1640. return;
  1641. }
  1642. const uint32_t stride = CMesh::vertexStride (mesh->format);
  1643. if (stride == 0 || mesh->vertexBytes % stride != 0 || mesh->material.empty ()
  1644. || !CMesh::vertexComponentOffset (mesh->format, 0x1).has_value ()) {
  1645. sLog.error (
  1646. "Ignoring the blend map mesh of ", *this->getImage ().model->puppet, ": vertex format ", mesh->format,
  1647. " doesn't match its data"
  1648. );
  1649. return;
  1650. }
  1651. glGenBuffers (1, &this->m_blendMap.vertices);
  1652. glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.vertices);
  1653. glBufferData (GL_ARRAY_BUFFER, mesh->vertexBytes, data.data () + mesh->vertices, GL_STATIC_DRAW);
  1654. glGenBuffers (1, &this->m_blendMap.indices);
  1655. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_blendMap.indices);
  1656. glBufferData (GL_ELEMENT_ARRAY_BUFFER, mesh->indexBytes, data.data () + mesh->indices, GL_STATIC_DRAW);
  1657. this->m_blendMap.indexCount = static_cast<GLsizei> (mesh->indexBytes / sizeof (GLushort));
  1658. this->m_blendMap.format = mesh->format;
  1659. this->m_blendMap.stride = stride;
  1660. // g_BlendMap rows from puppet +848
  1661. this->m_blendMap.rows = std::min<uint32_t> (mesh->rows, this->m_rig.blendMap.size () / 4);
  1662. this->m_blendMap.material = mesh->material;
  1663. }
  1664. // pass flags 0x10 LIGHTING / 0x8 REFLECTION (sub_140209540)
  1665. bool CImage::hasLitMaterial () const {
  1666. const auto& materialPasses = this->getImage ().model->material->passes;
  1667. if (materialPasses.empty ()) {
  1668. return false;
  1669. }
  1670. const auto& combos = materialPasses.front ()->combos;
  1671. const auto enabled = [&combos] (const char* name) {
  1672. const auto combo = combos.find (name);
  1673. return combo != combos.end () && combo->second != 0;
  1674. };
  1675. return enabled ("LIGHTING") || enabled ("REFLECTION");
  1676. }
  1677. // sub_140209540: lit materials draw texture + flag 2 mesh into _rt_imageLayerAlbedo_<id>, else an offscreen layer's
  1678. // base draw (sub_140207B50) puts the mesh over the texture. Never for layers drawn straight to the scene
  1679. void CImage::setupPuppetBlendMap (bool offscreen) {
  1680. if (this->m_blendMap.indexCount == 0 || this->m_passes.empty () || this->m_texture == nullptr) {
  1681. return;
  1682. }
  1683. if (!this->hasLitMaterial () && !offscreen) {
  1684. return;
  1685. }
  1686. const auto& project = this->getScene ().getScene ().project;
  1687. const auto fboProvider = std::make_shared<FBOProvider> (this);
  1688. const auto& texture = this->m_texture;
  1689. try {
  1690. this->m_materials.blendMap = MaterialParser::load (project, this->m_blendMap.material);
  1691. } catch (const std::exception& ex) {
  1692. sLog.error ("Cannot load the blend map material ", this->m_blendMap.material, ": ", ex.what ());
  1693. return;
  1694. }
  1695. if (this->m_materials.blendMap->passes.empty ()) {
  1696. return;
  1697. }
  1698. this->m_blendMap.albedo = std::make_shared<CFBO> (
  1699. "_rt_imageLayerAlbedo_" + std::to_string (this->getId ()), TextureFormat_ARGB8888, texture->getFlags (), 1.0f,
  1700. texture->getRealWidth (), texture->getRealHeight (), texture->getTextureWidth (0), texture->getTextureHeight (0)
  1701. );
  1702. const glm::vec2 albedoSize (texture->getTextureWidth (0), texture->getTextureHeight (0));
  1703. // mesh is in texture pixels, y up
  1704. this->m_blendMap.projection = DepthRange::toClip (glm::ortho (0.0f, albedoSize.x, albedoSize.y, 0.0f, -1.0f, 1.0f));
  1705. constexpr GLfloat quad[] = { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
  1706. -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f };
  1707. glGenBuffers (1, &this->m_blendMap.quad);
  1708. glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.quad);
  1709. glBufferData (GL_ARRAY_BUFFER, sizeof (quad), quad, GL_STATIC_DRAW);
  1710. const auto setMatrices = [this] (Effects::CPass* pass, const glm::mat4* projection) {
  1711. static const glm::mat3 identityNormal (1.0f);
  1712. pass->setModelViewProjectionMatrix (projection);
  1713. pass->setModelViewProjectionMatrixInverse (&this->m_puppetClipIdentity);
  1714. pass->setModelMatrix (&this->m_puppetClipIdentity);
  1715. pass->setViewProjectionMatrix (&this->m_puppetClipIdentity);
  1716. pass->setLightingTransform (&this->m_puppetClipIdentity, &identityNormal, &this->m_puppetClipIdentity);
  1717. pass->setEffectTextureProjectionMatrix (&this->m_puppetClipIdentity, &this->m_puppetClipIdentity);
  1718. };
  1719. // fullscreenlayer.json copy, normal blending
  1720. ComboMap copyCombos;
  1721. if (texture->isAnimated ()) {
  1722. copyCombos.emplace ("SPRITESHEET", 1);
  1723. }
  1724. const auto& copyConfig = *this->m_virtualPassess.emplace_back (
  1725. std::make_unique<MaterialPass> (MaterialPass {
  1726. .blending = BlendingMode_Normal,
  1727. .cullmode = CullingMode_Disable,
  1728. .depthtest = DepthtestMode_Disabled,
  1729. .depthwrite = DepthwriteMode_Disabled,
  1730. .shader = "passthrough",
  1731. .textures = {},
  1732. .usertextures = {},
  1733. .combos = copyCombos,
  1734. .constants = {},
  1735. })
  1736. );
  1737. auto* copy = new CPass (*this, fboProvider, copyConfig, std::nullopt, std::nullopt, std::nullopt);
  1738. copy->setInput (texture);
  1739. copy->setDestination (this->m_blendMap.albedo);
  1740. setMatrices (copy, &this->m_puppetClipIdentity);
  1741. copy->setGeometryCallback (
  1742. [this, copy] () {
  1743. const GLint position = glGetAttribLocation (copy->getProgramID (), "a_Position");
  1744. const GLint texCoord = glGetAttribLocation (copy->getProgramID (), "a_TexCoord");
  1745. glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.quad);
  1746. if (position >= 0) {
  1747. glEnableVertexAttribArray (position);
  1748. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, sizeof (GLfloat) * 5, nullptr);
  1749. }
  1750. if (texCoord >= 0) {
  1751. glEnableVertexAttribArray (texCoord);
  1752. glVertexAttribPointer (
  1753. texCoord, 2, GL_FLOAT, GL_FALSE, sizeof (GLfloat) * 5,
  1754. reinterpret_cast<const void*> (sizeof (GLfloat) * 3)
  1755. );
  1756. }
  1757. },
  1758. [] () { glDrawArrays (GL_TRIANGLE_STRIP, 0, 4); },
  1759. [copy] () {
  1760. for (const char* name : { "a_Position", "a_TexCoord" }) {
  1761. if (const GLint location = glGetAttribLocation (copy->getProgramID (), name); location >= 0) {
  1762. glDisableVertexAttribArray (location);
  1763. }
  1764. }
  1765. }
  1766. );
  1767. this->m_blendMap.copyPass = copy;
  1768. this->m_materials.blendMapOverride = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1769. .id = -1,
  1770. .combos = { { "BLENDROWCOUNT", static_cast<int> (this->m_blendMap.rows) } },
  1771. .constants = {},
  1772. .textures = {},
  1773. });
  1774. auto* pass = new CPass (
  1775. *this, fboProvider, **this->m_materials.blendMap->passes.begin (), *this->m_materials.blendMapOverride,
  1776. std::nullopt, std::nullopt
  1777. );
  1778. pass->setInput (texture);
  1779. pass->setDestination (this->m_blendMap.albedo);
  1780. pass->setKeepDestination (true);
  1781. setMatrices (pass, &this->m_blendMap.projection);
  1782. pass->setGeometryCallback (
  1783. [this, pass] () {
  1784. const GLuint program = pass->getProgramID ();
  1785. const auto stride = static_cast<GLsizei> (this->m_blendMap.stride);
  1786. const auto attribute = [&] (const char* name, uint32_t bit, GLint size, bool integer) {
  1787. const GLint location = glGetAttribLocation (program, name);
  1788. const auto offset = CMesh::vertexComponentOffset (this->m_blendMap.format, bit);
  1789. if (location < 0) {
  1790. return;
  1791. }
  1792. if (!offset.has_value ()) {
  1793. glDisableVertexAttribArray (location);
  1794. return;
  1795. }
  1796. const auto* pointer = reinterpret_cast<const void*> (static_cast<uintptr_t> (*offset));
  1797. glEnableVertexAttribArray (location);
  1798. if (integer) {
  1799. glVertexAttribIPointer (location, size, GL_UNSIGNED_INT, stride, pointer);
  1800. } else {
  1801. glVertexAttribPointer (location, size, GL_FLOAT, GL_FALSE, stride, pointer);
  1802. }
  1803. };
  1804. glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.vertices);
  1805. attribute ("a_Position", 0x1, 3, false);
  1806. attribute ("a_BlendIndices", 0x800000, 4, true);
  1807. attribute ("a_TexCoordVec4", 0x20, 4, false);
  1808. if (const GLint location = glGetUniformLocation (program, "g_BlendMap");
  1809. location >= 0 && this->m_blendMap.rows > 0) {
  1810. glUniform4fv (location, static_cast<GLsizei> (this->m_blendMap.rows), this->m_rig.blendMap.data ());
  1811. }
  1812. },
  1813. [this] () {
  1814. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_blendMap.indices);
  1815. glDrawElements (GL_TRIANGLES, this->m_blendMap.indexCount, GL_UNSIGNED_SHORT, nullptr);
  1816. },
  1817. [pass] () {
  1818. for (const char* name : { "a_Position", "a_BlendIndices", "a_TexCoordVec4" }) {
  1819. if (const GLint location = glGetAttribLocation (pass->getProgramID (), name); location >= 0) {
  1820. glDisableVertexAttribArray (location);
  1821. }
  1822. }
  1823. }
  1824. );
  1825. this->m_blendMap.pass = pass;
  1826. this->m_passes.front ()->setTexture (0, this->m_blendMap.albedo);
  1827. if (this->m_puppetClipTargetPass != nullptr && this->m_puppetMeshPass == this->m_passes.front ()) {
  1828. this->m_puppetClipTargetPass->setTexture (0, this->m_blendMap.albedo);
  1829. }
  1830. }
  1831. void CImage::selectPuppetDraw (const int draw) {
  1832. if (draw < 0 || !this->m_puppetClipping.has_value ()
  1833. || static_cast<size_t> (draw) >= this->m_puppetClipping->draws.size ()) {
  1834. this->m_puppetDrawBuffer = this->m_puppetIndices;
  1835. this->m_puppetDrawOffset = 0;
  1836. this->m_puppetDrawCount = draw < 0 ? this->m_puppetIndexCount : 0;
  1837. return;
  1838. }
  1839. const auto& range = this->m_puppetClipping->draws[draw];
  1840. this->m_puppetDrawBuffer = this->m_puppetClipIndices;
  1841. this->m_puppetDrawOffset = static_cast<GLsizei> (range.offset);
  1842. this->m_puppetDrawCount = static_cast<GLsizei> (range.count);
  1843. }
  1844. void CImage::renderPuppetClipMask (
  1845. const Effects::CPass& meshPass, const int record, const int draw, const bool clear, const bool intermediate
  1846. ) {
  1847. auto& scene = this->getScene ();
  1848. auto* pass = this->m_puppetClipMaskPasses[record];
  1849. const bool inverted = this->m_puppetClipping->records[record].flags & PuppetClipping::Inverted;
  1850. pass->copyBindings (meshPass);
  1851. pass->setDestination (scene.requireAlphaMaskFrameBuffer (intermediate));
  1852. // a mesh going onto the scene may be drawn into a passthrough layer, the mask has to be laid out the same way
  1853. pass->setFollowLayerTarget (meshPass.getDestination () == scene.getFBO ());
  1854. pass->setKeepDestination (!clear && !intermediate);
  1855. this->m_puppetClipClearColor = glm::vec4 (inverted ? 1.0f : 0.0f);
  1856. this->m_puppetClipRenderVar0.x = inverted ? 1.0f : 0.0f;
  1857. this->selectPuppetDraw (draw);
  1858. pass->render ();
  1859. if (intermediate && this->m_puppetClipComposePass != nullptr) {
  1860. this->m_puppetClipComposePass->render ();
  1861. }
  1862. }
  1863. void CImage::renderPuppetClipped (Effects::CPass* meshPass) {
  1864. const auto& commands = this->m_puppetClipping->commands;
  1865. const auto& records = this->m_puppetClipping->records;
  1866. auto* target = this->m_puppetClipTargetPass;
  1867. int draw = 0;
  1868. bool drawn = false;
  1869. target->copyBindings (*meshPass);
  1870. const auto drawMesh = [&] (Effects::CPass* pass, const int index) {
  1871. this->selectPuppetDraw (index);
  1872. this->m_puppetDrawKeep = drawn;
  1873. pass->setKeepDestination (drawn);
  1874. pass->render ();
  1875. drawn = true;
  1876. };
  1877. const auto drawTargets = [&] (const int record, const int index) {
  1878. target->setBlendingMode (
  1879. records[record].flags & PuppetClipping::Additive ? BlendingMode_Additive : BlendingMode_Translucent
  1880. );
  1881. drawMesh (target, index);
  1882. };
  1883. for (size_t i = 0; i < commands.size (); i++) {
  1884. switch (commands[i]) {
  1885. case PuppetClipping::PlainDraw:
  1886. drawMesh (meshPass, draw++);
  1887. break;
  1888. case PuppetClipping::Mask:
  1889. {
  1890. const int record = commands[++i];
  1891. if (static_cast<size_t> (record) < records.size ()) {
  1892. this->renderPuppetClipMask (*meshPass, record, draw, true, false);
  1893. drawTargets (record, draw + 1);
  1894. }
  1895. draw += 2;
  1896. break;
  1897. }
  1898. case PuppetClipping::NestedMask:
  1899. {
  1900. const int chain = commands[++i];
  1901. for (int link = 0; link < chain; link++) {
  1902. const int parent = commands[++i];
  1903. const int parentDraw = commands[++i];
  1904. this->renderPuppetClipMask (*meshPass, parent, parentDraw, link == 0, link != 0);
  1905. }
  1906. const int record = commands[++i];
  1907. this->renderPuppetClipMask (*meshPass, record, draw, false, true);
  1908. drawTargets (record, draw + 1);
  1909. draw += 2;
  1910. break;
  1911. }
  1912. default:
  1913. break;
  1914. }
  1915. }
  1916. meshPass->setKeepDestination (false);
  1917. this->m_puppetDrawKeep = false;
  1918. this->selectPuppetDraw (-1);
  1919. }
  1920. bool CImage::followsOutputSize () const {
  1921. // a fullscreen layer takes its texture's size (sub_1401912C0), which for the usual one is _rt_FullFrameBuffer
  1922. return this->getImage ().model->fullscreen && this->m_texture == this->getScene ().getFBO ();
  1923. }
  1924. void CImage::addEffectPasses (const ImageEffect& effect) {
  1925. const auto fboProvider = std::make_shared<FBOProvider> (this);
  1926. EffectBuffers buffers;
  1927. for (const auto& fbo : effect.effect->fbos) {
  1928. if (!fbo->conditions.holds (effect.combos)) {
  1929. continue;
  1930. }
  1931. const auto created = fboProvider->create (*fbo, this->getSize (), this->getScene ().isHDR ());
  1932. if (this->followsOutputSize ()) {
  1933. this->getScene ().followOutputSize (created, *fbo);
  1934. }
  1935. buffers.emplace_back (fbo.get (), created);
  1936. }
  1937. this->registerEffectBuffers (effect, std::move (buffers));
  1938. for (size_t passIndex = 0; passIndex < effect.effect->passes.size (); passIndex++) {
  1939. auto& effectPass = *effect.effect->passes[passIndex];
  1940. // a failed pass is left out, overrides still go by the effect's pass index
  1941. if (!effectPass.conditions.holds (effect.combos)) {
  1942. continue;
  1943. }
  1944. if (!effectPass.material.has_value ()) {
  1945. if (!effectPass.command.has_value ()) {
  1946. sLog.error ("Pass without material and command not supported");
  1947. continue;
  1948. }
  1949. if (!effectPass.source.has_value ()) {
  1950. sLog.error ("Pass without material and source not supported");
  1951. continue;
  1952. }
  1953. if (!effectPass.target.has_value ()) {
  1954. sLog.error ("Pass without material and target not supported");
  1955. continue;
  1956. }
  1957. if (effectPass.command != Command_Copy) {
  1958. sLog.error ("Only copy command is supported for pass without material");
  1959. continue;
  1960. }
  1961. auto virtualPass = std::make_unique<MaterialPass> (MaterialPass { .blending = BlendingMode_Normal,
  1962. .cullmode = CullingMode_Disable,
  1963. .depthtest = DepthtestMode_Disabled,
  1964. .depthwrite = DepthwriteMode_Disabled,
  1965. .shader = "commands/copy",
  1966. .textures = { { 0, *effectPass.source } },
  1967. .combos = {},
  1968. .constants = {} });
  1969. const auto& config = *this->m_virtualPassess.emplace_back (std::move (virtualPass));
  1970. this->m_passes.push_back (
  1971. new CPass (*this, fboProvider, config, std::nullopt, std::nullopt, effectPass.target.value ())
  1972. );
  1973. continue;
  1974. }
  1975. const auto override = passIndex < effect.passOverrides.size ()
  1976. ? std::optional<std::reference_wrapper<const ImageEffectPassOverride>> (*effect.passOverrides[passIndex])
  1977. : std::nullopt;
  1978. const auto target = effectPass.target.has_value ()
  1979. ? std::optional<std::reference_wrapper<std::string>> (*effectPass.target)
  1980. : std::nullopt;
  1981. for (auto& pass : effectPass.material.value ()->passes) {
  1982. this->m_passes.push_back (new CPass (*this, fboProvider, *pass, override, effectPass.binds, target));
  1983. this->registerEffectMaterial (effect, passIndex, this->m_passes.back ());
  1984. }
  1985. }
  1986. }
  1987. void CImage::setup () {
  1988. if (this->m_initialized) {
  1989. return;
  1990. }
  1991. this->m_readByOtherLayer = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
  1992. return object->id != this->getImage ().id
  1993. && std::ranges::find (object->dependencies, this->getImage ().id) != object->dependencies.end ();
  1994. });
  1995. this->m_emitterImageSource
  1996. = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
  1997. return std::ranges::any_of (object->componentDependencies, [this] (const auto& record) {
  1998. return record.type == "emitterimage" && record.id == this->getImage ().id;
  1999. });
  2000. });
  2001. // setParent may add children later
  2002. this->m_hasPassthroughChildren = this->m_image.model->passthrough
  2003. && (this->getScene ().scriptsMayReparent ()
  2004. || std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
  2005. return object->parent == this->getImage ().id;
  2006. }));
  2007. // passthrough without effects has nothing to draw unless another layer reads its _rt_imageLayerComposite or it
  2008. // has children to draw into its buffer
  2009. if (this->m_image.model->passthrough && this->m_image.effects.empty () && !this->m_readByOtherLayer
  2010. && !this->m_hasPassthroughChildren && !this->m_image.renderable.ledSource->value->getBool ()) {
  2011. return;
  2012. }
  2013. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  2014. // a shape has no image of its own, only its effect is drawn (sub_14025FAF0)
  2015. if (!this->getImage ().shape) {
  2016. for (const auto& cur : this->getImage ().model->material->passes) {
  2017. this->m_passes.push_back (
  2018. new CPass (*this, std::make_shared<FBOProvider> (this), *cur, std::nullopt, std::nullopt, std::nullopt)
  2019. );
  2020. }
  2021. }
  2022. std::vector<const DynamicValue*> passVisibility (this->m_passes.size (), nullptr);
  2023. std::vector<bool> passFromEffect (this->m_passes.size (), false);
  2024. if (!debug.baseOnly && !this->getImage ().effects.empty ()) {
  2025. for (const auto& cur : this->m_image.effects) {
  2026. if (std::find (debug.skipEffects.begin (), debug.skipEffects.end (), static_cast<int> (cur->id))
  2027. != debug.skipEffects.end ()) {
  2028. continue;
  2029. }
  2030. const auto effectVisibility
  2031. = this->getScene ().getContext ().getApp ().getContext ().resolveEffectVisibility (
  2032. static_cast<int> (cur->id), cur->name
  2033. );
  2034. // an explicit --disable-effect/--enable-effect override wins over the scene's own visibility
  2035. if (effectVisibility.has_value () && !*effectVisibility) {
  2036. continue;
  2037. }
  2038. // scripts can toggle hidden effects at runtime; puppets can't, their mesh pass layout
  2039. // depends on the pass count
  2040. const bool followsVisibility = !effectVisibility.has_value () && !this->m_hasPuppetMesh;
  2041. if (!followsVisibility && !effectVisibility.has_value () && !cur->visible->value->getBool ()) {
  2042. continue;
  2043. }
  2044. const DynamicValue* visibleValue = followsVisibility ? cur->visible->value.get () : nullptr;
  2045. const size_t firstEffectPass = this->m_passes.size ();
  2046. try {
  2047. this->addEffectPasses (*cur);
  2048. } catch (const std::exception& e) {
  2049. if (visibleValue == nullptr || visibleValue->getBool ()) {
  2050. throw;
  2051. }
  2052. for (size_t i = firstEffectPass; i < this->m_passes.size (); i++) {
  2053. delete this->m_passes[i];
  2054. }
  2055. this->m_passes.resize (firstEffectPass);
  2056. sLog.error (
  2057. "Dropping hidden effect ", cur->id, " (", cur->name, ") on ", this->getImage ().name, ": ",
  2058. e.what ()
  2059. );
  2060. continue;
  2061. }
  2062. passVisibility.resize (this->m_passes.size (), visibleValue);
  2063. passFromEffect.resize (this->m_passes.size (), true);
  2064. }
  2065. }
  2066. const size_t passCountBeforeTrailingPasses = this->m_passes.size ();
  2067. if (!debug.baseOnly && !this->getImage ().shape) {
  2068. const auto magentaCompositeTint = findMagentaCompositeTint (this->m_image, debug.skipEffects);
  2069. if (magentaCompositeTint.has_value ()) {
  2070. auto tintOverride = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  2071. .id = -1,
  2072. .combos = {
  2073. { "BLENDMODE", 30 },
  2074. },
  2075. .constants = {},
  2076. .textures = {},
  2077. });
  2078. tintOverride->constants.emplace ("color", UserSettingBuilder::fromValue (magentaCompositeTint.value ()));
  2079. tintOverride->constants.emplace ("alpha", UserSettingBuilder::fromValue (1.0f));
  2080. this->m_materials.compatibilityMaterials.emplace_back (
  2081. MaterialParser::load (this->getScene ().getScene ().project, "materials/effects/tint.json")
  2082. );
  2083. this->m_materials.compatibilityOverrides.emplace_back (std::move (tintOverride));
  2084. this->m_passes.push_back (new CPass (
  2085. *this, std::make_shared<FBOProvider> (this),
  2086. **this->m_materials.compatibilityMaterials.back ()->passes.begin (),
  2087. *this->m_materials.compatibilityOverrides.back (), std::nullopt, std::nullopt
  2088. ));
  2089. }
  2090. }
  2091. const int colorBlendMode = this->m_image.colorBlendMode->value->getInt ();
  2092. // WE keeps the result of a layer another one reads in _a and only copies it to the screen from there,
  2093. // drawing the last effect pass straight to the screen would leave _a one pass behind (or empty)
  2094. const bool copyForReaders = this->copiesForReaders ();
  2095. // fog sends every layer through its buffer and a FOG_COMPUTED composite (sub_1401E6F50, sub_1401EBBC0)
  2096. const bool fog = this->getScene ().hasDistanceFog () || this->getScene ().hasHeightFog ();
  2097. this->m_fogPass = nullptr;
  2098. this->m_materials.colorBlendingPass = nullptr;
  2099. // children go into the layer's buffer, which then needs a composite onto the scene even without effects
  2100. // (sub_1401E8AA0 with children, sub_140208670)
  2101. if (!debug.baseOnly && !this->getImage ().shape
  2102. && (colorBlendMode > 0 || copyForReaders || fog || this->m_hasPassthroughChildren)) {
  2103. // scenes from version 3 on composite with genericimage4, the one with fog (sub_1401EBBC0)
  2104. const auto& project = this->getScene ().getScene ().project;
  2105. this->m_materials.colorBlending.material = MaterialParser::load (
  2106. project,
  2107. project.sceneVersion >= 3 ? "materials/util/effectpassthrough_4.json"
  2108. : "materials/util/effectpassthrough.json"
  2109. );
  2110. ComboMap combos;
  2111. if (colorBlendMode > 0) {
  2112. combos.emplace ("BLENDMODE", colorBlendMode);
  2113. }
  2114. if (fog) {
  2115. combos.emplace ("FOG_COMPUTED", 1);
  2116. }
  2117. // draws the warped mesh over the flat texture in the buffer (sub_140208670)
  2118. if (this->m_hasPuppetMesh) {
  2119. combos.merge (this->puppetVertexAlphaCombos ());
  2120. }
  2121. this->m_materials.colorBlending.override = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  2122. .id = -1,
  2123. .combos = combos,
  2124. .constants = {},
  2125. .textures = {},
  2126. });
  2127. this->m_passes.push_back (new CPass (
  2128. *this, std::make_shared<FBOProvider> (this), **this->m_materials.colorBlending.material->passes.begin (),
  2129. *this->m_materials.colorBlending.override, std::nullopt, std::nullopt
  2130. ));
  2131. this->m_materials.colorBlendingPass = this->m_passes.back ();
  2132. // the layer buffer already holds color and alpha, WE draws this composite with a white renderer color
  2133. // (sub_1401E8AA0 sets renderer +288..+300 to 1 before it)
  2134. this->m_passes.back ()->setNeutralColor (true);
  2135. if (fog) {
  2136. this->m_fogPass = this->m_passes.back ();
  2137. }
  2138. }
  2139. if (this->m_hasPuppetMesh && !this->m_passes.empty ()) {
  2140. this->m_puppetMeshPass = this->m_passes.front ();
  2141. this->m_puppetMeshLast = this->m_passes.size () == 1;
  2142. this->m_materials.puppetVertexAlpha = nullptr;
  2143. if (this->m_puppetVertexAlpha) {
  2144. this->m_materials.puppetVertexAlpha = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  2145. .id = -1,
  2146. .combos = this->puppetVertexAlphaCombos (),
  2147. .constants = {},
  2148. .textures = {},
  2149. });
  2150. }
  2151. // effect masks are laid out over the source texture, so effects run on the flat texture first
  2152. // and the warped mesh is drawn last, sampling their output
  2153. const auto& materialPasses = this->getImage ().model->material->passes;
  2154. const bool hasTrailingPasses = this->m_passes.size () != passCountBeforeTrailingPasses;
  2155. const bool lit = this->hasLitMaterial ();
  2156. if (hasTrailingPasses && this->m_passes.back () == this->m_materials.colorBlendingPass) {
  2157. this->m_puppetMeshPass = this->m_passes.back ();
  2158. this->m_puppetMeshLast = true;
  2159. } else if (
  2160. this->m_passes.size () > 1 && !hasTrailingPasses && materialPasses.size () == 1
  2161. && (lit || materialPasses.front ()->constants.empty ())
  2162. ) {
  2163. // lit layer with effects (sub_140209540): first pass lights the flat texture, the mesh is drawn by the same
  2164. // material with LIGHTING/REFLECTION off and is the only pass with vertex alpha
  2165. const auto& base = *materialPasses.front ();
  2166. ShaderConstantMap constants;
  2167. for (const auto& [name, setting] : base.constants) {
  2168. auto value = std::make_unique<DynamicValue> ();
  2169. value->connect (setting->value.get ());
  2170. value->setAnimation (setting->value->getAnimation ());
  2171. constants.emplace (
  2172. name,
  2173. std::make_unique<UserSetting> (UserSetting {
  2174. .value = std::move (value),
  2175. .property = setting->property,
  2176. .condition = setting->condition,
  2177. })
  2178. );
  2179. }
  2180. const auto& config = *this->m_virtualPassess.emplace_back (
  2181. std::make_unique<MaterialPass> (MaterialPass {
  2182. .blending = base.blending,
  2183. .cullmode = base.cullmode,
  2184. .depthtest = base.depthtest,
  2185. .depthwrite = base.depthwrite,
  2186. .shader = base.shader,
  2187. .textures = {},
  2188. .usertextures = {},
  2189. .combos = base.combos,
  2190. .constants = std::move (constants),
  2191. })
  2192. );
  2193. if (lit) {
  2194. auto combos = this->puppetVertexAlphaCombos ();
  2195. combos.insert_or_assign ("LIGHTING", 0);
  2196. combos.insert_or_assign ("REFLECTION", 0);
  2197. this->m_materials.puppetVertexAlpha
  2198. = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  2199. .id = -1,
  2200. .combos = combos,
  2201. .constants = {},
  2202. .textures = {},
  2203. });
  2204. }
  2205. this->m_puppetMeshPass = this->m_materials.puppetVertexAlpha != nullptr
  2206. ? new CPass (
  2207. *this, std::make_shared<FBOProvider> (this), config, *this->m_materials.puppetVertexAlpha,
  2208. std::nullopt, std::nullopt
  2209. )
  2210. : new CPass (
  2211. *this, std::make_shared<FBOProvider> (this), config, std::nullopt, std::nullopt, std::nullopt
  2212. );
  2213. this->m_passes.push_back (this->m_puppetMeshPass);
  2214. this->m_puppetMeshLast = true;
  2215. } else if (this->m_materials.puppetVertexAlpha != nullptr) {
  2216. // first pass draws the mesh, rebuilt with the combos
  2217. auto* pass = new CPass (
  2218. *this, std::make_shared<FBOProvider> (this), this->m_passes.front ()->getPass (),
  2219. *this->m_materials.puppetVertexAlpha, std::nullopt, std::nullopt
  2220. );
  2221. delete this->m_passes.front ();
  2222. this->m_passes.front () = pass;
  2223. this->m_puppetMeshPass = pass;
  2224. }
  2225. }
  2226. // WE sets MORPHING on any shader (sub_140209540), only shaders with MORPHING code use it
  2227. this->m_puppetMorphShader = false;
  2228. if (const auto& material = this->getImage ().model->material; material != nullptr && !material->passes.empty ()) {
  2229. const auto pass = std::ranges::find_if (this->m_passes, [&material] (const CPass* candidate) {
  2230. return candidate->getPass ().shader == material->passes.front ()->shader
  2231. && candidate->getShader () != nullptr;
  2232. });
  2233. this->m_puppetMorphShader
  2234. = pass != this->m_passes.end () && (*pass)->getShader ()->getVertex ().refersTo ("MORPHING");
  2235. }
  2236. this->setupPuppetPrelight ();
  2237. this->setupPuppetClipping ();
  2238. // offscreen when a visible effect adds passes (sub_1401E7170)
  2239. this->setupPuppetBlendMap (std::ranges::find (passFromEffect, true) != passFromEffect.end ());
  2240. passVisibility.resize (this->m_passes.size (), nullptr);
  2241. passFromEffect.resize (this->m_passes.size (), false);
  2242. for (size_t i = 0; i < this->m_passes.size (); i++) {
  2243. this->m_allPassStates.push_back (
  2244. { passVisibility[i], this->m_passes[i]->getBlendingMode (), passFromEffect[i] }
  2245. );
  2246. }
  2247. this->m_allPasses = this->m_passes;
  2248. CRenderable::setup ();
  2249. this->rebuildActivePasses ();
  2250. this->setupDirectLitPass ();
  2251. this->m_setupInputs = this->currentSetupInputs ();
  2252. this->m_initialized = true;
  2253. }
  2254. CImage::SetupInputs CImage::currentSetupInputs () const {
  2255. SetupInputs inputs {
  2256. .colorBlendMode = this->m_image.colorBlendMode->value->getInt (),
  2257. .copyForReaders = this->copiesForReaders (),
  2258. };
  2259. if (this->m_hasPuppetMesh) {
  2260. const auto& context = this->getScene ().getContext ().getApp ().getContext ();
  2261. for (const auto& effect : this->m_image.effects) {
  2262. if (!context.resolveEffectVisibility (static_cast<int> (effect->id), effect->name).has_value ()) {
  2263. inputs.puppetEffects.push_back (effect->visible->value->getBool ());
  2264. }
  2265. }
  2266. }
  2267. return inputs;
  2268. }
  2269. void CImage::releasePasses () {
  2270. this->releaseEffectMaterials ();
  2271. for (auto* pass : this->m_allPasses.empty () ? this->m_passes : this->m_allPasses) {
  2272. delete pass;
  2273. }
  2274. for (auto* pass : this->m_puppetClipMaskPasses) {
  2275. delete pass;
  2276. }
  2277. delete this->m_puppetClipTargetPass;
  2278. delete this->m_puppetClipComposePass;
  2279. delete this->m_blendMap.copyPass;
  2280. delete this->m_blendMap.pass;
  2281. for (GLuint* buffer :
  2282. { &this->m_puppetClipComposePosition, &this->m_puppetClipComposeTexCoord, &this->m_blendMap.quad }) {
  2283. if (*buffer != GL_NONE) {
  2284. glDeleteBuffers (1, buffer);
  2285. *buffer = GL_NONE;
  2286. }
  2287. }
  2288. this->m_passes.clear ();
  2289. this->m_allPasses.clear ();
  2290. this->m_allPassStates.clear ();
  2291. this->m_activePassMask.clear ();
  2292. this->m_virtualPassess.clear ();
  2293. this->m_puppetClipMaskPasses.clear ();
  2294. this->m_puppetClipTargetPass = nullptr;
  2295. this->m_puppetClipComposePass = nullptr;
  2296. this->m_blendMap.copyPass = nullptr;
  2297. this->m_blendMap.pass = nullptr;
  2298. this->m_blendMap.albedo = nullptr;
  2299. this->m_puppetPrelight.pass = nullptr;
  2300. this->m_directLitPass = nullptr;
  2301. this->m_materials.directLit = nullptr;
  2302. this->m_puppetMeshPass = nullptr;
  2303. this->m_puppetMeshLast = false;
  2304. this->m_fogPass = nullptr;
  2305. this->m_hasActiveEffectPass = false;
  2306. this->m_materials.colorBlendingPass = nullptr;
  2307. this->m_materials.compatibilityMaterials.clear ();
  2308. this->m_materials.compatibilityOverrides.clear ();
  2309. this->m_materials.clippingOverrides.clear ();
  2310. this->m_initialized = false;
  2311. }
  2312. bool CImage::effectVisibilityChanged () const {
  2313. for (size_t i = 0; i < this->m_allPassStates.size (); i++) {
  2314. const auto* visible = this->m_allPassStates[i].visible;
  2315. if (visible != nullptr && visible->getBool () != this->m_activePassMask[i]) {
  2316. return true;
  2317. }
  2318. }
  2319. return false;
  2320. }
  2321. void CImage::rebuildActivePasses () {
  2322. this->m_passes.clear ();
  2323. this->m_activePassMask.assign (this->m_allPasses.size (), false);
  2324. this->m_hasActiveEffectPass = false;
  2325. for (size_t i = 0; i < this->m_allPasses.size (); i++) {
  2326. const auto& state = this->m_allPassStates[i];
  2327. this->m_allPasses[i]->setBlendingMode (state.blending);
  2328. this->m_allPasses[i]->setDepthState (std::nullopt);
  2329. if (state.visible == nullptr || state.visible->getBool ()) {
  2330. this->m_activePassMask[i] = true;
  2331. this->m_hasActiveEffectPass |= state.fromEffect;
  2332. this->m_passes.push_back (this->m_allPasses[i]);
  2333. }
  2334. }
  2335. // WE skips the children-only composite while an effect runs, the last effect pass draws instead (sub_1401EBF60)
  2336. if (this->m_hasActiveEffectPass && this->m_hasPassthroughChildren && !this->m_passes.empty ()
  2337. && this->m_passes.back () == this->m_materials.colorBlendingPass
  2338. && this->m_image.colorBlendMode->value->getInt () == 0 && !this->copiesForReaders ()
  2339. && !this->getScene ().hasDistanceFog () && !this->getScene ().hasHeightFog ()) {
  2340. this->m_activePassMask
  2341. [std::ranges::find (this->m_allPasses, this->m_passes.back ()) - this->m_allPasses.begin ()] = false;
  2342. this->m_passes.pop_back ();
  2343. }
  2344. // a hidden layerimage source keeps its buffer but skips the composite (sub_1401D3AE0)
  2345. if (this->m_emitterImageSource && !this->shouldRenderFinalPass (true) && this->m_passes.size () > 1
  2346. && this->m_passes.back () == this->m_materials.colorBlendingPass) {
  2347. const auto index = std::ranges::find (this->m_allPasses, this->m_passes.back ()) - this->m_allPasses.begin ();
  2348. this->m_activePassMask[index] = false;
  2349. this->m_passes.pop_back ();
  2350. }
  2351. // if there's more than one pass the blendmode has to be moved from the beginning to the end
  2352. if (this->m_passes.size () > 1) {
  2353. const auto first = this->m_passes.begin ();
  2354. const auto last = this->m_passes.rbegin ();
  2355. (*last)->setBlendingMode ((*first)->getBlendingMode ());
  2356. (*first)->setBlendingMode (BlendingMode_Normal);
  2357. // the pass that draws an image's effects onto the scene also takes the image material's depth test and write
  2358. // (sub_1401EBF60 through image slot 33 sub_140209160, material bytes +498/+499): a 3D layer behind a model
  2359. // stays behind it (3453730450's moon_BBB)
  2360. const auto& materialPasses = this->getImage ().model->material->passes;
  2361. const auto lastState = std::ranges::find (this->m_allPasses, *last) - this->m_allPasses.begin ();
  2362. if (!this->getImage ().shape && !materialPasses.empty () && this->m_allPassStates[lastState].fromEffect) {
  2363. const auto& base = *materialPasses.front ();
  2364. (*last)->setDepthState (std::make_pair (base.depthtest, base.depthwrite));
  2365. }
  2366. }
  2367. // a shape's last pass goes onto the scene additively (its blend override sub_140260790 writes 2)
  2368. if (this->getImage ().shape && !this->m_passes.empty ()) {
  2369. this->m_passes.back ()->setBlendingMode (BlendingMode_Additive);
  2370. }
  2371. // passthrough with children and no other composite: slot 30 (sub_140208670) draws it with effectpassthrough or
  2372. // fullscreenlayer.json, colour tints, alpha does nothing (live WE)
  2373. if (this->m_materials.colorBlendingPass != nullptr && !this->m_passes.empty ()
  2374. && this->m_passes.back () == this->m_materials.colorBlendingPass) {
  2375. const int colorBlendMode = this->m_image.colorBlendMode->value->getInt ();
  2376. const bool childrenComposite = this->m_hasPassthroughChildren && !this->m_hasActiveEffectPass
  2377. && (colorBlendMode == 0 || colorBlendMode == 31) && !this->copiesForReaders ()
  2378. && !this->getScene ().hasDistanceFog () && !this->getScene ().hasHeightFog ();
  2379. auto* composite = this->m_passes.back ();
  2380. composite->setNeutralColor (!childrenComposite);
  2381. if (childrenComposite) {
  2382. composite->setBlendingMode (
  2383. colorBlendMode == 31 ? BlendingMode_Additive
  2384. : !this->m_image.copyBackground->value->getBool () || this->getImage ().model->fullscreen
  2385. ? BlendingMode_Translucent
  2386. : BlendingMode_Normal
  2387. );
  2388. }
  2389. }
  2390. // setupPasses() ping-pongs these, every rebuild has to start from the same pair
  2391. this->assignLayerBuffers ();
  2392. this->m_currentMainFBO = this->m_mainFBO;
  2393. this->m_currentSubFBO = this->m_subFBO;
  2394. this->setupPasses ();
  2395. }
  2396. void CImage::setupPasses () {
  2397. // like WE, start on whichever buffer makes the last offscreen pass land in _a, which is what other layers read
  2398. auto offscreenPasses = std::ranges::count_if (this->m_passes, [] (const Effects::CPass* pass) {
  2399. return !pass->getTarget ().has_value ();
  2400. });
  2401. this->m_passesDrawToScreen = this->shouldRenderFinalPass (true);
  2402. if (!this->m_passes.empty () && !this->m_passes.back ()->getTarget ().has_value () && this->m_passesDrawToScreen) {
  2403. offscreenPasses--;
  2404. }
  2405. if (offscreenPasses % 2 == 0) {
  2406. std::swap (this->m_currentMainFBO, this->m_currentSubFBO);
  2407. }
  2408. std::shared_ptr<const CFBO> drawTo = this->m_currentMainFBO;
  2409. std::shared_ptr<const TextureProvider> asInput = this->getTexture ();
  2410. GLuint texcoord = this->getTexCoordCopy ();
  2411. auto cur = this->m_passes.begin ();
  2412. auto end = this->m_passes.end ();
  2413. bool first = true;
  2414. bool inTargetEffectSequence = false;
  2415. std::shared_ptr<const TextureProvider> effectInput = nullptr;
  2416. for (; cur != end; ++cur) {
  2417. Effects::CPass* pass = *cur;
  2418. std::shared_ptr<const CFBO> prevDrawTo = drawTo;
  2419. bool writesToTarget = false;
  2420. const bool isFirstPass = first;
  2421. const bool isMeshPass = this->m_hasPuppetMesh && pass == this->m_puppetMeshPass;
  2422. GLuint spacePosition = isMeshPass ? this->m_puppetSpacePosition
  2423. : isFirstPass ? this->getCopySpacePosition ()
  2424. : this->getPassSpacePosition ();
  2425. const glm::mat4* projection
  2426. = (isFirstPass) ? &this->m_modelViewProjectionCopy : &this->m_modelViewProjectionPass;
  2427. const glm::mat4* inverseProjection
  2428. = (isFirstPass) ? &this->m_modelViewProjectionCopyInverse : &this->m_modelViewProjectionPassInverse;
  2429. first = false;
  2430. if (isMeshPass) {
  2431. pass->setBlendingMode (BlendingMode_Translucent);
  2432. this->setupPuppetGeometryCallback (pass);
  2433. }
  2434. pass->setModelMatrix (&this->m_modelMatrix);
  2435. pass->setViewProjectionMatrix (&this->m_viewProjectionMatrix);
  2436. pass->setLayerModelMatrix (&this->m_layerModelMatrix);
  2437. pass->setEffectTextureProjectionMatrix (
  2438. &this->m_effectTextureProjection, &this->m_effectTextureProjectionInverse
  2439. );
  2440. writesToTarget = this->configurePassTarget (pass, drawTo, asInput, effectInput, inTargetEffectSequence);
  2441. if (!writesToTarget && this->shouldRenderFinalPass (std::next (cur) == end)) {
  2442. drawTo = this->getScene ().getFBO ();
  2443. // a puppet without effects draws its mesh straight into the scene FBO, so it takes the screen projection
  2444. // like any final pass (m_puppetSpacePosition already holds the scene position, the puppet callback binds it
  2445. // itself)
  2446. spacePosition = this->getSceneSpacePosition ();
  2447. texcoord = isFirstPass ? this->m_texcoordDirect : this->m_texcoordFinal;
  2448. projection = &this->m_modelViewProjectionScreen;
  2449. // WE's final pass inverse lands in the layer's local space (origin at its center, unscaled
  2450. // pixels); older shaders like the bundled xray.vert unproject the pointer through it
  2451. inverseProjection = &this->m_objectSpaceProjectionInverse;
  2452. }
  2453. pass->setLightingTransform (
  2454. projection == &this->m_modelViewProjectionCopy ? &this->m_lightingCopyModel : &this->m_lightingSceneModel,
  2455. &this->m_lightingNormal, &this->m_lightingViewProjection
  2456. );
  2457. if (pass == this->m_puppetPrelight.pass) {
  2458. pass->setLightingTransform (
  2459. &this->m_puppetPrelight.model, &this->m_puppetPrelight.normal, &this->m_lightingViewProjection
  2460. );
  2461. }
  2462. if (pass == this->m_directLitPass) {
  2463. pass->setModelMatrix (&this->m_lightingSceneModel);
  2464. pass->setViewProjectionMatrix (&this->m_lightingViewProjection);
  2465. }
  2466. // the fog composite measures in WE's world, the lighting model already maps the layer there
  2467. if (pass == this->m_fogPass && projection == &this->m_modelViewProjectionScreen) {
  2468. pass->setModelMatrix (&this->m_lightingSceneModel);
  2469. pass->setFogWorld (true);
  2470. }
  2471. pass->setDestination (drawTo);
  2472. pass->setInput (asInput);
  2473. pass->setPreviousInput (inTargetEffectSequence ? effectInput : nullptr);
  2474. pass->setPosition (spacePosition);
  2475. pass->setTexCoord (texcoord);
  2476. pass->setModelViewProjectionMatrix (
  2477. pass == this->m_puppetPrelight.pass ? &this->m_puppetPrelight.projection : projection
  2478. );
  2479. pass->setModelViewProjectionMatrixInverse (inverseProjection);
  2480. // what WE's intermediate passes see as g_EffectModelViewProjectionMatrix: their geometry where the layer
  2481. // is on screen (sub_1401EBF60), the final pass keeps its own MVP
  2482. pass->setEffectModelViewProjectionMatrix (
  2483. projection == &this->m_modelViewProjectionCopy ? &this->m_effectModelViewProjectionCopy
  2484. : projection == &this->m_modelViewProjectionPass ? &this->m_effectModelViewProjectionPass
  2485. : nullptr
  2486. );
  2487. texcoord = this->getTexCoordPass ();
  2488. if (writesToTarget) {
  2489. asInput = drawTo;
  2490. drawTo = prevDrawTo;
  2491. } else {
  2492. drawTo = prevDrawTo;
  2493. this->pinpongFramebuffer (&drawTo, &asInput);
  2494. inTargetEffectSequence = false;
  2495. effectInput = nullptr;
  2496. }
  2497. }
  2498. }
  2499. bool CImage::shouldRenderFinalPass (bool isLastPass) const {
  2500. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  2501. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  2502. const bool visible = visibility.value_or (this->getImage ().visible->value->getBool ());
  2503. if (!isLastPass || !visible) {
  2504. return false;
  2505. }
  2506. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  2507. return !(debug.noSolidFinal && this->getImage ().model->solidlayer);
  2508. }
  2509. bool CImage::configurePassTarget (
  2510. Effects::CPass* pass, std::shared_ptr<const CFBO>& drawTo, const std::shared_ptr<const TextureProvider>& asInput,
  2511. std::shared_ptr<const TextureProvider>& effectInput, bool& inTargetEffectSequence
  2512. ) {
  2513. if (!pass->getTarget ().has_value ()) {
  2514. return false;
  2515. }
  2516. const std::string target = pass->getTarget ().value ();
  2517. std::shared_ptr<const CFBO> resolved = pass->getFBOProvider ()->find (target);
  2518. if (resolved == nullptr) {
  2519. resolved = this->getScene ().findFBO (target);
  2520. }
  2521. if (resolved == nullptr) {
  2522. sLog.error (
  2523. "Pass target FBO '", target, "' could not be resolved for object ", pass->getRenderable ().getId (),
  2524. " shader=", pass->getPass ().shader
  2525. );
  2526. return false;
  2527. }
  2528. if (!inTargetEffectSequence) {
  2529. effectInput = asInput;
  2530. inTargetEffectSequence = true;
  2531. }
  2532. drawTo = resolved;
  2533. return true;
  2534. }
  2535. void CImage::pinpongFramebuffer (std::shared_ptr<const CFBO>* drawTo, std::shared_ptr<const TextureProvider>* asInput) {
  2536. std::shared_ptr<const CFBO> currentMainFBO = this->m_currentMainFBO;
  2537. std::shared_ptr<const CFBO> currentSubFBO = this->m_currentSubFBO;
  2538. if (drawTo != nullptr) {
  2539. *drawTo = currentSubFBO;
  2540. }
  2541. if (asInput != nullptr) {
  2542. *asInput = currentMainFBO;
  2543. }
  2544. this->m_currentMainFBO = currentSubFBO;
  2545. this->m_currentSubFBO = currentMainFBO;
  2546. }
  2547. void CImage::render () {
  2548. if (!this->m_initialized) {
  2549. return;
  2550. }
  2551. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  2552. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  2553. // a hidden layer another object reads through _rt_imageLayerComposite_<id> (xray's "bloody" twins) still
  2554. // has to fill that FBO every frame, shouldRenderFinalPass() keeps it off the screen
  2555. if (!visibility.value_or (this->getImage ().visible->value->getBool ())
  2556. && (visibility.has_value () || !this->m_isDependency)) {
  2557. return;
  2558. }
  2559. if (this->currentSetupInputs () != this->m_setupInputs) {
  2560. this->releasePasses ();
  2561. this->setup ();
  2562. if (!this->m_initialized) {
  2563. return;
  2564. }
  2565. }
  2566. // the last pass only goes to the screen if the layer was visible when the passes were set up,
  2567. // layers a script shows later (hidden in scene.json) need that redone
  2568. if (this->effectVisibilityChanged () || this->shouldRenderFinalPass (true) != this->m_passesDrawToScreen) {
  2569. this->rebuildActivePasses ();
  2570. }
  2571. // the lit pass may move into or out of the layer buffer
  2572. if ((this->m_directLitPass != nullptr) != this->litDrawsDirect ()) {
  2573. this->releasePasses ();
  2574. this->setup ();
  2575. if (!this->m_initialized) {
  2576. return;
  2577. }
  2578. }
  2579. if (this->m_image.model->passthrough && !this->m_hasActiveEffectPass && !this->m_readByOtherLayer
  2580. && !this->m_hasPassthroughChildren && !this->m_image.renderable.ledSource->value->getBool ()) {
  2581. return;
  2582. }
  2583. glColorMask (true, true, true, true);
  2584. this->updateScreenSpacePosition ();
  2585. if (this->m_hasPuppetMesh) {
  2586. this->updatePuppetSkinning ();
  2587. }
  2588. if (this->m_blendMap.pass != nullptr) {
  2589. this->m_blendMap.copyPass->render ();
  2590. this->m_blendMap.pass->render ();
  2591. }
  2592. #if !NDEBUG
  2593. const std::string str = "Image " + this->getImage ().name + " (" + std::to_string (this->getId ()) + ", "
  2594. + this->getImage ().model->material->filename + ")";
  2595. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
  2596. #endif
  2597. // WE (sub_140207B50): a passthrough layer without copybackground clears its buffer to 0,0,0,0 instead of
  2598. // drawing the scene behind it, so its effects start from a transparent image
  2599. const Effects::CPass* skippedBasePass = this->m_image.model->passthrough
  2600. && !this->m_image.copyBackground->value->getBool () && !this->m_allPasses.empty ()
  2601. ? this->m_allPasses.front ()
  2602. : nullptr;
  2603. auto cur = this->m_passes.begin ();
  2604. const auto end = this->m_passes.end ();
  2605. for (; cur != end; ++cur) {
  2606. // the scene keeps its own alpha, but a hidden dependency's last pass fills the _a buffer other layers
  2607. // read and needs its alpha (2938612768's audio cover drawn through the background's blend effects)
  2608. if (std::next (cur) == end && this->m_passesDrawToScreen) {
  2609. glColorMask (true, true, true, false);
  2610. }
  2611. if (*cur == skippedBasePass && std::next (cur) != end) {
  2612. (*cur)->clearDestination ();
  2613. } else if (*cur == this->m_puppetMeshPass && this->m_puppetClipTargetPass != nullptr) {
  2614. this->renderPuppetClipped (*cur);
  2615. } else {
  2616. (*cur)->render ();
  2617. }
  2618. if (this->m_hasPassthroughChildren && *cur == this->m_allPasses.front () && std::next (cur) != end) {
  2619. this->renderPassthroughChildren ((*cur)->getDestination ());
  2620. // the children's final passes leave the scene's rgb only mask behind
  2621. glColorMask (true, true, true, true);
  2622. }
  2623. }
  2624. // CParticle::render () never resets glColorMask, a disabled mask would leak into the next clear
  2625. glColorMask (true, true, true, true);
  2626. #if !NDEBUG
  2627. glPopDebugGroup ();
  2628. #endif
  2629. }
  2630. const float& CImage::getBrightness () const { return this->m_image.brightness->value->getFloat (); }
  2631. const float& CImage::getUserAlpha () const { return this->getAlpha (); }
  2632. const float& CImage::getAlpha () const {
  2633. // some scenes store out-of-range alpha (e.g. 222) - it feeds mix() in blend modes, so it must stay in 0..1
  2634. m_alphaCache = glm::clamp (this->m_image.alpha->value->getFloat (), 0.0f, 1.0f);
  2635. return m_alphaCache;
  2636. }
  2637. const glm::vec3& CImage::getColor () const {
  2638. // a solid layer showing an image the user picked draws it untinted, its color only tints the plain
  2639. // white fill (checked against WE with 3765586324's local file background, black and white color alike)
  2640. const glm::vec3 color
  2641. = this->showsUserTextureOnSolidLayer () ? glm::vec3 (1.0f) : this->m_image.color->value->getVec3 ();
  2642. // the object's brightness only scales its color in HDR scene rendering (sub_140207740)
  2643. m_colorCache = color * (this->getScene ().isHDR () ? this->m_image.brightness->value->getFloat () : 1.0f);
  2644. return m_colorCache;
  2645. }
  2646. bool CImage::showsUserTextureOnSolidLayer () const {
  2647. if (!this->m_image.model->solidlayer || this->m_image.model->material->passes.empty ()) {
  2648. return false;
  2649. }
  2650. const auto& properties = this->getScene ().getScene ().project.properties;
  2651. for (const auto& [index, propertyName] : (*this->m_image.model->material->passes.begin ())->usertextures) {
  2652. const auto it = properties.find (propertyName);
  2653. if (it != properties.end ()) {
  2654. it->second->pin ();
  2655. }
  2656. if (it != properties.end () && !it->second->is<Data::Model::PropertyUserShortcut> ()
  2657. && !it->second->getString ().empty ()) {
  2658. return true;
  2659. }
  2660. }
  2661. return false;
  2662. }
  2663. const glm::vec4& CImage::getColor4 () const {
  2664. // "version" 2 materials take color and alpha together through g_Color4
  2665. m_color4Cache = glm::vec4 (this->getColor (), this->getAlpha ());
  2666. return m_color4Cache;
  2667. }
  2668. const glm::vec3& CImage::getCompositeColor () const { return this->m_image.color->value->getVec3 (); }
  2669. glm::vec2 CImage::resolveGeometrySize () const {
  2670. glm::vec2 size = this->getSize ();
  2671. if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
  2672. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  2673. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  2674. } else if (
  2675. (size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
  2676. && this->getImage ().model->height.has_value ()
  2677. ) {
  2678. size.x = static_cast<float> (this->getImage ().model->width.value ());
  2679. size.y = static_cast<float> (this->getImage ().model->height.value ());
  2680. }
  2681. if (this->getImage ().model->fullscreen) {
  2682. size = { static_cast<float> (this->getScene ().getCanvasWidth ()),
  2683. static_cast<float> (this->getScene ().getCanvasHeight ()) };
  2684. }
  2685. return size;
  2686. }
  2687. void CImage::updateScenePosition (const glm::vec2& size) {
  2688. glm::vec2 displaySize = size;
  2689. const glm::vec2 declared = this->getImage ().size;
  2690. const auto& model = *this->getImage ().model;
  2691. if (!model.fullscreen && !model.autosize && !model.puppet.has_value () && declared.x > 0.0f && declared.y > 0.0f) {
  2692. displaySize = declared;
  2693. }
  2694. this->m_displaySize = displaySize;
  2695. // WE's quad (sub_1401EDE30) is centered on the object, size truncated to int; m_pos is y down
  2696. const glm::vec2 half = (model.fullscreen ? displaySize : glm::trunc (displaySize)) / 2.0f;
  2697. this->m_pos = { -half.x, half.y, half.x, -half.y };
  2698. }
  2699. void CImage::uploadGeometryBuffers (const glm::vec2& size) {
  2700. GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
  2701. this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
  2702. this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
  2703. float width = 1.0f;
  2704. float height = 1.0f;
  2705. if (this->getTexture () != nullptr && !this->getTexture ()->isAnimated ()
  2706. && (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
  2707. || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())) {
  2708. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  2709. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  2710. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  2711. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  2712. }
  2713. float x = 0.0f;
  2714. float y = 0.0f;
  2715. GLfloat realWidth = size.x;
  2716. GLfloat realHeight = size.y;
  2717. GLfloat realX = 0.0f;
  2718. GLfloat realY = 0.0f;
  2719. if (this->getImage ().model->passthrough) {
  2720. width = 1.0f;
  2721. height = 1.0f;
  2722. realX = this->m_pos.x;
  2723. realY = this->m_pos.w;
  2724. realWidth = this->m_pos.z;
  2725. realHeight = this->m_pos.y;
  2726. if (this->getImage ().model->fullscreen) {
  2727. realX = -1.0f;
  2728. realY = -1.0f;
  2729. realWidth = 1.0f;
  2730. realHeight = 1.0f;
  2731. }
  2732. }
  2733. GLfloat texcoordCopy[] = { x, height, x, y, width, height, width, height, x, y, width, y };
  2734. GLfloat copySpacePosition[] = { realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f,
  2735. realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f };
  2736. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  2737. glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_DYNAMIC_DRAW);
  2738. glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
  2739. glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_DYNAMIC_DRAW);
  2740. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
  2741. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_DYNAMIC_DRAW);
  2742. this->uploadSceneTexCoords ({ x, y, width, height });
  2743. this->uploadShapePointMesh (size);
  2744. this->m_modelViewProjectionCopy = this->getImage ().model->passthrough
  2745. ? this->m_modelViewProjectionScreen
  2746. : DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y));
  2747. this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
  2748. this->m_modelMatrix = DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y));
  2749. // WE's buffer ortho has near -1000 / far 1000 (sub_14009A630), so the mesh keeps its z
  2750. const glm::mat4 placement = glm::translate (glm::mat4 (1.0f), glm::vec3 (size / 2.0f, 0.0f));
  2751. this->m_puppetPrelight.projection = this->getImage ().model->passthrough
  2752. ? this->m_modelViewProjectionCopy * glm::scale (placement, glm::vec3 (1.0f, -1.0f, 0.0f))
  2753. : DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y, -1000.0f, 1000.0f))
  2754. * glm::scale (placement, glm::vec3 (1.0f, -1.0f, 1.0f));
  2755. }
  2756. // sub_140260190: a shape whose last effect pass sets point0..3 (the light shafts' perspective gizmo) swaps its square
  2757. // for the quad through those four points, positions (p - 0.5) * size, texcoords = p, triangles (0,1,2) (0,2,3)
  2758. void CImage::uploadShapePointMesh (const glm::vec2& size) {
  2759. if (!this->getImage ().shape || this->getImage ().effects.empty ()) {
  2760. return;
  2761. }
  2762. const auto& effect = this->getImage ().effects.back ();
  2763. if (effect->passOverrides.empty ()) {
  2764. return;
  2765. }
  2766. const auto& constants = effect->passOverrides.back ()->constants;
  2767. glm::vec2 points[4];
  2768. const char* names[4] = { "point0", "point1", "point2", "point3" };
  2769. for (int i = 0; i < 4; i++) {
  2770. const auto it = constants.find (names[i]);
  2771. if (it == constants.end () || it->second == nullptr || it->second->value == nullptr) {
  2772. return;
  2773. }
  2774. points[i] = it->second->value->getVec2 ();
  2775. }
  2776. const int order[6] = { 0, 1, 2, 0, 2, 3 };
  2777. GLfloat positions[18];
  2778. GLfloat texcoords[12];
  2779. for (int i = 0; i < 6; i++) {
  2780. const glm::vec2& point = points[order[i]];
  2781. positions[i * 3] = (point.x - 0.5f) * size.x;
  2782. positions[i * 3 + 1] = (point.y - 0.5f) * size.y;
  2783. positions[i * 3 + 2] = 0.0f;
  2784. texcoords[i * 2] = point.x;
  2785. texcoords[i * 2 + 1] = point.y;
  2786. }
  2787. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  2788. glBufferData (GL_ARRAY_BUFFER, sizeof (positions), positions, GL_DYNAMIC_DRAW);
  2789. // the shape's only pass is its first pass and reads m_texcoordDirect, the final pass of a longer chain
  2790. // m_texcoordFinal
  2791. for (const GLuint buffer : { this->m_texcoordFinal, this->m_texcoordDirect }) {
  2792. glBindBuffer (GL_ARRAY_BUFFER, buffer);
  2793. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoords), texcoords, GL_DYNAMIC_DRAW);
  2794. }
  2795. }
  2796. void CImage::updateGeometryBuffers () {
  2797. const glm::vec2 size = this->resolveGeometrySize ();
  2798. this->m_size = size;
  2799. this->updateScenePosition (size);
  2800. if (this->m_pos != this->m_lastUploadedPos || size != this->m_lastUploadedGeometrySize) {
  2801. this->uploadGeometryBuffers (size);
  2802. if (this->m_hasPuppetMesh) {
  2803. this->updatePuppetPositionBuffer (size);
  2804. }
  2805. this->m_lastUploadedPos = this->m_pos;
  2806. this->m_lastUploadedGeometrySize = size;
  2807. }
  2808. }
  2809. namespace {
  2810. // keeps an edge pair (m_pos.x/.z) from sliding into the visible canvas, so the image never uncovers ground it has no
  2811. // pixels for; images too small to cover the axis move freely and cropped canvas may scroll in. WE has no clamp
  2812. // (sub_14018AAC0)
  2813. float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
  2814. const float low = std::min (edgeA, edgeB);
  2815. const float high = std::max (edgeA, edgeB);
  2816. const float maxOffset = visibleLow - low;
  2817. const float minOffset = visibleHigh - high;
  2818. if (minOffset > maxOffset) {
  2819. return offset;
  2820. }
  2821. // a layer that doesn't cover the screen at rest stays where the scene puts it (3621923790's hair), the clamp
  2822. // only keeps the parallax from uncovering more
  2823. return std::clamp (offset, std::min (minOffset, 0.0f), std::max (maxOffset, 0.0f));
  2824. }
  2825. }
  2826. void CImage::updateScreenSpacePosition () {
  2827. this->updateGeometryBuffers ();
  2828. // WE multiplies the world matrix into the model stack (sub_1401E8AA0), seen here from y down scene space
  2829. const auto& scene = this->getScene ();
  2830. const glm::mat4 flipY = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
  2831. const glm::mat4 toScene = flipY
  2832. * glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene.getWidth () / 2.0f, -scene.getHeight () / 2.0f, 0.0f));
  2833. const glm::mat4 objectModel = this->worldMatrix () * flipY;
  2834. glm::mat4 rotModel = toScene * objectModel;
  2835. glm::mat4 mvp = this->getViewProjection () * rotModel;
  2836. std::optional<std::pair<glm::mat4, glm::mat4>> objectTransform;
  2837. const bool fullscreen = this->getImage ().model->fullscreen;
  2838. const auto& camera = scene.getCamera ();
  2839. // WE draws fullscreen layers with an identity transform, camera movement and parallax don't reach them
  2840. if (fullscreen) {
  2841. rotModel = glm::mat4 (1.0f);
  2842. mvp = camera.getFullscreenProjection ();
  2843. } else if (camera.isPerspective ()) {
  2844. const glm::mat4 viewProjection = this->getImage ().perspective->value->getBool ()
  2845. ? camera.getPerspectiveLayerViewProjection ()
  2846. : scene.getWorldViewProjection ();
  2847. mvp = viewProjection * objectModel;
  2848. objectTransform.emplace (objectModel, viewProjection);
  2849. }
  2850. // CScene::renderFrame() already folds in disableparallax. Ortho scenes only (sub_14018AAC0), outside the rotation
  2851. if (scene.getScene ().camera.parallax.enabled->value->getBool () && !fullscreen && !camera.isPerspective ()) {
  2852. glm::vec2 offset = scene.getParallaxOffset (this->getImage ());
  2853. // a texture that isn't UV-clamped repeats, sliding it further is harmless; scene.json "clampuvs" overrides the
  2854. // texture's flag
  2855. const bool textureTiles = !this->getImage ().clampUVs && this->getTexture () != nullptr
  2856. && (this->getTexture ()->getFlags () & TextureFlags_ClampUVs) == 0;
  2857. if (scene.getContext ().getApp ().getContext ().settings.mouse.clampParallaxToImageSize && !textureTiles) {
  2858. glm::vec2 low (std::numeric_limits<float>::max ());
  2859. glm::vec2 high (std::numeric_limits<float>::lowest ());
  2860. for (const glm::vec2 corner :
  2861. { glm::vec2 (this->m_pos.x, this->m_pos.y), glm::vec2 (this->m_pos.x, this->m_pos.w),
  2862. glm::vec2 (this->m_pos.z, this->m_pos.y), glm::vec2 (this->m_pos.z, this->m_pos.w) }) {
  2863. const glm::vec2 point (rotModel * glm::vec4 (corner, 0.0f, 1.0f));
  2864. low = glm::min (low, point);
  2865. high = glm::max (high, point);
  2866. }
  2867. const glm::vec4 visible = scene.getVisibleCanvasRegion ();
  2868. offset.x = clampParallaxAxis (offset.x, low.x, high.x, visible.x, visible.y);
  2869. offset.y = clampParallaxAxis (offset.y, low.y, high.y, visible.z, visible.w);
  2870. }
  2871. rotModel = glm::translate (glm::mat4 (1.0f), { offset.x, offset.y, 0.0f }) * rotModel;
  2872. mvp = this->getViewProjection () * rotModel;
  2873. }
  2874. this->updateLightingTransform (rotModel, objectTransform, mvp);
  2875. // only the inverse is expensive; skip it when mvp didn't actually change
  2876. if (mvp != this->m_modelViewProjectionScreen) {
  2877. this->m_modelViewProjectionScreenInverse = glm::inverse (mvp);
  2878. }
  2879. this->m_modelViewProjectionScreen = mvp;
  2880. this->m_layerModelMatrix = this->getScene ().objectWorldMatrix (this->getImage ());
  2881. // buffer space (0..size, y = size at m_pos.y like the copy quad) onto the layer's scene quad, then the screen
  2882. const glm::vec2 bufferSize = this->m_size;
  2883. if (bufferSize.x > 0.0f && bufferSize.y > 0.0f) {
  2884. glm::mat4 bufferToScene (1.0f);
  2885. bufferToScene[0][0] = (this->m_pos.z - this->m_pos.x) / bufferSize.x;
  2886. bufferToScene[1][1] = (this->m_pos.y - this->m_pos.w) / bufferSize.y;
  2887. bufferToScene[3][0] = this->m_pos.x;
  2888. bufferToScene[3][1] = this->m_pos.w;
  2889. this->m_effectModelViewProjectionCopy = mvp * bufferToScene;
  2890. // later passes draw WE's unit quad (-1..1), sub_1401EBF60 scales it by half the layer size first
  2891. glm::mat4 unitToBuffer (1.0f);
  2892. unitToBuffer[0][0] = bufferSize.x * 0.5f;
  2893. unitToBuffer[1][1] = bufferSize.y * 0.5f;
  2894. unitToBuffer[3][0] = bufferSize.x * 0.5f;
  2895. unitToBuffer[3][1] = bufferSize.y * 0.5f;
  2896. this->m_effectModelViewProjectionPass = this->m_effectModelViewProjectionCopy * unitToBuffer;
  2897. }
  2898. this->updateEffectTextureProjection ();
  2899. if (this->getImage ().model->passthrough) {
  2900. this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
  2901. this->m_modelViewProjectionCopyInverse = this->m_modelViewProjectionScreenInverse;
  2902. }
  2903. }
  2904. glm::mat4 CImage::getViewProjection () const {
  2905. const auto& camera = this->getScene ().getCamera ();
  2906. // "perspective" layers get their own camera in 2D scenes (sub_1401E8AA0 -> sub_1401E5B60)
  2907. if (camera.isOrthogonal () && this->getImage ().perspective->value->getBool ()) {
  2908. return camera.getPerspectiveLayerViewProjection ();
  2909. }
  2910. return camera.getProjection () * camera.getLookAt ();
  2911. }
  2912. void CImage::updateLightingTransform (
  2913. const glm::mat4& sceneTransform, const std::optional<std::pair<glm::mat4, glm::mat4>>& objectTransform,
  2914. const glm::mat4& screen
  2915. ) {
  2916. const auto width = static_cast<float> (this->getScene ().getWidth ());
  2917. const auto height = static_cast<float> (this->getScene ().getHeight ());
  2918. const glm::mat4 toWorld = glm::scale (
  2919. glm::translate (glm::mat4 (1.0f), glm::vec3 (width / 2.0f, height / 2.0f, 0.0f)), glm::vec3 (1.0f, -1.0f, 1.0f)
  2920. );
  2921. const glm::mat3 flip = glm::mat3 (glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f)));
  2922. // WE's normal matrix: model rows at unit length (sub_1400D8300)
  2923. const auto inverseLength = [] (const float squared) {
  2924. const float estimate = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (squared) >> 1));
  2925. return (1.5f - squared * 0.5f * estimate * estimate) * estimate;
  2926. };
  2927. const glm::mat3 normal
  2928. = objectTransform.has_value () ? glm::mat3 (this->worldMatrix ()) : flip * glm::mat3 (sceneTransform) * flip;
  2929. if (objectTransform.has_value ()) {
  2930. this->m_lightingSceneModel = objectTransform->first;
  2931. this->m_lightingViewProjection = objectTransform->second;
  2932. } else {
  2933. this->m_lightingSceneModel = toWorld * sceneTransform;
  2934. this->m_lightingViewProjection = this->getViewProjection () * glm::inverse (toWorld);
  2935. }
  2936. if (this->getImage ().model->fullscreen) {
  2937. this->m_lightingViewProjection = screen * glm::inverse (this->m_lightingSceneModel);
  2938. }
  2939. for (int axis = 0; axis < 3; axis++) {
  2940. this->m_lightingNormal[axis] = normal[axis] * inverseLength (glm::dot (normal[axis], normal[axis]));
  2941. }
  2942. // the first pass draws into the layer's own buffer, (0, 0) there is the image's top left corner in the scene
  2943. if (this->getImage ().model->passthrough) {
  2944. this->m_lightingCopyModel = this->m_lightingSceneModel;
  2945. return;
  2946. }
  2947. const glm::vec2 size = glm::max (this->getSize (), glm::vec2 (1.0f));
  2948. const glm::mat4 copyToScene = glm::scale (
  2949. glm::translate (glm::mat4 (1.0f), glm::vec3 (this->m_pos.x, this->m_pos.w, 0.0f)),
  2950. glm::vec3 ((this->m_pos.z - this->m_pos.x) / size.x, (this->m_pos.y - this->m_pos.w) / size.y, 1.0f)
  2951. );
  2952. this->m_lightingCopyModel = this->m_lightingSceneModel * copyToScene;
  2953. // prelighting vertices are the puppet's own, moved by half the texture into the buffer (sub_140207B50)
  2954. const glm::mat4 modelToCopy
  2955. = glm::scale (glm::translate (glm::mat4 (1.0f), glm::vec3 (size / 2.0f, 0.0f)), glm::vec3 (1.0f, -1.0f, 1.0f));
  2956. this->m_puppetPrelight.model = this->m_lightingCopyModel * modelToCopy;
  2957. for (int axis = 0; axis < 3; axis++) {
  2958. const glm::vec3 column (this->m_puppetPrelight.model[axis]);
  2959. this->m_puppetPrelight.normal[axis] = column * inverseLength (glm::dot (column, column));
  2960. }
  2961. }
  2962. void CImage::updateEffectTextureProjection () {
  2963. // the final quad puts texcoord (0, 0) at (m_pos.x, m_pos.w), which is the layer's local (-1, +1) corner;
  2964. // the scene FBO is y-flipped against the screen the pointer position is measured on, hence the flip
  2965. const glm::vec3 center ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  2966. const glm::vec3 halfSize ((this->m_pos.z - this->m_pos.x) / 2.0f, (this->m_pos.w - this->m_pos.y) / 2.0f, 1.0f);
  2967. const glm::mat4 projection = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  2968. * this->m_modelViewProjectionScreen * glm::scale (glm::translate (glm::mat4 (1.0f), center), halfSize);
  2969. if (projection == this->m_effectTextureProjection) {
  2970. return;
  2971. }
  2972. this->m_effectTextureProjection = projection;
  2973. // a zero-sized layer has no inverse, keep the last usable one instead of feeding NaNs to the shader
  2974. if (halfSize.x != 0.0f && halfSize.y != 0.0f) {
  2975. this->m_effectTextureProjectionInverse = glm::inverse (projection);
  2976. }
  2977. const glm::vec2 size = this->getSize ();
  2978. this->m_objectSpaceProjectionInverse = glm::scale (glm::mat4 (1.0f), glm::vec3 (size.x / 2.0f, size.y / 2.0f, 1.0f))
  2979. * this->m_effectTextureProjectionInverse;
  2980. }
  2981. const Image& CImage::getImage () const { return this->m_image; }
  2982. void CImage::markAsDependency () { this->m_isDependency = true; }
  2983. bool CImage::copiesForReaders () const {
  2984. return (this->m_readByOtherLayer || this->m_image.renderable.ledSource->value->getBool ())
  2985. && (this->getImage ().visible->value->getBool () || this->m_emitterImageSource);
  2986. }
  2987. glm::vec2 CImage::getSize () const {
  2988. if (this->m_texture == nullptr) {
  2989. return this->getImage ().size;
  2990. }
  2991. // compose layers sample the whole scene, but effect masks map over the layer's own size
  2992. if (this->getImage ().model->passthrough && this->getImage ().size.x > 0.0f && this->getImage ().size.y > 0.0f) {
  2993. return this->getImage ().size;
  2994. }
  2995. // solid layers use a stock white texture, the real footprint is declared by the scene
  2996. if (this->getImage ().model->solidlayer && this->getImage ().size.x > 0.0f && this->getImage ().size.y > 0.0f) {
  2997. return this->getImage ().size;
  2998. }
  2999. return { this->m_texture->getRealWidth (), this->m_texture->getRealHeight () };
  3000. }
  3001. GLuint CImage::getSceneSpacePosition () const { return this->m_sceneSpacePosition; }
  3002. GLuint CImage::getCopySpacePosition () const { return this->m_copySpacePosition; }
  3003. GLuint CImage::getPassSpacePosition () const { return this->m_passSpacePosition; }
  3004. GLuint CImage::getTexCoordCopy () const { return this->m_texcoordCopy; }
  3005. GLuint CImage::getTexCoordPass () const { return this->m_texcoordPass; }
  3006. // sub_1402066A0: texcoords 0.15 texel in from every edge, on the plain draw unless
  3007. // fullscreen/nopadding/passthrough/solidlayer and the last effect pass unless fullscreen/passthrough/solidlayer. Texel
  3008. // = the texture's storage size, else the object's size
  3009. void CImage::uploadSceneTexCoords (const glm::vec4& copy) {
  3010. const auto& model = *this->getImage ().model;
  3011. const auto texture = this->getTexture ();
  3012. const glm::vec2 texel = texture != nullptr ? glm::vec2 (texture->getTextureWidth (0), texture->getTextureHeight (0))
  3013. : glm::trunc (this->getSize ());
  3014. const glm::vec2 inset = 0.15000001f / glm::max (texel, glm::vec2 (1.0f));
  3015. const bool excluded = model.fullscreen || model.passthrough || model.solidlayer;
  3016. const auto upload = [&inset] (GLuint& buffer, glm::vec4 rect, const bool apply) {
  3017. if (apply) {
  3018. rect += glm::vec4 (inset, -inset);
  3019. }
  3020. const GLfloat texcoords[]
  3021. = { rect.x, rect.w, rect.x, rect.y, rect.z, rect.w, rect.z, rect.w, rect.x, rect.y, rect.z, rect.y };
  3022. if (buffer == GL_NONE) {
  3023. glGenBuffers (1, &buffer);
  3024. }
  3025. glBindBuffer (GL_ARRAY_BUFFER, buffer);
  3026. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoords), texcoords, GL_DYNAMIC_DRAW);
  3027. };
  3028. upload (this->m_texcoordDirect, copy, !excluded && !model.nopadding);
  3029. upload (this->m_texcoordFinal, { 0.0f, 0.0f, 1.0f, 1.0f }, !excluded);
  3030. }