visual_server_scene.cpp 162 KB

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