visual_server_scene.cpp 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619
  1. /**************************************************************************/
  2. /* visual_server_scene.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "visual_server_scene.h"
  31. #include "core/math/transform_interpolator.h"
  32. #include "core/os/os.h"
  33. #include "visual_server_globals.h"
  34. #include "visual_server_raster.h"
  35. #include <new>
  36. /* CAMERA API */
  37. Transform VisualServerScene::Camera::get_transform_interpolated() const {
  38. if (!interpolated) {
  39. return transform;
  40. }
  41. Transform final;
  42. TransformInterpolator::interpolate_transform_via_method(transform_prev, transform, final, Engine::get_singleton()->get_physics_interpolation_fraction(), interpolation_method);
  43. return final;
  44. }
  45. RID VisualServerScene::camera_create() {
  46. Camera *camera = memnew(Camera);
  47. return camera_owner.make_rid(camera);
  48. }
  49. void VisualServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
  50. Camera *camera = camera_owner.get(p_camera);
  51. ERR_FAIL_COND(!camera);
  52. camera->type = Camera::PERSPECTIVE;
  53. camera->fov = p_fovy_degrees;
  54. camera->znear = p_z_near;
  55. camera->zfar = p_z_far;
  56. }
  57. void VisualServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
  58. Camera *camera = camera_owner.get(p_camera);
  59. ERR_FAIL_COND(!camera);
  60. camera->type = Camera::ORTHOGONAL;
  61. camera->size = p_size;
  62. camera->znear = p_z_near;
  63. camera->zfar = p_z_far;
  64. }
  65. void VisualServerScene::camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
  66. Camera *camera = camera_owner.get(p_camera);
  67. ERR_FAIL_COND(!camera);
  68. camera->type = Camera::FRUSTUM;
  69. camera->size = p_size;
  70. camera->offset = p_offset;
  71. camera->znear = p_z_near;
  72. camera->zfar = p_z_far;
  73. }
  74. void VisualServerScene::camera_reset_physics_interpolation(RID p_camera) {
  75. Camera *camera = camera_owner.get(p_camera);
  76. ERR_FAIL_COND(!camera);
  77. if (_interpolation_data.interpolation_enabled && camera->interpolated) {
  78. _interpolation_data.camera_teleport_list.push_back(p_camera);
  79. }
  80. }
  81. void VisualServerScene::camera_set_interpolated(RID p_camera, bool p_interpolated) {
  82. Camera *camera = camera_owner.get(p_camera);
  83. ERR_FAIL_COND(!camera);
  84. camera->interpolated = p_interpolated;
  85. }
  86. void VisualServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) {
  87. Camera *camera = camera_owner.get(p_camera);
  88. ERR_FAIL_COND(!camera);
  89. camera->transform = p_transform.orthonormalized();
  90. if (_interpolation_data.interpolation_enabled) {
  91. if (camera->interpolated) {
  92. if (!camera->on_interpolate_transform_list) {
  93. _interpolation_data.camera_transform_update_list_curr->push_back(p_camera);
  94. camera->on_interpolate_transform_list = true;
  95. }
  96. // decide on the interpolation method .. slerp if possible
  97. camera->interpolation_method = TransformInterpolator::find_method(camera->transform_prev.basis, camera->transform.basis);
  98. #if defined(DEBUG_ENABLED) && defined(TOOLS_ENABLED)
  99. if (!Engine::get_singleton()->is_in_physics_frame()) {
  100. // Effectively a WARN_PRINT_ONCE but after a certain number of occurrences.
  101. static int32_t warn_count = -256;
  102. if ((warn_count == 0) && GLOBAL_GET("debug/settings/physics_interpolation/enable_warnings")) {
  103. WARN_PRINT("[Physics interpolation] Camera interpolation is being triggered from outside physics process, this might lead to issues (possibly benign).");
  104. }
  105. warn_count++;
  106. }
  107. #endif
  108. } else {
  109. #if defined(DEBUG_ENABLED) && defined(TOOLS_ENABLED)
  110. if (Engine::get_singleton()->is_in_physics_frame()) {
  111. static int32_t warn_count = -256;
  112. if ((warn_count == 0) && GLOBAL_GET("debug/settings/physics_interpolation/enable_warnings")) {
  113. WARN_PRINT("[Physics interpolation] Non-interpolated Camera is being triggered from physics process, this might lead to issues (possibly benign).");
  114. }
  115. warn_count++;
  116. }
  117. #endif
  118. }
  119. }
  120. }
  121. void VisualServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
  122. Camera *camera = camera_owner.get(p_camera);
  123. ERR_FAIL_COND(!camera);
  124. camera->visible_layers = p_layers;
  125. }
  126. void VisualServerScene::camera_set_environment(RID p_camera, RID p_env) {
  127. Camera *camera = camera_owner.get(p_camera);
  128. ERR_FAIL_COND(!camera);
  129. camera->env = p_env;
  130. }
  131. void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
  132. Camera *camera = camera_owner.get(p_camera);
  133. ERR_FAIL_COND(!camera);
  134. camera->vaspect = p_enable;
  135. }
  136. /* SPATIAL PARTITIONING */
  137. VisualServerScene::SpatialPartitioningScene_BVH::SpatialPartitioningScene_BVH() {
  138. _bvh.params_set_thread_safe(GLOBAL_GET("rendering/threads/thread_safe_bvh"));
  139. _bvh.params_set_pairing_expansion(GLOBAL_GET("rendering/quality/spatial_partitioning/bvh_collision_margin"));
  140. _dummy_cull_object = memnew(Instance);
  141. }
  142. VisualServerScene::SpatialPartitioningScene_BVH::~SpatialPartitioningScene_BVH() {
  143. if (_dummy_cull_object) {
  144. memdelete(_dummy_cull_object);
  145. _dummy_cull_object = nullptr;
  146. }
  147. }
  148. VisualServerScene::SpatialPartitionID VisualServerScene::SpatialPartitioningScene_BVH::create(Instance *p_userdata, const AABB &p_aabb, int p_subindex, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) {
  149. #if defined(DEBUG_ENABLED) && defined(TOOLS_ENABLED)
  150. // we are relying on this instance to be valid in order to pass
  151. // the visible flag to the bvh.
  152. DEV_ASSERT(p_userdata);
  153. #endif
  154. // cache the pairable mask and pairable type on the instance as it is needed for user callbacks from the BVH, and this is
  155. // too complex to calculate each callback...
  156. p_userdata->bvh_pairable_mask = p_pairable_mask;
  157. p_userdata->bvh_pairable_type = p_pairable_type;
  158. uint32_t tree_id = p_pairable ? 1 : 0;
  159. uint32_t tree_collision_mask = 3;
  160. return _bvh.create(p_userdata, p_userdata->visible, tree_id, tree_collision_mask, p_aabb, p_subindex) + 1;
  161. }
  162. void VisualServerScene::SpatialPartitioningScene_BVH::erase(SpatialPartitionID p_handle) {
  163. _bvh.erase(p_handle - 1);
  164. }
  165. void VisualServerScene::SpatialPartitioningScene_BVH::move(SpatialPartitionID p_handle, const AABB &p_aabb) {
  166. _bvh.move(p_handle - 1, p_aabb);
  167. }
  168. void VisualServerScene::SpatialPartitioningScene_BVH::activate(SpatialPartitionID p_handle, const AABB &p_aabb) {
  169. // be very careful here, we are deferring the collision check, expecting a set_pairable to be called
  170. // immediately after.
  171. // see the notes in the BVH function.
  172. _bvh.activate(p_handle - 1, p_aabb, true);
  173. }
  174. void VisualServerScene::SpatialPartitioningScene_BVH::deactivate(SpatialPartitionID p_handle) {
  175. _bvh.deactivate(p_handle - 1);
  176. }
  177. void VisualServerScene::SpatialPartitioningScene_BVH::force_collision_check(SpatialPartitionID p_handle) {
  178. _bvh.force_collision_check(p_handle - 1);
  179. }
  180. void VisualServerScene::SpatialPartitioningScene_BVH::update() {
  181. _bvh.update();
  182. }
  183. void VisualServerScene::SpatialPartitioningScene_BVH::update_collisions() {
  184. _bvh.update_collisions();
  185. }
  186. void VisualServerScene::SpatialPartitioningScene_BVH::set_pairable(Instance *p_instance, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) {
  187. SpatialPartitionID handle = p_instance->spatial_partition_id;
  188. p_instance->bvh_pairable_mask = p_pairable_mask;
  189. p_instance->bvh_pairable_type = p_pairable_type;
  190. uint32_t tree_id = p_pairable ? 1 : 0;
  191. uint32_t tree_collision_mask = 3;
  192. _bvh.set_tree(handle - 1, tree_id, tree_collision_mask);
  193. }
  194. int VisualServerScene::SpatialPartitioningScene_BVH::cull_convex(const Vector<Plane> &p_convex, Instance **p_result_array, int p_result_max, uint32_t p_mask) {
  195. _dummy_cull_object->bvh_pairable_mask = p_mask;
  196. _dummy_cull_object->bvh_pairable_type = 0;
  197. return _bvh.cull_convex(p_convex, p_result_array, p_result_max, _dummy_cull_object);
  198. }
  199. int VisualServerScene::SpatialPartitioningScene_BVH::cull_aabb(const AABB &p_aabb, Instance **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  200. _dummy_cull_object->bvh_pairable_mask = p_mask;
  201. _dummy_cull_object->bvh_pairable_type = 0;
  202. return _bvh.cull_aabb(p_aabb, p_result_array, p_result_max, _dummy_cull_object, 0xFFFFFFFF, p_subindex_array);
  203. }
  204. int VisualServerScene::SpatialPartitioningScene_BVH::cull_segment(const Vector3 &p_from, const Vector3 &p_to, Instance **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  205. _dummy_cull_object->bvh_pairable_mask = p_mask;
  206. _dummy_cull_object->bvh_pairable_type = 0;
  207. return _bvh.cull_segment(p_from, p_to, p_result_array, p_result_max, _dummy_cull_object, 0xFFFFFFFF, p_subindex_array);
  208. }
  209. void VisualServerScene::SpatialPartitioningScene_BVH::set_pair_callback(PairCallback p_callback, void *p_userdata) {
  210. _bvh.set_pair_callback(p_callback, p_userdata);
  211. }
  212. void VisualServerScene::SpatialPartitioningScene_BVH::set_unpair_callback(UnpairCallback p_callback, void *p_userdata) {
  213. _bvh.set_unpair_callback(p_callback, p_userdata);
  214. }
  215. ///////////////////////
  216. VisualServerScene::SpatialPartitionID VisualServerScene::SpatialPartitioningScene_Octree::create(Instance *p_userdata, const AABB &p_aabb, int p_subindex, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) {
  217. return _octree.create(p_userdata, p_aabb, p_subindex, p_pairable, p_pairable_type, p_pairable_mask);
  218. }
  219. void VisualServerScene::SpatialPartitioningScene_Octree::erase(SpatialPartitionID p_handle) {
  220. _octree.erase(p_handle);
  221. }
  222. void VisualServerScene::SpatialPartitioningScene_Octree::move(SpatialPartitionID p_handle, const AABB &p_aabb) {
  223. _octree.move(p_handle, p_aabb);
  224. }
  225. void VisualServerScene::SpatialPartitioningScene_Octree::set_pairable(Instance *p_instance, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) {
  226. SpatialPartitionID handle = p_instance->spatial_partition_id;
  227. _octree.set_pairable(handle, p_pairable, p_pairable_type, p_pairable_mask);
  228. }
  229. int VisualServerScene::SpatialPartitioningScene_Octree::cull_convex(const Vector<Plane> &p_convex, Instance **p_result_array, int p_result_max, uint32_t p_mask) {
  230. return _octree.cull_convex(p_convex, p_result_array, p_result_max, p_mask);
  231. }
  232. int VisualServerScene::SpatialPartitioningScene_Octree::cull_aabb(const AABB &p_aabb, Instance **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  233. return _octree.cull_aabb(p_aabb, p_result_array, p_result_max, p_subindex_array, p_mask);
  234. }
  235. int VisualServerScene::SpatialPartitioningScene_Octree::cull_segment(const Vector3 &p_from, const Vector3 &p_to, Instance **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
  236. return _octree.cull_segment(p_from, p_to, p_result_array, p_result_max, p_subindex_array, p_mask);
  237. }
  238. void VisualServerScene::SpatialPartitioningScene_Octree::set_pair_callback(PairCallback p_callback, void *p_userdata) {
  239. _octree.set_pair_callback(p_callback, p_userdata);
  240. }
  241. void VisualServerScene::SpatialPartitioningScene_Octree::set_unpair_callback(UnpairCallback p_callback, void *p_userdata) {
  242. _octree.set_unpair_callback(p_callback, p_userdata);
  243. }
  244. void VisualServerScene::SpatialPartitioningScene_Octree::set_balance(float p_balance) {
  245. _octree.set_balance(p_balance);
  246. }
  247. /* SCENARIO API */
  248. VisualServerScene::Scenario::Scenario() {
  249. debug = VS::SCENARIO_DEBUG_DISABLED;
  250. bool use_bvh_or_octree = GLOBAL_GET("rendering/quality/spatial_partitioning/use_bvh");
  251. if (use_bvh_or_octree) {
  252. sps = memnew(SpatialPartitioningScene_BVH);
  253. } else {
  254. sps = memnew(SpatialPartitioningScene_Octree);
  255. }
  256. }
  257. void *VisualServerScene::_instance_pair(void *p_self, SpatialPartitionID, Instance *p_A, int, SpatialPartitionID, Instance *p_B, int) {
  258. //VisualServerScene *self = (VisualServerScene*)p_self;
  259. Instance *A = p_A;
  260. Instance *B = p_B;
  261. //instance indices are designed so greater always contains lesser
  262. if (A->base_type > B->base_type) {
  263. SWAP(A, B); //lesser always first
  264. }
  265. if (B->base_type == VS::INSTANCE_LIGHT && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  266. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  267. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  268. InstanceLightData::PairInfo pinfo;
  269. pinfo.geometry = A;
  270. pinfo.L = geom->lighting.push_back(B);
  271. List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);
  272. if (geom->can_cast_shadows) {
  273. light->shadow_dirty = true;
  274. }
  275. geom->lighting_dirty = true;
  276. return E; //this element should make freeing faster
  277. } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  278. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  279. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  280. InstanceReflectionProbeData::PairInfo pinfo;
  281. pinfo.geometry = A;
  282. pinfo.L = geom->reflection_probes.push_back(B);
  283. List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo);
  284. geom->reflection_dirty = true;
  285. return E; //this element should make freeing faster
  286. } else if (B->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  287. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
  288. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  289. InstanceLightmapCaptureData::PairInfo pinfo;
  290. pinfo.geometry = A;
  291. pinfo.L = geom->lightmap_captures.push_back(B);
  292. List<InstanceLightmapCaptureData::PairInfo>::Element *E = lightmap_capture->geometries.push_back(pinfo);
  293. ((VisualServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
  294. return E; //this element should make freeing faster
  295. } else if (B->base_type == VS::INSTANCE_GI_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  296. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  297. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  298. InstanceGIProbeData::PairInfo pinfo;
  299. pinfo.geometry = A;
  300. pinfo.L = geom->gi_probes.push_back(B);
  301. List<InstanceGIProbeData::PairInfo>::Element *E = gi_probe->geometries.push_back(pinfo);
  302. geom->gi_probes_dirty = true;
  303. return E; //this element should make freeing faster
  304. } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
  305. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  306. return gi_probe->lights.insert(A);
  307. }
  308. return nullptr;
  309. }
  310. void VisualServerScene::_instance_unpair(void *p_self, SpatialPartitionID, Instance *p_A, int, SpatialPartitionID, Instance *p_B, int, void *udata) {
  311. //VisualServerScene *self = (VisualServerScene*)p_self;
  312. Instance *A = p_A;
  313. Instance *B = p_B;
  314. //instance indices are designed so greater always contains lesser
  315. if (A->base_type > B->base_type) {
  316. SWAP(A, B); //lesser always first
  317. }
  318. if (B->base_type == VS::INSTANCE_LIGHT && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  319. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  320. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  321. List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata);
  322. geom->lighting.erase(E->get().L);
  323. light->geometries.erase(E);
  324. if (geom->can_cast_shadows) {
  325. light->shadow_dirty = true;
  326. }
  327. geom->lighting_dirty = true;
  328. } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  329. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  330. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  331. List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata);
  332. geom->reflection_probes.erase(E->get().L);
  333. reflection_probe->geometries.erase(E);
  334. geom->reflection_dirty = true;
  335. } else if (B->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  336. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
  337. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  338. List<InstanceLightmapCaptureData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightmapCaptureData::PairInfo>::Element *>(udata);
  339. geom->lightmap_captures.erase(E->get().L);
  340. lightmap_capture->geometries.erase(E);
  341. ((VisualServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
  342. } else if (B->base_type == VS::INSTANCE_GI_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  343. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  344. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  345. List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata);
  346. geom->gi_probes.erase(E->get().L);
  347. gi_probe->geometries.erase(E);
  348. geom->gi_probes_dirty = true;
  349. } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
  350. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  351. Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata);
  352. gi_probe->lights.erase(E);
  353. }
  354. }
  355. RID VisualServerScene::scenario_create() {
  356. Scenario *scenario = memnew(Scenario);
  357. ERR_FAIL_COND_V(!scenario, RID());
  358. RID scenario_rid = scenario_owner.make_rid(scenario);
  359. scenario->self = scenario_rid;
  360. scenario->sps->set_balance(GLOBAL_GET("rendering/quality/spatial_partitioning/render_tree_balance"));
  361. scenario->sps->set_pair_callback(_instance_pair, this);
  362. scenario->sps->set_unpair_callback(_instance_unpair, this);
  363. scenario->reflection_probe_shadow_atlas = VSG::scene_render->shadow_atlas_create();
  364. VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
  365. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
  366. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
  367. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
  368. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
  369. scenario->reflection_atlas = VSG::scene_render->reflection_atlas_create();
  370. return scenario_rid;
  371. }
  372. void VisualServerScene::set_physics_interpolation_enabled(bool p_enabled) {
  373. _interpolation_data.interpolation_enabled = p_enabled;
  374. }
  375. void VisualServerScene::tick() {
  376. if (_interpolation_data.interpolation_enabled) {
  377. update_interpolation_tick(true);
  378. }
  379. }
  380. void VisualServerScene::pre_draw(bool p_will_draw) {
  381. // even when running and not drawing scenes, we still need to clear intermediate per frame
  382. // interpolation data .. hence the p_will_draw flag (so we can reduce the processing if the frame
  383. // will not be drawn)
  384. if (_interpolation_data.interpolation_enabled) {
  385. update_interpolation_frame(p_will_draw);
  386. }
  387. }
  388. void VisualServerScene::scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode) {
  389. Scenario *scenario = scenario_owner.get(p_scenario);
  390. ERR_FAIL_COND(!scenario);
  391. scenario->debug = p_debug_mode;
  392. }
  393. void VisualServerScene::scenario_set_environment(RID p_scenario, RID p_environment) {
  394. Scenario *scenario = scenario_owner.get(p_scenario);
  395. ERR_FAIL_COND(!scenario);
  396. scenario->environment = p_environment;
  397. }
  398. void VisualServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
  399. Scenario *scenario = scenario_owner.get(p_scenario);
  400. ERR_FAIL_COND(!scenario);
  401. scenario->fallback_environment = p_environment;
  402. }
  403. void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv) {
  404. Scenario *scenario = scenario_owner.get(p_scenario);
  405. ERR_FAIL_COND(!scenario);
  406. VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_size);
  407. VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas, p_subdiv);
  408. }
  409. /* INSTANCING API */
  410. void VisualServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials) {
  411. if (p_update_aabb) {
  412. p_instance->update_aabb = true;
  413. }
  414. if (p_update_materials) {
  415. p_instance->update_materials = true;
  416. }
  417. if (p_instance->update_item.in_list()) {
  418. return;
  419. }
  420. _instance_update_list.add(&p_instance->update_item);
  421. }
  422. RID VisualServerScene::instance_create() {
  423. Instance *instance = memnew(Instance);
  424. ERR_FAIL_COND_V(!instance, RID());
  425. RID instance_rid = instance_owner.make_rid(instance);
  426. instance->self = instance_rid;
  427. return instance_rid;
  428. }
  429. void VisualServerScene::instance_set_base(RID p_instance, RID p_base) {
  430. Instance *instance = instance_owner.get(p_instance);
  431. ERR_FAIL_COND(!instance);
  432. Scenario *scenario = instance->scenario;
  433. if (instance->base_type != VS::INSTANCE_NONE) {
  434. //free anything related to that base
  435. VSG::storage->instance_remove_dependency(instance->base, instance);
  436. if (instance->base_type == VS::INSTANCE_GI_PROBE) {
  437. //if gi probe is baking, wait until done baking, else race condition may happen when removing it
  438. //from octree
  439. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  440. //make sure probes are done baking
  441. while (!probe_bake_list.empty()) {
  442. OS::get_singleton()->delay_usec(1);
  443. }
  444. //make sure this one is done baking
  445. while (gi_probe->dynamic.updating_stage == GI_UPDATE_STAGE_LIGHTING) {
  446. //wait until bake is done if it's baking
  447. OS::get_singleton()->delay_usec(1);
  448. }
  449. }
  450. if (scenario && instance->spatial_partition_id) {
  451. scenario->sps->erase(instance->spatial_partition_id);
  452. instance->spatial_partition_id = 0;
  453. }
  454. switch (instance->base_type) {
  455. case VS::INSTANCE_LIGHT: {
  456. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  457. if (instance->scenario && light->D) {
  458. instance->scenario->directional_lights.erase(light->D);
  459. light->D = nullptr;
  460. }
  461. VSG::scene_render->free(light->instance);
  462. } break;
  463. case VS::INSTANCE_REFLECTION_PROBE: {
  464. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  465. VSG::scene_render->free(reflection_probe->instance);
  466. if (reflection_probe->update_list.in_list()) {
  467. reflection_probe_render_list.remove(&reflection_probe->update_list);
  468. }
  469. } break;
  470. case VS::INSTANCE_LIGHTMAP_CAPTURE: {
  471. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(instance->base_data);
  472. //erase dependencies, since no longer a lightmap
  473. while (lightmap_capture->users.front()) {
  474. instance_set_use_lightmap(lightmap_capture->users.front()->get()->self, RID(), RID(), -1, Rect2(0, 0, 1, 1));
  475. }
  476. } break;
  477. case VS::INSTANCE_GI_PROBE: {
  478. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  479. if (gi_probe->update_element.in_list()) {
  480. gi_probe_update_list.remove(&gi_probe->update_element);
  481. }
  482. if (gi_probe->dynamic.probe_data.is_valid()) {
  483. VSG::storage->free(gi_probe->dynamic.probe_data);
  484. }
  485. if (instance->lightmap_capture) {
  486. Instance *capture = (Instance *)instance->lightmap_capture;
  487. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(capture->base_data);
  488. lightmap_capture->users.erase(instance);
  489. instance->lightmap_capture = nullptr;
  490. instance->lightmap = RID();
  491. }
  492. VSG::scene_render->free(gi_probe->probe_instance);
  493. } break;
  494. default: {
  495. }
  496. }
  497. if (instance->base_data) {
  498. memdelete(instance->base_data);
  499. instance->base_data = nullptr;
  500. }
  501. instance->blend_values = PoolRealArray();
  502. for (int i = 0; i < instance->materials.size(); i++) {
  503. if (instance->materials[i].is_valid()) {
  504. VSG::storage->material_remove_instance_owner(instance->materials[i], instance);
  505. }
  506. }
  507. instance->materials.clear();
  508. }
  509. instance->base_type = VS::INSTANCE_NONE;
  510. instance->base = RID();
  511. if (p_base.is_valid()) {
  512. instance->base_type = VSG::storage->get_base_type(p_base);
  513. ERR_FAIL_COND(instance->base_type == VS::INSTANCE_NONE);
  514. switch (instance->base_type) {
  515. case VS::INSTANCE_LIGHT: {
  516. InstanceLightData *light = memnew(InstanceLightData);
  517. if (scenario && VSG::storage->light_get_type(p_base) == VS::LIGHT_DIRECTIONAL) {
  518. light->D = scenario->directional_lights.push_back(instance);
  519. }
  520. light->instance = VSG::scene_render->light_instance_create(p_base);
  521. instance->base_data = light;
  522. } break;
  523. case VS::INSTANCE_MESH:
  524. case VS::INSTANCE_MULTIMESH:
  525. case VS::INSTANCE_IMMEDIATE:
  526. case VS::INSTANCE_PARTICLES: {
  527. InstanceGeometryData *geom = memnew(InstanceGeometryData);
  528. instance->base_data = geom;
  529. if (instance->base_type == VS::INSTANCE_MESH) {
  530. instance->blend_values.resize(VSG::storage->mesh_get_blend_shape_count(p_base));
  531. }
  532. } break;
  533. case VS::INSTANCE_REFLECTION_PROBE: {
  534. InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
  535. reflection_probe->owner = instance;
  536. instance->base_data = reflection_probe;
  537. reflection_probe->instance = VSG::scene_render->reflection_probe_instance_create(p_base);
  538. } break;
  539. case VS::INSTANCE_LIGHTMAP_CAPTURE: {
  540. InstanceLightmapCaptureData *lightmap_capture = memnew(InstanceLightmapCaptureData);
  541. instance->base_data = lightmap_capture;
  542. //lightmap_capture->instance = VSG::scene_render->lightmap_capture_instance_create(p_base);
  543. } break;
  544. case VS::INSTANCE_GI_PROBE: {
  545. InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
  546. instance->base_data = gi_probe;
  547. gi_probe->owner = instance;
  548. if (scenario && !gi_probe->update_element.in_list()) {
  549. gi_probe_update_list.add(&gi_probe->update_element);
  550. }
  551. gi_probe->probe_instance = VSG::scene_render->gi_probe_instance_create();
  552. } break;
  553. default: {
  554. }
  555. }
  556. VSG::storage->instance_add_dependency(p_base, instance);
  557. instance->base = p_base;
  558. if (scenario) {
  559. _instance_queue_update(instance, true, true);
  560. }
  561. }
  562. }
  563. void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
  564. Instance *instance = instance_owner.get(p_instance);
  565. ERR_FAIL_COND(!instance);
  566. if (instance->scenario) {
  567. instance->scenario->instances.remove(&instance->scenario_item);
  568. if (instance->spatial_partition_id) {
  569. instance->scenario->sps->erase(instance->spatial_partition_id);
  570. instance->spatial_partition_id = 0;
  571. }
  572. // handle occlusion changes
  573. if (instance->occlusion_handle) {
  574. _instance_destroy_occlusion_rep(instance);
  575. }
  576. // remove any interpolation data associated with the instance in this scenario
  577. _interpolation_data.notify_free_instance(p_instance, *instance);
  578. switch (instance->base_type) {
  579. case VS::INSTANCE_LIGHT: {
  580. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  581. if (light->D) {
  582. instance->scenario->directional_lights.erase(light->D);
  583. light->D = nullptr;
  584. }
  585. } break;
  586. case VS::INSTANCE_REFLECTION_PROBE: {
  587. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  588. VSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
  589. } break;
  590. case VS::INSTANCE_GI_PROBE: {
  591. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  592. if (gi_probe->update_element.in_list()) {
  593. gi_probe_update_list.remove(&gi_probe->update_element);
  594. }
  595. } break;
  596. default: {
  597. }
  598. }
  599. instance->scenario = nullptr;
  600. }
  601. if (p_scenario.is_valid()) {
  602. Scenario *scenario = scenario_owner.get(p_scenario);
  603. ERR_FAIL_COND(!scenario);
  604. instance->scenario = scenario;
  605. scenario->instances.add(&instance->scenario_item);
  606. switch (instance->base_type) {
  607. case VS::INSTANCE_LIGHT: {
  608. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  609. if (VSG::storage->light_get_type(instance->base) == VS::LIGHT_DIRECTIONAL) {
  610. light->D = scenario->directional_lights.push_back(instance);
  611. }
  612. } break;
  613. case VS::INSTANCE_GI_PROBE: {
  614. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  615. if (!gi_probe->update_element.in_list()) {
  616. gi_probe_update_list.add(&gi_probe->update_element);
  617. }
  618. } break;
  619. default: {
  620. }
  621. }
  622. // handle occlusion changes if necessary
  623. _instance_create_occlusion_rep(instance);
  624. _instance_queue_update(instance, true, true);
  625. }
  626. }
  627. void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
  628. Instance *instance = instance_owner.get(p_instance);
  629. ERR_FAIL_COND(!instance);
  630. instance->layer_mask = p_mask;
  631. }
  632. void VisualServerScene::instance_set_pivot_data(RID p_instance, float p_sorting_offset, bool p_use_aabb_center) {
  633. Instance *instance = instance_owner.get(p_instance);
  634. ERR_FAIL_COND(!instance);
  635. instance->sorting_offset = p_sorting_offset;
  636. instance->use_aabb_center = p_use_aabb_center;
  637. }
  638. void VisualServerScene::instance_reset_physics_interpolation(RID p_instance) {
  639. Instance *instance = instance_owner.get(p_instance);
  640. ERR_FAIL_COND(!instance);
  641. if (_interpolation_data.interpolation_enabled && instance->interpolated) {
  642. _interpolation_data.instance_teleport_list.push_back(p_instance);
  643. }
  644. }
  645. void VisualServerScene::instance_set_interpolated(RID p_instance, bool p_interpolated) {
  646. Instance *instance = instance_owner.get(p_instance);
  647. ERR_FAIL_COND(!instance);
  648. instance->interpolated = p_interpolated;
  649. }
  650. void VisualServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) {
  651. Instance *instance = instance_owner.get(p_instance);
  652. ERR_FAIL_COND(!instance);
  653. if (!(_interpolation_data.interpolation_enabled && instance->interpolated) || !instance->scenario) {
  654. if (instance->transform == p_transform) {
  655. return; //must be checked to avoid worst evil
  656. }
  657. #ifdef DEBUG_ENABLED
  658. for (int i = 0; i < 4; i++) {
  659. const Vector3 &v = i < 3 ? p_transform.basis.elements[i] : p_transform.origin;
  660. ERR_FAIL_COND(Math::is_inf(v.x));
  661. ERR_FAIL_COND(Math::is_nan(v.x));
  662. ERR_FAIL_COND(Math::is_inf(v.y));
  663. ERR_FAIL_COND(Math::is_nan(v.y));
  664. ERR_FAIL_COND(Math::is_inf(v.z));
  665. ERR_FAIL_COND(Math::is_nan(v.z));
  666. }
  667. #endif
  668. instance->transform = p_transform;
  669. _instance_queue_update(instance, true);
  670. #if defined(DEBUG_ENABLED) && defined(TOOLS_ENABLED)
  671. if ((_interpolation_data.interpolation_enabled && !instance->interpolated) && (Engine::get_singleton()->is_in_physics_frame())) {
  672. static int32_t warn_count = 0;
  673. warn_count++;
  674. if (((warn_count % 2048) == 0) && GLOBAL_GET("debug/settings/physics_interpolation/enable_warnings")) {
  675. String node_name;
  676. ObjectID id = instance->object_id;
  677. if (id != 0) {
  678. if (ObjectDB::get_instance(id)) {
  679. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(id));
  680. if (node && node->is_inside_tree()) {
  681. node_name = "\"" + String(node->get_path()) + "\"";
  682. } else {
  683. node_name = "\"unknown\"";
  684. }
  685. }
  686. }
  687. WARN_PRINT("[Physics interpolation] Non-interpolated Instance is being triggered from physics process, this might lead to issues: " + node_name + " (possibly benign).");
  688. }
  689. }
  690. #endif
  691. return;
  692. }
  693. float new_checksum = TransformInterpolator::checksum_transform(p_transform);
  694. bool checksums_match = (instance->transform_checksum_curr == new_checksum) && (instance->transform_checksum_prev == new_checksum);
  695. // we can't entirely reject no changes because we need the interpolation
  696. // system to keep on stewing
  697. // Optimized check. First checks the checksums. If they pass it does the slow check at the end.
  698. // Alternatively we can do this non-optimized and ignore the checksum...
  699. // if no change
  700. if (checksums_match && (instance->transform_curr == p_transform) && (instance->transform_prev == p_transform)) {
  701. return;
  702. }
  703. #ifdef DEBUG_ENABLED
  704. for (int i = 0; i < 4; i++) {
  705. const Vector3 &v = i < 3 ? p_transform.basis.elements[i] : p_transform.origin;
  706. ERR_FAIL_COND(Math::is_inf(v.x));
  707. ERR_FAIL_COND(Math::is_nan(v.x));
  708. ERR_FAIL_COND(Math::is_inf(v.y));
  709. ERR_FAIL_COND(Math::is_nan(v.y));
  710. ERR_FAIL_COND(Math::is_inf(v.z));
  711. ERR_FAIL_COND(Math::is_nan(v.z));
  712. }
  713. #endif
  714. instance->transform_curr = p_transform;
  715. // keep checksums up to date
  716. instance->transform_checksum_curr = new_checksum;
  717. if (!instance->on_interpolate_transform_list) {
  718. _interpolation_data.instance_transform_update_list_curr->push_back(p_instance);
  719. instance->on_interpolate_transform_list = true;
  720. } else {
  721. DEV_ASSERT(_interpolation_data.instance_transform_update_list_curr->size());
  722. }
  723. // If the instance is invisible, then we are simply updating the data flow, there is no need to calculate the interpolated
  724. // transform or anything else.
  725. // Ideally we would not even call the VisualServer::set_transform() when invisible but that would entail having logic
  726. // to keep track of the previous transform on the SceneTree side. The "early out" below is less efficient but a lot cleaner codewise.
  727. if (!instance->visible) {
  728. return;
  729. }
  730. // decide on the interpolation method .. slerp if possible
  731. instance->interpolation_method = TransformInterpolator::find_method(instance->transform_prev.basis, instance->transform_curr.basis);
  732. if (!instance->on_interpolate_list) {
  733. _interpolation_data.instance_interpolate_update_list.push_back(p_instance);
  734. instance->on_interpolate_list = true;
  735. } else {
  736. DEV_ASSERT(_interpolation_data.instance_interpolate_update_list.size());
  737. }
  738. _instance_queue_update(instance, true);
  739. #if defined(DEBUG_ENABLED) && defined(TOOLS_ENABLED)
  740. if (!Engine::get_singleton()->is_in_physics_frame()) {
  741. static int32_t warn_count = 0;
  742. warn_count++;
  743. if (((warn_count % 2048) == 0) && GLOBAL_GET("debug/settings/physics_interpolation/enable_warnings")) {
  744. String node_name;
  745. ObjectID id = instance->object_id;
  746. if (id != 0) {
  747. if (ObjectDB::get_instance(id)) {
  748. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(id));
  749. if (node && node->is_inside_tree()) {
  750. node_name = "\"" + String(node->get_path()) + "\"";
  751. } else {
  752. node_name = "\"unknown\"";
  753. }
  754. }
  755. }
  756. WARN_PRINT("[Physics interpolation] Instance interpolation is being triggered from outside physics process, this might lead to issues: " + node_name + " (possibly benign).");
  757. }
  758. }
  759. #endif
  760. }
  761. void VisualServerScene::InterpolationData::notify_free_camera(RID p_rid, Camera &r_camera) {
  762. r_camera.on_interpolate_transform_list = false;
  763. if (!interpolation_enabled) {
  764. return;
  765. }
  766. // if the camera was on any of the lists, remove
  767. camera_transform_update_list_curr->erase_multiple_unordered(p_rid);
  768. camera_transform_update_list_prev->erase_multiple_unordered(p_rid);
  769. camera_teleport_list.erase_multiple_unordered(p_rid);
  770. }
  771. void VisualServerScene::InterpolationData::notify_free_instance(RID p_rid, Instance &r_instance) {
  772. r_instance.on_interpolate_list = false;
  773. r_instance.on_interpolate_transform_list = false;
  774. if (!interpolation_enabled) {
  775. return;
  776. }
  777. // if the instance was on any of the lists, remove
  778. instance_interpolate_update_list.erase_multiple_unordered(p_rid);
  779. instance_transform_update_list_curr->erase_multiple_unordered(p_rid);
  780. instance_transform_update_list_prev->erase_multiple_unordered(p_rid);
  781. instance_teleport_list.erase_multiple_unordered(p_rid);
  782. }
  783. void VisualServerScene::update_interpolation_tick(bool p_process) {
  784. // update interpolation in storage
  785. VSG::storage->update_interpolation_tick(p_process);
  786. // detect any that were on the previous transform list that are no longer active,
  787. // we should remove them from the interpolate list
  788. for (unsigned int n = 0; n < _interpolation_data.instance_transform_update_list_prev->size(); n++) {
  789. const RID &rid = (*_interpolation_data.instance_transform_update_list_prev)[n];
  790. Instance *instance = instance_owner.getornull(rid);
  791. bool active = true;
  792. // no longer active? (either the instance deleted or no longer being transformed)
  793. if (instance && !instance->on_interpolate_transform_list) {
  794. active = false;
  795. instance->on_interpolate_list = false;
  796. // make sure the most recent transform is set
  797. instance->transform = instance->transform_curr;
  798. // and that both prev and current are the same, just in case of any interpolations
  799. instance->transform_prev = instance->transform_curr;
  800. // make sure are updated one more time to ensure the AABBs are correct
  801. _instance_queue_update(instance, true);
  802. }
  803. if (!instance) {
  804. active = false;
  805. }
  806. if (!active) {
  807. _interpolation_data.instance_interpolate_update_list.erase(rid);
  808. }
  809. }
  810. // and now for any in the transform list (being actively interpolated), keep the previous transform
  811. // value up to date ready for the next tick
  812. if (p_process) {
  813. for (unsigned int n = 0; n < _interpolation_data.instance_transform_update_list_curr->size(); n++) {
  814. const RID &rid = (*_interpolation_data.instance_transform_update_list_curr)[n];
  815. Instance *instance = instance_owner.getornull(rid);
  816. if (instance) {
  817. instance->transform_prev = instance->transform_curr;
  818. instance->transform_checksum_prev = instance->transform_checksum_curr;
  819. instance->on_interpolate_transform_list = false;
  820. }
  821. }
  822. }
  823. // we maintain a mirror list for the transform updates, so we can detect when an instance
  824. // is no longer being transformed, and remove it from the interpolate list
  825. SWAP(_interpolation_data.instance_transform_update_list_curr, _interpolation_data.instance_transform_update_list_prev);
  826. // prepare for the next iteration
  827. _interpolation_data.instance_transform_update_list_curr->clear();
  828. // CAMERAS
  829. // detect any that were on the previous transform list that are no longer active,
  830. for (unsigned int n = 0; n < _interpolation_data.camera_transform_update_list_prev->size(); n++) {
  831. const RID &rid = (*_interpolation_data.camera_transform_update_list_prev)[n];
  832. Camera *camera = camera_owner.getornull(rid);
  833. // no longer active? (either the instance deleted or no longer being transformed)
  834. if (camera && !camera->on_interpolate_transform_list) {
  835. camera->transform = camera->transform_prev;
  836. }
  837. }
  838. // cameras , swap any current with previous
  839. for (unsigned int n = 0; n < _interpolation_data.camera_transform_update_list_curr->size(); n++) {
  840. const RID &rid = (*_interpolation_data.camera_transform_update_list_curr)[n];
  841. Camera *camera = camera_owner.getornull(rid);
  842. if (camera) {
  843. camera->transform_prev = camera->transform;
  844. camera->on_interpolate_transform_list = false;
  845. }
  846. }
  847. // we maintain a mirror list for the transform updates, so we can detect when an instance
  848. // is no longer being transformed, and remove it from the interpolate list
  849. SWAP(_interpolation_data.camera_transform_update_list_curr, _interpolation_data.camera_transform_update_list_prev);
  850. // prepare for the next iteration
  851. _interpolation_data.camera_transform_update_list_curr->clear();
  852. }
  853. void VisualServerScene::update_interpolation_frame(bool p_process) {
  854. // update interpolation in storage
  855. VSG::storage->update_interpolation_frame(p_process);
  856. // teleported instances
  857. for (unsigned int n = 0; n < _interpolation_data.instance_teleport_list.size(); n++) {
  858. const RID &rid = _interpolation_data.instance_teleport_list[n];
  859. Instance *instance = instance_owner.getornull(rid);
  860. if (instance) {
  861. instance->transform_prev = instance->transform_curr;
  862. instance->transform_checksum_prev = instance->transform_checksum_curr;
  863. }
  864. }
  865. _interpolation_data.instance_teleport_list.clear();
  866. // camera teleports
  867. for (unsigned int n = 0; n < _interpolation_data.camera_teleport_list.size(); n++) {
  868. const RID &rid = _interpolation_data.camera_teleport_list[n];
  869. Camera *camera = camera_owner.getornull(rid);
  870. if (camera) {
  871. camera->transform_prev = camera->transform;
  872. }
  873. }
  874. _interpolation_data.camera_teleport_list.clear();
  875. if (p_process) {
  876. real_t f = Engine::get_singleton()->get_physics_interpolation_fraction();
  877. for (unsigned int i = 0; i < _interpolation_data.instance_interpolate_update_list.size(); i++) {
  878. const RID &rid = _interpolation_data.instance_interpolate_update_list[i];
  879. Instance *instance = instance_owner.getornull(rid);
  880. if (instance) {
  881. TransformInterpolator::interpolate_transform_via_method(instance->transform_prev, instance->transform_curr, instance->transform, f, instance->interpolation_method);
  882. // make sure AABBs are constantly up to date through the interpolation
  883. _instance_queue_update(instance, true);
  884. }
  885. } // for n
  886. }
  887. }
  888. void VisualServerScene::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {
  889. Instance *instance = instance_owner.get(p_instance);
  890. ERR_FAIL_COND(!instance);
  891. instance->object_id = p_id;
  892. }
  893. void VisualServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
  894. Instance *instance = instance_owner.get(p_instance);
  895. ERR_FAIL_COND(!instance);
  896. if (instance->update_item.in_list()) {
  897. _update_dirty_instance(instance);
  898. }
  899. ERR_FAIL_INDEX(p_shape, instance->blend_values.size());
  900. instance->blend_values.write().ptr()[p_shape] = p_weight;
  901. VSG::storage->mesh_set_blend_shape_values(instance->base, instance->blend_values);
  902. }
  903. void VisualServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {
  904. Instance *instance = instance_owner.get(p_instance);
  905. ERR_FAIL_COND(!instance);
  906. if (instance->base_type == VS::INSTANCE_MESH) {
  907. //may not have been updated yet
  908. instance->materials.resize(VSG::storage->mesh_get_surface_count(instance->base));
  909. }
  910. ERR_FAIL_INDEX(p_surface, instance->materials.size());
  911. if (instance->materials[p_surface].is_valid()) {
  912. VSG::storage->material_remove_instance_owner(instance->materials[p_surface], instance);
  913. }
  914. instance->materials.write[p_surface] = p_material;
  915. instance->base_changed(false, true);
  916. if (instance->materials[p_surface].is_valid()) {
  917. VSG::storage->material_add_instance_owner(instance->materials[p_surface], instance);
  918. }
  919. }
  920. void VisualServerScene::instance_set_visible(RID p_instance, bool p_visible) {
  921. Instance *instance = instance_owner.get(p_instance);
  922. ERR_FAIL_COND(!instance);
  923. if (instance->visible == p_visible) {
  924. return;
  925. }
  926. instance->visible = p_visible;
  927. // Special case for physics interpolation, we want to ensure the interpolated data is up to date
  928. if (_interpolation_data.interpolation_enabled && p_visible && instance->interpolated && instance->scenario && !instance->on_interpolate_list) {
  929. // Do all the extra work we normally do on instance_set_transform(), because this is optimized out for hidden instances.
  930. // This prevents a glitch of stale interpolation transform data when unhiding before the next physics tick.
  931. instance->interpolation_method = TransformInterpolator::find_method(instance->transform_prev.basis, instance->transform_curr.basis);
  932. _interpolation_data.instance_interpolate_update_list.push_back(p_instance);
  933. instance->on_interpolate_list = true;
  934. _instance_queue_update(instance, true);
  935. // We must also place on the transform update list for a tick, so the system
  936. // can auto-detect if the instance is no longer moving, and remove from the interpolate lists again.
  937. // If this step is ignored, an unmoving instance could remain on the interpolate lists indefinitely
  938. // (or rather until the object is deleted) and cause unnecessary updates and drawcalls.
  939. if (!instance->on_interpolate_transform_list) {
  940. _interpolation_data.instance_transform_update_list_curr->push_back(p_instance);
  941. instance->on_interpolate_transform_list = true;
  942. }
  943. }
  944. // give the opportunity for the spatial partitioning scene to use a special implementation of visibility
  945. // for efficiency (supported in BVH but not octree)
  946. // slightly bug prone optimization here - we want to avoid doing a collision check twice
  947. // once when activating, and once when calling set_pairable. We do this by deferring the collision check.
  948. // However, in some cases (notably meshes), set_pairable never gets called. So we want to catch this case
  949. // and force a collision check (see later in this function).
  950. // This is only done in two stages to maintain compatibility with the octree.
  951. if (instance->spatial_partition_id && instance->scenario) {
  952. if (p_visible) {
  953. instance->scenario->sps->activate(instance->spatial_partition_id, instance->transformed_aabb);
  954. } else {
  955. instance->scenario->sps->deactivate(instance->spatial_partition_id);
  956. }
  957. }
  958. // when showing or hiding geometry, lights must be kept up to date to show / hide shadows
  959. if ((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  960. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  961. if (geom->can_cast_shadows) {
  962. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  963. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  964. light->shadow_dirty = true;
  965. }
  966. }
  967. }
  968. switch (instance->base_type) {
  969. case VS::INSTANCE_LIGHT: {
  970. if (VSG::storage->light_get_type(instance->base) != VS::LIGHT_DIRECTIONAL && instance->spatial_partition_id && instance->scenario) {
  971. instance->scenario->sps->set_pairable(instance, p_visible, 1 << VS::INSTANCE_LIGHT, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
  972. }
  973. } break;
  974. case VS::INSTANCE_REFLECTION_PROBE: {
  975. if (instance->spatial_partition_id && instance->scenario) {
  976. instance->scenario->sps->set_pairable(instance, p_visible, 1 << VS::INSTANCE_REFLECTION_PROBE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
  977. }
  978. } break;
  979. case VS::INSTANCE_LIGHTMAP_CAPTURE: {
  980. if (instance->spatial_partition_id && instance->scenario) {
  981. instance->scenario->sps->set_pairable(instance, p_visible, 1 << VS::INSTANCE_LIGHTMAP_CAPTURE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
  982. }
  983. } break;
  984. case VS::INSTANCE_GI_PROBE: {
  985. if (instance->spatial_partition_id && instance->scenario) {
  986. instance->scenario->sps->set_pairable(instance, p_visible, 1 << VS::INSTANCE_GI_PROBE, p_visible ? (VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT)) : 0);
  987. }
  988. } break;
  989. default: {
  990. // if we haven't called set_pairable, we STILL need to do a collision check
  991. // for activated items because we deferred it earlier in the call to activate.
  992. if (instance->spatial_partition_id && instance->scenario && p_visible) {
  993. instance->scenario->sps->force_collision_check(instance->spatial_partition_id);
  994. }
  995. }
  996. }
  997. }
  998. inline bool is_geometry_instance(VisualServer::InstanceType p_type) {
  999. return p_type == VS::INSTANCE_MESH || p_type == VS::INSTANCE_MULTIMESH || p_type == VS::INSTANCE_PARTICLES || p_type == VS::INSTANCE_IMMEDIATE;
  1000. }
  1001. void VisualServerScene::instance_set_use_lightmap(RID p_instance, RID p_lightmap_instance, RID p_lightmap, int p_lightmap_slice, const Rect2 &p_lightmap_uv_rect) {
  1002. Instance *instance = instance_owner.get(p_instance);
  1003. ERR_FAIL_COND(!instance);
  1004. instance->lightmap = RID();
  1005. instance->lightmap_slice = -1;
  1006. instance->lightmap_uv_rect = Rect2(0, 0, 1, 1);
  1007. instance->baked_light = false;
  1008. if (instance->lightmap_capture) {
  1009. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
  1010. lightmap_capture->users.erase(instance);
  1011. instance->lightmap_capture = nullptr;
  1012. }
  1013. if (p_lightmap_instance.is_valid()) {
  1014. Instance *lightmap_instance = instance_owner.get(p_lightmap_instance);
  1015. ERR_FAIL_COND(!lightmap_instance);
  1016. ERR_FAIL_COND(lightmap_instance->base_type != VS::INSTANCE_LIGHTMAP_CAPTURE);
  1017. instance->lightmap_capture = lightmap_instance;
  1018. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
  1019. lightmap_capture->users.insert(instance);
  1020. instance->lightmap = p_lightmap;
  1021. instance->lightmap_slice = p_lightmap_slice;
  1022. instance->lightmap_uv_rect = p_lightmap_uv_rect;
  1023. instance->baked_light = true;
  1024. }
  1025. }
  1026. void VisualServerScene::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
  1027. Instance *instance = instance_owner.get(p_instance);
  1028. ERR_FAIL_COND(!instance);
  1029. ERR_FAIL_COND(!is_geometry_instance(instance->base_type));
  1030. if (p_aabb != AABB()) {
  1031. // Set custom AABB
  1032. if (instance->custom_aabb == nullptr) {
  1033. instance->custom_aabb = memnew(AABB);
  1034. }
  1035. *instance->custom_aabb = p_aabb;
  1036. } else {
  1037. // Clear custom AABB
  1038. if (instance->custom_aabb != nullptr) {
  1039. memdelete(instance->custom_aabb);
  1040. instance->custom_aabb = nullptr;
  1041. }
  1042. }
  1043. if (instance->scenario) {
  1044. _instance_queue_update(instance, true, false);
  1045. }
  1046. }
  1047. void VisualServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
  1048. Instance *instance = instance_owner.get(p_instance);
  1049. ERR_FAIL_COND(!instance);
  1050. if (instance->skeleton == p_skeleton) {
  1051. return;
  1052. }
  1053. if (instance->skeleton.is_valid()) {
  1054. VSG::storage->instance_remove_skeleton(instance->skeleton, instance);
  1055. }
  1056. instance->skeleton = p_skeleton;
  1057. if (instance->skeleton.is_valid()) {
  1058. VSG::storage->instance_add_skeleton(instance->skeleton, instance);
  1059. }
  1060. _instance_queue_update(instance, true);
  1061. }
  1062. void VisualServerScene::instance_set_exterior(RID p_instance, bool p_enabled) {
  1063. }
  1064. void VisualServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
  1065. Instance *instance = instance_owner.get(p_instance);
  1066. ERR_FAIL_COND(!instance);
  1067. instance->extra_margin = p_margin;
  1068. _instance_queue_update(instance, true, false);
  1069. }
  1070. // Portals
  1071. void VisualServerScene::instance_set_portal_mode(RID p_instance, VisualServer::InstancePortalMode p_mode) {
  1072. Instance *instance = instance_owner.get(p_instance);
  1073. ERR_FAIL_COND(!instance);
  1074. // no change?
  1075. if (instance->portal_mode == p_mode) {
  1076. return;
  1077. }
  1078. // should this happen?
  1079. if (!instance->scenario) {
  1080. instance->portal_mode = p_mode;
  1081. return;
  1082. }
  1083. // destroy previous occlusion instance?
  1084. _instance_destroy_occlusion_rep(instance);
  1085. instance->portal_mode = p_mode;
  1086. _instance_create_occlusion_rep(instance);
  1087. }
  1088. void VisualServerScene::_instance_create_occlusion_rep(Instance *p_instance) {
  1089. ERR_FAIL_COND(!p_instance);
  1090. ERR_FAIL_COND(!p_instance->scenario);
  1091. switch (p_instance->portal_mode) {
  1092. default: {
  1093. p_instance->occlusion_handle = 0;
  1094. } break;
  1095. case VisualServer::InstancePortalMode::INSTANCE_PORTAL_MODE_ROAMING: {
  1096. p_instance->occlusion_handle = p_instance->scenario->_portal_renderer.instance_moving_create(p_instance, p_instance->self, false, p_instance->transformed_aabb);
  1097. } break;
  1098. case VisualServer::InstancePortalMode::INSTANCE_PORTAL_MODE_GLOBAL: {
  1099. p_instance->occlusion_handle = p_instance->scenario->_portal_renderer.instance_moving_create(p_instance, p_instance->self, true, p_instance->transformed_aabb);
  1100. } break;
  1101. }
  1102. }
  1103. void VisualServerScene::_instance_destroy_occlusion_rep(Instance *p_instance) {
  1104. ERR_FAIL_COND(!p_instance);
  1105. ERR_FAIL_COND(!p_instance->scenario);
  1106. // not an error, can occur
  1107. if (!p_instance->occlusion_handle) {
  1108. return;
  1109. }
  1110. p_instance->scenario->_portal_renderer.instance_moving_destroy(p_instance->occlusion_handle);
  1111. // unset
  1112. p_instance->occlusion_handle = 0;
  1113. }
  1114. void *VisualServerScene::_instance_get_from_rid(RID p_instance) {
  1115. Instance *instance = instance_owner.get(p_instance);
  1116. return instance;
  1117. }
  1118. bool VisualServerScene::_instance_get_transformed_aabb(RID p_instance, AABB &r_aabb) {
  1119. Instance *instance = instance_owner.get(p_instance);
  1120. ERR_FAIL_NULL_V(instance, false);
  1121. r_aabb = instance->transformed_aabb;
  1122. return true;
  1123. }
  1124. // the portal has to be associated with a scenario, this is assumed to be
  1125. // the same scenario as the portal node
  1126. RID VisualServerScene::portal_create() {
  1127. Portal *portal = memnew(Portal);
  1128. ERR_FAIL_COND_V(!portal, RID());
  1129. RID portal_rid = portal_owner.make_rid(portal);
  1130. return portal_rid;
  1131. }
  1132. // should not be called multiple times, different scenarios etc, but just in case, we will support this
  1133. void VisualServerScene::portal_set_scenario(RID p_portal, RID p_scenario) {
  1134. Portal *portal = portal_owner.getornull(p_portal);
  1135. ERR_FAIL_COND(!portal);
  1136. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1137. // noop?
  1138. if (portal->scenario == scenario) {
  1139. return;
  1140. }
  1141. // if the portal is in a scenario already, remove it
  1142. if (portal->scenario) {
  1143. portal->scenario->_portal_renderer.portal_destroy(portal->scenario_portal_id);
  1144. portal->scenario = nullptr;
  1145. portal->scenario_portal_id = 0;
  1146. }
  1147. // create when entering the world
  1148. if (scenario) {
  1149. portal->scenario = scenario;
  1150. // defer the actual creation to here
  1151. portal->scenario_portal_id = scenario->_portal_renderer.portal_create();
  1152. }
  1153. }
  1154. void VisualServerScene::portal_set_geometry(RID p_portal, const Vector<Vector3> &p_points, real_t p_margin) {
  1155. Portal *portal = portal_owner.getornull(p_portal);
  1156. ERR_FAIL_COND(!portal);
  1157. ERR_FAIL_COND(!portal->scenario);
  1158. portal->scenario->_portal_renderer.portal_set_geometry(portal->scenario_portal_id, p_points, p_margin);
  1159. }
  1160. void VisualServerScene::portal_link(RID p_portal, RID p_room_from, RID p_room_to, bool p_two_way) {
  1161. Portal *portal = portal_owner.getornull(p_portal);
  1162. ERR_FAIL_COND(!portal);
  1163. ERR_FAIL_COND(!portal->scenario);
  1164. Room *room_from = room_owner.getornull(p_room_from);
  1165. ERR_FAIL_COND(!room_from);
  1166. Room *room_to = room_owner.getornull(p_room_to);
  1167. ERR_FAIL_COND(!room_to);
  1168. portal->scenario->_portal_renderer.portal_link(portal->scenario_portal_id, room_from->scenario_room_id, room_to->scenario_room_id, p_two_way);
  1169. }
  1170. void VisualServerScene::portal_set_active(RID p_portal, bool p_active) {
  1171. Portal *portal = portal_owner.getornull(p_portal);
  1172. ERR_FAIL_COND(!portal);
  1173. ERR_FAIL_COND(!portal->scenario);
  1174. portal->scenario->_portal_renderer.portal_set_active(portal->scenario_portal_id, p_active);
  1175. }
  1176. RID VisualServerScene::ghost_create() {
  1177. Ghost *ci = memnew(Ghost);
  1178. ERR_FAIL_COND_V(!ci, RID());
  1179. RID ci_rid = ghost_owner.make_rid(ci);
  1180. return ci_rid;
  1181. }
  1182. void VisualServerScene::ghost_set_scenario(RID p_ghost, RID p_scenario, ObjectID p_id, const AABB &p_aabb) {
  1183. Ghost *ci = ghost_owner.getornull(p_ghost);
  1184. ERR_FAIL_COND(!ci);
  1185. ci->aabb = p_aabb;
  1186. ci->object_id = p_id;
  1187. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1188. // noop?
  1189. if (ci->scenario == scenario) {
  1190. return;
  1191. }
  1192. // if the portal is in a scenario already, remove it
  1193. if (ci->scenario) {
  1194. _ghost_destroy_occlusion_rep(ci);
  1195. ci->scenario = nullptr;
  1196. }
  1197. // create when entering the world
  1198. if (scenario) {
  1199. ci->scenario = scenario;
  1200. // defer the actual creation to here
  1201. _ghost_create_occlusion_rep(ci);
  1202. }
  1203. }
  1204. void VisualServerScene::ghost_update(RID p_ghost, const AABB &p_aabb) {
  1205. Ghost *ci = ghost_owner.getornull(p_ghost);
  1206. ERR_FAIL_COND(!ci);
  1207. ERR_FAIL_COND(!ci->scenario);
  1208. ci->aabb = p_aabb;
  1209. if (ci->rghost_handle) {
  1210. ci->scenario->_portal_renderer.rghost_update(ci->rghost_handle, p_aabb);
  1211. }
  1212. }
  1213. void VisualServerScene::_ghost_create_occlusion_rep(Ghost *p_ghost) {
  1214. ERR_FAIL_COND(!p_ghost);
  1215. ERR_FAIL_COND(!p_ghost->scenario);
  1216. if (!p_ghost->rghost_handle) {
  1217. p_ghost->rghost_handle = p_ghost->scenario->_portal_renderer.rghost_create(p_ghost->object_id, p_ghost->aabb);
  1218. }
  1219. }
  1220. void VisualServerScene::_ghost_destroy_occlusion_rep(Ghost *p_ghost) {
  1221. ERR_FAIL_COND(!p_ghost);
  1222. ERR_FAIL_COND(!p_ghost->scenario);
  1223. // not an error, can occur
  1224. if (!p_ghost->rghost_handle) {
  1225. return;
  1226. }
  1227. p_ghost->scenario->_portal_renderer.rghost_destroy(p_ghost->rghost_handle);
  1228. p_ghost->rghost_handle = 0;
  1229. }
  1230. RID VisualServerScene::roomgroup_create() {
  1231. RoomGroup *rg = memnew(RoomGroup);
  1232. ERR_FAIL_COND_V(!rg, RID());
  1233. RID roomgroup_rid = roomgroup_owner.make_rid(rg);
  1234. return roomgroup_rid;
  1235. }
  1236. void VisualServerScene::roomgroup_prepare(RID p_roomgroup, ObjectID p_roomgroup_object_id) {
  1237. RoomGroup *roomgroup = roomgroup_owner.getornull(p_roomgroup);
  1238. ERR_FAIL_COND(!roomgroup);
  1239. ERR_FAIL_COND(!roomgroup->scenario);
  1240. roomgroup->scenario->_portal_renderer.roomgroup_prepare(roomgroup->scenario_roomgroup_id, p_roomgroup_object_id);
  1241. }
  1242. void VisualServerScene::roomgroup_set_scenario(RID p_roomgroup, RID p_scenario) {
  1243. RoomGroup *rg = roomgroup_owner.getornull(p_roomgroup);
  1244. ERR_FAIL_COND(!rg);
  1245. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1246. // noop?
  1247. if (rg->scenario == scenario) {
  1248. return;
  1249. }
  1250. // if the portal is in a scenario already, remove it
  1251. if (rg->scenario) {
  1252. rg->scenario->_portal_renderer.roomgroup_destroy(rg->scenario_roomgroup_id);
  1253. rg->scenario = nullptr;
  1254. rg->scenario_roomgroup_id = 0;
  1255. }
  1256. // create when entering the world
  1257. if (scenario) {
  1258. rg->scenario = scenario;
  1259. // defer the actual creation to here
  1260. rg->scenario_roomgroup_id = scenario->_portal_renderer.roomgroup_create();
  1261. }
  1262. }
  1263. void VisualServerScene::roomgroup_add_room(RID p_roomgroup, RID p_room) {
  1264. RoomGroup *roomgroup = roomgroup_owner.getornull(p_roomgroup);
  1265. ERR_FAIL_COND(!roomgroup);
  1266. ERR_FAIL_COND(!roomgroup->scenario);
  1267. Room *room = room_owner.getornull(p_room);
  1268. ERR_FAIL_COND(!room);
  1269. ERR_FAIL_COND(!room->scenario);
  1270. ERR_FAIL_COND(roomgroup->scenario != room->scenario);
  1271. roomgroup->scenario->_portal_renderer.roomgroup_add_room(roomgroup->scenario_roomgroup_id, room->scenario_room_id);
  1272. }
  1273. // Occluders
  1274. RID VisualServerScene::occluder_instance_create() {
  1275. OccluderInstance *ro = memnew(OccluderInstance);
  1276. ERR_FAIL_COND_V(!ro, RID());
  1277. RID occluder_rid = occluder_instance_owner.make_rid(ro);
  1278. return occluder_rid;
  1279. }
  1280. void VisualServerScene::occluder_instance_link_resource(RID p_occluder_instance, RID p_occluder_resource) {
  1281. OccluderInstance *oi = occluder_instance_owner.getornull(p_occluder_instance);
  1282. ERR_FAIL_COND(!oi);
  1283. ERR_FAIL_COND(!oi->scenario);
  1284. OccluderResource *res = occluder_resource_owner.getornull(p_occluder_resource);
  1285. ERR_FAIL_COND(!res);
  1286. oi->scenario->_portal_renderer.occluder_instance_link(oi->scenario_occluder_id, res->occluder_resource_id);
  1287. }
  1288. void VisualServerScene::occluder_instance_set_scenario(RID p_occluder_instance, RID p_scenario) {
  1289. OccluderInstance *oi = occluder_instance_owner.getornull(p_occluder_instance);
  1290. ERR_FAIL_COND(!oi);
  1291. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1292. // noop?
  1293. if (oi->scenario == scenario) {
  1294. return;
  1295. }
  1296. // if the portal is in a scenario already, remove it
  1297. if (oi->scenario) {
  1298. oi->scenario->_portal_renderer.occluder_instance_destroy(oi->scenario_occluder_id);
  1299. oi->scenario = nullptr;
  1300. oi->scenario_occluder_id = 0;
  1301. }
  1302. // create when entering the world
  1303. if (scenario) {
  1304. oi->scenario = scenario;
  1305. oi->scenario_occluder_id = scenario->_portal_renderer.occluder_instance_create();
  1306. }
  1307. }
  1308. void VisualServerScene::occluder_instance_set_active(RID p_occluder_instance, bool p_active) {
  1309. OccluderInstance *oi = occluder_instance_owner.getornull(p_occluder_instance);
  1310. ERR_FAIL_COND(!oi);
  1311. ERR_FAIL_COND(!oi->scenario);
  1312. oi->scenario->_portal_renderer.occluder_instance_set_active(oi->scenario_occluder_id, p_active);
  1313. }
  1314. void VisualServerScene::occluder_instance_set_transform(RID p_occluder_instance, const Transform &p_xform) {
  1315. OccluderInstance *oi = occluder_instance_owner.getornull(p_occluder_instance);
  1316. ERR_FAIL_COND(!oi);
  1317. ERR_FAIL_COND(!oi->scenario);
  1318. oi->scenario->_portal_renderer.occluder_instance_set_transform(oi->scenario_occluder_id, p_xform);
  1319. }
  1320. RID VisualServerScene::occluder_resource_create() {
  1321. OccluderResource *res = memnew(OccluderResource);
  1322. ERR_FAIL_COND_V(!res, RID());
  1323. res->occluder_resource_id = _portal_resources.occluder_resource_create();
  1324. RID occluder_resource_rid = occluder_resource_owner.make_rid(res);
  1325. return occluder_resource_rid;
  1326. }
  1327. void VisualServerScene::occluder_resource_prepare(RID p_occluder_resource, VisualServer::OccluderType p_type) {
  1328. OccluderResource *res = occluder_resource_owner.getornull(p_occluder_resource);
  1329. ERR_FAIL_COND(!res);
  1330. _portal_resources.occluder_resource_prepare(res->occluder_resource_id, (VSOccluder_Instance::Type)p_type);
  1331. }
  1332. void VisualServerScene::occluder_resource_spheres_update(RID p_occluder_resource, const Vector<Plane> &p_spheres) {
  1333. OccluderResource *res = occluder_resource_owner.getornull(p_occluder_resource);
  1334. ERR_FAIL_COND(!res);
  1335. _portal_resources.occluder_resource_update_spheres(res->occluder_resource_id, p_spheres);
  1336. }
  1337. void VisualServerScene::occluder_resource_mesh_update(RID p_occluder_resource, const Geometry::OccluderMeshData &p_mesh_data) {
  1338. OccluderResource *res = occluder_resource_owner.getornull(p_occluder_resource);
  1339. ERR_FAIL_COND(!res);
  1340. _portal_resources.occluder_resource_update_mesh(res->occluder_resource_id, p_mesh_data);
  1341. }
  1342. void VisualServerScene::set_use_occlusion_culling(bool p_enable) {
  1343. // this is not scenario specific, and is global
  1344. // (mainly for debugging)
  1345. PortalRenderer::use_occlusion_culling = p_enable;
  1346. }
  1347. Geometry::MeshData VisualServerScene::occlusion_debug_get_current_polys(RID p_scenario) const {
  1348. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1349. if (!scenario) {
  1350. return Geometry::MeshData();
  1351. }
  1352. return scenario->_portal_renderer.occlusion_debug_get_current_polys();
  1353. }
  1354. // Rooms
  1355. void VisualServerScene::callbacks_register(VisualServerCallbacks *p_callbacks) {
  1356. _visual_server_callbacks = p_callbacks;
  1357. }
  1358. // the room has to be associated with a scenario, this is assumed to be
  1359. // the same scenario as the room node
  1360. RID VisualServerScene::room_create() {
  1361. Room *room = memnew(Room);
  1362. ERR_FAIL_COND_V(!room, RID());
  1363. RID room_rid = room_owner.make_rid(room);
  1364. return room_rid;
  1365. }
  1366. // should not be called multiple times, different scenarios etc, but just in case, we will support this
  1367. void VisualServerScene::room_set_scenario(RID p_room, RID p_scenario) {
  1368. Room *room = room_owner.getornull(p_room);
  1369. ERR_FAIL_COND(!room);
  1370. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1371. // no change?
  1372. if (room->scenario == scenario) {
  1373. return;
  1374. }
  1375. // if the room has an existing scenario, remove from it
  1376. if (room->scenario) {
  1377. room->scenario->_portal_renderer.room_destroy(room->scenario_room_id);
  1378. room->scenario = nullptr;
  1379. room->scenario_room_id = 0;
  1380. }
  1381. // create when entering the world
  1382. if (scenario) {
  1383. room->scenario = scenario;
  1384. // defer the actual creation to here
  1385. room->scenario_room_id = scenario->_portal_renderer.room_create();
  1386. }
  1387. }
  1388. void VisualServerScene::room_add_ghost(RID p_room, ObjectID p_object_id, const AABB &p_aabb) {
  1389. Room *room = room_owner.getornull(p_room);
  1390. ERR_FAIL_COND(!room);
  1391. ERR_FAIL_COND(!room->scenario);
  1392. room->scenario->_portal_renderer.room_add_ghost(room->scenario_room_id, p_object_id, p_aabb);
  1393. }
  1394. void VisualServerScene::room_add_instance(RID p_room, RID p_instance, const AABB &p_aabb, const Vector<Vector3> &p_object_pts) {
  1395. Room *room = room_owner.getornull(p_room);
  1396. ERR_FAIL_COND(!room);
  1397. ERR_FAIL_COND(!room->scenario);
  1398. Instance *instance = instance_owner.getornull(p_instance);
  1399. ERR_FAIL_COND(!instance);
  1400. AABB bb = p_aabb;
  1401. // the aabb passed from the client takes no account of the extra cull margin,
  1402. // so we need to add this manually.
  1403. // It is assumed it is in world space.
  1404. if (instance->extra_margin != 0.0) {
  1405. bb.grow_by(instance->extra_margin);
  1406. }
  1407. bool dynamic = false;
  1408. // don't add if portal mode is not static or dynamic
  1409. switch (instance->portal_mode) {
  1410. default: {
  1411. return; // this should be taken care of by the calling function, but just in case
  1412. } break;
  1413. case VisualServer::InstancePortalMode::INSTANCE_PORTAL_MODE_DYNAMIC: {
  1414. dynamic = true;
  1415. } break;
  1416. case VisualServer::InstancePortalMode::INSTANCE_PORTAL_MODE_STATIC: {
  1417. dynamic = false;
  1418. } break;
  1419. }
  1420. instance->occlusion_handle = room->scenario->_portal_renderer.room_add_instance(room->scenario_room_id, p_instance, bb, dynamic, p_object_pts);
  1421. }
  1422. void VisualServerScene::room_prepare(RID p_room, int32_t p_priority) {
  1423. Room *room = room_owner.getornull(p_room);
  1424. ERR_FAIL_COND(!room);
  1425. ERR_FAIL_COND(!room->scenario);
  1426. room->scenario->_portal_renderer.room_prepare(room->scenario_room_id, p_priority);
  1427. }
  1428. void VisualServerScene::room_set_bound(RID p_room, ObjectID p_room_object_id, const Vector<Plane> &p_convex, const AABB &p_aabb, const Vector<Vector3> &p_verts) {
  1429. Room *room = room_owner.getornull(p_room);
  1430. ERR_FAIL_COND(!room);
  1431. ERR_FAIL_COND(!room->scenario);
  1432. room->scenario->_portal_renderer.room_set_bound(room->scenario_room_id, p_room_object_id, p_convex, p_aabb, p_verts);
  1433. }
  1434. void VisualServerScene::rooms_unload(RID p_scenario, String p_reason) {
  1435. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1436. ERR_FAIL_COND(!scenario);
  1437. scenario->_portal_renderer.rooms_unload(p_reason);
  1438. }
  1439. void VisualServerScene::rooms_and_portals_clear(RID p_scenario) {
  1440. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1441. ERR_FAIL_COND(!scenario);
  1442. scenario->_portal_renderer.rooms_and_portals_clear();
  1443. }
  1444. void VisualServerScene::rooms_finalize(RID p_scenario, bool p_generate_pvs, bool p_cull_using_pvs, bool p_use_secondary_pvs, bool p_use_signals, String p_pvs_filename, bool p_use_simple_pvs, bool p_log_pvs_generation) {
  1445. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1446. ERR_FAIL_COND(!scenario);
  1447. scenario->_portal_renderer.rooms_finalize(p_generate_pvs, p_cull_using_pvs, p_use_secondary_pvs, p_use_signals, p_pvs_filename, p_use_simple_pvs, p_log_pvs_generation);
  1448. }
  1449. void VisualServerScene::rooms_override_camera(RID p_scenario, bool p_override, const Vector3 &p_point, const Vector<Plane> *p_convex) {
  1450. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1451. ERR_FAIL_COND(!scenario);
  1452. scenario->_portal_renderer.rooms_override_camera(p_override, p_point, p_convex);
  1453. }
  1454. void VisualServerScene::rooms_set_active(RID p_scenario, bool p_active) {
  1455. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1456. ERR_FAIL_COND(!scenario);
  1457. scenario->_portal_renderer.rooms_set_active(p_active);
  1458. }
  1459. void VisualServerScene::rooms_set_params(RID p_scenario, int p_portal_depth_limit, real_t p_roaming_expansion_margin) {
  1460. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1461. ERR_FAIL_COND(!scenario);
  1462. scenario->_portal_renderer.rooms_set_params(p_portal_depth_limit, p_roaming_expansion_margin);
  1463. }
  1464. void VisualServerScene::rooms_set_debug_feature(RID p_scenario, VisualServer::RoomsDebugFeature p_feature, bool p_active) {
  1465. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1466. ERR_FAIL_COND(!scenario);
  1467. switch (p_feature) {
  1468. default: {
  1469. } break;
  1470. case VisualServer::ROOMS_DEBUG_SPRAWL: {
  1471. scenario->_portal_renderer.set_debug_sprawl(p_active);
  1472. } break;
  1473. }
  1474. }
  1475. void VisualServerScene::rooms_update_gameplay_monitor(RID p_scenario, const Vector<Vector3> &p_camera_positions) {
  1476. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1477. ERR_FAIL_COND(!scenario);
  1478. scenario->_portal_renderer.rooms_update_gameplay_monitor(p_camera_positions);
  1479. }
  1480. bool VisualServerScene::rooms_is_loaded(RID p_scenario) const {
  1481. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1482. ERR_FAIL_COND_V(!scenario, false);
  1483. return scenario->_portal_renderer.rooms_is_loaded();
  1484. }
  1485. Vector<ObjectID> VisualServerScene::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
  1486. Vector<ObjectID> instances;
  1487. Scenario *scenario = scenario_owner.get(p_scenario);
  1488. ERR_FAIL_COND_V(!scenario, instances);
  1489. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  1490. int culled = 0;
  1491. Instance *cull[1024];
  1492. culled = scenario->sps->cull_aabb(p_aabb, cull, 1024);
  1493. for (int i = 0; i < culled; i++) {
  1494. Instance *instance = cull[i];
  1495. ERR_CONTINUE(!instance);
  1496. if (instance->object_id == 0) {
  1497. continue;
  1498. }
  1499. instances.push_back(instance->object_id);
  1500. }
  1501. return instances;
  1502. }
  1503. Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
  1504. Vector<ObjectID> instances;
  1505. Scenario *scenario = scenario_owner.get(p_scenario);
  1506. ERR_FAIL_COND_V(!scenario, instances);
  1507. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  1508. int culled = 0;
  1509. Instance *cull[1024];
  1510. culled = scenario->sps->cull_segment(p_from, p_from + p_to * 10000, cull, 1024);
  1511. for (int i = 0; i < culled; i++) {
  1512. Instance *instance = cull[i];
  1513. ERR_CONTINUE(!instance);
  1514. if (instance->object_id == 0) {
  1515. continue;
  1516. }
  1517. instances.push_back(instance->object_id);
  1518. }
  1519. return instances;
  1520. }
  1521. Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
  1522. Vector<ObjectID> instances;
  1523. Scenario *scenario = scenario_owner.get(p_scenario);
  1524. ERR_FAIL_COND_V(!scenario, instances);
  1525. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  1526. int culled = 0;
  1527. Instance *cull[1024];
  1528. culled = scenario->sps->cull_convex(p_convex, cull, 1024);
  1529. for (int i = 0; i < culled; i++) {
  1530. Instance *instance = cull[i];
  1531. ERR_CONTINUE(!instance);
  1532. if (instance->object_id == 0) {
  1533. continue;
  1534. }
  1535. instances.push_back(instance->object_id);
  1536. }
  1537. return instances;
  1538. }
  1539. // thin wrapper to allow rooms / portals to take over culling if active
  1540. int VisualServerScene::_cull_convex_from_point(Scenario *p_scenario, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, const Vector<Plane> &p_convex, Instance **p_result_array, int p_result_max, int32_t &r_previous_room_id_hint, uint32_t p_mask) {
  1541. int res = -1;
  1542. if (p_scenario->_portal_renderer.is_active()) {
  1543. // Note that the portal renderer ASSUMES that the planes exactly match the convention in
  1544. // CameraMatrix of enum Planes (6 planes, in order, near, far etc)
  1545. // If this is not the case, it should not be used.
  1546. res = p_scenario->_portal_renderer.cull_convex(p_cam_transform, p_cam_projection, p_convex, (VSInstance **)p_result_array, p_result_max, p_mask, r_previous_room_id_hint);
  1547. }
  1548. // fallback to BVH / octree if portals not active
  1549. if (res == -1) {
  1550. res = p_scenario->sps->cull_convex(p_convex, p_result_array, p_result_max, p_mask);
  1551. // Opportunity for occlusion culling on the main scene. This will be a noop if no occluders.
  1552. if (p_scenario->_portal_renderer.occlusion_is_active()) {
  1553. res = p_scenario->_portal_renderer.occlusion_cull(p_cam_transform, p_cam_projection, p_convex, (VSInstance **)p_result_array, res);
  1554. }
  1555. }
  1556. return res;
  1557. }
  1558. void VisualServerScene::_rooms_instance_update(Instance *p_instance, const AABB &p_aabb) {
  1559. // magic number for instances in the room / portal system, but not requiring an update
  1560. // (due to being a STATIC or DYNAMIC object within a room)
  1561. // Must match the value in PortalRenderer in VisualServer
  1562. const uint32_t OCCLUSION_HANDLE_ROOM_BIT = 1 << 31;
  1563. // if the instance is a moving object in the room / portal system, update it
  1564. // Note that if rooms and portals is not in use, occlusion_handle should be zero in all cases unless the portal_mode
  1565. // has been set to global or roaming. (which is unlikely as the default is static).
  1566. // The exception is editor user interface elements.
  1567. // These are always set to global and will always keep their aabb up to date in the portal renderer unnecessarily.
  1568. // There is no easy way around this, but it should be very cheap, and have no impact outside the editor.
  1569. if (p_instance->occlusion_handle && (p_instance->occlusion_handle != OCCLUSION_HANDLE_ROOM_BIT)) {
  1570. p_instance->scenario->_portal_renderer.instance_moving_update(p_instance->occlusion_handle, p_aabb);
  1571. }
  1572. }
  1573. void VisualServerScene::instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled) {
  1574. Instance *instance = instance_owner.get(p_instance);
  1575. ERR_FAIL_COND(!instance);
  1576. switch (p_flags) {
  1577. case VS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
  1578. instance->baked_light = p_enabled;
  1579. } break;
  1580. case VS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {
  1581. instance->redraw_if_visible = p_enabled;
  1582. } break;
  1583. default: {
  1584. }
  1585. }
  1586. }
  1587. void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) {
  1588. Instance *instance = instance_owner.get(p_instance);
  1589. ERR_FAIL_COND(!instance);
  1590. instance->cast_shadows = p_shadow_casting_setting;
  1591. instance->base_changed(false, true); // to actually compute if shadows are visible or not
  1592. }
  1593. void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) {
  1594. Instance *instance = instance_owner.get(p_instance);
  1595. ERR_FAIL_COND(!instance);
  1596. if (instance->material_override.is_valid()) {
  1597. VSG::storage->material_remove_instance_owner(instance->material_override, instance);
  1598. }
  1599. instance->material_override = p_material;
  1600. instance->base_changed(false, true);
  1601. if (instance->material_override.is_valid()) {
  1602. VSG::storage->material_add_instance_owner(instance->material_override, instance);
  1603. }
  1604. }
  1605. void VisualServerScene::instance_geometry_set_material_overlay(RID p_instance, RID p_material) {
  1606. Instance *instance = instance_owner.get(p_instance);
  1607. ERR_FAIL_COND(!instance);
  1608. if (instance->material_overlay.is_valid()) {
  1609. VSG::storage->material_remove_instance_owner(instance->material_overlay, instance);
  1610. }
  1611. instance->material_overlay = p_material;
  1612. instance->base_changed(false, true);
  1613. if (instance->material_overlay.is_valid()) {
  1614. VSG::storage->material_add_instance_owner(instance->material_overlay, instance);
  1615. }
  1616. }
  1617. void VisualServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
  1618. }
  1619. void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
  1620. }
  1621. void VisualServerScene::_update_instance(Instance *p_instance) {
  1622. p_instance->version++;
  1623. // when not using interpolation the transform is used straight
  1624. const Transform *instance_xform = &p_instance->transform;
  1625. // Can possibly use the most up to date current transform here when using physics interpolation ..
  1626. // uncomment the next line for this..
  1627. // if (p_instance->is_currently_interpolated()) {
  1628. // instance_xform = &p_instance->transform_curr;
  1629. // }
  1630. // However it does seem that using the interpolated transform (transform) works for keeping AABBs
  1631. // up to date to avoid culling errors.
  1632. if (p_instance->base_type == VS::INSTANCE_LIGHT) {
  1633. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1634. VSG::scene_render->light_instance_set_transform(light->instance, *instance_xform);
  1635. light->shadow_dirty = true;
  1636. }
  1637. if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) {
  1638. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  1639. VSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, *instance_xform);
  1640. reflection_probe->reflection_dirty = true;
  1641. }
  1642. if (p_instance->base_type == VS::INSTANCE_PARTICLES) {
  1643. VSG::storage->particles_set_emission_transform(p_instance->base, *instance_xform);
  1644. }
  1645. if (p_instance->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE) {
  1646. InstanceLightmapCaptureData *capture = static_cast<InstanceLightmapCaptureData *>(p_instance->base_data);
  1647. for (List<InstanceLightmapCaptureData::PairInfo>::Element *E = capture->geometries.front(); E; E = E->next()) {
  1648. _instance_queue_update(E->get().geometry, false, true);
  1649. }
  1650. }
  1651. if (p_instance->aabb.has_no_surface()) {
  1652. return;
  1653. }
  1654. if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  1655. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1656. //make sure lights are updated if it casts shadow
  1657. if (geom->can_cast_shadows) {
  1658. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  1659. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1660. light->shadow_dirty = true;
  1661. }
  1662. }
  1663. if (!p_instance->lightmap_capture && geom->lightmap_captures.size()) {
  1664. //affected by lightmap captures, must update capture info!
  1665. _update_instance_lightmap_captures(p_instance);
  1666. } else {
  1667. if (!p_instance->lightmap_capture_data.empty()) {
  1668. p_instance->lightmap_capture_data.resize(0); //not in use, clear capture data
  1669. }
  1670. }
  1671. }
  1672. p_instance->mirror = instance_xform->basis.determinant() < 0.0;
  1673. AABB new_aabb;
  1674. new_aabb = instance_xform->xform(p_instance->aabb);
  1675. p_instance->transformed_aabb = new_aabb;
  1676. if (!p_instance->scenario) {
  1677. return;
  1678. }
  1679. if (p_instance->spatial_partition_id == 0) {
  1680. uint32_t base_type = 1 << p_instance->base_type;
  1681. uint32_t pairable_mask = 0;
  1682. bool pairable = false;
  1683. if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE || p_instance->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE) {
  1684. pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK : 0;
  1685. pairable = true;
  1686. }
  1687. if (p_instance->base_type == VS::INSTANCE_GI_PROBE) {
  1688. //lights and geometries
  1689. pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT) : 0;
  1690. pairable = true;
  1691. }
  1692. // not inside octree
  1693. p_instance->spatial_partition_id = p_instance->scenario->sps->create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask);
  1694. } else {
  1695. /*
  1696. if (new_aabb==p_instance->data.transformed_aabb)
  1697. return;
  1698. */
  1699. p_instance->scenario->sps->move(p_instance->spatial_partition_id, new_aabb);
  1700. }
  1701. // keep rooms and portals instance up to date if present
  1702. _rooms_instance_update(p_instance, new_aabb);
  1703. }
  1704. void VisualServerScene::_update_instance_aabb(Instance *p_instance) {
  1705. AABB new_aabb;
  1706. ERR_FAIL_COND(p_instance->base_type != VS::INSTANCE_NONE && !p_instance->base.is_valid());
  1707. switch (p_instance->base_type) {
  1708. case VisualServer::INSTANCE_NONE: {
  1709. // do nothing
  1710. } break;
  1711. case VisualServer::INSTANCE_MESH: {
  1712. if (p_instance->custom_aabb) {
  1713. new_aabb = *p_instance->custom_aabb;
  1714. } else {
  1715. new_aabb = VSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
  1716. }
  1717. } break;
  1718. case VisualServer::INSTANCE_MULTIMESH: {
  1719. if (p_instance->custom_aabb) {
  1720. new_aabb = *p_instance->custom_aabb;
  1721. } else {
  1722. new_aabb = VSG::storage->multimesh_get_aabb(p_instance->base);
  1723. }
  1724. } break;
  1725. case VisualServer::INSTANCE_IMMEDIATE: {
  1726. if (p_instance->custom_aabb) {
  1727. new_aabb = *p_instance->custom_aabb;
  1728. } else {
  1729. new_aabb = VSG::storage->immediate_get_aabb(p_instance->base);
  1730. }
  1731. } break;
  1732. case VisualServer::INSTANCE_PARTICLES: {
  1733. if (p_instance->custom_aabb) {
  1734. new_aabb = *p_instance->custom_aabb;
  1735. } else {
  1736. new_aabb = VSG::storage->particles_get_aabb(p_instance->base);
  1737. }
  1738. } break;
  1739. case VisualServer::INSTANCE_LIGHT: {
  1740. new_aabb = VSG::storage->light_get_aabb(p_instance->base);
  1741. } break;
  1742. case VisualServer::INSTANCE_REFLECTION_PROBE: {
  1743. new_aabb = VSG::storage->reflection_probe_get_aabb(p_instance->base);
  1744. } break;
  1745. case VisualServer::INSTANCE_GI_PROBE: {
  1746. new_aabb = VSG::storage->gi_probe_get_bounds(p_instance->base);
  1747. } break;
  1748. case VisualServer::INSTANCE_LIGHTMAP_CAPTURE: {
  1749. new_aabb = VSG::storage->lightmap_capture_get_bounds(p_instance->base);
  1750. } break;
  1751. default: {
  1752. }
  1753. }
  1754. // <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
  1755. if (p_instance->extra_margin) {
  1756. new_aabb.grow_by(p_instance->extra_margin);
  1757. }
  1758. p_instance->aabb = new_aabb;
  1759. }
  1760. _FORCE_INLINE_ static void _light_capture_sample_octree(const RasterizerStorage::LightmapCaptureOctree *p_octree, int p_cell_subdiv, const Vector3 &p_pos, const Vector3 &p_dir, float p_level, Vector3 &r_color, float &r_alpha) {
  1761. static const Vector3 aniso_normal[6] = {
  1762. Vector3(-1, 0, 0),
  1763. Vector3(1, 0, 0),
  1764. Vector3(0, -1, 0),
  1765. Vector3(0, 1, 0),
  1766. Vector3(0, 0, -1),
  1767. Vector3(0, 0, 1)
  1768. };
  1769. int size = 1 << (p_cell_subdiv - 1);
  1770. int clamp_v = size - 1;
  1771. //first of all, clamp
  1772. Vector3 pos;
  1773. pos.x = CLAMP(p_pos.x, 0, clamp_v);
  1774. pos.y = CLAMP(p_pos.y, 0, clamp_v);
  1775. pos.z = CLAMP(p_pos.z, 0, clamp_v);
  1776. float level = (p_cell_subdiv - 1) - p_level;
  1777. int target_level;
  1778. float level_filter;
  1779. if (level <= 0.0) {
  1780. level_filter = 0;
  1781. target_level = 0;
  1782. } else {
  1783. target_level = Math::ceil(level);
  1784. level_filter = target_level - level;
  1785. }
  1786. Vector3 color[2][8];
  1787. float alpha[2][8];
  1788. memset(alpha, 0, sizeof(float) * 2 * 8);
  1789. //find cell at given level first
  1790. for (int c = 0; c < 2; c++) {
  1791. int current_level = MAX(0, target_level - c);
  1792. int level_cell_size = (1 << (p_cell_subdiv - 1)) >> current_level;
  1793. for (int n = 0; n < 8; n++) {
  1794. int x = int(pos.x);
  1795. int y = int(pos.y);
  1796. int z = int(pos.z);
  1797. if (n & 1) {
  1798. x += level_cell_size;
  1799. }
  1800. if (n & 2) {
  1801. y += level_cell_size;
  1802. }
  1803. if (n & 4) {
  1804. z += level_cell_size;
  1805. }
  1806. int ofs_x = 0;
  1807. int ofs_y = 0;
  1808. int ofs_z = 0;
  1809. x = CLAMP(x, 0, clamp_v);
  1810. y = CLAMP(y, 0, clamp_v);
  1811. z = CLAMP(z, 0, clamp_v);
  1812. int half = size / 2;
  1813. uint32_t cell = 0;
  1814. for (int i = 0; i < current_level; i++) {
  1815. const RasterizerStorage::LightmapCaptureOctree *bc = &p_octree[cell];
  1816. int child = 0;
  1817. if (x >= ofs_x + half) {
  1818. child |= 1;
  1819. ofs_x += half;
  1820. }
  1821. if (y >= ofs_y + half) {
  1822. child |= 2;
  1823. ofs_y += half;
  1824. }
  1825. if (z >= ofs_z + half) {
  1826. child |= 4;
  1827. ofs_z += half;
  1828. }
  1829. cell = bc->children[child];
  1830. if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY) {
  1831. break;
  1832. }
  1833. half >>= 1;
  1834. }
  1835. if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY) {
  1836. alpha[c][n] = 0;
  1837. } else {
  1838. alpha[c][n] = p_octree[cell].alpha;
  1839. for (int i = 0; i < 6; i++) {
  1840. //anisotropic read light
  1841. float amount = p_dir.dot(aniso_normal[i]);
  1842. if (amount < 0) {
  1843. amount = 0;
  1844. }
  1845. color[c][n].x += p_octree[cell].light[i][0] / 1024.0 * amount;
  1846. color[c][n].y += p_octree[cell].light[i][1] / 1024.0 * amount;
  1847. color[c][n].z += p_octree[cell].light[i][2] / 1024.0 * amount;
  1848. }
  1849. }
  1850. //print_line("\tlev " + itos(c) + " - " + itos(n) + " alpha: " + rtos(cells[test_cell].alpha) + " col: " + color[c][n]);
  1851. }
  1852. }
  1853. float target_level_size = size >> target_level;
  1854. Vector3 pos_fract[2];
  1855. pos_fract[0].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  1856. pos_fract[0].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  1857. pos_fract[0].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  1858. target_level_size = size >> MAX(0, target_level - 1);
  1859. pos_fract[1].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  1860. pos_fract[1].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  1861. pos_fract[1].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  1862. float alpha_interp[2];
  1863. Vector3 color_interp[2];
  1864. for (int i = 0; i < 2; i++) {
  1865. Vector3 color_x00 = color[i][0].linear_interpolate(color[i][1], pos_fract[i].x);
  1866. Vector3 color_xy0 = color[i][2].linear_interpolate(color[i][3], pos_fract[i].x);
  1867. Vector3 blend_z0 = color_x00.linear_interpolate(color_xy0, pos_fract[i].y);
  1868. Vector3 color_x0z = color[i][4].linear_interpolate(color[i][5], pos_fract[i].x);
  1869. Vector3 color_xyz = color[i][6].linear_interpolate(color[i][7], pos_fract[i].x);
  1870. Vector3 blend_z1 = color_x0z.linear_interpolate(color_xyz, pos_fract[i].y);
  1871. color_interp[i] = blend_z0.linear_interpolate(blend_z1, pos_fract[i].z);
  1872. float alpha_x00 = Math::lerp(alpha[i][0], alpha[i][1], pos_fract[i].x);
  1873. float alpha_xy0 = Math::lerp(alpha[i][2], alpha[i][3], pos_fract[i].x);
  1874. float alpha_z0 = Math::lerp(alpha_x00, alpha_xy0, pos_fract[i].y);
  1875. float alpha_x0z = Math::lerp(alpha[i][4], alpha[i][5], pos_fract[i].x);
  1876. float alpha_xyz = Math::lerp(alpha[i][6], alpha[i][7], pos_fract[i].x);
  1877. float alpha_z1 = Math::lerp(alpha_x0z, alpha_xyz, pos_fract[i].y);
  1878. alpha_interp[i] = Math::lerp(alpha_z0, alpha_z1, pos_fract[i].z);
  1879. }
  1880. r_color = color_interp[0].linear_interpolate(color_interp[1], level_filter);
  1881. r_alpha = Math::lerp(alpha_interp[0], alpha_interp[1], level_filter);
  1882. //print_line("pos: " + p_posf + " level " + rtos(p_level) + " down to " + itos(target_level) + "." + rtos(level_filter) + " color " + r_color + " alpha " + rtos(r_alpha));
  1883. }
  1884. _FORCE_INLINE_ static Color _light_capture_voxel_cone_trace(const RasterizerStorage::LightmapCaptureOctree *p_octree, const Vector3 &p_pos, const Vector3 &p_dir, float p_aperture, int p_cell_subdiv) {
  1885. float bias = 0.0; //no need for bias here
  1886. float max_distance = (Vector3(1, 1, 1) * (1 << (p_cell_subdiv - 1))).length();
  1887. float dist = bias;
  1888. float alpha = 0.0;
  1889. Vector3 color;
  1890. Vector3 scolor;
  1891. float salpha;
  1892. while (dist < max_distance && alpha < 0.95) {
  1893. float diameter = MAX(1.0, 2.0 * p_aperture * dist);
  1894. _light_capture_sample_octree(p_octree, p_cell_subdiv, p_pos + dist * p_dir, p_dir, log2(diameter), scolor, salpha);
  1895. float a = (1.0 - alpha);
  1896. color += scolor * a;
  1897. alpha += a * salpha;
  1898. dist += diameter * 0.5;
  1899. }
  1900. return Color(color.x, color.y, color.z, alpha);
  1901. }
  1902. void VisualServerScene::_update_instance_lightmap_captures(Instance *p_instance) {
  1903. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1904. static const Vector3 cone_traces[12] = {
  1905. Vector3(0, 0, 1),
  1906. Vector3(0.866025, 0, 0.5),
  1907. Vector3(0.267617, 0.823639, 0.5),
  1908. Vector3(-0.700629, 0.509037, 0.5),
  1909. Vector3(-0.700629, -0.509037, 0.5),
  1910. Vector3(0.267617, -0.823639, 0.5),
  1911. Vector3(0, 0, -1),
  1912. Vector3(0.866025, 0, -0.5),
  1913. Vector3(0.267617, 0.823639, -0.5),
  1914. Vector3(-0.700629, 0.509037, -0.5),
  1915. Vector3(-0.700629, -0.509037, -0.5),
  1916. Vector3(0.267617, -0.823639, -0.5)
  1917. };
  1918. float cone_aperture = 0.577; // tan(angle) 60 degrees
  1919. if (p_instance->lightmap_capture_data.empty()) {
  1920. p_instance->lightmap_capture_data.resize(12);
  1921. }
  1922. //print_line("update captures for pos: " + p_instance->transform.origin);
  1923. for (int i = 0; i < 12; i++) {
  1924. new (&p_instance->lightmap_capture_data.ptrw()[i]) Color;
  1925. }
  1926. bool interior = true;
  1927. //this could use some sort of blending..
  1928. for (List<Instance *>::Element *E = geom->lightmap_captures.front(); E; E = E->next()) {
  1929. const PoolVector<RasterizerStorage::LightmapCaptureOctree> *octree = VSG::storage->lightmap_capture_get_octree_ptr(E->get()->base);
  1930. //print_line("octree size: " + itos(octree->size()));
  1931. if (octree->size() == 0) {
  1932. continue;
  1933. }
  1934. Transform to_cell_xform = VSG::storage->lightmap_capture_get_octree_cell_transform(E->get()->base);
  1935. int cell_subdiv = VSG::storage->lightmap_capture_get_octree_cell_subdiv(E->get()->base);
  1936. to_cell_xform = to_cell_xform * E->get()->transform.affine_inverse();
  1937. PoolVector<RasterizerStorage::LightmapCaptureOctree>::Read octree_r = octree->read();
  1938. Vector3 pos = to_cell_xform.xform(p_instance->transform.origin);
  1939. const float capture_energy = VSG::storage->lightmap_capture_get_energy(E->get()->base);
  1940. interior = interior && VSG::storage->lightmap_capture_is_interior(E->get()->base);
  1941. for (int i = 0; i < 12; i++) {
  1942. Vector3 dir = to_cell_xform.basis.xform(cone_traces[i]).normalized();
  1943. Color capture = _light_capture_voxel_cone_trace(octree_r.ptr(), pos, dir, cone_aperture, cell_subdiv);
  1944. capture.r *= capture_energy;
  1945. capture.g *= capture_energy;
  1946. capture.b *= capture_energy;
  1947. p_instance->lightmap_capture_data.write[i] += capture;
  1948. }
  1949. }
  1950. p_instance->lightmap_capture_data.write[0].a = interior ? 0.0f : 1.0f;
  1951. }
  1952. bool VisualServerScene::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_shadow_atlas, Scenario *p_scenario) {
  1953. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1954. Transform light_transform = p_instance->transform;
  1955. light_transform.orthonormalize(); //scale does not count on lights
  1956. bool animated_material_found = false;
  1957. switch (VSG::storage->light_get_type(p_instance->base)) {
  1958. case VS::LIGHT_DIRECTIONAL: {
  1959. float max_distance = p_cam_projection.get_z_far();
  1960. float shadow_max = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
  1961. if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
  1962. max_distance = MIN(shadow_max, max_distance);
  1963. }
  1964. max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
  1965. float min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
  1966. VS::LightDirectionalShadowDepthRangeMode depth_range_mode = VSG::storage->light_directional_get_shadow_depth_range_mode(p_instance->base);
  1967. if (depth_range_mode == VS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_OPTIMIZED) {
  1968. //optimize min/max
  1969. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  1970. int cull_count = p_scenario->sps->cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  1971. Plane base(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2));
  1972. //check distance max and min
  1973. bool found_items = false;
  1974. float z_max = -1e20;
  1975. float z_min = 1e20;
  1976. for (int i = 0; i < cull_count; i++) {
  1977. Instance *instance = instance_shadow_cull_result[i];
  1978. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1979. continue;
  1980. }
  1981. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1982. animated_material_found = true;
  1983. }
  1984. float max, min;
  1985. instance->transformed_aabb.project_range_in_plane(base, min, max);
  1986. if (max > z_max) {
  1987. z_max = max;
  1988. }
  1989. if (min < z_min) {
  1990. z_min = min;
  1991. }
  1992. found_items = true;
  1993. }
  1994. if (found_items) {
  1995. min_distance = MAX(min_distance, z_min);
  1996. max_distance = MIN(max_distance, z_max);
  1997. }
  1998. }
  1999. float range = max_distance - min_distance;
  2000. int splits = 0;
  2001. switch (VSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
  2002. case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  2003. splits = 1;
  2004. break;
  2005. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  2006. splits = 2;
  2007. break;
  2008. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  2009. splits = 4;
  2010. break;
  2011. }
  2012. float distances[5];
  2013. distances[0] = min_distance;
  2014. for (int i = 0; i < splits; i++) {
  2015. distances[i + 1] = min_distance + VSG::storage->light_get_param(p_instance->base, VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
  2016. };
  2017. distances[splits] = max_distance;
  2018. float texture_size = VSG::scene_render->get_directional_light_shadow_size(light->instance);
  2019. bool overlap = VSG::storage->light_directional_get_blend_splits(p_instance->base);
  2020. float first_radius = 0.0;
  2021. for (int i = 0; i < splits; i++) {
  2022. // setup a camera matrix for that range!
  2023. CameraMatrix camera_matrix;
  2024. float aspect = p_cam_projection.get_aspect();
  2025. if (p_cam_orthogonal) {
  2026. Vector2 vp_he = p_cam_projection.get_viewport_half_extents();
  2027. camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  2028. } else {
  2029. float fov = p_cam_projection.get_fov();
  2030. camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  2031. }
  2032. //obtain the frustum endpoints
  2033. Vector3 endpoints[8]; // frustum plane endpoints
  2034. bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
  2035. ERR_CONTINUE(!res);
  2036. // obtain the light frustm ranges (given endpoints)
  2037. Transform transform = light_transform; //discard scale and stabilize light
  2038. Vector3 x_vec = transform.basis.get_axis(Vector3::AXIS_X).normalized();
  2039. Vector3 y_vec = transform.basis.get_axis(Vector3::AXIS_Y).normalized();
  2040. Vector3 z_vec = transform.basis.get_axis(Vector3::AXIS_Z).normalized();
  2041. //z_vec points agsint the camera, like in default opengl
  2042. float x_min = 0.f, x_max = 0.f;
  2043. float y_min = 0.f, y_max = 0.f;
  2044. float z_min = 0.f, z_max = 0.f;
  2045. // FIXME: z_max_cam is defined, computed, but not used below when setting up
  2046. // ortho_camera. Commented out for now to fix warnings but should be investigated.
  2047. float x_min_cam = 0.f, x_max_cam = 0.f;
  2048. float y_min_cam = 0.f, y_max_cam = 0.f;
  2049. float z_min_cam = 0.f;
  2050. //float z_max_cam = 0.f;
  2051. float bias_scale = 1.0;
  2052. //used for culling
  2053. for (int j = 0; j < 8; j++) {
  2054. float d_x = x_vec.dot(endpoints[j]);
  2055. float d_y = y_vec.dot(endpoints[j]);
  2056. float d_z = z_vec.dot(endpoints[j]);
  2057. if (j == 0 || d_x < x_min) {
  2058. x_min = d_x;
  2059. }
  2060. if (j == 0 || d_x > x_max) {
  2061. x_max = d_x;
  2062. }
  2063. if (j == 0 || d_y < y_min) {
  2064. y_min = d_y;
  2065. }
  2066. if (j == 0 || d_y > y_max) {
  2067. y_max = d_y;
  2068. }
  2069. if (j == 0 || d_z < z_min) {
  2070. z_min = d_z;
  2071. }
  2072. if (j == 0 || d_z > z_max) {
  2073. z_max = d_z;
  2074. }
  2075. }
  2076. {
  2077. //camera viewport stuff
  2078. Vector3 center;
  2079. for (int j = 0; j < 8; j++) {
  2080. center += endpoints[j];
  2081. }
  2082. center /= 8.0;
  2083. //center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5;
  2084. float radius = 0;
  2085. for (int j = 0; j < 8; j++) {
  2086. float d = center.distance_to(endpoints[j]);
  2087. if (d > radius) {
  2088. radius = d;
  2089. }
  2090. }
  2091. radius *= texture_size / (texture_size - 2.0); //add a texel by each side
  2092. if (i == 0) {
  2093. first_radius = radius;
  2094. } else {
  2095. bias_scale = radius / first_radius;
  2096. }
  2097. x_max_cam = x_vec.dot(center) + radius;
  2098. x_min_cam = x_vec.dot(center) - radius;
  2099. y_max_cam = y_vec.dot(center) + radius;
  2100. y_min_cam = y_vec.dot(center) - radius;
  2101. //z_max_cam = z_vec.dot(center) + radius;
  2102. z_min_cam = z_vec.dot(center) - radius;
  2103. if (depth_range_mode == VS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE) {
  2104. //this trick here is what stabilizes the shadow (make potential jaggies to not move)
  2105. //at the cost of some wasted resolution. Still the quality increase is very well worth it
  2106. float unit = radius * 2.0 / texture_size;
  2107. x_max_cam = Math::stepify(x_max_cam, unit);
  2108. x_min_cam = Math::stepify(x_min_cam, unit);
  2109. y_max_cam = Math::stepify(y_max_cam, unit);
  2110. y_min_cam = Math::stepify(y_min_cam, unit);
  2111. }
  2112. }
  2113. //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree
  2114. Vector<Plane> light_frustum_planes;
  2115. light_frustum_planes.resize(6);
  2116. //right/left
  2117. light_frustum_planes.write[0] = Plane(x_vec, x_max);
  2118. light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
  2119. //top/bottom
  2120. light_frustum_planes.write[2] = Plane(y_vec, y_max);
  2121. light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
  2122. //near/far
  2123. light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
  2124. light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
  2125. int cull_count = p_scenario->sps->cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  2126. // a pre pass will need to be needed to determine the actual z-near to be used
  2127. Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
  2128. for (int j = 0; j < cull_count; j++) {
  2129. float min, max;
  2130. Instance *instance = instance_shadow_cull_result[j];
  2131. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  2132. cull_count--;
  2133. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  2134. j--;
  2135. continue;
  2136. }
  2137. instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max);
  2138. instance->depth = near_plane.distance_to(instance->transform.origin);
  2139. instance->depth_layer = 0;
  2140. if (max > z_max) {
  2141. z_max = max;
  2142. }
  2143. }
  2144. {
  2145. CameraMatrix ortho_camera;
  2146. real_t half_x = (x_max_cam - x_min_cam) * 0.5;
  2147. real_t half_y = (y_max_cam - y_min_cam) * 0.5;
  2148. ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
  2149. Transform ortho_transform;
  2150. ortho_transform.basis = transform.basis;
  2151. ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
  2152. VSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, 0, distances[i + 1], i, bias_scale);
  2153. }
  2154. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  2155. }
  2156. } break;
  2157. case VS::LIGHT_OMNI: {
  2158. VS::LightOmniShadowMode shadow_mode = VSG::storage->light_omni_get_shadow_mode(p_instance->base);
  2159. if (shadow_mode == VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !VSG::scene_render->light_instances_can_render_shadow_cube()) {
  2160. for (int i = 0; i < 2; i++) {
  2161. //using this one ensures that raster deferred will have it
  2162. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  2163. float z = i == 0 ? -1 : 1;
  2164. Vector<Plane> planes;
  2165. planes.resize(6);
  2166. planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
  2167. planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
  2168. planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
  2169. planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
  2170. planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
  2171. planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
  2172. int cull_count = p_scenario->sps->cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  2173. Plane near_plane(light_transform.origin, light_transform.basis.get_axis(2) * z);
  2174. for (int j = 0; j < cull_count; j++) {
  2175. Instance *instance = instance_shadow_cull_result[j];
  2176. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  2177. cull_count--;
  2178. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  2179. j--;
  2180. } else {
  2181. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  2182. animated_material_found = true;
  2183. }
  2184. instance->depth = near_plane.distance_to(instance->transform.origin);
  2185. instance->depth_layer = 0;
  2186. }
  2187. }
  2188. VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, i);
  2189. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  2190. }
  2191. } else { //shadow cube
  2192. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  2193. CameraMatrix cm;
  2194. cm.set_perspective(90, 1, 0.01, radius);
  2195. for (int i = 0; i < 6; i++) {
  2196. //using this one ensures that raster deferred will have it
  2197. static const Vector3 view_normals[6] = {
  2198. Vector3(-1, 0, 0),
  2199. Vector3(+1, 0, 0),
  2200. Vector3(0, -1, 0),
  2201. Vector3(0, +1, 0),
  2202. Vector3(0, 0, -1),
  2203. Vector3(0, 0, +1)
  2204. };
  2205. static const Vector3 view_up[6] = {
  2206. Vector3(0, -1, 0),
  2207. Vector3(0, -1, 0),
  2208. Vector3(0, 0, -1),
  2209. Vector3(0, 0, +1),
  2210. Vector3(0, -1, 0),
  2211. Vector3(0, -1, 0)
  2212. };
  2213. Transform xform = light_transform * Transform().looking_at(view_normals[i], view_up[i]);
  2214. Vector<Plane> planes = cm.get_projection_planes(xform);
  2215. int cull_count = _cull_convex_from_point(p_scenario, light_transform, cm, planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, light->previous_room_id_hint, VS::INSTANCE_GEOMETRY_MASK);
  2216. Plane near_plane(xform.origin, -xform.basis.get_axis(2));
  2217. for (int j = 0; j < cull_count; j++) {
  2218. Instance *instance = instance_shadow_cull_result[j];
  2219. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  2220. cull_count--;
  2221. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  2222. j--;
  2223. } else {
  2224. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  2225. animated_material_found = true;
  2226. }
  2227. instance->depth = near_plane.distance_to(instance->transform.origin);
  2228. instance->depth_layer = 0;
  2229. }
  2230. }
  2231. VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i);
  2232. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  2233. }
  2234. //restore the regular DP matrix
  2235. VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, 0);
  2236. }
  2237. } break;
  2238. case VS::LIGHT_SPOT: {
  2239. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  2240. float angle = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  2241. CameraMatrix cm;
  2242. cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);
  2243. Vector<Plane> planes = cm.get_projection_planes(light_transform);
  2244. int cull_count = _cull_convex_from_point(p_scenario, light_transform, cm, planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, light->previous_room_id_hint, VS::INSTANCE_GEOMETRY_MASK);
  2245. Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
  2246. for (int j = 0; j < cull_count; j++) {
  2247. Instance *instance = instance_shadow_cull_result[j];
  2248. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  2249. cull_count--;
  2250. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  2251. j--;
  2252. } else {
  2253. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  2254. animated_material_found = true;
  2255. }
  2256. instance->depth = near_plane.distance_to(instance->transform.origin);
  2257. instance->depth_layer = 0;
  2258. }
  2259. }
  2260. VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0);
  2261. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  2262. } break;
  2263. }
  2264. return animated_material_found;
  2265. }
  2266. void VisualServerScene::render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  2267. // render to mono camera
  2268. #ifndef _3D_DISABLED
  2269. Camera *camera = camera_owner.getornull(p_camera);
  2270. ERR_FAIL_COND(!camera);
  2271. /* STEP 1 - SETUP CAMERA */
  2272. CameraMatrix camera_matrix;
  2273. bool ortho = false;
  2274. switch (camera->type) {
  2275. case Camera::ORTHOGONAL: {
  2276. camera_matrix.set_orthogonal(
  2277. camera->size,
  2278. p_viewport_size.width / (float)p_viewport_size.height,
  2279. camera->znear,
  2280. camera->zfar,
  2281. camera->vaspect);
  2282. ortho = true;
  2283. } break;
  2284. case Camera::PERSPECTIVE: {
  2285. camera_matrix.set_perspective(
  2286. camera->fov,
  2287. p_viewport_size.width / (float)p_viewport_size.height,
  2288. camera->znear,
  2289. camera->zfar,
  2290. camera->vaspect);
  2291. ortho = false;
  2292. } break;
  2293. case Camera::FRUSTUM: {
  2294. camera_matrix.set_frustum(
  2295. camera->size,
  2296. p_viewport_size.width / (float)p_viewport_size.height,
  2297. camera->offset,
  2298. camera->znear,
  2299. camera->zfar,
  2300. camera->vaspect);
  2301. ortho = false;
  2302. } break;
  2303. }
  2304. Transform camera_transform = _interpolation_data.interpolation_enabled ? camera->get_transform_interpolated() : camera->transform;
  2305. _prepare_scene(camera_transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), camera->previous_room_id_hint);
  2306. _render_scene(camera_transform, camera_matrix, 0, ortho, camera->env, p_scenario, p_shadow_atlas, RID(), -1);
  2307. #endif
  2308. }
  2309. void VisualServerScene::render_camera(Ref<ARVRInterface> &p_interface, ARVRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  2310. // render for AR/VR interface
  2311. Camera *camera = camera_owner.getornull(p_camera);
  2312. ERR_FAIL_COND(!camera);
  2313. /* SETUP CAMERA, we are ignoring type and FOV here */
  2314. float aspect = p_viewport_size.width / (float)p_viewport_size.height;
  2315. CameraMatrix camera_matrix = p_interface->get_projection_for_eye(p_eye, aspect, camera->znear, camera->zfar);
  2316. // We also ignore our camera position, it will have been positioned with a slightly old tracking position.
  2317. // Instead we take our origin point and have our ar/vr interface add fresh tracking data! Whoohoo!
  2318. Transform world_origin = ARVRServer::get_singleton()->get_world_origin();
  2319. Transform cam_transform = p_interface->get_transform_for_eye(p_eye, world_origin);
  2320. // For stereo render we only prepare for our left eye and then reuse the outcome for our right eye
  2321. if (p_eye == ARVRInterface::EYE_LEFT) {
  2322. ///@TODO possibly move responsibility for this into our ARVRServer or ARVRInterface?
  2323. // Center our transform, we assume basis is equal.
  2324. Transform mono_transform = cam_transform;
  2325. Transform right_transform = p_interface->get_transform_for_eye(ARVRInterface::EYE_RIGHT, world_origin);
  2326. mono_transform.origin += right_transform.origin;
  2327. mono_transform.origin *= 0.5;
  2328. // We need to combine our projection frustums for culling.
  2329. // Ideally we should use our clipping planes for this and combine them,
  2330. // however our shadow map logic uses our projection matrix.
  2331. // Note: as our left and right frustums should be mirrored, we don't need our right projection matrix.
  2332. // - get some base values we need
  2333. float eye_dist = (mono_transform.origin - cam_transform.origin).length();
  2334. float z_near = camera_matrix.get_z_near(); // get our near plane
  2335. float z_far = camera_matrix.get_z_far(); // get our far plane
  2336. float width = (2.0 * z_near) / camera_matrix.matrix[0][0];
  2337. float x_shift = width * camera_matrix.matrix[2][0];
  2338. float height = (2.0 * z_near) / camera_matrix.matrix[1][1];
  2339. float y_shift = height * camera_matrix.matrix[2][1];
  2340. // printf("Eye_dist = %f, Near = %f, Far = %f, Width = %f, Shift = %f\n", eye_dist, z_near, z_far, width, x_shift);
  2341. // - calculate our near plane size (horizontal only, right_near is mirrored)
  2342. float left_near = -eye_dist - ((width - x_shift) * 0.5);
  2343. // - calculate our far plane size (horizontal only, right_far is mirrored)
  2344. float left_far = -eye_dist - (z_far * (width - x_shift) * 0.5 / z_near);
  2345. float left_far_right_eye = eye_dist - (z_far * (width + x_shift) * 0.5 / z_near);
  2346. if (left_far > left_far_right_eye) {
  2347. // on displays smaller then double our iod, the right eye far frustrum can overtake the left eyes.
  2348. left_far = left_far_right_eye;
  2349. }
  2350. // - figure out required z-shift
  2351. float slope = (left_far - left_near) / (z_far - z_near);
  2352. float z_shift = (left_near / slope) - z_near;
  2353. // - figure out new vertical near plane size (this will be slightly oversized thanks to our z-shift)
  2354. float top_near = (height - y_shift) * 0.5;
  2355. top_near += (top_near / z_near) * z_shift;
  2356. float bottom_near = -(height + y_shift) * 0.5;
  2357. bottom_near += (bottom_near / z_near) * z_shift;
  2358. // printf("Left_near = %f, Left_far = %f, Top_near = %f, Bottom_near = %f, Z_shift = %f\n", left_near, left_far, top_near, bottom_near, z_shift);
  2359. // - generate our frustum
  2360. CameraMatrix combined_matrix;
  2361. combined_matrix.set_frustum(left_near, -left_near, bottom_near, top_near, z_near + z_shift, z_far + z_shift);
  2362. // and finally move our camera back
  2363. Transform apply_z_shift;
  2364. apply_z_shift.origin = Vector3(0.0, 0.0, z_shift); // z negative is forward so this moves it backwards
  2365. mono_transform *= apply_z_shift;
  2366. // now prepare our scene with our adjusted transform projection matrix
  2367. _prepare_scene(mono_transform, combined_matrix, false, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), camera->previous_room_id_hint);
  2368. } else if (p_eye == ARVRInterface::EYE_MONO) {
  2369. // For mono render, prepare as per usual
  2370. _prepare_scene(cam_transform, camera_matrix, false, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), camera->previous_room_id_hint);
  2371. }
  2372. // And render our scene...
  2373. _render_scene(cam_transform, camera_matrix, p_eye, false, camera->env, p_scenario, p_shadow_atlas, RID(), -1);
  2374. };
  2375. void VisualServerScene::_prepare_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int32_t &r_previous_room_id_hint) {
  2376. // Note, in stereo rendering:
  2377. // - p_cam_transform will be a transform in the middle of our two eyes
  2378. // - p_cam_projection is a wider frustrum that encompasses both eyes
  2379. Scenario *scenario = scenario_owner.getornull(p_scenario);
  2380. render_pass++;
  2381. uint32_t camera_layer_mask = p_visible_layers;
  2382. VSG::scene_render->set_scene_pass(render_pass);
  2383. //rasterizer->set_camera(camera->transform, camera_matrix,ortho);
  2384. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  2385. Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
  2386. float z_far = p_cam_projection.get_z_far();
  2387. /* STEP 2 - CULL */
  2388. instance_cull_count = _cull_convex_from_point(scenario, p_cam_transform, p_cam_projection, planes, instance_cull_result, MAX_INSTANCE_CULL, r_previous_room_id_hint);
  2389. light_cull_count = 0;
  2390. reflection_probe_cull_count = 0;
  2391. //light_samplers_culled=0;
  2392. /*
  2393. print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0));
  2394. print_line("OTO: "+itos(p_scenario->octree.get_octant_count()));
  2395. print_line("OTE: "+itos(p_scenario->octree.get_elem_count()));
  2396. print_line("OTP: "+itos(p_scenario->octree.get_pair_count()));
  2397. */
  2398. /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
  2399. //removed, will replace with culling
  2400. /* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */
  2401. for (int i = 0; i < instance_cull_count; i++) {
  2402. Instance *ins = instance_cull_result[i];
  2403. bool keep = false;
  2404. if ((camera_layer_mask & ins->layer_mask) == 0) {
  2405. //failure
  2406. } else if (ins->base_type == VS::INSTANCE_LIGHT && ins->visible) {
  2407. if (light_cull_count < MAX_LIGHTS_CULLED) {
  2408. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  2409. if (!light->geometries.empty()) {
  2410. //do not add this light if no geometry is affected by it..
  2411. light_cull_result[light_cull_count] = ins;
  2412. light_instance_cull_result[light_cull_count] = light->instance;
  2413. if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(ins->base)) {
  2414. VSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later
  2415. }
  2416. light_cull_count++;
  2417. }
  2418. }
  2419. } else if (ins->base_type == VS::INSTANCE_REFLECTION_PROBE && ins->visible) {
  2420. if (reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) {
  2421. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data);
  2422. if (p_reflection_probe != reflection_probe->instance) {
  2423. //avoid entering The Matrix
  2424. if (!reflection_probe->geometries.empty()) {
  2425. //do not add this light if no geometry is affected by it..
  2426. if (reflection_probe->reflection_dirty || VSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) {
  2427. if (!reflection_probe->update_list.in_list()) {
  2428. reflection_probe->render_step = 0;
  2429. reflection_probe_render_list.add_last(&reflection_probe->update_list);
  2430. }
  2431. reflection_probe->reflection_dirty = false;
  2432. }
  2433. if (VSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) {
  2434. reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance;
  2435. reflection_probe_cull_count++;
  2436. }
  2437. }
  2438. }
  2439. }
  2440. } else if (ins->base_type == VS::INSTANCE_GI_PROBE && ins->visible) {
  2441. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data);
  2442. if (!gi_probe->update_element.in_list()) {
  2443. gi_probe_update_list.add(&gi_probe->update_element);
  2444. }
  2445. } else if (((1 << ins->base_type) & VS::INSTANCE_GEOMETRY_MASK) && ins->visible && ins->cast_shadows != VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  2446. keep = true;
  2447. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data);
  2448. if (ins->redraw_if_visible) {
  2449. VisualServerRaster::redraw_request(false);
  2450. }
  2451. if (ins->base_type == VS::INSTANCE_PARTICLES) {
  2452. //particles visible? process them
  2453. if (VSG::storage->particles_is_inactive(ins->base)) {
  2454. //but if nothing is going on, don't do it.
  2455. keep = false;
  2456. } else {
  2457. if (OS::get_singleton()->is_update_pending(true)) {
  2458. VSG::storage->particles_request_process(ins->base);
  2459. //particles visible? request redraw
  2460. VisualServerRaster::redraw_request(false);
  2461. }
  2462. }
  2463. }
  2464. if (geom->lighting_dirty) {
  2465. int l = 0;
  2466. //only called when lights AABB enter/exit this geometry
  2467. ins->light_instances.resize(geom->lighting.size());
  2468. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  2469. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  2470. ins->light_instances.write[l++] = light->instance;
  2471. }
  2472. geom->lighting_dirty = false;
  2473. }
  2474. if (geom->reflection_dirty) {
  2475. int l = 0;
  2476. //only called when reflection probe AABB enter/exit this geometry
  2477. ins->reflection_probe_instances.resize(geom->reflection_probes.size());
  2478. for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {
  2479. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
  2480. ins->reflection_probe_instances.write[l++] = reflection_probe->instance;
  2481. }
  2482. geom->reflection_dirty = false;
  2483. }
  2484. if (geom->gi_probes_dirty) {
  2485. int l = 0;
  2486. //only called when reflection probe AABB enter/exit this geometry
  2487. ins->gi_probe_instances.resize(geom->gi_probes.size());
  2488. for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {
  2489. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);
  2490. ins->gi_probe_instances.write[l++] = gi_probe->probe_instance;
  2491. }
  2492. geom->gi_probes_dirty = false;
  2493. }
  2494. }
  2495. if (!keep) {
  2496. // remove, no reason to keep
  2497. instance_cull_count--;
  2498. SWAP(instance_cull_result[i], instance_cull_result[instance_cull_count]);
  2499. i--;
  2500. ins->last_render_pass = 0; // make invalid
  2501. } else {
  2502. ins->last_render_pass = render_pass;
  2503. }
  2504. }
  2505. /* STEP 5 - PROCESS LIGHTS */
  2506. RID *directional_light_ptr = &light_instance_cull_result[light_cull_count];
  2507. directional_light_count = 0;
  2508. // directional lights
  2509. {
  2510. Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size());
  2511. int directional_shadow_count = 0;
  2512. for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {
  2513. if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) {
  2514. break;
  2515. }
  2516. if (!E->get()->visible) {
  2517. continue;
  2518. }
  2519. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  2520. //check shadow..
  2521. if (light) {
  2522. if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(E->get()->base)) {
  2523. lights_with_shadow[directional_shadow_count++] = E->get();
  2524. }
  2525. //add to list
  2526. directional_light_ptr[directional_light_count++] = light->instance;
  2527. }
  2528. }
  2529. VSG::scene_render->set_directional_shadow_count(directional_shadow_count);
  2530. for (int i = 0; i < directional_shadow_count; i++) {
  2531. _light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
  2532. }
  2533. }
  2534. { //setup shadow maps
  2535. //SortArray<Instance*,_InstanceLightsort> sorter;
  2536. //sorter.sort(light_cull_result,light_cull_count);
  2537. for (int i = 0; i < light_cull_count; i++) {
  2538. Instance *ins = light_cull_result[i];
  2539. if (!p_shadow_atlas.is_valid() || !VSG::storage->light_has_shadow(ins->base)) {
  2540. continue;
  2541. }
  2542. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  2543. float coverage = 0.f;
  2544. { //compute coverage
  2545. Transform cam_xf = p_cam_transform;
  2546. float zn = p_cam_projection.get_z_near();
  2547. Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane
  2548. // near plane half width and height
  2549. Vector2 vp_half_extents = p_cam_projection.get_viewport_half_extents();
  2550. switch (VSG::storage->light_get_type(ins->base)) {
  2551. case VS::LIGHT_OMNI: {
  2552. float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
  2553. //get two points parallel to near plane
  2554. Vector3 points[2] = {
  2555. ins->transform.origin,
  2556. ins->transform.origin + cam_xf.basis.get_axis(0) * radius
  2557. };
  2558. if (!p_cam_orthogonal) {
  2559. //if using perspetive, map them to near plane
  2560. for (int j = 0; j < 2; j++) {
  2561. if (p.distance_to(points[j]) < 0) {
  2562. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  2563. }
  2564. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  2565. }
  2566. }
  2567. float screen_diameter = points[0].distance_to(points[1]) * 2;
  2568. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  2569. } break;
  2570. case VS::LIGHT_SPOT: {
  2571. float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
  2572. float angle = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  2573. float w = radius * Math::sin(Math::deg2rad(angle));
  2574. float d = radius * Math::cos(Math::deg2rad(angle));
  2575. Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;
  2576. Vector3 points[2] = {
  2577. base,
  2578. base + cam_xf.basis.get_axis(0) * w
  2579. };
  2580. if (!p_cam_orthogonal) {
  2581. //if using perspetive, map them to near plane
  2582. for (int j = 0; j < 2; j++) {
  2583. if (p.distance_to(points[j]) < 0) {
  2584. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  2585. }
  2586. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  2587. }
  2588. }
  2589. float screen_diameter = points[0].distance_to(points[1]) * 2;
  2590. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  2591. } break;
  2592. default: {
  2593. ERR_PRINT("Invalid Light Type");
  2594. }
  2595. }
  2596. }
  2597. if (light->shadow_dirty) {
  2598. light->last_version++;
  2599. light->shadow_dirty = false;
  2600. }
  2601. bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
  2602. if (redraw) {
  2603. //must redraw!
  2604. light->shadow_dirty = _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
  2605. }
  2606. }
  2607. }
  2608. // Calculate instance->depth from the camera, after shadow calculation has stopped overwriting instance->depth
  2609. for (int i = 0; i < instance_cull_count; i++) {
  2610. Instance *ins = instance_cull_result[i];
  2611. if (((1 << ins->base_type) & VS::INSTANCE_GEOMETRY_MASK) && ins->visible && ins->cast_shadows != VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  2612. Vector3 center = ins->transform.origin;
  2613. if (ins->use_aabb_center) {
  2614. center = ins->transformed_aabb.position + (ins->transformed_aabb.size * 0.5);
  2615. }
  2616. if (p_cam_orthogonal) {
  2617. ins->depth = near_plane.distance_to(center) - ins->sorting_offset;
  2618. } else {
  2619. ins->depth = p_cam_transform.origin.distance_to(center) - ins->sorting_offset;
  2620. }
  2621. ins->depth_layer = CLAMP(int(ins->depth * 16 / z_far), 0, 15);
  2622. }
  2623. }
  2624. }
  2625. void VisualServerScene::_render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, const int p_eye, bool p_cam_orthogonal, RID p_force_environment, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
  2626. Scenario *scenario = scenario_owner.getornull(p_scenario);
  2627. /* ENVIRONMENT */
  2628. RID environment;
  2629. if (p_force_environment.is_valid()) { //camera has more environment priority
  2630. environment = p_force_environment;
  2631. } else if (scenario->environment.is_valid()) {
  2632. environment = scenario->environment;
  2633. } else {
  2634. environment = scenario->fallback_environment;
  2635. }
  2636. /* PROCESS GEOMETRY AND DRAW SCENE */
  2637. VSG::scene_render->render_scene(p_cam_transform, p_cam_projection, p_eye, p_cam_orthogonal, (RasterizerScene::InstanceBase **)instance_cull_result, instance_cull_count, light_instance_cull_result, light_cull_count + directional_light_count, reflection_probe_instance_cull_result, reflection_probe_cull_count, environment, p_shadow_atlas, scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass);
  2638. }
  2639. void VisualServerScene::render_empty_scene(RID p_scenario, RID p_shadow_atlas) {
  2640. #ifndef _3D_DISABLED
  2641. Scenario *scenario = scenario_owner.getornull(p_scenario);
  2642. RID environment;
  2643. if (scenario->environment.is_valid()) {
  2644. environment = scenario->environment;
  2645. } else {
  2646. environment = scenario->fallback_environment;
  2647. }
  2648. VSG::scene_render->render_scene(Transform(), CameraMatrix(), 0, true, nullptr, 0, nullptr, 0, nullptr, 0, environment, p_shadow_atlas, scenario->reflection_atlas, RID(), 0);
  2649. #endif
  2650. }
  2651. bool VisualServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) {
  2652. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  2653. Scenario *scenario = p_instance->scenario;
  2654. ERR_FAIL_COND_V(!scenario, true);
  2655. VisualServerRaster::redraw_request(false); //update, so it updates in editor
  2656. if (p_step == 0) {
  2657. if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
  2658. return true; //sorry, all full :(
  2659. }
  2660. }
  2661. if (p_step >= 0 && p_step < 6) {
  2662. static const Vector3 view_normals[6] = {
  2663. Vector3(-1, 0, 0),
  2664. Vector3(+1, 0, 0),
  2665. Vector3(0, -1, 0),
  2666. Vector3(0, +1, 0),
  2667. Vector3(0, 0, -1),
  2668. Vector3(0, 0, +1)
  2669. };
  2670. Vector3 extents = VSG::storage->reflection_probe_get_extents(p_instance->base);
  2671. Vector3 origin_offset = VSG::storage->reflection_probe_get_origin_offset(p_instance->base);
  2672. float max_distance = VSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);
  2673. Vector3 edge = view_normals[p_step] * extents;
  2674. float distance = ABS(view_normals[p_step].dot(edge) - view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit
  2675. max_distance = MAX(max_distance, distance);
  2676. //render cubemap side
  2677. CameraMatrix cm;
  2678. cm.set_perspective(90, 1, 0.01, max_distance);
  2679. static const Vector3 view_up[6] = {
  2680. Vector3(0, -1, 0),
  2681. Vector3(0, -1, 0),
  2682. Vector3(0, 0, -1),
  2683. Vector3(0, 0, +1),
  2684. Vector3(0, -1, 0),
  2685. Vector3(0, -1, 0)
  2686. };
  2687. Transform local_view;
  2688. local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
  2689. Transform xform = p_instance->transform * local_view;
  2690. RID shadow_atlas;
  2691. if (VSG::storage->reflection_probe_renders_shadows(p_instance->base)) {
  2692. shadow_atlas = scenario->reflection_probe_shadow_atlas;
  2693. }
  2694. _prepare_scene(xform, cm, false, RID(), VSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, reflection_probe->previous_room_id_hint);
  2695. bool async_forbidden_backup = VSG::storage->is_shader_async_hidden_forbidden();
  2696. VSG::storage->set_shader_async_hidden_forbidden(true);
  2697. _render_scene(xform, cm, 0, false, RID(), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step);
  2698. VSG::storage->set_shader_async_hidden_forbidden(async_forbidden_backup);
  2699. } else {
  2700. //do roughness postprocess step until it believes it's done
  2701. return VSG::scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
  2702. }
  2703. return false;
  2704. }
  2705. void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell *p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) {
  2706. if ((uint32_t)p_level == p_header->cell_subdiv - 1) {
  2707. Vector3 emission;
  2708. emission.x = (p_cell[p_idx].emission >> 24) / 255.0;
  2709. emission.y = ((p_cell[p_idx].emission >> 16) & 0xFF) / 255.0;
  2710. emission.z = ((p_cell[p_idx].emission >> 8) & 0xFF) / 255.0;
  2711. float l = (p_cell[p_idx].emission & 0xFF) / 255.0;
  2712. l *= 8.0;
  2713. emission *= l;
  2714. p_local_data[p_idx].energy[0] = uint16_t(emission.x * 1024); //go from 0 to 1024 for light
  2715. p_local_data[p_idx].energy[1] = uint16_t(emission.y * 1024); //go from 0 to 1024 for light
  2716. p_local_data[p_idx].energy[2] = uint16_t(emission.z * 1024); //go from 0 to 1024 for light
  2717. } else {
  2718. p_local_data[p_idx].energy[0] = 0;
  2719. p_local_data[p_idx].energy[1] = 0;
  2720. p_local_data[p_idx].energy[2] = 0;
  2721. int half = (1 << (p_header->cell_subdiv - 1)) >> (p_level + 1);
  2722. for (int i = 0; i < 8; i++) {
  2723. uint32_t child = p_cell[p_idx].children[i];
  2724. if (child == 0xFFFFFFFF) {
  2725. continue;
  2726. }
  2727. int x = p_x;
  2728. int y = p_y;
  2729. int z = p_z;
  2730. if (i & 1) {
  2731. x += half;
  2732. }
  2733. if (i & 2) {
  2734. y += half;
  2735. }
  2736. if (i & 4) {
  2737. z += half;
  2738. }
  2739. _gi_probe_fill_local_data(child, p_level + 1, x, y, z, p_cell, p_header, p_local_data, prev_cell);
  2740. }
  2741. }
  2742. //position for each part of the mipmaped texture
  2743. p_local_data[p_idx].pos[0] = p_x >> (p_header->cell_subdiv - p_level - 1);
  2744. p_local_data[p_idx].pos[1] = p_y >> (p_header->cell_subdiv - p_level - 1);
  2745. p_local_data[p_idx].pos[2] = p_z >> (p_header->cell_subdiv - p_level - 1);
  2746. prev_cell[p_level].push_back(p_idx);
  2747. }
  2748. void VisualServerScene::_gi_probe_bake_threads(void *self) {
  2749. VisualServerScene *vss = (VisualServerScene *)self;
  2750. vss->_gi_probe_bake_thread();
  2751. }
  2752. void VisualServerScene::_setup_gi_probe(Instance *p_instance) {
  2753. InstanceGIProbeData *probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);
  2754. if (probe->dynamic.probe_data.is_valid()) {
  2755. VSG::storage->free(probe->dynamic.probe_data);
  2756. probe->dynamic.probe_data = RID();
  2757. }
  2758. probe->dynamic.light_data = VSG::storage->gi_probe_get_dynamic_data(p_instance->base);
  2759. if (probe->dynamic.light_data.size() == 0) {
  2760. return;
  2761. }
  2762. //using dynamic data
  2763. PoolVector<int>::Read r = probe->dynamic.light_data.read();
  2764. const GIProbeDataHeader *header = (GIProbeDataHeader *)r.ptr();
  2765. probe->dynamic.local_data.resize(header->cell_count);
  2766. int cell_count = probe->dynamic.local_data.size();
  2767. PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe->dynamic.local_data.write();
  2768. const GIProbeDataCell *cells = (GIProbeDataCell *)&r[16];
  2769. probe->dynamic.level_cell_lists.resize(header->cell_subdiv);
  2770. _gi_probe_fill_local_data(0, 0, 0, 0, 0, cells, header, ldw.ptr(), probe->dynamic.level_cell_lists.ptrw());
  2771. probe->dynamic.compression = RasterizerStorage::GI_PROBE_UNCOMPRESSED;
  2772. probe->dynamic.probe_data = VSG::storage->gi_probe_dynamic_data_create(header->width, header->height, header->depth, probe->dynamic.compression);
  2773. probe->dynamic.bake_dynamic_range = VSG::storage->gi_probe_get_dynamic_range(p_instance->base);
  2774. probe->dynamic.mipmaps_3d.clear();
  2775. probe->dynamic.propagate = VSG::storage->gi_probe_get_propagation(p_instance->base);
  2776. probe->dynamic.grid_size[0] = header->width;
  2777. probe->dynamic.grid_size[1] = header->height;
  2778. probe->dynamic.grid_size[2] = header->depth;
  2779. int size_limit = 1;
  2780. int size_divisor = 1;
  2781. if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  2782. size_limit = 4;
  2783. size_divisor = 4;
  2784. }
  2785. for (int i = 0; i < (int)header->cell_subdiv; i++) {
  2786. int x = header->width >> i;
  2787. int y = header->height >> i;
  2788. int z = header->depth >> i;
  2789. //create and clear mipmap
  2790. PoolVector<uint8_t> mipmap;
  2791. int size = x * y * z * 4;
  2792. size /= size_divisor;
  2793. mipmap.resize(size);
  2794. PoolVector<uint8_t>::Write w = mipmap.write();
  2795. memset(w.ptr(), 0, size);
  2796. w.release();
  2797. probe->dynamic.mipmaps_3d.push_back(mipmap);
  2798. if (x <= size_limit || y <= size_limit || z <= size_limit) {
  2799. break;
  2800. }
  2801. }
  2802. probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
  2803. probe->invalid = false;
  2804. probe->dynamic.enabled = true;
  2805. Transform cell_to_xform = VSG::storage->gi_probe_get_to_cell_xform(p_instance->base);
  2806. AABB bounds = VSG::storage->gi_probe_get_bounds(p_instance->base);
  2807. float cell_size = VSG::storage->gi_probe_get_cell_size(p_instance->base);
  2808. probe->dynamic.light_to_cell_xform = cell_to_xform * p_instance->transform.affine_inverse();
  2809. VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance, p_instance->base, probe->dynamic.probe_data);
  2810. VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance, probe->dynamic.light_to_cell_xform);
  2811. VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance, bounds.size / cell_size);
  2812. probe->base_version = VSG::storage->gi_probe_get_version(p_instance->base);
  2813. //if compression is S3TC, fill it up
  2814. if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  2815. //create all blocks
  2816. Vector<Map<uint32_t, InstanceGIProbeData::CompBlockS3TC>> comp_blocks;
  2817. int mipmap_count = probe->dynamic.mipmaps_3d.size();
  2818. comp_blocks.resize(mipmap_count);
  2819. for (int i = 0; i < cell_count; i++) {
  2820. const GIProbeDataCell &c = cells[i];
  2821. const InstanceGIProbeData::LocalData &ld = ldw[i];
  2822. int level = c.level_alpha >> 16;
  2823. int mipmap = header->cell_subdiv - level - 1;
  2824. if (mipmap >= mipmap_count) {
  2825. continue; //uninteresting
  2826. }
  2827. int blockx = (ld.pos[0] >> 2);
  2828. int blocky = (ld.pos[1] >> 2);
  2829. int blockz = (ld.pos[2]); //compression is x/y only
  2830. int blockw = (header->width >> mipmap) >> 2;
  2831. int blockh = (header->height >> mipmap) >> 2;
  2832. //print_line("cell "+itos(i)+" level "+itos(level)+"mipmap: "+itos(mipmap)+" pos: "+Vector3(blockx,blocky,blockz)+" size "+Vector2(blockw,blockh));
  2833. uint32_t key = blockz * blockw * blockh + blocky * blockw + blockx;
  2834. Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> &cmap = comp_blocks.write[mipmap];
  2835. if (!cmap.has(key)) {
  2836. InstanceGIProbeData::CompBlockS3TC k;
  2837. k.offset = key; //use offset as counter first
  2838. k.source_count = 0;
  2839. cmap[key] = k;
  2840. }
  2841. InstanceGIProbeData::CompBlockS3TC &k = cmap[key];
  2842. ERR_CONTINUE(k.source_count == 16);
  2843. k.sources[k.source_count++] = i;
  2844. }
  2845. //fix the blocks, precomputing what is needed
  2846. probe->dynamic.mipmaps_s3tc.resize(mipmap_count);
  2847. for (int i = 0; i < mipmap_count; i++) {
  2848. //print_line("S3TC level: " + itos(i) + " blocks: " + itos(comp_blocks[i].size()));
  2849. probe->dynamic.mipmaps_s3tc.write[i].resize(comp_blocks[i].size());
  2850. PoolVector<InstanceGIProbeData::CompBlockS3TC>::Write w = probe->dynamic.mipmaps_s3tc.write[i].write();
  2851. int block_idx = 0;
  2852. for (Map<uint32_t, InstanceGIProbeData::CompBlockS3TC>::Element *E = comp_blocks[i].front(); E; E = E->next()) {
  2853. InstanceGIProbeData::CompBlockS3TC k = E->get();
  2854. //PRECOMPUTE ALPHA
  2855. int max_alpha = -100000;
  2856. int min_alpha = k.source_count == 16 ? 100000 : 0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero)
  2857. uint8_t alpha_block[4][4] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };
  2858. for (uint32_t j = 0; j < k.source_count; j++) {
  2859. int alpha = (cells[k.sources[j]].level_alpha >> 8) & 0xFF;
  2860. if (alpha < min_alpha) {
  2861. min_alpha = alpha;
  2862. }
  2863. if (alpha > max_alpha) {
  2864. max_alpha = alpha;
  2865. }
  2866. //fill up alpha block
  2867. alpha_block[ldw[k.sources[j]].pos[0] % 4][ldw[k.sources[j]].pos[1] % 4] = alpha;
  2868. }
  2869. //use the first mode (8 adjustable levels)
  2870. k.alpha[0] = max_alpha;
  2871. k.alpha[1] = min_alpha;
  2872. uint64_t alpha_bits = 0;
  2873. if (max_alpha != min_alpha) {
  2874. int idx = 0;
  2875. for (int y = 0; y < 4; y++) {
  2876. for (int x = 0; x < 4; x++) {
  2877. //subtract minimum
  2878. uint32_t a = uint32_t(alpha_block[x][y]) - min_alpha;
  2879. //convert range to 3 bits
  2880. a = int((a * 7.0 / (max_alpha - min_alpha)) + 0.5);
  2881. a = MIN(a, 7); //just to be sure
  2882. a = 7 - a; //because range is inverted in this mode
  2883. if (a == 0) {
  2884. //do none, remain
  2885. } else if (a == 7) {
  2886. a = 1;
  2887. } else {
  2888. a = a + 1;
  2889. }
  2890. alpha_bits |= uint64_t(a) << (idx * 3);
  2891. idx++;
  2892. }
  2893. }
  2894. }
  2895. k.alpha[2] = (alpha_bits >> 0) & 0xFF;
  2896. k.alpha[3] = (alpha_bits >> 8) & 0xFF;
  2897. k.alpha[4] = (alpha_bits >> 16) & 0xFF;
  2898. k.alpha[5] = (alpha_bits >> 24) & 0xFF;
  2899. k.alpha[6] = (alpha_bits >> 32) & 0xFF;
  2900. k.alpha[7] = (alpha_bits >> 40) & 0xFF;
  2901. w[block_idx++] = k;
  2902. }
  2903. }
  2904. }
  2905. }
  2906. void VisualServerScene::_gi_probe_bake_thread() {
  2907. while (true) {
  2908. probe_bake_sem.wait();
  2909. if (probe_bake_thread_exit) {
  2910. break;
  2911. }
  2912. Instance *to_bake = nullptr;
  2913. probe_bake_mutex.lock();
  2914. if (!probe_bake_list.empty()) {
  2915. to_bake = probe_bake_list.front()->get();
  2916. probe_bake_list.pop_front();
  2917. }
  2918. probe_bake_mutex.unlock();
  2919. if (!to_bake) {
  2920. continue;
  2921. }
  2922. _bake_gi_probe(to_bake);
  2923. }
  2924. }
  2925. uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv) {
  2926. uint32_t cell = 0;
  2927. int ofs_x = 0;
  2928. int ofs_y = 0;
  2929. int ofs_z = 0;
  2930. int size = 1 << (p_cell_subdiv - 1);
  2931. int half = size / 2;
  2932. if (x < 0 || x >= size) {
  2933. return -1;
  2934. }
  2935. if (y < 0 || y >= size) {
  2936. return -1;
  2937. }
  2938. if (z < 0 || z >= size) {
  2939. return -1;
  2940. }
  2941. for (int i = 0; i < p_cell_subdiv - 1; i++) {
  2942. const GIProbeDataCell *bc = &cells[cell];
  2943. int child = 0;
  2944. if (x >= ofs_x + half) {
  2945. child |= 1;
  2946. ofs_x += half;
  2947. }
  2948. if (y >= ofs_y + half) {
  2949. child |= 2;
  2950. ofs_y += half;
  2951. }
  2952. if (z >= ofs_z + half) {
  2953. child |= 4;
  2954. ofs_z += half;
  2955. }
  2956. cell = bc->children[child];
  2957. if (cell == 0xFFFFFFFF) {
  2958. return 0xFFFFFFFF;
  2959. }
  2960. half >>= 1;
  2961. }
  2962. return cell;
  2963. }
  2964. static float _get_normal_advance(const Vector3 &p_normal) {
  2965. Vector3 normal = p_normal;
  2966. Vector3 unorm = normal.abs();
  2967. if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
  2968. // x code
  2969. unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0);
  2970. } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
  2971. // y code
  2972. unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0);
  2973. } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
  2974. // z code
  2975. unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0);
  2976. } else {
  2977. // oh-no we messed up code
  2978. // has to be
  2979. unorm = Vector3(1.0, 0.0, 0.0);
  2980. }
  2981. return 1.0 / normal.dot(unorm);
  2982. }
  2983. void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header, const GIProbeDataCell *cells, InstanceGIProbeData::LocalData *local_data, const uint32_t *leaves, int p_leaf_count, const InstanceGIProbeData::LightCache &light_cache, int p_sign) {
  2984. int light_r = int(light_cache.color.r * light_cache.energy * 1024.0) * p_sign;
  2985. int light_g = int(light_cache.color.g * light_cache.energy * 1024.0) * p_sign;
  2986. int light_b = int(light_cache.color.b * light_cache.energy * 1024.0) * p_sign;
  2987. float limits[3] = { float(header->width), float(header->height), float(header->depth) };
  2988. Plane clip[3];
  2989. int clip_planes = 0;
  2990. switch (light_cache.type) {
  2991. case VS::LIGHT_DIRECTIONAL: {
  2992. float max_len = Vector3(limits[0], limits[1], limits[2]).length() * 1.1;
  2993. Vector3 light_axis = -light_cache.transform.basis.get_axis(2).normalized();
  2994. for (int i = 0; i < 3; i++) {
  2995. if (Math::is_zero_approx(light_axis[i])) {
  2996. continue;
  2997. }
  2998. clip[clip_planes].normal[i] = 1.0;
  2999. if (light_axis[i] < 0) {
  3000. clip[clip_planes].d = limits[i] + 1;
  3001. } else {
  3002. clip[clip_planes].d -= 1.0;
  3003. }
  3004. clip_planes++;
  3005. }
  3006. float distance_adv = _get_normal_advance(light_axis);
  3007. for (int i = 0; i < p_leaf_count; i++) {
  3008. uint32_t idx = leaves[i];
  3009. const GIProbeDataCell *cell = &cells[idx];
  3010. InstanceGIProbeData::LocalData *light = &local_data[idx];
  3011. Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
  3012. to += -light_axis.sign() * 0.47; //make it more likely to receive a ray
  3013. Vector3 norm(
  3014. (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
  3015. (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
  3016. (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
  3017. float att = norm.dot(-light_axis);
  3018. if (att < 0.001) {
  3019. //not lighting towards this
  3020. continue;
  3021. }
  3022. Vector3 from = to - max_len * light_axis;
  3023. for (int j = 0; j < clip_planes; j++) {
  3024. clip[j].intersects_segment(from, to, &from);
  3025. }
  3026. float distance = (to - from).length();
  3027. distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always
  3028. from = to - light_axis * distance;
  3029. uint32_t result = 0xFFFFFFFF;
  3030. while (distance > -distance_adv) { //use this to avoid precision errors
  3031. result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
  3032. if (result != 0xFFFFFFFF) {
  3033. break;
  3034. }
  3035. from += light_axis * distance_adv;
  3036. distance -= distance_adv;
  3037. }
  3038. if (result == idx) {
  3039. //cell hit itself! hooray!
  3040. light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
  3041. light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
  3042. light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
  3043. }
  3044. }
  3045. } break;
  3046. case VS::LIGHT_OMNI:
  3047. case VS::LIGHT_SPOT: {
  3048. Vector3 light_pos = light_cache.transform.origin;
  3049. Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized();
  3050. float local_radius = light_cache.radius * light_cache.transform.basis.get_axis(2).length();
  3051. for (int i = 0; i < p_leaf_count; i++) {
  3052. uint32_t idx = leaves[i];
  3053. const GIProbeDataCell *cell = &cells[idx];
  3054. InstanceGIProbeData::LocalData *light = &local_data[idx];
  3055. Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
  3056. to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
  3057. Vector3 norm(
  3058. (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
  3059. (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
  3060. (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
  3061. Vector3 light_axis = (to - light_pos).normalized();
  3062. float distance_adv = _get_normal_advance(light_axis);
  3063. float att = norm.dot(-light_axis);
  3064. if (att < 0.001) {
  3065. //not lighting towards this
  3066. continue;
  3067. }
  3068. {
  3069. float d = light_pos.distance_to(to);
  3070. if (d + distance_adv > local_radius) {
  3071. continue; // too far away
  3072. }
  3073. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  3074. att *= powf(1.0 - dt, light_cache.attenuation);
  3075. }
  3076. if (light_cache.type == VS::LIGHT_SPOT) {
  3077. float angle = Math::rad2deg(acos(light_axis.dot(spot_axis)));
  3078. if (angle > light_cache.spot_angle) {
  3079. continue;
  3080. }
  3081. float d = CLAMP(angle / light_cache.spot_angle, 0, 1);
  3082. att *= powf(1.0 - d, light_cache.spot_attenuation);
  3083. }
  3084. clip_planes = 0;
  3085. for (int c = 0; c < 3; c++) {
  3086. if (Math::is_zero_approx(light_axis[c])) {
  3087. continue;
  3088. }
  3089. clip[clip_planes].normal[c] = 1.0;
  3090. if (light_axis[c] < 0) {
  3091. clip[clip_planes].d = limits[c] + 1;
  3092. } else {
  3093. clip[clip_planes].d -= 1.0;
  3094. }
  3095. clip_planes++;
  3096. }
  3097. Vector3 from = light_pos;
  3098. for (int j = 0; j < clip_planes; j++) {
  3099. clip[j].intersects_segment(from, to, &from);
  3100. }
  3101. float distance = (to - from).length();
  3102. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  3103. from = to - light_axis * distance;
  3104. uint32_t result = 0xFFFFFFFF;
  3105. while (distance > -distance_adv) { //use this to avoid precision errors
  3106. result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
  3107. if (result != 0xFFFFFFFF) {
  3108. break;
  3109. }
  3110. from += light_axis * distance_adv;
  3111. distance -= distance_adv;
  3112. }
  3113. if (result == idx) {
  3114. //cell hit itself! hooray!
  3115. light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
  3116. light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
  3117. light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
  3118. }
  3119. }
  3120. } break;
  3121. }
  3122. }
  3123. void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell *p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate) {
  3124. //average light to upper level
  3125. float divisor = 0;
  3126. float sum[3] = { 0.0, 0.0, 0.0 };
  3127. for (int i = 0; i < 8; i++) {
  3128. uint32_t child = p_cells[p_idx].children[i];
  3129. if (child == 0xFFFFFFFF) {
  3130. continue;
  3131. }
  3132. if (p_level + 1 < (int)p_header->cell_subdiv - 1) {
  3133. _bake_gi_downscale_light(child, p_level + 1, p_cells, p_header, p_local_data, p_propagate);
  3134. }
  3135. sum[0] += p_local_data[child].energy[0];
  3136. sum[1] += p_local_data[child].energy[1];
  3137. sum[2] += p_local_data[child].energy[2];
  3138. divisor += 1.0;
  3139. }
  3140. divisor = Math::lerp((float)8.0, divisor, p_propagate);
  3141. sum[0] /= divisor;
  3142. sum[1] /= divisor;
  3143. sum[2] /= divisor;
  3144. //divide by eight for average
  3145. p_local_data[p_idx].energy[0] = Math::fast_ftoi(sum[0]);
  3146. p_local_data[p_idx].energy[1] = Math::fast_ftoi(sum[1]);
  3147. p_local_data[p_idx].energy[2] = Math::fast_ftoi(sum[2]);
  3148. }
  3149. void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) {
  3150. InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
  3151. PoolVector<int>::Read r = probe_data->dynamic.light_data.read();
  3152. const GIProbeDataHeader *header = (const GIProbeDataHeader *)r.ptr();
  3153. const GIProbeDataCell *cells = (const GIProbeDataCell *)&r[16];
  3154. int leaf_count = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].size();
  3155. const uint32_t *leaves = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].ptr();
  3156. PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe_data->dynamic.local_data.write();
  3157. InstanceGIProbeData::LocalData *local_data = ldw.ptr();
  3158. //remove what must be removed
  3159. for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache.front(); E; E = E->next()) {
  3160. RID rid = E->key();
  3161. const InstanceGIProbeData::LightCache &lc = E->get();
  3162. if ((!probe_data->dynamic.light_cache_changes.has(rid) || probe_data->dynamic.light_cache_changes[rid] != lc) && lc.visible) {
  3163. //erase light data
  3164. _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, -1);
  3165. }
  3166. }
  3167. //add what must be added
  3168. for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache_changes.front(); E; E = E->next()) {
  3169. RID rid = E->key();
  3170. const InstanceGIProbeData::LightCache &lc = E->get();
  3171. if ((!probe_data->dynamic.light_cache.has(rid) || probe_data->dynamic.light_cache[rid] != lc) && lc.visible) {
  3172. //add light data
  3173. _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, 1);
  3174. }
  3175. }
  3176. SWAP(probe_data->dynamic.light_cache_changes, probe_data->dynamic.light_cache);
  3177. //downscale to lower res levels
  3178. _bake_gi_downscale_light(0, 0, cells, header, local_data, probe_data->dynamic.propagate);
  3179. //plot result to 3D texture!
  3180. if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_UNCOMPRESSED) {
  3181. for (int i = 0; i < (int)header->cell_subdiv; i++) {
  3182. int stage = header->cell_subdiv - i - 1;
  3183. if (stage >= probe_data->dynamic.mipmaps_3d.size()) {
  3184. continue; //no mipmap for this one
  3185. }
  3186. //print_line("generating mipmap stage: " + itos(stage));
  3187. int level_cell_count = probe_data->dynamic.level_cell_lists[i].size();
  3188. const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[i].ptr();
  3189. PoolVector<uint8_t>::Write lw = probe_data->dynamic.mipmaps_3d.write[stage].write();
  3190. uint8_t *mipmapw = lw.ptr();
  3191. uint32_t sizes[3] = { header->width >> stage, header->height >> stage, header->depth >> stage };
  3192. for (int j = 0; j < level_cell_count; j++) {
  3193. uint32_t idx = level_cells[j];
  3194. uint32_t r2 = (uint32_t(local_data[idx].energy[0]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  3195. uint32_t g = (uint32_t(local_data[idx].energy[1]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  3196. uint32_t b = (uint32_t(local_data[idx].energy[2]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  3197. uint32_t a = (cells[idx].level_alpha >> 8) & 0xFF;
  3198. uint32_t mm_ofs = sizes[0] * sizes[1] * (local_data[idx].pos[2]) + sizes[0] * (local_data[idx].pos[1]) + (local_data[idx].pos[0]);
  3199. mm_ofs *= 4; //for RGBA (4 bytes)
  3200. mipmapw[mm_ofs + 0] = uint8_t(MIN(r2, 255));
  3201. mipmapw[mm_ofs + 1] = uint8_t(MIN(g, 255));
  3202. mipmapw[mm_ofs + 2] = uint8_t(MIN(b, 255));
  3203. mipmapw[mm_ofs + 3] = uint8_t(MIN(a, 255));
  3204. }
  3205. }
  3206. } else if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  3207. int mipmap_count = probe_data->dynamic.mipmaps_3d.size();
  3208. for (int mmi = 0; mmi < mipmap_count; mmi++) {
  3209. PoolVector<uint8_t>::Write mmw = probe_data->dynamic.mipmaps_3d.write[mmi].write();
  3210. int block_count = probe_data->dynamic.mipmaps_s3tc[mmi].size();
  3211. PoolVector<InstanceGIProbeData::CompBlockS3TC>::Read mmr = probe_data->dynamic.mipmaps_s3tc[mmi].read();
  3212. for (int i = 0; i < block_count; i++) {
  3213. const InstanceGIProbeData::CompBlockS3TC &b = mmr[i];
  3214. uint8_t *blockptr = &mmw[b.offset * 16];
  3215. memcpy(blockptr, b.alpha, 8); //copy alpha part, which is precomputed
  3216. Vector3 colors[16];
  3217. for (uint32_t j = 0; j < b.source_count; j++) {
  3218. colors[j].x = (local_data[b.sources[j]].energy[0] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  3219. colors[j].y = (local_data[b.sources[j]].energy[1] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  3220. colors[j].z = (local_data[b.sources[j]].energy[2] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  3221. }
  3222. //super quick and dirty compression
  3223. //find 2 most further apart
  3224. float distance = 0;
  3225. Vector3 from, to;
  3226. if (b.source_count == 16) {
  3227. //all cells are used so, find minmax between them
  3228. int further_apart[2] = { 0, 0 };
  3229. for (uint32_t j = 0; j < b.source_count; j++) {
  3230. for (uint32_t k = j + 1; k < b.source_count; k++) {
  3231. float d = colors[j].distance_squared_to(colors[k]);
  3232. if (d > distance) {
  3233. distance = d;
  3234. further_apart[0] = j;
  3235. further_apart[1] = k;
  3236. }
  3237. }
  3238. }
  3239. from = colors[further_apart[0]];
  3240. to = colors[further_apart[1]];
  3241. } else {
  3242. //if a block is missing, the priority is that this block remains black,
  3243. //otherwise the geometry will appear deformed
  3244. //correct shape wins over correct color in this case
  3245. //average all colors first
  3246. Vector3 average;
  3247. for (uint32_t j = 0; j < b.source_count; j++) {
  3248. average += colors[j];
  3249. }
  3250. average.normalize();
  3251. //find max distance in normal from average
  3252. for (uint32_t j = 0; j < b.source_count; j++) {
  3253. float d = average.dot(colors[j]);
  3254. distance = MAX(d, distance);
  3255. }
  3256. from = Vector3(); //from black
  3257. to = average * distance;
  3258. //find max distance
  3259. }
  3260. int indices[16];
  3261. uint16_t color_0 = 0;
  3262. color_0 = CLAMP(int(from.x * 31), 0, 31) << 11;
  3263. color_0 |= CLAMP(int(from.y * 63), 0, 63) << 5;
  3264. color_0 |= CLAMP(int(from.z * 31), 0, 31);
  3265. uint16_t color_1 = 0;
  3266. color_1 = CLAMP(int(to.x * 31), 0, 31) << 11;
  3267. color_1 |= CLAMP(int(to.y * 63), 0, 63) << 5;
  3268. color_1 |= CLAMP(int(to.z * 31), 0, 31);
  3269. if (color_1 > color_0) {
  3270. SWAP(color_1, color_0);
  3271. SWAP(from, to);
  3272. }
  3273. if (distance > 0) {
  3274. Vector3 dir = (to - from).normalized();
  3275. for (uint32_t j = 0; j < b.source_count; j++) {
  3276. float d = (colors[j] - from).dot(dir) / distance;
  3277. indices[j] = int(d * 3 + 0.5);
  3278. static const int index_swap[4] = { 0, 3, 1, 2 };
  3279. indices[j] = index_swap[CLAMP(indices[j], 0, 3)];
  3280. }
  3281. } else {
  3282. for (uint32_t j = 0; j < b.source_count; j++) {
  3283. indices[j] = 0;
  3284. }
  3285. }
  3286. //by default, 1 is black, otherwise it will be overridden by source
  3287. uint32_t index_block[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
  3288. for (uint32_t j = 0; j < b.source_count; j++) {
  3289. int x = local_data[b.sources[j]].pos[0] % 4;
  3290. int y = local_data[b.sources[j]].pos[1] % 4;
  3291. index_block[y * 4 + x] = indices[j];
  3292. }
  3293. uint32_t encode = 0;
  3294. for (int j = 0; j < 16; j++) {
  3295. encode |= index_block[j] << (j * 2);
  3296. }
  3297. blockptr[8] = color_0 & 0xFF;
  3298. blockptr[9] = (color_0 >> 8) & 0xFF;
  3299. blockptr[10] = color_1 & 0xFF;
  3300. blockptr[11] = (color_1 >> 8) & 0xFF;
  3301. blockptr[12] = encode & 0xFF;
  3302. blockptr[13] = (encode >> 8) & 0xFF;
  3303. blockptr[14] = (encode >> 16) & 0xFF;
  3304. blockptr[15] = (encode >> 24) & 0xFF;
  3305. }
  3306. }
  3307. }
  3308. //send back to main thread to update un little chunks
  3309. probe_bake_mutex.lock();
  3310. probe_data->dynamic.updating_stage = GI_UPDATE_STAGE_UPLOADING;
  3311. probe_bake_mutex.unlock();
  3312. }
  3313. bool VisualServerScene::_check_gi_probe(Instance *p_gi_probe) {
  3314. InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
  3315. probe_data->dynamic.light_cache_changes.clear();
  3316. bool all_equal = true;
  3317. for (List<Instance *>::Element *E = p_gi_probe->scenario->directional_lights.front(); E; E = E->next()) {
  3318. if (VSG::storage->light_get_bake_mode(E->get()->base) == VS::LightBakeMode::LIGHT_BAKE_DISABLED) {
  3319. continue;
  3320. }
  3321. InstanceGIProbeData::LightCache lc;
  3322. lc.type = VSG::storage->light_get_type(E->get()->base);
  3323. lc.color = VSG::storage->light_get_color(E->get()->base);
  3324. lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY) * VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_INDIRECT_ENERGY);
  3325. lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
  3326. lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
  3327. lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  3328. lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
  3329. lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
  3330. lc.visible = E->get()->visible;
  3331. if (!probe_data->dynamic.light_cache.has(E->get()->self) || probe_data->dynamic.light_cache[E->get()->self] != lc) {
  3332. all_equal = false;
  3333. }
  3334. probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
  3335. }
  3336. for (Set<Instance *>::Element *E = probe_data->lights.front(); E; E = E->next()) {
  3337. if (VSG::storage->light_get_bake_mode(E->get()->base) == VS::LightBakeMode::LIGHT_BAKE_DISABLED) {
  3338. continue;
  3339. }
  3340. InstanceGIProbeData::LightCache lc;
  3341. lc.type = VSG::storage->light_get_type(E->get()->base);
  3342. lc.color = VSG::storage->light_get_color(E->get()->base);
  3343. lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY) * VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_INDIRECT_ENERGY);
  3344. lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
  3345. lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
  3346. lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  3347. lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
  3348. lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
  3349. lc.visible = E->get()->visible;
  3350. if (!probe_data->dynamic.light_cache.has(E->get()->self) || probe_data->dynamic.light_cache[E->get()->self] != lc) {
  3351. all_equal = false;
  3352. }
  3353. probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
  3354. }
  3355. //lighting changed from after to before, must do some updating
  3356. return !all_equal || probe_data->dynamic.light_cache_changes.size() != probe_data->dynamic.light_cache.size();
  3357. }
  3358. void VisualServerScene::render_probes() {
  3359. /* REFLECTION PROBES */
  3360. SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
  3361. bool busy = false;
  3362. while (ref_probe) {
  3363. SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
  3364. RID base = ref_probe->self()->owner->base;
  3365. switch (VSG::storage->reflection_probe_get_update_mode(base)) {
  3366. case VS::REFLECTION_PROBE_UPDATE_ONCE: {
  3367. if (busy) { //already rendering something
  3368. break;
  3369. }
  3370. bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
  3371. if (done) {
  3372. reflection_probe_render_list.remove(ref_probe);
  3373. } else {
  3374. ref_probe->self()->render_step++;
  3375. }
  3376. busy = true; //do not render another one of this kind
  3377. } break;
  3378. case VS::REFLECTION_PROBE_UPDATE_ALWAYS: {
  3379. int step = 0;
  3380. bool done = false;
  3381. while (!done) {
  3382. done = _render_reflection_probe_step(ref_probe->self()->owner, step);
  3383. step++;
  3384. }
  3385. reflection_probe_render_list.remove(ref_probe);
  3386. } break;
  3387. }
  3388. ref_probe = next;
  3389. }
  3390. /* GI PROBES */
  3391. SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();
  3392. while (gi_probe) {
  3393. SelfList<InstanceGIProbeData> *next = gi_probe->next();
  3394. InstanceGIProbeData *probe = gi_probe->self();
  3395. Instance *instance_probe = probe->owner;
  3396. //check if probe must be setup, but don't do if on the lighting thread
  3397. bool force_lighting = false;
  3398. if (probe->invalid || (probe->dynamic.updating_stage == GI_UPDATE_STAGE_CHECK && probe->base_version != VSG::storage->gi_probe_get_version(instance_probe->base))) {
  3399. _setup_gi_probe(instance_probe);
  3400. force_lighting = true;
  3401. }
  3402. float propagate = VSG::storage->gi_probe_get_propagation(instance_probe->base);
  3403. if (probe->dynamic.propagate != propagate) {
  3404. probe->dynamic.propagate = propagate;
  3405. force_lighting = true;
  3406. }
  3407. if (!probe->invalid && probe->dynamic.enabled) {
  3408. switch (probe->dynamic.updating_stage) {
  3409. case GI_UPDATE_STAGE_CHECK: {
  3410. if (_check_gi_probe(instance_probe) || force_lighting) { //send to lighting thread
  3411. #ifndef NO_THREADS
  3412. probe_bake_mutex.lock();
  3413. probe->dynamic.updating_stage = GI_UPDATE_STAGE_LIGHTING;
  3414. probe_bake_list.push_back(instance_probe);
  3415. probe_bake_mutex.unlock();
  3416. probe_bake_sem.post();
  3417. #else
  3418. _bake_gi_probe(instance_probe);
  3419. #endif
  3420. }
  3421. } break;
  3422. case GI_UPDATE_STAGE_LIGHTING: {
  3423. //do none, wait til done!
  3424. } break;
  3425. case GI_UPDATE_STAGE_UPLOADING: {
  3426. //uint64_t us = OS::get_singleton()->get_ticks_usec();
  3427. for (int i = 0; i < (int)probe->dynamic.mipmaps_3d.size(); i++) {
  3428. PoolVector<uint8_t>::Read r = probe->dynamic.mipmaps_3d[i].read();
  3429. VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data, 0, probe->dynamic.grid_size[2] >> i, i, r.ptr());
  3430. }
  3431. probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
  3432. //print_line("UPLOAD TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
  3433. } break;
  3434. }
  3435. }
  3436. //_update_gi_probe(gi_probe->self()->owner);
  3437. gi_probe = next;
  3438. }
  3439. }
  3440. void VisualServerScene::_update_dirty_instance(Instance *p_instance) {
  3441. if (p_instance->update_aabb) {
  3442. _update_instance_aabb(p_instance);
  3443. }
  3444. if (p_instance->update_materials) {
  3445. if (p_instance->base_type == VS::INSTANCE_MESH) {
  3446. //remove materials no longer used and un-own them
  3447. int new_mat_count = VSG::storage->mesh_get_surface_count(p_instance->base);
  3448. for (int i = p_instance->materials.size() - 1; i >= new_mat_count; i--) {
  3449. if (p_instance->materials[i].is_valid()) {
  3450. VSG::storage->material_remove_instance_owner(p_instance->materials[i], p_instance);
  3451. }
  3452. }
  3453. p_instance->materials.resize(new_mat_count);
  3454. int new_blend_shape_count = VSG::storage->mesh_get_blend_shape_count(p_instance->base);
  3455. if (new_blend_shape_count != p_instance->blend_values.size()) {
  3456. p_instance->blend_values.resize(new_blend_shape_count);
  3457. for (int i = 0; i < new_blend_shape_count; i++) {
  3458. p_instance->blend_values.write().ptr()[i] = 0;
  3459. }
  3460. }
  3461. }
  3462. if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  3463. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  3464. bool can_cast_shadows = true;
  3465. bool is_animated = false;
  3466. if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_OFF) {
  3467. can_cast_shadows = false;
  3468. } else if (p_instance->material_override.is_valid()) {
  3469. can_cast_shadows = VSG::storage->material_casts_shadows(p_instance->material_override);
  3470. is_animated = VSG::storage->material_is_animated(p_instance->material_override);
  3471. } else {
  3472. if (p_instance->base_type == VS::INSTANCE_MESH) {
  3473. RID mesh = p_instance->base;
  3474. if (mesh.is_valid()) {
  3475. bool cast_shadows = false;
  3476. for (int i = 0; i < p_instance->materials.size(); i++) {
  3477. RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : VSG::storage->mesh_surface_get_material(mesh, i);
  3478. if (!mat.is_valid()) {
  3479. cast_shadows = true;
  3480. } else {
  3481. if (VSG::storage->material_casts_shadows(mat)) {
  3482. cast_shadows = true;
  3483. }
  3484. if (VSG::storage->material_is_animated(mat)) {
  3485. is_animated = true;
  3486. }
  3487. }
  3488. }
  3489. if (!cast_shadows) {
  3490. can_cast_shadows = false;
  3491. }
  3492. }
  3493. } else if (p_instance->base_type == VS::INSTANCE_MULTIMESH) {
  3494. RID mesh = VSG::storage->multimesh_get_mesh(p_instance->base);
  3495. if (mesh.is_valid()) {
  3496. bool cast_shadows = false;
  3497. int sc = VSG::storage->mesh_get_surface_count(mesh);
  3498. for (int i = 0; i < sc; i++) {
  3499. RID mat = VSG::storage->mesh_surface_get_material(mesh, i);
  3500. if (!mat.is_valid()) {
  3501. cast_shadows = true;
  3502. } else {
  3503. if (VSG::storage->material_casts_shadows(mat)) {
  3504. cast_shadows = true;
  3505. }
  3506. if (VSG::storage->material_is_animated(mat)) {
  3507. is_animated = true;
  3508. }
  3509. }
  3510. }
  3511. if (!cast_shadows) {
  3512. can_cast_shadows = false;
  3513. }
  3514. }
  3515. } else if (p_instance->base_type == VS::INSTANCE_IMMEDIATE) {
  3516. RID mat = VSG::storage->immediate_get_material(p_instance->base);
  3517. can_cast_shadows = !mat.is_valid() || VSG::storage->material_casts_shadows(mat);
  3518. if (mat.is_valid() && VSG::storage->material_is_animated(mat)) {
  3519. is_animated = true;
  3520. }
  3521. } else if (p_instance->base_type == VS::INSTANCE_PARTICLES) {
  3522. bool cast_shadows = false;
  3523. int dp = VSG::storage->particles_get_draw_passes(p_instance->base);
  3524. for (int i = 0; i < dp; i++) {
  3525. RID mesh = VSG::storage->particles_get_draw_pass_mesh(p_instance->base, i);
  3526. if (!mesh.is_valid()) {
  3527. continue;
  3528. }
  3529. int sc = VSG::storage->mesh_get_surface_count(mesh);
  3530. for (int j = 0; j < sc; j++) {
  3531. RID mat = VSG::storage->mesh_surface_get_material(mesh, j);
  3532. if (!mat.is_valid()) {
  3533. cast_shadows = true;
  3534. } else {
  3535. if (VSG::storage->material_casts_shadows(mat)) {
  3536. cast_shadows = true;
  3537. }
  3538. if (VSG::storage->material_is_animated(mat)) {
  3539. is_animated = true;
  3540. }
  3541. }
  3542. }
  3543. }
  3544. if (!cast_shadows) {
  3545. can_cast_shadows = false;
  3546. }
  3547. }
  3548. }
  3549. if (p_instance->material_overlay.is_valid()) {
  3550. can_cast_shadows = can_cast_shadows || VSG::storage->material_casts_shadows(p_instance->material_overlay);
  3551. is_animated = is_animated || VSG::storage->material_is_animated(p_instance->material_overlay);
  3552. }
  3553. if (can_cast_shadows != geom->can_cast_shadows) {
  3554. //ability to cast shadows change, let lights now
  3555. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  3556. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  3557. light->shadow_dirty = true;
  3558. }
  3559. geom->can_cast_shadows = can_cast_shadows;
  3560. }
  3561. geom->material_is_animated = is_animated;
  3562. }
  3563. }
  3564. _instance_update_list.remove(&p_instance->update_item);
  3565. _update_instance(p_instance);
  3566. p_instance->update_aabb = false;
  3567. p_instance->update_materials = false;
  3568. }
  3569. void VisualServerScene::update_dirty_instances() {
  3570. VSG::storage->update_dirty_resources();
  3571. // this is just to get access to scenario so we can update the spatial partitioning scheme
  3572. Scenario *scenario = nullptr;
  3573. if (_instance_update_list.first()) {
  3574. scenario = _instance_update_list.first()->self()->scenario;
  3575. }
  3576. while (_instance_update_list.first()) {
  3577. _update_dirty_instance(_instance_update_list.first()->self());
  3578. }
  3579. if (scenario) {
  3580. scenario->sps->update();
  3581. }
  3582. }
  3583. bool VisualServerScene::free(RID p_rid) {
  3584. if (camera_owner.owns(p_rid)) {
  3585. Camera *camera = camera_owner.get(p_rid);
  3586. _interpolation_data.notify_free_camera(p_rid, *camera);
  3587. camera_owner.free(p_rid);
  3588. memdelete(camera);
  3589. } else if (scenario_owner.owns(p_rid)) {
  3590. Scenario *scenario = scenario_owner.get(p_rid);
  3591. while (scenario->instances.first()) {
  3592. instance_set_scenario(scenario->instances.first()->self()->self, RID());
  3593. }
  3594. VSG::scene_render->free(scenario->reflection_probe_shadow_atlas);
  3595. VSG::scene_render->free(scenario->reflection_atlas);
  3596. scenario_owner.free(p_rid);
  3597. memdelete(scenario);
  3598. } else if (instance_owner.owns(p_rid)) {
  3599. // delete the instance
  3600. update_dirty_instances();
  3601. Instance *instance = instance_owner.get(p_rid);
  3602. _interpolation_data.notify_free_instance(p_rid, *instance);
  3603. instance_set_use_lightmap(p_rid, RID(), RID(), -1, Rect2(0, 0, 1, 1));
  3604. instance_set_scenario(p_rid, RID());
  3605. instance_set_base(p_rid, RID());
  3606. instance_geometry_set_material_override(p_rid, RID());
  3607. instance_geometry_set_material_overlay(p_rid, RID());
  3608. instance_attach_skeleton(p_rid, RID());
  3609. update_dirty_instances(); //in case something changed this
  3610. instance_owner.free(p_rid);
  3611. memdelete(instance);
  3612. } else if (room_owner.owns(p_rid)) {
  3613. Room *room = room_owner.get(p_rid);
  3614. room_owner.free(p_rid);
  3615. memdelete(room);
  3616. } else if (portal_owner.owns(p_rid)) {
  3617. Portal *portal = portal_owner.get(p_rid);
  3618. portal_owner.free(p_rid);
  3619. memdelete(portal);
  3620. } else if (ghost_owner.owns(p_rid)) {
  3621. Ghost *ghost = ghost_owner.get(p_rid);
  3622. ghost_owner.free(p_rid);
  3623. memdelete(ghost);
  3624. } else if (roomgroup_owner.owns(p_rid)) {
  3625. RoomGroup *roomgroup = roomgroup_owner.get(p_rid);
  3626. roomgroup_owner.free(p_rid);
  3627. memdelete(roomgroup);
  3628. } else if (occluder_instance_owner.owns(p_rid)) {
  3629. OccluderInstance *occ_inst = occluder_instance_owner.get(p_rid);
  3630. occluder_instance_owner.free(p_rid);
  3631. memdelete(occ_inst);
  3632. } else if (occluder_resource_owner.owns(p_rid)) {
  3633. OccluderResource *occ_res = occluder_resource_owner.get(p_rid);
  3634. occ_res->destroy(_portal_resources);
  3635. occluder_resource_owner.free(p_rid);
  3636. memdelete(occ_res);
  3637. } else {
  3638. return false;
  3639. }
  3640. return true;
  3641. }
  3642. VisualServerScene *VisualServerScene::singleton = nullptr;
  3643. VisualServerScene::VisualServerScene() {
  3644. probe_bake_thread.start(_gi_probe_bake_threads, this);
  3645. probe_bake_thread_exit = false;
  3646. render_pass = 1;
  3647. singleton = this;
  3648. _use_bvh = GLOBAL_DEF("rendering/quality/spatial_partitioning/use_bvh", true);
  3649. GLOBAL_DEF("rendering/quality/spatial_partitioning/bvh_collision_margin", 0.1);
  3650. ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/spatial_partitioning/bvh_collision_margin", PropertyInfo(Variant::REAL, "rendering/quality/spatial_partitioning/bvh_collision_margin", PROPERTY_HINT_RANGE, "0.0,2.0,0.01"));
  3651. _visual_server_callbacks = nullptr;
  3652. }
  3653. VisualServerScene::~VisualServerScene() {
  3654. probe_bake_thread_exit = true;
  3655. probe_bake_sem.post();
  3656. probe_bake_thread.wait_to_finish();
  3657. }