CParticle.cpp 197 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190
  1. #include "CParticle.h"
  2. #include "CImage.h"
  3. #include "CMesh.h"
  4. #include "CText.h"
  5. #include "WallpaperEngine/Logging/Log.h"
  6. #include "WallpaperEngine/Maths.h"
  7. #include "WallpaperEngine/Render/Utils/NoiseUtils.h"
  8. #include <GL/glew.h>
  9. #include <algorithm>
  10. #include <chrono>
  11. #include <cmath>
  12. #include <cstdlib>
  13. #include <cstring>
  14. #include <ctime>
  15. #include <limits>
  16. #include <numeric>
  17. extern float g_Time;
  18. extern float g_RealTime;
  19. using namespace WallpaperEngine::Render::Objects;
  20. using namespace WallpaperEngine::Render::Utils;
  21. using namespace WallpaperEngine::Data::Model;
  22. namespace {
  23. EmitterClock startClock (const ParticleEmitter& emitter) {
  24. return { .delay = emitter.delay, .duration = emitter.duration, .pendingBurst = emitter.instantaneous };
  25. }
  26. /** A blend window as sub_1401C2A40 stores it, active only when it changes anything (the loader's blended tags) */
  27. struct BlendWindow {
  28. float inStart;
  29. float inScale;
  30. float outEnd;
  31. float outScale;
  32. bool active;
  33. };
  34. BlendWindow makeBlendWindow (const ParticleBlendWindow& window) {
  35. const float inStart = std::min (window.inStart, window.inEnd - 0.0001f);
  36. const float outEnd = window.outEnd <= window.outStart + 0.0001f ? window.outStart + 0.0001f : window.outEnd;
  37. const float inLength = window.inEnd - inStart;
  38. const float outLength = outEnd - window.outStart;
  39. const bool active = (window.inEnd > 0.01f || window.outStart < 0.99f)
  40. && (window.outStart - window.inEnd > 0.01f || inLength > 0.01f || outLength > 0.01f);
  41. return { inStart, 1.0f / inLength, outEnd, 1.0f / outLength, active };
  42. }
  43. /** sub_14022A530 */
  44. float blendWeight (const BlendWindow& window, const ParticleInstance& p) {
  45. const float life = p.age / p.lifetime;
  46. return std::clamp ((window.outEnd - life) * window.outScale, 0.0f, 1.0f)
  47. * std::clamp ((life - window.inStart) * window.inScale, 0.0f, 1.0f);
  48. }
  49. /** sub_1401D15A0 cases 0xB/0xC: a color moved in HSV by the override color's distance to the reference */
  50. glm::vec3 shiftColor (const glm::vec3& rgb, const glm::vec3& shift) {
  51. const glm::vec3 hsv = WallpaperEngine::Maths::rgbToHsv (rgb);
  52. const float hue = shift.x + hsv.x;
  53. return WallpaperEngine::Maths::hsvToRgb (
  54. glm::vec3 (
  55. hue - std::floor (hue), std::clamp (shift.y + hsv.y, 0.0f, 1.0f), std::clamp (shift.z + hsv.z, 0.0f, 1.0f)
  56. )
  57. );
  58. }
  59. }
  60. CParticle::CParticle (Wallpapers::CScene& scene, const Particle& particle) :
  61. CObject (scene, particle), CRenderable (scene, particle, *particle.material->material),
  62. ScriptableObject (scene, particle), m_particle (particle) {
  63. this->registerProperty ("scale", *particle.scale->value);
  64. this->registerProperty ("angles", *particle.angles->value);
  65. this->registerProperty ("visible", *particle.visible->value);
  66. this->registerProperty ("parallaxDepth", *particle.parallaxDepth->value);
  67. // scripts on the instance override keys run like on any other property (property table sub_14024D940), the
  68. // particle reads the values live
  69. const auto bindOverride = [this] (const std::string& name, const UserSettingUniquePtr& setting) {
  70. if (setting != nullptr) {
  71. this->registerProperty ("instanceoverride." + name, *setting->value);
  72. }
  73. };
  74. const auto& instanceOverride = particle.instanceOverride;
  75. bindOverride ("alpha", instanceOverride.alpha);
  76. bindOverride ("size", instanceOverride.size);
  77. bindOverride ("lifetime", instanceOverride.lifetime);
  78. bindOverride ("rate", instanceOverride.rate);
  79. bindOverride ("speed", instanceOverride.speed);
  80. bindOverride ("count", instanceOverride.count);
  81. bindOverride ("brightness", instanceOverride.brightness);
  82. bindOverride ("colorn", instanceOverride.colorn);
  83. for (size_t i = 0; i < instanceOverride.controlPoints.size (); i++) {
  84. bindOverride ("controlpoint" + std::to_string (i), instanceOverride.controlPoints[i]);
  85. bindOverride ("controlpointangle" + std::to_string (i), instanceOverride.controlPointAngles[i]);
  86. }
  87. this->detectTexture ();
  88. m_worldSpace = (particle.flags & 1) != 0;
  89. if (std::getenv ("LWE_FIXED_TIMESTEP") != nullptr) {
  90. m_rng.seed (static_cast<std::mt19937::result_type> (this->getId ()));
  91. } else {
  92. std::random_device rd;
  93. m_rng.seed (rd ());
  94. }
  95. if (!m_particle.renderers.empty ()) {
  96. const auto& renderer = m_particle.renderers[0];
  97. if (renderer.name == "rope" || renderer.name == "ropetrail") {
  98. m_useRopeRenderer = true;
  99. m_ropeSubdivision = std::clamp (static_cast<int> (renderer.subdivision), 0, 32);
  100. m_ropeUVScale = renderer.uvScale;
  101. m_ropeUVScrolling = renderer.uvScrolling;
  102. if (renderer.name == "ropetrail") {
  103. // clamps from wallpaper64.exe sub_1401C5490
  104. m_useTrailRenderer = true;
  105. m_trailLength = std::max (renderer.length, 0.001f);
  106. m_ropeSegments = std::clamp (static_cast<int> (renderer.segments), 2, 32);
  107. m_ropeSubdivision = std::clamp (static_cast<int> (renderer.subdivision), 0, 32);
  108. m_trailFadeAlpha = renderer.fadeAlpha;
  109. m_trailFadeSize = renderer.fadeSize;
  110. }
  111. } else if (renderer.name == "spritetrail") {
  112. m_useTrailRenderer = true;
  113. m_trailLength = renderer.length;
  114. m_trailMaxLength = renderer.maxLength;
  115. m_trailMinLength = renderer.minLength;
  116. } else {
  117. for (size_t i = 1; i < m_particle.renderers.size (); i++) {
  118. if (const auto& extra = m_particle.renderers[i]; extra.name == "spritetrail") {
  119. m_hasTrailPass = true;
  120. m_extraTrailLength = extra.length;
  121. m_extraTrailMaxLength = extra.maxLength;
  122. m_extraTrailMinLength = extra.minLength;
  123. break;
  124. }
  125. }
  126. }
  127. }
  128. // the pool is maxcount big whatever the count override says, that one only binds emitter rates
  129. // (wallpaper64.exe sub_1401D3780 copies maxcount unscaled, sub_1402378A0 emits while alive < maxcount)
  130. const uint32_t requestedParticles = particle.maxCount > 0 ? particle.maxCount : DEFAULT_MAX_PARTICLES;
  131. const size_t floatsPerParticle = m_useRopeRenderer && m_useTrailRenderer
  132. ? static_cast<size_t> (m_ropeSegments) * 4 * ROPE_FLOATS_PER_VERTEX
  133. : (m_useRopeRenderer ? 4 * ROPE_FLOATS_PER_VERTEX : 4 * SPRITE_FLOATS_PER_VERTEX);
  134. m_maxParticles
  135. = static_cast<uint32_t> (std::min<size_t> ({ requestedParticles, MAX_PARTICLES,
  136. MAX_VERTEX_FLOATS / std::max<size_t> (floatsPerParticle, 1) }));
  137. if (m_maxParticles < requestedParticles) {
  138. sLog.error (
  139. "Particle system ", particle.name, " asks for ", requestedParticles, " particles, using ", m_maxParticles
  140. );
  141. }
  142. m_particles.resize (m_maxParticles);
  143. m_slotUsed.assign (m_maxParticles, 0);
  144. if (m_useRopeRenderer && m_useTrailRenderer) {
  145. const size_t quads = static_cast<size_t> (m_maxParticles) * m_ropeSegments;
  146. m_vertices.resize (quads * 4 * ROPE_FLOATS_PER_VERTEX);
  147. m_indices.resize (quads * 6);
  148. m_trailHistory.resize (static_cast<size_t> (m_maxParticles) * m_ropeSegments);
  149. m_trailCount.resize (m_maxParticles);
  150. m_trailScroll.resize (m_maxParticles);
  151. m_trailInterval = m_trailLength / static_cast<float> (m_ropeSegments);
  152. } else if (m_useRopeRenderer) {
  153. const size_t segments = std::max (1u, m_maxParticles - 1);
  154. m_vertices.resize (segments * 4 * ROPE_FLOATS_PER_VERTEX);
  155. m_indices.resize (segments * 6);
  156. } else {
  157. const int verticesPerParticle = 4;
  158. const int indicesPerParticle = 6;
  159. m_vertices.resize (static_cast<size_t> (m_maxParticles) * verticesPerParticle * SPRITE_FLOATS_PER_VERTEX);
  160. m_indices.resize (static_cast<size_t> (m_maxParticles) * indicesPerParticle);
  161. }
  162. }
  163. CParticle::CParticle (CParticle& parent, const ParticleChild& child) : CParticle (parent.getScene (), *child.particle) {
  164. m_parent = &parent;
  165. m_childDefinition = &child;
  166. m_placement = child.transform;
  167. }
  168. CParticle::~CParticle () {
  169. delete m_pass;
  170. delete m_trailPass;
  171. if (m_trailVao != 0) {
  172. glDeleteVertexArrays (1, &m_trailVao);
  173. }
  174. if (m_vao != 0) {
  175. glDeleteVertexArrays (1, &m_vao);
  176. }
  177. if (m_vbo != 0) {
  178. glDeleteBuffers (1, &m_vbo);
  179. }
  180. if (m_ebo != 0) {
  181. glDeleteBuffers (1, &m_ebo);
  182. }
  183. m_vertices.clear ();
  184. m_indices.clear ();
  185. }
  186. void CParticle::setup () {
  187. if (m_initialized) {
  188. return;
  189. }
  190. if (m_particle.material && m_particle.material->material && !m_particle.material->material->passes.empty ()) {
  191. auto& firstPass = *m_particle.material->material->passes.begin ();
  192. auto overbrightIt = firstPass->constants.find ("ui_editor_properties_overbright");
  193. if (overbrightIt != firstPass->constants.end ()) {
  194. m_overbright = overbrightIt->second->value->getFloat ();
  195. }
  196. }
  197. if (const auto texture = getTexture (); texture && texture->isAnimated ()) {
  198. m_spritesheetFrames = static_cast<int> (texture->getFrames ().size ());
  199. }
  200. // wallpaper64.exe system flag 2: only angularvelocityrandom and angularmovement make angular speed a thing, the
  201. // remap components ignore it otherwise
  202. for (const auto& initializer : m_particle.initializers) {
  203. if (initializer && initializer->is<AngularVelocityRandomInitializer> ()) {
  204. m_hasAngularVelocity = true;
  205. }
  206. }
  207. for (const auto& op : m_particle.operators) {
  208. if (op && op->is<AngularMovementOperator> ()) {
  209. m_hasAngularVelocity = true;
  210. }
  211. }
  212. setupEmitters ();
  213. setupInitializers ();
  214. setupOperators ();
  215. setupPass ();
  216. m_controlPoints.resize (8);
  217. for (const auto& cp : m_particle.controlPoints) {
  218. if (cp.id >= 0 && cp.id < 8) {
  219. auto& point = m_controlPoints[cp.id];
  220. point.offset = cp.offset;
  221. point.linkMouse = (cp.flags & 1) != 0;
  222. point.worldSpace = (cp.flags & 2) != 0;
  223. point.followParent = (cp.flags & 4) != 0;
  224. point.copyUntransformed = (cp.flags & 8) != 0;
  225. point.parentIndex = cp.parentControlPoint;
  226. // sub_14022C3C0 starts every control point as a plain translation to its offset
  227. point.position = point.offset;
  228. if (point.linkMouse) {
  229. m_hasMouseControlPoint = true;
  230. }
  231. }
  232. }
  233. for (size_t i = 0; i < m_controlPoints.size (); i++) {
  234. m_controlPoints[i].remapOutput = (m_particle.remapOutputControlPoints & (1u << i)) != 0;
  235. }
  236. this->updateFrame ();
  237. this->updateControlPoints ();
  238. m_initialized = true;
  239. this->refreshColorOverride ();
  240. this->setupChildren ();
  241. }
  242. bool CParticle::isShown () const {
  243. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  244. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  245. return visibility.value_or (m_particle.visible->value->getBool ());
  246. }
  247. void CParticle::simulate () {
  248. if (!m_initialized) {
  249. return;
  250. }
  251. if (!this->isShown ()) {
  252. // sub_140230650 starts the layer's time over while it is hidden
  253. m_layerTime = 0.0f;
  254. return;
  255. }
  256. const auto playback = this->getPlayback ();
  257. const float currentTime = m_hasMouseControlPoint ? g_RealTime : g_Time;
  258. if (m_time == 0.0) {
  259. if (playback == Playback::Playing) {
  260. this->prewarm (currentTime);
  261. }
  262. m_time = currentTime;
  263. return;
  264. }
  265. float dt = currentTime - static_cast<float> (m_time);
  266. m_time = currentTime;
  267. if (dt > 0.0f) {
  268. dt = std::min (dt, 0.1f);
  269. update (dt);
  270. }
  271. }
  272. void CParticle::render () {
  273. if (!m_initialized || !this->isShown ()) {
  274. return;
  275. }
  276. this->draw (glm::mat4 (1.0f));
  277. }
  278. void CParticle::draw (const glm::mat4& base) {
  279. // sub_140236600 / sub_1402366F0: world space systems draw with the stack's base, everything else multiplies
  280. // its +928 matrix onto what the parent left
  281. const glm::mat4 placement = m_parent == nullptr ? this->objectMatrix () : m_placement;
  282. const glm::mat4 top = m_worldSpace ? base : base * placement;
  283. m_worldModelMatrix = m_worldSpace ? glm::mat4 (1.0f) : top;
  284. m_modelMatrix = this->sceneMatrix () * m_worldModelMatrix;
  285. if (m_particleCount > 0 && m_particle.material) {
  286. if (m_useRopeRenderer) {
  287. renderRope ();
  288. } else {
  289. renderSprites ();
  290. }
  291. }
  292. if (m_staticChildren.empty () && m_eventChildren.empty ()) {
  293. return;
  294. }
  295. // drawn right away, depth first: static children, then event children slot by slot. A world space system
  296. // hands down its raw +928 matrix, for a static child that is only the child transform, not its full frame
  297. const glm::mat4 childBase = m_worldSpace ? placement : top;
  298. for (const auto& child : m_staticChildren) {
  299. child->draw (childBase);
  300. }
  301. for (const auto& slot : m_eventChildren) {
  302. for (const auto& child : slot.active) {
  303. child->draw (childBase);
  304. }
  305. }
  306. }
  307. void CParticle::prewarm (double now) {
  308. if (m_prewarmed || m_particle.startTime <= 0.0f) {
  309. return;
  310. }
  311. m_prewarmed = true;
  312. // wallpaper64.exe sub_14022EBE0: whole fixed steps, coarser ones for big systems, and no child events meanwhile
  313. const float step = m_particle.maxCount < 500 ? 0.05f : 0.2f;
  314. // the longest one installed is 1000 s; a file asking for more (4294967296 never got past 2^25 in the float count)
  315. // would freeze the wallpaper at load
  316. constexpr float MaxStartTime = 3600.0f;
  317. const float startTime = std::min (m_particle.startTime, MaxStartTime);
  318. if (startTime < m_particle.startTime) {
  319. sLog.error ("Particle starttime ", m_particle.startTime, " is too long, using ", MaxStartTime);
  320. }
  321. m_prewarming = true;
  322. m_time = now - startTime;
  323. for (float done = 0.0f; done < startTime; done += step) {
  324. m_time += step;
  325. update (step);
  326. }
  327. m_time = now;
  328. m_prewarming = false;
  329. }
  330. bool CParticle::isPlaying () const {
  331. // sub_14024CA10: never while paused, otherwise while anything still emits or lives, children included
  332. return this->getPlayback () != Playback::Paused && !this->isFinished ();
  333. }
  334. void CParticle::applyPlayback (Playback playback) {
  335. // wallpaper64.exe 2.8.42 IParticleSystem: pause only holds back the emitters (+1719 bit 1, read by sub_1402378A0),
  336. // stop leaves the pause alone
  337. if (playback == Playback::Paused) {
  338. this->setPlayback (Playback::Paused);
  339. return;
  340. }
  341. if (playback == Playback::Playing) {
  342. // sub_14024C5B0: a system with nothing left lets its emitters go again (sub_14022F5B0), their timers stay
  343. this->setPlayback (Playback::Playing);
  344. if (this->isFinished ()) {
  345. this->resumeEmitters ();
  346. }
  347. return;
  348. }
  349. // sub_14024C680: every particle and child gone, the emitters back at their start but finished
  350. this->restart ();
  351. this->finishEmitters ();
  352. }
  353. bool CParticle::emissionPaused () const {
  354. const CParticle* root = this;
  355. while (root->m_parent != nullptr) {
  356. root = root->m_parent;
  357. }
  358. return root->getPlayback () == Playback::Paused;
  359. }
  360. void CParticle::finishEmitters () {
  361. for (auto& clock : m_emitterClocks) {
  362. clock.finished = true;
  363. }
  364. for (const auto& child : m_staticChildren) {
  365. child->finishEmitters ();
  366. }
  367. }
  368. void CParticle::resumeEmitters () {
  369. for (auto& clock : m_emitterClocks) {
  370. clock.finished = false;
  371. }
  372. m_emissionStopped = false;
  373. for (const auto& child : m_staticChildren) {
  374. child->resumeEmitters ();
  375. }
  376. }
  377. void CParticle::emitParticles (int count) {
  378. // sub_14024CAC0: nothing for a negative count. sub_1402378A0 with dt 0 then adds it to every emitter's spawn
  379. // count, paused or not, as long as the pool has room
  380. if (count < 0) {
  381. return;
  382. }
  383. m_forcedEmission = count == 0 ? 1 : static_cast<uint32_t> (count);
  384. const uint32_t firstNew = m_particleCount;
  385. for (auto& emitter : m_emitters) {
  386. emitter (m_particles, m_particleCount, 0.0f);
  387. }
  388. m_forcedEmission = 0;
  389. this->registerNewParticles (firstNew);
  390. }
  391. void CParticle::registerNewParticles (uint32_t firstNew) {
  392. for (uint32_t i = firstNew; i < m_particleCount; i++) {
  393. auto& p = m_particles[i];
  394. p.id = m_nextParticleId++;
  395. // sub_1402378A0 puts a new particle in the lowest free pool slot
  396. const auto freeSlot = std::find (m_slotUsed.begin (), m_slotUsed.end (), 0);
  397. p.slot = static_cast<uint32_t> (freeSlot - m_slotUsed.begin ());
  398. if (freeSlot != m_slotUsed.end ()) {
  399. *freeSlot = 1;
  400. }
  401. m_slotExtent = std::max (m_slotExtent, p.slot + 1);
  402. if (p.slot < m_ghostUsed.size ()) {
  403. m_ghostUsed[p.slot] = 0;
  404. }
  405. // sub_14023B340 end: a new particle's whole trail history starts where it spawned
  406. if (!m_trailHistory.empty ()) {
  407. std::fill_n (
  408. m_trailHistory.begin () + static_cast<std::ptrdiff_t> (i) * m_ropeSegments, m_ropeSegments, p.position
  409. );
  410. m_trailCount[i] = 1;
  411. m_trailScroll[i] = 0;
  412. }
  413. if (m_hasBirthEvents && !m_prewarming) {
  414. m_births.push_back (p.id);
  415. }
  416. }
  417. }
  418. void CParticle::update (float dt) {
  419. const float childDt = dt;
  420. // instanceoverride "rate" scales the whole simulation's time, not only emission (wallpaper64.exe sub_1401B7FF0)
  421. dt *= std::max (0.01f, m_particle.instanceOverride.rate->value->getFloat ());
  422. // prewarming runs the simulation directly, the layer and system clocks only move in real updates
  423. if (!m_prewarming) {
  424. m_systemTime += dt;
  425. if (m_parent == nullptr) {
  426. m_layerTime += dt;
  427. }
  428. }
  429. if (g_RealTime != m_lastRealTime) {
  430. if (m_lastRealTime > 0.0f) {
  431. m_frameDelta = g_RealTime - m_lastRealTime;
  432. }
  433. m_lastRealTime = g_RealTime;
  434. }
  435. this->refreshColorOverride ();
  436. // sub_140236CD0: ages first, so a new particle is drawn at age 0 on its first frame, then control points,
  437. // emission and operators
  438. for (uint32_t i = 0; i < m_particleCount; i++) {
  439. m_particles[i].age += dt;
  440. }
  441. uint32_t writeIdx = 0;
  442. for (uint32_t readIdx = 0; readIdx < m_particleCount; readIdx++) {
  443. if (m_particles[readIdx].isAlive ()) {
  444. if (writeIdx != readIdx) {
  445. m_particles[writeIdx] = m_particles[readIdx];
  446. if (!m_trailHistory.empty ()) {
  447. std::copy_n (
  448. m_trailHistory.begin () + static_cast<std::ptrdiff_t> (readIdx) * m_ropeSegments,
  449. m_ropeSegments,
  450. m_trailHistory.begin () + static_cast<std::ptrdiff_t> (writeIdx) * m_ropeSegments
  451. );
  452. m_trailCount[writeIdx] = m_trailCount[readIdx];
  453. m_trailScroll[writeIdx] = m_trailScroll[readIdx];
  454. }
  455. }
  456. writeIdx++;
  457. } else {
  458. const uint32_t slot = m_particles[readIdx].slot;
  459. if (slot < m_slotUsed.size ()) {
  460. m_slotUsed[slot] = 0;
  461. }
  462. if (slot < m_ghostUsed.size ()) {
  463. m_ghosts[slot] = m_particles[readIdx];
  464. m_ghostUsed[slot] = 1;
  465. }
  466. if (m_hasDeathEvents && !m_prewarming) {
  467. m_deaths.push_back (m_particles[readIdx]);
  468. }
  469. }
  470. }
  471. m_ropeDeaths += m_particleCount - writeIdx;
  472. m_particleCount = writeIdx;
  473. this->updateFrame ();
  474. this->updateControlPoints ();
  475. for (auto& cp : m_controlPoints) {
  476. cp.movement = cp.hasPreviousPosition ? cp.position - cp.previousPosition : glm::vec3 (0.0f);
  477. cp.velocity = cp.hasPreviousPosition && dt > 0.0f ? cp.movement / dt : glm::vec3 (0.0f);
  478. cp.previousPosition = cp.position;
  479. cp.hasPreviousPosition = true;
  480. }
  481. if (!this->emissionPaused () && !m_emissionStopped) {
  482. const uint32_t firstNew = m_particleCount;
  483. for (auto& emitter : m_emitters) {
  484. emitter (m_particles, m_particleCount, dt);
  485. }
  486. this->registerNewParticles (firstNew);
  487. }
  488. // sub_14023FBC0 starts from the spawn values of what a remapvalue writes, and remembers where particles are
  489. // for collisionquad
  490. if (m_resetSizeFromBase || m_resetAlphaFromBase || m_resetColorFromBase || m_tracksPreviousPosition) {
  491. for (uint32_t i = 0; i < m_particleCount; i++) {
  492. auto& p = m_particles[i];
  493. if (m_resetSizeFromBase) {
  494. p.size = p.initial.size;
  495. }
  496. if (m_resetAlphaFromBase) {
  497. p.alpha = p.initial.alpha;
  498. }
  499. if (m_resetColorFromBase) {
  500. p.color = p.initial.color;
  501. }
  502. if (m_tracksPreviousPosition) {
  503. p.previousPosition = p.position;
  504. }
  505. }
  506. }
  507. for (auto& op : m_operators) {
  508. op (m_particles, m_particleCount, m_controlPoints, static_cast<float> (m_time), dt);
  509. }
  510. for (uint32_t i = 0; i < m_particleCount; i++) {
  511. auto& p = m_particles[i];
  512. if (m_spritesheetFrames > 0) {
  513. // sub_140236CD0: frame = age / lifetime * sequencemultiplier, the shader takes frac() of it. WE's loader
  514. // only knows "randomframe", every other mode is this one, and the texture's own frame times are not used
  515. if (m_particle.animationMode == "randomframe") {
  516. if (p.frame < 0.0f) {
  517. std::mt19937 particleRng (
  518. static_cast<std::mt19937::result_type> (i + this->getId () * 2654435761u)
  519. );
  520. std::uniform_int_distribution<int> dist (0, m_spritesheetFrames - 1);
  521. p.frame = static_cast<float> (dist (particleRng));
  522. }
  523. } else {
  524. p.frame
  525. = p.getLifetimePos () * m_particle.sequenceMultiplier * static_cast<float> (m_spritesheetFrames);
  526. }
  527. }
  528. }
  529. // sub_1402308A0: every interval each particle pushes its position to the front of its history. It runs with
  530. // the vertex build, which prewarming skips
  531. if (!m_trailHistory.empty () && !m_prewarming) {
  532. m_trailTimer -= dt;
  533. if (m_trailTimer <= 0.0f) {
  534. m_trailTimer = m_trailInterval;
  535. for (uint32_t i = 0; i < m_particleCount; i++) {
  536. const auto history = m_trailHistory.begin () + static_cast<std::ptrdiff_t> (i) * m_ropeSegments;
  537. std::copy_backward (history, history + m_ropeSegments - 1, history + m_ropeSegments);
  538. *history = m_particles[i].position;
  539. m_trailCount[i] = static_cast<uint16_t> (std::min<int> (m_trailCount[i] + 1, m_ropeSegments));
  540. m_trailScroll[i]++;
  541. }
  542. }
  543. }
  544. // prewarming leaves children alone, static ones prewarm on their own when created
  545. if (!m_prewarming) {
  546. this->updateChildren (childDt);
  547. }
  548. }
  549. void CParticle::refreshColorOverride () {
  550. const auto& instanceOverride = m_particle.instanceOverride;
  551. const glm::vec3 color = instanceOverride.colorn->value->getVec3 ();
  552. const glm::vec3 distance = glm::abs (m_particle.colorReference - color);
  553. // children only follow it while their parent does
  554. m_colorOverride.active = (instanceOverride.hasColor || m_scriptColor) && color.r >= 0.0f
  555. && (m_particle.flags & 8) == 0
  556. && (distance.x >= 0.0035294117f || distance.y >= 0.0035294117f || distance.z >= 0.0035294117f)
  557. && (m_parent == nullptr || m_parent->m_colorOverride.active);
  558. // sub_1401D15A0: the spawn color starts at the brightness override (HDR scene rendering only, not with particle
  559. // flag 8). A file without a color initializer, or any scene before version 5, also multiplies by the color
  560. const float brightness
  561. = getScene ().isHDR () && (m_particle.flags & 8) == 0 ? instanceOverride.brightness->value->getFloat () : 1.0f;
  562. m_colorOverride.tint
  563. = (m_colorOverride.active && m_particle.overrideColorTints ? color : glm::vec3 (1.0f)) * brightness;
  564. if (m_colorOverride.active) {
  565. m_colorOverride.hsv = WallpaperEngine::Maths::rgbToHsv (color);
  566. m_colorOverride.shift = m_colorOverride.hsv - WallpaperEngine::Maths::rgbToHsv (m_particle.colorReference);
  567. }
  568. }
  569. void CParticle::setupChildren () {
  570. for (const auto& child : m_particle.children) {
  571. if (child.particle == nullptr) {
  572. continue;
  573. }
  574. if (child.type == ParticleChildType::Static) {
  575. std::unique_ptr<CParticle> instance (new CParticle (*this, child));
  576. instance->setup ();
  577. instance->prewarm (m_time);
  578. m_staticChildren.push_back (std::move (instance));
  579. continue;
  580. }
  581. m_eventChildren.push_back (EventChildSlot { .child = &child, .active = {}, .pool = {} });
  582. m_hasBirthEvents |= child.type != ParticleChildType::EventDeath;
  583. m_hasDeathEvents |= child.type == ParticleChildType::EventDeath;
  584. }
  585. }
  586. const ParticleInstance* CParticle::findParticle (uint32_t id) const {
  587. const auto end = m_particles.begin () + m_particleCount;
  588. const auto it = std::lower_bound (m_particles.begin (), end, id, [] (const ParticleInstance& p, uint32_t value) {
  589. return p.id < value;
  590. });
  591. return it != end && it->id == id ? &*it : nullptr;
  592. }
  593. void CParticle::placeChild (const glm::mat4& placement) { m_placement = placement; }
  594. glm::mat4 CParticle::eventPlacement (const ParticleChild& child, const glm::vec3& position) const {
  595. // particle positions are in this system's frame, or the world when it is world space; the child's +928
  596. // matrix is relative to this frame, or the world when the child is world space
  597. const glm::mat4 placement = glm::translate (glm::mat4 (1.0f), position) * child.transform;
  598. const bool childWorldSpace = (child.particle->flags & 1) != 0;
  599. if (childWorldSpace == m_worldSpace) {
  600. return placement;
  601. }
  602. return childWorldSpace ? m_frame * placement : glm::inverse (m_frame) * placement;
  603. }
  604. glm::mat4 CParticle::objectMatrix () const {
  605. // WE's world matrix, parent chain included: particles parented to a layer or group move and scale with it
  606. glm::mat4 matrix = getScene ().objectWorldMatrix (m_particle);
  607. // ortho scenes only (sub_14018AAC0), disableparallax is already folded in
  608. if (getScene ().getScene ().camera.parallax.enabled->value->getBool ()
  609. && !getScene ().getCamera ().isPerspective ()) {
  610. const glm::vec2 offset = getScene ().getParallaxOffset (m_particle);
  611. matrix = glm::translate (glm::mat4 (1.0f), glm::vec3 (offset.x, -offset.y, 0.0f)) * matrix;
  612. }
  613. return matrix;
  614. }
  615. glm::mat4 CParticle::sceneMatrix () const {
  616. if (getScene ().getCamera ().isPerspective ()) {
  617. return glm::mat4 (1.0f);
  618. }
  619. return glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  620. * glm::translate (
  621. glm::mat4 (1.0f),
  622. glm::vec3 (
  623. static_cast<float> (-getScene ().getWidth ()) / 2.0f,
  624. static_cast<float> (-getScene ().getHeight ()) / 2.0f, 0.0f
  625. )
  626. );
  627. }
  628. void CParticle::updateFrame () {
  629. if (m_parent == nullptr) {
  630. m_placement = this->objectMatrix ();
  631. m_frame = m_placement;
  632. } else if (m_worldSpace && m_childDefinition->type != ParticleChildType::Static) {
  633. // sub_140229760 replaces the stack top for world space systems
  634. m_frame = m_placement;
  635. } else {
  636. // static children go through sub_140229810, which always multiplies
  637. m_frame = m_parent->m_frame * m_placement;
  638. }
  639. }
  640. void CParticle::updateControlPoints () {
  641. const glm::mat4 toLocal = glm::inverse (m_frame);
  642. const bool takesParentParticles = m_childDefinition != nullptr && (m_childDefinition->flags & 1) != 0;
  643. const int firstParticlePoint = m_childDefinition != nullptr ? m_childDefinition->controlPointStartIndex : 0;
  644. for (size_t i = 0; i < m_controlPoints.size (); i++) {
  645. auto& cp = m_controlPoints[i];
  646. if (cp.remapOutput) {
  647. continue;
  648. }
  649. if (cp.linkMouse) {
  650. // the cursor through the scene camera replaces the point's translation, its offset plays no part
  651. const glm::vec3 position
  652. = glm::vec3 (glm::inverse (this->sceneMatrix ()) * glm::vec4 (getScene ().unprojectCursor (), 1.0f));
  653. cp.position = m_worldSpace ? glm::vec3 (position.x, position.y, 0.0f)
  654. : glm::vec3 (toLocal * glm::vec4 (position, 1.0f));
  655. continue;
  656. }
  657. if (cp.followParent && m_parent != nullptr && cp.parentIndex >= 0
  658. && cp.parentIndex < static_cast<int> (m_parent->m_controlPoints.size ())) {
  659. const auto& source = m_parent->m_controlPoints[cp.parentIndex];
  660. glm::mat4 matrix (source.orientation);
  661. matrix[3] = glm::vec4 (source.position, 1.0f);
  662. if (!cp.copyUntransformed && !(m_worldSpace && m_parent->m_worldSpace)) {
  663. if (m_worldSpace) {
  664. matrix = m_parent->m_frame * matrix;
  665. } else if (m_parent->m_worldSpace) {
  666. matrix = toLocal * matrix;
  667. } else {
  668. matrix = toLocal * m_parent->m_frame * matrix;
  669. }
  670. }
  671. cp.orientation = glm::mat3 (matrix);
  672. cp.position = glm::vec3 (matrix[3]);
  673. continue;
  674. }
  675. // the parent's particles own these (sub_14022A580)
  676. if (!cp.followParent && takesParentParticles && static_cast<int> (i) >= firstParticlePoint) {
  677. continue;
  678. }
  679. // sub_14022A070: the point's local matrix (its offset, or what the instance override made of it) is local
  680. // unless flag 2 says world, and the point lives in the system's space. Control point 0 of a world space system
  681. // always counts as local
  682. const glm::mat4 local = localControlPointMatrix (i);
  683. glm::mat4 matrix;
  684. if (m_worldSpace) {
  685. matrix = cp.worldSpace && i != 0 ? local : m_frame * local;
  686. } else {
  687. matrix = cp.worldSpace ? toLocal * local : local;
  688. }
  689. cp.orientation = glm::mat3 (matrix);
  690. cp.position = glm::vec3 (matrix[3]);
  691. }
  692. }
  693. void CParticle::spawnEventChildren (ParticleChildType type, const ParticleInstance& particle, bool alive) {
  694. for (auto& slot : m_eventChildren) {
  695. const auto& child = *slot.child;
  696. if (child.type != type || slot.active.size () >= static_cast<size_t> (std::max (0, child.maxCount))) {
  697. continue;
  698. }
  699. if (WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) > child.probability) {
  700. continue;
  701. }
  702. const glm::mat4 placement = this->eventPlacement (child, particle.position);
  703. std::unique_ptr<CParticle> instance;
  704. if (!slot.pool.empty ()) {
  705. instance = std::move (slot.pool.back ());
  706. slot.pool.pop_back ();
  707. instance->placeChild (placement);
  708. instance->restart ();
  709. } else {
  710. instance.reset (new CParticle (*this, child));
  711. instance->m_placement = placement;
  712. instance->setup ();
  713. }
  714. // the inherit components read the event's particle from the first emission on, prewarm included
  715. instance->m_eventId = alive ? std::optional<uint32_t> (particle.id) : std::nullopt;
  716. instance->m_eventParticle = particle;
  717. instance->m_hasEventParticle = true;
  718. instance->m_following = type == ParticleChildType::EventFollow;
  719. instance->m_time = m_time;
  720. instance->prewarm (m_time);
  721. slot.active.push_back (std::move (instance));
  722. }
  723. }
  724. void CParticle::passControlPoints (CParticle& child, const ParticleChild& definition) const {
  725. // sub_14022A580: child flags bit 0 hands the parent's particles to the control points from the start index on,
  726. // one each in order. WE never gets past a control point that follows the cursor or the parent or that a remap
  727. // component owns (flags & 0x10005)
  728. if ((definition.flags & 1) == 0) {
  729. return;
  730. }
  731. // only the space switch through this system's frame, WE doesn't undo the child's own placement
  732. glm::mat4 transform (1.0f);
  733. if (m_worldSpace && !child.m_worldSpace) {
  734. transform = glm::inverse (m_frame);
  735. } else if (!m_worldSpace && child.m_worldSpace) {
  736. transform = m_frame;
  737. }
  738. auto& points = child.m_controlPoints;
  739. int index = std::max (0, definition.controlPointStartIndex);
  740. if (index >= static_cast<int> (points.size ()) || m_particleCount == 0) {
  741. return;
  742. }
  743. // WE walks its particle pool slot by slot, so the particles go out in slot order, not by age
  744. std::vector<uint32_t> order (m_particleCount);
  745. std::iota (order.begin (), order.end (), 0u);
  746. const size_t wanted = std::min<size_t> (order.size (), points.size () - index);
  747. std::partial_sort (
  748. order.begin (), order.begin () + static_cast<long> (wanted), order.end (),
  749. [this] (uint32_t a, uint32_t b) { return m_particles[a].slot < m_particles[b].slot; }
  750. );
  751. for (size_t n = 0; n < wanted; n++) {
  752. auto& cp = points[index];
  753. if (cp.linkMouse || cp.followParent || cp.remapOutput) {
  754. break;
  755. }
  756. cp.position = glm::vec3 (transform * glm::vec4 (m_particles[order[n]].position, 1.0f));
  757. index++;
  758. }
  759. }
  760. void CParticle::updateChildren (float dt) {
  761. for (const auto& child : m_staticChildren) {
  762. this->passControlPoints (*child, *child->m_childDefinition);
  763. child->m_time += dt;
  764. child->update (dt);
  765. }
  766. if (m_eventChildren.empty ()) {
  767. return;
  768. }
  769. // wallpaper64.exe sub_140236CD0 (deaths) and the end of sub_1402378A0 (births)
  770. for (const auto& particle : m_deaths) {
  771. this->spawnEventChildren (ParticleChildType::EventDeath, particle, false);
  772. }
  773. m_deaths.clear ();
  774. for (const uint32_t id : m_births) {
  775. if (const auto* p = this->findParticle (id)) {
  776. const ParticleInstance particle = *p;
  777. this->spawnEventChildren (ParticleChildType::EventFollow, particle, true);
  778. this->spawnEventChildren (ParticleChildType::EventSpawn, particle, true);
  779. }
  780. }
  781. m_births.clear ();
  782. // sub_1402308A0: followers move with their particle, once it dies they stop emitting and fade out,
  783. // and finished instances go back to the pool
  784. for (auto& slot : m_eventChildren) {
  785. for (auto it = slot.active.begin (); it != slot.active.end ();) {
  786. CParticle& child = **it;
  787. if (child.m_eventId.has_value ()) {
  788. if (const auto* p = this->findParticle (*child.m_eventId)) {
  789. child.m_eventParticle = *p;
  790. if (child.m_following) {
  791. child.placeChild (this->eventPlacement (*slot.child, p->position));
  792. }
  793. } else {
  794. child.m_eventId.reset ();
  795. if (child.m_following) {
  796. child.m_emissionStopped = true;
  797. }
  798. }
  799. }
  800. this->passControlPoints (child, *slot.child);
  801. child.m_time += dt;
  802. child.update (dt);
  803. if (child.isFinished ()) {
  804. slot.pool.push_back (std::move (*it));
  805. it = slot.active.erase (it);
  806. } else {
  807. ++it;
  808. }
  809. }
  810. }
  811. }
  812. void CParticle::clearEventChildren () {
  813. for (auto& slot : m_eventChildren) {
  814. for (auto& child : slot.active) {
  815. slot.pool.push_back (std::move (child));
  816. }
  817. slot.active.clear ();
  818. }
  819. m_births.clear ();
  820. m_deaths.clear ();
  821. }
  822. void CParticle::restart () {
  823. m_particleCount = 0;
  824. m_ropeDeaths = 0;
  825. std::fill (m_slotUsed.begin (), m_slotUsed.end (), 0);
  826. std::fill (m_ghostUsed.begin (), m_ghostUsed.end (), 0);
  827. m_slotExtent = 0;
  828. m_systemTime = 0.0f;
  829. m_emitters.clear ();
  830. setupEmitters ();
  831. m_emissionStopped = false;
  832. m_prewarmed = false;
  833. m_eventId.reset ();
  834. m_hasEventParticle = false;
  835. m_following = false;
  836. for (auto& cp : m_controlPoints) {
  837. cp.hasPreviousPosition = false;
  838. }
  839. for (auto& counter : m_sequences) {
  840. counter.sequence = 0.0f;
  841. }
  842. for (const auto& child : m_staticChildren) {
  843. child->restart ();
  844. }
  845. this->clearEventChildren ();
  846. }
  847. void CParticle::restartEmission () {
  848. m_systemTime = 0.0f;
  849. m_emitterClocks.clear ();
  850. for (const auto& emitter : m_particle.emitters) {
  851. if (emitter.name == "boxrandom" || emitter.name == "sphererandom" || emitter.name == "layerimage") {
  852. m_emitterClocks.push_back (startClock (emitter));
  853. }
  854. }
  855. m_emissionStopped = false;
  856. for (auto& counter : m_sequences) {
  857. counter.sequence = 0.0f;
  858. }
  859. for (const auto& child : m_staticChildren) {
  860. child->restartEmission ();
  861. }
  862. }
  863. void CParticle::startEmitterPeriod () {
  864. // static children with child flag 2 start emitting over, the particles already out stay
  865. for (const auto& child : m_staticChildren) {
  866. if ((child->m_childDefinition->flags & 2) != 0) {
  867. child->restartEmission ();
  868. }
  869. }
  870. for (auto& counter : m_sequences) {
  871. if (counter.periodReset) {
  872. counter.sequence = 0.0f;
  873. }
  874. }
  875. }
  876. bool CParticle::isFinished () const {
  877. if (m_particleCount > 0 || (!m_emissionStopped && !this->emittersExhausted ())) {
  878. return false;
  879. }
  880. for (const auto& child : m_staticChildren) {
  881. if (!child->isFinished ()) {
  882. return false;
  883. }
  884. }
  885. for (const auto& slot : m_eventChildren) {
  886. if (!slot.active.empty ()) {
  887. return false;
  888. }
  889. }
  890. return true;
  891. }
  892. DynamicValue* CParticle::emitterCountOverride () const {
  893. // wallpaper64.exe sub_1401C5490 binds the instanceoverride count to every emitter's rate, speed to its
  894. // speedmin/speedmax, unless particle flag 0x20 / 0x10
  895. return (m_particle.flags & 0x20) == 0 ? m_particle.instanceOverride.count->value.get () : nullptr;
  896. }
  897. bool CParticle::emittersExhausted () const {
  898. return std::all_of (m_emitterClocks.begin (), m_emitterClocks.end (), [] (const EmitterClock& clock) {
  899. return clock.finished;
  900. });
  901. }
  902. const Particle& CParticle::getParticle () const { return m_particle; }
  903. const float& CParticle::getBrightness () const { return m_overbright; }
  904. const float& CParticle::getUserAlpha () const { return m_particle.instanceOverride.alpha->value->getFloat (); }
  905. const float& CParticle::getAlpha () const { return m_particle.instanceOverride.alpha->value->getFloat (); }
  906. const glm::vec3& CParticle::getColor () const {
  907. static const glm::vec3 defaultColor (1.0f);
  908. if (m_particle.instanceOverride.color && m_particle.instanceOverride.color->value) {
  909. return m_particle.instanceOverride.color->value->getVec3 ();
  910. }
  911. return defaultColor;
  912. }
  913. const glm::vec4& CParticle::getColor4 () const {
  914. static const glm::vec4 defaultColor (1.0f);
  915. if (m_particle.instanceOverride.color && m_particle.instanceOverride.color->value) {
  916. return m_particle.instanceOverride.color->value->getVec4 ();
  917. }
  918. return defaultColor;
  919. }
  920. const glm::vec3& CParticle::getCompositeColor () const { return getColor (); }
  921. void CParticle::setupEmitters () {
  922. m_emitterClocks.clear ();
  923. m_imageEmitters.clear ();
  924. for (const auto& emitter : m_particle.emitters) {
  925. EmitterFunc func;
  926. if (emitter.name == "boxrandom") {
  927. func = createBoxEmitter (emitter);
  928. } else if (emitter.name == "sphererandom") {
  929. func = createSphereEmitter (emitter);
  930. } else if (emitter.name == "layerimage") {
  931. func = createImageEmitter (emitter);
  932. } else {
  933. sLog.out ("Unknown emitter type: ", emitter.name);
  934. continue;
  935. }
  936. if (func) {
  937. m_emitterClocks.push_back (startClock (emitter));
  938. m_emitters.push_back (std::move (func));
  939. }
  940. }
  941. }
  942. uint32_t CParticle::emitCount (EmitterClock& clock, const ParticleEmitter& emitter, float dt) {
  943. // wallpaper64.exe sub_1402378A0. The count override is bound to rate and maxtoemitperperiod at load
  944. // (sub_1401C5490, type 2 float and type 1 int bindings), not with particle flag 0x20
  945. DynamicValue* countOverride = this->emitterCountOverride ();
  946. const float count = countOverride != nullptr ? countOverride->getFloat () : 1.0f;
  947. const float rate = emitter.rate * count;
  948. const int maxPerPeriod = countOverride != nullptr
  949. ? static_cast<int> (static_cast<float> (emitter.maxToEmitPerPeriod) * count)
  950. : emitter.maxToEmitPerPeriod;
  951. const bool periodic = (emitter.flags & 4) != 0;
  952. const bool room = m_particleCount < m_particles.size ();
  953. // emitParticles () spawns its count whatever state the emitter is in, the pool only has to have room
  954. uint32_t toEmit = room ? m_forcedEmission : 0;
  955. if (!clock.finished && room && clock.delay <= 0.0f && !this->emissionPaused () && !m_emissionStopped) {
  956. float emitRate = rate;
  957. if (emitter.audioProcessingMode != 0) {
  958. emitRate *= sampleAudio (
  959. emitter.audioProcessingMode, emitter.audioProcessingBounds, emitter.audioProcessingExponent,
  960. emitter.audioProcessingFrequencyStart, emitter.audioProcessingFrequencyEnd
  961. );
  962. }
  963. if (periodic) {
  964. // the loader clamps both minimums to their maximum (sub_1401C1C70)
  965. if (clock.period <= 0.0f) {
  966. clock.period += dt;
  967. if (clock.period < 0.0f) {
  968. emitRate = 0.0f;
  969. } else {
  970. const float minDuration = std::min (emitter.minPeriodicDuration, emitter.maxPeriodicDuration);
  971. clock.period = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f)
  972. * (emitter.maxPeriodicDuration - minDuration)
  973. + minDuration;
  974. clock.pendingBurst = emitter.instantaneous;
  975. clock.emittedInPeriod = 0;
  976. this->startEmitterPeriod ();
  977. }
  978. } else {
  979. clock.period -= dt;
  980. if (clock.period < 0.0f) {
  981. const float minDelay = std::min (emitter.minPeriodicDelay, emitter.maxPeriodicDelay);
  982. clock.period
  983. = -(WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f)
  984. * (emitter.maxPeriodicDelay - minDelay)
  985. + minDelay);
  986. }
  987. }
  988. }
  989. toEmit += clock.pendingBurst;
  990. clock.pendingBurst = 0;
  991. // WE takes the burst off the accumulator too, so an instantaneous burst holds the rate back
  992. const float accumulated = emitRate * dt + clock.accumulator;
  993. if (accumulated < 1.0f || clock.duration < 0.0f) {
  994. clock.accumulator = accumulated - static_cast<float> (toEmit);
  995. } else {
  996. int n = static_cast<int> (std::floor (accumulated));
  997. clock.accumulator = accumulated - static_cast<float> (n + static_cast<int> (toEmit));
  998. if ((emitter.flags & 2) != 0) {
  999. n = std::min (n, 1);
  1000. }
  1001. if (periodic && maxPerPeriod != 0) {
  1002. n = std::min (std::max (maxPerPeriod - clock.emittedInPeriod, 0), n);
  1003. clock.emittedInPeriod += n;
  1004. }
  1005. toEmit += static_cast<uint32_t> (std::max (n, 0));
  1006. }
  1007. }
  1008. // after the spawn: the delay runs down first, then the duration. Without a duration an emitter stops
  1009. // right away unless it has a rate or a periodic burst
  1010. if (clock.delay > 0.0f) {
  1011. clock.delay -= dt;
  1012. } else if (clock.duration <= 0.0f) {
  1013. if (!(rate > 0.0f || (emitter.instantaneous != 0 && periodic))) {
  1014. clock.finished = true;
  1015. }
  1016. } else {
  1017. clock.duration -= dt;
  1018. if (clock.duration <= 0.0f) {
  1019. clock.duration = -1.0f;
  1020. clock.finished = true;
  1021. }
  1022. }
  1023. return std::min<uint32_t> (toEmit, static_cast<uint32_t> (m_particles.size ()) - m_particleCount);
  1024. }
  1025. float CParticle::sampleAudio (
  1026. int mode, const glm::vec2& bounds, float exponent, int frequencyStart, int frequencyEnd
  1027. ) const {
  1028. // same curve as wallpaper64.exe: modes 1/2/3 read left, right or (left + right) / 2 of the 16 band buffer
  1029. if (mode == 0) {
  1030. return 1.0f;
  1031. }
  1032. int first = std::clamp (frequencyStart, 0, 15);
  1033. int last = std::clamp (frequencyEnd, 0, 15);
  1034. if (last < first) {
  1035. std::swap (first, last);
  1036. }
  1037. const auto& recorder = this->getScene ().getAudioContext ().getRecorder ();
  1038. float peak = 0.0f;
  1039. const float* left = recorder.audio16;
  1040. const float* right = recorder.audio16 + 16;
  1041. for (int i = first; i <= last; i++) {
  1042. if (mode == 1) {
  1043. peak = std::max (peak, left[i]);
  1044. } else if (mode == 2) {
  1045. peak = std::max (peak, right[i]);
  1046. } else if (mode == 3) {
  1047. peak = std::max (peak, (left[i] + right[i]) * 0.5f);
  1048. }
  1049. }
  1050. float t = (peak - bounds.x) / (bounds.y - bounds.x);
  1051. // NaN from equal bounds ends up as 0 like the original
  1052. t = t >= 1.0f ? 1.0f : (t >= 0.0f ? t : 0.0f);
  1053. const float response = std::pow (t * t * (3.0f - 2.0f * t), exponent);
  1054. return response >= 1.0f ? 1.0f : (response >= 0.0f ? response : 0.0f);
  1055. }
  1056. int CParticle::emitterControlPoint (const ParticleEmitter& emitter) const {
  1057. if (emitter.controlPoint == -1 && !m_particle.controlPoints.empty ()
  1058. && (m_particle.controlPoints[0].flags & 1) != 0) {
  1059. return 0;
  1060. }
  1061. return emitter.controlPoint;
  1062. }
  1063. const ControlPointData* CParticle::controlPointAt (int index) const {
  1064. return index >= 0 && index < static_cast<int> (m_controlPoints.size ()) ? &m_controlPoints[index] : nullptr;
  1065. }
  1066. void CParticle::startSpawn (ParticleInstance& p, const glm::vec3& color, float lifetime) {
  1067. p.acceleration = glm::vec3 (0.0f);
  1068. p.rotation = glm::vec3 (0.0f);
  1069. p.angularVelocity = glm::vec3 (0.0f);
  1070. p.angularAcceleration = glm::vec3 (0.0f);
  1071. p.color = color;
  1072. p.alpha = 1.0f * m_particle.instanceOverride.alpha->value->getFloat ();
  1073. // sub_14023B340: new slots start at size 0.5, lifetime 1; instanceoverride only scales the randoms
  1074. p.size = 0.5f;
  1075. p.lifetime = lifetime;
  1076. p.age = 0.0f;
  1077. p.alive = true;
  1078. p.frame = -1.0f;
  1079. p.seed = m_usesParticleSeed ? WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) : 0.0f;
  1080. p.initial.color = p.color;
  1081. p.initial.alpha = p.alpha;
  1082. p.initial.size = p.size;
  1083. p.initial.lifetime = p.lifetime;
  1084. // sub_14023B340 starts the step collisionquad looks at where the emitter put the particle
  1085. p.previousPosition = p.position;
  1086. }
  1087. EmitterFunc CParticle::createBoxEmitter (const ParticleEmitter& emitter) {
  1088. const int controlPointIndex = this->emitterControlPoint (emitter);
  1089. const size_t clockIndex = m_emitters.size ();
  1090. return [this, emitter, controlPointIndex,
  1091. clockIndex] (std::vector<ParticleInstance>& particles, uint32_t& count, float dt) {
  1092. const uint32_t toEmit = this->emitCount (m_emitterClocks[clockIndex], emitter, dt);
  1093. for (uint32_t i = 0; i < toEmit && count < particles.size (); i++) {
  1094. auto& p = particles[count];
  1095. const ControlPointData* cp = this->controlPointAt (controlPointIndex);
  1096. // sub_1402378A0 box emitter: u = (2 rand - 1) * directions per axis, then
  1097. // pos = sign (u) * (|u| * (distancemax - distancemin) + distancemin)
  1098. glm::vec3 randomPos;
  1099. for (int axis = 0; axis < 3; axis++) {
  1100. const float u = (WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * 2.0f - 1.0f)
  1101. * emitter.directions[axis];
  1102. const float sign = u > 0.0f ? 1.0f : (u < 0.0f ? -1.0f : 0.0f);
  1103. randomPos[axis] = sign
  1104. * (std::abs (u) * (emitter.distanceMax[axis] - emitter.distanceMin[axis])
  1105. + emitter.distanceMin[axis]);
  1106. }
  1107. this->placeSpawn (p, cp, controlPointIndex, emitter.origin, randomPos);
  1108. p.velocity = glm::vec3 (0.0f);
  1109. this->startSpawn (p, m_colorOverride.tint, 1.0f);
  1110. for (auto& init : m_initializers) {
  1111. init (p);
  1112. }
  1113. count++;
  1114. }
  1115. };
  1116. }
  1117. namespace {
  1118. /** RGBA8 readback sampled like WE's D3D sampler for its flags */
  1119. struct ReadbackTexture {
  1120. std::vector<uint8_t> data;
  1121. int width = 0;
  1122. int height = 0;
  1123. glm::vec2 realScale { 1.0f };
  1124. bool clamp = true;
  1125. bool point = false;
  1126. explicit ReadbackTexture (const TextureProvider& texture) {
  1127. width = static_cast<int> (texture.getTextureWidth (0));
  1128. height = static_cast<int> (texture.getTextureHeight (0));
  1129. if (width <= 0 || height <= 0) {
  1130. return;
  1131. }
  1132. realScale = glm::vec2 (texture.getRealWidth (), texture.getRealHeight ()) / glm::vec2 (width, height);
  1133. clamp = (texture.getFlags () & TextureFlags_ClampUVs) != 0;
  1134. point = (texture.getFlags () & TextureFlags_NoInterpolation) != 0;
  1135. data.resize (static_cast<size_t> (width) * height * 4);
  1136. glBindTexture (GL_TEXTURE_2D, texture.getTextureID (0));
  1137. glPixelStorei (GL_PACK_ALIGNMENT, 1);
  1138. glGetTexImage (GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data ());
  1139. }
  1140. [[nodiscard]] bool empty () const { return data.empty (); }
  1141. [[nodiscard]] glm::vec4 texel (int x, int y) const {
  1142. if (clamp) {
  1143. x = std::clamp (x, 0, width - 1);
  1144. y = std::clamp (y, 0, height - 1);
  1145. } else {
  1146. x = ((x % width) + width) % width;
  1147. y = ((y % height) + height) % height;
  1148. }
  1149. const uint8_t* p = &data[(static_cast<size_t> (y) * width + x) * 4];
  1150. return glm::vec4 (p[0], p[1], p[2], p[3]) / 255.0f;
  1151. }
  1152. [[nodiscard]] glm::vec4 sample (glm::vec2 uv) const {
  1153. const glm::vec2 at = uv * realScale * glm::vec2 (width, height);
  1154. if (point) {
  1155. const glm::ivec2 base = glm::floor (at);
  1156. return texel (base.x, base.y);
  1157. }
  1158. const glm::vec2 shifted = at - 0.5f;
  1159. const glm::ivec2 base = glm::floor (shifted);
  1160. const glm::vec2 f = shifted - glm::vec2 (base);
  1161. return glm::mix (
  1162. glm::mix (texel (base.x, base.y), texel (base.x + 1, base.y), f.x),
  1163. glm::mix (texel (base.x, base.y + 1), texel (base.x + 1, base.y + 1), f.x), f.y
  1164. );
  1165. }
  1166. };
  1167. }
  1168. void CParticle::downsampleLayerBuffer (ImageEmitter& state, const CFBO& buffer) {
  1169. // sub_1401D3AE0: quarter size (max 3840x2160) downsample_quarter with WRITEALPHA/OPACITYMASK, read back next frame,
  1170. // pixels at least half opaque relative to the buffer's center
  1171. state.staged.clear ();
  1172. const int width = static_cast<uint16_t> (buffer.getRealWidth ());
  1173. const int height = static_cast<uint16_t> (buffer.getRealHeight ());
  1174. state.stagedSize = glm::ivec2 (width, height);
  1175. if (width < 1 || height < 1) {
  1176. return;
  1177. }
  1178. int cappedWidth = width;
  1179. int cappedHeight = height;
  1180. if (width > 0xF00 || height > 0x870) {
  1181. const float aspect = static_cast<float> (width) / static_cast<float> (height);
  1182. if (aspect < 1.7777778f) {
  1183. cappedHeight = 2160;
  1184. cappedWidth = static_cast<int> (aspect * 2160.0f);
  1185. } else {
  1186. cappedWidth = 3840;
  1187. cappedHeight = static_cast<int> (3840.0f / aspect);
  1188. }
  1189. }
  1190. const int columns = std::max (2, cappedWidth / 4);
  1191. const int rows = std::max (2, cappedHeight / 4);
  1192. const float scale = static_cast<float> (width) / static_cast<float> (columns);
  1193. const ReadbackTexture source (buffer);
  1194. if (source.empty ()) {
  1195. return;
  1196. }
  1197. std::optional<ReadbackTexture> mask;
  1198. if (state.mask != nullptr) {
  1199. mask.emplace (*state.mask);
  1200. if (mask->empty ()) {
  1201. mask.reset ();
  1202. }
  1203. }
  1204. const glm::vec2 step = 2.0f / glm::vec2 (source.width, source.height);
  1205. const auto unorm
  1206. = [] (float value) { return static_cast<uint8_t> (std::clamp (value * 255.0f + 0.5f, 0.0f, 255.0f)); };
  1207. for (int x = 0; x < columns; x++) {
  1208. for (int y = 0; y < rows; y++) {
  1209. const glm::vec2 uv (
  1210. (static_cast<float> (x) + 0.5f) / static_cast<float> (columns),
  1211. (static_cast<float> (y) + 0.5f) / static_cast<float> (rows)
  1212. );
  1213. glm::vec4 albedo = (source.sample (uv - step) + source.sample (uv + step)
  1214. + source.sample (uv + glm::vec2 (-step.x, step.y))
  1215. + source.sample (uv + glm::vec2 (step.x, -step.y)))
  1216. * 0.25f;
  1217. if (mask.has_value ()) {
  1218. albedo.a *= mask->sample (uv).r;
  1219. }
  1220. if (unorm (albedo.a) < 0x7F) {
  1221. continue;
  1222. }
  1223. state.staged.push_back (
  1224. { .r = unorm (albedo.r),
  1225. .g = unorm (albedo.g),
  1226. .b = unorm (albedo.b),
  1227. .x = static_cast<int16_t> (static_cast<int> (
  1228. scale * static_cast<float> (x) - static_cast<float> ((width >> 1)) + scale * 0.5f
  1229. )),
  1230. .y = static_cast<int16_t> (static_cast<int> (
  1231. scale * static_cast<float> (y) - static_cast<float> ((height >> 1)) + scale * 0.5f
  1232. )) }
  1233. );
  1234. }
  1235. }
  1236. }
  1237. bool CParticle::readImagePixels (ImageEmitter& state, const CObject& layer) {
  1238. // sub_1401D3AE0: the first call only sets the layer's flags 0x1010, ours draw into _a from the start
  1239. if (!state.flagged) {
  1240. state.flagged = true;
  1241. return false;
  1242. }
  1243. const auto buffer = getScene ().find ("_rt_imageLayerComposite_" + std::to_string (layer.getId ()) + "_a");
  1244. if (buffer == nullptr) {
  1245. return false;
  1246. }
  1247. const auto layerWorld = [&layer] {
  1248. return layer.is<CImage> () ? layer.as<CImage> ()->worldMatrix () : layer.as<CText> ()->worldMatrix ();
  1249. };
  1250. if (state.stage == 2) {
  1251. state.world = layerWorld ();
  1252. if (glm::ivec2 (buffer->getRealWidth (), buffer->getRealHeight ()) != state.size) {
  1253. state.stage = 0;
  1254. }
  1255. return !state.pixels.empty ();
  1256. }
  1257. const uint32_t frame = getScene ().getFrameCounter ();
  1258. if (!state.requested || state.requestFrame == frame) {
  1259. state.requested = true;
  1260. state.requestFrame = frame;
  1261. return false;
  1262. }
  1263. if (state.stage == 0) {
  1264. WallpaperEngine::Render::Objects::CParticle::downsampleLayerBuffer (state, *buffer);
  1265. state.stage = 1;
  1266. return !state.pixels.empty ();
  1267. }
  1268. state.pixels = std::move (state.staged);
  1269. state.staged.clear ();
  1270. state.size = state.stagedSize;
  1271. state.world = layerWorld ();
  1272. state.boneInverseBind.clear ();
  1273. if (layer.is<CImage> ()) {
  1274. if (const auto& rig = layer.as<CImage> ()->getRig (); !rig.bones.empty ()) {
  1275. assignImagePixelBones (state, rig);
  1276. }
  1277. }
  1278. state.stage = 2;
  1279. return !state.pixels.empty ();
  1280. }
  1281. void CParticle::assignImagePixelBones (ImageEmitter& state, const PuppetRig& rig) {
  1282. // sub_1401D6D30: a pixel follows the bone whose capsule rectangle holds it, else the nearest one past the edges;
  1283. // pixels in several take the bone of the nearest pixel in only one
  1284. const std::vector<glm::mat4> bind = rig.layerImageBindModel ();
  1285. state.boneInverseBind.resize (bind.size ());
  1286. for (size_t bone = 0; bone < bind.size (); bone++) {
  1287. state.boneInverseBind[bone] = glm::inverse (bind[bone]);
  1288. }
  1289. auto& pixels = state.pixels;
  1290. std::vector<float> distance (pixels.size (), 0.0f);
  1291. std::vector<bool> inside (pixels.size (), false);
  1292. std::vector<bool> overlapped (pixels.size (), false);
  1293. for (size_t bone = 0; bone < rig.bones.size () && bone < 0xFF; bone++) {
  1294. if (!rig.bones[bone].hasCapsule) {
  1295. continue;
  1296. }
  1297. const glm::mat4 frame = bind[bone] * rig.bones[bone].capsule;
  1298. const glm::vec2 extents (rig.bones[bone].capsuleExtents);
  1299. const auto corner = [&frame] (float x, float y) { return glm::vec2 (frame * glm::vec4 (x, y, 0.0f, 1.0f)); };
  1300. const glm::vec2 a = corner (extents.x, extents.y);
  1301. const glm::vec2 b = corner (-extents.x, extents.y);
  1302. const glm::vec2 edgeA = b - a;
  1303. const glm::vec2 edgeB = corner (-extents.x, -extents.y) - b;
  1304. const float lengthA = edgeA.y * edgeA.y + edgeA.x * edgeA.x;
  1305. const float lengthB = edgeB.y * edgeB.y + edgeB.x * edgeB.x;
  1306. for (size_t n = 0; n < pixels.size (); n++) {
  1307. const float x = pixels[n].x;
  1308. const float y = -static_cast<float> (pixels[n].y);
  1309. const float alongA = (y - a.y) * edgeA.y + (x - a.x) * edgeA.x;
  1310. const float alongB = (y - b.y) * edgeB.y + (x - b.x) * edgeB.x;
  1311. if (alongA < 0.0f || lengthA < alongA || alongB < 0.0f || lengthB < alongB) {
  1312. if (inside[n]) {
  1313. continue;
  1314. }
  1315. float past = alongA >= 0.0f ? 0.0f : -alongA;
  1316. if (alongA > lengthA) {
  1317. past = std::max (past, alongA - lengthA);
  1318. }
  1319. if (alongB < 0.0f && -alongB > past) {
  1320. past = -alongB;
  1321. }
  1322. if (alongB > lengthB) {
  1323. past = std::max (past, alongB - lengthB);
  1324. }
  1325. if (distance[n] == 0.0f || distance[n] > past) {
  1326. distance[n] = past;
  1327. pixels[n].bone = static_cast<uint8_t> (bone);
  1328. }
  1329. } else {
  1330. if (pixels[n].bone != 0xFF && inside[n]) {
  1331. overlapped[n] = true;
  1332. }
  1333. pixels[n].bone = static_cast<uint8_t> (bone);
  1334. inside[n] = true;
  1335. }
  1336. }
  1337. }
  1338. for (size_t m = 0; m < pixels.size (); m++) {
  1339. if (!overlapped[m]) {
  1340. continue;
  1341. }
  1342. float best = std::numeric_limits<float>::max ();
  1343. uint8_t bone = 0xFF;
  1344. for (size_t n = 0; n < pixels.size (); n++) {
  1345. if (overlapped[n]) {
  1346. continue;
  1347. }
  1348. const float dy = static_cast<float> (pixels[n].y) - static_cast<float> (pixels[m].y);
  1349. const float dx = static_cast<float> (pixels[n].x) - static_cast<float> (pixels[m].x);
  1350. const float squared = dy * dy + dx * dx;
  1351. if (best > squared) {
  1352. bone = pixels[n].bone;
  1353. best = squared;
  1354. }
  1355. }
  1356. pixels[m].bone = bone;
  1357. }
  1358. }
  1359. EmitterFunc CParticle::createImageEmitter (const ParticleEmitter& emitter) {
  1360. const size_t clockIndex = m_emitters.size ();
  1361. m_imageEmitters.push_back ({ .index = static_cast<int> (m_imageEmitters.size ()) });
  1362. const size_t stateIndex = m_imageEmitters.size () - 1;
  1363. // looked up without loading at setup (sub_14022CFA0), only an already loaded texture masks
  1364. const auto record = std::ranges::find_if (m_particle.componentDependencies, [stateIndex] (const auto& cur) {
  1365. return cur.type == "emitterimage" && cur.index == static_cast<int> (stateIndex);
  1366. });
  1367. if (record != m_particle.componentDependencies.end () && !record->mask.empty ()) {
  1368. m_imageEmitters.back ().mask = getContext ().findLoadedTexture (record->mask, getScene ().getScene ().project);
  1369. }
  1370. // sub_1402378A0 emitter type 3 (layerimage) with the defaults of sub_1401B9930
  1371. return [this, emitter, clockIndex,
  1372. stateIndex] (std::vector<ParticleInstance>& particles, uint32_t& count, float dt) {
  1373. ImageEmitter& state = m_imageEmitters[stateIndex];
  1374. const uint32_t toEmit = this->emitCount (m_emitterClocks[clockIndex], emitter, dt);
  1375. const CObject* target = this->componentDependency ("emitterimage", state.index);
  1376. if (target == nullptr || (!target->is<CImage> () && !target->is<CText> ())) {
  1377. return;
  1378. }
  1379. const auto* image = target->is<CImage> () ? target->as<CImage> () : nullptr;
  1380. // flag 0x20000 re-reads every second (sub_1401D42B0), old pixels stay until the new ones are in
  1381. if ((emitter.flags & 0x20000) != 0) {
  1382. state.refreshTimer += dt;
  1383. if (state.refreshTimer > 1.0f) {
  1384. state.refreshTimer = std::fmod (state.refreshTimer, 1.0f);
  1385. if (state.stage != 1) {
  1386. state.stage = 0;
  1387. }
  1388. }
  1389. }
  1390. if (!this->readImagePixels (state, *target)) {
  1391. return;
  1392. }
  1393. // sub_1401D42E0
  1394. const PuppetRig* rig = image == nullptr || image->getRig ().bones.empty () ? nullptr : &image->getRig ();
  1395. const glm::mat4 toParticles = this->worldToParticles ();
  1396. const glm::mat4& world = state.world;
  1397. const glm::mat4 current = toParticles * world;
  1398. const glm::mat4 previous = toParticles * state.previousWorld;
  1399. const bool flat = !getScene ().getCamera ().isPerspective ();
  1400. const glm::vec3 offsetMin
  1401. = emitter.offsetMin.value_or (flat ? glm::vec3 (-5.0f, -5.0f, 0.0f) : glm::vec3 (0.0f));
  1402. const glm::vec3 offsetRange
  1403. = emitter.offsetMax.value_or (flat ? glm::vec3 (5.0f, 5.0f, 0.0f) : glm::vec3 (0.0f)) - offsetMin;
  1404. // per bone: toParticles * world * model * bind^-1, plus last frame's (sub_1401D4400, sub_1402378A0)
  1405. struct BoneFrames {
  1406. bool current = false;
  1407. bool previous = false;
  1408. glm::mat4 currentMatrix { 1.0f };
  1409. glm::mat4 previousMatrix { 1.0f };
  1410. };
  1411. std::vector<BoneFrames> boneFrames (rig != nullptr ? state.boneInverseBind.size () : 0);
  1412. const auto pixelFrames = [&] (const ImagePixel& pixel, bool wantPrevious) -> std::pair<glm::mat4, glm::mat4> {
  1413. // no bone: plain layer matrices
  1414. if (pixel.bone >= boneFrames.size ()) {
  1415. return { current, previous };
  1416. }
  1417. auto& frames = boneFrames[pixel.bone];
  1418. const glm::mat4& inverseBind = state.boneInverseBind[pixel.bone];
  1419. if (!frames.current) {
  1420. frames.current = true;
  1421. const glm::mat4 model
  1422. = pixel.bone < rig->boneModel.size () ? rig->boneModel[pixel.bone] : glm::mat4 (1.0f);
  1423. frames.currentMatrix = current * model * inverseBind;
  1424. }
  1425. if (wantPrevious && !frames.previous) {
  1426. frames.previous = true;
  1427. const glm::mat4 scene = pixel.bone < rig->physicsPreviousScene.size ()
  1428. ? rig->physicsPreviousScene[pixel.bone]
  1429. : glm::mat4 (1.0f);
  1430. frames.previousMatrix = toParticles * scene * inverseBind;
  1431. }
  1432. return { frames.currentMatrix, frames.previousMatrix };
  1433. };
  1434. std::uniform_int_distribution<size_t> pick (0, state.pixels.size () - 1);
  1435. for (uint32_t i = 0; i < toEmit && count < particles.size (); i++) {
  1436. auto& p = particles[count];
  1437. const ImagePixel& pixel = state.pixels[pick (m_rng)];
  1438. glm::vec3 offset (0.0f);
  1439. if ((emitter.flags & 0x80000) != 0) {
  1440. for (int axis = 0; axis < 3; axis++) {
  1441. offset[axis]
  1442. = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * offsetRange[axis] + offsetMin[axis];
  1443. }
  1444. }
  1445. const glm::vec4 local (
  1446. static_cast<float> (pixel.x) + offset.x, static_cast<float> (-pixel.y) + offset.y, offset.z, 1.0f
  1447. );
  1448. const bool moving = (emitter.flags & 0x40000) != 0 && m_frameDelta > 0.0f;
  1449. const auto [pixelCurrent, pixelPrevious] = pixelFrames (pixel, moving);
  1450. p.position = glm::vec3 (pixelCurrent * local);
  1451. // flags 0x40000: the pixel's movement over the last frame, times a random speed
  1452. p.velocity = glm::vec3 (0.0f);
  1453. if (moving) {
  1454. const float speed
  1455. = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * (emitter.speedMax - emitter.speedMin)
  1456. + emitter.speedMin;
  1457. p.velocity = (p.position - glm::vec3 (pixelPrevious * local)) / m_frameDelta * speed;
  1458. }
  1459. // flags 0x10000: the spawn colour takes the pixel's
  1460. glm::vec3 color = m_colorOverride.tint;
  1461. if ((emitter.flags & 0x10000) != 0) {
  1462. color *= glm::vec3 (pixel.r, pixel.g, pixel.b) / 255.0f;
  1463. }
  1464. this->startSpawn (p, color, 1.0f);
  1465. m_emitOrientation = glm::mat3 (1.0f);
  1466. for (auto& init : m_initializers) {
  1467. init (p);
  1468. }
  1469. count++;
  1470. }
  1471. // the frame's image matrix, what the next frame's velocities start from
  1472. state.previousWorld = world;
  1473. };
  1474. }
  1475. EmitterFunc CParticle::createSphereEmitter (const ParticleEmitter& emitter) {
  1476. DynamicValue* speedOverride
  1477. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  1478. // sub_14023B340: lifetime 1 unless lifetimerandom sets it
  1479. const float lifetime = 1.0f;
  1480. const int controlPointIndex = this->emitterControlPoint (emitter);
  1481. const size_t clockIndex = m_emitters.size ();
  1482. return [this, emitter, controlPointIndex, speedOverride, lifetime,
  1483. clockIndex] (std::vector<ParticleInstance>& particles, uint32_t& count, float dt) {
  1484. const uint32_t toEmit = this->emitCount (m_emitterClocks[clockIndex], emitter, dt);
  1485. for (uint32_t i = 0; i < toEmit && count < particles.size (); i++) {
  1486. auto& p = particles[count];
  1487. const ControlPointData* cp = this->controlPointAt (controlPointIndex);
  1488. // sub_1402378A0 sphererandom: a point in the unit ball (cone around x) scaled by
  1489. // directions, whose length also picks the distance between distancemin and distancemax
  1490. const float phi = glm::two_pi<float> () * WallpaperEngine::Maths::randomFloat (m_rng, 0.00001f, 1.0f);
  1491. const float coneMin = -std::cos (emitter.cone * glm::pi<float> ());
  1492. const float c = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * (1.0f - coneMin) + coneMin;
  1493. const float r = std::cbrt (WallpaperEngine::Maths::randomFloat (m_rng, 0.00001f, 1.0f));
  1494. const float s = std::sqrt (std::max (0.0f, 1.0f - c * c));
  1495. const glm::vec3 point
  1496. = glm::vec3 (r * c, r * s * std::sin (phi), r * s * std::cos (phi)) * emitter.directions;
  1497. const float pointLength = glm::length (point);
  1498. const float distance
  1499. = emitter.distanceMin.x + (emitter.distanceMax.x - emitter.distanceMin.x) * pointLength;
  1500. glm::vec3 randomPos = pointLength > 0.0f ? point / pointLength : glm::vec3 (0.0f);
  1501. // a nonzero sign component forces that axis to its sign, zero leaves it alone
  1502. for (int axis = 0; axis < 3; axis++) {
  1503. if (emitter.sign[axis] > 0.0f) {
  1504. randomPos[axis] = std::abs (randomPos[axis]);
  1505. } else if (emitter.sign[axis] < 0.0f) {
  1506. randomPos[axis] = -std::abs (randomPos[axis]);
  1507. }
  1508. }
  1509. randomPos *= distance;
  1510. this->placeSpawn (p, cp, controlPointIndex, emitter.origin, randomPos);
  1511. // the velocity points along the (control point transformed) offset, a zero offset gets a random direction
  1512. // inside directions instead
  1513. glm::vec3 direction = randomPos;
  1514. if (glm::dot (direction, direction) < 0.0001f) {
  1515. direction = emitter.directions
  1516. * glm::vec3 (
  1517. WallpaperEngine::Maths::randomFloat (m_rng, 0.00001f, 1.0f) * 2.0f - 1.0f,
  1518. WallpaperEngine::Maths::randomFloat (m_rng, 0.00001f, 1.0f) * 2.0f - 1.0f,
  1519. WallpaperEngine::Maths::randomFloat (m_rng, 0.00001f, 1.0f) * 2.0f - 1.0f
  1520. );
  1521. if (cp != nullptr && (controlPointIndex != 0 || m_worldSpace)) {
  1522. direction = cp->orientation * direction;
  1523. }
  1524. }
  1525. const float directionLength = glm::length (direction);
  1526. const float speedScale = speedOverride != nullptr ? speedOverride->getFloat () : 1.0f;
  1527. const float speed = (emitter.speedMin
  1528. + (emitter.speedMax - emitter.speedMin)
  1529. * WallpaperEngine::Maths::randomFloat (m_rng, 0.00001f, 1.0f))
  1530. * speedScale;
  1531. p.velocity = directionLength > 0.0f ? direction * (speed / directionLength) : glm::vec3 (0.0f);
  1532. this->startSpawn (p, m_colorOverride.tint, lifetime);
  1533. for (auto& init : m_initializers) {
  1534. init (p);
  1535. }
  1536. count++;
  1537. }
  1538. };
  1539. }
  1540. void CParticle::placeSpawn (
  1541. ParticleInstance& p, const ControlPointData* cp, int controlPointIndex, const glm::vec3& origin, glm::vec3& offset
  1542. ) {
  1543. // sub_1402378A0 box/sphere emitters: the shape turns with the control point's matrix unless it is control
  1544. // point 0 of a local system, the emitter origin is added untransformed, and the velocity initializers get
  1545. // the control point's rotation and scale either way
  1546. if (cp != nullptr && (controlPointIndex != 0 || m_worldSpace)) {
  1547. offset = cp->orientation * offset;
  1548. }
  1549. p.position = origin + offset + (cp != nullptr ? cp->position : glm::vec3 (0.0f));
  1550. m_emitOrientation = cp != nullptr ? cp->orientation : glm::mat3 (1.0f);
  1551. }
  1552. void CParticle::setupInitializers () {
  1553. for (const auto& initializer : m_particle.initializers) {
  1554. if (!initializer) {
  1555. continue;
  1556. }
  1557. InitializerFunc func;
  1558. if (initializer->is<ColorRandomInitializer> ()) {
  1559. func = createColorRandomInitializer (*initializer->as<ColorRandomInitializer> ());
  1560. } else if (initializer->is<SizeRandomInitializer> ()) {
  1561. func = createSizeRandomInitializer (*initializer->as<SizeRandomInitializer> ());
  1562. } else if (initializer->is<AlphaRandomInitializer> ()) {
  1563. func = createAlphaRandomInitializer (*initializer->as<AlphaRandomInitializer> ());
  1564. } else if (initializer->is<LifetimeRandomInitializer> ()) {
  1565. func = createLifetimeRandomInitializer (*initializer->as<LifetimeRandomInitializer> ());
  1566. } else if (initializer->is<VelocityRandomInitializer> ()) {
  1567. func = createVelocityRandomInitializer (*initializer->as<VelocityRandomInitializer> ());
  1568. } else if (initializer->is<RotationRandomInitializer> ()) {
  1569. func = createRotationRandomInitializer (*initializer->as<RotationRandomInitializer> ());
  1570. } else if (initializer->is<AngularVelocityRandomInitializer> ()) {
  1571. func = createAngularVelocityRandomInitializer (*initializer->as<AngularVelocityRandomInitializer> ());
  1572. } else if (initializer->is<TurbulentVelocityRandomInitializer> ()) {
  1573. func = createTurbulentVelocityRandomInitializer (*initializer->as<TurbulentVelocityRandomInitializer> ());
  1574. } else if (initializer->is<MapSequenceAroundControlPointInitializer> ()) {
  1575. func = createMapSequenceAroundControlPointInitializer (
  1576. *initializer->as<MapSequenceAroundControlPointInitializer> ()
  1577. );
  1578. } else if (initializer->is<InheritInitialValueFromEventInitializer> ()) {
  1579. func = createInheritInitialValueFromEventInitializer (
  1580. *initializer->as<InheritInitialValueFromEventInitializer> ()
  1581. );
  1582. } else if (initializer->is<InheritControlPointVelocityInitializer> ()) {
  1583. func = createInheritControlPointVelocityInitializer (
  1584. *initializer->as<InheritControlPointVelocityInitializer> ()
  1585. );
  1586. } else if (initializer->is<HsvColorRandomInitializer> ()) {
  1587. func = createHsvColorRandomInitializer (*initializer->as<HsvColorRandomInitializer> ());
  1588. } else if (initializer->is<ColorListInitializer> ()) {
  1589. func = createColorListInitializer (*initializer->as<ColorListInitializer> ());
  1590. } else if (initializer->is<PositionOffsetRandomInitializer> ()) {
  1591. func = createPositionOffsetRandomInitializer (*initializer->as<PositionOffsetRandomInitializer> ());
  1592. } else if (initializer->is<MapSequenceBetweenControlPointsInitializer> ()) {
  1593. func = createMapSequenceBetweenControlPointsInitializer (
  1594. *initializer->as<MapSequenceBetweenControlPointsInitializer> ()
  1595. );
  1596. } else if (initializer->is<RemapInitialValueInitializer> ()) {
  1597. func = createRemapInitialValueInitializer (*initializer->as<RemapInitialValueInitializer> ());
  1598. } else {
  1599. sLog.out ("Unknown initializer type");
  1600. }
  1601. if (func) {
  1602. m_initializers.push_back (std::move (func));
  1603. }
  1604. }
  1605. }
  1606. InitializerFunc CParticle::createColorRandomInitializer (const ColorRandomInitializer& init) {
  1607. DynamicValue* minValue = init.min->value.get ();
  1608. DynamicValue* maxValue = init.max->value.get ();
  1609. DynamicValue* exponentValue = init.exponent->value.get ();
  1610. // wallpaper64.exe sub_14023B340 case 3, one random for all three channels. An active override color moves
  1611. // both ends in HSV first (sub_1401D15A0 case 0xB)
  1612. return [this, minValue, maxValue, exponentValue] (ParticleInstance& p) {
  1613. glm::vec3 min = minValue->getVec3 () / 255.0f;
  1614. glm::vec3 max = maxValue->getVec3 () / 255.0f;
  1615. if (m_colorOverride.active) {
  1616. min = shiftColor (min, m_colorOverride.shift);
  1617. max = shiftColor (max, m_colorOverride.shift);
  1618. }
  1619. float t = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f);
  1620. if (const float exponent = exponentValue->getFloat (); exponent != 1.0f) {
  1621. t = std::pow (t, exponent);
  1622. }
  1623. p.color *= (max - min) * t + min;
  1624. p.initial.color = p.color;
  1625. };
  1626. }
  1627. InitializerFunc CParticle::createSizeRandomInitializer (const SizeRandomInitializer& init) {
  1628. DynamicValue* minValue = init.min->value.get ();
  1629. DynamicValue* maxValue = init.max->value.get ();
  1630. DynamicValue* exponentValue = init.exponent->value.get ();
  1631. DynamicValue* sizeOverride
  1632. = (m_particle.flags & 0x80) == 0 ? m_particle.instanceOverride.size->value.get () : nullptr;
  1633. return [this, minValue, maxValue, exponentValue, sizeOverride] (ParticleInstance& p) {
  1634. float t = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f);
  1635. float exponent = exponentValue->getFloat ();
  1636. float min = minValue->getFloat ();
  1637. float max = maxValue->getFloat ();
  1638. float adjustedT = std::pow (t, exponent);
  1639. p.size = (min + adjustedT * (max - min)) * (sizeOverride != nullptr ? sizeOverride->getFloat () : 1.0f) / 2.0f;
  1640. p.initial.size = p.size;
  1641. };
  1642. }
  1643. InitializerFunc CParticle::createAlphaRandomInitializer (const AlphaRandomInitializer& init) {
  1644. DynamicValue* minValue = init.min->value.get ();
  1645. DynamicValue* maxValue = init.max->value.get ();
  1646. DynamicValue* alphaOverride = m_particle.instanceOverride.alpha->value.get ();
  1647. return [this, minValue, maxValue, alphaOverride] (ParticleInstance& p) {
  1648. p.alpha = WallpaperEngine::Maths::randomFloat (m_rng, minValue->getFloat (), maxValue->getFloat ())
  1649. * alphaOverride->getFloat ();
  1650. p.initial.alpha = p.alpha;
  1651. };
  1652. }
  1653. InitializerFunc CParticle::createLifetimeRandomInitializer (const LifetimeRandomInitializer& init) {
  1654. DynamicValue* minValue = init.min->value.get ();
  1655. DynamicValue* maxValue = init.max->value.get ();
  1656. DynamicValue* exponentValue = init.exponent->value.get ();
  1657. DynamicValue* lifetimeOverride = m_particle.instanceOverride.lifetime->value.get ();
  1658. // sub_14023B340 case 1: min + random ^ exponent * (max - min), at least 0.001
  1659. return [this, minValue, maxValue, exponentValue, lifetimeOverride] (ParticleInstance& p) {
  1660. float t = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f);
  1661. if (const float exponent = exponentValue->getFloat (); exponent != 1.0f) {
  1662. t = std::pow (t, exponent);
  1663. }
  1664. const float min = minValue->getFloat ();
  1665. const float lifetime = (min + t * (maxValue->getFloat () - min)) * lifetimeOverride->getFloat ();
  1666. p.lifetime = std::max (lifetime, 0.001f);
  1667. p.initial.lifetime = p.lifetime;
  1668. };
  1669. }
  1670. namespace {
  1671. /** min + t * (max - min) per axis, t = random ^ exponent (plain random for exponent 1), x drawn first */
  1672. glm::vec3 randomExponentVec3 (std::mt19937& rng, const glm::vec3& min, const glm::vec3& max, float exponent) {
  1673. glm::vec3 result;
  1674. for (int i = 0; i < 3; i++) {
  1675. float t = WallpaperEngine::Maths::randomFloat (rng, 0.0f, 1.0f);
  1676. if (exponent != 1.0f) {
  1677. t = std::pow (t, exponent);
  1678. }
  1679. result[i] = min[i] + t * (max[i] - min[i]);
  1680. }
  1681. return result;
  1682. }
  1683. }
  1684. InitializerFunc CParticle::createVelocityRandomInitializer (const VelocityRandomInitializer& init) {
  1685. DynamicValue* minValue = init.min ? init.min->value.get () : nullptr;
  1686. DynamicValue* maxValue = init.max ? init.max->value.get () : nullptr;
  1687. DynamicValue* exponentValue = init.exponent->value.get ();
  1688. DynamicValue* speedOverride
  1689. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  1690. // sub_14023B340 case 7: z is drawn first, then y and x
  1691. return [this, minValue, maxValue, exponentValue, speedOverride] (ParticleInstance& p) {
  1692. const bool flat = !getScene ().getCamera ().isPerspective ();
  1693. const glm::vec3 min = minValue != nullptr ? minValue->getVec3 ()
  1694. : flat ? glm::vec3 (-32.0f, -32.0f, 0.0f)
  1695. : glm::vec3 (-1.0f);
  1696. const glm::vec3 max = maxValue != nullptr ? maxValue->getVec3 ()
  1697. : flat ? glm::vec3 (32.0f, 32.0f, 0.0f)
  1698. : glm::vec3 (1.0f);
  1699. const float exponent = exponentValue->getFloat ();
  1700. glm::vec3 vel;
  1701. for (int i = 2; i >= 0; i--) {
  1702. float t = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f);
  1703. if (exponent != 1.0f) {
  1704. t = std::pow (t, exponent);
  1705. }
  1706. vel[i] = min[i] + t * (max[i] - min[i]);
  1707. }
  1708. if (speedOverride != nullptr) {
  1709. vel *= speedOverride->getFloat ();
  1710. }
  1711. p.velocity += m_emitOrientation * vel;
  1712. };
  1713. }
  1714. InitializerFunc CParticle::createRotationRandomInitializer (const RotationRandomInitializer& init) {
  1715. DynamicValue* minValue = init.min->value.get ();
  1716. DynamicValue* maxValue = init.max->value.get ();
  1717. DynamicValue* exponentValue = init.exponent->value.get ();
  1718. // case 10, no speed binding
  1719. return [this, minValue, maxValue, exponentValue] (ParticleInstance& p) {
  1720. p.rotation
  1721. += randomExponentVec3 (m_rng, minValue->getVec3 (), maxValue->getVec3 (), exponentValue->getFloat ());
  1722. };
  1723. }
  1724. InitializerFunc CParticle::createAngularVelocityRandomInitializer (const AngularVelocityRandomInitializer& init) {
  1725. DynamicValue* minValue = init.min->value.get ();
  1726. DynamicValue* maxValue = init.max->value.get ();
  1727. DynamicValue* exponentValue = init.exponent->value.get ();
  1728. DynamicValue* speedOverride
  1729. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  1730. // case 12
  1731. return [this, minValue, maxValue, exponentValue, speedOverride] (ParticleInstance& p) {
  1732. glm::vec3 result
  1733. = randomExponentVec3 (m_rng, minValue->getVec3 (), maxValue->getVec3 (), exponentValue->getFloat ());
  1734. if (speedOverride != nullptr) {
  1735. result *= speedOverride->getFloat ();
  1736. }
  1737. p.angularVelocity += result;
  1738. };
  1739. }
  1740. InitializerFunc CParticle::createTurbulentVelocityRandomInitializer (const TurbulentVelocityRandomInitializer& init) {
  1741. DynamicValue* speedMin = init.speedMin->value.get ();
  1742. DynamicValue* speedMax = init.speedMax->value.get ();
  1743. DynamicValue* offsetVal = init.offset->value.get ();
  1744. DynamicValue* scaleVal = init.scale->value.get ();
  1745. DynamicValue* forwardVal = init.forward->value.get ();
  1746. DynamicValue* timeScaleVal = init.timeScale->value.get ();
  1747. DynamicValue* phaseMinVal = init.phaseMin->value.get ();
  1748. DynamicValue* phaseMaxVal = init.phaseMax->value.get ();
  1749. DynamicValue* rightVal = init.right->value.get ();
  1750. DynamicValue* speedOverride = m_particle.instanceOverride.speed->value.get ();
  1751. DynamicValue* audioModeValue = init.audioProcessingMode->value.get ();
  1752. DynamicValue* audioBoundsValue = init.audioProcessingBounds->value.get ();
  1753. DynamicValue* audioExponentValue = init.audioProcessingExponent->value.get ();
  1754. DynamicValue* audioStartValue = init.audioProcessingFrequencyStart->value.get ();
  1755. DynamicValue* audioEndValue = init.audioProcessingFrequencyEnd->value.get ();
  1756. // same formula as wallpaper64.exe (sub_1401C8AF0)
  1757. return [this, speedMin, speedMax, offsetVal, scaleVal, forwardVal, timeScaleVal, phaseMinVal, phaseMaxVal, rightVal,
  1758. speedOverride, audioModeValue, audioBoundsValue, audioExponentValue, audioStartValue,
  1759. audioEndValue] (ParticleInstance& p) {
  1760. const float audio = sampleAudio (
  1761. audioModeValue->getInt (), audioBoundsValue->getVec2 (), audioExponentValue->getFloat (),
  1762. audioStartValue->getInt (), audioEndValue->getInt ()
  1763. );
  1764. const float phaseMin = phaseMinVal->getFloat ();
  1765. const float phaseRange = (phaseMaxVal->getFloat () - phaseMin) * audio;
  1766. // sub_14023B340 case 9: the renderer's scene clock is added to the phase
  1767. const float phase = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * phaseRange + phaseMin
  1768. + getScene ().getSceneClock ();
  1769. const float timeScale = timeScaleVal->getFloat () * m_particle.instanceOverride.rate->value->getFloat ();
  1770. const float angle
  1771. = simplexNoise1D (phase * timeScale) * glm::pi<float> () * scaleVal->getFloat () + offsetVal->getFloat ();
  1772. const float speed = WallpaperEngine::Maths::randomFloat (m_rng, speedMin->getFloat (), speedMax->getFloat ());
  1773. glm::vec3 right = rightVal->getVec3 ();
  1774. if (glm::length (right) < 0.0001f) {
  1775. right = glm::vec3 (0.0f, 0.0f, 1.0f);
  1776. }
  1777. const glm::vec3 direction = glm::mat3 (glm::rotate (glm::mat4 (1.0f), angle, right)) * forwardVal->getVec3 ();
  1778. p.velocity += m_emitOrientation * (direction * speed * speedOverride->getFloat ());
  1779. };
  1780. }
  1781. InitializerFunc
  1782. CParticle::createMapSequenceAroundControlPointInitializer (const MapSequenceAroundControlPointInitializer& init) {
  1783. // the loader's basis (sub_1401C19E0): the axis normalized, (0, 0, 1) when zero, and two directions around it
  1784. glm::vec3 axis = init.axis == glm::vec3 (0.0f) ? glm::vec3 (0.0f, 0.0f, 1.0f) : glm::normalize (init.axis);
  1785. glm::vec3 across (1.0f, 0.0f, 0.0f);
  1786. glm::vec3 up (0.0f, 1.0f, 0.0f);
  1787. if (axis.x != 0.0f || axis.y != 0.0f) {
  1788. const glm::vec3 side = glm::cross (axis, glm::vec3 (0.0f, 0.0f, 1.0f));
  1789. across = glm::normalize (side);
  1790. up = glm::normalize (glm::cross (axis, side));
  1791. }
  1792. const int controlPoint = init.controlPoint;
  1793. const bool mirror = init.mirror;
  1794. const float boundsMin = init.bounds.x;
  1795. const float boundsRange = init.bounds.y - init.bounds.x;
  1796. const glm::vec3 speedMin = init.speedMin;
  1797. const glm::vec3 speedRange = init.speedMax - init.speedMin;
  1798. DynamicValue* speedOverride
  1799. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  1800. SequenceCounter& counter = m_sequences.emplace_back (
  1801. SequenceCounter { .step = 1.0f / (init.count <= 0.000099999997f ? 0.000099999997f : init.count) }
  1802. );
  1803. // sub_14023B340 case 13: the particle is turned around the control point's axis to the sequence's angle, keeping
  1804. // its distance from the axis and its height along it, then gets a random speed in that frame
  1805. return [this, axis, across, up, controlPoint, mirror, boundsMin, boundsRange, speedMin, speedRange, speedOverride,
  1806. &counter] (ParticleInstance& p) {
  1807. const ControlPointData& point = m_controlPoints[controlPoint];
  1808. const glm::vec3 center = point.position;
  1809. const glm::vec3 pointAxis = point.orientation * axis;
  1810. const glm::vec3 pointAcross = point.orientation * across;
  1811. const glm::vec3 pointUp = point.orientation * up;
  1812. const glm::vec3 relative = p.position - center;
  1813. const float along = glm::dot (relative, pointAxis);
  1814. const float radius = glm::length (relative - along * pointAxis);
  1815. const float angle = (counter.sequence * boundsRange + boundsMin) * 6.2831855f;
  1816. const float sine = std::sin (angle);
  1817. const float cosine = std::cos (angle);
  1818. const glm::vec3 outwards = sine * pointAcross + cosine * pointUp;
  1819. const glm::vec3 around = cosine * pointAcross - sine * pointUp;
  1820. const float randomZ = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f);
  1821. const float randomX = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f);
  1822. const float randomY = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f);
  1823. const glm::vec3 velocity = around * (speedMin.x + randomX * speedRange.x)
  1824. + outwards * (speedMin.y + randomY * speedRange.y) + pointAxis * (speedMin.z + randomZ * speedRange.z);
  1825. p.position = outwards * radius + (along * pointAxis + center);
  1826. p.velocity += velocity * (speedOverride != nullptr ? speedOverride->getFloat () : 1.0f);
  1827. counter.sequence += counter.step;
  1828. if (counter.sequence > 1.0f) {
  1829. if (mirror) {
  1830. counter.step = -counter.step;
  1831. counter.sequence = 1.0f - (counter.sequence - 1.0f);
  1832. } else {
  1833. counter.sequence = std::fmod (counter.sequence, 1.0f);
  1834. }
  1835. } else if (counter.sequence < 0.0f) {
  1836. counter.sequence = -counter.sequence;
  1837. counter.step = -counter.step;
  1838. }
  1839. };
  1840. }
  1841. namespace {
  1842. void applyEventInput (ParticleInstance& p, const ParticleInstance& source, ParticleEventInput input, bool initial) {
  1843. switch (input) {
  1844. case ParticleEventInput::SetColor:
  1845. p.color = source.color;
  1846. break;
  1847. case ParticleEventInput::MultiplyColor:
  1848. p.color *= source.color;
  1849. break;
  1850. case ParticleEventInput::SetOpacity:
  1851. p.alpha = source.alpha;
  1852. break;
  1853. case ParticleEventInput::MultiplyOpacity:
  1854. p.alpha *= source.alpha;
  1855. break;
  1856. case ParticleEventInput::SetColorOpacity:
  1857. p.color = source.color;
  1858. p.alpha = source.alpha;
  1859. break;
  1860. case ParticleEventInput::MultiplyColorOpacity:
  1861. p.color *= source.color;
  1862. p.alpha *= source.alpha;
  1863. break;
  1864. case ParticleEventInput::SetVelocity:
  1865. p.velocity = source.velocity;
  1866. break;
  1867. case ParticleEventInput::AddVelocity:
  1868. p.velocity += source.velocity;
  1869. break;
  1870. case ParticleEventInput::SetSize:
  1871. p.size = source.size;
  1872. break;
  1873. case ParticleEventInput::MultiplySize:
  1874. p.size *= source.size;
  1875. break;
  1876. case ParticleEventInput::SetRotation:
  1877. p.rotation = source.rotation;
  1878. break;
  1879. case ParticleEventInput::AddRotation:
  1880. p.rotation += source.rotation;
  1881. break;
  1882. case ParticleEventInput::SetAngularVelocity:
  1883. p.angularVelocity = source.angularVelocity;
  1884. break;
  1885. case ParticleEventInput::AddAngularVelocity:
  1886. p.angularVelocity += source.angularVelocity;
  1887. break;
  1888. }
  1889. if (initial) {
  1890. p.initial.color = p.color;
  1891. p.initial.alpha = p.alpha;
  1892. p.initial.size = p.size;
  1893. }
  1894. }
  1895. }
  1896. InitializerFunc
  1897. CParticle::createInheritInitialValueFromEventInitializer (const InheritInitialValueFromEventInitializer& init) {
  1898. const ParticleEventInput input = init.input;
  1899. // wallpaper64.exe sub_14023B340 case 16: the event's particle as it was, a dead one included
  1900. return [this, input] (ParticleInstance& p) {
  1901. if (m_hasEventParticle) {
  1902. applyEventInput (p, m_eventParticle, input, true);
  1903. }
  1904. };
  1905. }
  1906. InitializerFunc
  1907. CParticle::createInheritControlPointVelocityInitializer (const InheritControlPointVelocityInitializer& init) {
  1908. const int controlPoint = init.controlPoint;
  1909. DynamicValue* minValue = init.min->value.get ();
  1910. DynamicValue* maxValue = init.max->value.get ();
  1911. // sub_14023B340 case 8: a random share of how fast the control point moved over the last frame
  1912. return [this, controlPoint, minValue, maxValue] (ParticleInstance& p) {
  1913. if (controlPoint < 0 || controlPoint >= static_cast<int> (m_controlPoints.size ())) {
  1914. return;
  1915. }
  1916. const auto& cp = m_controlPoints[controlPoint];
  1917. glm::vec3 velocity = cp.velocity;
  1918. // a world space system's control points move in the world, back into its own space unless flag 2 made
  1919. // the point a world one, then through the emitter's orientation like every velocity initializer
  1920. if (m_worldSpace && !cp.worldSpace) {
  1921. velocity = glm::mat3 (glm::inverse (m_frame)) * velocity;
  1922. }
  1923. const float share = WallpaperEngine::Maths::randomFloat (m_rng, minValue->getFloat (), maxValue->getFloat ());
  1924. p.velocity += m_emitOrientation * (velocity * share);
  1925. };
  1926. }
  1927. OperatorFunc CParticle::createInheritValueFromEventOperator (const InheritValueFromEventOperator& op) {
  1928. const ParticleEventInput input = op.input;
  1929. // same clamps as sub_1401C2A40 so the blend windows never have zero length
  1930. const float inStart = std::min (op.blend.x, op.blend.y - 0.0001f);
  1931. const float inEnd = op.blend.y;
  1932. const float outStart = op.blend.z;
  1933. const float outEnd = std::max (op.blend.w, op.blend.z + 0.0001f);
  1934. // sub_14023FBC0 case 20: every frame while the event's particle lives, nothing for eventdeath children
  1935. return
  1936. [this, input, inStart, inEnd, outStart, outEnd] (
  1937. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
  1938. ) {
  1939. if (!m_eventId.has_value ()) {
  1940. return;
  1941. }
  1942. for (uint32_t i = 0; i < count; i++) {
  1943. auto& p = particles[i];
  1944. const float life = p.getLifetimePos ();
  1945. const float weight = std::clamp ((life - inStart) / (inEnd - inStart), 0.0f, 1.0f)
  1946. * std::clamp ((outEnd - life) / (outEnd - outStart), 0.0f, 1.0f);
  1947. if (weight >= 1.0f) {
  1948. applyEventInput (p, m_eventParticle, input, false);
  1949. continue;
  1950. }
  1951. ParticleInstance target = p;
  1952. applyEventInput (target, m_eventParticle, input, false);
  1953. p.color = glm::mix (p.color, target.color, weight);
  1954. p.alpha = glm::mix (p.alpha, target.alpha, weight);
  1955. p.velocity = glm::mix (p.velocity, target.velocity, weight);
  1956. p.size = glm::mix (p.size, target.size, weight);
  1957. p.rotation = glm::mix (p.rotation, target.rotation, weight);
  1958. p.angularVelocity = glm::mix (p.angularVelocity, target.angularVelocity, weight);
  1959. }
  1960. };
  1961. }
  1962. void CParticle::setupOperators () {
  1963. for (const auto& op : m_particle.operators) {
  1964. if (!op) {
  1965. continue;
  1966. }
  1967. OperatorFunc func;
  1968. if (op->is<MovementOperator> ()) {
  1969. func = createMovementOperator (*op->as<MovementOperator> ());
  1970. } else if (op->is<AngularMovementOperator> ()) {
  1971. func = createAngularMovementOperator (*op->as<AngularMovementOperator> ());
  1972. } else if (op->is<AlphaFadeOperator> ()) {
  1973. func = createAlphaFadeOperator (*op->as<AlphaFadeOperator> ());
  1974. } else if (op->is<SizeChangeOperator> ()) {
  1975. func = createSizeChangeOperator (*op->as<SizeChangeOperator> ());
  1976. } else if (op->is<AlphaChangeOperator> ()) {
  1977. func = createAlphaChangeOperator (*op->as<AlphaChangeOperator> ());
  1978. } else if (op->is<ColorChangeOperator> ()) {
  1979. func = createColorChangeOperator (*op->as<ColorChangeOperator> ());
  1980. } else if (op->is<TurbulenceOperator> ()) {
  1981. func = createTurbulenceOperator (*op->as<TurbulenceOperator> ());
  1982. } else if (op->is<VortexOperator> ()) {
  1983. func = createVortexOperator (*op->as<VortexOperator> ());
  1984. } else if (op->is<ControlPointAttractOperator> ()) {
  1985. func = createControlPointAttractOperator (*op->as<ControlPointAttractOperator> ());
  1986. } else if (op->is<OscillateAlphaOperator> ()) {
  1987. func = createOscillateAlphaOperator (*op->as<OscillateAlphaOperator> ());
  1988. } else if (op->is<OscillateSizeOperator> ()) {
  1989. func = createOscillateSizeOperator (*op->as<OscillateSizeOperator> ());
  1990. } else if (op->is<OscillatePositionOperator> ()) {
  1991. func = createOscillatePositionOperator (*op->as<OscillatePositionOperator> ());
  1992. } else if (op->is<InheritValueFromEventOperator> ()) {
  1993. func = createInheritValueFromEventOperator (*op->as<InheritValueFromEventOperator> ());
  1994. } else if (op->is<CapVelocityOperator> ()) {
  1995. func = createCapVelocityOperator (*op->as<CapVelocityOperator> ());
  1996. } else if (op->is<BoidsOperator> ()) {
  1997. func = createBoidsOperator (*op->as<BoidsOperator> ());
  1998. if (!m_hasBoids) {
  1999. m_hasBoids = true;
  2000. m_ghosts.resize (m_maxParticles);
  2001. m_ghostUsed.assign (m_maxParticles, 0);
  2002. }
  2003. } else if (op->is<RemapValueOperator> ()) {
  2004. func = createRemapValueOperator (*op->as<RemapValueOperator> ());
  2005. } else if (op->is<MaintainDistanceToControlPointOperator> ()) {
  2006. func = createMaintainDistanceToControlPointOperator (*op->as<MaintainDistanceToControlPointOperator> ());
  2007. } else if (op->is<MaintainDistanceBetweenControlPointsOperator> ()) {
  2008. func = createMaintainDistanceBetweenControlPointsOperator (
  2009. *op->as<MaintainDistanceBetweenControlPointsOperator> ()
  2010. );
  2011. } else if (op->is<ReduceMovementNearControlPointOperator> ()) {
  2012. func = createReduceMovementNearControlPointOperator (*op->as<ReduceMovementNearControlPointOperator> ());
  2013. } else if (op->is<CollisionOperator> ()) {
  2014. func = createCollisionOperator (*op->as<CollisionOperator> ());
  2015. } else {
  2016. sLog.out ("Unknown operator type");
  2017. }
  2018. if (func) {
  2019. m_operators.push_back (std::move (func));
  2020. }
  2021. }
  2022. }
  2023. OperatorFunc CParticle::createMovementOperator (const MovementOperator& op) {
  2024. DynamicValue* dragValue = op.drag->value.get ();
  2025. DynamicValue* gravityValue = op.gravity->value.get ();
  2026. DynamicValue* speedOverride
  2027. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  2028. // sub_14023FBC0 case 1: velocity first, then position with the new velocity, then drag over the frame scaled dt.
  2029. // It runs over every pool slot, dead ones included
  2030. const bool turnGravity = (op.flags & 1) != 0;
  2031. return [this, dragValue, gravityValue, speedOverride, turnGravity] (
  2032. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
  2033. float dt
  2034. ) {
  2035. glm::vec3 gravity = gravityValue->getVec3 () * (speedOverride != nullptr ? speedOverride->getFloat () : 1.0f);
  2036. // sub_1401F87E0 multiplies the gravity by the frame's 3x3 from the other side (its transpose), so drawn
  2037. // through the frame a rotation cancels out and the scale applies twice
  2038. if (turnGravity && !m_worldSpace) {
  2039. gravity = glm::transpose (glm::mat3 (m_frame)) * gravity;
  2040. }
  2041. const float drag = std::min (dragValue->getFloat () * frameScaledDelta (dt), 0.99999988f);
  2042. const glm::vec3 step = gravity * dt;
  2043. const auto move = [&] (ParticleInstance& p) {
  2044. const glm::vec3 velocity = p.velocity + step;
  2045. p.position += velocity * dt;
  2046. p.velocity = velocity * (1.0f - drag);
  2047. };
  2048. for (uint32_t i = 0; i < count; i++) {
  2049. if (particles[i].alive) {
  2050. move (particles[i]);
  2051. }
  2052. }
  2053. for (uint32_t slot = 0; slot < m_ghostUsed.size (); slot++) {
  2054. if (m_ghostUsed[slot]) {
  2055. move (m_ghosts[slot]);
  2056. }
  2057. }
  2058. };
  2059. }
  2060. OperatorFunc CParticle::createAngularMovementOperator (const AngularMovementOperator& op) {
  2061. DynamicValue* dragValue = op.drag->value.get ();
  2062. DynamicValue* forceValue = op.force->value.get ();
  2063. DynamicValue* speedOverride
  2064. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  2065. // sub_14023FBC0 case 2, like movement: the speed override only scales the force (a loader binding)
  2066. return [this, dragValue, forceValue, speedOverride] (
  2067. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
  2068. float dt
  2069. ) {
  2070. const float drag = std::min (dragValue->getFloat () * frameScaledDelta (dt), 0.99999988f);
  2071. glm::vec3 force = forceValue->getVec3 ();
  2072. if (speedOverride != nullptr) {
  2073. force *= speedOverride->getFloat ();
  2074. }
  2075. const glm::vec3 step = force * dt;
  2076. for (uint32_t i = 0; i < count; i++) {
  2077. auto& p = particles[i];
  2078. if (!p.alive) {
  2079. continue;
  2080. }
  2081. const glm::vec3 angularVelocity = p.angularVelocity + step;
  2082. p.rotation += angularVelocity * dt;
  2083. p.angularVelocity = angularVelocity * (1.0f - drag);
  2084. }
  2085. };
  2086. }
  2087. OperatorFunc CParticle::createAlphaFadeOperator (const AlphaFadeOperator& op) {
  2088. DynamicValue* fadeInTimeValue = op.fadeInTime->value.get ();
  2089. DynamicValue* fadeOutTimeValue = op.fadeOutTime->value.get ();
  2090. // the loader sets system flag 0x10 for alphafade, alphachange and oscillatealpha: sub_14023FBC0 starts every
  2091. // pass from the spawn alpha and they multiply it
  2092. m_resetAlphaFromBase = true;
  2093. return
  2094. [fadeInTimeValue, fadeOutTimeValue] (
  2095. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
  2096. ) {
  2097. float fadeInTime = fadeInTimeValue->getFloat ();
  2098. float fadeOutTime = fadeOutTimeValue->getFloat ();
  2099. for (uint32_t i = 0; i < count; i++) {
  2100. auto& p = particles[i];
  2101. if (!p.alive) {
  2102. continue;
  2103. }
  2104. float life = p.getLifetimePos ();
  2105. if (life <= fadeInTime) {
  2106. p.alpha *= WallpaperEngine::Maths::fadeValue (life, 0.0f, fadeInTime, 0.0f, 1.0f);
  2107. } else if (life > fadeOutTime) {
  2108. p.alpha *= 1.0f - WallpaperEngine::Maths::fadeValue (life, fadeOutTime, 1.0f, 0.0f, 1.0f);
  2109. }
  2110. }
  2111. };
  2112. }
  2113. OperatorFunc CParticle::createSizeChangeOperator (const SizeChangeOperator& op) {
  2114. DynamicValue* startTimeValue = op.startTime->value.get ();
  2115. DynamicValue* endTimeValue = op.endTime->value.get ();
  2116. DynamicValue* startValueValue = op.startValue->value.get ();
  2117. DynamicValue* endValueValue = op.endValue->value.get ();
  2118. // wallpaper64.exe binds the instanceoverride size to both values (sub_1401C5490, sub_1401D15A0 case 7), on top of
  2119. // sizerandom's own binding. Particle flag 0x80 turns the size bindings off
  2120. DynamicValue* sizeOverride
  2121. = (m_particle.flags & 0x80) == 0 ? m_particle.instanceOverride.size->value.get () : nullptr;
  2122. return
  2123. [startTimeValue, endTimeValue, startValueValue, endValueValue, sizeOverride] (
  2124. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
  2125. ) {
  2126. const float scale = sizeOverride != nullptr ? sizeOverride->getFloat () : 1.0f;
  2127. float startTime = startTimeValue->getFloat ();
  2128. float endTime = endTimeValue->getFloat ();
  2129. float startValue = startValueValue->getFloat () * scale;
  2130. float endValue = endValueValue->getFloat () * scale;
  2131. for (uint32_t i = 0; i < count; i++) {
  2132. auto& p = particles[i];
  2133. if (!p.alive) {
  2134. continue;
  2135. }
  2136. float life = p.getLifetimePos ();
  2137. float multiplier = WallpaperEngine::Maths::fadeValue (life, startTime, endTime, startValue, endValue);
  2138. p.size *= multiplier;
  2139. }
  2140. };
  2141. }
  2142. OperatorFunc CParticle::createAlphaChangeOperator (const AlphaChangeOperator& op) {
  2143. DynamicValue* startTimeValue = op.startTime->value.get ();
  2144. DynamicValue* endTimeValue = op.endTime->value.get ();
  2145. DynamicValue* startValueValue = op.startValue->value.get ();
  2146. DynamicValue* endValueValue = op.endValue->value.get ();
  2147. m_resetAlphaFromBase = true;
  2148. return
  2149. [startTimeValue, endTimeValue, startValueValue, endValueValue] (
  2150. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
  2151. ) {
  2152. float startTime = startTimeValue->getFloat ();
  2153. float endTime = endTimeValue->getFloat ();
  2154. float startValue = startValueValue->getFloat ();
  2155. float endValue = endValueValue->getFloat ();
  2156. for (uint32_t i = 0; i < count; i++) {
  2157. auto& p = particles[i];
  2158. if (!p.alive) {
  2159. continue;
  2160. }
  2161. float life = p.getLifetimePos ();
  2162. float multiplier = WallpaperEngine::Maths::fadeValue (life, startTime, endTime, startValue, endValue);
  2163. p.alpha *= multiplier;
  2164. }
  2165. };
  2166. }
  2167. OperatorFunc CParticle::createColorChangeOperator (const ColorChangeOperator& op) {
  2168. DynamicValue* startTimeValue = op.startTime->value.get ();
  2169. DynamicValue* endTimeValue = op.endTime->value.get ();
  2170. DynamicValue* startValueValue = op.startValue->value.get ();
  2171. DynamicValue* endValueValue = op.endValue->value.get ();
  2172. // system flag 8: the pass starts from the spawn color
  2173. m_resetColorFromBase = true;
  2174. return
  2175. [this, startTimeValue, endTimeValue, startValueValue, endValueValue] (
  2176. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
  2177. ) {
  2178. float startTime = startTimeValue->getFloat ();
  2179. float endTime = endTimeValue->getFloat ();
  2180. glm::vec3 startValue = startValueValue->getVec3 ();
  2181. glm::vec3 endValue = endValueValue->getVec3 ();
  2182. // sub_1401D15A0 case 0xC, same shift as colorrandom
  2183. if (m_colorOverride.active) {
  2184. startValue = shiftColor (startValue, m_colorOverride.shift);
  2185. endValue = shiftColor (endValue, m_colorOverride.shift);
  2186. }
  2187. for (uint32_t i = 0; i < count; i++) {
  2188. auto& p = particles[i];
  2189. if (!p.alive) {
  2190. continue;
  2191. }
  2192. float life = p.getLifetimePos ();
  2193. glm::vec3 color;
  2194. color.r = WallpaperEngine::Maths::fadeValue (life, startTime, endTime, startValue.r, endValue.r);
  2195. color.g = WallpaperEngine::Maths::fadeValue (life, startTime, endTime, startValue.g, endValue.g);
  2196. color.b = WallpaperEngine::Maths::fadeValue (life, startTime, endTime, startValue.b, endValue.b);
  2197. p.color *= color;
  2198. }
  2199. };
  2200. }
  2201. OperatorFunc CParticle::createTurbulenceOperator (const TurbulenceOperator& op) {
  2202. DynamicValue* scaleValue = op.scale ? op.scale->value.get () : nullptr;
  2203. DynamicValue* speedMinValue = op.speedMin ? op.speedMin->value.get () : nullptr;
  2204. DynamicValue* speedMaxValue = op.speedMax ? op.speedMax->value.get () : nullptr;
  2205. DynamicValue* timeScaleValue = op.timeScale ? op.timeScale->value.get () : nullptr;
  2206. DynamicValue* maskValue = op.mask ? op.mask->value.get () : nullptr;
  2207. DynamicValue* phaseMinValue = op.phaseMin->value.get ();
  2208. DynamicValue* phaseMaxValue = op.phaseMax->value.get ();
  2209. // the loader binds speedmin/speedmax to the speed override unless particle flag 0x10, timescale to the rate
  2210. DynamicValue* speedOverride
  2211. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  2212. DynamicValue* rateOverride = m_particle.instanceOverride.rate->value.get ();
  2213. DynamicValue* audioModeValue = op.audioProcessingMode->value.get ();
  2214. DynamicValue* audioBoundsValue = op.audioProcessingBounds->value.get ();
  2215. DynamicValue* audioExponentValue = op.audioProcessingExponent->value.get ();
  2216. DynamicValue* audioStartValue = op.audioProcessingFrequencyStart->value.get ();
  2217. DynamicValue* audioEndValue = op.audioProcessingFrequencyEnd->value.get ();
  2218. this->m_usesParticleSeed = true;
  2219. // sub_14023FBC0 case 14, defaults from sub_1401BEB80. phasemin is loaded but never read
  2220. return [this, scaleValue, speedMinValue, speedMaxValue, timeScaleValue, maskValue, phaseMinValue, phaseMaxValue,
  2221. speedOverride, rateOverride, audioModeValue, audioBoundsValue, audioExponentValue, audioStartValue,
  2222. audioEndValue] (
  2223. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
  2224. float dt
  2225. ) {
  2226. const bool flat = !getScene ().getCamera ().isPerspective ();
  2227. const glm::vec3 mask
  2228. = maskValue != nullptr ? maskValue->getVec3 () : (flat ? glm::vec3 (1.0f, 1.0f, 0.0f) : glm::vec3 (1.0f));
  2229. if (mask.x == 0.0f && mask.y == 0.0f && mask.z == 0.0f) {
  2230. return;
  2231. }
  2232. const float audio = audioModeValue->getInt () != 0
  2233. ? sampleAudio (
  2234. audioModeValue->getInt (), audioBoundsValue->getVec2 (), audioExponentValue->getFloat (),
  2235. audioStartValue->getInt (), audioEndValue->getInt ()
  2236. )
  2237. : 1.0f;
  2238. const float speed = speedOverride != nullptr ? speedOverride->getFloat () : 1.0f;
  2239. const float speedMin = (speedMinValue != nullptr ? speedMinValue->getFloat () : (flat ? 500.0f : 1.0f)) * speed;
  2240. const float speedMax
  2241. = (speedMaxValue != nullptr ? speedMaxValue->getFloat () : (flat ? 1000.0f : 5.0f)) * speed;
  2242. const float speedRange = (speedMax - speedMin) * audio;
  2243. const float scaledMin = speedMin * audio;
  2244. const float phaseRange = phaseMaxValue->getFloat () - phaseMinValue->getFloat ();
  2245. const float scale = scaleValue != nullptr ? scaleValue->getFloat () : (flat ? 0.01f : 0.5f);
  2246. const float timeScale = (timeScaleValue != nullptr ? timeScaleValue->getFloat () : (flat ? 20.0f : 1.0f))
  2247. * rateOverride->getFloat ();
  2248. // the renderer's scene clock moves the noise field
  2249. const float time = getScene ().getSceneClock () * timeScale;
  2250. const glm::vec3 step = mask * frameScaledDelta (dt);
  2251. const auto push = [&] (ParticleInstance& p) {
  2252. const float phase = p.seed * phaseRange + time;
  2253. const float x = scale * (phase + p.position.x);
  2254. const float y = scale * (phase + p.position.y);
  2255. const float z = scale * (phase + p.position.z);
  2256. const float strength = p.seed * speedRange + scaledMin;
  2257. glm::vec3 delta (0.0f);
  2258. if (mask.x != 0.0f) {
  2259. delta.x = simplexNoise3D (x, y, z);
  2260. }
  2261. if (mask.y != 0.0f) {
  2262. delta.y = simplexNoise3D (z, x, y);
  2263. }
  2264. if (mask.z != 0.0f) {
  2265. delta.z = simplexNoise3D (y, z, x);
  2266. }
  2267. delta *= step * strength;
  2268. p.velocity += delta;
  2269. };
  2270. // every pool slot, dead ones included
  2271. for (uint32_t i = 0; i < count; i++) {
  2272. if (particles[i].alive) {
  2273. push (particles[i]);
  2274. }
  2275. }
  2276. for (uint32_t slot = 0; slot < m_ghostUsed.size (); slot++) {
  2277. if (m_ghostUsed[slot]) {
  2278. push (m_ghosts[slot]);
  2279. }
  2280. }
  2281. };
  2282. }
  2283. OperatorFunc CParticle::createVortexOperator (const VortexOperator& op) {
  2284. const int controlPoint = op.controlPoint;
  2285. const bool v2 = op.v2;
  2286. const bool infiniteAxis = (op.flags & 1) != 0;
  2287. // vortex (v1) reads neither centerforce nor the ring
  2288. const bool useCenterForce = v2 && (op.flags & 2) != 0;
  2289. const bool ringShape = v2 && (op.flags & 4) != 0;
  2290. const BlendWindow blend = makeBlendWindow (op.blend);
  2291. DynamicValue* axisValue = op.axis->value.get ();
  2292. DynamicValue* offsetValue = op.offset->value.get ();
  2293. DynamicValue* distanceInnerValue = op.distanceInner ? op.distanceInner->value.get () : nullptr;
  2294. DynamicValue* distanceOuterValue = op.distanceOuter ? op.distanceOuter->value.get () : nullptr;
  2295. DynamicValue* speedInnerValue = op.speedInner ? op.speedInner->value.get () : nullptr;
  2296. DynamicValue* speedOuterValue = op.speedOuter->value.get ();
  2297. DynamicValue* centerForceValue = op.centerForce->value.get ();
  2298. DynamicValue* ringRadiusValue = op.ringRadius ? op.ringRadius->value.get () : nullptr;
  2299. DynamicValue* ringWidthValue = op.ringWidth ? op.ringWidth->value.get () : nullptr;
  2300. DynamicValue* ringPullDistanceValue = op.ringPullDistance ? op.ringPullDistance->value.get () : nullptr;
  2301. DynamicValue* ringPullForceValue = op.ringPullForce ? op.ringPullForce->value.get () : nullptr;
  2302. DynamicValue* audioModeValue = op.audioProcessingMode->value.get ();
  2303. DynamicValue* audioBoundsValue = op.audioProcessingBounds->value.get ();
  2304. DynamicValue* audioExponentValue = op.audioProcessingExponent->value.get ();
  2305. DynamicValue* audioStartValue = op.audioProcessingFrequencyStart->value.get ();
  2306. DynamicValue* audioEndValue = op.audioProcessingFrequencyEnd->value.get ();
  2307. DynamicValue* speedOverride
  2308. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  2309. // sub_14023FBC0 cases 15/16 (vortex) and 37 (vortex_v2), loaders sub_1401C5490, defaults sub_1401BEF00 /
  2310. // sub_1401BF2D0
  2311. return [this, controlPoint, v2, infiniteAxis, useCenterForce, ringShape, blend, axisValue, offsetValue,
  2312. distanceInnerValue, distanceOuterValue, speedInnerValue, speedOuterValue, centerForceValue, ringRadiusValue,
  2313. ringWidthValue, ringPullDistanceValue, ringPullForceValue, audioModeValue, audioBoundsValue,
  2314. audioExponentValue, audioStartValue, audioEndValue, speedOverride] (
  2315. std::vector<ParticleInstance>& particles, uint32_t count,
  2316. const std::vector<ControlPointData>& controlPoints, float, float dt
  2317. ) {
  2318. const bool flat = !getScene ().getCamera ().isPerspective ();
  2319. const float audio = audioModeValue->getInt () != 0
  2320. ? sampleAudio (
  2321. audioModeValue->getInt (), audioBoundsValue->getVec2 (), audioExponentValue->getFloat (),
  2322. audioStartValue->getInt (), audioEndValue->getInt ()
  2323. )
  2324. : 1.0f;
  2325. const float speedScale = speedOverride != nullptr ? speedOverride->getFloat () : 1.0f;
  2326. const float speedInner
  2327. = (speedInnerValue != nullptr ? speedInnerValue->getFloat () : (flat ? 2500.0f : 1.0f)) * speedScale;
  2328. const float speedOuter = speedOuterValue->getFloat () * speedScale;
  2329. const float scaledDt = frameScaledDelta (dt);
  2330. const float innerSpeed = speedInner * audio * scaledDt;
  2331. const float speedRange = (speedOuter - speedInner) * audio * scaledDt;
  2332. // the loader normalizes the axis, (0, 0, 1) when it is too short
  2333. glm::vec3 axis = axisValue->getVec3 ();
  2334. axis = glm::length (axis) >= 0.001f ? glm::normalize (axis) : glm::vec3 (0.0f, 0.0f, 1.0f);
  2335. const ControlPointData& point = controlPoints[controlPoint];
  2336. glm::vec3 center = point.position;
  2337. if (v2) {
  2338. // turned (and scaled) by the control point's matrix, not normalized again
  2339. axis = point.orientation * axis;
  2340. } else {
  2341. center += offsetValue->getVec3 ();
  2342. }
  2343. float start;
  2344. float rangeScale;
  2345. if (ringShape) {
  2346. const float pullDistance
  2347. = ringPullDistanceValue != nullptr ? ringPullDistanceValue->getFloat () : (flat ? 50.0f : 0.25f);
  2348. start = ringWidthValue != nullptr ? ringWidthValue->getFloat () : (flat ? 50.0f : 0.2f);
  2349. rangeScale = pullDistance != 0.0f ? 1.0f / pullDistance : 1.0f;
  2350. } else {
  2351. const float distanceOuter
  2352. = distanceOuterValue != nullptr ? distanceOuterValue->getFloat () : (flat ? 650.0f : 2.0f);
  2353. start = distanceInnerValue != nullptr ? distanceInnerValue->getFloat () : (flat ? 500.0f : 1.0f);
  2354. rangeScale = start != distanceOuter ? 1.0f / (distanceOuter - start) : 1.0f;
  2355. }
  2356. const float ringRadius = ringRadiusValue != nullptr ? ringRadiusValue->getFloat () : (flat ? 300.0f : 1.0f);
  2357. const float ringPull
  2358. = (ringPullForceValue != nullptr ? ringPullForceValue->getFloat () : (flat ? 10.0f : 0.05f)) * dt;
  2359. const float centerPull = useCenterForce ? centerForceValue->getFloat () / dt : 0.0f;
  2360. const auto spin = [&] (ParticleInstance& p) {
  2361. const glm::vec3& position = p.position;
  2362. const glm::vec3& velocity = p.velocity;
  2363. const glm::vec3 toParticle = position - center;
  2364. const glm::vec3 along = infiniteAxis ? axis * glm::dot (toParticle, axis) : glm::vec3 (0.0f);
  2365. const glm::vec3 radial = toParticle - along;
  2366. const float distance = glm::length (radial);
  2367. // WE's rsqrt turns a particle on the axis into NaN, leave it alone instead
  2368. if (distance == 0.0f) {
  2369. return;
  2370. }
  2371. const glm::vec3 direction = radial / distance;
  2372. const float weight = v2 && blend.active ? blendWeight (blend, p) : 1.0f;
  2373. float t;
  2374. if (ringShape) {
  2375. t = std::clamp ((std::abs (ringRadius - distance) - start) * rangeScale, 0.0f, 1.0f);
  2376. } else {
  2377. t = std::clamp ((distance - start) * rangeScale, 0.0f, 1.0f);
  2378. }
  2379. glm::vec3 change = glm::cross (direction, axis) * ((t * speedRange + innerSpeed) * weight);
  2380. if (v2) {
  2381. // keeps the particle at its distance from the axis over the coming move, and pulls it onto the ring
  2382. const glm::vec3 next = velocity * dt + position - center - along;
  2383. const float nextDistance = glm::length (next);
  2384. float pull = nextDistance > 0.0f ? (distance / nextDistance - 1.0f) * centerPull : 0.0f;
  2385. if (ringShape) {
  2386. const float falloff = 1.0f - t;
  2387. pull += (falloff != 1.0f ? std::copysign (falloff, ringRadius - distance) : 0.0f) * ringPull;
  2388. }
  2389. change += next * (pull * weight);
  2390. }
  2391. p.velocity += change;
  2392. };
  2393. for (uint32_t i = 0; i < count; i++) {
  2394. if (particles[i].alive) {
  2395. spin (particles[i]);
  2396. }
  2397. }
  2398. for (uint32_t slot = 0; slot < m_ghostUsed.size (); slot++) {
  2399. if (m_ghostUsed[slot]) {
  2400. spin (m_ghosts[slot]);
  2401. }
  2402. }
  2403. };
  2404. }
  2405. OperatorFunc CParticle::createControlPointAttractOperator (const ControlPointAttractOperator& op) {
  2406. const int controlPoint = op.controlPoint;
  2407. const bool deleteNear = (op.flags & 1) != 0;
  2408. const bool clampToPoint = (op.flags & 2) != 0;
  2409. DynamicValue* scaleValue = op.scale ? op.scale->value.get () : nullptr;
  2410. DynamicValue* thresholdValue = op.threshold ? op.threshold->value.get () : nullptr;
  2411. DynamicValue* deleteThresholdValue = op.deleteThreshold ? op.deleteThreshold->value.get () : nullptr;
  2412. DynamicValue* speedOverride
  2413. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  2414. if (deleteNear) {
  2415. m_tracksPreviousPosition = true;
  2416. }
  2417. // sub_14023FBC0 case 10, defaults from sub_1401BDEE0
  2418. return [this, controlPoint, deleteNear, clampToPoint, scaleValue, thresholdValue, deleteThresholdValue,
  2419. speedOverride] (
  2420. std::vector<ParticleInstance>& particles, uint32_t count,
  2421. const std::vector<ControlPointData>& controlPoints, float, float dt
  2422. ) {
  2423. const bool flat = !getScene ().getCamera ().isPerspective ();
  2424. const float scale = (scaleValue != nullptr ? scaleValue->getFloat () : (flat ? 512.0f : 20.0f))
  2425. * (speedOverride != nullptr ? speedOverride->getFloat () : 1.0f);
  2426. const float threshold = thresholdValue != nullptr ? thresholdValue->getFloat () : (flat ? 512.0f : 5.0f);
  2427. const float force = scale * frameScaledDelta (dt);
  2428. const glm::vec3 center = controlPoints[controlPoint].position;
  2429. const auto attract = [&] (ParticleInstance& p) {
  2430. const glm::vec3 toCenter = center - p.position;
  2431. const float distance = glm::length (toCenter);
  2432. if (!(distance < threshold) || !(distance > std::numeric_limits<float>::min ())) {
  2433. return;
  2434. }
  2435. float pull = (1.0f - distance / threshold) * force;
  2436. if (clampToPoint && distance < pull) {
  2437. pull = distance;
  2438. }
  2439. p.velocity += toCenter * (pull / distance);
  2440. };
  2441. for (uint32_t i = 0; i < count; i++) {
  2442. if (particles[i].alive) {
  2443. attract (particles[i]);
  2444. }
  2445. }
  2446. for (uint32_t slot = 0; slot < m_ghostUsed.size (); slot++) {
  2447. if (m_ghostUsed[slot]) {
  2448. attract (m_ghosts[slot]);
  2449. }
  2450. }
  2451. if (!deleteNear) {
  2452. return;
  2453. }
  2454. // sub_14022A150: a particle whose step since the operators started came within deletethreshold dies
  2455. const float deleteThreshold
  2456. = deleteThresholdValue != nullptr ? deleteThresholdValue->getFloat () : (flat ? 15.0f : 0.5f);
  2457. for (uint32_t i = 0; i < count; i++) {
  2458. auto& p = particles[i];
  2459. if (!p.alive) {
  2460. continue;
  2461. }
  2462. const glm::vec3 step = p.position - p.previousPosition;
  2463. const float length = glm::length (step);
  2464. const glm::vec3 direction = length > 0.0f ? step / length : step;
  2465. const float along = std::clamp (glm::dot (center - p.previousPosition, direction), 0.0f, length);
  2466. const glm::vec3 closest = center - (p.previousPosition + direction * along);
  2467. if (!(deleteThreshold * deleteThreshold < glm::dot (closest, closest))) {
  2468. p.age = p.lifetime;
  2469. }
  2470. }
  2471. };
  2472. }
  2473. namespace {
  2474. /** oscillatealpha/oscillatesize as the loader stores them: min and max - min */
  2475. struct OscillationRanges {
  2476. float frequencyMin;
  2477. float frequencyRange;
  2478. float phaseMin;
  2479. float phaseRange;
  2480. float scaleMin;
  2481. float scaleRange;
  2482. };
  2483. template <typename T> OscillationRanges oscillationRanges (const T& op) {
  2484. const float frequencyMin = op.frequencyMin->value->getFloat ();
  2485. const float phaseMin = op.phaseMin->value->getFloat ();
  2486. const float scaleMin = op.scaleMin->value->getFloat ();
  2487. return {
  2488. .frequencyMin = frequencyMin,
  2489. .frequencyRange = op.frequencyMax->value->getFloat () - frequencyMin,
  2490. .phaseMin = phaseMin,
  2491. .phaseRange = op.phaseMax->value->getFloat () - phaseMin,
  2492. .scaleMin = scaleMin,
  2493. .scaleRange = op.scaleMax->value->getFloat () - scaleMin,
  2494. };
  2495. }
  2496. /** sub_14023FBC0 cases 8/9, from the particle's spawn random */
  2497. float oscillateFactor (const ParticleInstance& p, const OscillationRanges& ranges) {
  2498. const float frequency = p.seed * ranges.frequencyRange + ranges.frequencyMin;
  2499. const float phase = p.seed * ranges.phaseRange + ranges.phaseMin;
  2500. return (std::sin ((phase + p.age) * frequency) + 1.0f) * (p.seed * ranges.scaleRange * 0.5f) + ranges.scaleMin;
  2501. }
  2502. }
  2503. OperatorFunc CParticle::createOscillateAlphaOperator (const OscillateAlphaOperator& op) {
  2504. const OscillateAlphaOperator* definition = &op;
  2505. const BlendWindow blend = makeBlendWindow (op.blend);
  2506. m_resetAlphaFromBase = true;
  2507. m_usesParticleSeed = true;
  2508. // case 8, blended 30 lerps the factor from 1
  2509. return
  2510. [definition, blend] (
  2511. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
  2512. ) {
  2513. const OscillationRanges ranges = oscillationRanges (*definition);
  2514. for (uint32_t i = 0; i < count; i++) {
  2515. auto& p = particles[i];
  2516. if (!p.alive) {
  2517. continue;
  2518. }
  2519. const float factor = oscillateFactor (p, ranges);
  2520. p.alpha *= blend.active ? 1.0f - (1.0f - factor) * blendWeight (blend, p) : factor;
  2521. }
  2522. };
  2523. }
  2524. OperatorFunc CParticle::createOscillateSizeOperator (const OscillateSizeOperator& op) {
  2525. const OscillateSizeOperator* definition = &op;
  2526. const BlendWindow blend = makeBlendWindow (op.blend);
  2527. m_usesParticleSeed = true;
  2528. // case 9, blended 31
  2529. return
  2530. [definition, blend] (
  2531. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
  2532. ) {
  2533. const OscillationRanges ranges = oscillationRanges (*definition);
  2534. for (uint32_t i = 0; i < count; i++) {
  2535. auto& p = particles[i];
  2536. if (!p.alive) {
  2537. continue;
  2538. }
  2539. const float factor = oscillateFactor (p, ranges);
  2540. p.size *= blend.active ? 1.0f - (1.0f - factor) * blendWeight (blend, p) : factor;
  2541. }
  2542. };
  2543. }
  2544. OperatorFunc CParticle::createOscillatePositionOperator (const OscillatePositionOperator& op) {
  2545. DynamicValue* frequencyMinValue = op.frequencyMin->value.get ();
  2546. DynamicValue* frequencyMaxValue = op.frequencyMax->value.get ();
  2547. DynamicValue* phaseMinValue = op.phaseMin->value.get ();
  2548. DynamicValue* phaseMaxValue = op.phaseMax->value.get ();
  2549. DynamicValue* scaleMinValue = op.scaleMin->value.get ();
  2550. DynamicValue* scaleMaxValue = op.scaleMax ? op.scaleMax->value.get () : nullptr;
  2551. DynamicValue* maskValue = op.mask->value.get ();
  2552. // the loader binds the frequencies to the speed override unless particle flag 0x10
  2553. DynamicValue* speedOverride
  2554. = (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
  2555. const BlendWindow blend = makeBlendWindow (op.blend);
  2556. m_usesParticleSeed = true;
  2557. // case 7, blended 29 scales the move by the weight. x and z share one wave, y's is 2pi * random ahead. Its
  2558. // phase is in seconds, the move is the wave's change since the last frame
  2559. return [this, frequencyMinValue, frequencyMaxValue, phaseMinValue, phaseMaxValue, scaleMinValue, scaleMaxValue,
  2560. maskValue, speedOverride, blend] (
  2561. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
  2562. float dt
  2563. ) {
  2564. const float speed = speedOverride != nullptr ? speedOverride->getFloat () : 1.0f;
  2565. const float frequencyMin = frequencyMinValue->getFloat () * speed;
  2566. const float frequencyRange = frequencyMaxValue->getFloat () * speed - frequencyMin;
  2567. const float phaseMin = phaseMinValue->getFloat ();
  2568. const float phaseRange = phaseMaxValue->getFloat () - phaseMin;
  2569. const float scaleMin = scaleMinValue->getFloat ();
  2570. const float scaleMax = scaleMaxValue != nullptr ? scaleMaxValue->getFloat ()
  2571. : (getScene ().getCamera ().isPerspective () ? 0.5f : 10.0f);
  2572. const float scaleRange = scaleMax - scaleMin;
  2573. const glm::vec3 mask = maskValue->getVec3 ();
  2574. for (uint32_t i = 0; i < count; i++) {
  2575. auto& p = particles[i];
  2576. if (!p.alive) {
  2577. continue;
  2578. }
  2579. const float frequency = p.seed * frequencyRange + frequencyMin;
  2580. const float time = p.seed * phaseRange + phaseMin + p.age;
  2581. const float shifted = p.seed * 6.2831855f + time;
  2582. float scale = p.seed * scaleRange + scaleMin;
  2583. if (blend.active) {
  2584. scale *= blendWeight (blend, p);
  2585. }
  2586. const float wave = (std::sin (time * frequency) - std::sin ((time - dt) * frequency)) * scale;
  2587. const float waveY = (std::sin (shifted * frequency) - std::sin ((shifted - dt) * frequency)) * scale;
  2588. p.position += glm::vec3 (wave * mask.x, waveY * mask.y, wave * mask.z);
  2589. }
  2590. };
  2591. }
  2592. namespace {
  2593. /** 0.0 up to the zero range wallpaper64.exe replaces with FLT_EPSILON */
  2594. glm::vec3 remapRange (const glm::vec3& min, const glm::vec3& max) {
  2595. glm::vec3 range = max - min;
  2596. for (int i = 0; i < 3; i++) {
  2597. if (range[i] == 0.0f) {
  2598. range[i] = 1.1920929e-7f;
  2599. }
  2600. }
  2601. return range;
  2602. }
  2603. bool remapIsVector (ParticleRemapValue value) { return static_cast<int> (value) > 12; }
  2604. glm::vec3 remapSelectComponent (const glm::vec3& value, ParticleRemapComponent component) {
  2605. switch (component) {
  2606. case ParticleRemapComponent::X:
  2607. return glm::vec3 (value.x);
  2608. case ParticleRemapComponent::Y:
  2609. return glm::vec3 (value.y);
  2610. case ParticleRemapComponent::Z:
  2611. return glm::vec3 (value.z);
  2612. case ParticleRemapComponent::Sum:
  2613. return glm::vec3 ((value.y + value.x) + value.z);
  2614. case ParticleRemapComponent::Average:
  2615. return glm::vec3 (((value.y + value.x) + value.z) * 0.33333334f);
  2616. case ParticleRemapComponent::Max:
  2617. return glm::vec3 (std::fmax (std::fmax (value.x, value.y), value.z));
  2618. case ParticleRemapComponent::Min:
  2619. return glm::vec3 (std::fmin (std::fmin (value.x, value.y), value.z));
  2620. default:
  2621. return value;
  2622. }
  2623. }
  2624. float remapApply (ParticleRemapOperation operation, float current, float value) {
  2625. switch (operation) {
  2626. case ParticleRemapOperation::Remap:
  2627. return value;
  2628. case ParticleRemapOperation::Multiply:
  2629. return value * current;
  2630. case ParticleRemapOperation::Add:
  2631. return value + current;
  2632. case ParticleRemapOperation::Subtract:
  2633. return current - value;
  2634. default:
  2635. return current;
  2636. }
  2637. }
  2638. template <typename Apply>
  2639. glm::vec3 remapComponents (
  2640. ParticleRemapComponent component, const Apply& apply, glm::vec3 current, const glm::vec3& target, bool allFromX
  2641. ) {
  2642. switch (component) {
  2643. case ParticleRemapComponent::All:
  2644. for (int c = 0; c < 3; c++) {
  2645. current[c] = apply (current[c], allFromX ? target.x : target[c]);
  2646. }
  2647. break;
  2648. case ParticleRemapComponent::X:
  2649. current.x = apply (current.x, target.x);
  2650. break;
  2651. case ParticleRemapComponent::Y:
  2652. current.y = apply (current.y, target.y);
  2653. break;
  2654. case ParticleRemapComponent::Z:
  2655. current.z = apply (current.z, target.z);
  2656. break;
  2657. default:
  2658. break;
  2659. }
  2660. return current;
  2661. }
  2662. /** The transform functions of sub_14023FBC0 case 19, seed is the particle's random as integer bits */
  2663. float remapTransformOperator (
  2664. ParticleRemapTransform transform, float value, float scale, int octaves, float fbmAmplitude, int32_t seed
  2665. ) {
  2666. switch (transform) {
  2667. case ParticleRemapTransform::Sine:
  2668. return std::sin (value * (scale * glm::pi<float> ()) - glm::half_pi<float> ()) * 0.5f + 0.5f;
  2669. case ParticleRemapTransform::Square:
  2670. {
  2671. const float scaled = value * scale;
  2672. return std::nearbyint (scaled - std::trunc (scaled)) + (scaled < 0.0f ? 1.0f : 0.0f);
  2673. }
  2674. case ParticleRemapTransform::Saw:
  2675. {
  2676. const float scaled = value * scale;
  2677. return (scaled - std::trunc (scaled)) + (value < 0.0f ? 1.0f : 0.0f);
  2678. }
  2679. case ParticleRemapTransform::Triangle:
  2680. {
  2681. const float scaled = std::fabs (value * scale);
  2682. return 1.0f - std::fabs ((scaled - std::trunc (scaled)) * 2.0f - 1.0f);
  2683. }
  2684. case ParticleRemapTransform::SimplexNoise:
  2685. return hashedNoise2D (seed, value * scale, 0.0f) * 0.5f + 0.5f;
  2686. case ParticleRemapTransform::FbmNoise:
  2687. return hashedNoiseFbm (octaves, fbmAmplitude, seed, value * scale, 0.0f) * 0.5f + 0.5f;
  2688. default:
  2689. return value;
  2690. }
  2691. }
  2692. /** The transform functions of sub_14023B340 case 15: floor instead of trunc, 1D noise without a seed */
  2693. float remapTransformInitial (ParticleRemapTransform transform, float value, float scale, int octaves) {
  2694. switch (transform) {
  2695. case ParticleRemapTransform::Sine:
  2696. return std::sin ((value * glm::pi<float> ()) * scale - glm::half_pi<float> ()) * 0.5f + 0.5f;
  2697. case ParticleRemapTransform::Square:
  2698. {
  2699. const float scaled = value * scale;
  2700. return std::round (scaled - std::floor (scaled)) + (scaled < 0.0f ? 1.0f : 0.0f);
  2701. }
  2702. case ParticleRemapTransform::Saw:
  2703. {
  2704. const float scaled = value * scale;
  2705. return (scaled - std::floor (scaled)) + (value < 0.0f ? 1.0f : 0.0f);
  2706. }
  2707. case ParticleRemapTransform::Triangle:
  2708. {
  2709. const float scaled = std::fabs (value * scale);
  2710. return 1.0f - std::fabs ((scaled - std::floor (scaled)) * 2.0f - 1.0f);
  2711. }
  2712. case ParticleRemapTransform::SimplexNoise:
  2713. return simplexNoise1D (value * scale) * 0.5f + 0.5f;
  2714. case ParticleRemapTransform::FbmNoise:
  2715. return simplexFbm1D (value, scale, octaves) * 0.5f + 0.5f;
  2716. default:
  2717. return value;
  2718. }
  2719. }
  2720. int32_t particleSeedBits (const ParticleInstance& p) {
  2721. int32_t bits;
  2722. std::memcpy (&bits, &p.seed, sizeof (bits));
  2723. return bits;
  2724. }
  2725. /** The engine's g_Daytime as sub_140110630 fills it: local time as a fraction of the day, milliseconds included */
  2726. float dayFraction () {
  2727. const auto now = std::chrono::system_clock::now ();
  2728. const std::time_t seconds = std::chrono::system_clock::to_time_t (now);
  2729. const auto milliseconds
  2730. = std::chrono::duration_cast<std::chrono::milliseconds> (now.time_since_epoch ()).count () % 1000;
  2731. std::tm local {};
  2732. localtime_r (&seconds, &local);
  2733. const double fraction = local.tm_min * (1.0 / 1440.0) + local.tm_hour * (1.0 / 24.0)
  2734. + local.tm_sec * (1.0 / 86400.0) + static_cast<double> (milliseconds) * (1.0 / 86400000.0);
  2735. return static_cast<float> (fraction);
  2736. }
  2737. }
  2738. glm::mat4 CParticle::localControlPointMatrix (size_t index) const {
  2739. const auto& cp = m_controlPoints[index];
  2740. glm::mat4 local = glm::translate (glm::mat4 (1.0f), cp.offset);
  2741. // sub_14022BD40, skipped for points with flags 0x10005 like WE
  2742. if (cp.followParent || index >= m_particle.instanceOverride.controlPoints.size ()) {
  2743. return local;
  2744. }
  2745. const auto& angles = m_particle.instanceOverride.controlPointAngles[index];
  2746. const auto& scriptAngles = m_scriptControlPointAngles[index];
  2747. if (angles || scriptAngles) {
  2748. const glm::vec3 angle = angles ? angles->value->getVec3 () : *scriptAngles;
  2749. const float cx = std::cos (angle.x), sx = std::sin (angle.x);
  2750. const float cy = std::cos (angle.y), sy = std::sin (angle.y);
  2751. const float cz = std::cos (angle.z), sz = std::sin (angle.z);
  2752. const glm::mat3 rotation (
  2753. cy * cz, cy * sz, -sy, sy * cz * sx - cx * sz, sy * sz * sx + cx * cz, sx * cy, cx * cz * sy + sx * sz,
  2754. cx * sz * sy - sx * cz, cx * cy
  2755. );
  2756. local[0] = glm::vec4 (rotation[0], 0.0f);
  2757. local[1] = glm::vec4 (rotation[1], 0.0f);
  2758. local[2] = glm::vec4 (rotation[2], 0.0f);
  2759. }
  2760. if (const auto& position = m_particle.instanceOverride.controlPoints[index]; position) {
  2761. local[3] = glm::vec4 (position->value->getVec3 (), 1.0f);
  2762. } else if (const auto& scriptPosition = m_scriptControlPoints[index]) {
  2763. local[3] = glm::vec4 (*scriptPosition, 1.0f);
  2764. }
  2765. return local;
  2766. }
  2767. glm::vec3 CParticle::getInstanceColor () const {
  2768. const auto& instanceOverride = m_particle.instanceOverride;
  2769. return instanceOverride.hasColor || m_scriptColor ? instanceOverride.colorn->value->getVec3 () : glm::vec3 (-1.0f);
  2770. }
  2771. void CParticle::setInstanceColor (const glm::vec3& color) {
  2772. m_scriptColor = true;
  2773. m_particle.instanceOverride.colorn->value->update (color, DynamicValue::UpdateSource::Script);
  2774. }
  2775. glm::vec3 CParticle::getInstanceControlPoint (size_t index, bool angle) const {
  2776. const auto& scene
  2777. = angle ? m_particle.instanceOverride.controlPointAngles : m_particle.instanceOverride.controlPoints;
  2778. const auto& script = angle ? m_scriptControlPointAngles : m_scriptControlPoints;
  2779. if (index >= scene.size ()) {
  2780. return glm::vec3 (0.0f);
  2781. }
  2782. if (scene[index]) {
  2783. return scene[index]->value->getVec3 ();
  2784. }
  2785. return script[index].value_or (glm::vec3 (std::numeric_limits<float>::max (), 0.0f, 0.0f));
  2786. }
  2787. void CParticle::setInstanceControlPoint (size_t index, bool angle, const glm::vec3& value) {
  2788. const auto& scene
  2789. = angle ? m_particle.instanceOverride.controlPointAngles : m_particle.instanceOverride.controlPoints;
  2790. auto& script = angle ? m_scriptControlPointAngles : m_scriptControlPoints;
  2791. if (index >= scene.size ()) {
  2792. return;
  2793. }
  2794. if (scene[index]) {
  2795. scene[index]->value->update (value, DynamicValue::UpdateSource::Script);
  2796. return;
  2797. }
  2798. // sub_14022BD40 skips a point whose x is FLT_MAX
  2799. if (value.x == std::numeric_limits<float>::max ()) {
  2800. script[index].reset ();
  2801. } else {
  2802. script[index] = value;
  2803. }
  2804. }
  2805. float CParticle::frameScaledDelta (float dt) const {
  2806. const float ratio = m_frameDelta > 0.0f ? std::min (1.0f, 0.025f / m_frameDelta) : 1.0f;
  2807. return std::pow (ratio, 0.7f) * dt;
  2808. }
  2809. float CParticle::layerTime () const {
  2810. const CParticle* root = this;
  2811. while (root->m_parent != nullptr) {
  2812. root = root->m_parent;
  2813. }
  2814. return root->m_layerTime;
  2815. }
  2816. glm::vec3 CParticle::remapLayerOrigin () const {
  2817. const CParticle* root = this;
  2818. while (root->m_parent != nullptr) {
  2819. root = root->m_parent;
  2820. }
  2821. return glm::vec3 (root->objectMatrix ()[3]);
  2822. }
  2823. InitializerFunc CParticle::createHsvColorRandomInitializer (const HsvColorRandomInitializer& init) {
  2824. DynamicValue* hueMinValue = init.hueMin->value.get ();
  2825. DynamicValue* hueMaxValue = init.hueMax->value.get ();
  2826. DynamicValue* saturationMinValue = init.saturationMin->value.get ();
  2827. DynamicValue* saturationMaxValue = init.saturationMax->value.get ();
  2828. DynamicValue* valueMinValue = init.valueMin->value.get ();
  2829. DynamicValue* valueMaxValue = init.valueMax->value.get ();
  2830. const int steps = init.hueSteps;
  2831. // wallpaper64.exe sub_14023B340 case 4, the hue step from sub_1401C5490
  2832. return [this, hueMinValue, hueMaxValue, saturationMinValue, saturationMaxValue, valueMinValue, valueMaxValue,
  2833. steps] (ParticleInstance& p) {
  2834. float hueMin = hueMinValue->getFloat ();
  2835. float hueSpan = 0.0f;
  2836. float step = 0.0f;
  2837. if (static_cast<float> (steps) > 1.0f) {
  2838. const float span = hueMaxValue->getFloat () - hueMin;
  2839. // a full circle has as many steps as hues, anything shorter ends on huemax
  2840. float divisions = static_cast<float> (steps) - 1.0f;
  2841. if (std::fabs (std::fmod (span, 1.0f)) < 0.0027777778f) {
  2842. divisions += 1.0f;
  2843. }
  2844. hueSpan = span != 0.0f ? span : 1.0f;
  2845. step = hueSpan / divisions;
  2846. }
  2847. float saturationMin = saturationMinValue->getFloat ();
  2848. float saturationSpan = saturationMaxValue->getFloat () - saturationMin;
  2849. float valueMin = valueMinValue->getFloat ();
  2850. float valueSpan = valueMaxValue->getFloat () - valueMin;
  2851. // sub_1401D15A0 case 0xD: the ranges get centered on the override color
  2852. if (m_colorOverride.active) {
  2853. const glm::vec3& target = m_colorOverride.hsv;
  2854. const auto center = [] (float goal, float& min, float& span) {
  2855. min = std::clamp (goal - (span * 0.5f + min) + min, 0.0f, 1.0f);
  2856. if (min + span > 1.0f) {
  2857. span = 1.0f - std::fmin (min, 1.0f);
  2858. }
  2859. };
  2860. center (target.y, saturationMin, saturationSpan);
  2861. center (target.z, valueMin, valueSpan);
  2862. hueMin = target.x - (hueSpan * 0.5f + hueMin) + hueMin;
  2863. }
  2864. // rand () / 32767 can reach steps + 1, clamped back
  2865. const int draw = std::uniform_int_distribution<int> (0, 32767) (m_rng);
  2866. int index = static_cast<int> ((static_cast<float> (draw) / 32767.0f) * static_cast<float> (steps + 1) + 0.0f);
  2867. index = std::max (0, std::min (steps, index));
  2868. const float hue = static_cast<float> (index) * step + hueMin;
  2869. const float saturation
  2870. = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * saturationSpan + saturationMin;
  2871. const float value = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * valueSpan + valueMin;
  2872. p.color *= WallpaperEngine::Maths::hsvToRgb ({ hue, saturation, value });
  2873. p.initial.color = p.color;
  2874. };
  2875. }
  2876. InitializerFunc CParticle::createColorListInitializer (const ColorListInitializer& init) {
  2877. // sub_1401C5490 keeps the colors as HSV, an empty list is one pure red
  2878. std::vector<glm::vec3> colors;
  2879. colors.reserve (init.colors.size ());
  2880. for (const auto& color : init.colors) {
  2881. colors.push_back (WallpaperEngine::Maths::rgbToHsv (color));
  2882. }
  2883. if (colors.empty ()) {
  2884. colors.emplace_back (0.0f, 1.0f, 1.0f);
  2885. }
  2886. DynamicValue* hueNoiseValue = init.hueNoise->value.get ();
  2887. DynamicValue* saturationNoiseValue = init.saturationNoise->value.get ();
  2888. DynamicValue* valueNoiseValue = init.valueNoise->value.get ();
  2889. // sub_14023B340 case 5: a random entry, each channel randomized within its noise
  2890. return [this, colors, hueNoiseValue, saturationNoiseValue, valueNoiseValue] (ParticleInstance& p) {
  2891. const auto& picked = colors[std::uniform_int_distribution<size_t> (0, colors.size () - 1) (m_rng)];
  2892. const glm::vec3 noise (
  2893. hueNoiseValue->getFloat (), saturationNoiseValue->getFloat (), valueNoiseValue->getFloat ()
  2894. );
  2895. // sub_1401D15A0 case 0xE: an active override color moves every entry by its distance to the first one
  2896. const glm::vec3 offset = m_colorOverride.active ? m_colorOverride.hsv - colors.front () : glm::vec3 (0.0f);
  2897. glm::vec3 hsv;
  2898. for (int i = 0; i < 3; i++) {
  2899. const float low = std::max (picked[i] - noise[i], 0.0f);
  2900. const float high = std::min (noise[i] + picked[i], 1.0f);
  2901. hsv[i] = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * (high - low) + low + offset[i];
  2902. }
  2903. hsv.x -= std::floor (hsv.x);
  2904. hsv.y = std::clamp (hsv.y, 0.0f, 1.0f);
  2905. hsv.z = std::clamp (hsv.z, 0.0f, 1.0f);
  2906. p.color *= WallpaperEngine::Maths::hsvToRgb (hsv);
  2907. p.initial.color = p.color;
  2908. };
  2909. }
  2910. InitializerFunc CParticle::createPositionOffsetRandomInitializer (const PositionOffsetRandomInitializer& init) {
  2911. DynamicValue* directionsValue = init.directions ? init.directions->value.get () : nullptr;
  2912. DynamicValue* signValue = init.sign->value.get ();
  2913. DynamicValue* scaleValue = init.scale ? init.scale->value.get () : nullptr;
  2914. DynamicValue* distanceValue = init.distance ? init.distance->value.get () : nullptr;
  2915. DynamicValue* timeScaleValue = init.timeScale->value.get ();
  2916. const int octaves = init.octaves;
  2917. // sub_14023B340 case 11, defaults from sub_1401BB660
  2918. return
  2919. [this, directionsValue, signValue, scaleValue, distanceValue, timeScaleValue, octaves] (ParticleInstance& p) {
  2920. const bool flat = !getScene ().getCamera ().isPerspective ();
  2921. const glm::vec3 directions = directionsValue != nullptr ? directionsValue->getVec3 ()
  2922. : (flat ? glm::vec3 (1, 1, 0) : glm::vec3 (1));
  2923. const float scale = scaleValue != nullptr ? scaleValue->getFloat () : (flat ? 0.001f : 1.0f);
  2924. const float distance = distanceValue != nullptr ? distanceValue->getFloat () : (flat ? 100.0f : 0.1f);
  2925. const glm::vec3 sign = signValue->getVec3 ();
  2926. // the renderer's scene clock is the time axis of the noise
  2927. const float time = timeScaleValue->getFloat () * getScene ().getSceneClock ();
  2928. const glm::vec3 position = p.position;
  2929. const auto fbm = [octaves] (float x, float y) {
  2930. float sum = 0.0f;
  2931. float total = 0.0f;
  2932. float amplitude = 1.0f;
  2933. float frequency = 1.0f;
  2934. for (int octave = 0; octave < octaves; octave++) {
  2935. const float noise = simplexNoise2D (frequency * x, frequency * y) * amplitude;
  2936. total += amplitude;
  2937. amplitude *= 0.5f;
  2938. frequency += frequency;
  2939. sum += noise;
  2940. }
  2941. return sum / total;
  2942. };
  2943. glm::vec3 offset (
  2944. fbm (position.x * scale, time) * directions.x, fbm (time, position.y * scale) * directions.y,
  2945. fbm (position.z * scale, -time) * directions.z
  2946. );
  2947. // sign pushes the offset to one side per axis
  2948. if (glm::length (sign) > 1.1920929e-7f) {
  2949. const glm::vec3 absoluteSign = glm::abs (sign);
  2950. offset = glm::abs (offset) * sign + offset * (1.0f - absoluteSign);
  2951. }
  2952. p.position = offset * distance + position;
  2953. };
  2954. }
  2955. InitializerFunc
  2956. CParticle::createMapSequenceBetweenControlPointsInitializer (const MapSequenceBetweenControlPointsInitializer& init) {
  2957. const int start = init.controlPointStart;
  2958. const int end = init.controlPointEnd;
  2959. const uint32_t flags = init.flags;
  2960. const bool mirror = init.mirror;
  2961. const float boundsMin = init.bounds.x;
  2962. const float boundsRange = init.bounds.y - init.bounds.x;
  2963. DynamicValue* arcAmountValue = init.arcAmount->value.get ();
  2964. DynamicValue* arcDirectionValue = init.arcDirection->value.get ();
  2965. DynamicValue* sizeReductionValue = init.sizeReductionAmount->value.get ();
  2966. // sub_1401C5490, with flag 0x10 the instance override's count takes part (sub_1401D15A0 case 4)
  2967. float step;
  2968. if ((flags & 0x10) != 0 && (m_particle.flags & 0x20) == 0) {
  2969. const float countOverride = m_particle.instanceOverride.count->value->getFloat ();
  2970. step = 1.0f / std::fmax (init.count * countOverride - 1.0f, 0.000099999997f);
  2971. } else {
  2972. step = 1.0f / (init.count - 1.0f <= 0.000099999997f ? 0.000099999997f : init.count - 1.0f);
  2973. }
  2974. SequenceCounter& counter
  2975. = m_sequences.emplace_back (SequenceCounter { .step = step, .periodReset = (flags & 0x20) != 0 });
  2976. // sub_14023B340 case 14: spread along the line between two control points, one step per particle
  2977. return [this, start, end, flags, mirror, boundsMin, boundsRange, arcAmountValue, arcDirectionValue,
  2978. sizeReductionValue, &counter] (ParticleInstance& p) {
  2979. float& sequence = counter.sequence;
  2980. float& stride = counter.step;
  2981. const glm::vec3 first = m_controlPoints[start].position;
  2982. const glm::vec3 line = m_controlPoints[end].position - first;
  2983. const float length = std::fmax (glm::length (line), 1.1754944e-38f);
  2984. const glm::vec3 direction = line / length;
  2985. glm::vec3 position = p.position;
  2986. if (m_worldSpace) {
  2987. position -= first;
  2988. }
  2989. const float along = glm::dot (position, direction);
  2990. glm::vec3 offset = position - along * direction;
  2991. const float at = sequence * boundsRange + boundsMin;
  2992. const float middle = 1.0f - std::pow (std::fabs ((sequence + sequence) - 1.0f), 2.0f);
  2993. if ((flags & 1) != 0) {
  2994. offset *= middle;
  2995. }
  2996. position = offset + ((at * direction) * length + first);
  2997. if ((flags & 8) != 0) {
  2998. position += arcDirectionValue->getVec3 () * (middle * length * arcAmountValue->getFloat ());
  2999. }
  3000. p.position = position;
  3001. if ((flags & 2) != 0) {
  3002. p.velocity *= middle;
  3003. }
  3004. if ((flags & 4) != 0) {
  3005. const float reduction = sizeReductionValue->getFloat ();
  3006. p.size *= (1.0f - reduction) + reduction * middle;
  3007. p.initial.size = p.size;
  3008. }
  3009. sequence += stride;
  3010. if (sequence > 1.0f) {
  3011. if (mirror) {
  3012. stride = -stride;
  3013. sequence = 1.0f - (sequence - 1.0f);
  3014. } else {
  3015. sequence = 0.0f;
  3016. }
  3017. } else if (sequence < 0.0f) {
  3018. sequence = -sequence;
  3019. stride = -stride;
  3020. }
  3021. };
  3022. }
  3023. glm::vec3 CParticle::remapInitialInput (const ParticleRemap& remap, ParticleInstance& p) {
  3024. // sub_14023B340 case 15: scalars fill every component, the base values are read where the engine keeps them
  3025. switch (remap.input) {
  3026. case ParticleRemapValue::LifetimeFraction:
  3027. // the sprite frame array, only filled at spawn for randomframe (with the particle's random)
  3028. return glm::vec3 (m_particle.animationMode == "randomframe" ? p.seed : 0.0f);
  3029. case ParticleRemapValue::MaxLifetime:
  3030. return glm::vec3 (p.lifetime);
  3031. case ParticleRemapValue::Size:
  3032. return glm::vec3 (p.initial.size);
  3033. case ParticleRemapValue::Opacity:
  3034. return glm::vec3 (p.initial.alpha);
  3035. case ParticleRemapValue::Speed:
  3036. return glm::vec3 (glm::length (p.velocity));
  3037. case ParticleRemapValue::Rotation:
  3038. return glm::vec3 (p.rotation.z);
  3039. case ParticleRemapValue::AngularSpeed:
  3040. return glm::vec3 (m_hasAngularVelocity ? p.angularVelocity.z : 0.0f);
  3041. case ParticleRemapValue::DistanceToControlPoint:
  3042. return glm::vec3 (glm::length (p.position - m_controlPoints[remap.inputControlPoint0].position));
  3043. case ParticleRemapValue::PositionBetweenTwoControlPoints:
  3044. {
  3045. // the engine reads the output control points here, same as remapvalue
  3046. const glm::vec3 first = m_controlPoints[remap.outputControlPoint0].position;
  3047. glm::vec3 line = m_controlPoints[remap.outputControlPoint1].position - first;
  3048. const float length = glm::length (line);
  3049. if (length <= 1.1920929e-7f) {
  3050. return glm::vec3 (0.0f);
  3051. }
  3052. line /= length;
  3053. return glm::vec3 (glm::dot (p.position - first, line) / length);
  3054. }
  3055. case ParticleRemapValue::Runtime:
  3056. return glm::vec3 (getScene ().getSceneClock ());
  3057. case ParticleRemapValue::TimeOfDay:
  3058. return glm::vec3 (dayFraction ());
  3059. case ParticleRemapValue::ParticleSystemTime:
  3060. return glm::vec3 (m_systemTime);
  3061. case ParticleRemapValue::LayerTime:
  3062. return glm::vec3 (layerTime ());
  3063. case ParticleRemapValue::Color:
  3064. return p.initial.color;
  3065. case ParticleRemapValue::Position:
  3066. return p.position;
  3067. case ParticleRemapValue::Velocity:
  3068. return p.velocity;
  3069. case ParticleRemapValue::ControlPoint:
  3070. case ParticleRemapValue::DeltaToControlPoint:
  3071. case ParticleRemapValue::DirectionToControlPoint:
  3072. {
  3073. // the engine writes zeros into the control point's translation here instead of reading it
  3074. m_controlPoints[remap.inputControlPoint0].position = glm::vec3 (0.0f);
  3075. if (remap.input == ParticleRemapValue::ControlPoint) {
  3076. return glm::vec3 (0.0f);
  3077. }
  3078. const glm::vec3 delta = -p.position;
  3079. if (remap.input == ParticleRemapValue::DeltaToControlPoint) {
  3080. return delta;
  3081. }
  3082. const float length = glm::length (delta);
  3083. return length != 0.0f ? delta / length : glm::vec3 (0.0f);
  3084. }
  3085. case ParticleRemapValue::LayerOrigin:
  3086. return remapLayerOrigin ();
  3087. default:
  3088. return glm::vec3 (0.0f);
  3089. }
  3090. }
  3091. InitializerFunc CParticle::createRemapInitialValueInitializer (const RemapInitialValueInitializer& init) {
  3092. const ParticleRemap remap = init.remap;
  3093. const glm::vec3 inputRange = remapRange (remap.inputRangeMin, remap.inputRangeMax);
  3094. const glm::vec3 outputRange = remap.outputRangeMax - remap.outputRangeMin;
  3095. if (remap.input == ParticleRemapValue::LifetimeFraction && m_particle.animationMode == "randomframe") {
  3096. m_usesParticleSeed = true;
  3097. }
  3098. return [this, remap, inputRange, outputRange] (ParticleInstance& p) {
  3099. if (remap.output == ParticleRemapValue::Unknown) {
  3100. return;
  3101. }
  3102. glm::vec3 value = remapInitialInput (remap, p);
  3103. if (remapIsVector (remap.input)) {
  3104. value = remapSelectComponent (value, remap.inputComponent);
  3105. }
  3106. value = (value - remap.inputRangeMin) / inputRange;
  3107. if ((remap.flags & 1) != 0) {
  3108. value = glm::clamp (value, 0.0f, 1.0f);
  3109. }
  3110. value.x = remapTransformInitial (remap.transform, value.x, remap.transformInputScale, remap.transformOctaves);
  3111. if (remapIsVector (remap.output)) {
  3112. for (int i = 1; i < 3; i++) {
  3113. value[i] = remapTransformInitial (
  3114. remap.transform, value[i], remap.transformInputScale, remap.transformOctaves
  3115. );
  3116. }
  3117. }
  3118. value = value * outputRange + remap.outputRangeMin;
  3119. if ((remap.flags & 2) != 0) {
  3120. value = glm::clamp (value, 0.0f, 1.0f);
  3121. }
  3122. const auto apply
  3123. = [&remap] (float current, float target) { return remapApply (remap.operation, current, target); };
  3124. // all three components, or the one outputcomponent names
  3125. const auto applyVector = [&remap, &apply] (const glm::vec3& current, const glm::vec3& target) {
  3126. return remapComponents (remap.outputComponent, apply, current, target, false);
  3127. };
  3128. switch (remap.output) {
  3129. case ParticleRemapValue::MaxLifetime:
  3130. p.lifetime = apply (p.lifetime, value.x);
  3131. p.initial.lifetime = p.lifetime;
  3132. break;
  3133. case ParticleRemapValue::Size:
  3134. p.initial.size = apply (p.initial.size, value.x);
  3135. p.size = p.initial.size;
  3136. break;
  3137. case ParticleRemapValue::Opacity:
  3138. p.initial.alpha = apply (p.initial.alpha, value.x);
  3139. p.alpha = p.initial.alpha;
  3140. break;
  3141. case ParticleRemapValue::Speed:
  3142. {
  3143. const float speed = glm::length (p.velocity);
  3144. float scale = apply (speed, value.x);
  3145. if (speed != 0.0f) {
  3146. scale /= speed;
  3147. }
  3148. p.velocity *= scale;
  3149. break;
  3150. }
  3151. case ParticleRemapValue::Rotation:
  3152. p.rotation.z = apply (p.rotation.z, value.x);
  3153. break;
  3154. case ParticleRemapValue::AngularSpeed:
  3155. if (m_hasAngularVelocity) {
  3156. p.angularVelocity.z = apply (p.angularVelocity.z, value.x);
  3157. }
  3158. break;
  3159. case ParticleRemapValue::DistanceToControlPoint:
  3160. {
  3161. const glm::vec3 point = m_controlPoints[remap.outputControlPoint0].position;
  3162. glm::vec3 offset = p.position - point;
  3163. const float distance = glm::length (offset);
  3164. if (distance != 0.0f) {
  3165. offset /= distance;
  3166. }
  3167. p.position = point + offset * apply (distance, value.x);
  3168. break;
  3169. }
  3170. case ParticleRemapValue::PositionBetweenTwoControlPoints:
  3171. {
  3172. const glm::vec3 first = m_controlPoints[remap.outputControlPoint0].position;
  3173. glm::vec3 line = m_controlPoints[remap.outputControlPoint1].position - first;
  3174. const float length = glm::length (line);
  3175. if (length > 1.1920929e-7f) {
  3176. line /= length;
  3177. }
  3178. const glm::vec3 relative = p.position - first;
  3179. const float along = glm::dot (relative, line);
  3180. const glm::vec3 offset = relative - along * line;
  3181. const float fraction = apply (length > 1.1920929e-7f ? along / length : along, value.x);
  3182. p.position = (first + offset) + (line * fraction) * length;
  3183. break;
  3184. }
  3185. case ParticleRemapValue::Color:
  3186. p.initial.color = applyVector (p.initial.color, value);
  3187. p.color = p.initial.color;
  3188. break;
  3189. case ParticleRemapValue::Position:
  3190. p.position = applyVector (p.position, value);
  3191. break;
  3192. case ParticleRemapValue::Velocity:
  3193. p.velocity = applyVector (p.velocity, value);
  3194. break;
  3195. case ParticleRemapValue::ControlPoint:
  3196. {
  3197. auto& point = m_controlPoints[remap.outputControlPoint0];
  3198. point.position = applyVector (point.position, value);
  3199. break;
  3200. }
  3201. case ParticleRemapValue::DeltaToControlPoint:
  3202. {
  3203. const glm::vec3 point = m_controlPoints[remap.outputControlPoint0].position;
  3204. p.position = point - applyVector (point - p.position, value);
  3205. break;
  3206. }
  3207. case ParticleRemapValue::DirectionToControlPoint:
  3208. {
  3209. const glm::vec3 point = m_controlPoints[remap.outputControlPoint0].position;
  3210. glm::vec3 direction = point - p.position;
  3211. const float distance = glm::length (direction);
  3212. if (distance != 0.0f) {
  3213. direction /= distance;
  3214. }
  3215. direction = applyVector (direction, value);
  3216. const float length = glm::length (direction);
  3217. p.position = point - (length != 0.0f ? direction / length : glm::vec3 (0.0f)) * distance;
  3218. break;
  3219. }
  3220. default:
  3221. break;
  3222. }
  3223. };
  3224. }
  3225. glm::vec3 CParticle::remapOperatorInput (const ParticleRemap& remap, const ParticleInstance& p) const {
  3226. // sub_14023FBC0 case 19, scalars in x
  3227. switch (remap.input) {
  3228. case ParticleRemapValue::LifetimeFraction:
  3229. return { p.age / p.lifetime, 0.0f, 0.0f };
  3230. case ParticleRemapValue::MaxLifetime:
  3231. return { p.lifetime, 0.0f, 0.0f };
  3232. case ParticleRemapValue::Size:
  3233. return { p.size, 0.0f, 0.0f };
  3234. case ParticleRemapValue::Opacity:
  3235. return { p.alpha, 0.0f, 0.0f };
  3236. case ParticleRemapValue::Speed:
  3237. return { glm::length (p.velocity), 0.0f, 0.0f };
  3238. case ParticleRemapValue::Rotation:
  3239. return { p.rotation.z, 0.0f, 0.0f };
  3240. case ParticleRemapValue::AngularSpeed:
  3241. return { m_hasAngularVelocity ? p.angularVelocity.z : 0.0f, 0.0f, 0.0f };
  3242. case ParticleRemapValue::DistanceToControlPoint:
  3243. return { glm::length (p.position - m_controlPoints[remap.inputControlPoint0].position), 0.0f, 0.0f };
  3244. case ParticleRemapValue::PositionBetweenTwoControlPoints:
  3245. {
  3246. // the engine reads the output control points here, not the input ones
  3247. const glm::vec3 first = m_controlPoints[remap.outputControlPoint0].position;
  3248. const glm::vec3 line = m_controlPoints[remap.outputControlPoint1].position - first;
  3249. const float lengthSquared = glm::dot (line, line);
  3250. return { lengthSquared > 0.0f ? glm::dot (p.position - first, line) / lengthSquared : 0.0f, 0.0f,
  3251. 0.0f };
  3252. }
  3253. // runtime and particlesystemtime both read the renderer's scene clock here (+304)
  3254. case ParticleRemapValue::Runtime:
  3255. case ParticleRemapValue::ParticleSystemTime:
  3256. return { getScene ().getSceneClock (), 0.0f, 0.0f };
  3257. case ParticleRemapValue::TimeOfDay:
  3258. return { dayFraction (), 0.0f, 0.0f };
  3259. case ParticleRemapValue::LayerTime:
  3260. return { layerTime (), 0.0f, 0.0f };
  3261. case ParticleRemapValue::Color:
  3262. return p.color;
  3263. case ParticleRemapValue::Position:
  3264. return p.position;
  3265. case ParticleRemapValue::Velocity:
  3266. return p.velocity;
  3267. case ParticleRemapValue::ControlPoint:
  3268. return m_controlPoints[remap.inputControlPoint0].position;
  3269. case ParticleRemapValue::DeltaToControlPoint:
  3270. return m_controlPoints[remap.inputControlPoint0].position - p.position;
  3271. case ParticleRemapValue::DirectionToControlPoint:
  3272. {
  3273. const glm::vec3 delta = m_controlPoints[remap.inputControlPoint0].position - p.position;
  3274. const float length = glm::length (delta);
  3275. return length > 0.0f ? delta / length : glm::vec3 (0.0f);
  3276. }
  3277. case ParticleRemapValue::LayerOrigin:
  3278. return remapLayerOrigin ();
  3279. default:
  3280. return glm::vec3 (0.0f);
  3281. }
  3282. }
  3283. OperatorFunc CParticle::createRemapValueOperator (const RemapValueOperator& op) {
  3284. const ParticleRemap remap = op.remap;
  3285. const BlendWindow blend = makeBlendWindow (op.blend);
  3286. const glm::vec3 inputRange = remapRange (remap.inputRangeMin, remap.inputRangeMax);
  3287. const glm::vec3 outputRange = remap.outputRangeMax - remap.outputRangeMin;
  3288. const float fbmAmplitude = hashedNoiseFbmNormalizer (remap.transformOctaves);
  3289. // sub_14023FBC0 restores alpha or color when a remap writes them (system flags 0x10/8)
  3290. if (remap.output == ParticleRemapValue::Opacity) {
  3291. m_resetAlphaFromBase = true;
  3292. } else if (remap.output == ParticleRemapValue::Color) {
  3293. m_resetColorFromBase = true;
  3294. }
  3295. if (remap.transform == ParticleRemapTransform::SimplexNoise
  3296. || remap.transform == ParticleRemapTransform::FbmNoise) {
  3297. m_usesParticleSeed = true;
  3298. }
  3299. // sub_14023FBC0 case 19 and its blended variant 39, which moves every value only part of the way
  3300. return [this, remap, blend, inputRange, outputRange, fbmAmplitude] (
  3301. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
  3302. float
  3303. ) {
  3304. if (remap.input == ParticleRemapValue::Unknown || remap.output == ParticleRemapValue::Unknown) {
  3305. return;
  3306. }
  3307. const bool vectorInput = remapIsVector (remap.input);
  3308. const bool vectorOutput = remapIsVector (remap.output);
  3309. for (uint32_t i = 0; i < count; i++) {
  3310. auto& p = particles[i];
  3311. const glm::vec3 raw = remapOperatorInput (remap, p);
  3312. glm::vec3 value;
  3313. if (vectorInput) {
  3314. value = (remapSelectComponent (raw, remap.inputComponent) - remap.inputRangeMin) / inputRange;
  3315. } else {
  3316. value = glm::vec3 ((raw.x - remap.inputRangeMin.x) / inputRange.x);
  3317. }
  3318. if ((remap.flags & 1) != 0) {
  3319. value = glm::clamp (value, 0.0f, 1.0f);
  3320. }
  3321. // the y and z noise use the particle's random with a few bits flipped
  3322. const int32_t seed = particleSeedBits (p);
  3323. const int32_t seeds[3] = { seed, seed ^ 0x0B3924AD, seed ^ 0x493A8E83 };
  3324. const int transformed = vectorOutput ? 3 : 1;
  3325. for (int c = 0; c < transformed; c++) {
  3326. value[c] = remapTransformOperator (
  3327. remap.transform, value[c], remap.transformInputScale, remap.transformOctaves, fbmAmplitude, seeds[c]
  3328. );
  3329. value[c] = outputRange[c] * value[c] + remap.outputRangeMin[c];
  3330. if ((remap.flags & 2) != 0) {
  3331. value[c] = std::clamp (value[c], 0.0f, 1.0f);
  3332. }
  3333. }
  3334. const float weight = blend.active ? blendWeight (blend, p) : 1.0f;
  3335. const auto apply = [&remap, &blend, weight] (float current, float target) {
  3336. const float result = remapApply (remap.operation, current, target);
  3337. return blend.active ? (result - current) * weight + current : result;
  3338. };
  3339. // blended "remap" on all components gives every component the x value, like wallpaper64.exe's variant 39
  3340. const auto applyVector
  3341. = [&remap, &blend, &apply] (const glm::vec3& current, const glm::vec3& target, bool setQuirk) {
  3342. const bool useX = setQuirk && blend.active && remap.operation == ParticleRemapOperation::Remap;
  3343. return remapComponents (remap.outputComponent, apply, current, target, useX);
  3344. };
  3345. switch (remap.output) {
  3346. case ParticleRemapValue::MaxLifetime:
  3347. p.lifetime = apply (p.lifetime, value.x);
  3348. break;
  3349. case ParticleRemapValue::Size:
  3350. p.size = apply (p.size, value.x);
  3351. break;
  3352. case ParticleRemapValue::Opacity:
  3353. p.alpha = apply (p.alpha, value.x);
  3354. break;
  3355. case ParticleRemapValue::Speed:
  3356. {
  3357. const float speed = glm::length (p.velocity);
  3358. const float target = apply (speed, value.x);
  3359. p.velocity *= speed > 0.0f ? target / speed : target;
  3360. break;
  3361. }
  3362. case ParticleRemapValue::Rotation:
  3363. p.rotation.z = apply (p.rotation.z, value.x);
  3364. break;
  3365. case ParticleRemapValue::AngularSpeed:
  3366. if (m_hasAngularVelocity) {
  3367. p.angularVelocity.z = apply (p.angularVelocity.z, value.x);
  3368. }
  3369. break;
  3370. case ParticleRemapValue::DistanceToControlPoint:
  3371. {
  3372. const glm::vec3 point = m_controlPoints[remap.outputControlPoint0].position;
  3373. const glm::vec3 offset = p.position - point;
  3374. const float distance = glm::length (offset);
  3375. const glm::vec3 direction = distance != 0.0f ? offset / distance : glm::vec3 (0.0f);
  3376. p.position = point + direction * apply (distance, value.x);
  3377. break;
  3378. }
  3379. case ParticleRemapValue::PositionBetweenTwoControlPoints:
  3380. {
  3381. const glm::vec3 first = m_controlPoints[remap.outputControlPoint0].position;
  3382. const glm::vec3 line = m_controlPoints[remap.outputControlPoint1].position - first;
  3383. const float length = glm::length (line);
  3384. const glm::vec3 direction = length != 0.0f ? line / length : glm::vec3 (0.0f);
  3385. const glm::vec3 relative = p.position - first;
  3386. const float along = glm::dot (relative, direction);
  3387. const glm::vec3 offset = relative - along * direction;
  3388. const float fraction = apply (length != 0.0f ? along / length : 0.0f, value.x);
  3389. p.position = (fraction * length) * direction + offset + first;
  3390. break;
  3391. }
  3392. case ParticleRemapValue::Color:
  3393. p.color = applyVector (p.color, value, true);
  3394. break;
  3395. case ParticleRemapValue::Position:
  3396. p.position = applyVector (p.position, value, true);
  3397. break;
  3398. case ParticleRemapValue::Velocity:
  3399. p.velocity = applyVector (p.velocity, value, true);
  3400. break;
  3401. case ParticleRemapValue::ControlPoint:
  3402. {
  3403. // written per particle, the last one wins
  3404. auto& point = m_controlPoints[remap.outputControlPoint0];
  3405. point.position = applyVector (point.position, value, false);
  3406. break;
  3407. }
  3408. case ParticleRemapValue::DeltaToControlPoint:
  3409. {
  3410. const glm::vec3 point = m_controlPoints[remap.outputControlPoint0].position;
  3411. p.position = point - applyVector (point - p.position, value, false);
  3412. break;
  3413. }
  3414. case ParticleRemapValue::DirectionToControlPoint:
  3415. {
  3416. const glm::vec3 point = m_controlPoints[remap.outputControlPoint0].position;
  3417. const glm::vec3 delta = point - p.position;
  3418. const float distance = glm::length (delta);
  3419. const glm::vec3 direction
  3420. = applyVector (distance > 0.0f ? delta / distance : glm::vec3 (0.0f), value, false);
  3421. const float length = glm::length (direction);
  3422. p.position = point - (length > 0.0f ? direction / length : glm::vec3 (0.0f)) * distance;
  3423. break;
  3424. }
  3425. default:
  3426. break;
  3427. }
  3428. }
  3429. };
  3430. }
  3431. OperatorFunc CParticle::createCapVelocityOperator (const CapVelocityOperator& op) {
  3432. DynamicValue* maxSpeedValue = op.maxSpeed ? op.maxSpeed->value.get () : nullptr;
  3433. const BlendWindow blend = makeBlendWindow (op.blend);
  3434. // sub_14023FBC0 case 18 and its blended variant 38, maxspeed defaults from sub_1401BFAB0
  3435. return [this, maxSpeedValue, blend] (
  3436. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
  3437. float
  3438. ) {
  3439. const float maxSpeed = maxSpeedValue != nullptr ? maxSpeedValue->getFloat ()
  3440. : (getScene ().getCamera ().isPerspective () ? 1.0f : 100.0f);
  3441. for (uint32_t i = 0; i < count; i++) {
  3442. auto& p = particles[i];
  3443. const float speed = glm::length (p.velocity);
  3444. if (speed == 0.0f) {
  3445. continue;
  3446. }
  3447. const float ratio = maxSpeed / speed;
  3448. p.velocity *= blend.active ? std::min (0.0f, ratio - 1.0f) * blendWeight (blend, p) + 1.0f
  3449. : std::min (1.0f, ratio);
  3450. }
  3451. };
  3452. }
  3453. OperatorFunc CParticle::createBoidsOperator (const BoidsOperator& op) {
  3454. DynamicValue* separationThresholdValue = op.separationThreshold ? op.separationThreshold->value.get () : nullptr;
  3455. DynamicValue* neighborThresholdValue = op.neighborThreshold ? op.neighborThreshold->value.get () : nullptr;
  3456. DynamicValue* maxSpeedValue = op.maxSpeed ? op.maxSpeed->value.get () : nullptr;
  3457. DynamicValue* separationFactorValue = op.separationFactor->value.get ();
  3458. DynamicValue* alignmentFactorValue = op.alignmentFactor->value.get ();
  3459. DynamicValue* cohesionFactorValue = op.cohesionFactor->value.get ();
  3460. const uint32_t flags = op.flags;
  3461. // sub_14023FBC0 case 17, defaults from sub_1401BF700. The engine walks its pool four slots at a time and only
  3462. // every stride-th block of them (and of their neighbors) per frame, rotating with the frame count, the forces
  3463. // grow by the stride to make up for it
  3464. return [this, separationThresholdValue, neighborThresholdValue, maxSpeedValue, separationFactorValue,
  3465. alignmentFactorValue, cohesionFactorValue, flags] (
  3466. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
  3467. float dt
  3468. ) {
  3469. const bool flat = !getScene ().getCamera ().isPerspective ();
  3470. const float separationThreshold
  3471. = separationThresholdValue != nullptr ? separationThresholdValue->getFloat () : (flat ? 20.0f : 0.02f);
  3472. const float neighborThreshold
  3473. = neighborThresholdValue != nullptr ? neighborThresholdValue->getFloat () : (flat ? 50.0f : 0.2f);
  3474. const float maxSpeed = maxSpeedValue != nullptr ? maxSpeedValue->getFloat () : (flat ? 500.0f : 1.0f);
  3475. // every pool slot below the high water mark takes part, a dead one with its last state (m_ghosts)
  3476. const uint32_t blocks = (m_slotExtent + 3) / 4;
  3477. std::vector<ParticleInstance*> slots (static_cast<size_t> (blocks) * 4, nullptr);
  3478. std::vector<uint8_t> alive (slots.size (), 0);
  3479. for (uint32_t i = 0; i < count; i++) {
  3480. if (particles[i].slot < slots.size ()) {
  3481. slots[particles[i].slot] = &particles[i];
  3482. alive[particles[i].slot] = 1;
  3483. }
  3484. }
  3485. for (uint32_t slot = 0; slot < slots.size () && slot < m_ghostUsed.size (); slot++) {
  3486. if (slots[slot] == nullptr && m_ghostUsed[slot]) {
  3487. slots[slot] = &m_ghosts[slot];
  3488. }
  3489. }
  3490. const uint32_t stride = m_slotExtent / 200 + 1;
  3491. const float scaledDt = frameScaledDelta (dt);
  3492. const float separationFactor = static_cast<float> (stride) * separationFactorValue->getFloat () * scaledDt;
  3493. const float alignmentFactor = static_cast<float> (stride) * alignmentFactorValue->getFloat () * scaledDt;
  3494. const float cohesionFactor = static_cast<float> (stride) * cohesionFactorValue->getFloat () * scaledDt;
  3495. // the lane a neighbor block is compared on in each of the four passes (_mm_shuffle_ps 0, 147, 78, 57)
  3496. static constexpr int lanes[4][4] = { { 0, 1, 2, 3 }, { 3, 0, 1, 2 }, { 2, 3, 0, 1 }, { 1, 2, 3, 0 } };
  3497. for (uint32_t block = getScene ().getFrameCounter () % stride; block < blocks; block += stride) {
  3498. glm::vec3 results[4];
  3499. for (int lane = 0; lane < 4; lane++) {
  3500. const ParticleInstance* self = slots[block * 4 + lane];
  3501. if (self == nullptr) {
  3502. continue;
  3503. }
  3504. float separationCount = 0.0f;
  3505. float neighborCount = 0.0f;
  3506. glm::vec3 separation (0.0f);
  3507. glm::vec3 velocitySum (0.0f);
  3508. glm::vec3 positionSum (0.0f);
  3509. for (uint32_t other = (block * 4 + getScene ().getFrameCounter ()) % stride; other < blocks;
  3510. other += stride) {
  3511. // WE's alive mask (lifetime != 0) is taken from the neighbor block unshuffled, so it belongs to
  3512. // this lane's slot there, not to the shuffled neighbor it gets applied to
  3513. if (!alive[other * 4 + lane]) {
  3514. continue;
  3515. }
  3516. for (const auto& pass : lanes) {
  3517. const ParticleInstance* neighbor = slots[other * 4 + pass[lane]];
  3518. if (neighbor == nullptr) {
  3519. continue;
  3520. }
  3521. const glm::vec3 delta = self->position - neighbor->position;
  3522. const float distanceSquared = glm::dot (delta, delta);
  3523. const float distance = std::sqrt (distanceSquared);
  3524. if (distanceSquared != 0.0f && distance < separationThreshold) {
  3525. separationCount += 1.0f;
  3526. separation += (separationThreshold / distance - 1.0f) * delta;
  3527. }
  3528. if (distance < neighborThreshold) {
  3529. neighborCount += 1.0f;
  3530. velocitySum += neighbor->velocity;
  3531. positionSum += neighbor->position;
  3532. }
  3533. }
  3534. }
  3535. const float separationWeight = separationCount != 0.0f ? separationFactor / separationCount : 0.0f;
  3536. const float average = neighborCount != 0.0f ? 1.0f / neighborCount : 0.0f;
  3537. const float alignment = neighborCount != 0.0f ? alignmentFactor : 0.0f;
  3538. const float cohesion = neighborCount != 0.0f ? cohesionFactor : 0.0f;
  3539. const glm::vec3 change
  3540. = ((average * velocitySum - self->velocity) * alignment + separationWeight * separation)
  3541. + (average * positionSum - self->position) * cohesion;
  3542. glm::vec3 velocity = self->velocity + change;
  3543. if ((flags & 1) != 0) {
  3544. const float speedSquared = glm::dot (velocity, velocity);
  3545. if (std::max (glm::dot (self->velocity, self->velocity), maxSpeed * maxSpeed) < speedSquared) {
  3546. velocity *= maxSpeed / std::sqrt (speedSquared);
  3547. }
  3548. }
  3549. results[lane] = velocity;
  3550. }
  3551. // the four lanes are written together, after all of them were computed
  3552. for (int lane = 0; lane < 4; lane++) {
  3553. if (ParticleInstance* target = slots[block * 4 + lane]) {
  3554. target->velocity = results[lane];
  3555. }
  3556. }
  3557. }
  3558. };
  3559. }
  3560. OperatorFunc
  3561. CParticle::createMaintainDistanceToControlPointOperator (const MaintainDistanceToControlPointOperator& op) {
  3562. const int controlPoint = op.controlPoint;
  3563. DynamicValue* distanceValue = op.distance ? op.distance->value.get () : nullptr;
  3564. DynamicValue* strengthValue = op.variableStrength->value.get ();
  3565. const BlendWindow blend = makeBlendWindow (op.blend);
  3566. // sub_14023FBC0 case 11 and its blended variant 33, distance defaults from sub_1401BE2A0
  3567. return [this, controlPoint, distanceValue, strengthValue, blend] (
  3568. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>& points,
  3569. float, float dt
  3570. ) {
  3571. const auto& point = points[controlPoint];
  3572. const float distance = distanceValue != nullptr ? distanceValue->getFloat ()
  3573. : (getScene ().getCamera ().isPerspective () ? 1.0f : 200.0f);
  3574. const float variableStrength = strengthValue->getFloat ();
  3575. const float strength = variableStrength == 0.0f ? 1.0f : std::clamp (variableStrength * dt, 0.0f, 1.0f);
  3576. // the distance is measured in the control point's own frame
  3577. const glm::mat3 toPoint = glm::inverse (point.orientation);
  3578. for (uint32_t i = 0; i < count; i++) {
  3579. auto& p = particles[i];
  3580. // particles move along with the control point, then get pulled onto the sphere around it
  3581. const glm::vec3 moved = p.position + point.movement;
  3582. const glm::vec3 offset = moved - point.position;
  3583. const float length = glm::length (toPoint * offset);
  3584. if (length == 0.0f) {
  3585. p.position = moved;
  3586. continue;
  3587. }
  3588. float pull = (distance / length - 1.0f) * strength;
  3589. if (blend.active) {
  3590. pull *= blendWeight (blend, p);
  3591. }
  3592. p.position = pull * offset + moved;
  3593. }
  3594. };
  3595. }
  3596. OperatorFunc
  3597. CParticle::createMaintainDistanceBetweenControlPointsOperator (const MaintainDistanceBetweenControlPointsOperator& op) {
  3598. const int start = op.controlPointStart;
  3599. const int end = op.controlPointEnd;
  3600. const BlendWindow blend = makeBlendWindow (op.blend);
  3601. // sub_14023FBC0 case 12 and its blended variant 34: whatever lay along the line between the two control points
  3602. // last frame is moved to the same share of the line now
  3603. return [start, end, blend] (
  3604. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>& points,
  3605. float, float
  3606. ) {
  3607. const glm::vec3 first = points[start].position;
  3608. const glm::vec3 previousFirst = first - points[start].movement;
  3609. const glm::vec3 previousLast = points[end].position - points[end].movement;
  3610. const glm::vec3 line = points[end].position - first;
  3611. const glm::vec3 previousLine = previousLast - previousFirst;
  3612. const float lengthSquared = glm::dot (line, line);
  3613. const float previousLengthSquared = glm::dot (previousLine, previousLine);
  3614. if (lengthSquared <= 1.4210855e-14f || previousLengthSquared <= 1.4210855e-14f) {
  3615. return;
  3616. }
  3617. const float length = std::sqrt (lengthSquared);
  3618. const float previousLength = std::sqrt (previousLengthSquared);
  3619. const glm::vec3 direction = line / length;
  3620. const glm::vec3 previousDirection = previousLine / previousLength;
  3621. const glm::vec3 shift = first - previousFirst;
  3622. for (uint32_t i = 0; i < count; i++) {
  3623. auto& p = particles[i];
  3624. const float along = glm::dot (p.position - previousFirst, previousDirection);
  3625. const float scaled = std::clamp (along / previousLength, 0.0f, 1.0f) * length;
  3626. glm::vec3 change = (scaled * direction - along * previousDirection) + shift;
  3627. if (blend.active) {
  3628. change *= blendWeight (blend, p);
  3629. }
  3630. p.position += change;
  3631. }
  3632. };
  3633. }
  3634. OperatorFunc
  3635. CParticle::createReduceMovementNearControlPointOperator (const ReduceMovementNearControlPointOperator& op) {
  3636. const int controlPoint = op.controlPoint;
  3637. DynamicValue* innerValue = op.distanceInner ? op.distanceInner->value.get () : nullptr;
  3638. DynamicValue* outerValue = op.distanceOuter ? op.distanceOuter->value.get () : nullptr;
  3639. DynamicValue* reductionInnerValue = op.reductionInner->value.get ();
  3640. DynamicValue* reductionOuterValue = op.reductionOuter->value.get ();
  3641. const BlendWindow blend = makeBlendWindow (op.blend);
  3642. // sub_14023FBC0 case 13 and its blended variant 35, distance defaults from sub_1401BE810
  3643. return [this, controlPoint, innerValue, outerValue, reductionInnerValue, reductionOuterValue, blend] (
  3644. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>& points,
  3645. float, float dt
  3646. ) {
  3647. const bool flat = !getScene ().getCamera ().isPerspective ();
  3648. const float inner = innerValue != nullptr ? innerValue->getFloat () : (flat ? 100.0f : 0.5f);
  3649. const float outer = outerValue != nullptr ? outerValue->getFloat () : (flat ? 350.0f : 1.0f);
  3650. const float reductionInner = reductionInnerValue->getFloat ();
  3651. const float reductionOuter = reductionOuterValue->getFloat ();
  3652. const float distanceScale = inner == outer ? 1.0f : 1.0f / (outer - inner);
  3653. const float reductionRange = reductionInner == reductionOuter ? 1.0f : reductionOuter - reductionInner;
  3654. const glm::vec3 center = points[controlPoint].position;
  3655. for (uint32_t i = 0; i < count; i++) {
  3656. auto& p = particles[i];
  3657. const float distance = glm::length (p.position - center);
  3658. const float share = std::clamp ((distance - inner) * distanceScale, 0.0f, 1.0f);
  3659. float reduction = std::clamp ((share * reductionRange + reductionInner) * dt, 0.0f, 1.0f);
  3660. if (blend.active) {
  3661. reduction *= blendWeight (blend, p);
  3662. }
  3663. p.velocity *= 1.0f - reduction;
  3664. }
  3665. };
  3666. }
  3667. namespace {
  3668. /** sub_1401D5880: a capsule along the largest extent, as thick as the second largest */
  3669. void capsuleShape (const glm::vec3& extents, glm::vec3& axis, float& halfLength, glm::vec3& radius) {
  3670. if (glm::dot (extents, extents) < 0.0099999998f) {
  3671. axis = glm::vec3 (0.0f, 1.0f, 0.0f);
  3672. halfLength = 0.0f;
  3673. radius = glm::vec3 (0.0f);
  3674. return;
  3675. }
  3676. float smallX = extents.x;
  3677. float smallY = extents.y;
  3678. float z = extents.z;
  3679. float largeX, largeY;
  3680. if (smallY * smallY <= smallX * smallX) {
  3681. largeX = extents.x;
  3682. largeY = 0.0f;
  3683. smallX = 0.0f;
  3684. } else {
  3685. largeY = extents.y;
  3686. largeX = 0.0f;
  3687. smallY = 0.0f;
  3688. }
  3689. float secondX, secondZ, axisY;
  3690. if (z * z <= largeX * largeX + largeY * largeY) {
  3691. secondZ = extents.z;
  3692. axisY = largeY;
  3693. z = 0.0f;
  3694. largeY = 0.0f;
  3695. secondX = 0.0f;
  3696. } else {
  3697. secondX = largeX;
  3698. secondZ = 0.0f;
  3699. largeX = 0.0f;
  3700. axisY = 0.0f;
  3701. }
  3702. if (secondX * secondX + largeY * largeY + secondZ * secondZ <= smallX * smallX + smallY * smallY) {
  3703. secondZ = 0.0f;
  3704. largeY = smallY;
  3705. secondX = smallX;
  3706. }
  3707. const float length = largeX + axisY + z;
  3708. axis = glm::vec3 (largeX, axisY, z) / length;
  3709. halfLength = length - (largeY + secondX + secondZ);
  3710. radius = glm::vec3 (secondX, largeY, secondZ);
  3711. }
  3712. }
  3713. glm::mat4 CParticle::worldToParticles () const { return m_worldSpace ? glm::mat4 (1.0f) : glm::inverse (m_frame); }
  3714. const CObject* CParticle::componentDependency (const char* type, int index) const {
  3715. // sub_14022AF30: the record naming the index-th component of that type
  3716. for (const auto& cur : m_particle.componentDependencies) {
  3717. if (cur.type == type && cur.index == index) {
  3718. return getScene ().getObject (cur.id);
  3719. }
  3720. }
  3721. return nullptr;
  3722. }
  3723. std::vector<CParticle::CollisionCapsule> CParticle::collisionCapsules (int index) const {
  3724. // sub_1401D4580
  3725. const CObject* target = this->componentDependency ("collisionmodel", index);
  3726. if (target == nullptr) {
  3727. return {};
  3728. }
  3729. // capsule frames are in WE's world
  3730. const glm::mat4 toParticles = this->worldToParticles ();
  3731. std::vector<CollisionCapsule> capsules;
  3732. const auto add = [&capsules, &toParticles] (const glm::mat4& frame, const glm::vec3& extents) {
  3733. glm::vec3 axis, radius;
  3734. float halfLength;
  3735. capsuleShape (extents, axis, halfLength, radius);
  3736. const glm::mat4 matrix = toParticles * frame;
  3737. const glm::vec3 start = glm::vec3 (matrix * glm::vec4 (-halfLength * axis, 1.0f));
  3738. const glm::vec3 end = glm::vec3 (matrix * glm::vec4 (halfLength * axis, 1.0f));
  3739. const glm::vec3 direction = glm::mat3 (matrix) * axis;
  3740. if (glm::dot (direction, direction) <= 0.0f) {
  3741. return;
  3742. }
  3743. capsules.push_back (
  3744. { .start = start,
  3745. .direction = glm::normalize (direction),
  3746. .length = glm::distance (start, end),
  3747. .radius = glm::length (glm::mat3 (matrix) * radius) }
  3748. );
  3749. };
  3750. // puppets: a capsule per bone in bone space, following the pose
  3751. if (target->is<CImage> ()) {
  3752. const auto* image = target->as<CImage> ();
  3753. if (!image->hasPuppetPose ()) {
  3754. return {};
  3755. }
  3756. const auto& bones = image->getPuppetBones ();
  3757. for (int bone = 0; bone < static_cast<int> (bones.size ()); bone++) {
  3758. if (bones[bone].hasCapsule) {
  3759. add (image->getPuppetBoneTransform (bone) * bones[bone].capsule, bones[bone].capsuleExtents);
  3760. }
  3761. }
  3762. return capsules;
  3763. }
  3764. // models without capsules: one around the bounds, half their size on each axis
  3765. if (target->is<CMesh> ()) {
  3766. const auto* mesh = target->as<CMesh> ();
  3767. const glm::vec3& low = mesh->getBoundsMin ();
  3768. const glm::vec3& high = mesh->getBoundsMax ();
  3769. if (!(high.x > low.x)) {
  3770. return {};
  3771. }
  3772. const glm::vec3 extents = (high - low) * 0.5f;
  3773. add (
  3774. getScene ().objectWorldMatrix (mesh->getMesh ()) * glm::translate (glm::mat4 (1.0f), low + extents), extents
  3775. );
  3776. }
  3777. return capsules;
  3778. }
  3779. OperatorFunc CParticle::createCollisionModelOperator (const CollisionOperator& op) {
  3780. const int index = m_collisionModels++;
  3781. const ParticleCollisionBehavior behavior = op.behavior;
  3782. DynamicValue* bounceValue = op.bounceFactor->value.get ();
  3783. // sub_14023FBC0 case 26 with sub_1402508C0 (bounce), sub_140250E00 (slide), sub_140251320 (stop) and
  3784. // sub_1402517D0 (delete): of the capsules a particle is inside the last one counts, it is pushed out along the
  3785. // line from the capsule's segment. Unlike the other shapes flag 2 doesn't stop the spin
  3786. return
  3787. [this, index, behavior, bounceValue] (
  3788. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
  3789. ) {
  3790. const std::vector<CollisionCapsule> capsules = this->collisionCapsules (index);
  3791. if (capsules.empty ()) {
  3792. return;
  3793. }
  3794. const float bounce = -1.0f - bounceValue->getFloat ();
  3795. for (uint32_t i = 0; i < count; i++) {
  3796. auto& p = particles[i];
  3797. bool hit = false;
  3798. glm::vec3 normal (0.0f);
  3799. float depth = 0.0f;
  3800. for (const auto& capsule : capsules) {
  3801. const float along
  3802. = std::clamp (glm::dot (p.position - capsule.start, capsule.direction), 0.0f, capsule.length);
  3803. const glm::vec3 offset = p.position - (capsule.start + along * capsule.direction);
  3804. const float distanceSquared = glm::dot (offset, offset);
  3805. // on the segment itself the engine's normal would be NaN
  3806. if (distanceSquared < capsule.radius * capsule.radius && distanceSquared > 0.0f) {
  3807. const float distance = std::sqrt (distanceSquared);
  3808. hit = true;
  3809. normal = offset / distance;
  3810. depth = distance - capsule.radius;
  3811. }
  3812. }
  3813. if (!hit) {
  3814. continue;
  3815. }
  3816. if (behavior == ParticleCollisionBehavior::Delete) {
  3817. p.age = p.lifetime;
  3818. continue;
  3819. }
  3820. p.position -= depth * normal;
  3821. const float velocity = glm::dot (p.velocity, normal);
  3822. switch (behavior) {
  3823. case ParticleCollisionBehavior::Bounce:
  3824. p.velocity += (velocity * bounce) * normal;
  3825. break;
  3826. case ParticleCollisionBehavior::Slide:
  3827. p.velocity -= velocity * normal;
  3828. break;
  3829. default:
  3830. p.velocity = glm::vec3 (0.0f);
  3831. break;
  3832. }
  3833. }
  3834. };
  3835. }
  3836. OperatorFunc CParticle::createCollisionOperator (const CollisionOperator& op) {
  3837. if (op.shape == ParticleCollisionShape::Model) {
  3838. return this->createCollisionModelOperator (op);
  3839. }
  3840. // sub_14023FBC0 case 23 does nothing, collisionbox only exists in the file format
  3841. if (op.shape == ParticleCollisionShape::Box) {
  3842. return nullptr;
  3843. }
  3844. if (op.shape == ParticleCollisionShape::Quad) {
  3845. m_tracksPreviousPosition = true;
  3846. }
  3847. const ParticleCollisionShape shape = op.shape;
  3848. const ParticleCollisionBehavior behavior = op.behavior;
  3849. const uint32_t flags = op.flags;
  3850. const int controlPoint = op.controlPoint;
  3851. DynamicValue* bounceValue = op.bounceFactor->value.get ();
  3852. DynamicValue* planeValue = op.plane->value.get ();
  3853. DynamicValue* distanceValue = op.distance ? op.distance->value.get () : nullptr;
  3854. DynamicValue* originValue = op.origin ? op.origin->value.get () : nullptr;
  3855. DynamicValue* radiusValue = op.radius ? op.radius->value.get () : nullptr;
  3856. DynamicValue* forwardValue = op.forward->value.get ();
  3857. DynamicValue* sizeValue = op.size ? op.size->value.get () : nullptr;
  3858. // sub_14023FBC0 cases 21, 22, 24 and 25 with the per behavior workers (sub_14024F5E0 and siblings), defaults
  3859. // from sub_1401C00A0, sub_1401C0540, sub_1401C0740 and sub_1401C0870
  3860. return [this, shape, behavior, flags, controlPoint, bounceValue, planeValue, distanceValue, originValue,
  3861. radiusValue, forwardValue, sizeValue] (
  3862. std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>& points,
  3863. float, float
  3864. ) {
  3865. const bool flat = !getScene ().getCamera ().isPerspective ();
  3866. const float bounce = -1.0f - bounceValue->getFloat ();
  3867. const bool followPoint = (flags & 1) != 0;
  3868. const auto& point = points[controlPoint];
  3869. // pushes the particle back by depth along the normal, then the velocity rule, flag 2 also stops the spin
  3870. const auto collide = [behavior, bounce, flags] (ParticleInstance& p, const glm::vec3& normal, float depth) {
  3871. if (behavior == ParticleCollisionBehavior::Delete) {
  3872. p.age = p.lifetime;
  3873. } else {
  3874. p.position -= depth * normal;
  3875. const float along = glm::dot (p.velocity, normal);
  3876. switch (behavior) {
  3877. case ParticleCollisionBehavior::Bounce:
  3878. p.velocity += (along * bounce) * normal;
  3879. break;
  3880. case ParticleCollisionBehavior::Slide:
  3881. p.velocity -= along * normal;
  3882. break;
  3883. default:
  3884. p.velocity = glm::vec3 (0.0f);
  3885. break;
  3886. }
  3887. }
  3888. if ((flags & 2) != 0) {
  3889. p.angularVelocity = glm::vec3 (0.0f);
  3890. }
  3891. };
  3892. switch (shape) {
  3893. case ParticleCollisionShape::Plane:
  3894. {
  3895. glm::vec3 normal = glm::normalize (planeValue->getVec3 ());
  3896. float distance = distanceValue != nullptr ? distanceValue->getFloat () : (flat ? -150.0f : 0.0f);
  3897. if (followPoint) {
  3898. normal = point.orientation * normal;
  3899. distance = glm::dot (normal, point.position);
  3900. }
  3901. for (uint32_t i = 0; i < count; i++) {
  3902. const float along = glm::dot (particles[i].position, normal);
  3903. if (along < distance) {
  3904. collide (particles[i], normal, along - distance);
  3905. }
  3906. }
  3907. break;
  3908. }
  3909. case ParticleCollisionShape::Sphere:
  3910. {
  3911. glm::vec3 center = originValue != nullptr
  3912. ? originValue->getVec3 ()
  3913. : (flat ? glm::vec3 (0.0f, -200.0f, 0.0f) : glm::vec3 (0.0f));
  3914. const float radius = radiusValue != nullptr ? radiusValue->getFloat () : (flat ? 50.0f : 1.0f);
  3915. if (followPoint) {
  3916. center = point.position;
  3917. }
  3918. for (uint32_t i = 0; i < count; i++) {
  3919. const glm::vec3 offset = particles[i].position - center;
  3920. const float distanceSquared = glm::dot (offset, offset);
  3921. // at the very center the engine's normal would be NaN
  3922. if (distanceSquared < radius * radius && distanceSquared > 0.0f) {
  3923. const float distance = std::sqrt (distanceSquared);
  3924. collide (particles[i], offset / distance, distance - radius);
  3925. }
  3926. }
  3927. break;
  3928. }
  3929. case ParticleCollisionShape::Quad:
  3930. {
  3931. glm::vec3 origin = originValue != nullptr
  3932. ? originValue->getVec3 ()
  3933. : (flat ? glm::vec3 (0.0f, -150.0f, 0.0f) : glm::vec3 (0.0f));
  3934. const glm::vec2 halfSize = (sizeValue != nullptr ? sizeValue->getVec2 ()
  3935. : (flat ? glm::vec2 (200.0f) : glm::vec2 (1.0f)))
  3936. * 0.5f;
  3937. glm::vec3 normal = glm::normalize (planeValue->getVec3 ());
  3938. const glm::vec3 forward = glm::normalize (forwardValue->getVec3 ());
  3939. glm::vec3 right = glm::normalize (glm::cross (normal, forward));
  3940. glm::vec3 up = glm::normalize (glm::cross (right, normal));
  3941. if (followPoint) {
  3942. origin = point.position;
  3943. normal = point.orientation * normal;
  3944. up = point.orientation * up;
  3945. right = point.orientation * right;
  3946. }
  3947. // only particles crossing it from the front during this frame hit it
  3948. for (uint32_t i = 0; i < count; i++) {
  3949. auto& p = particles[i];
  3950. const glm::vec3 offset = p.position - origin;
  3951. const float along = glm::dot (offset, normal);
  3952. if (glm::dot (p.previousPosition - origin, normal) > 0.0f && along <= 0.0f
  3953. && std::fabs (glm::dot (offset, up)) < halfSize.y
  3954. && std::fabs (glm::dot (offset, right)) < halfSize.x) {
  3955. collide (p, normal, along * 1.05f);
  3956. }
  3957. }
  3958. break;
  3959. }
  3960. case ParticleCollisionShape::Bounds:
  3961. {
  3962. // the scene's ortho size (0 for automatic/perspective) as a box from (0, 0), in the system's space
  3963. const auto& projection = getScene ().getScene ().camera.projection;
  3964. glm::vec3 low (0.0f);
  3965. glm::vec3 high (
  3966. static_cast<float> (projection.width), static_cast<float> (projection.height), 0.0f
  3967. );
  3968. glm::vec3 normals[4] = { { 1, 0, 0 }, { 0, 1, 0 }, { -1, 0, 0 }, { 0, -1, 0 } };
  3969. if (!m_worldSpace) {
  3970. const glm::mat4 toLocal = glm::inverse (m_frame);
  3971. for (auto& normal : normals) {
  3972. normal = glm::mat3 (toLocal) * normal;
  3973. }
  3974. low = glm::vec3 (toLocal * glm::vec4 (low, 1.0f));
  3975. high = glm::vec3 (toLocal * glm::vec4 (high, 1.0f));
  3976. }
  3977. const float distances[4] = { glm::dot (low, normals[0]), glm::dot (low, normals[1]),
  3978. glm::dot (high, normals[2]), glm::dot (high, normals[3]) };
  3979. // the last side the particle is outside of is the one it hits
  3980. for (uint32_t i = 0; i < count; i++) {
  3981. auto& p = particles[i];
  3982. int side = -1;
  3983. for (int s = 0; s < 4; s++) {
  3984. if (glm::dot (p.position, normals[s]) < distances[s]) {
  3985. side = s;
  3986. }
  3987. }
  3988. if (side >= 0) {
  3989. collide (p, normals[side], glm::dot (p.position, normals[side]) - distances[side]);
  3990. }
  3991. }
  3992. break;
  3993. }
  3994. default:
  3995. break;
  3996. }
  3997. };
  3998. }
  3999. void CParticle::setupPass () {
  4000. if (!m_particle.material || !m_particle.material->material || m_particle.material->material->passes.empty ()) {
  4001. sLog.error ("No valid material for particle ", m_particle.name);
  4002. return;
  4003. }
  4004. const auto& firstPass = **m_particle.material->material->passes.begin ();
  4005. m_passOverride = std::make_unique<ImageEffectPassOverride> ();
  4006. m_passOverride->combos["THICKFORMAT"] = 1;
  4007. if (m_useRopeRenderer) {
  4008. m_passOverride->shaderOverride = "genericropeparticle";
  4009. // WE's renderer always defines GS_ENABLED (sub_140110630 sets renderer flag 8, sub_140162AC0 adds the define):
  4010. // each segment is one point the geometry shader turns into a strip, curved with TRAILSUBDIVISION midpoints
  4011. // (sub_1401D2340 cases 3 and 4)
  4012. m_passOverride->combos["GS_ENABLED"] = 1;
  4013. m_passOverride->combos["TRAILSUBDIVISION"] = m_ropeSubdivision;
  4014. }
  4015. if (m_spritesheetFrames > 0) {
  4016. m_passOverride->combos["SPRITESHEET"] = 1;
  4017. m_passOverride->combos["SPRITESHEETBLEND"]
  4018. = (m_particle.flags & 2) == 0 && m_particle.animationMode != "randomframe" ? 1 : 0;
  4019. if (const auto texture = getTexture ()) {
  4020. const glm::vec4* res = texture->getResolution ();
  4021. m_passOverride->combos["SPRITESHEETBLENDNPOT"] = res->z < res->x ? 1 : 0;
  4022. }
  4023. }
  4024. if (m_useTrailRenderer) {
  4025. m_passOverride->combos["TRAILRENDERER"] = 1;
  4026. }
  4027. if (m_useRopeRenderer && m_useTrailRenderer) {
  4028. // sub_1401D2340 case 4. WE leaves THICKFORMAT off here and packs a single size and color per point, the
  4029. // THICKFORMAT layout below repeats them as the end values, which the shader treats the same way
  4030. if (m_ropeUVScrolling) {
  4031. m_passOverride->combos["TRAILSCROLLALPHA"] = 1;
  4032. }
  4033. if (m_trailFadeAlpha) {
  4034. m_passOverride->combos["TRAILFADEALPHA"] = 1;
  4035. }
  4036. if (m_trailFadeSize) {
  4037. m_passOverride->combos["TRAILFADESIZE"] = 1;
  4038. }
  4039. }
  4040. // texture 0 is the particle texture, not the shader's util/white default
  4041. m_passBinds = { { 0, "previous" } };
  4042. auto refractIt = firstPass.combos.find ("REFRACT");
  4043. m_hasRefract = refractIt != firstPass.combos.end () && refractIt->second != 0;
  4044. m_passFBOProvider = std::make_shared<FBOProvider> (this);
  4045. // REFRACT reads _rt_FullFrameBuffer while drawing into the scene FBO (undefined, black on NVIDIA), so a copy is
  4046. // registered under that name and blitted before each render
  4047. if (m_hasRefract) {
  4048. auto sceneFBO = getScene ().getFBO ();
  4049. auto w = static_cast<float> (sceneFBO->getRealWidth ());
  4050. auto h = static_cast<float> (sceneFBO->getRealHeight ());
  4051. m_refractFBO = m_passFBOProvider->create (
  4052. "_rt_FullFrameBuffer", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0f, { w, h }, { w, h }
  4053. );
  4054. getScene ().followOutputSize (m_refractFBO, 1);
  4055. }
  4056. m_pass = new Effects::CPass (*this, m_passFBOProvider, firstPass, *m_passOverride, m_passBinds, std::nullopt);
  4057. m_geometryStage = m_useRopeRenderer && m_pass->hasGeometryStage ();
  4058. m_pass->setDestination (getScene ().getFBO ());
  4059. m_pass->setInput (getTexture ());
  4060. m_pass->setModelViewProjectionMatrix (&m_mvpMatrix);
  4061. m_pass->setModelViewProjectionMatrixInverse (&m_mvpMatrixInverse);
  4062. m_pass->setModelMatrix (&m_worldModelMatrix);
  4063. m_pass->setViewProjectionMatrix (&m_viewProjectionMatrix);
  4064. GLint prevVAO = 0;
  4065. glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &prevVAO);
  4066. glGenVertexArrays (1, &m_vao);
  4067. glGenBuffers (1, &m_vbo);
  4068. glGenBuffers (1, &m_ebo);
  4069. glBindVertexArray (m_vao);
  4070. glBindBuffer (GL_ARRAY_BUFFER, m_vbo);
  4071. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, m_ebo);
  4072. const GLuint program = m_pass->getProgramID ();
  4073. if (m_useRopeRenderer) {
  4074. // rope vertex: a_PositionVec4, a_TexCoordVec4, C1, C2, C3 (4 each), a_TexCoordC4 (2), a_Color (4) = 26 floats
  4075. const GLsizei stride = sizeof (float) * ROPE_FLOATS_PER_VERTEX;
  4076. const GLint loc0 = glGetAttribLocation (program, "a_PositionVec4");
  4077. const GLint loc1 = glGetAttribLocation (program, "a_TexCoordVec4");
  4078. const GLint loc2 = glGetAttribLocation (program, "a_TexCoordVec4C1");
  4079. const GLint loc3 = glGetAttribLocation (program, "a_TexCoordVec4C2");
  4080. const GLint loc4 = glGetAttribLocation (program, "a_TexCoordVec4C3");
  4081. const GLint loc5 = glGetAttribLocation (program, "a_TexCoordC4");
  4082. const GLint loc6 = glGetAttribLocation (program, "a_Color");
  4083. if (loc0 >= 0) {
  4084. glEnableVertexAttribArray (loc0);
  4085. glVertexAttribPointer (loc0, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 0));
  4086. }
  4087. if (loc1 >= 0) {
  4088. glEnableVertexAttribArray (loc1);
  4089. glVertexAttribPointer (loc1, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 4));
  4090. }
  4091. if (loc2 >= 0) {
  4092. glEnableVertexAttribArray (loc2);
  4093. glVertexAttribPointer (loc2, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 8));
  4094. }
  4095. if (loc3 >= 0) {
  4096. glEnableVertexAttribArray (loc3);
  4097. glVertexAttribPointer (loc3, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 12));
  4098. }
  4099. if (loc4 >= 0) {
  4100. glEnableVertexAttribArray (loc4);
  4101. glVertexAttribPointer (loc4, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 16));
  4102. }
  4103. if (loc5 >= 0) {
  4104. glEnableVertexAttribArray (loc5);
  4105. glVertexAttribPointer (loc5, 2, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 20));
  4106. }
  4107. if (loc6 >= 0) {
  4108. glEnableVertexAttribArray (loc6);
  4109. glVertexAttribPointer (loc6, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 22));
  4110. }
  4111. } else {
  4112. this->setupSpriteAttributes (program);
  4113. }
  4114. glBindVertexArray (prevVAO);
  4115. setupGeometryCallbacks ();
  4116. setupParticleUniforms ();
  4117. if (m_hasTrailPass) {
  4118. this->setupTrailPass (firstPass);
  4119. }
  4120. }
  4121. void CParticle::setupSpriteAttributes (GLuint program) const {
  4122. // sprite vertex: a_Position (3), a_TexCoordVec4 (4), a_Color (4), a_TexCoordVec4C1 (4), a_TexCoordC2 (2)
  4123. const GLsizei stride = sizeof (float) * SPRITE_FLOATS_PER_VERTEX;
  4124. const struct {
  4125. const char* name;
  4126. GLint size;
  4127. size_t offset;
  4128. } attributes[] = { { "a_Position", 3, 0 },
  4129. { "a_TexCoordVec4", 4, 3 },
  4130. { "a_Color", 4, 7 },
  4131. { "a_TexCoordVec4C1", 4, 11 },
  4132. { "a_TexCoordC2", 2, 15 } };
  4133. for (const auto& attribute : attributes) {
  4134. if (const GLint location = glGetAttribLocation (program, attribute.name); location >= 0) {
  4135. glEnableVertexAttribArray (location);
  4136. glVertexAttribPointer (
  4137. location, attribute.size, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * attribute.offset)
  4138. );
  4139. }
  4140. }
  4141. }
  4142. void CParticle::setupTrailPass (const MaterialPass& firstPass) {
  4143. // the particle's override only ever carries combos and a shader name
  4144. m_trailPassOverride = std::make_unique<ImageEffectPassOverride> ();
  4145. m_trailPassOverride->combos = m_passOverride->combos;
  4146. m_trailPassOverride->shaderOverride = m_passOverride->shaderOverride;
  4147. m_trailPassOverride->combos["TRAILRENDERER"] = 1;
  4148. m_trailPass
  4149. = new Effects::CPass (*this, m_passFBOProvider, firstPass, *m_trailPassOverride, m_passBinds, std::nullopt);
  4150. m_trailPass->setDestination (getScene ().getFBO ());
  4151. m_trailPass->setInput (getTexture ());
  4152. m_trailPass->setModelViewProjectionMatrix (&m_mvpMatrix);
  4153. m_trailPass->setModelViewProjectionMatrixInverse (&m_mvpMatrixInverse);
  4154. m_trailPass->setModelMatrix (&m_worldModelMatrix);
  4155. m_trailPass->setViewProjectionMatrix (&m_viewProjectionMatrix);
  4156. GLint prevVAO = 0;
  4157. glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &prevVAO);
  4158. glGenVertexArrays (1, &m_trailVao);
  4159. glBindVertexArray (m_trailVao);
  4160. glBindBuffer (GL_ARRAY_BUFFER, m_vbo);
  4161. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, m_ebo);
  4162. this->setupSpriteAttributes (m_trailPass->getProgramID ());
  4163. glBindVertexArray (prevVAO);
  4164. m_trailPass->setGeometryCallback (
  4165. [this] () {
  4166. glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &m_trailPrevVAO);
  4167. glBindVertexArray (m_trailVao);
  4168. glFrontFace (GL_CW);
  4169. },
  4170. [this] () { glDrawElements (GL_TRIANGLES, m_activeIndexCount, GL_UNSIGNED_INT, nullptr); },
  4171. [this] () {
  4172. glFrontFace (GL_CCW);
  4173. glBindVertexArray (m_trailPrevVAO);
  4174. }
  4175. );
  4176. this->addParticleUniforms (*m_trailPass, &m_trailRenderVar0);
  4177. }
  4178. void CParticle::setupGeometryCallbacks () {
  4179. m_pass->setGeometryCallback (
  4180. [this] () {
  4181. glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &m_prevVAO);
  4182. glBindVertexArray (m_vao);
  4183. // WE has one rasterizer state for all objects (sub_140099050)
  4184. glFrontFace (GL_CW);
  4185. },
  4186. [this] () {
  4187. if (m_geometryStage) {
  4188. glDrawArrays (GL_POINTS, 0, m_activeIndexCount);
  4189. } else {
  4190. glDrawElements (GL_TRIANGLES, m_activeIndexCount, GL_UNSIGNED_INT, nullptr);
  4191. }
  4192. },
  4193. [this] () {
  4194. glFrontFace (GL_CCW);
  4195. glBindVertexArray (m_prevVAO);
  4196. }
  4197. );
  4198. }
  4199. void CParticle::setupParticleUniforms () { this->addParticleUniforms (*m_pass, &m_renderVar0); }
  4200. void CParticle::addParticleUniforms (Effects::CPass& pass, const glm::vec4* renderVar0) {
  4201. // common_particles.h uniforms CPass doesn't provide, read every frame
  4202. pass.addUniform ("g_ModelMatrixInverse", &m_modelMatrixInverse);
  4203. pass.addUniform ("g_OrientationUp", &m_orientationUp);
  4204. pass.addUniform ("g_OrientationRight", &m_orientationRight);
  4205. pass.addUniform ("g_OrientationForward", &m_orientationForward);
  4206. pass.addUniform ("g_ViewUp", &m_viewUp);
  4207. pass.addUniform ("g_ViewRight", &m_viewRight);
  4208. pass.addUniform ("g_EyePosition", &m_eyePosition);
  4209. pass.addUniform ("g_RenderVar0", renderVar0);
  4210. pass.addUniform ("g_RenderVar1", &m_renderVar1);
  4211. if (m_hasRefract) {
  4212. pass.addUniform ("g_RefractAmount", &m_refractAmount);
  4213. }
  4214. }
  4215. void CParticle::updateMatrices () {
  4216. // g_ModelMatrix is WE's world matrix (lighting, fog, eye), m_modelMatrix adds the 2D scene space
  4217. m_modelMatrixInverse = glm::inverse (m_worldModelMatrix);
  4218. this->updateParticleViewProjection ();
  4219. m_mvpMatrix = m_viewProjectionMatrix * m_modelMatrix;
  4220. m_mvpMatrixInverse = glm::inverse (m_mvpMatrix);
  4221. this->updateOrientation ();
  4222. // g_ViewRight / g_ViewUp (uniforms 0x1B / 0x1C, sub_1400D8300) are renderer +364 / +376: rows 0 and 1 of the view,
  4223. // the camera's right and up in the world (sub_14017FA70 0x1401801a0)
  4224. m_viewRight = glm::vec3 (1.0f, 0.0f, 0.0f);
  4225. m_viewUp = glm::vec3 (0.0f, 1.0f, 0.0f);
  4226. if (const auto& camera = getScene ().getCamera (); camera.isPerspective ()) {
  4227. const glm::mat4& view = camera.getView ();
  4228. m_viewRight = glm::vec3 (view[0][0], view[1][0], view[2][0]);
  4229. m_viewUp = glm::vec3 (view[0][1], view[1][1], view[2][1]);
  4230. }
  4231. this->updateParticleRenderVars ();
  4232. }
  4233. void CParticle::updateOrientation () {
  4234. // sub_1402298B0: the camera's forward and up (renderer +352 / +376, -row 2 and row 1 of the view), the
  4235. // system's world matrix as WE has it (local axes in its rows, so "v * M" is W * v here and "M * v" is
  4236. // transpose (W) * v), forward and up worked out in the world and taken into the system's own frame
  4237. const auto& camera = getScene ().getCamera ();
  4238. glm::vec3 cameraForward (0.0f, 0.0f, -1.0f);
  4239. glm::vec3 cameraUp (0.0f, 1.0f, 0.0f);
  4240. if (camera.isPerspective ()) {
  4241. const glm::mat4& view = camera.getView ();
  4242. cameraForward = -glm::vec3 (view[0][2], view[1][2], view[2][2]);
  4243. cameraUp = glm::vec3 (view[0][1], view[1][1], view[2][1]);
  4244. }
  4245. static const ParticleRenderer screen {};
  4246. const ParticleRenderer& renderer = m_particle.renderers.empty () ? screen : m_particle.renderers[0];
  4247. const glm::mat3 world (m_worldModelMatrix);
  4248. glm::vec3 forward;
  4249. glm::vec3 up;
  4250. switch (renderer.orientation) {
  4251. case 1:
  4252. {
  4253. // upright: up along the axis, facing the camera around it
  4254. up = renderer.orientationFlag ? glm::vec3 (0.0f, 1.0f, 0.0f) : world * renderer.axis;
  4255. const glm::vec3 right = glm::cross (cameraForward, up);
  4256. forward = glm::cross (right, up);
  4257. break;
  4258. }
  4259. case 2:
  4260. // fixed: the axis as forward, in the system's frame unless flags & 1
  4261. forward = renderer.orientationFlag ? renderer.axis : world * renderer.axis;
  4262. up = renderer.orientationFlag ? renderer.axisUp : world * renderer.axisUp;
  4263. break;
  4264. default:
  4265. // screen: facing the camera, up the system's y axis (or the camera's up) made perpendicular to it
  4266. forward = -cameraForward;
  4267. up = renderer.orientationFlag ? cameraUp : world[1];
  4268. up -= forward * glm::dot (forward, up);
  4269. break;
  4270. }
  4271. forward = glm::transpose (world) * forward;
  4272. up = glm::transpose (world) * up;
  4273. m_orientationForward = glm::normalize (forward);
  4274. m_orientationRight = glm::normalize (glm::cross (up, forward));
  4275. m_orientationUp = glm::normalize (up);
  4276. }
  4277. void CParticle::updateParticleViewProjection () {
  4278. const auto& camera = getScene ().getCamera ();
  4279. if (camera.isPerspective ()) {
  4280. m_viewProjectionMatrix = camera.getPerspective () * camera.getView ();
  4281. m_eyePosition = camera.getEye ();
  4282. } else {
  4283. // particle file flags 4 (sub_1402366F0) and the object's "perspective" (sub_1402222A0) both switch to the
  4284. // perspective layer camera (sub_1401E5B60)
  4285. const bool perspective = (m_particle.flags & 4) != 0 || m_particle.perspective->value->getBool ();
  4286. m_viewProjectionMatrix
  4287. = perspective ? camera.getPerspectiveLayerViewProjection () : camera.getProjection () * camera.getLookAt ();
  4288. // g_EyePosition is the renderer eye like for every other pass, in 2D scenes 2000 units out over the scene
  4289. // center plus the camera (end of sub_1401891A0). The trail shader's ComputeParticleTrailTangents crosses the
  4290. // eye direction with the velocity, LIGHTING takes it as the sprite's normal
  4291. m_eyePosition = getScene ().getFog ().eyeWorld;
  4292. }
  4293. }
  4294. void CParticle::updateParticleRenderVars () {
  4295. if (m_useRopeRenderer && m_useTrailRenderer) {
  4296. // sub_1402366F0 renderer type 4: z is how far the history timer got, w the segment count the UVs span
  4297. const auto segments = static_cast<float> (m_ropeSegments);
  4298. const float timeOffset = 1.0f - std::max (m_trailTimer, 0.0f) / m_trailInterval;
  4299. m_renderVar0 = m_ropeUVScrolling
  4300. ? glm::vec4 (segments - 1.0f, 0.0f, timeOffset, (segments - 1.0f) / this->ropeUVScale ())
  4301. : glm::vec4 (0.0f, 0.0f, timeOffset, segments - 0.5f);
  4302. } else {
  4303. m_renderVar0 = glm::vec4 (m_trailLength, m_trailMaxLength, m_trailMinLength, 0.0f);
  4304. }
  4305. m_trailRenderVar0 = glm::vec4 (m_extraTrailLength, m_extraTrailMaxLength, m_extraTrailMinLength, 0.0f);
  4306. if (m_spritesheetFrames > 0) {
  4307. const auto texture = getTexture ();
  4308. const auto& frame = *texture->getFrames ().front ();
  4309. const float frameWidth = frame.width1 / static_cast<float> (texture->getTextureWidth (frame.frameNumber));
  4310. const float frameHeight = frame.height1 / static_cast<float> (texture->getTextureHeight (frame.frameNumber));
  4311. const glm::vec4* res = texture->getResolution ();
  4312. m_renderVar1 = glm::vec4 (
  4313. frameWidth, frameHeight, static_cast<float> (m_spritesheetFrames),
  4314. res->y / res->x * (frameHeight / frameWidth)
  4315. );
  4316. } else {
  4317. float textureRatio = 1.0f;
  4318. if (const auto texture = getTexture ()) {
  4319. auto w = static_cast<float> (texture->getRealWidth ());
  4320. auto h = static_cast<float> (texture->getRealHeight ());
  4321. if (w > 0.0f) {
  4322. textureRatio = h / w;
  4323. }
  4324. }
  4325. m_renderVar1 = glm::vec4 (0.0f, 0.0f, 0.0f, textureRatio);
  4326. }
  4327. }
  4328. void CParticle::renderSprites () {
  4329. if (m_particleCount == 0 || m_pass == nullptr) {
  4330. return;
  4331. }
  4332. uint32_t aliveCount = 0;
  4333. for (uint32_t i = 0; i < m_particleCount; i++) {
  4334. if (m_particles[i].alive) {
  4335. aliveCount++;
  4336. }
  4337. }
  4338. if (aliveCount == 0) {
  4339. return;
  4340. }
  4341. // a_Position, a_TexCoordVec4 (uv, rotZ, size), a_Color, a_TexCoordVec4C1 (velocity, lifetime), a_TexCoordC2 (rotX,
  4342. // rotY)
  4343. uint32_t vertexIndex = 0;
  4344. uint32_t indexOffset = 0;
  4345. for (uint32_t i = 0; i < m_particleCount; i++) {
  4346. const auto& p = m_particles[i];
  4347. if (!p.alive) {
  4348. continue;
  4349. }
  4350. if (!std::isfinite (p.position.x) || !std::isfinite (p.position.y) || !std::isfinite (p.position.z)
  4351. || !std::isfinite (p.size) || p.size <= 0.0f || p.size > 10000.0f) {
  4352. continue;
  4353. }
  4354. // the CPU frame encoded as the lifetime ComputeSpriteFrame expects: floor(frac(lifetime) * frames), blend
  4355. // frac(lifetime * frames)
  4356. float lifetime = p.getLifetimePos ();
  4357. if (m_spritesheetFrames > 0 && p.frame >= 0.0f) {
  4358. if (m_particle.animationMode == "randomframe") {
  4359. // frame center, away from float edges
  4360. lifetime = (p.frame + 0.5f) / static_cast<float> (m_spritesheetFrames);
  4361. } else {
  4362. lifetime = p.frame / static_cast<float> (m_spritesheetFrames);
  4363. }
  4364. }
  4365. const glm::vec3& position = p.position;
  4366. const glm::vec3& velocity = p.velocity;
  4367. auto addVertex = [&] (float u, float v) {
  4368. const uint32_t base = vertexIndex * SPRITE_FLOATS_PER_VERTEX;
  4369. m_vertices[base + 0] = position.x;
  4370. m_vertices[base + 1] = position.y;
  4371. m_vertices[base + 2] = position.z;
  4372. m_vertices[base + 3] = u;
  4373. m_vertices[base + 4] = v;
  4374. m_vertices[base + 5] = p.rotation.z;
  4375. m_vertices[base + 6] = p.size;
  4376. m_vertices[base + 7] = p.color.r;
  4377. m_vertices[base + 8] = p.color.g;
  4378. m_vertices[base + 9] = p.color.b;
  4379. m_vertices[base + 10] = p.alpha;
  4380. m_vertices[base + 11] = velocity.x;
  4381. m_vertices[base + 12] = velocity.y;
  4382. m_vertices[base + 13] = velocity.z;
  4383. m_vertices[base + 14] = lifetime;
  4384. m_vertices[base + 15] = p.rotation.x;
  4385. m_vertices[base + 16] = p.rotation.y;
  4386. vertexIndex++;
  4387. };
  4388. uint32_t baseVertex = vertexIndex;
  4389. addVertex (0.0f, 1.0f);
  4390. addVertex (1.0f, 1.0f);
  4391. addVertex (1.0f, 0.0f);
  4392. addVertex (0.0f, 0.0f);
  4393. m_indices[indexOffset++] = baseVertex + 0;
  4394. m_indices[indexOffset++] = baseVertex + 1;
  4395. m_indices[indexOffset++] = baseVertex + 2;
  4396. m_indices[indexOffset++] = baseVertex + 2;
  4397. m_indices[indexOffset++] = baseVertex + 3;
  4398. m_indices[indexOffset++] = baseVertex + 0;
  4399. }
  4400. m_activeIndexCount = static_cast<GLsizei> (indexOffset);
  4401. if (m_activeIndexCount == 0) {
  4402. return;
  4403. }
  4404. #if !NDEBUG
  4405. std::string str = "Particles ";
  4406. str += this->getParticle ().name + " (" + std::to_string (this->getId ()) + ", " + this->getParticle ().particleFile
  4407. + ")";
  4408. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
  4409. #endif
  4410. glBindBuffer (GL_ARRAY_BUFFER, m_vbo);
  4411. glBufferData (
  4412. GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (vertexIndex * SPRITE_FLOATS_PER_VERTEX * sizeof (float)),
  4413. m_vertices.data (), GL_DYNAMIC_DRAW
  4414. );
  4415. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, m_ebo);
  4416. glBufferData (
  4417. GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (indexOffset * sizeof (uint32_t)), m_indices.data (),
  4418. GL_DYNAMIC_DRAW
  4419. );
  4420. updateMatrices ();
  4421. copyRefractSource ();
  4422. // trail tangents have a z component that pushes 2D quads past the ortho near plane, clamp depth instead of clipping
  4423. glEnable (GL_DEPTH_CLAMP);
  4424. m_pass->render ();
  4425. if (m_trailPass != nullptr) {
  4426. m_trailPass->render ();
  4427. }
  4428. glDisable (GL_DEPTH_CLAMP);
  4429. #if !NDEBUG
  4430. glPopDebugGroup ();
  4431. #endif
  4432. }
  4433. float CParticle::ropeUVScale () const { return m_ropeUVScale != 0.0f ? m_ropeUVScale : 1.0f; }
  4434. void CParticle::copyRefractSource () const {
  4435. if (!m_hasRefract || !m_refractFBO) {
  4436. return;
  4437. }
  4438. // WE resolves the bound target into _rt_FullFrameBuffer (sub_1402366F0 -> sub_1400D3310); under a passthrough layer
  4439. // that's its buffer, which only copies at the window's size (same color format, sub_1400D2A20), otherwise the
  4440. // texture keeps the scene from before the layer, our scene buffer
  4441. std::shared_ptr<const CFBO> source = getScene ().getFBO ();
  4442. if (const auto* layer = getScene ().getLayerTarget (); layer != nullptr) {
  4443. const glm::ivec2 layerSize { std::max (layer->fbo->getRealWidth (), 4u),
  4444. std::max (layer->fbo->getRealHeight (), 4u) };
  4445. const glm::ivec2 outputSize = glm::max (getScene ().getOutputSize (), glm::ivec2 (2));
  4446. if (layerSize == outputSize) {
  4447. source = layer->fbo;
  4448. }
  4449. }
  4450. if (source == getScene ().getFBO ()) {
  4451. getScene ().resolveMultisample ();
  4452. }
  4453. const auto sw = static_cast<GLint> (source->getRealWidth ());
  4454. const auto sh = static_cast<GLint> (source->getRealHeight ());
  4455. const auto dw = static_cast<GLint> (m_refractFBO->getRealWidth ());
  4456. const auto dh = static_cast<GLint> (m_refractFBO->getRealHeight ());
  4457. // our copy is scene sized, the shader samples it with normalized coordinates only
  4458. glBindFramebuffer (GL_READ_FRAMEBUFFER, source->getFramebuffer ());
  4459. glBindFramebuffer (GL_DRAW_FRAMEBUFFER, m_refractFBO->getFramebuffer ());
  4460. glBlitFramebuffer (0, 0, sw, sh, 0, 0, dw, dh, GL_COLOR_BUFFER_BIT, sw == dw && sh == dh ? GL_NEAREST : GL_LINEAR);
  4461. }
  4462. void CParticle::buildRopeTrail (uint32_t& vertexIndex, uint32_t& indexOffset) {
  4463. // sub_1402308A0, the ropetrail vertex build without a geometry shader: every particle gets one strip through
  4464. // its position and its history, a quad per segment whether that history is filled yet or not
  4465. const int segments = m_ropeSegments;
  4466. const float uvScaleInverse = 1.0f / this->ropeUVScale ();
  4467. for (uint32_t i = 0; i < m_particleCount; i++) {
  4468. const auto& p = m_particles[i];
  4469. const glm::vec3* history = m_trailHistory.data () + static_cast<size_t> (i) * segments;
  4470. const auto point = [&] (int index) -> const glm::vec3& { return index == 0 ? p.position : history[index - 1]; };
  4471. const glm::vec4 color (p.color, p.alpha);
  4472. const float trailLength = static_cast<float> (m_trailCount[i]) * uvScaleInverse;
  4473. const auto scroll = static_cast<float> (m_trailScroll[i]);
  4474. for (int k = 0; k < segments; k++) {
  4475. const glm::vec3& start = point (k);
  4476. const glm::vec3& end = point (k + 1);
  4477. const glm::vec3& before = point (std::max (k - 1, 0));
  4478. const glm::vec3& after = point (std::min (k + 2, segments));
  4479. // with uvscrolling the length slot carries the segment index and positions move back with every push
  4480. const float lengthSlot = m_ropeUVScrolling ? static_cast<float> (k) : trailLength;
  4481. const float position = m_ropeUVScrolling ? static_cast<float> (k) - scroll : static_cast<float> (k);
  4482. // sub_1402308A0 with a geometry shader: the same record once per segment, without the corner
  4483. if (m_geometryStage) {
  4484. float* v = &m_vertices[static_cast<size_t> (vertexIndex++) * ROPE_FLOATS_PER_VERTEX];
  4485. const float values[ROPE_FLOATS_PER_VERTEX] = {
  4486. start.x, start.y, start.z, p.size, end.x, end.y, end.z, lengthSlot, before.x,
  4487. before.y, before.z, position, after.x, after.y, after.z, p.size, color.r, color.g,
  4488. color.b, color.a, 0.0f, 0.0f, color.r, color.g, color.b, color.a,
  4489. };
  4490. std::copy (std::begin (values), std::end (values), v);
  4491. continue;
  4492. }
  4493. const uint32_t baseVertex = vertexIndex;
  4494. for (const glm::vec2 uv :
  4495. { glm::vec2 (0.0f, 0.0f), glm::vec2 (1.0f, 0.0f), glm::vec2 (1.0f, 1.0f), glm::vec2 (0.0f, 1.0f) }) {
  4496. float* v = &m_vertices[static_cast<size_t> (vertexIndex++) * ROPE_FLOATS_PER_VERTEX];
  4497. const float values[ROPE_FLOATS_PER_VERTEX] = {
  4498. start.x, start.y, start.z, p.size, end.x, end.y, end.z, lengthSlot, before.x,
  4499. before.y, before.z, position, after.x, after.y, after.z, p.size, color.r, color.g,
  4500. color.b, color.a, uv.x, uv.y, color.r, color.g, color.b, color.a,
  4501. };
  4502. std::copy (std::begin (values), std::end (values), v);
  4503. }
  4504. for (const uint32_t corner : { 0u, 1u, 2u, 2u, 3u, 0u }) {
  4505. m_indices[indexOffset++] = baseVertex + corner;
  4506. }
  4507. }
  4508. }
  4509. }
  4510. void CParticle::buildRopeSegments (uint32_t& vertexIndex, uint32_t& indexOffset) {
  4511. // sub_1402308A0: a record per neighbouring pair with their neighbours as control points, UV length count / uvscale.
  4512. // 2.8.42 zeroes the uvscrolling/uvsmoothing rate, scrolling gives -1 / uvscale shifted by dead particles
  4513. const uint32_t count = m_particleCount;
  4514. const float lengthSlot = (m_ropeUVScrolling ? -1.0f : static_cast<float> (count)) / this->ropeUVScale ();
  4515. const float positionOffset = m_ropeUVScrolling ? static_cast<float> (m_ropeDeaths) : 0.0f;
  4516. // a single segment: position 0, length the plain count
  4517. const bool single = count <= 2;
  4518. const auto position = [this, count] (uint32_t index) { return m_particles[std::min (index, count - 1)].position; };
  4519. for (uint32_t k = 0; k + 1 < count; k++) {
  4520. const auto& first = m_particles[k];
  4521. const auto& second = m_particles[k + 1];
  4522. const glm::vec3 start = position (k);
  4523. const glm::vec3 end = position (k + 1);
  4524. const glm::vec3 before = position (k == 0 ? 0 : k - 1);
  4525. const glm::vec3 after = position (k + 2);
  4526. const float segmentLength = single && m_geometryStage ? static_cast<float> (count) : lengthSlot;
  4527. const float segmentPosition = single ? 0.0f : static_cast<float> (k) + positionOffset;
  4528. const auto write = [&] (const glm::vec2& corner) {
  4529. float* v = &m_vertices[static_cast<size_t> (vertexIndex++) * ROPE_FLOATS_PER_VERTEX];
  4530. const float values[ROPE_FLOATS_PER_VERTEX] = {
  4531. start.x, start.y, start.z, first.size, end.x, end.y, end.z,
  4532. segmentLength, before.x, before.y, before.z, segmentPosition, after.x, after.y,
  4533. after.z, second.size, second.color.r, second.color.g, second.color.b, second.alpha, corner.x,
  4534. corner.y, first.color.r, first.color.g, first.color.b, first.alpha,
  4535. };
  4536. std::copy (std::begin (values), std::end (values), v);
  4537. };
  4538. if (m_geometryStage) {
  4539. write (glm::vec2 (0.0f));
  4540. continue;
  4541. }
  4542. const uint32_t baseVertex = vertexIndex;
  4543. for (const glm::vec2 corner :
  4544. { glm::vec2 (0.0f, 0.0f), glm::vec2 (1.0f, 0.0f), glm::vec2 (1.0f, 1.0f), glm::vec2 (0.0f, 1.0f) }) {
  4545. write (corner);
  4546. }
  4547. for (const uint32_t corner : { 0u, 1u, 2u, 2u, 3u, 0u }) {
  4548. m_indices[indexOffset++] = baseVertex + corner;
  4549. }
  4550. }
  4551. }
  4552. void CParticle::renderRope () {
  4553. if (m_pass == nullptr || m_particleCount < (m_useTrailRenderer ? 1u : 2u)) {
  4554. return;
  4555. }
  4556. uint32_t vertexIndex = 0;
  4557. uint32_t indexOffset = 0;
  4558. if (m_useTrailRenderer) {
  4559. this->buildRopeTrail (vertexIndex, indexOffset);
  4560. } else {
  4561. this->buildRopeSegments (vertexIndex, indexOffset);
  4562. }
  4563. m_activeIndexCount = static_cast<GLsizei> (m_geometryStage ? vertexIndex : indexOffset);
  4564. if (m_activeIndexCount == 0) {
  4565. return;
  4566. }
  4567. #if !NDEBUG
  4568. std::string str = "Rope particles ";
  4569. str += this->getParticle ().name + " (" + std::to_string (this->getId ()) + ", " + this->getParticle ().particleFile
  4570. + ")";
  4571. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
  4572. #endif
  4573. glBindBuffer (GL_ARRAY_BUFFER, m_vbo);
  4574. glBufferData (
  4575. GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (vertexIndex * ROPE_FLOATS_PER_VERTEX * sizeof (float)),
  4576. m_vertices.data (), GL_DYNAMIC_DRAW
  4577. );
  4578. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, m_ebo);
  4579. glBufferData (
  4580. GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (indexOffset * sizeof (uint32_t)), m_indices.data (),
  4581. GL_DYNAMIC_DRAW
  4582. );
  4583. updateMatrices ();
  4584. copyRefractSource ();
  4585. glEnable (GL_DEPTH_CLAMP);
  4586. m_pass->render ();
  4587. glDisable (GL_DEPTH_CLAMP);
  4588. #if !NDEBUG
  4589. glPopDebugGroup ();
  4590. #endif
  4591. }