renderer_scene_cull.cpp 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557
  1. /*************************************************************************/
  2. /* renderer_scene_cull.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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 "renderer_scene_cull.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/os/os.h"
  33. #include "rendering_server_default.h"
  34. #include "rendering_server_globals.h"
  35. #include <new>
  36. /* CAMERA API */
  37. RID RendererSceneCull::camera_allocate() {
  38. return camera_owner.allocate_rid();
  39. }
  40. void RendererSceneCull::camera_initialize(RID p_rid) {
  41. camera_owner.initialize_rid(p_rid, memnew(Camera));
  42. }
  43. void RendererSceneCull::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
  44. Camera *camera = camera_owner.getornull(p_camera);
  45. ERR_FAIL_COND(!camera);
  46. camera->type = Camera::PERSPECTIVE;
  47. camera->fov = p_fovy_degrees;
  48. camera->znear = p_z_near;
  49. camera->zfar = p_z_far;
  50. }
  51. void RendererSceneCull::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
  52. Camera *camera = camera_owner.getornull(p_camera);
  53. ERR_FAIL_COND(!camera);
  54. camera->type = Camera::ORTHOGONAL;
  55. camera->size = p_size;
  56. camera->znear = p_z_near;
  57. camera->zfar = p_z_far;
  58. }
  59. void RendererSceneCull::camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
  60. Camera *camera = camera_owner.getornull(p_camera);
  61. ERR_FAIL_COND(!camera);
  62. camera->type = Camera::FRUSTUM;
  63. camera->size = p_size;
  64. camera->offset = p_offset;
  65. camera->znear = p_z_near;
  66. camera->zfar = p_z_far;
  67. }
  68. void RendererSceneCull::camera_set_transform(RID p_camera, const Transform &p_transform) {
  69. Camera *camera = camera_owner.getornull(p_camera);
  70. ERR_FAIL_COND(!camera);
  71. camera->transform = p_transform.orthonormalized();
  72. }
  73. void RendererSceneCull::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
  74. Camera *camera = camera_owner.getornull(p_camera);
  75. ERR_FAIL_COND(!camera);
  76. camera->visible_layers = p_layers;
  77. }
  78. void RendererSceneCull::camera_set_environment(RID p_camera, RID p_env) {
  79. Camera *camera = camera_owner.getornull(p_camera);
  80. ERR_FAIL_COND(!camera);
  81. camera->env = p_env;
  82. }
  83. void RendererSceneCull::camera_set_camera_effects(RID p_camera, RID p_fx) {
  84. Camera *camera = camera_owner.getornull(p_camera);
  85. ERR_FAIL_COND(!camera);
  86. camera->effects = p_fx;
  87. }
  88. void RendererSceneCull::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
  89. Camera *camera = camera_owner.getornull(p_camera);
  90. ERR_FAIL_COND(!camera);
  91. camera->vaspect = p_enable;
  92. }
  93. bool RendererSceneCull::is_camera(RID p_camera) const {
  94. return camera_owner.owns(p_camera);
  95. }
  96. /* SCENARIO API */
  97. void RendererSceneCull::_instance_pair(Instance *p_A, Instance *p_B) {
  98. RendererSceneCull *self = (RendererSceneCull *)singleton;
  99. Instance *A = p_A;
  100. Instance *B = p_B;
  101. //instance indices are designed so greater always contains lesser
  102. if (A->base_type > B->base_type) {
  103. SWAP(A, B); //lesser always first
  104. }
  105. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  106. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  107. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  108. geom->lights.insert(B);
  109. light->geometries.insert(A);
  110. if (geom->can_cast_shadows) {
  111. light->shadow_dirty = true;
  112. }
  113. if (A->scenario && A->array_index >= 0) {
  114. InstanceData &idata = A->scenario->instance_data[A->array_index];
  115. idata.flags |= InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
  116. }
  117. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  118. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  119. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  120. geom->reflection_probes.insert(B);
  121. reflection_probe->geometries.insert(A);
  122. if (A->scenario && A->array_index >= 0) {
  123. InstanceData &idata = A->scenario->instance_data[A->array_index];
  124. idata.flags |= InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
  125. }
  126. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  127. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  128. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  129. geom->decals.insert(B);
  130. decal->geometries.insert(A);
  131. if (A->scenario && A->array_index >= 0) {
  132. InstanceData &idata = A->scenario->instance_data[A->array_index];
  133. idata.flags |= InstanceData::FLAG_GEOM_DECAL_DIRTY;
  134. }
  135. } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  136. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
  137. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  138. if (A->dynamic_gi) {
  139. geom->lightmap_captures.insert(A);
  140. lightmap_data->geometries.insert(B);
  141. if (A->scenario && A->array_index >= 0) {
  142. InstanceData &idata = A->scenario->instance_data[A->array_index];
  143. idata.flags |= InstanceData::FLAG_LIGHTMAP_CAPTURE;
  144. }
  145. ((RendererSceneCull *)self)->_instance_queue_update(A, false, false); //need to update capture
  146. }
  147. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_GI_PROBE) && B->base_type == RS::INSTANCE_GI_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  148. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  149. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  150. geom->gi_probes.insert(B);
  151. if (A->dynamic_gi) {
  152. gi_probe->dynamic_geometries.insert(A);
  153. } else {
  154. gi_probe->geometries.insert(A);
  155. }
  156. if (A->scenario && A->array_index >= 0) {
  157. InstanceData &idata = A->scenario->instance_data[A->array_index];
  158. idata.flags |= InstanceData::FLAG_GEOM_GI_PROBE_DIRTY;
  159. }
  160. } else if (B->base_type == RS::INSTANCE_GI_PROBE && A->base_type == RS::INSTANCE_LIGHT) {
  161. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  162. gi_probe->lights.insert(A);
  163. } else if (B->base_type == RS::INSTANCE_PARTICLES_COLLISION && A->base_type == RS::INSTANCE_PARTICLES) {
  164. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(B->base_data);
  165. RSG::storage->particles_add_collision(A->base, collision->instance);
  166. }
  167. }
  168. void RendererSceneCull::_instance_unpair(Instance *p_A, Instance *p_B) {
  169. RendererSceneCull *self = (RendererSceneCull *)singleton;
  170. Instance *A = p_A;
  171. Instance *B = p_B;
  172. //instance indices are designed so greater always contains lesser
  173. if (A->base_type > B->base_type) {
  174. SWAP(A, B); //lesser always first
  175. }
  176. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  177. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  178. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  179. geom->lights.erase(B);
  180. light->geometries.erase(A);
  181. if (geom->can_cast_shadows) {
  182. light->shadow_dirty = true;
  183. }
  184. if (A->scenario && A->array_index >= 0) {
  185. InstanceData &idata = A->scenario->instance_data[A->array_index];
  186. idata.flags |= InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
  187. }
  188. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  189. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  190. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  191. geom->reflection_probes.erase(B);
  192. reflection_probe->geometries.erase(A);
  193. if (A->scenario && A->array_index >= 0) {
  194. InstanceData &idata = A->scenario->instance_data[A->array_index];
  195. idata.flags |= InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
  196. }
  197. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  198. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  199. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  200. geom->decals.erase(B);
  201. decal->geometries.erase(A);
  202. if (A->scenario && A->array_index >= 0) {
  203. InstanceData &idata = A->scenario->instance_data[A->array_index];
  204. idata.flags |= InstanceData::FLAG_GEOM_DECAL_DIRTY;
  205. }
  206. } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  207. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
  208. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  209. if (A->dynamic_gi) {
  210. geom->lightmap_captures.erase(B);
  211. if (geom->lightmap_captures.is_empty() && A->scenario && A->array_index >= 0) {
  212. InstanceData &idata = A->scenario->instance_data[A->array_index];
  213. idata.flags &= ~uint32_t(InstanceData::FLAG_LIGHTMAP_CAPTURE);
  214. }
  215. lightmap_data->geometries.erase(A);
  216. ((RendererSceneCull *)self)->_instance_queue_update(A, false, false); //need to update capture
  217. }
  218. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_GI_PROBE) && B->base_type == RS::INSTANCE_GI_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  219. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  220. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  221. geom->gi_probes.erase(B);
  222. if (A->dynamic_gi) {
  223. gi_probe->dynamic_geometries.erase(A);
  224. } else {
  225. gi_probe->geometries.erase(A);
  226. }
  227. if (A->scenario && A->array_index >= 0) {
  228. InstanceData &idata = A->scenario->instance_data[A->array_index];
  229. idata.flags |= InstanceData::FLAG_GEOM_GI_PROBE_DIRTY;
  230. }
  231. } else if (B->base_type == RS::INSTANCE_GI_PROBE && A->base_type == RS::INSTANCE_LIGHT) {
  232. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  233. gi_probe->lights.erase(A);
  234. } else if (B->base_type == RS::INSTANCE_PARTICLES_COLLISION && A->base_type == RS::INSTANCE_PARTICLES) {
  235. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(B->base_data);
  236. RSG::storage->particles_remove_collision(A->base, collision->instance);
  237. }
  238. }
  239. RID RendererSceneCull::scenario_allocate() {
  240. return scenario_owner.allocate_rid();
  241. }
  242. void RendererSceneCull::scenario_initialize(RID p_rid) {
  243. Scenario *scenario = memnew(Scenario);
  244. scenario->self = p_rid;
  245. scenario->reflection_probe_shadow_atlas = scene_render->shadow_atlas_create();
  246. scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
  247. scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
  248. scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
  249. scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
  250. scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
  251. scenario->reflection_atlas = scene_render->reflection_atlas_create();
  252. scenario->instance_aabbs.set_page_pool(&instance_aabb_page_pool);
  253. scenario->instance_data.set_page_pool(&instance_data_page_pool);
  254. scenario_owner.initialize_rid(p_rid, scenario);
  255. }
  256. void RendererSceneCull::scenario_set_debug(RID p_scenario, RS::ScenarioDebugMode p_debug_mode) {
  257. Scenario *scenario = scenario_owner.getornull(p_scenario);
  258. ERR_FAIL_COND(!scenario);
  259. scenario->debug = p_debug_mode;
  260. }
  261. void RendererSceneCull::scenario_set_environment(RID p_scenario, RID p_environment) {
  262. Scenario *scenario = scenario_owner.getornull(p_scenario);
  263. ERR_FAIL_COND(!scenario);
  264. scenario->environment = p_environment;
  265. }
  266. void RendererSceneCull::scenario_set_camera_effects(RID p_scenario, RID p_camera_effects) {
  267. Scenario *scenario = scenario_owner.getornull(p_scenario);
  268. ERR_FAIL_COND(!scenario);
  269. scenario->camera_effects = p_camera_effects;
  270. }
  271. void RendererSceneCull::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
  272. Scenario *scenario = scenario_owner.getornull(p_scenario);
  273. ERR_FAIL_COND(!scenario);
  274. scenario->fallback_environment = p_environment;
  275. }
  276. void RendererSceneCull::scenario_set_reflection_atlas_size(RID p_scenario, int p_reflection_size, int p_reflection_count) {
  277. Scenario *scenario = scenario_owner.getornull(p_scenario);
  278. ERR_FAIL_COND(!scenario);
  279. scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_reflection_size, p_reflection_count);
  280. }
  281. bool RendererSceneCull::is_scenario(RID p_scenario) const {
  282. return scenario_owner.owns(p_scenario);
  283. }
  284. RID RendererSceneCull::scenario_get_environment(RID p_scenario) {
  285. Scenario *scenario = scenario_owner.getornull(p_scenario);
  286. ERR_FAIL_COND_V(!scenario, RID());
  287. return scenario->environment;
  288. }
  289. /* INSTANCING API */
  290. void RendererSceneCull::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_dependencies) {
  291. if (p_update_aabb) {
  292. p_instance->update_aabb = true;
  293. }
  294. if (p_update_dependencies) {
  295. p_instance->update_dependencies = true;
  296. }
  297. if (p_instance->update_item.in_list()) {
  298. return;
  299. }
  300. _instance_update_list.add(&p_instance->update_item);
  301. }
  302. RID RendererSceneCull::instance_allocate() {
  303. return instance_owner.allocate_rid();
  304. }
  305. void RendererSceneCull::instance_initialize(RID p_rid) {
  306. Instance *instance = memnew(Instance);
  307. instance->self = p_rid;
  308. instance_owner.initialize_rid(p_rid, instance);
  309. }
  310. void RendererSceneCull::_instance_update_mesh_instance(Instance *p_instance) {
  311. bool needs_instance = RSG::storage->mesh_needs_instance(p_instance->base, p_instance->skeleton.is_valid());
  312. if (needs_instance != p_instance->mesh_instance.is_valid()) {
  313. if (needs_instance) {
  314. p_instance->mesh_instance = RSG::storage->mesh_instance_create(p_instance->base);
  315. } else {
  316. RSG::storage->free(p_instance->mesh_instance);
  317. p_instance->mesh_instance = RID();
  318. }
  319. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  320. scene_render->geometry_instance_set_mesh_instance(geom->geometry_instance, p_instance->mesh_instance);
  321. if (p_instance->scenario && p_instance->array_index >= 0) {
  322. InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
  323. if (p_instance->mesh_instance.is_valid()) {
  324. idata.flags |= InstanceData::FLAG_USES_MESH_INSTANCE;
  325. } else {
  326. idata.flags &= ~uint32_t(InstanceData::FLAG_USES_MESH_INSTANCE);
  327. }
  328. }
  329. }
  330. if (p_instance->mesh_instance.is_valid()) {
  331. RSG::storage->mesh_instance_set_skeleton(p_instance->mesh_instance, p_instance->skeleton);
  332. }
  333. }
  334. void RendererSceneCull::instance_set_base(RID p_instance, RID p_base) {
  335. Instance *instance = instance_owner.getornull(p_instance);
  336. ERR_FAIL_COND(!instance);
  337. Scenario *scenario = instance->scenario;
  338. if (instance->base_type != RS::INSTANCE_NONE) {
  339. //free anything related to that base
  340. if (scenario && instance->indexer_id.is_valid()) {
  341. _unpair_instance(instance);
  342. }
  343. if (instance->mesh_instance.is_valid()) {
  344. RSG::storage->free(instance->mesh_instance);
  345. instance->mesh_instance = RID();
  346. // no need to set instance data flag here, as it was freed above
  347. }
  348. switch (instance->base_type) {
  349. case RS::INSTANCE_MESH:
  350. case RS::INSTANCE_MULTIMESH:
  351. case RS::INSTANCE_IMMEDIATE:
  352. case RS::INSTANCE_PARTICLES: {
  353. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  354. scene_render->geometry_instance_free(geom->geometry_instance);
  355. } break;
  356. case RS::INSTANCE_LIGHT: {
  357. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  358. if (scenario && instance->visible && RSG::storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  359. scenario->dynamic_lights.erase(light->instance);
  360. }
  361. #ifdef DEBUG_ENABLED
  362. if (light->geometries.size()) {
  363. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  364. }
  365. #endif
  366. if (scenario && light->D) {
  367. scenario->directional_lights.erase(light->D);
  368. light->D = nullptr;
  369. }
  370. scene_render->free(light->instance);
  371. } break;
  372. case RS::INSTANCE_PARTICLES_COLLISION: {
  373. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(instance->base_data);
  374. RSG::storage->free(collision->instance);
  375. } break;
  376. case RS::INSTANCE_REFLECTION_PROBE: {
  377. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  378. scene_render->free(reflection_probe->instance);
  379. if (reflection_probe->update_list.in_list()) {
  380. reflection_probe_render_list.remove(&reflection_probe->update_list);
  381. }
  382. } break;
  383. case RS::INSTANCE_DECAL: {
  384. InstanceDecalData *decal = static_cast<InstanceDecalData *>(instance->base_data);
  385. scene_render->free(decal->instance);
  386. } break;
  387. case RS::INSTANCE_LIGHTMAP: {
  388. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(instance->base_data);
  389. //erase dependencies, since no longer a lightmap
  390. while (lightmap_data->users.front()) {
  391. instance_geometry_set_lightmap(lightmap_data->users.front()->get()->self, RID(), Rect2(), 0);
  392. }
  393. scene_render->free(lightmap_data->instance);
  394. } break;
  395. case RS::INSTANCE_GI_PROBE: {
  396. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  397. #ifdef DEBUG_ENABLED
  398. if (gi_probe->geometries.size()) {
  399. ERR_PRINT("BUG, indexing did not unpair geometries from GIProbe.");
  400. }
  401. #endif
  402. #ifdef DEBUG_ENABLED
  403. if (gi_probe->lights.size()) {
  404. ERR_PRINT("BUG, indexing did not unpair lights from GIProbe.");
  405. }
  406. #endif
  407. if (gi_probe->update_element.in_list()) {
  408. gi_probe_update_list.remove(&gi_probe->update_element);
  409. }
  410. scene_render->free(gi_probe->probe_instance);
  411. } break;
  412. default: {
  413. }
  414. }
  415. if (instance->base_data) {
  416. memdelete(instance->base_data);
  417. instance->base_data = nullptr;
  418. }
  419. instance->materials.clear();
  420. }
  421. instance->base_type = RS::INSTANCE_NONE;
  422. instance->base = RID();
  423. if (p_base.is_valid()) {
  424. instance->base_type = RSG::storage->get_base_type(p_base);
  425. ERR_FAIL_COND(instance->base_type == RS::INSTANCE_NONE);
  426. switch (instance->base_type) {
  427. case RS::INSTANCE_LIGHT: {
  428. InstanceLightData *light = memnew(InstanceLightData);
  429. if (scenario && RSG::storage->light_get_type(p_base) == RS::LIGHT_DIRECTIONAL) {
  430. light->D = scenario->directional_lights.push_back(instance);
  431. }
  432. light->instance = scene_render->light_instance_create(p_base);
  433. instance->base_data = light;
  434. } break;
  435. case RS::INSTANCE_MESH:
  436. case RS::INSTANCE_MULTIMESH:
  437. case RS::INSTANCE_IMMEDIATE:
  438. case RS::INSTANCE_PARTICLES: {
  439. InstanceGeometryData *geom = memnew(InstanceGeometryData);
  440. instance->base_data = geom;
  441. geom->geometry_instance = scene_render->geometry_instance_create(p_base);
  442. scene_render->geometry_instance_set_skeleton(geom->geometry_instance, instance->skeleton);
  443. scene_render->geometry_instance_set_material_override(geom->geometry_instance, instance->material_override);
  444. scene_render->geometry_instance_set_surface_materials(geom->geometry_instance, instance->materials);
  445. scene_render->geometry_instance_set_transform(geom->geometry_instance, instance->transform, instance->aabb, instance->transformed_aabb);
  446. scene_render->geometry_instance_set_layer_mask(geom->geometry_instance, instance->layer_mask);
  447. scene_render->geometry_instance_set_lod_bias(geom->geometry_instance, instance->lod_bias);
  448. scene_render->geometry_instance_set_use_baked_light(geom->geometry_instance, instance->baked_light);
  449. scene_render->geometry_instance_set_use_dynamic_gi(geom->geometry_instance, instance->dynamic_gi);
  450. scene_render->geometry_instance_set_cast_double_sided_shadows(geom->geometry_instance, instance->cast_shadows == RS::SHADOW_CASTING_SETTING_DOUBLE_SIDED);
  451. scene_render->geometry_instance_set_use_lightmap(geom->geometry_instance, RID(), instance->lightmap_uv_scale, instance->lightmap_slice_index);
  452. if (instance->lightmap_sh.size() == 9) {
  453. scene_render->geometry_instance_set_lightmap_capture(geom->geometry_instance, instance->lightmap_sh.ptr());
  454. }
  455. } break;
  456. case RS::INSTANCE_PARTICLES_COLLISION: {
  457. InstanceParticlesCollisionData *collision = memnew(InstanceParticlesCollisionData);
  458. collision->instance = RSG::storage->particles_collision_instance_create(p_base);
  459. RSG::storage->particles_collision_instance_set_active(collision->instance, instance->visible);
  460. instance->base_data = collision;
  461. } break;
  462. case RS::INSTANCE_REFLECTION_PROBE: {
  463. InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
  464. reflection_probe->owner = instance;
  465. instance->base_data = reflection_probe;
  466. reflection_probe->instance = scene_render->reflection_probe_instance_create(p_base);
  467. } break;
  468. case RS::INSTANCE_DECAL: {
  469. InstanceDecalData *decal = memnew(InstanceDecalData);
  470. decal->owner = instance;
  471. instance->base_data = decal;
  472. decal->instance = scene_render->decal_instance_create(p_base);
  473. } break;
  474. case RS::INSTANCE_LIGHTMAP: {
  475. InstanceLightmapData *lightmap_data = memnew(InstanceLightmapData);
  476. instance->base_data = lightmap_data;
  477. lightmap_data->instance = scene_render->lightmap_instance_create(p_base);
  478. } break;
  479. case RS::INSTANCE_GI_PROBE: {
  480. InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
  481. instance->base_data = gi_probe;
  482. gi_probe->owner = instance;
  483. if (scenario && !gi_probe->update_element.in_list()) {
  484. gi_probe_update_list.add(&gi_probe->update_element);
  485. }
  486. gi_probe->probe_instance = scene_render->gi_probe_instance_create(p_base);
  487. } break;
  488. default: {
  489. }
  490. }
  491. instance->base = p_base;
  492. if (instance->base_type == RS::INSTANCE_MESH) {
  493. _instance_update_mesh_instance(instance);
  494. }
  495. //forcefully update the dependency now, so if for some reason it gets removed, we can immediately clear it
  496. RSG::storage->base_update_dependency(p_base, &instance->dependency_tracker);
  497. }
  498. _instance_queue_update(instance, true, true);
  499. }
  500. void RendererSceneCull::instance_set_scenario(RID p_instance, RID p_scenario) {
  501. Instance *instance = instance_owner.getornull(p_instance);
  502. ERR_FAIL_COND(!instance);
  503. if (instance->scenario) {
  504. instance->scenario->instances.remove(&instance->scenario_item);
  505. if (instance->indexer_id.is_valid()) {
  506. _unpair_instance(instance);
  507. }
  508. switch (instance->base_type) {
  509. case RS::INSTANCE_LIGHT: {
  510. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  511. #ifdef DEBUG_ENABLED
  512. if (light->geometries.size()) {
  513. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  514. }
  515. #endif
  516. if (light->D) {
  517. instance->scenario->directional_lights.erase(light->D);
  518. light->D = nullptr;
  519. }
  520. } break;
  521. case RS::INSTANCE_REFLECTION_PROBE: {
  522. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  523. scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
  524. } break;
  525. case RS::INSTANCE_PARTICLES_COLLISION: {
  526. heightfield_particle_colliders_update_list.erase(instance);
  527. } break;
  528. case RS::INSTANCE_GI_PROBE: {
  529. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  530. #ifdef DEBUG_ENABLED
  531. if (gi_probe->geometries.size()) {
  532. ERR_PRINT("BUG, indexing did not unpair geometries from GIProbe.");
  533. }
  534. #endif
  535. #ifdef DEBUG_ENABLED
  536. if (gi_probe->lights.size()) {
  537. ERR_PRINT("BUG, indexing did not unpair lights from GIProbe.");
  538. }
  539. #endif
  540. if (gi_probe->update_element.in_list()) {
  541. gi_probe_update_list.remove(&gi_probe->update_element);
  542. }
  543. } break;
  544. default: {
  545. }
  546. }
  547. instance->scenario = nullptr;
  548. }
  549. if (p_scenario.is_valid()) {
  550. Scenario *scenario = scenario_owner.getornull(p_scenario);
  551. ERR_FAIL_COND(!scenario);
  552. instance->scenario = scenario;
  553. scenario->instances.add(&instance->scenario_item);
  554. switch (instance->base_type) {
  555. case RS::INSTANCE_LIGHT: {
  556. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  557. if (RSG::storage->light_get_type(instance->base) == RS::LIGHT_DIRECTIONAL) {
  558. light->D = scenario->directional_lights.push_back(instance);
  559. }
  560. } break;
  561. case RS::INSTANCE_GI_PROBE: {
  562. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  563. if (!gi_probe->update_element.in_list()) {
  564. gi_probe_update_list.add(&gi_probe->update_element);
  565. }
  566. } break;
  567. default: {
  568. }
  569. }
  570. _instance_queue_update(instance, true, true);
  571. }
  572. }
  573. void RendererSceneCull::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
  574. Instance *instance = instance_owner.getornull(p_instance);
  575. ERR_FAIL_COND(!instance);
  576. instance->layer_mask = p_mask;
  577. if (instance->scenario && instance->array_index >= 0) {
  578. instance->scenario->instance_data[instance->array_index].layer_mask = p_mask;
  579. }
  580. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  581. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  582. scene_render->geometry_instance_set_layer_mask(geom->geometry_instance, p_mask);
  583. }
  584. }
  585. void RendererSceneCull::instance_set_transform(RID p_instance, const Transform &p_transform) {
  586. Instance *instance = instance_owner.getornull(p_instance);
  587. ERR_FAIL_COND(!instance);
  588. if (instance->transform == p_transform) {
  589. return; //must be checked to avoid worst evil
  590. }
  591. #ifdef DEBUG_ENABLED
  592. for (int i = 0; i < 4; i++) {
  593. const Vector3 &v = i < 3 ? p_transform.basis.elements[i] : p_transform.origin;
  594. ERR_FAIL_COND(Math::is_inf(v.x));
  595. ERR_FAIL_COND(Math::is_nan(v.x));
  596. ERR_FAIL_COND(Math::is_inf(v.y));
  597. ERR_FAIL_COND(Math::is_nan(v.y));
  598. ERR_FAIL_COND(Math::is_inf(v.z));
  599. ERR_FAIL_COND(Math::is_nan(v.z));
  600. }
  601. #endif
  602. instance->transform = p_transform;
  603. _instance_queue_update(instance, true);
  604. }
  605. void RendererSceneCull::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {
  606. Instance *instance = instance_owner.getornull(p_instance);
  607. ERR_FAIL_COND(!instance);
  608. instance->object_id = p_id;
  609. }
  610. void RendererSceneCull::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
  611. Instance *instance = instance_owner.getornull(p_instance);
  612. ERR_FAIL_COND(!instance);
  613. if (instance->update_item.in_list()) {
  614. _update_dirty_instance(instance);
  615. }
  616. if (instance->mesh_instance.is_valid()) {
  617. RSG::storage->mesh_instance_set_blend_shape_weight(instance->mesh_instance, p_shape, p_weight);
  618. }
  619. }
  620. void RendererSceneCull::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {
  621. Instance *instance = instance_owner.getornull(p_instance);
  622. ERR_FAIL_COND(!instance);
  623. if (instance->base_type == RS::INSTANCE_MESH) {
  624. //may not have been updated yet, may also have not been set yet. When updated will be correcte, worst case
  625. instance->materials.resize(MAX(p_surface + 1, RSG::storage->mesh_get_surface_count(instance->base)));
  626. }
  627. ERR_FAIL_INDEX(p_surface, instance->materials.size());
  628. instance->materials.write[p_surface] = p_material;
  629. _instance_queue_update(instance, false, true);
  630. }
  631. void RendererSceneCull::instance_set_visible(RID p_instance, bool p_visible) {
  632. Instance *instance = instance_owner.getornull(p_instance);
  633. ERR_FAIL_COND(!instance);
  634. if (instance->visible == p_visible) {
  635. return;
  636. }
  637. instance->visible = p_visible;
  638. if (p_visible) {
  639. if (instance->scenario != nullptr) {
  640. _instance_queue_update(instance, true, false);
  641. }
  642. } else if (instance->indexer_id.is_valid()) {
  643. _unpair_instance(instance);
  644. }
  645. if (instance->base_type == RS::INSTANCE_LIGHT) {
  646. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  647. if (instance->scenario && RSG::storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  648. if (p_visible) {
  649. instance->scenario->dynamic_lights.push_back(light->instance);
  650. } else {
  651. instance->scenario->dynamic_lights.erase(light->instance);
  652. }
  653. }
  654. }
  655. if (instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  656. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(instance->base_data);
  657. RSG::storage->particles_collision_instance_set_active(collision->instance, p_visible);
  658. }
  659. }
  660. inline bool is_geometry_instance(RenderingServer::InstanceType p_type) {
  661. return p_type == RS::INSTANCE_MESH || p_type == RS::INSTANCE_MULTIMESH || p_type == RS::INSTANCE_PARTICLES || p_type == RS::INSTANCE_IMMEDIATE;
  662. }
  663. void RendererSceneCull::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
  664. Instance *instance = instance_owner.getornull(p_instance);
  665. ERR_FAIL_COND(!instance);
  666. ERR_FAIL_COND(!is_geometry_instance(instance->base_type));
  667. if (p_aabb != AABB()) {
  668. // Set custom AABB
  669. if (instance->custom_aabb == nullptr) {
  670. instance->custom_aabb = memnew(AABB);
  671. }
  672. *instance->custom_aabb = p_aabb;
  673. } else {
  674. // Clear custom AABB
  675. if (instance->custom_aabb != nullptr) {
  676. memdelete(instance->custom_aabb);
  677. instance->custom_aabb = nullptr;
  678. }
  679. }
  680. if (instance->scenario) {
  681. _instance_queue_update(instance, true, false);
  682. }
  683. }
  684. void RendererSceneCull::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
  685. Instance *instance = instance_owner.getornull(p_instance);
  686. ERR_FAIL_COND(!instance);
  687. if (instance->skeleton == p_skeleton) {
  688. return;
  689. }
  690. instance->skeleton = p_skeleton;
  691. if (p_skeleton.is_valid()) {
  692. //update the dependency now, so if cleared, we remove it
  693. RSG::storage->skeleton_update_dependency(p_skeleton, &instance->dependency_tracker);
  694. }
  695. _instance_queue_update(instance, true, true);
  696. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  697. _instance_update_mesh_instance(instance);
  698. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  699. scene_render->geometry_instance_set_skeleton(geom->geometry_instance, p_skeleton);
  700. }
  701. }
  702. void RendererSceneCull::instance_set_exterior(RID p_instance, bool p_enabled) {
  703. }
  704. void RendererSceneCull::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
  705. Instance *instance = instance_owner.getornull(p_instance);
  706. ERR_FAIL_COND(!instance);
  707. instance->extra_margin = p_margin;
  708. _instance_queue_update(instance, true, false);
  709. }
  710. Vector<ObjectID> RendererSceneCull::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
  711. Vector<ObjectID> instances;
  712. Scenario *scenario = scenario_owner.getornull(p_scenario);
  713. ERR_FAIL_COND_V(!scenario, instances);
  714. const_cast<RendererSceneCull *>(this)->update_dirty_instances(); // check dirty instances before culling
  715. struct CullAABB {
  716. Vector<ObjectID> instances;
  717. _FORCE_INLINE_ bool operator()(void *p_data) {
  718. Instance *p_instance = (Instance *)p_data;
  719. if (!p_instance->object_id.is_null()) {
  720. instances.push_back(p_instance->object_id);
  721. }
  722. return false;
  723. }
  724. };
  725. CullAABB cull_aabb;
  726. scenario->indexers[Scenario::INDEXER_GEOMETRY].aabb_query(p_aabb, cull_aabb);
  727. scenario->indexers[Scenario::INDEXER_VOLUMES].aabb_query(p_aabb, cull_aabb);
  728. return cull_aabb.instances;
  729. }
  730. Vector<ObjectID> RendererSceneCull::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
  731. Vector<ObjectID> instances;
  732. Scenario *scenario = scenario_owner.getornull(p_scenario);
  733. ERR_FAIL_COND_V(!scenario, instances);
  734. const_cast<RendererSceneCull *>(this)->update_dirty_instances(); // check dirty instances before culling
  735. struct CullRay {
  736. Vector<ObjectID> instances;
  737. _FORCE_INLINE_ bool operator()(void *p_data) {
  738. Instance *p_instance = (Instance *)p_data;
  739. if (!p_instance->object_id.is_null()) {
  740. instances.push_back(p_instance->object_id);
  741. }
  742. return false;
  743. }
  744. };
  745. CullRay cull_ray;
  746. scenario->indexers[Scenario::INDEXER_GEOMETRY].ray_query(p_from, p_to, cull_ray);
  747. scenario->indexers[Scenario::INDEXER_VOLUMES].ray_query(p_from, p_to, cull_ray);
  748. return cull_ray.instances;
  749. }
  750. Vector<ObjectID> RendererSceneCull::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
  751. Vector<ObjectID> instances;
  752. Scenario *scenario = scenario_owner.getornull(p_scenario);
  753. ERR_FAIL_COND_V(!scenario, instances);
  754. const_cast<RendererSceneCull *>(this)->update_dirty_instances(); // check dirty instances before culling
  755. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&p_convex[0], p_convex.size());
  756. struct CullConvex {
  757. Vector<ObjectID> instances;
  758. _FORCE_INLINE_ bool operator()(void *p_data) {
  759. Instance *p_instance = (Instance *)p_data;
  760. if (!p_instance->object_id.is_null()) {
  761. instances.push_back(p_instance->object_id);
  762. }
  763. return false;
  764. }
  765. };
  766. CullConvex cull_convex;
  767. scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(p_convex.ptr(), p_convex.size(), points.ptr(), points.size(), cull_convex);
  768. scenario->indexers[Scenario::INDEXER_VOLUMES].convex_query(p_convex.ptr(), p_convex.size(), points.ptr(), points.size(), cull_convex);
  769. return cull_convex.instances;
  770. }
  771. void RendererSceneCull::instance_geometry_set_flag(RID p_instance, RS::InstanceFlags p_flags, bool p_enabled) {
  772. Instance *instance = instance_owner.getornull(p_instance);
  773. ERR_FAIL_COND(!instance);
  774. //ERR_FAIL_COND(((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK));
  775. switch (p_flags) {
  776. case RS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
  777. instance->baked_light = p_enabled;
  778. if (instance->scenario && instance->array_index >= 0) {
  779. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  780. if (instance->baked_light) {
  781. idata.flags |= InstanceData::FLAG_USES_BAKED_LIGHT;
  782. } else {
  783. idata.flags &= ~uint32_t(InstanceData::FLAG_USES_BAKED_LIGHT);
  784. }
  785. }
  786. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  787. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  788. scene_render->geometry_instance_set_use_baked_light(geom->geometry_instance, p_enabled);
  789. }
  790. } break;
  791. case RS::INSTANCE_FLAG_USE_DYNAMIC_GI: {
  792. if (p_enabled == instance->dynamic_gi) {
  793. //bye, redundant
  794. return;
  795. }
  796. if (instance->indexer_id.is_valid()) {
  797. _unpair_instance(instance);
  798. _instance_queue_update(instance, true, true);
  799. }
  800. //once out of octree, can be changed
  801. instance->dynamic_gi = p_enabled;
  802. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  803. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  804. scene_render->geometry_instance_set_use_dynamic_gi(geom->geometry_instance, p_enabled);
  805. }
  806. } break;
  807. case RS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {
  808. instance->redraw_if_visible = p_enabled;
  809. if (instance->scenario && instance->array_index >= 0) {
  810. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  811. if (instance->redraw_if_visible) {
  812. idata.flags |= InstanceData::FLAG_REDRAW_IF_VISIBLE;
  813. } else {
  814. idata.flags &= ~uint32_t(InstanceData::FLAG_REDRAW_IF_VISIBLE);
  815. }
  816. }
  817. } break;
  818. default: {
  819. }
  820. }
  821. }
  822. void RendererSceneCull::instance_geometry_set_cast_shadows_setting(RID p_instance, RS::ShadowCastingSetting p_shadow_casting_setting) {
  823. Instance *instance = instance_owner.getornull(p_instance);
  824. ERR_FAIL_COND(!instance);
  825. instance->cast_shadows = p_shadow_casting_setting;
  826. if (instance->scenario && instance->array_index >= 0) {
  827. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  828. if (instance->cast_shadows != RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  829. idata.flags |= InstanceData::FLAG_CAST_SHADOWS;
  830. } else {
  831. idata.flags &= ~uint32_t(InstanceData::FLAG_CAST_SHADOWS);
  832. }
  833. if (instance->cast_shadows == RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  834. idata.flags |= InstanceData::FLAG_CAST_SHADOWS_ONLY;
  835. } else {
  836. idata.flags &= ~uint32_t(InstanceData::FLAG_CAST_SHADOWS_ONLY);
  837. }
  838. }
  839. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  840. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  841. scene_render->geometry_instance_set_cast_double_sided_shadows(geom->geometry_instance, instance->cast_shadows == RS::SHADOW_CASTING_SETTING_DOUBLE_SIDED);
  842. }
  843. _instance_queue_update(instance, false, true);
  844. }
  845. void RendererSceneCull::instance_geometry_set_material_override(RID p_instance, RID p_material) {
  846. Instance *instance = instance_owner.getornull(p_instance);
  847. ERR_FAIL_COND(!instance);
  848. instance->material_override = p_material;
  849. _instance_queue_update(instance, false, true);
  850. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  851. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  852. scene_render->geometry_instance_set_material_override(geom->geometry_instance, p_material);
  853. }
  854. }
  855. void RendererSceneCull::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
  856. }
  857. void RendererSceneCull::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
  858. }
  859. void RendererSceneCull::instance_geometry_set_lightmap(RID p_instance, RID p_lightmap, const Rect2 &p_lightmap_uv_scale, int p_slice_index) {
  860. Instance *instance = instance_owner.getornull(p_instance);
  861. ERR_FAIL_COND(!instance);
  862. if (instance->lightmap) {
  863. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(((Instance *)instance->lightmap)->base_data);
  864. lightmap_data->users.erase(instance);
  865. instance->lightmap = nullptr;
  866. }
  867. Instance *lightmap_instance = instance_owner.getornull(p_lightmap);
  868. instance->lightmap = lightmap_instance;
  869. instance->lightmap_uv_scale = p_lightmap_uv_scale;
  870. instance->lightmap_slice_index = p_slice_index;
  871. RID lightmap_instance_rid;
  872. if (lightmap_instance) {
  873. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(lightmap_instance->base_data);
  874. lightmap_data->users.insert(instance);
  875. lightmap_instance_rid = lightmap_data->instance;
  876. }
  877. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  878. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  879. scene_render->geometry_instance_set_use_lightmap(geom->geometry_instance, lightmap_instance_rid, p_lightmap_uv_scale, p_slice_index);
  880. }
  881. }
  882. void RendererSceneCull::instance_geometry_set_lod_bias(RID p_instance, float p_lod_bias) {
  883. Instance *instance = instance_owner.getornull(p_instance);
  884. ERR_FAIL_COND(!instance);
  885. instance->lod_bias = p_lod_bias;
  886. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  887. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  888. scene_render->geometry_instance_set_lod_bias(geom->geometry_instance, p_lod_bias);
  889. }
  890. }
  891. void RendererSceneCull::instance_geometry_set_shader_parameter(RID p_instance, const StringName &p_parameter, const Variant &p_value) {
  892. Instance *instance = instance_owner.getornull(p_instance);
  893. ERR_FAIL_COND(!instance);
  894. Map<StringName, Instance::InstanceShaderParameter>::Element *E = instance->instance_shader_parameters.find(p_parameter);
  895. if (!E) {
  896. Instance::InstanceShaderParameter isp;
  897. isp.index = -1;
  898. isp.info = PropertyInfo();
  899. isp.value = p_value;
  900. instance->instance_shader_parameters[p_parameter] = isp;
  901. } else {
  902. E->get().value = p_value;
  903. if (E->get().index >= 0 && instance->instance_allocated_shader_parameters) {
  904. //update directly
  905. RSG::storage->global_variables_instance_update(p_instance, E->get().index, p_value);
  906. }
  907. }
  908. }
  909. Variant RendererSceneCull::instance_geometry_get_shader_parameter(RID p_instance, const StringName &p_parameter) const {
  910. const Instance *instance = const_cast<RendererSceneCull *>(this)->instance_owner.getornull(p_instance);
  911. ERR_FAIL_COND_V(!instance, Variant());
  912. if (instance->instance_shader_parameters.has(p_parameter)) {
  913. return instance->instance_shader_parameters[p_parameter].value;
  914. }
  915. return Variant();
  916. }
  917. Variant RendererSceneCull::instance_geometry_get_shader_parameter_default_value(RID p_instance, const StringName &p_parameter) const {
  918. const Instance *instance = const_cast<RendererSceneCull *>(this)->instance_owner.getornull(p_instance);
  919. ERR_FAIL_COND_V(!instance, Variant());
  920. if (instance->instance_shader_parameters.has(p_parameter)) {
  921. return instance->instance_shader_parameters[p_parameter].default_value;
  922. }
  923. return Variant();
  924. }
  925. void RendererSceneCull::instance_geometry_get_shader_parameter_list(RID p_instance, List<PropertyInfo> *p_parameters) const {
  926. const Instance *instance = const_cast<RendererSceneCull *>(this)->instance_owner.getornull(p_instance);
  927. ERR_FAIL_COND(!instance);
  928. const_cast<RendererSceneCull *>(this)->update_dirty_instances();
  929. Vector<StringName> names;
  930. for (Map<StringName, Instance::InstanceShaderParameter>::Element *E = instance->instance_shader_parameters.front(); E; E = E->next()) {
  931. names.push_back(E->key());
  932. }
  933. names.sort_custom<StringName::AlphCompare>();
  934. for (int i = 0; i < names.size(); i++) {
  935. PropertyInfo pinfo = instance->instance_shader_parameters[names[i]].info;
  936. p_parameters->push_back(pinfo);
  937. }
  938. }
  939. void RendererSceneCull::_update_instance(Instance *p_instance) {
  940. p_instance->version++;
  941. if (p_instance->base_type == RS::INSTANCE_LIGHT) {
  942. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  943. scene_render->light_instance_set_transform(light->instance, p_instance->transform);
  944. scene_render->light_instance_set_aabb(light->instance, p_instance->transform.xform(p_instance->aabb));
  945. light->shadow_dirty = true;
  946. RS::LightBakeMode bake_mode = RSG::storage->light_get_bake_mode(p_instance->base);
  947. if (RSG::storage->light_get_type(p_instance->base) != RS::LIGHT_DIRECTIONAL && bake_mode != light->bake_mode) {
  948. if (p_instance->visible && p_instance->scenario && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  949. p_instance->scenario->dynamic_lights.erase(light->instance);
  950. }
  951. light->bake_mode = bake_mode;
  952. if (p_instance->visible && p_instance->scenario && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  953. p_instance->scenario->dynamic_lights.push_back(light->instance);
  954. }
  955. }
  956. uint32_t max_sdfgi_cascade = RSG::storage->light_get_max_sdfgi_cascade(p_instance->base);
  957. if (light->max_sdfgi_cascade != max_sdfgi_cascade) {
  958. light->max_sdfgi_cascade = max_sdfgi_cascade; //should most likely make sdfgi dirty in scenario
  959. }
  960. } else if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
  961. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  962. scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
  963. if (p_instance->scenario && p_instance->array_index >= 0) {
  964. InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
  965. idata.flags |= InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
  966. }
  967. } else if (p_instance->base_type == RS::INSTANCE_DECAL) {
  968. InstanceDecalData *decal = static_cast<InstanceDecalData *>(p_instance->base_data);
  969. scene_render->decal_instance_set_transform(decal->instance, p_instance->transform);
  970. } else if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  971. InstanceLightmapData *lightmap = static_cast<InstanceLightmapData *>(p_instance->base_data);
  972. scene_render->lightmap_instance_set_transform(lightmap->instance, p_instance->transform);
  973. } else if (p_instance->base_type == RS::INSTANCE_GI_PROBE) {
  974. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);
  975. scene_render->gi_probe_instance_set_transform_to_data(gi_probe->probe_instance, p_instance->transform);
  976. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  977. RSG::storage->particles_set_emission_transform(p_instance->base, p_instance->transform);
  978. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  979. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(p_instance->base_data);
  980. //remove materials no longer used and un-own them
  981. if (RSG::storage->particles_collision_is_heightfield(p_instance->base)) {
  982. heightfield_particle_colliders_update_list.insert(p_instance);
  983. }
  984. RSG::storage->particles_collision_instance_set_transform(collision->instance, p_instance->transform);
  985. }
  986. if (p_instance->aabb.has_no_surface()) {
  987. return;
  988. }
  989. if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  990. //if this moved, update the captured objects
  991. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(p_instance->base_data);
  992. //erase dependencies, since no longer a lightmap
  993. for (Set<Instance *>::Element *E = lightmap_data->geometries.front(); E; E = E->next()) {
  994. Instance *geom = E->get();
  995. _instance_queue_update(geom, true, false);
  996. }
  997. }
  998. AABB new_aabb;
  999. new_aabb = p_instance->transform.xform(p_instance->aabb);
  1000. p_instance->transformed_aabb = new_aabb;
  1001. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1002. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1003. //make sure lights are updated if it casts shadow
  1004. if (geom->can_cast_shadows) {
  1005. for (Set<Instance *>::Element *E = geom->lights.front(); E; E = E->next()) {
  1006. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1007. light->shadow_dirty = true;
  1008. }
  1009. }
  1010. if (!p_instance->lightmap && geom->lightmap_captures.size()) {
  1011. //affected by lightmap captures, must update capture info!
  1012. _update_instance_lightmap_captures(p_instance);
  1013. } else {
  1014. if (!p_instance->lightmap_sh.is_empty()) {
  1015. p_instance->lightmap_sh.clear(); //don't need SH
  1016. p_instance->lightmap_target_sh.clear(); //don't need SH
  1017. scene_render->geometry_instance_set_lightmap_capture(geom->geometry_instance, nullptr);
  1018. }
  1019. }
  1020. scene_render->geometry_instance_set_transform(geom->geometry_instance, p_instance->transform, p_instance->aabb, p_instance->transformed_aabb);
  1021. }
  1022. // note: we had to remove is equal approx check here, it meant that det == 0.000004 won't work, which is the case for some of our scenes.
  1023. if (p_instance->scenario == nullptr || !p_instance->visible || p_instance->transform.basis.determinant() == 0) {
  1024. p_instance->prev_transformed_aabb = p_instance->transformed_aabb;
  1025. return;
  1026. }
  1027. //quantize to improve moving object performance
  1028. AABB bvh_aabb = p_instance->transformed_aabb;
  1029. if (p_instance->indexer_id.is_valid() && bvh_aabb != p_instance->prev_transformed_aabb) {
  1030. //assume motion, see if bounds need to be quantized
  1031. AABB motion_aabb = bvh_aabb.merge(p_instance->prev_transformed_aabb);
  1032. float motion_longest_axis = motion_aabb.get_longest_axis_size();
  1033. float longest_axis = p_instance->transformed_aabb.get_longest_axis_size();
  1034. if (motion_longest_axis < longest_axis * 2) {
  1035. //moved but not a lot, use motion aabb quantizing
  1036. float quantize_size = Math::pow(2.0, Math::ceil(Math::log(motion_longest_axis) / Math::log(2.0))) * 0.5; //one fifth
  1037. bvh_aabb.quantize(quantize_size);
  1038. }
  1039. }
  1040. if (!p_instance->indexer_id.is_valid()) {
  1041. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1042. p_instance->indexer_id = p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].insert(bvh_aabb, p_instance);
  1043. } else {
  1044. p_instance->indexer_id = p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].insert(bvh_aabb, p_instance);
  1045. }
  1046. p_instance->array_index = p_instance->scenario->instance_data.size();
  1047. InstanceData idata;
  1048. idata.instance = p_instance;
  1049. idata.layer_mask = p_instance->layer_mask;
  1050. idata.flags = p_instance->base_type; //changing it means de-indexing, so this never needs to be changed later
  1051. idata.base_rid = p_instance->base;
  1052. switch (p_instance->base_type) {
  1053. case RS::INSTANCE_MESH:
  1054. case RS::INSTANCE_MULTIMESH:
  1055. case RS::INSTANCE_IMMEDIATE:
  1056. case RS::INSTANCE_PARTICLES: {
  1057. idata.instance_geometry = static_cast<InstanceGeometryData *>(p_instance->base_data)->geometry_instance;
  1058. } break;
  1059. case RS::INSTANCE_LIGHT: {
  1060. idata.instance_data_rid = static_cast<InstanceLightData *>(p_instance->base_data)->instance.get_id();
  1061. } break;
  1062. case RS::INSTANCE_REFLECTION_PROBE: {
  1063. idata.instance_data_rid = static_cast<InstanceReflectionProbeData *>(p_instance->base_data)->instance.get_id();
  1064. } break;
  1065. case RS::INSTANCE_DECAL: {
  1066. idata.instance_data_rid = static_cast<InstanceDecalData *>(p_instance->base_data)->instance.get_id();
  1067. } break;
  1068. case RS::INSTANCE_LIGHTMAP: {
  1069. idata.instance_data_rid = static_cast<InstanceLightmapData *>(p_instance->base_data)->instance.get_id();
  1070. } break;
  1071. case RS::INSTANCE_GI_PROBE: {
  1072. idata.instance_data_rid = static_cast<InstanceGIProbeData *>(p_instance->base_data)->probe_instance.get_id();
  1073. } break;
  1074. default: {
  1075. }
  1076. }
  1077. if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
  1078. //always dirty when added
  1079. idata.flags |= InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
  1080. }
  1081. if (p_instance->cast_shadows != RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  1082. idata.flags |= InstanceData::FLAG_CAST_SHADOWS;
  1083. }
  1084. if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  1085. idata.flags |= InstanceData::FLAG_CAST_SHADOWS_ONLY;
  1086. }
  1087. if (p_instance->redraw_if_visible) {
  1088. idata.flags |= InstanceData::FLAG_REDRAW_IF_VISIBLE;
  1089. }
  1090. // dirty flags should not be set here, since no pairing has happened
  1091. if (p_instance->baked_light) {
  1092. idata.flags |= InstanceData::FLAG_USES_BAKED_LIGHT;
  1093. }
  1094. if (p_instance->mesh_instance.is_valid()) {
  1095. idata.flags |= InstanceData::FLAG_USES_MESH_INSTANCE;
  1096. }
  1097. p_instance->scenario->instance_data.push_back(idata);
  1098. p_instance->scenario->instance_aabbs.push_back(InstanceBounds(p_instance->transformed_aabb));
  1099. } else {
  1100. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1101. p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].update(p_instance->indexer_id, bvh_aabb);
  1102. } else {
  1103. p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].update(p_instance->indexer_id, bvh_aabb);
  1104. }
  1105. p_instance->scenario->instance_aabbs[p_instance->array_index] = InstanceBounds(p_instance->transformed_aabb);
  1106. }
  1107. //move instance and repair
  1108. pair_pass++;
  1109. PairInstances pair;
  1110. pair.instance = p_instance;
  1111. pair.pair_allocator = &pair_allocator;
  1112. pair.pair_pass = pair_pass;
  1113. pair.pair_mask = 0;
  1114. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1115. pair.pair_mask |= 1 << RS::INSTANCE_LIGHT;
  1116. pair.pair_mask |= 1 << RS::INSTANCE_GI_PROBE;
  1117. pair.pair_mask |= 1 << RS::INSTANCE_LIGHTMAP;
  1118. pair.pair_mask |= geometry_instance_pair_mask;
  1119. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1120. } else if (p_instance->base_type == RS::INSTANCE_LIGHT) {
  1121. pair.pair_mask |= RS::INSTANCE_GEOMETRY_MASK;
  1122. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1123. if (RSG::storage->light_get_bake_mode(p_instance->base) == RS::LIGHT_BAKE_DYNAMIC) {
  1124. pair.pair_mask |= (1 << RS::INSTANCE_GI_PROBE);
  1125. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1126. }
  1127. } else if (geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE)) {
  1128. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
  1129. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1130. } else if (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && (p_instance->base_type == RS::INSTANCE_DECAL)) {
  1131. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
  1132. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1133. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  1134. pair.pair_mask = (1 << RS::INSTANCE_PARTICLES);
  1135. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1136. } else if (p_instance->base_type == RS::INSTANCE_GI_PROBE) {
  1137. //lights and geometries
  1138. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT);
  1139. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1140. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1141. }
  1142. pair.pair();
  1143. p_instance->prev_transformed_aabb = p_instance->transformed_aabb;
  1144. }
  1145. void RendererSceneCull::_unpair_instance(Instance *p_instance) {
  1146. if (!p_instance->indexer_id.is_valid()) {
  1147. return; //nothing to do
  1148. }
  1149. while (p_instance->pairs.first()) {
  1150. InstancePair *pair = p_instance->pairs.first()->self();
  1151. Instance *other_instance = p_instance == pair->a ? pair->b : pair->a;
  1152. _instance_unpair(p_instance, other_instance);
  1153. pair_allocator.free(pair);
  1154. }
  1155. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1156. p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].remove(p_instance->indexer_id);
  1157. } else {
  1158. p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].remove(p_instance->indexer_id);
  1159. }
  1160. p_instance->indexer_id = DynamicBVH::ID();
  1161. //replace this by last
  1162. int32_t swap_with_index = p_instance->scenario->instance_data.size() - 1;
  1163. if (swap_with_index != p_instance->array_index) {
  1164. p_instance->scenario->instance_data[swap_with_index].instance->array_index = p_instance->array_index; //swap
  1165. p_instance->scenario->instance_data[p_instance->array_index] = p_instance->scenario->instance_data[swap_with_index];
  1166. p_instance->scenario->instance_aabbs[p_instance->array_index] = p_instance->scenario->instance_aabbs[swap_with_index];
  1167. }
  1168. // pop last
  1169. p_instance->scenario->instance_data.pop_back();
  1170. p_instance->scenario->instance_aabbs.pop_back();
  1171. //uninitialize
  1172. p_instance->array_index = -1;
  1173. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1174. // Clear these now because the InstanceData containing the dirty flags is gone
  1175. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1176. scene_render->geometry_instance_pair_light_instances(geom->geometry_instance, nullptr, 0);
  1177. scene_render->geometry_instance_pair_reflection_probe_instances(geom->geometry_instance, nullptr, 0);
  1178. scene_render->geometry_instance_pair_decal_instances(geom->geometry_instance, nullptr, 0);
  1179. scene_render->geometry_instance_pair_gi_probe_instances(geom->geometry_instance, nullptr, 0);
  1180. }
  1181. }
  1182. void RendererSceneCull::_update_instance_aabb(Instance *p_instance) {
  1183. AABB new_aabb;
  1184. ERR_FAIL_COND(p_instance->base_type != RS::INSTANCE_NONE && !p_instance->base.is_valid());
  1185. switch (p_instance->base_type) {
  1186. case RenderingServer::INSTANCE_NONE: {
  1187. // do nothing
  1188. } break;
  1189. case RenderingServer::INSTANCE_MESH: {
  1190. if (p_instance->custom_aabb) {
  1191. new_aabb = *p_instance->custom_aabb;
  1192. } else {
  1193. new_aabb = RSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
  1194. }
  1195. } break;
  1196. case RenderingServer::INSTANCE_MULTIMESH: {
  1197. if (p_instance->custom_aabb) {
  1198. new_aabb = *p_instance->custom_aabb;
  1199. } else {
  1200. new_aabb = RSG::storage->multimesh_get_aabb(p_instance->base);
  1201. }
  1202. } break;
  1203. case RenderingServer::INSTANCE_IMMEDIATE: {
  1204. if (p_instance->custom_aabb) {
  1205. new_aabb = *p_instance->custom_aabb;
  1206. } else {
  1207. new_aabb = RSG::storage->immediate_get_aabb(p_instance->base);
  1208. }
  1209. } break;
  1210. case RenderingServer::INSTANCE_PARTICLES: {
  1211. if (p_instance->custom_aabb) {
  1212. new_aabb = *p_instance->custom_aabb;
  1213. } else {
  1214. new_aabb = RSG::storage->particles_get_aabb(p_instance->base);
  1215. }
  1216. } break;
  1217. case RenderingServer::INSTANCE_PARTICLES_COLLISION: {
  1218. new_aabb = RSG::storage->particles_collision_get_aabb(p_instance->base);
  1219. } break;
  1220. case RenderingServer::INSTANCE_LIGHT: {
  1221. new_aabb = RSG::storage->light_get_aabb(p_instance->base);
  1222. } break;
  1223. case RenderingServer::INSTANCE_REFLECTION_PROBE: {
  1224. new_aabb = RSG::storage->reflection_probe_get_aabb(p_instance->base);
  1225. } break;
  1226. case RenderingServer::INSTANCE_DECAL: {
  1227. new_aabb = RSG::storage->decal_get_aabb(p_instance->base);
  1228. } break;
  1229. case RenderingServer::INSTANCE_GI_PROBE: {
  1230. new_aabb = RSG::storage->gi_probe_get_bounds(p_instance->base);
  1231. } break;
  1232. case RenderingServer::INSTANCE_LIGHTMAP: {
  1233. new_aabb = RSG::storage->lightmap_get_aabb(p_instance->base);
  1234. } break;
  1235. default: {
  1236. }
  1237. }
  1238. // <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
  1239. if (p_instance->extra_margin) {
  1240. new_aabb.grow_by(p_instance->extra_margin);
  1241. }
  1242. p_instance->aabb = new_aabb;
  1243. }
  1244. void RendererSceneCull::_update_instance_lightmap_captures(Instance *p_instance) {
  1245. bool first_set = p_instance->lightmap_sh.size() == 0;
  1246. p_instance->lightmap_sh.resize(9); //using SH
  1247. p_instance->lightmap_target_sh.resize(9); //using SH
  1248. Color *instance_sh = p_instance->lightmap_target_sh.ptrw();
  1249. bool inside = false;
  1250. Color accum_sh[9];
  1251. float accum_blend = 0.0;
  1252. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1253. for (Set<Instance *>::Element *E = geom->lightmap_captures.front(); E; E = E->next()) {
  1254. Instance *lightmap = E->get();
  1255. bool interior = RSG::storage->lightmap_is_interior(lightmap->base);
  1256. if (inside && !interior) {
  1257. continue; //we are inside, ignore exteriors
  1258. }
  1259. Transform to_bounds = lightmap->transform.affine_inverse();
  1260. Vector3 center = p_instance->transform.xform(p_instance->aabb.position + p_instance->aabb.size * 0.5); //use aabb center
  1261. Vector3 lm_pos = to_bounds.xform(center);
  1262. AABB bounds = RSG::storage->lightmap_get_aabb(lightmap->base);
  1263. if (!bounds.has_point(lm_pos)) {
  1264. continue; //not in this lightmap
  1265. }
  1266. Color sh[9];
  1267. RSG::storage->lightmap_tap_sh_light(lightmap->base, lm_pos, sh);
  1268. //rotate it
  1269. Basis rot = lightmap->transform.basis.orthonormalized();
  1270. for (int i = 0; i < 3; i++) {
  1271. float csh[9];
  1272. for (int j = 0; j < 9; j++) {
  1273. csh[j] = sh[j][i];
  1274. }
  1275. rot.rotate_sh(csh);
  1276. for (int j = 0; j < 9; j++) {
  1277. sh[j][i] = csh[j];
  1278. }
  1279. }
  1280. Vector3 inner_pos = ((lm_pos - bounds.position) / bounds.size) * 2.0 - Vector3(1.0, 1.0, 1.0);
  1281. float blend = MAX(inner_pos.x, MAX(inner_pos.y, inner_pos.z));
  1282. //make blend more rounded
  1283. blend = Math::lerp(inner_pos.length(), blend, blend);
  1284. blend *= blend;
  1285. blend = MAX(0.0, 1.0 - blend);
  1286. if (interior && !inside) {
  1287. //do not blend, just replace
  1288. for (int j = 0; j < 9; j++) {
  1289. accum_sh[j] = sh[j] * blend;
  1290. }
  1291. accum_blend = blend;
  1292. inside = true;
  1293. } else {
  1294. for (int j = 0; j < 9; j++) {
  1295. accum_sh[j] += sh[j] * blend;
  1296. }
  1297. accum_blend += blend;
  1298. }
  1299. }
  1300. if (accum_blend > 0.0) {
  1301. for (int j = 0; j < 9; j++) {
  1302. instance_sh[j] = accum_sh[j] / accum_blend;
  1303. if (first_set) {
  1304. p_instance->lightmap_sh.write[j] = instance_sh[j];
  1305. }
  1306. }
  1307. }
  1308. scene_render->geometry_instance_set_lightmap_capture(geom->geometry_instance, p_instance->lightmap_sh.ptr());
  1309. }
  1310. void RendererSceneCull::_light_instance_setup_directional_shadow(int p_shadow_index, Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect) {
  1311. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1312. Transform light_transform = p_instance->transform;
  1313. light_transform.orthonormalize(); //scale does not count on lights
  1314. real_t max_distance = p_cam_projection.get_z_far();
  1315. real_t shadow_max = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
  1316. if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
  1317. max_distance = MIN(shadow_max, max_distance);
  1318. }
  1319. max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
  1320. real_t min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
  1321. RS::LightDirectionalShadowDepthRangeMode depth_range_mode = RSG::storage->light_directional_get_shadow_depth_range_mode(p_instance->base);
  1322. real_t pancake_size = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE);
  1323. real_t range = max_distance - min_distance;
  1324. int splits = 0;
  1325. switch (RSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
  1326. case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  1327. splits = 1;
  1328. break;
  1329. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  1330. splits = 2;
  1331. break;
  1332. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  1333. splits = 4;
  1334. break;
  1335. }
  1336. real_t distances[5];
  1337. distances[0] = min_distance;
  1338. for (int i = 0; i < splits; i++) {
  1339. distances[i + 1] = min_distance + RSG::storage->light_get_param(p_instance->base, RS::LightParam(RS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
  1340. };
  1341. distances[splits] = max_distance;
  1342. real_t texture_size = scene_render->get_directional_light_shadow_size(light->instance);
  1343. bool overlap = RSG::storage->light_directional_get_blend_splits(p_instance->base);
  1344. real_t first_radius = 0.0;
  1345. real_t min_distance_bias_scale = distances[1];
  1346. cull.shadow_count = p_shadow_index + 1;
  1347. cull.shadows[p_shadow_index].cascade_count = splits;
  1348. cull.shadows[p_shadow_index].light_instance = light->instance;
  1349. for (int i = 0; i < splits; i++) {
  1350. RENDER_TIMESTAMP("Culling Directional Light split" + itos(i));
  1351. // setup a camera matrix for that range!
  1352. CameraMatrix camera_matrix;
  1353. real_t aspect = p_cam_projection.get_aspect();
  1354. if (p_cam_orthogonal) {
  1355. Vector2 vp_he = p_cam_projection.get_viewport_half_extents();
  1356. camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1357. } else {
  1358. real_t fov = p_cam_projection.get_fov(); //this is actually yfov, because set aspect tries to keep it
  1359. camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1360. }
  1361. //obtain the frustum endpoints
  1362. Vector3 endpoints[8]; // frustum plane endpoints
  1363. bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
  1364. ERR_CONTINUE(!res);
  1365. // obtain the light frustum ranges (given endpoints)
  1366. Transform transform = light_transform; //discard scale and stabilize light
  1367. Vector3 x_vec = transform.basis.get_axis(Vector3::AXIS_X).normalized();
  1368. Vector3 y_vec = transform.basis.get_axis(Vector3::AXIS_Y).normalized();
  1369. Vector3 z_vec = transform.basis.get_axis(Vector3::AXIS_Z).normalized();
  1370. //z_vec points against the camera, like in default opengl
  1371. real_t x_min = 0.f, x_max = 0.f;
  1372. real_t y_min = 0.f, y_max = 0.f;
  1373. real_t z_min = 0.f, z_max = 0.f;
  1374. // FIXME: z_max_cam is defined, computed, but not used below when setting up
  1375. // ortho_camera. Commented out for now to fix warnings but should be investigated.
  1376. real_t x_min_cam = 0.f, x_max_cam = 0.f;
  1377. real_t y_min_cam = 0.f, y_max_cam = 0.f;
  1378. real_t z_min_cam = 0.f;
  1379. //real_t z_max_cam = 0.f;
  1380. real_t bias_scale = 1.0;
  1381. real_t aspect_bias_scale = 1.0;
  1382. //used for culling
  1383. for (int j = 0; j < 8; j++) {
  1384. real_t d_x = x_vec.dot(endpoints[j]);
  1385. real_t d_y = y_vec.dot(endpoints[j]);
  1386. real_t d_z = z_vec.dot(endpoints[j]);
  1387. if (j == 0 || d_x < x_min) {
  1388. x_min = d_x;
  1389. }
  1390. if (j == 0 || d_x > x_max) {
  1391. x_max = d_x;
  1392. }
  1393. if (j == 0 || d_y < y_min) {
  1394. y_min = d_y;
  1395. }
  1396. if (j == 0 || d_y > y_max) {
  1397. y_max = d_y;
  1398. }
  1399. if (j == 0 || d_z < z_min) {
  1400. z_min = d_z;
  1401. }
  1402. if (j == 0 || d_z > z_max) {
  1403. z_max = d_z;
  1404. }
  1405. }
  1406. real_t radius = 0;
  1407. real_t soft_shadow_expand = 0;
  1408. Vector3 center;
  1409. {
  1410. //camera viewport stuff
  1411. for (int j = 0; j < 8; j++) {
  1412. center += endpoints[j];
  1413. }
  1414. center /= 8.0;
  1415. //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;
  1416. for (int j = 0; j < 8; j++) {
  1417. real_t d = center.distance_to(endpoints[j]);
  1418. if (d > radius) {
  1419. radius = d;
  1420. }
  1421. }
  1422. radius *= texture_size / (texture_size - 2.0); //add a texel by each side
  1423. if (i == 0) {
  1424. first_radius = radius;
  1425. } else {
  1426. bias_scale = radius / first_radius;
  1427. }
  1428. z_min_cam = z_vec.dot(center) - radius;
  1429. {
  1430. float soft_shadow_angle = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE);
  1431. if (soft_shadow_angle > 0.0) {
  1432. float z_range = (z_vec.dot(center) + radius + pancake_size) - z_min_cam;
  1433. soft_shadow_expand = Math::tan(Math::deg2rad(soft_shadow_angle)) * z_range;
  1434. x_max += soft_shadow_expand;
  1435. y_max += soft_shadow_expand;
  1436. x_min -= soft_shadow_expand;
  1437. y_min -= soft_shadow_expand;
  1438. }
  1439. }
  1440. x_max_cam = x_vec.dot(center) + radius + soft_shadow_expand;
  1441. x_min_cam = x_vec.dot(center) - radius - soft_shadow_expand;
  1442. y_max_cam = y_vec.dot(center) + radius + soft_shadow_expand;
  1443. y_min_cam = y_vec.dot(center) - radius - soft_shadow_expand;
  1444. if (depth_range_mode == RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE) {
  1445. //this trick here is what stabilizes the shadow (make potential jaggies to not move)
  1446. //at the cost of some wasted resolution. Still the quality increase is very well worth it
  1447. real_t unit = radius * 2.0 / texture_size;
  1448. x_max_cam = Math::snapped(x_max_cam, unit);
  1449. x_min_cam = Math::snapped(x_min_cam, unit);
  1450. y_max_cam = Math::snapped(y_max_cam, unit);
  1451. y_min_cam = Math::snapped(y_min_cam, unit);
  1452. }
  1453. }
  1454. //now that we know all ranges, we can proceed to make the light frustum planes, for culling octree
  1455. Vector<Plane> light_frustum_planes;
  1456. light_frustum_planes.resize(6);
  1457. //right/left
  1458. light_frustum_planes.write[0] = Plane(x_vec, x_max);
  1459. light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
  1460. //top/bottom
  1461. light_frustum_planes.write[2] = Plane(y_vec, y_max);
  1462. light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
  1463. //near/far
  1464. light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
  1465. light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
  1466. // a pre pass will need to be needed to determine the actual z-near to be used
  1467. if (pancake_size > 0) {
  1468. z_max = z_vec.dot(center) + radius + pancake_size;
  1469. }
  1470. if (aspect != 1.0) {
  1471. // if the aspect is different, then the radius will become larger.
  1472. // if this happens, then bias needs to be adjusted too, as depth will increase
  1473. // to do this, compare the depth of one that would have resulted from a square frustum
  1474. CameraMatrix camera_matrix_square;
  1475. if (p_cam_orthogonal) {
  1476. Vector2 vp_he = camera_matrix.get_viewport_half_extents();
  1477. if (p_cam_vaspect) {
  1478. camera_matrix_square.set_orthogonal(vp_he.x * 2.0, 1.0, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1479. } else {
  1480. camera_matrix_square.set_orthogonal(vp_he.y * 2.0, 1.0, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1481. }
  1482. } else {
  1483. Vector2 vp_he = camera_matrix.get_viewport_half_extents();
  1484. if (p_cam_vaspect) {
  1485. camera_matrix_square.set_frustum(vp_he.x * 2.0, 1.0, Vector2(), distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1486. } else {
  1487. camera_matrix_square.set_frustum(vp_he.y * 2.0, 1.0, Vector2(), distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1488. }
  1489. }
  1490. Vector3 endpoints_square[8]; // frustum plane endpoints
  1491. res = camera_matrix_square.get_endpoints(p_cam_transform, endpoints_square);
  1492. ERR_CONTINUE(!res);
  1493. Vector3 center_square;
  1494. for (int j = 0; j < 8; j++) {
  1495. center_square += endpoints_square[j];
  1496. }
  1497. center_square /= 8.0;
  1498. real_t radius_square = 0;
  1499. for (int j = 0; j < 8; j++) {
  1500. real_t d = center_square.distance_to(endpoints_square[j]);
  1501. if (d > radius_square) {
  1502. radius_square = d;
  1503. }
  1504. }
  1505. radius_square *= texture_size / (texture_size - 2.0); //add a texel by each side
  1506. float z_max_square = z_vec.dot(center_square) + radius_square + pancake_size;
  1507. real_t z_min_cam_square = z_vec.dot(center_square) - radius_square;
  1508. aspect_bias_scale = (z_max - z_min_cam) / (z_max_square - z_min_cam_square);
  1509. // this is not entirely perfect, because the cull-adjusted z-max may be different
  1510. // but at least it's warranted that it results in a greater bias, so no acne should be present either way.
  1511. // pancaking also helps with this.
  1512. }
  1513. {
  1514. CameraMatrix ortho_camera;
  1515. real_t half_x = (x_max_cam - x_min_cam) * 0.5;
  1516. real_t half_y = (y_max_cam - y_min_cam) * 0.5;
  1517. ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
  1518. Vector2 uv_scale(1.0 / (x_max_cam - x_min_cam), 1.0 / (y_max_cam - y_min_cam));
  1519. Transform ortho_transform;
  1520. ortho_transform.basis = transform.basis;
  1521. ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
  1522. cull.shadows[p_shadow_index].cascades[i].frustum = Frustum(light_frustum_planes);
  1523. cull.shadows[p_shadow_index].cascades[i].projection = ortho_camera;
  1524. cull.shadows[p_shadow_index].cascades[i].transform = ortho_transform;
  1525. cull.shadows[p_shadow_index].cascades[i].zfar = z_max - z_min_cam;
  1526. cull.shadows[p_shadow_index].cascades[i].split = distances[i + 1];
  1527. cull.shadows[p_shadow_index].cascades[i].shadow_texel_size = radius * 2.0 / texture_size;
  1528. cull.shadows[p_shadow_index].cascades[i].bias_scale = bias_scale * aspect_bias_scale * min_distance_bias_scale;
  1529. cull.shadows[p_shadow_index].cascades[i].range_begin = z_max;
  1530. cull.shadows[p_shadow_index].cascades[i].uv_scale = uv_scale;
  1531. }
  1532. }
  1533. }
  1534. bool RendererSceneCull::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_shadow_atlas, Scenario *p_scenario, float p_screen_lod_threshold) {
  1535. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1536. Transform light_transform = p_instance->transform;
  1537. light_transform.orthonormalize(); //scale does not count on lights
  1538. bool animated_material_found = false;
  1539. switch (RSG::storage->light_get_type(p_instance->base)) {
  1540. case RS::LIGHT_DIRECTIONAL: {
  1541. } break;
  1542. case RS::LIGHT_OMNI: {
  1543. RS::LightOmniShadowMode shadow_mode = RSG::storage->light_omni_get_shadow_mode(p_instance->base);
  1544. if (shadow_mode == RS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !scene_render->light_instances_can_render_shadow_cube()) {
  1545. if (max_shadows_used + 2 > MAX_UPDATE_SHADOWS) {
  1546. return true;
  1547. }
  1548. for (int i = 0; i < 2; i++) {
  1549. //using this one ensures that raster deferred will have it
  1550. RENDER_TIMESTAMP("Culling Shadow Paraboloid" + itos(i));
  1551. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1552. real_t z = i == 0 ? -1 : 1;
  1553. Vector<Plane> planes;
  1554. planes.resize(6);
  1555. planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
  1556. planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
  1557. planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
  1558. planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
  1559. planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
  1560. planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
  1561. instance_shadow_cull_result.clear();
  1562. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  1563. struct CullConvex {
  1564. PagedArray<Instance *> *result;
  1565. _FORCE_INLINE_ bool operator()(void *p_data) {
  1566. Instance *p_instance = (Instance *)p_data;
  1567. result->push_back(p_instance);
  1568. return false;
  1569. }
  1570. };
  1571. CullConvex cull_convex;
  1572. cull_convex.result = &instance_shadow_cull_result;
  1573. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  1574. Plane near_plane(light_transform.origin, light_transform.basis.get_axis(2) * z);
  1575. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  1576. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  1577. Instance *instance = instance_shadow_cull_result[j];
  1578. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1579. continue;
  1580. } else {
  1581. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1582. animated_material_found = true;
  1583. }
  1584. if (instance->mesh_instance.is_valid()) {
  1585. RSG::storage->mesh_instance_check_for_update(instance->mesh_instance);
  1586. }
  1587. }
  1588. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  1589. }
  1590. RSG::storage->update_mesh_instances();
  1591. scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, i, 0);
  1592. shadow_data.light = light->instance;
  1593. shadow_data.pass = i;
  1594. }
  1595. } else { //shadow cube
  1596. if (max_shadows_used + 6 > MAX_UPDATE_SHADOWS) {
  1597. return true;
  1598. }
  1599. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1600. CameraMatrix cm;
  1601. cm.set_perspective(90, 1, 0.01, radius);
  1602. for (int i = 0; i < 6; i++) {
  1603. RENDER_TIMESTAMP("Culling Shadow Cube side" + itos(i));
  1604. //using this one ensures that raster deferred will have it
  1605. static const Vector3 view_normals[6] = {
  1606. Vector3(+1, 0, 0),
  1607. Vector3(-1, 0, 0),
  1608. Vector3(0, -1, 0),
  1609. Vector3(0, +1, 0),
  1610. Vector3(0, 0, +1),
  1611. Vector3(0, 0, -1)
  1612. };
  1613. static const Vector3 view_up[6] = {
  1614. Vector3(0, -1, 0),
  1615. Vector3(0, -1, 0),
  1616. Vector3(0, 0, -1),
  1617. Vector3(0, 0, +1),
  1618. Vector3(0, -1, 0),
  1619. Vector3(0, -1, 0)
  1620. };
  1621. Transform xform = light_transform * Transform().looking_at(view_normals[i], view_up[i]);
  1622. Vector<Plane> planes = cm.get_projection_planes(xform);
  1623. instance_shadow_cull_result.clear();
  1624. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  1625. struct CullConvex {
  1626. PagedArray<Instance *> *result;
  1627. _FORCE_INLINE_ bool operator()(void *p_data) {
  1628. Instance *p_instance = (Instance *)p_data;
  1629. result->push_back(p_instance);
  1630. return false;
  1631. }
  1632. };
  1633. CullConvex cull_convex;
  1634. cull_convex.result = &instance_shadow_cull_result;
  1635. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  1636. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  1637. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  1638. Instance *instance = instance_shadow_cull_result[j];
  1639. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1640. continue;
  1641. } else {
  1642. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1643. animated_material_found = true;
  1644. }
  1645. if (instance->mesh_instance.is_valid()) {
  1646. RSG::storage->mesh_instance_check_for_update(instance->mesh_instance);
  1647. }
  1648. }
  1649. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  1650. }
  1651. RSG::storage->update_mesh_instances();
  1652. scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i, 0);
  1653. shadow_data.light = light->instance;
  1654. shadow_data.pass = i;
  1655. }
  1656. //restore the regular DP matrix
  1657. //scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, 0, 0);
  1658. }
  1659. } break;
  1660. case RS::LIGHT_SPOT: {
  1661. RENDER_TIMESTAMP("Culling Spot Light");
  1662. if (max_shadows_used + 1 > MAX_UPDATE_SHADOWS) {
  1663. return true;
  1664. }
  1665. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1666. real_t angle = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1667. CameraMatrix cm;
  1668. cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);
  1669. Vector<Plane> planes = cm.get_projection_planes(light_transform);
  1670. instance_shadow_cull_result.clear();
  1671. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  1672. struct CullConvex {
  1673. PagedArray<Instance *> *result;
  1674. _FORCE_INLINE_ bool operator()(void *p_data) {
  1675. Instance *p_instance = (Instance *)p_data;
  1676. result->push_back(p_instance);
  1677. return false;
  1678. }
  1679. };
  1680. CullConvex cull_convex;
  1681. cull_convex.result = &instance_shadow_cull_result;
  1682. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  1683. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  1684. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  1685. Instance *instance = instance_shadow_cull_result[j];
  1686. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1687. continue;
  1688. } else {
  1689. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1690. animated_material_found = true;
  1691. }
  1692. if (instance->mesh_instance.is_valid()) {
  1693. RSG::storage->mesh_instance_check_for_update(instance->mesh_instance);
  1694. }
  1695. }
  1696. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  1697. }
  1698. RSG::storage->update_mesh_instances();
  1699. scene_render->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0, 0);
  1700. shadow_data.light = light->instance;
  1701. shadow_data.pass = 0;
  1702. } break;
  1703. }
  1704. return animated_material_found;
  1705. }
  1706. void RendererSceneCull::render_camera(RID p_render_buffers, RID p_camera, RID p_scenario, Size2 p_viewport_size, float p_screen_lod_threshold, RID p_shadow_atlas) {
  1707. // render to mono camera
  1708. #ifndef _3D_DISABLED
  1709. Camera *camera = camera_owner.getornull(p_camera);
  1710. ERR_FAIL_COND(!camera);
  1711. /* STEP 1 - SETUP CAMERA */
  1712. CameraMatrix camera_matrix;
  1713. bool ortho = false;
  1714. switch (camera->type) {
  1715. case Camera::ORTHOGONAL: {
  1716. camera_matrix.set_orthogonal(
  1717. camera->size,
  1718. p_viewport_size.width / (float)p_viewport_size.height,
  1719. camera->znear,
  1720. camera->zfar,
  1721. camera->vaspect);
  1722. ortho = true;
  1723. } break;
  1724. case Camera::PERSPECTIVE: {
  1725. camera_matrix.set_perspective(
  1726. camera->fov,
  1727. p_viewport_size.width / (float)p_viewport_size.height,
  1728. camera->znear,
  1729. camera->zfar,
  1730. camera->vaspect);
  1731. ortho = false;
  1732. } break;
  1733. case Camera::FRUSTUM: {
  1734. camera_matrix.set_frustum(
  1735. camera->size,
  1736. p_viewport_size.width / (float)p_viewport_size.height,
  1737. camera->offset,
  1738. camera->znear,
  1739. camera->zfar,
  1740. camera->vaspect);
  1741. ortho = false;
  1742. } break;
  1743. }
  1744. RID environment = _render_get_environment(p_camera, p_scenario);
  1745. _render_scene(camera->transform, camera_matrix, ortho, camera->vaspect, p_render_buffers, environment, camera->effects, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), -1, p_screen_lod_threshold);
  1746. #endif
  1747. }
  1748. void RendererSceneCull::render_camera(RID p_render_buffers, Ref<XRInterface> &p_interface, XRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, float p_screen_lod_threshold, RID p_shadow_atlas) {
  1749. // render for AR/VR interface
  1750. #if 0
  1751. Camera *camera = camera_owner.getornull(p_camera);
  1752. ERR_FAIL_COND(!camera);
  1753. /* SETUP CAMERA, we are ignoring type and FOV here */
  1754. float aspect = p_viewport_size.width / (float)p_viewport_size.height;
  1755. CameraMatrix camera_matrix = p_interface->get_projection_for_eye(p_eye, aspect, camera->znear, camera->zfar);
  1756. // We also ignore our camera position, it will have been positioned with a slightly old tracking position.
  1757. // Instead we take our origin point and have our ar/vr interface add fresh tracking data! Whoohoo!
  1758. Transform world_origin = XRServer::get_singleton()->get_world_origin();
  1759. Transform cam_transform = p_interface->get_transform_for_eye(p_eye, world_origin);
  1760. RID environment = _render_get_environment(p_camera, p_scenario);
  1761. // For stereo render we only prepare for our left eye and then reuse the outcome for our right eye
  1762. if (p_eye == XRInterface::EYE_LEFT) {
  1763. // Center our transform, we assume basis is equal.
  1764. Transform mono_transform = cam_transform;
  1765. Transform right_transform = p_interface->get_transform_for_eye(XRInterface::EYE_RIGHT, world_origin);
  1766. mono_transform.origin += right_transform.origin;
  1767. mono_transform.origin *= 0.5;
  1768. // We need to combine our projection frustums for culling.
  1769. // Ideally we should use our clipping planes for this and combine them,
  1770. // however our shadow map logic uses our projection matrix.
  1771. // Note: as our left and right frustums should be mirrored, we don't need our right projection matrix.
  1772. // - get some base values we need
  1773. float eye_dist = (mono_transform.origin - cam_transform.origin).length();
  1774. float z_near = camera_matrix.get_z_near(); // get our near plane
  1775. float z_far = camera_matrix.get_z_far(); // get our far plane
  1776. float width = (2.0 * z_near) / camera_matrix.matrix[0][0];
  1777. float x_shift = width * camera_matrix.matrix[2][0];
  1778. float height = (2.0 * z_near) / camera_matrix.matrix[1][1];
  1779. float y_shift = height * camera_matrix.matrix[2][1];
  1780. // printf("Eye_dist = %f, Near = %f, Far = %f, Width = %f, Shift = %f\n", eye_dist, z_near, z_far, width, x_shift);
  1781. // - calculate our near plane size (horizontal only, right_near is mirrored)
  1782. float left_near = -eye_dist - ((width - x_shift) * 0.5);
  1783. // - calculate our far plane size (horizontal only, right_far is mirrored)
  1784. float left_far = -eye_dist - (z_far * (width - x_shift) * 0.5 / z_near);
  1785. float left_far_right_eye = eye_dist - (z_far * (width + x_shift) * 0.5 / z_near);
  1786. if (left_far > left_far_right_eye) {
  1787. // on displays smaller then double our iod, the right eye far frustrum can overtake the left eyes.
  1788. left_far = left_far_right_eye;
  1789. }
  1790. // - figure out required z-shift
  1791. float slope = (left_far - left_near) / (z_far - z_near);
  1792. float z_shift = (left_near / slope) - z_near;
  1793. // - figure out new vertical near plane size (this will be slightly oversized thanks to our z-shift)
  1794. float top_near = (height - y_shift) * 0.5;
  1795. top_near += (top_near / z_near) * z_shift;
  1796. float bottom_near = -(height + y_shift) * 0.5;
  1797. bottom_near += (bottom_near / z_near) * z_shift;
  1798. // 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);
  1799. // - generate our frustum
  1800. CameraMatrix combined_matrix;
  1801. combined_matrix.set_frustum(left_near, -left_near, bottom_near, top_near, z_near + z_shift, z_far + z_shift);
  1802. // and finally move our camera back
  1803. Transform apply_z_shift;
  1804. apply_z_shift.origin = Vector3(0.0, 0.0, z_shift); // z negative is forward so this moves it backwards
  1805. mono_transform *= apply_z_shift;
  1806. // now prepare our scene with our adjusted transform projection matrix
  1807. _prepare_scene(mono_transform, combined_matrix, false, false, p_render_buffers, environment, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), p_screen_lod_threshold);
  1808. } else if (p_eye == XRInterface::EYE_MONO) {
  1809. // For mono render, prepare as per usual
  1810. _prepare_scene(cam_transform, camera_matrix, false, false, p_render_buffers, environment, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), p_screen_lod_threshold);
  1811. }
  1812. // And render our scene...
  1813. _render_scene(p_render_buffers, cam_transform, camera_matrix, false, environment, camera->effects, p_scenario, p_shadow_atlas, RID(), -1, p_screen_lod_threshold);
  1814. #endif
  1815. };
  1816. void RendererSceneCull::_frustum_cull_threaded(uint32_t p_thread, FrustumCullData *cull_data) {
  1817. uint32_t cull_total = cull_data->scenario->instance_data.size();
  1818. uint32_t total_threads = RendererThreadPool::singleton->thread_work_pool.get_thread_count();
  1819. uint32_t cull_from = p_thread * cull_total / total_threads;
  1820. uint32_t cull_to = (p_thread + 1 == total_threads) ? cull_total : ((p_thread + 1) * cull_total / total_threads);
  1821. _frustum_cull(*cull_data, frustum_cull_result_threads[p_thread], cull_from, cull_to);
  1822. }
  1823. void RendererSceneCull::_frustum_cull(FrustumCullData &cull_data, FrustumCullResult &cull_result, uint64_t p_from, uint64_t p_to) {
  1824. uint64_t frame_number = RSG::rasterizer->get_frame_number();
  1825. float lightmap_probe_update_speed = RSG::storage->lightmap_get_probe_capture_update_speed() * RSG::rasterizer->get_frame_delta_time();
  1826. uint32_t sdfgi_last_light_index = 0xFFFFFFFF;
  1827. uint32_t sdfgi_last_light_cascade = 0xFFFFFFFF;
  1828. RID instance_pair_buffer[MAX_INSTANCE_PAIRS];
  1829. for (uint64_t i = p_from; i < p_to; i++) {
  1830. bool mesh_visible = false;
  1831. if (cull_data.scenario->instance_aabbs[i].in_frustum(cull_data.cull->frustum)) {
  1832. InstanceData &idata = cull_data.scenario->instance_data[i];
  1833. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  1834. if ((cull_data.visible_layers & idata.layer_mask) == 0) {
  1835. //failure
  1836. } else if (base_type == RS::INSTANCE_LIGHT) {
  1837. cull_result.lights.push_back(idata.instance);
  1838. cull_result.light_instances.push_back(RID::from_uint64(idata.instance_data_rid));
  1839. if (cull_data.shadow_atlas.is_valid() && RSG::storage->light_has_shadow(idata.base_rid)) {
  1840. scene_render->light_instance_mark_visible(RID::from_uint64(idata.instance_data_rid)); //mark it visible for shadow allocation later
  1841. }
  1842. } else if (base_type == RS::INSTANCE_REFLECTION_PROBE) {
  1843. if (cull_data.render_reflection_probe != idata.instance) {
  1844. //avoid entering The Matrix
  1845. if ((idata.flags & InstanceData::FLAG_REFLECTION_PROBE_DIRTY) || scene_render->reflection_probe_instance_needs_redraw(RID::from_uint64(idata.instance_data_rid))) {
  1846. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(idata.instance->base_data);
  1847. cull_data.cull->lock.lock();
  1848. if (!reflection_probe->update_list.in_list()) {
  1849. reflection_probe->render_step = 0;
  1850. reflection_probe_render_list.add_last(&reflection_probe->update_list);
  1851. }
  1852. cull_data.cull->lock.unlock();
  1853. idata.flags &= ~uint32_t(InstanceData::FLAG_REFLECTION_PROBE_DIRTY);
  1854. }
  1855. if (scene_render->reflection_probe_instance_has_reflection(RID::from_uint64(idata.instance_data_rid))) {
  1856. cull_result.reflections.push_back(RID::from_uint64(idata.instance_data_rid));
  1857. }
  1858. }
  1859. } else if (base_type == RS::INSTANCE_DECAL) {
  1860. cull_result.decals.push_back(RID::from_uint64(idata.instance_data_rid));
  1861. } else if (base_type == RS::INSTANCE_GI_PROBE) {
  1862. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(idata.instance->base_data);
  1863. cull_data.cull->lock.lock();
  1864. if (!gi_probe->update_element.in_list()) {
  1865. gi_probe_update_list.add(&gi_probe->update_element);
  1866. }
  1867. cull_data.cull->lock.unlock();
  1868. cull_result.gi_probes.push_back(RID::from_uint64(idata.instance_data_rid));
  1869. } else if (base_type == RS::INSTANCE_LIGHTMAP) {
  1870. cull_result.gi_probes.push_back(RID::from_uint64(idata.instance_data_rid));
  1871. } else if (((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) && !(idata.flags & InstanceData::FLAG_CAST_SHADOWS_ONLY)) {
  1872. bool keep = true;
  1873. if (idata.flags & InstanceData::FLAG_REDRAW_IF_VISIBLE) {
  1874. RenderingServerDefault::redraw_request();
  1875. }
  1876. if (base_type == RS::INSTANCE_MESH) {
  1877. mesh_visible = true;
  1878. } else if (base_type == RS::INSTANCE_PARTICLES) {
  1879. //particles visible? process them
  1880. if (RSG::storage->particles_is_inactive(idata.base_rid)) {
  1881. //but if nothing is going on, don't do it.
  1882. keep = false;
  1883. } else {
  1884. cull_data.cull->lock.lock();
  1885. RSG::storage->particles_request_process(idata.base_rid);
  1886. cull_data.cull->lock.unlock();
  1887. RSG::storage->particles_set_view_axis(idata.base_rid, -cull_data.cam_transform.basis.get_axis(2).normalized());
  1888. //particles visible? request redraw
  1889. RenderingServerDefault::redraw_request();
  1890. }
  1891. }
  1892. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_LIGHT) && (idata.flags & InstanceData::FLAG_GEOM_LIGHTING_DIRTY)) {
  1893. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  1894. uint32_t idx = 0;
  1895. for (Set<Instance *>::Element *E = geom->lights.front(); E; E = E->next()) {
  1896. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1897. instance_pair_buffer[idx++] = light->instance;
  1898. if (idx == MAX_INSTANCE_PAIRS) {
  1899. break;
  1900. }
  1901. }
  1902. scene_render->geometry_instance_pair_light_instances(geom->geometry_instance, instance_pair_buffer, idx);
  1903. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_LIGHTING_DIRTY);
  1904. }
  1905. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && (idata.flags & InstanceData::FLAG_GEOM_REFLECTION_DIRTY)) {
  1906. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  1907. uint32_t idx = 0;
  1908. for (Set<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {
  1909. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
  1910. instance_pair_buffer[idx++] = reflection_probe->instance;
  1911. if (idx == MAX_INSTANCE_PAIRS) {
  1912. break;
  1913. }
  1914. }
  1915. scene_render->geometry_instance_pair_reflection_probe_instances(geom->geometry_instance, instance_pair_buffer, idx);
  1916. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_REFLECTION_DIRTY);
  1917. }
  1918. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && (idata.flags & InstanceData::FLAG_GEOM_DECAL_DIRTY)) {
  1919. //InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  1920. //todo for GLES3
  1921. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_DECAL_DIRTY);
  1922. /*for (Set<Instance *>::Element *E = geom->dec.front(); E; E = E->next()) {
  1923. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
  1924. instance_pair_buffer[idx++] = reflection_probe->instance;
  1925. if (idx==MAX_INSTANCE_PAIRS) {
  1926. break;
  1927. }
  1928. }*/
  1929. //scene_render->geometry_instance_pair_decal_instances(geom->geometry_instance, light_instances, idx);
  1930. }
  1931. if (idata.flags & InstanceData::FLAG_GEOM_GI_PROBE_DIRTY) {
  1932. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  1933. uint32_t idx = 0;
  1934. for (Set<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {
  1935. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);
  1936. instance_pair_buffer[idx++] = gi_probe->probe_instance;
  1937. if (idx == MAX_INSTANCE_PAIRS) {
  1938. break;
  1939. }
  1940. }
  1941. scene_render->geometry_instance_pair_gi_probe_instances(geom->geometry_instance, instance_pair_buffer, idx);
  1942. idata.flags &= ~uint32_t(InstanceData::FLAG_GEOM_GI_PROBE_DIRTY);
  1943. }
  1944. if ((idata.flags & InstanceData::FLAG_LIGHTMAP_CAPTURE) && idata.instance->last_frame_pass != frame_number && !idata.instance->lightmap_target_sh.is_empty() && !idata.instance->lightmap_sh.is_empty()) {
  1945. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  1946. Color *sh = idata.instance->lightmap_sh.ptrw();
  1947. const Color *target_sh = idata.instance->lightmap_target_sh.ptr();
  1948. for (uint32_t j = 0; j < 9; j++) {
  1949. sh[j] = sh[j].lerp(target_sh[j], MIN(1.0, lightmap_probe_update_speed));
  1950. }
  1951. scene_render->geometry_instance_set_lightmap_capture(geom->geometry_instance, sh);
  1952. idata.instance->last_frame_pass = frame_number;
  1953. }
  1954. if (keep) {
  1955. cull_result.geometry_instances.push_back(idata.instance_geometry);
  1956. }
  1957. }
  1958. }
  1959. for (uint32_t j = 0; j < cull_data.cull->shadow_count; j++) {
  1960. for (uint32_t k = 0; k < cull_data.cull->shadows[j].cascade_count; k++) {
  1961. if (cull_data.scenario->instance_aabbs[i].in_frustum(cull_data.cull->shadows[j].cascades[k].frustum)) {
  1962. InstanceData &idata = cull_data.scenario->instance_data[i];
  1963. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  1964. if (((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) && idata.flags & InstanceData::FLAG_CAST_SHADOWS) {
  1965. cull_result.directional_shadows[j].cascade_geometry_instances[k].push_back(idata.instance_geometry);
  1966. mesh_visible = true;
  1967. }
  1968. }
  1969. }
  1970. }
  1971. for (uint32_t j = 0; j < cull_data.cull->sdfgi.region_count; j++) {
  1972. if (cull_data.scenario->instance_aabbs[i].in_aabb(cull_data.cull->sdfgi.region_aabb[j])) {
  1973. InstanceData &idata = cull_data.scenario->instance_data[i];
  1974. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  1975. if (base_type == RS::INSTANCE_LIGHT) {
  1976. InstanceLightData *instance_light = (InstanceLightData *)idata.instance->base_data;
  1977. if (instance_light->bake_mode == RS::LIGHT_BAKE_STATIC && cull_data.cull->sdfgi.region_cascade[j] <= instance_light->max_sdfgi_cascade) {
  1978. if (sdfgi_last_light_index != i || sdfgi_last_light_cascade != cull_data.cull->sdfgi.region_cascade[j]) {
  1979. sdfgi_last_light_index = i;
  1980. sdfgi_last_light_cascade = cull_data.cull->sdfgi.region_cascade[j];
  1981. cull_result.sdfgi_cascade_lights[sdfgi_last_light_cascade].push_back(instance_light->instance);
  1982. }
  1983. }
  1984. } else if ((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1985. if (idata.flags & InstanceData::FLAG_USES_BAKED_LIGHT) {
  1986. cull_result.sdfgi_region_geometry_instances[j].push_back(idata.instance_geometry);
  1987. mesh_visible = true;
  1988. }
  1989. }
  1990. }
  1991. }
  1992. if (mesh_visible && cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_USES_MESH_INSTANCE) {
  1993. cull_result.mesh_instances.push_back(cull_data.scenario->instance_data[i].instance->mesh_instance);
  1994. }
  1995. }
  1996. }
  1997. void RendererSceneCull::_render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_render_buffers, RID p_environment, RID p_force_camera_effects, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_lod_threshold, bool p_using_shadows) {
  1998. // Note, in stereo rendering:
  1999. // - p_cam_transform will be a transform in the middle of our two eyes
  2000. // - p_cam_projection is a wider frustrum that encompasses both eyes
  2001. Instance *render_reflection_probe = instance_owner.getornull(p_reflection_probe); //if null, not rendering to it
  2002. Scenario *scenario = scenario_owner.getornull(p_scenario);
  2003. render_pass++;
  2004. scene_render->set_scene_pass(render_pass);
  2005. if (p_render_buffers.is_valid()) {
  2006. //no rendering code here, this is only to set up what needs to be done, request regions, etc.
  2007. scene_render->sdfgi_update(p_render_buffers, p_environment, p_cam_transform.origin); //update conditions for SDFGI (whether its used or not)
  2008. }
  2009. RENDER_TIMESTAMP("Frustum Culling");
  2010. //rasterizer->set_camera(camera->transform, camera_matrix,ortho);
  2011. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  2012. Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
  2013. /* STEP 2 - CULL */
  2014. cull.frustum = Frustum(planes);
  2015. Vector<RID> directional_lights;
  2016. // directional lights
  2017. {
  2018. cull.shadow_count = 0;
  2019. Vector<Instance *> lights_with_shadow;
  2020. for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {
  2021. if (!E->get()->visible) {
  2022. continue;
  2023. }
  2024. if (directional_lights.size() > RendererSceneRender::MAX_DIRECTIONAL_LIGHTS) {
  2025. break;
  2026. }
  2027. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  2028. //check shadow..
  2029. if (light) {
  2030. if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(E->get()->base) && !(RSG::storage->light_get_type(E->get()->base) == RS::LIGHT_DIRECTIONAL && RSG::storage->light_directional_is_sky_only(E->get()->base))) {
  2031. lights_with_shadow.push_back(E->get());
  2032. }
  2033. //add to list
  2034. directional_lights.push_back(light->instance);
  2035. }
  2036. }
  2037. scene_render->set_directional_shadow_count(lights_with_shadow.size());
  2038. for (int i = 0; i < lights_with_shadow.size(); i++) {
  2039. _light_instance_setup_directional_shadow(i, lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_cam_vaspect);
  2040. }
  2041. }
  2042. { //sdfgi
  2043. cull.sdfgi.region_count = 0;
  2044. if (p_render_buffers.is_valid()) {
  2045. cull.sdfgi.cascade_light_count = 0;
  2046. uint32_t prev_cascade = 0xFFFFFFFF;
  2047. uint32_t pending_region_count = scene_render->sdfgi_get_pending_region_count(p_render_buffers);
  2048. for (uint32_t i = 0; i < pending_region_count; i++) {
  2049. cull.sdfgi.region_aabb[i] = scene_render->sdfgi_get_pending_region_bounds(p_render_buffers, i);
  2050. uint32_t region_cascade = scene_render->sdfgi_get_pending_region_cascade(p_render_buffers, i);
  2051. cull.sdfgi.region_cascade[i] = region_cascade;
  2052. if (region_cascade != prev_cascade) {
  2053. cull.sdfgi.cascade_light_index[cull.sdfgi.cascade_light_count] = region_cascade;
  2054. cull.sdfgi.cascade_light_count++;
  2055. prev_cascade = region_cascade;
  2056. }
  2057. }
  2058. cull.sdfgi.region_count = pending_region_count;
  2059. }
  2060. }
  2061. frustum_cull_result.clear();
  2062. {
  2063. uint64_t cull_from = 0;
  2064. uint64_t cull_to = scenario->instance_data.size();
  2065. FrustumCullData cull_data;
  2066. //prepare for eventual thread usage
  2067. cull_data.cull = &cull;
  2068. cull_data.scenario = scenario;
  2069. cull_data.shadow_atlas = p_shadow_atlas;
  2070. cull_data.cam_transform = p_cam_transform;
  2071. cull_data.visible_layers = p_visible_layers;
  2072. cull_data.render_reflection_probe = render_reflection_probe;
  2073. //#define DEBUG_CULL_TIME
  2074. #ifdef DEBUG_CULL_TIME
  2075. uint64_t time_from = OS::get_singleton()->get_ticks_usec();
  2076. #endif
  2077. if (cull_to > thread_cull_threshold) {
  2078. //multiple threads
  2079. for (uint32_t i = 0; i < frustum_cull_result_threads.size(); i++) {
  2080. frustum_cull_result_threads[i].clear();
  2081. }
  2082. RendererThreadPool::singleton->thread_work_pool.do_work(frustum_cull_result_threads.size(), this, &RendererSceneCull::_frustum_cull_threaded, &cull_data);
  2083. for (uint32_t i = 0; i < frustum_cull_result_threads.size(); i++) {
  2084. frustum_cull_result.append_from(frustum_cull_result_threads[i]);
  2085. }
  2086. } else {
  2087. //single threaded
  2088. _frustum_cull(cull_data, frustum_cull_result, cull_from, cull_to);
  2089. }
  2090. #ifdef DEBUG_CULL_TIME
  2091. static float time_avg = 0;
  2092. static uint32_t time_count = 0;
  2093. time_avg += double(OS::get_singleton()->get_ticks_usec() - time_from) / 1000.0;
  2094. time_count++;
  2095. print_line("time taken: " + rtos(time_avg / time_count));
  2096. #endif
  2097. if (frustum_cull_result.mesh_instances.size()) {
  2098. for (uint64_t i = 0; i < frustum_cull_result.mesh_instances.size(); i++) {
  2099. RSG::storage->mesh_instance_check_for_update(frustum_cull_result.mesh_instances[i]);
  2100. }
  2101. RSG::storage->update_mesh_instances();
  2102. }
  2103. }
  2104. //render shadows
  2105. max_shadows_used = 0;
  2106. if (p_using_shadows) { //setup shadow maps
  2107. // Directional Shadows
  2108. for (uint32_t i = 0; i < cull.shadow_count; i++) {
  2109. for (uint32_t j = 0; j < cull.shadows[i].cascade_count; j++) {
  2110. const Cull::Shadow::Cascade &c = cull.shadows[i].cascades[j];
  2111. // print_line("shadow " + itos(i) + " cascade " + itos(j) + " elements: " + itos(c.cull_result.size()));
  2112. scene_render->light_instance_set_shadow_transform(cull.shadows[i].light_instance, c.projection, c.transform, c.zfar, c.split, j, c.shadow_texel_size, c.bias_scale, c.range_begin, c.uv_scale);
  2113. if (max_shadows_used == MAX_UPDATE_SHADOWS) {
  2114. continue;
  2115. }
  2116. render_shadow_data[max_shadows_used].light = cull.shadows[i].light_instance;
  2117. render_shadow_data[max_shadows_used].pass = j;
  2118. render_shadow_data[max_shadows_used].instances.merge_unordered(frustum_cull_result.directional_shadows[i].cascade_geometry_instances[j]);
  2119. max_shadows_used++;
  2120. }
  2121. }
  2122. // Positional Shadowss
  2123. for (uint32_t i = 0; i < (uint32_t)frustum_cull_result.lights.size(); i++) {
  2124. Instance *ins = frustum_cull_result.lights[i];
  2125. if (!p_shadow_atlas.is_valid() || !RSG::storage->light_has_shadow(ins->base)) {
  2126. continue;
  2127. }
  2128. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  2129. float coverage = 0.f;
  2130. { //compute coverage
  2131. Transform cam_xf = p_cam_transform;
  2132. float zn = p_cam_projection.get_z_near();
  2133. Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane
  2134. // near plane half width and height
  2135. Vector2 vp_half_extents = p_cam_projection.get_viewport_half_extents();
  2136. switch (RSG::storage->light_get_type(ins->base)) {
  2137. case RS::LIGHT_OMNI: {
  2138. float radius = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  2139. //get two points parallel to near plane
  2140. Vector3 points[2] = {
  2141. ins->transform.origin,
  2142. ins->transform.origin + cam_xf.basis.get_axis(0) * radius
  2143. };
  2144. if (!p_cam_orthogonal) {
  2145. //if using perspetive, map them to near plane
  2146. for (int j = 0; j < 2; j++) {
  2147. if (p.distance_to(points[j]) < 0) {
  2148. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  2149. }
  2150. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  2151. }
  2152. }
  2153. float screen_diameter = points[0].distance_to(points[1]) * 2;
  2154. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  2155. } break;
  2156. case RS::LIGHT_SPOT: {
  2157. float radius = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  2158. float angle = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2159. float w = radius * Math::sin(Math::deg2rad(angle));
  2160. float d = radius * Math::cos(Math::deg2rad(angle));
  2161. Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;
  2162. Vector3 points[2] = {
  2163. base,
  2164. base + cam_xf.basis.get_axis(0) * w
  2165. };
  2166. if (!p_cam_orthogonal) {
  2167. //if using perspetive, map them to near plane
  2168. for (int j = 0; j < 2; j++) {
  2169. if (p.distance_to(points[j]) < 0) {
  2170. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  2171. }
  2172. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  2173. }
  2174. }
  2175. float screen_diameter = points[0].distance_to(points[1]) * 2;
  2176. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  2177. } break;
  2178. default: {
  2179. ERR_PRINT("Invalid Light Type");
  2180. }
  2181. }
  2182. }
  2183. if (light->shadow_dirty) {
  2184. light->last_version++;
  2185. light->shadow_dirty = false;
  2186. }
  2187. bool redraw = scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
  2188. if (redraw && max_shadows_used < MAX_UPDATE_SHADOWS) {
  2189. //must redraw!
  2190. RENDER_TIMESTAMP(">Rendering Light " + itos(i));
  2191. light->shadow_dirty = _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_cam_vaspect, p_shadow_atlas, scenario, p_screen_lod_threshold);
  2192. RENDER_TIMESTAMP("<Rendering Light " + itos(i));
  2193. } else {
  2194. light->shadow_dirty = redraw;
  2195. }
  2196. }
  2197. }
  2198. //render SDFGI
  2199. {
  2200. sdfgi_update_data.update_static = false;
  2201. if (cull.sdfgi.region_count > 0) {
  2202. //update regions
  2203. for (uint32_t i = 0; i < cull.sdfgi.region_count; i++) {
  2204. render_sdfgi_data[i].instances.merge_unordered(frustum_cull_result.sdfgi_region_geometry_instances[i]);
  2205. render_sdfgi_data[i].region = i;
  2206. }
  2207. //check if static lights were culled
  2208. bool static_lights_culled = false;
  2209. for (uint32_t i = 0; i < cull.sdfgi.cascade_light_count; i++) {
  2210. if (frustum_cull_result.sdfgi_cascade_lights[i].size()) {
  2211. static_lights_culled = true;
  2212. break;
  2213. }
  2214. }
  2215. if (static_lights_culled) {
  2216. sdfgi_update_data.static_cascade_count = cull.sdfgi.cascade_light_count;
  2217. sdfgi_update_data.static_cascade_indices = cull.sdfgi.cascade_light_index;
  2218. sdfgi_update_data.static_positional_lights = frustum_cull_result.sdfgi_cascade_lights;
  2219. sdfgi_update_data.update_static = true;
  2220. }
  2221. }
  2222. if (p_render_buffers.is_valid()) {
  2223. sdfgi_update_data.directional_lights = &directional_lights;
  2224. sdfgi_update_data.positional_light_instances = scenario->dynamic_lights.ptr();
  2225. sdfgi_update_data.positional_light_count = scenario->dynamic_lights.size();
  2226. }
  2227. }
  2228. //append the directional lights to the lights culled
  2229. for (int i = 0; i < directional_lights.size(); i++) {
  2230. frustum_cull_result.light_instances.push_back(directional_lights[i]);
  2231. }
  2232. RID camera_effects;
  2233. if (p_force_camera_effects.is_valid()) {
  2234. camera_effects = p_force_camera_effects;
  2235. } else {
  2236. camera_effects = scenario->camera_effects;
  2237. }
  2238. /* PROCESS GEOMETRY AND DRAW SCENE */
  2239. RENDER_TIMESTAMP("Render Scene ");
  2240. scene_render->render_scene(p_render_buffers, p_cam_transform, p_cam_projection, p_cam_orthogonal, frustum_cull_result.geometry_instances, frustum_cull_result.light_instances, frustum_cull_result.reflections, frustum_cull_result.gi_probes, frustum_cull_result.decals, frustum_cull_result.lightmaps, p_environment, camera_effects, p_shadow_atlas, p_reflection_probe.is_valid() ? RID() : scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass, p_screen_lod_threshold, render_shadow_data, max_shadows_used, render_sdfgi_data, cull.sdfgi.region_count, &sdfgi_update_data);
  2241. for (uint32_t i = 0; i < max_shadows_used; i++) {
  2242. render_shadow_data[i].instances.clear();
  2243. }
  2244. max_shadows_used = 0;
  2245. for (uint32_t i = 0; i < cull.sdfgi.region_count; i++) {
  2246. render_sdfgi_data[i].instances.clear();
  2247. }
  2248. // virtual void render_scene(RID p_render_buffers, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray<GeometryInstance *> &p_instances, const PagedArray<RID> &p_lights, const PagedArray<RID> &p_reflection_probes, const PagedArray<RID> &p_gi_probes, const PagedArray<RID> &p_decals, const PagedArray<RID> &p_lightmaps, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_lod_threshold,const RenderShadowData *p_render_shadows,int p_render_shadow_count,const RenderSDFGIData *p_render_sdfgi_regions,int p_render_sdfgi_region_count,const RenderSDFGIStaticLightData *p_render_sdfgi_static_lights=nullptr) = 0;
  2249. }
  2250. RID RendererSceneCull::_render_get_environment(RID p_camera, RID p_scenario) {
  2251. Camera *camera = camera_owner.getornull(p_camera);
  2252. if (camera && scene_render->is_environment(camera->env)) {
  2253. return camera->env;
  2254. }
  2255. Scenario *scenario = scenario_owner.getornull(p_scenario);
  2256. if (!scenario) {
  2257. return RID();
  2258. }
  2259. if (scene_render->is_environment(scenario->environment)) {
  2260. return scenario->environment;
  2261. }
  2262. if (scene_render->is_environment(scenario->fallback_environment)) {
  2263. return scenario->fallback_environment;
  2264. }
  2265. return RID();
  2266. }
  2267. void RendererSceneCull::render_empty_scene(RID p_render_buffers, RID p_scenario, RID p_shadow_atlas) {
  2268. #ifndef _3D_DISABLED
  2269. Scenario *scenario = scenario_owner.getornull(p_scenario);
  2270. RID environment;
  2271. if (scenario->environment.is_valid()) {
  2272. environment = scenario->environment;
  2273. } else {
  2274. environment = scenario->fallback_environment;
  2275. }
  2276. RENDER_TIMESTAMP("Render Empty Scene ");
  2277. scene_render->render_scene(p_render_buffers, Transform(), CameraMatrix(), true, PagedArray<RendererSceneRender::GeometryInstance *>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), RID(), RID(), p_shadow_atlas, scenario->reflection_atlas, RID(), 0, 0, nullptr, 0, nullptr, 0, nullptr);
  2278. #endif
  2279. }
  2280. bool RendererSceneCull::_render_reflection_probe_step(Instance *p_instance, int p_step) {
  2281. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  2282. Scenario *scenario = p_instance->scenario;
  2283. ERR_FAIL_COND_V(!scenario, true);
  2284. RenderingServerDefault::redraw_request(); //update, so it updates in editor
  2285. if (p_step == 0) {
  2286. if (!scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
  2287. return true; //all full
  2288. }
  2289. }
  2290. if (p_step >= 0 && p_step < 6) {
  2291. static const Vector3 view_normals[6] = {
  2292. Vector3(+1, 0, 0),
  2293. Vector3(-1, 0, 0),
  2294. Vector3(0, +1, 0),
  2295. Vector3(0, -1, 0),
  2296. Vector3(0, 0, +1),
  2297. Vector3(0, 0, -1)
  2298. };
  2299. static const Vector3 view_up[6] = {
  2300. Vector3(0, -1, 0),
  2301. Vector3(0, -1, 0),
  2302. Vector3(0, 0, +1),
  2303. Vector3(0, 0, -1),
  2304. Vector3(0, -1, 0),
  2305. Vector3(0, -1, 0)
  2306. };
  2307. Vector3 extents = RSG::storage->reflection_probe_get_extents(p_instance->base);
  2308. Vector3 origin_offset = RSG::storage->reflection_probe_get_origin_offset(p_instance->base);
  2309. float max_distance = RSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);
  2310. float size = scene_render->reflection_atlas_get_size(scenario->reflection_atlas);
  2311. float lod_threshold = RSG::storage->reflection_probe_get_lod_threshold(p_instance->base) / size;
  2312. Vector3 edge = view_normals[p_step] * extents;
  2313. 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
  2314. max_distance = MAX(max_distance, distance);
  2315. //render cubemap side
  2316. CameraMatrix cm;
  2317. cm.set_perspective(90, 1, 0.01, max_distance);
  2318. Transform local_view;
  2319. local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
  2320. Transform xform = p_instance->transform * local_view;
  2321. RID shadow_atlas;
  2322. bool use_shadows = RSG::storage->reflection_probe_renders_shadows(p_instance->base);
  2323. if (use_shadows) {
  2324. shadow_atlas = scenario->reflection_probe_shadow_atlas;
  2325. }
  2326. RENDER_TIMESTAMP("Render Reflection Probe, Step " + itos(p_step));
  2327. _render_scene(xform, cm, false, false, RID(), RID(), RID(), RSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step, lod_threshold, use_shadows);
  2328. } else {
  2329. //do roughness postprocess step until it believes it's done
  2330. RENDER_TIMESTAMP("Post-Process Reflection Probe, Step " + itos(p_step));
  2331. return scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
  2332. }
  2333. return false;
  2334. }
  2335. void RendererSceneCull::render_probes() {
  2336. /* REFLECTION PROBES */
  2337. SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
  2338. bool busy = false;
  2339. while (ref_probe) {
  2340. SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
  2341. RID base = ref_probe->self()->owner->base;
  2342. switch (RSG::storage->reflection_probe_get_update_mode(base)) {
  2343. case RS::REFLECTION_PROBE_UPDATE_ONCE: {
  2344. if (busy) { //already rendering something
  2345. break;
  2346. }
  2347. bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
  2348. if (done) {
  2349. reflection_probe_render_list.remove(ref_probe);
  2350. } else {
  2351. ref_probe->self()->render_step++;
  2352. }
  2353. busy = true; //do not render another one of this kind
  2354. } break;
  2355. case RS::REFLECTION_PROBE_UPDATE_ALWAYS: {
  2356. int step = 0;
  2357. bool done = false;
  2358. while (!done) {
  2359. done = _render_reflection_probe_step(ref_probe->self()->owner, step);
  2360. step++;
  2361. }
  2362. reflection_probe_render_list.remove(ref_probe);
  2363. } break;
  2364. }
  2365. ref_probe = next;
  2366. }
  2367. /* GI PROBES */
  2368. SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();
  2369. if (gi_probe) {
  2370. RENDER_TIMESTAMP("Render GI Probes");
  2371. }
  2372. while (gi_probe) {
  2373. SelfList<InstanceGIProbeData> *next = gi_probe->next();
  2374. InstanceGIProbeData *probe = gi_probe->self();
  2375. //Instance *instance_probe = probe->owner;
  2376. //check if probe must be setup, but don't do if on the lighting thread
  2377. bool cache_dirty = false;
  2378. int cache_count = 0;
  2379. {
  2380. int light_cache_size = probe->light_cache.size();
  2381. const InstanceGIProbeData::LightCache *caches = probe->light_cache.ptr();
  2382. const RID *instance_caches = probe->light_instances.ptr();
  2383. int idx = 0; //must count visible lights
  2384. for (Set<Instance *>::Element *E = probe->lights.front(); E; E = E->next()) {
  2385. Instance *instance = E->get();
  2386. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2387. if (!instance->visible) {
  2388. continue;
  2389. }
  2390. if (cache_dirty) {
  2391. //do nothing, since idx must count all visible lights anyway
  2392. } else if (idx >= light_cache_size) {
  2393. cache_dirty = true;
  2394. } else {
  2395. const InstanceGIProbeData::LightCache *cache = &caches[idx];
  2396. if (
  2397. instance_caches[idx] != instance_light->instance ||
  2398. cache->has_shadow != RSG::storage->light_has_shadow(instance->base) ||
  2399. cache->type != RSG::storage->light_get_type(instance->base) ||
  2400. cache->transform != instance->transform ||
  2401. cache->color != RSG::storage->light_get_color(instance->base) ||
  2402. cache->energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  2403. cache->bake_energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  2404. cache->radius != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  2405. cache->attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  2406. cache->spot_angle != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  2407. cache->spot_attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
  2408. cache_dirty = true;
  2409. }
  2410. }
  2411. idx++;
  2412. }
  2413. for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) {
  2414. Instance *instance = E->get();
  2415. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2416. if (!instance->visible) {
  2417. continue;
  2418. }
  2419. if (cache_dirty) {
  2420. //do nothing, since idx must count all visible lights anyway
  2421. } else if (idx >= light_cache_size) {
  2422. cache_dirty = true;
  2423. } else {
  2424. const InstanceGIProbeData::LightCache *cache = &caches[idx];
  2425. if (
  2426. instance_caches[idx] != instance_light->instance ||
  2427. cache->has_shadow != RSG::storage->light_has_shadow(instance->base) ||
  2428. cache->type != RSG::storage->light_get_type(instance->base) ||
  2429. cache->transform != instance->transform ||
  2430. cache->color != RSG::storage->light_get_color(instance->base) ||
  2431. cache->energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  2432. cache->bake_energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  2433. cache->radius != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  2434. cache->attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  2435. cache->spot_angle != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  2436. cache->spot_attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION) ||
  2437. cache->sky_only != RSG::storage->light_directional_is_sky_only(instance->base)) {
  2438. cache_dirty = true;
  2439. }
  2440. }
  2441. idx++;
  2442. }
  2443. if (idx != light_cache_size) {
  2444. cache_dirty = true;
  2445. }
  2446. cache_count = idx;
  2447. }
  2448. bool update_lights = scene_render->gi_probe_needs_update(probe->probe_instance);
  2449. if (cache_dirty) {
  2450. probe->light_cache.resize(cache_count);
  2451. probe->light_instances.resize(cache_count);
  2452. if (cache_count) {
  2453. InstanceGIProbeData::LightCache *caches = probe->light_cache.ptrw();
  2454. RID *instance_caches = probe->light_instances.ptrw();
  2455. int idx = 0; //must count visible lights
  2456. for (Set<Instance *>::Element *E = probe->lights.front(); E; E = E->next()) {
  2457. Instance *instance = E->get();
  2458. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2459. if (!instance->visible) {
  2460. continue;
  2461. }
  2462. InstanceGIProbeData::LightCache *cache = &caches[idx];
  2463. instance_caches[idx] = instance_light->instance;
  2464. cache->has_shadow = RSG::storage->light_has_shadow(instance->base);
  2465. cache->type = RSG::storage->light_get_type(instance->base);
  2466. cache->transform = instance->transform;
  2467. cache->color = RSG::storage->light_get_color(instance->base);
  2468. cache->energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  2469. cache->bake_energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  2470. cache->radius = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  2471. cache->attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  2472. cache->spot_angle = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2473. cache->spot_attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  2474. idx++;
  2475. }
  2476. for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) {
  2477. Instance *instance = E->get();
  2478. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2479. if (!instance->visible) {
  2480. continue;
  2481. }
  2482. InstanceGIProbeData::LightCache *cache = &caches[idx];
  2483. instance_caches[idx] = instance_light->instance;
  2484. cache->has_shadow = RSG::storage->light_has_shadow(instance->base);
  2485. cache->type = RSG::storage->light_get_type(instance->base);
  2486. cache->transform = instance->transform;
  2487. cache->color = RSG::storage->light_get_color(instance->base);
  2488. cache->energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  2489. cache->bake_energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  2490. cache->radius = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  2491. cache->attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  2492. cache->spot_angle = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2493. cache->spot_attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  2494. cache->sky_only = RSG::storage->light_directional_is_sky_only(instance->base);
  2495. idx++;
  2496. }
  2497. }
  2498. update_lights = true;
  2499. }
  2500. frustum_cull_result.geometry_instances.clear();
  2501. RID instance_pair_buffer[MAX_INSTANCE_PAIRS];
  2502. for (Set<Instance *>::Element *E = probe->dynamic_geometries.front(); E; E = E->next()) {
  2503. Instance *ins = E->get();
  2504. if (!ins->visible) {
  2505. continue;
  2506. }
  2507. InstanceGeometryData *geom = (InstanceGeometryData *)ins->base_data;
  2508. if (ins->scenario && ins->array_index >= 0 && (ins->scenario->instance_data[ins->array_index].flags & InstanceData::FLAG_GEOM_GI_PROBE_DIRTY)) {
  2509. uint32_t idx = 0;
  2510. for (Set<Instance *>::Element *F = geom->gi_probes.front(); F; F = F->next()) {
  2511. InstanceGIProbeData *gi_probe2 = static_cast<InstanceGIProbeData *>(F->get()->base_data);
  2512. instance_pair_buffer[idx++] = gi_probe2->probe_instance;
  2513. if (idx == MAX_INSTANCE_PAIRS) {
  2514. break;
  2515. }
  2516. }
  2517. scene_render->geometry_instance_pair_gi_probe_instances(geom->geometry_instance, instance_pair_buffer, idx);
  2518. ins->scenario->instance_data[ins->array_index].flags &= ~uint32_t(InstanceData::FLAG_GEOM_GI_PROBE_DIRTY);
  2519. }
  2520. frustum_cull_result.geometry_instances.push_back(geom->geometry_instance);
  2521. }
  2522. scene_render->gi_probe_update(probe->probe_instance, update_lights, probe->light_instances, frustum_cull_result.geometry_instances);
  2523. gi_probe_update_list.remove(gi_probe);
  2524. gi_probe = next;
  2525. }
  2526. }
  2527. void RendererSceneCull::render_particle_colliders() {
  2528. while (heightfield_particle_colliders_update_list.front()) {
  2529. Instance *hfpc = heightfield_particle_colliders_update_list.front()->get();
  2530. if (hfpc->scenario && hfpc->base_type == RS::INSTANCE_PARTICLES_COLLISION && RSG::storage->particles_collision_is_heightfield(hfpc->base)) {
  2531. //update heightfield
  2532. instance_cull_result.clear();
  2533. frustum_cull_result.geometry_instances.clear();
  2534. struct CullAABB {
  2535. PagedArray<Instance *> *result;
  2536. _FORCE_INLINE_ bool operator()(void *p_data) {
  2537. Instance *p_instance = (Instance *)p_data;
  2538. result->push_back(p_instance);
  2539. return false;
  2540. }
  2541. };
  2542. CullAABB cull_aabb;
  2543. cull_aabb.result = &instance_cull_result;
  2544. hfpc->scenario->indexers[Scenario::INDEXER_GEOMETRY].aabb_query(hfpc->transformed_aabb, cull_aabb);
  2545. hfpc->scenario->indexers[Scenario::INDEXER_VOLUMES].aabb_query(hfpc->transformed_aabb, cull_aabb);
  2546. for (int i = 0; i < (int)instance_cull_result.size(); i++) {
  2547. Instance *instance = instance_cull_result[i];
  2548. if (!instance || !((1 << instance->base_type) & (RS::INSTANCE_GEOMETRY_MASK & (~(1 << RS::INSTANCE_PARTICLES))))) { //all but particles to avoid self collision
  2549. continue;
  2550. }
  2551. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  2552. frustum_cull_result.geometry_instances.push_back(geom->geometry_instance);
  2553. }
  2554. scene_render->render_particle_collider_heightfield(hfpc->base, hfpc->transform, frustum_cull_result.geometry_instances);
  2555. }
  2556. heightfield_particle_colliders_update_list.erase(heightfield_particle_colliders_update_list.front());
  2557. }
  2558. }
  2559. void RendererSceneCull::_update_instance_shader_parameters_from_material(Map<StringName, Instance::InstanceShaderParameter> &isparams, const Map<StringName, Instance::InstanceShaderParameter> &existing_isparams, RID p_material) {
  2560. List<RendererStorage::InstanceShaderParam> plist;
  2561. RSG::storage->material_get_instance_shader_parameters(p_material, &plist);
  2562. for (List<RendererStorage::InstanceShaderParam>::Element *E = plist.front(); E; E = E->next()) {
  2563. StringName name = E->get().info.name;
  2564. if (isparams.has(name)) {
  2565. if (isparams[name].info.type != E->get().info.type) {
  2566. WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E->get().info.name + "', but they do it with different data types. Only the first one (in order) will display correctly.");
  2567. }
  2568. if (isparams[name].index != E->get().index) {
  2569. WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E->get().info.name + "', but they do it with different indices. Only the first one (in order) will display correctly.");
  2570. }
  2571. continue; //first one found always has priority
  2572. }
  2573. Instance::InstanceShaderParameter isp;
  2574. isp.index = E->get().index;
  2575. isp.info = E->get().info;
  2576. isp.default_value = E->get().default_value;
  2577. if (existing_isparams.has(name)) {
  2578. isp.value = existing_isparams[name].value;
  2579. } else {
  2580. isp.value = E->get().default_value;
  2581. }
  2582. isparams[name] = isp;
  2583. }
  2584. }
  2585. void RendererSceneCull::_update_dirty_instance(Instance *p_instance) {
  2586. if (p_instance->update_aabb) {
  2587. _update_instance_aabb(p_instance);
  2588. }
  2589. if (p_instance->update_dependencies) {
  2590. p_instance->dependency_tracker.update_begin();
  2591. if (p_instance->base.is_valid()) {
  2592. RSG::storage->base_update_dependency(p_instance->base, &p_instance->dependency_tracker);
  2593. }
  2594. if (p_instance->material_override.is_valid()) {
  2595. RSG::storage->material_update_dependency(p_instance->material_override, &p_instance->dependency_tracker);
  2596. }
  2597. if (p_instance->base_type == RS::INSTANCE_MESH) {
  2598. //remove materials no longer used and un-own them
  2599. int new_mat_count = RSG::storage->mesh_get_surface_count(p_instance->base);
  2600. p_instance->materials.resize(new_mat_count);
  2601. _instance_update_mesh_instance(p_instance);
  2602. }
  2603. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  2604. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  2605. bool can_cast_shadows = true;
  2606. bool is_animated = false;
  2607. Map<StringName, Instance::InstanceShaderParameter> isparams;
  2608. if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_OFF) {
  2609. can_cast_shadows = false;
  2610. }
  2611. if (p_instance->material_override.is_valid()) {
  2612. if (!RSG::storage->material_casts_shadows(p_instance->material_override)) {
  2613. can_cast_shadows = false;
  2614. }
  2615. is_animated = RSG::storage->material_is_animated(p_instance->material_override);
  2616. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, p_instance->material_override);
  2617. } else {
  2618. if (p_instance->base_type == RS::INSTANCE_MESH) {
  2619. RID mesh = p_instance->base;
  2620. if (mesh.is_valid()) {
  2621. bool cast_shadows = false;
  2622. for (int i = 0; i < p_instance->materials.size(); i++) {
  2623. RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::storage->mesh_surface_get_material(mesh, i);
  2624. if (!mat.is_valid()) {
  2625. cast_shadows = true;
  2626. } else {
  2627. if (RSG::storage->material_casts_shadows(mat)) {
  2628. cast_shadows = true;
  2629. }
  2630. if (RSG::storage->material_is_animated(mat)) {
  2631. is_animated = true;
  2632. }
  2633. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2634. RSG::storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  2635. }
  2636. }
  2637. if (!cast_shadows) {
  2638. can_cast_shadows = false;
  2639. }
  2640. }
  2641. } else if (p_instance->base_type == RS::INSTANCE_MULTIMESH) {
  2642. RID mesh = RSG::storage->multimesh_get_mesh(p_instance->base);
  2643. if (mesh.is_valid()) {
  2644. bool cast_shadows = false;
  2645. int sc = RSG::storage->mesh_get_surface_count(mesh);
  2646. for (int i = 0; i < sc; i++) {
  2647. RID mat = RSG::storage->mesh_surface_get_material(mesh, i);
  2648. if (!mat.is_valid()) {
  2649. cast_shadows = true;
  2650. } else {
  2651. if (RSG::storage->material_casts_shadows(mat)) {
  2652. cast_shadows = true;
  2653. }
  2654. if (RSG::storage->material_is_animated(mat)) {
  2655. is_animated = true;
  2656. }
  2657. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2658. RSG::storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  2659. }
  2660. }
  2661. if (!cast_shadows) {
  2662. can_cast_shadows = false;
  2663. }
  2664. RSG::storage->base_update_dependency(mesh, &p_instance->dependency_tracker);
  2665. }
  2666. } else if (p_instance->base_type == RS::INSTANCE_IMMEDIATE) {
  2667. RID mat = RSG::storage->immediate_get_material(p_instance->base);
  2668. if (!(!mat.is_valid() || RSG::storage->material_casts_shadows(mat))) {
  2669. can_cast_shadows = false;
  2670. }
  2671. if (mat.is_valid() && RSG::storage->material_is_animated(mat)) {
  2672. is_animated = true;
  2673. }
  2674. if (mat.is_valid()) {
  2675. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2676. }
  2677. if (mat.is_valid()) {
  2678. RSG::storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  2679. }
  2680. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  2681. bool cast_shadows = false;
  2682. int dp = RSG::storage->particles_get_draw_passes(p_instance->base);
  2683. for (int i = 0; i < dp; i++) {
  2684. RID mesh = RSG::storage->particles_get_draw_pass_mesh(p_instance->base, i);
  2685. if (!mesh.is_valid()) {
  2686. continue;
  2687. }
  2688. int sc = RSG::storage->mesh_get_surface_count(mesh);
  2689. for (int j = 0; j < sc; j++) {
  2690. RID mat = RSG::storage->mesh_surface_get_material(mesh, j);
  2691. if (!mat.is_valid()) {
  2692. cast_shadows = true;
  2693. } else {
  2694. if (RSG::storage->material_casts_shadows(mat)) {
  2695. cast_shadows = true;
  2696. }
  2697. if (RSG::storage->material_is_animated(mat)) {
  2698. is_animated = true;
  2699. }
  2700. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2701. RSG::storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  2702. }
  2703. }
  2704. }
  2705. if (!cast_shadows) {
  2706. can_cast_shadows = false;
  2707. }
  2708. }
  2709. }
  2710. if (can_cast_shadows != geom->can_cast_shadows) {
  2711. //ability to cast shadows change, let lights now
  2712. for (Set<Instance *>::Element *E = geom->lights.front(); E; E = E->next()) {
  2713. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  2714. light->shadow_dirty = true;
  2715. }
  2716. geom->can_cast_shadows = can_cast_shadows;
  2717. }
  2718. geom->material_is_animated = is_animated;
  2719. p_instance->instance_shader_parameters = isparams;
  2720. if (p_instance->instance_allocated_shader_parameters != (p_instance->instance_shader_parameters.size() > 0)) {
  2721. p_instance->instance_allocated_shader_parameters = (p_instance->instance_shader_parameters.size() > 0);
  2722. if (p_instance->instance_allocated_shader_parameters) {
  2723. p_instance->instance_allocated_shader_parameters_offset = RSG::storage->global_variables_instance_allocate(p_instance->self);
  2724. scene_render->geometry_instance_set_instance_shader_parameters_offset(geom->geometry_instance, p_instance->instance_allocated_shader_parameters_offset);
  2725. for (Map<StringName, Instance::InstanceShaderParameter>::Element *E = p_instance->instance_shader_parameters.front(); E; E = E->next()) {
  2726. if (E->get().value.get_type() != Variant::NIL) {
  2727. RSG::storage->global_variables_instance_update(p_instance->self, E->get().index, E->get().value);
  2728. }
  2729. }
  2730. } else {
  2731. RSG::storage->global_variables_instance_free(p_instance->self);
  2732. p_instance->instance_allocated_shader_parameters_offset = -1;
  2733. scene_render->geometry_instance_set_instance_shader_parameters_offset(geom->geometry_instance, -1);
  2734. }
  2735. }
  2736. }
  2737. if (p_instance->skeleton.is_valid()) {
  2738. RSG::storage->skeleton_update_dependency(p_instance->skeleton, &p_instance->dependency_tracker);
  2739. }
  2740. p_instance->dependency_tracker.update_end();
  2741. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  2742. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  2743. scene_render->geometry_instance_set_surface_materials(geom->geometry_instance, p_instance->materials);
  2744. }
  2745. }
  2746. _instance_update_list.remove(&p_instance->update_item);
  2747. _update_instance(p_instance);
  2748. p_instance->update_aabb = false;
  2749. p_instance->update_dependencies = false;
  2750. }
  2751. void RendererSceneCull::update_dirty_instances() {
  2752. RSG::storage->update_dirty_resources();
  2753. while (_instance_update_list.first()) {
  2754. _update_dirty_instance(_instance_update_list.first()->self());
  2755. }
  2756. }
  2757. void RendererSceneCull::update() {
  2758. //optimize bvhs
  2759. for (uint32_t i = 0; i < scenario_owner.get_rid_count(); i++) {
  2760. Scenario *s = scenario_owner.get_ptr_by_index(i);
  2761. s->indexers[Scenario::INDEXER_GEOMETRY].optimize_incremental(indexer_update_iterations);
  2762. s->indexers[Scenario::INDEXER_VOLUMES].optimize_incremental(indexer_update_iterations);
  2763. }
  2764. scene_render->update();
  2765. update_dirty_instances();
  2766. render_particle_colliders();
  2767. }
  2768. bool RendererSceneCull::free(RID p_rid) {
  2769. if (scene_render->free(p_rid)) {
  2770. return true;
  2771. }
  2772. if (camera_owner.owns(p_rid)) {
  2773. Camera *camera = camera_owner.getornull(p_rid);
  2774. camera_owner.free(p_rid);
  2775. memdelete(camera);
  2776. } else if (scenario_owner.owns(p_rid)) {
  2777. Scenario *scenario = scenario_owner.getornull(p_rid);
  2778. while (scenario->instances.first()) {
  2779. instance_set_scenario(scenario->instances.first()->self()->self, RID());
  2780. }
  2781. scenario->instance_aabbs.reset();
  2782. scenario->instance_data.reset();
  2783. scene_render->free(scenario->reflection_probe_shadow_atlas);
  2784. scene_render->free(scenario->reflection_atlas);
  2785. scenario_owner.free(p_rid);
  2786. memdelete(scenario);
  2787. } else if (instance_owner.owns(p_rid)) {
  2788. // delete the instance
  2789. update_dirty_instances();
  2790. Instance *instance = instance_owner.getornull(p_rid);
  2791. instance_geometry_set_lightmap(p_rid, RID(), Rect2(), 0);
  2792. instance_set_scenario(p_rid, RID());
  2793. instance_set_base(p_rid, RID());
  2794. instance_geometry_set_material_override(p_rid, RID());
  2795. instance_attach_skeleton(p_rid, RID());
  2796. if (instance->instance_allocated_shader_parameters) {
  2797. //free the used shader parameters
  2798. RSG::storage->global_variables_instance_free(instance->self);
  2799. }
  2800. update_dirty_instances(); //in case something changed this
  2801. instance_owner.free(p_rid);
  2802. memdelete(instance);
  2803. } else {
  2804. return false;
  2805. }
  2806. return true;
  2807. }
  2808. TypedArray<Image> RendererSceneCull::bake_render_uv2(RID p_base, const Vector<RID> &p_material_overrides, const Size2i &p_image_size) {
  2809. return scene_render->bake_render_uv2(p_base, p_material_overrides, p_image_size);
  2810. }
  2811. /*******************************/
  2812. /* Passthrough to Scene Render */
  2813. /*******************************/
  2814. /* ENVIRONMENT API */
  2815. RendererSceneCull *RendererSceneCull::singleton = nullptr;
  2816. void RendererSceneCull::set_scene_render(RendererSceneRender *p_scene_render) {
  2817. scene_render = p_scene_render;
  2818. geometry_instance_pair_mask = scene_render->geometry_instance_get_pair_mask();
  2819. }
  2820. RendererSceneCull::RendererSceneCull() {
  2821. render_pass = 1;
  2822. singleton = this;
  2823. instance_cull_result.set_page_pool(&instance_cull_page_pool);
  2824. instance_shadow_cull_result.set_page_pool(&instance_cull_page_pool);
  2825. for (uint32_t i = 0; i < MAX_UPDATE_SHADOWS; i++) {
  2826. render_shadow_data[i].instances.set_page_pool(&geometry_instance_cull_page_pool);
  2827. }
  2828. for (uint32_t i = 0; i < SDFGI_MAX_CASCADES * SDFGI_MAX_REGIONS_PER_CASCADE; i++) {
  2829. render_sdfgi_data[i].instances.set_page_pool(&geometry_instance_cull_page_pool);
  2830. }
  2831. frustum_cull_result.init(&rid_cull_page_pool, &geometry_instance_cull_page_pool, &instance_cull_page_pool);
  2832. frustum_cull_result_threads.resize(RendererThreadPool::singleton->thread_work_pool.get_thread_count());
  2833. for (uint32_t i = 0; i < frustum_cull_result_threads.size(); i++) {
  2834. frustum_cull_result_threads[i].init(&rid_cull_page_pool, &geometry_instance_cull_page_pool, &instance_cull_page_pool);
  2835. }
  2836. indexer_update_iterations = GLOBAL_GET("rendering/limits/spatial_indexer/update_iterations_per_frame");
  2837. thread_cull_threshold = GLOBAL_GET("rendering/limits/spatial_indexer/threaded_cull_minimum_instances");
  2838. thread_cull_threshold = MAX(thread_cull_threshold, (uint32_t)RendererThreadPool::singleton->thread_work_pool.get_thread_count()); //make sure there is at least one thread per CPU
  2839. }
  2840. RendererSceneCull::~RendererSceneCull() {
  2841. instance_cull_result.reset();
  2842. instance_shadow_cull_result.reset();
  2843. for (uint32_t i = 0; i < MAX_UPDATE_SHADOWS; i++) {
  2844. render_shadow_data[i].instances.reset();
  2845. }
  2846. for (uint32_t i = 0; i < SDFGI_MAX_CASCADES * SDFGI_MAX_REGIONS_PER_CASCADE; i++) {
  2847. render_sdfgi_data[i].instances.reset();
  2848. }
  2849. frustum_cull_result.reset();
  2850. for (uint32_t i = 0; i < frustum_cull_result_threads.size(); i++) {
  2851. frustum_cull_result_threads[i].reset();
  2852. }
  2853. frustum_cull_result_threads.clear();
  2854. }