visual_server_scene.cpp 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343
  1. /*************************************************************************/
  2. /* visual_server_scene.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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 "visual_server_scene.h"
  31. #include "os/os.h"
  32. #include "visual_server_global.h"
  33. #include "visual_server_raster.h"
  34. /* CAMERA API */
  35. RID VisualServerScene::camera_create() {
  36. Camera *camera = memnew(Camera);
  37. return camera_owner.make_rid(camera);
  38. }
  39. void VisualServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
  40. Camera *camera = camera_owner.get(p_camera);
  41. ERR_FAIL_COND(!camera);
  42. camera->type = Camera::PERSPECTIVE;
  43. camera->fov = p_fovy_degrees;
  44. camera->znear = p_z_near;
  45. camera->zfar = p_z_far;
  46. }
  47. void VisualServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
  48. Camera *camera = camera_owner.get(p_camera);
  49. ERR_FAIL_COND(!camera);
  50. camera->type = Camera::ORTHOGONAL;
  51. camera->size = p_size;
  52. camera->znear = p_z_near;
  53. camera->zfar = p_z_far;
  54. }
  55. void VisualServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) {
  56. Camera *camera = camera_owner.get(p_camera);
  57. ERR_FAIL_COND(!camera);
  58. camera->transform = p_transform.orthonormalized();
  59. }
  60. void VisualServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
  61. Camera *camera = camera_owner.get(p_camera);
  62. ERR_FAIL_COND(!camera);
  63. camera->visible_layers = p_layers;
  64. }
  65. void VisualServerScene::camera_set_environment(RID p_camera, RID p_env) {
  66. Camera *camera = camera_owner.get(p_camera);
  67. ERR_FAIL_COND(!camera);
  68. camera->env = p_env;
  69. }
  70. void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
  71. Camera *camera = camera_owner.get(p_camera);
  72. ERR_FAIL_COND(!camera);
  73. camera->vaspect = p_enable;
  74. }
  75. /* SCENARIO API */
  76. void *VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int) {
  77. //VisualServerScene *self = (VisualServerScene*)p_self;
  78. Instance *A = p_A;
  79. Instance *B = p_B;
  80. //instance indices are designed so greater always contains lesser
  81. if (A->base_type > B->base_type) {
  82. SWAP(A, B); //lesser always first
  83. }
  84. if (B->base_type == VS::INSTANCE_LIGHT && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  85. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  86. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  87. InstanceLightData::PairInfo pinfo;
  88. pinfo.geometry = A;
  89. pinfo.L = geom->lighting.push_back(B);
  90. List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);
  91. if (geom->can_cast_shadows) {
  92. light->shadow_dirty = true;
  93. }
  94. geom->lighting_dirty = true;
  95. return E; //this element should make freeing faster
  96. } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  97. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  98. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  99. InstanceReflectionProbeData::PairInfo pinfo;
  100. pinfo.geometry = A;
  101. pinfo.L = geom->reflection_probes.push_back(B);
  102. List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo);
  103. geom->reflection_dirty = true;
  104. return E; //this element should make freeing faster
  105. } else if (B->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  106. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
  107. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  108. InstanceLightmapCaptureData::PairInfo pinfo;
  109. pinfo.geometry = A;
  110. pinfo.L = geom->lightmap_captures.push_back(B);
  111. List<InstanceLightmapCaptureData::PairInfo>::Element *E = lightmap_capture->geometries.push_back(pinfo);
  112. ((VisualServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
  113. return E; //this element should make freeing faster
  114. } else if (B->base_type == VS::INSTANCE_GI_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  115. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  116. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  117. InstanceGIProbeData::PairInfo pinfo;
  118. pinfo.geometry = A;
  119. pinfo.L = geom->gi_probes.push_back(B);
  120. List<InstanceGIProbeData::PairInfo>::Element *E = gi_probe->geometries.push_back(pinfo);
  121. geom->gi_probes_dirty = true;
  122. return E; //this element should make freeing faster
  123. } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
  124. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  125. return gi_probe->lights.insert(A);
  126. }
  127. return NULL;
  128. }
  129. void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *udata) {
  130. //VisualServerScene *self = (VisualServerScene*)p_self;
  131. Instance *A = p_A;
  132. Instance *B = p_B;
  133. //instance indices are designed so greater always contains lesser
  134. if (A->base_type > B->base_type) {
  135. SWAP(A, B); //lesser always first
  136. }
  137. if (B->base_type == VS::INSTANCE_LIGHT && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  138. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  139. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  140. List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata);
  141. geom->lighting.erase(E->get().L);
  142. light->geometries.erase(E);
  143. if (geom->can_cast_shadows) {
  144. light->shadow_dirty = true;
  145. }
  146. geom->lighting_dirty = true;
  147. } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  148. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  149. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  150. List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata);
  151. geom->reflection_probes.erase(E->get().L);
  152. reflection_probe->geometries.erase(E);
  153. geom->reflection_dirty = true;
  154. } else if (B->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  155. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(B->base_data);
  156. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  157. List<InstanceLightmapCaptureData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightmapCaptureData::PairInfo>::Element *>(udata);
  158. geom->lightmap_captures.erase(E->get().L);
  159. lightmap_capture->geometries.erase(E);
  160. ((VisualServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
  161. } else if (B->base_type == VS::INSTANCE_GI_PROBE && ((1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK)) {
  162. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  163. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  164. List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata);
  165. geom->gi_probes.erase(E->get().L);
  166. gi_probe->geometries.erase(E);
  167. geom->gi_probes_dirty = true;
  168. } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
  169. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  170. Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata);
  171. gi_probe->lights.erase(E);
  172. }
  173. }
  174. RID VisualServerScene::scenario_create() {
  175. Scenario *scenario = memnew(Scenario);
  176. ERR_FAIL_COND_V(!scenario, RID());
  177. RID scenario_rid = scenario_owner.make_rid(scenario);
  178. scenario->self = scenario_rid;
  179. scenario->octree.set_pair_callback(_instance_pair, this);
  180. scenario->octree.set_unpair_callback(_instance_unpair, this);
  181. scenario->reflection_probe_shadow_atlas = VSG::scene_render->shadow_atlas_create();
  182. VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
  183. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
  184. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
  185. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
  186. VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
  187. scenario->reflection_atlas = VSG::scene_render->reflection_atlas_create();
  188. return scenario_rid;
  189. }
  190. void VisualServerScene::scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode) {
  191. Scenario *scenario = scenario_owner.get(p_scenario);
  192. ERR_FAIL_COND(!scenario);
  193. scenario->debug = p_debug_mode;
  194. }
  195. void VisualServerScene::scenario_set_environment(RID p_scenario, RID p_environment) {
  196. Scenario *scenario = scenario_owner.get(p_scenario);
  197. ERR_FAIL_COND(!scenario);
  198. scenario->environment = p_environment;
  199. }
  200. void VisualServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
  201. Scenario *scenario = scenario_owner.get(p_scenario);
  202. ERR_FAIL_COND(!scenario);
  203. scenario->fallback_environment = p_environment;
  204. }
  205. void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv) {
  206. Scenario *scenario = scenario_owner.get(p_scenario);
  207. ERR_FAIL_COND(!scenario);
  208. VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_size);
  209. VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas, p_subdiv);
  210. }
  211. /* INSTANCING API */
  212. void VisualServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials) {
  213. if (p_update_aabb)
  214. p_instance->update_aabb = true;
  215. if (p_update_materials)
  216. p_instance->update_materials = true;
  217. if (p_instance->update_item.in_list())
  218. return;
  219. _instance_update_list.add(&p_instance->update_item);
  220. }
  221. // from can be mesh, light, area and portal so far.
  222. RID VisualServerScene::instance_create() {
  223. Instance *instance = memnew(Instance);
  224. ERR_FAIL_COND_V(!instance, RID());
  225. RID instance_rid = instance_owner.make_rid(instance);
  226. instance->self = instance_rid;
  227. return instance_rid;
  228. }
  229. void VisualServerScene::instance_set_base(RID p_instance, RID p_base) {
  230. Instance *instance = instance_owner.get(p_instance);
  231. ERR_FAIL_COND(!instance);
  232. Scenario *scenario = instance->scenario;
  233. if (instance->base_type != VS::INSTANCE_NONE) {
  234. //free anything related to that base
  235. VSG::storage->instance_remove_dependency(instance->base, instance);
  236. if (instance->base_type == VS::INSTANCE_GI_PROBE) {
  237. //if gi probe is baking, wait until done baking, else race condition may happen when removing it
  238. //from octree
  239. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  240. //make sure probes are done baking
  241. while (!probe_bake_list.empty()) {
  242. OS::get_singleton()->delay_usec(1);
  243. }
  244. //make sure this one is done baking
  245. while (gi_probe->dynamic.updating_stage == GI_UPDATE_STAGE_LIGHTING) {
  246. //wait until bake is done if it's baking
  247. OS::get_singleton()->delay_usec(1);
  248. }
  249. }
  250. if (scenario && instance->octree_id) {
  251. scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
  252. instance->octree_id = 0;
  253. }
  254. switch (instance->base_type) {
  255. case VS::INSTANCE_LIGHT: {
  256. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  257. if (instance->scenario && light->D) {
  258. instance->scenario->directional_lights.erase(light->D);
  259. light->D = NULL;
  260. }
  261. VSG::scene_render->free(light->instance);
  262. } break;
  263. case VS::INSTANCE_REFLECTION_PROBE: {
  264. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  265. VSG::scene_render->free(reflection_probe->instance);
  266. if (reflection_probe->update_list.in_list()) {
  267. reflection_probe_render_list.remove(&reflection_probe->update_list);
  268. }
  269. } break;
  270. case VS::INSTANCE_LIGHTMAP_CAPTURE: {
  271. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(instance->base_data);
  272. //erase dependencies, since no longer a lightmap
  273. while (lightmap_capture->users.front()) {
  274. instance_set_use_lightmap(lightmap_capture->users.front()->get()->self, RID(), RID());
  275. }
  276. } break;
  277. case VS::INSTANCE_GI_PROBE: {
  278. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  279. if (gi_probe->update_element.in_list()) {
  280. gi_probe_update_list.remove(&gi_probe->update_element);
  281. }
  282. if (gi_probe->dynamic.probe_data.is_valid()) {
  283. VSG::storage->free(gi_probe->dynamic.probe_data);
  284. }
  285. if (instance->lightmap_capture) {
  286. Instance *capture = (Instance *)instance->lightmap_capture;
  287. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(capture->base_data);
  288. lightmap_capture->users.erase(instance);
  289. instance->lightmap_capture = NULL;
  290. instance->lightmap = RID();
  291. }
  292. VSG::scene_render->free(gi_probe->probe_instance);
  293. } break;
  294. }
  295. if (instance->base_data) {
  296. memdelete(instance->base_data);
  297. instance->base_data = NULL;
  298. }
  299. instance->blend_values.clear();
  300. for (int i = 0; i < instance->materials.size(); i++) {
  301. if (instance->materials[i].is_valid()) {
  302. VSG::storage->material_remove_instance_owner(instance->materials[i], instance);
  303. }
  304. }
  305. instance->materials.clear();
  306. }
  307. instance->base_type = VS::INSTANCE_NONE;
  308. instance->base = RID();
  309. if (p_base.is_valid()) {
  310. instance->base_type = VSG::storage->get_base_type(p_base);
  311. ERR_FAIL_COND(instance->base_type == VS::INSTANCE_NONE);
  312. switch (instance->base_type) {
  313. case VS::INSTANCE_LIGHT: {
  314. InstanceLightData *light = memnew(InstanceLightData);
  315. if (scenario && VSG::storage->light_get_type(p_base) == VS::LIGHT_DIRECTIONAL) {
  316. light->D = scenario->directional_lights.push_back(instance);
  317. }
  318. light->instance = VSG::scene_render->light_instance_create(p_base);
  319. instance->base_data = light;
  320. } break;
  321. case VS::INSTANCE_MESH:
  322. case VS::INSTANCE_MULTIMESH:
  323. case VS::INSTANCE_IMMEDIATE:
  324. case VS::INSTANCE_PARTICLES: {
  325. InstanceGeometryData *geom = memnew(InstanceGeometryData);
  326. instance->base_data = geom;
  327. } break;
  328. case VS::INSTANCE_REFLECTION_PROBE: {
  329. InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
  330. reflection_probe->owner = instance;
  331. instance->base_data = reflection_probe;
  332. reflection_probe->instance = VSG::scene_render->reflection_probe_instance_create(p_base);
  333. } break;
  334. case VS::INSTANCE_LIGHTMAP_CAPTURE: {
  335. InstanceLightmapCaptureData *lightmap_capture = memnew(InstanceLightmapCaptureData);
  336. instance->base_data = lightmap_capture;
  337. //lightmap_capture->instance = VSG::scene_render->lightmap_capture_instance_create(p_base);
  338. } break;
  339. case VS::INSTANCE_GI_PROBE: {
  340. InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
  341. instance->base_data = gi_probe;
  342. gi_probe->owner = instance;
  343. if (scenario && !gi_probe->update_element.in_list()) {
  344. gi_probe_update_list.add(&gi_probe->update_element);
  345. }
  346. gi_probe->probe_instance = VSG::scene_render->gi_probe_instance_create();
  347. } break;
  348. }
  349. VSG::storage->instance_add_dependency(p_base, instance);
  350. instance->base = p_base;
  351. if (scenario)
  352. _instance_queue_update(instance, true, true);
  353. }
  354. }
  355. void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
  356. Instance *instance = instance_owner.get(p_instance);
  357. ERR_FAIL_COND(!instance);
  358. if (instance->scenario) {
  359. instance->scenario->instances.remove(&instance->scenario_item);
  360. if (instance->octree_id) {
  361. instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
  362. instance->octree_id = 0;
  363. }
  364. switch (instance->base_type) {
  365. case VS::INSTANCE_LIGHT: {
  366. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  367. if (light->D) {
  368. instance->scenario->directional_lights.erase(light->D);
  369. light->D = NULL;
  370. }
  371. } break;
  372. case VS::INSTANCE_REFLECTION_PROBE: {
  373. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  374. VSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
  375. } break;
  376. case VS::INSTANCE_GI_PROBE: {
  377. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  378. if (gi_probe->update_element.in_list()) {
  379. gi_probe_update_list.remove(&gi_probe->update_element);
  380. }
  381. } break;
  382. }
  383. instance->scenario = NULL;
  384. }
  385. if (p_scenario.is_valid()) {
  386. Scenario *scenario = scenario_owner.get(p_scenario);
  387. ERR_FAIL_COND(!scenario);
  388. instance->scenario = scenario;
  389. scenario->instances.add(&instance->scenario_item);
  390. switch (instance->base_type) {
  391. case VS::INSTANCE_LIGHT: {
  392. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  393. if (VSG::storage->light_get_type(instance->base) == VS::LIGHT_DIRECTIONAL) {
  394. light->D = scenario->directional_lights.push_back(instance);
  395. }
  396. } break;
  397. case VS::INSTANCE_GI_PROBE: {
  398. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  399. if (!gi_probe->update_element.in_list()) {
  400. gi_probe_update_list.add(&gi_probe->update_element);
  401. }
  402. } break;
  403. }
  404. _instance_queue_update(instance, true, true);
  405. }
  406. }
  407. void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
  408. Instance *instance = instance_owner.get(p_instance);
  409. ERR_FAIL_COND(!instance);
  410. instance->layer_mask = p_mask;
  411. }
  412. void VisualServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) {
  413. Instance *instance = instance_owner.get(p_instance);
  414. ERR_FAIL_COND(!instance);
  415. if (instance->transform == p_transform)
  416. return; //must be checked to avoid worst evil
  417. instance->transform = p_transform;
  418. _instance_queue_update(instance, true);
  419. }
  420. void VisualServerScene::instance_attach_object_instance_id(RID p_instance, ObjectID p_ID) {
  421. Instance *instance = instance_owner.get(p_instance);
  422. ERR_FAIL_COND(!instance);
  423. instance->object_ID = p_ID;
  424. }
  425. void VisualServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
  426. Instance *instance = instance_owner.get(p_instance);
  427. ERR_FAIL_COND(!instance);
  428. if (instance->update_item.in_list()) {
  429. _update_dirty_instance(instance);
  430. }
  431. ERR_FAIL_INDEX(p_shape, instance->blend_values.size());
  432. instance->blend_values[p_shape] = p_weight;
  433. }
  434. void VisualServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {
  435. Instance *instance = instance_owner.get(p_instance);
  436. ERR_FAIL_COND(!instance);
  437. if (instance->update_item.in_list()) {
  438. _update_dirty_instance(instance);
  439. }
  440. ERR_FAIL_INDEX(p_surface, instance->materials.size());
  441. if (instance->materials[p_surface].is_valid()) {
  442. VSG::storage->material_remove_instance_owner(instance->materials[p_surface], instance);
  443. }
  444. instance->materials[p_surface] = p_material;
  445. instance->base_material_changed();
  446. if (instance->materials[p_surface].is_valid()) {
  447. VSG::storage->material_add_instance_owner(instance->materials[p_surface], instance);
  448. }
  449. }
  450. void VisualServerScene::instance_set_visible(RID p_instance, bool p_visible) {
  451. Instance *instance = instance_owner.get(p_instance);
  452. ERR_FAIL_COND(!instance);
  453. if (instance->visible == p_visible)
  454. return;
  455. instance->visible = p_visible;
  456. switch (instance->base_type) {
  457. case VS::INSTANCE_LIGHT: {
  458. if (VSG::storage->light_get_type(instance->base) != VS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) {
  459. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_LIGHT, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
  460. }
  461. } break;
  462. case VS::INSTANCE_REFLECTION_PROBE: {
  463. if (instance->octree_id && instance->scenario) {
  464. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_REFLECTION_PROBE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
  465. }
  466. } break;
  467. case VS::INSTANCE_LIGHTMAP_CAPTURE: {
  468. if (instance->octree_id && instance->scenario) {
  469. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_LIGHTMAP_CAPTURE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
  470. }
  471. } break;
  472. case VS::INSTANCE_GI_PROBE: {
  473. if (instance->octree_id && instance->scenario) {
  474. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_GI_PROBE, p_visible ? (VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT)) : 0);
  475. }
  476. } break;
  477. }
  478. }
  479. inline bool is_geometry_instance(VisualServer::InstanceType p_type) {
  480. return p_type == VS::INSTANCE_MESH || p_type == VS::INSTANCE_MULTIMESH || p_type == VS::INSTANCE_PARTICLES || p_type == VS::INSTANCE_IMMEDIATE;
  481. }
  482. void VisualServerScene::instance_set_use_lightmap(RID p_instance, RID p_lightmap_instance, RID p_lightmap) {
  483. Instance *instance = instance_owner.get(p_instance);
  484. ERR_FAIL_COND(!instance);
  485. if (instance->lightmap_capture) {
  486. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
  487. lightmap_capture->users.erase(instance);
  488. instance->lightmap = RID();
  489. instance->lightmap_capture = NULL;
  490. }
  491. if (p_lightmap_instance.is_valid()) {
  492. Instance *lightmap_instance = instance_owner.get(p_lightmap_instance);
  493. ERR_FAIL_COND(!lightmap_instance);
  494. ERR_FAIL_COND(lightmap_instance->base_type != VS::INSTANCE_LIGHTMAP_CAPTURE);
  495. instance->lightmap_capture = lightmap_instance;
  496. InstanceLightmapCaptureData *lightmap_capture = static_cast<InstanceLightmapCaptureData *>(((Instance *)instance->lightmap_capture)->base_data);
  497. lightmap_capture->users.insert(instance);
  498. instance->lightmap = p_lightmap;
  499. }
  500. }
  501. void VisualServerScene::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
  502. Instance *instance = instance_owner.get(p_instance);
  503. ERR_FAIL_COND(!instance);
  504. ERR_FAIL_COND(!is_geometry_instance(instance->base_type));
  505. if (p_aabb != AABB()) {
  506. // Set custom AABB
  507. if (instance->custom_aabb == NULL)
  508. instance->custom_aabb = memnew(AABB);
  509. *instance->custom_aabb = p_aabb;
  510. } else {
  511. // Clear custom AABB
  512. if (instance->custom_aabb != NULL) {
  513. memdelete(instance->custom_aabb);
  514. instance->custom_aabb = NULL;
  515. }
  516. }
  517. if (instance->scenario)
  518. _instance_queue_update(instance, true, false);
  519. }
  520. void VisualServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
  521. Instance *instance = instance_owner.get(p_instance);
  522. ERR_FAIL_COND(!instance);
  523. if (instance->skeleton == p_skeleton)
  524. return;
  525. if (instance->skeleton.is_valid()) {
  526. VSG::storage->instance_remove_skeleton(instance->skeleton, instance);
  527. }
  528. instance->skeleton = p_skeleton;
  529. if (instance->skeleton.is_valid()) {
  530. VSG::storage->instance_add_skeleton(instance->skeleton, instance);
  531. }
  532. _instance_queue_update(instance, true);
  533. }
  534. void VisualServerScene::instance_set_exterior(RID p_instance, bool p_enabled) {
  535. }
  536. void VisualServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
  537. }
  538. Vector<ObjectID> VisualServerScene::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
  539. Vector<ObjectID> instances;
  540. Scenario *scenario = scenario_owner.get(p_scenario);
  541. ERR_FAIL_COND_V(!scenario, instances);
  542. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  543. int culled = 0;
  544. Instance *cull[1024];
  545. culled = scenario->octree.cull_aabb(p_aabb, cull, 1024);
  546. for (int i = 0; i < culled; i++) {
  547. Instance *instance = cull[i];
  548. ERR_CONTINUE(!instance);
  549. if (instance->object_ID == 0)
  550. continue;
  551. instances.push_back(instance->object_ID);
  552. }
  553. return instances;
  554. }
  555. Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
  556. Vector<ObjectID> instances;
  557. Scenario *scenario = scenario_owner.get(p_scenario);
  558. ERR_FAIL_COND_V(!scenario, instances);
  559. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  560. int culled = 0;
  561. Instance *cull[1024];
  562. culled = scenario->octree.cull_segment(p_from, p_from + p_to * 10000, cull, 1024);
  563. for (int i = 0; i < culled; i++) {
  564. Instance *instance = cull[i];
  565. ERR_CONTINUE(!instance);
  566. if (instance->object_ID == 0)
  567. continue;
  568. instances.push_back(instance->object_ID);
  569. }
  570. return instances;
  571. }
  572. Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
  573. Vector<ObjectID> instances;
  574. Scenario *scenario = scenario_owner.get(p_scenario);
  575. ERR_FAIL_COND_V(!scenario, instances);
  576. const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  577. int culled = 0;
  578. Instance *cull[1024];
  579. culled = scenario->octree.cull_convex(p_convex, cull, 1024);
  580. for (int i = 0; i < culled; i++) {
  581. Instance *instance = cull[i];
  582. ERR_CONTINUE(!instance);
  583. if (instance->object_ID == 0)
  584. continue;
  585. instances.push_back(instance->object_ID);
  586. }
  587. return instances;
  588. }
  589. void VisualServerScene::instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled) {
  590. Instance *instance = instance_owner.get(p_instance);
  591. ERR_FAIL_COND(!instance);
  592. switch (p_flags) {
  593. case VS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
  594. instance->baked_light = p_enabled;
  595. } break;
  596. }
  597. }
  598. void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) {
  599. Instance *instance = instance_owner.get(p_instance);
  600. ERR_FAIL_COND(!instance);
  601. instance->cast_shadows = p_shadow_casting_setting;
  602. instance->base_material_changed(); // to actually compute if shadows are visible or not
  603. }
  604. void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) {
  605. Instance *instance = instance_owner.get(p_instance);
  606. ERR_FAIL_COND(!instance);
  607. if (instance->material_override.is_valid()) {
  608. VSG::storage->material_remove_instance_owner(instance->material_override, instance);
  609. }
  610. instance->material_override = p_material;
  611. instance->base_material_changed();
  612. if (instance->material_override.is_valid()) {
  613. VSG::storage->material_add_instance_owner(instance->material_override, instance);
  614. }
  615. }
  616. void VisualServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
  617. }
  618. void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
  619. }
  620. void VisualServerScene::_update_instance(Instance *p_instance) {
  621. p_instance->version++;
  622. if (p_instance->base_type == VS::INSTANCE_LIGHT) {
  623. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  624. VSG::scene_render->light_instance_set_transform(light->instance, p_instance->transform);
  625. light->shadow_dirty = true;
  626. }
  627. if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) {
  628. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  629. VSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
  630. reflection_probe->reflection_dirty = true;
  631. }
  632. if (p_instance->base_type == VS::INSTANCE_PARTICLES) {
  633. VSG::storage->particles_set_emission_transform(p_instance->base, p_instance->transform);
  634. }
  635. if (p_instance->aabb.has_no_surface()) {
  636. return;
  637. }
  638. if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  639. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  640. //make sure lights are updated if it casts shadow
  641. if (geom->can_cast_shadows) {
  642. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  643. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  644. light->shadow_dirty = true;
  645. }
  646. }
  647. if (!p_instance->lightmap_capture && geom->lightmap_captures.size()) {
  648. //affected by lightmap captures, must update capture info!
  649. _update_instance_lightmap_captures(p_instance);
  650. } else {
  651. if (!p_instance->lightmap_capture_data.empty()) {
  652. !p_instance->lightmap_capture_data.resize(0); //not in use, clear capture data
  653. }
  654. }
  655. }
  656. p_instance->mirror = p_instance->transform.basis.determinant() < 0.0;
  657. AABB new_aabb;
  658. new_aabb = p_instance->transform.xform(p_instance->aabb);
  659. p_instance->transformed_aabb = new_aabb;
  660. if (!p_instance->scenario) {
  661. return;
  662. }
  663. if (p_instance->octree_id == 0) {
  664. uint32_t base_type = 1 << p_instance->base_type;
  665. uint32_t pairable_mask = 0;
  666. bool pairable = false;
  667. if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE || p_instance->base_type == VS::INSTANCE_LIGHTMAP_CAPTURE) {
  668. pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK : 0;
  669. pairable = true;
  670. }
  671. if (p_instance->base_type == VS::INSTANCE_GI_PROBE) {
  672. //lights and geometries
  673. pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT) : 0;
  674. pairable = true;
  675. }
  676. // not inside octree
  677. p_instance->octree_id = p_instance->scenario->octree.create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask);
  678. } else {
  679. /*
  680. if (new_aabb==p_instance->data.transformed_aabb)
  681. return;
  682. */
  683. p_instance->scenario->octree.move(p_instance->octree_id, new_aabb);
  684. }
  685. }
  686. void VisualServerScene::_update_instance_aabb(Instance *p_instance) {
  687. AABB new_aabb;
  688. ERR_FAIL_COND(p_instance->base_type != VS::INSTANCE_NONE && !p_instance->base.is_valid());
  689. switch (p_instance->base_type) {
  690. case VisualServer::INSTANCE_NONE: {
  691. // do nothing
  692. } break;
  693. case VisualServer::INSTANCE_MESH: {
  694. if (p_instance->custom_aabb)
  695. new_aabb = *p_instance->custom_aabb;
  696. else
  697. new_aabb = VSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
  698. } break;
  699. case VisualServer::INSTANCE_MULTIMESH: {
  700. if (p_instance->custom_aabb)
  701. new_aabb = *p_instance->custom_aabb;
  702. else
  703. new_aabb = VSG::storage->multimesh_get_aabb(p_instance->base);
  704. } break;
  705. case VisualServer::INSTANCE_IMMEDIATE: {
  706. if (p_instance->custom_aabb)
  707. new_aabb = *p_instance->custom_aabb;
  708. else
  709. new_aabb = VSG::storage->immediate_get_aabb(p_instance->base);
  710. } break;
  711. case VisualServer::INSTANCE_PARTICLES: {
  712. if (p_instance->custom_aabb)
  713. new_aabb = *p_instance->custom_aabb;
  714. else
  715. new_aabb = VSG::storage->particles_get_aabb(p_instance->base);
  716. } break;
  717. case VisualServer::INSTANCE_LIGHT: {
  718. new_aabb = VSG::storage->light_get_aabb(p_instance->base);
  719. } break;
  720. case VisualServer::INSTANCE_REFLECTION_PROBE: {
  721. new_aabb = VSG::storage->reflection_probe_get_aabb(p_instance->base);
  722. } break;
  723. case VisualServer::INSTANCE_GI_PROBE: {
  724. new_aabb = VSG::storage->gi_probe_get_bounds(p_instance->base);
  725. } break;
  726. case VisualServer::INSTANCE_LIGHTMAP_CAPTURE: {
  727. new_aabb = VSG::storage->lightmap_capture_get_bounds(p_instance->base);
  728. } break;
  729. default: {}
  730. }
  731. // <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
  732. if (p_instance->extra_margin)
  733. new_aabb.grow_by(p_instance->extra_margin);
  734. p_instance->aabb = new_aabb;
  735. }
  736. _FORCE_INLINE_ static void _light_capture_sample_octree(const RasterizerStorage::LightmapCaptureOctree *p_octree, int p_cell_subdiv, const Vector3 &p_pos, const Vector3 &p_dir, float p_level, Vector3 &r_color, float &r_alpha) {
  737. static const Vector3 aniso_normal[6] = {
  738. Vector3(-1, 0, 0),
  739. Vector3(1, 0, 0),
  740. Vector3(0, -1, 0),
  741. Vector3(0, 1, 0),
  742. Vector3(0, 0, -1),
  743. Vector3(0, 0, 1)
  744. };
  745. int size = 1 << (p_cell_subdiv - 1);
  746. int clamp_v = size - 1;
  747. //first of all, clamp
  748. Vector3 pos;
  749. pos.x = CLAMP(p_pos.x, 0, clamp_v);
  750. pos.y = CLAMP(p_pos.y, 0, clamp_v);
  751. pos.z = CLAMP(p_pos.z, 0, clamp_v);
  752. float level = (p_cell_subdiv - 1) - p_level;
  753. int target_level;
  754. float level_filter;
  755. if (level <= 0.0) {
  756. level_filter = 0;
  757. target_level = 0;
  758. } else {
  759. target_level = Math::ceil(level);
  760. level_filter = target_level - level;
  761. }
  762. Vector3 color[2][8];
  763. float alpha[2][8];
  764. zeromem(alpha, sizeof(float) * 2 * 8);
  765. //find cell at given level first
  766. for (int c = 0; c < 2; c++) {
  767. int current_level = MAX(0, target_level - c);
  768. int level_cell_size = (1 << (p_cell_subdiv - 1)) >> current_level;
  769. for (int n = 0; n < 8; n++) {
  770. int x = int(pos.x);
  771. int y = int(pos.y);
  772. int z = int(pos.z);
  773. if (n & 1)
  774. x += level_cell_size;
  775. if (n & 2)
  776. y += level_cell_size;
  777. if (n & 4)
  778. z += level_cell_size;
  779. int ofs_x = 0;
  780. int ofs_y = 0;
  781. int ofs_z = 0;
  782. x = CLAMP(x, 0, clamp_v);
  783. y = CLAMP(y, 0, clamp_v);
  784. z = CLAMP(z, 0, clamp_v);
  785. int half = size / 2;
  786. uint32_t cell = 0;
  787. for (int i = 0; i < current_level; i++) {
  788. const RasterizerStorage::LightmapCaptureOctree *bc = &p_octree[cell];
  789. int child = 0;
  790. if (x >= ofs_x + half) {
  791. child |= 1;
  792. ofs_x += half;
  793. }
  794. if (y >= ofs_y + half) {
  795. child |= 2;
  796. ofs_y += half;
  797. }
  798. if (z >= ofs_z + half) {
  799. child |= 4;
  800. ofs_z += half;
  801. }
  802. cell = bc->children[child];
  803. if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY)
  804. break;
  805. half >>= 1;
  806. }
  807. if (cell == RasterizerStorage::LightmapCaptureOctree::CHILD_EMPTY) {
  808. alpha[c][n] = 0;
  809. } else {
  810. alpha[c][n] = p_octree[cell].alpha;
  811. for (int i = 0; i < 6; i++) {
  812. //anisotropic read light
  813. float amount = p_dir.dot(aniso_normal[i]);
  814. if (amount < 0)
  815. amount = 0;
  816. color[c][n].x += p_octree[cell].light[i][0] / 1024.0 * amount;
  817. color[c][n].y += p_octree[cell].light[i][1] / 1024.0 * amount;
  818. color[c][n].z += p_octree[cell].light[i][2] / 1024.0 * amount;
  819. }
  820. }
  821. //print_line("\tlev " + itos(c) + " - " + itos(n) + " alpha: " + rtos(cells[test_cell].alpha) + " col: " + color[c][n]);
  822. }
  823. }
  824. float target_level_size = size >> target_level;
  825. Vector3 pos_fract[2];
  826. pos_fract[0].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  827. pos_fract[0].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  828. pos_fract[0].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  829. target_level_size = size >> MAX(0, target_level - 1);
  830. pos_fract[1].x = Math::fmod(pos.x, target_level_size) / target_level_size;
  831. pos_fract[1].y = Math::fmod(pos.y, target_level_size) / target_level_size;
  832. pos_fract[1].z = Math::fmod(pos.z, target_level_size) / target_level_size;
  833. float alpha_interp[2];
  834. Vector3 color_interp[2];
  835. for (int i = 0; i < 2; i++) {
  836. Vector3 color_x00 = color[i][0].linear_interpolate(color[i][1], pos_fract[i].x);
  837. Vector3 color_xy0 = color[i][2].linear_interpolate(color[i][3], pos_fract[i].x);
  838. Vector3 blend_z0 = color_x00.linear_interpolate(color_xy0, pos_fract[i].y);
  839. Vector3 color_x0z = color[i][4].linear_interpolate(color[i][5], pos_fract[i].x);
  840. Vector3 color_xyz = color[i][6].linear_interpolate(color[i][7], pos_fract[i].x);
  841. Vector3 blend_z1 = color_x0z.linear_interpolate(color_xyz, pos_fract[i].y);
  842. color_interp[i] = blend_z0.linear_interpolate(blend_z1, pos_fract[i].z);
  843. float alpha_x00 = Math::lerp(alpha[i][0], alpha[i][1], pos_fract[i].x);
  844. float alpha_xy0 = Math::lerp(alpha[i][2], alpha[i][3], pos_fract[i].x);
  845. float alpha_z0 = Math::lerp(alpha_x00, alpha_xy0, pos_fract[i].y);
  846. float alpha_x0z = Math::lerp(alpha[i][4], alpha[i][5], pos_fract[i].x);
  847. float alpha_xyz = Math::lerp(alpha[i][6], alpha[i][7], pos_fract[i].x);
  848. float alpha_z1 = Math::lerp(alpha_x0z, alpha_xyz, pos_fract[i].y);
  849. alpha_interp[i] = Math::lerp(alpha_z0, alpha_z1, pos_fract[i].z);
  850. }
  851. r_color = color_interp[0].linear_interpolate(color_interp[1], level_filter);
  852. r_alpha = Math::lerp(alpha_interp[0], alpha_interp[1], level_filter);
  853. // print_line("pos: " + p_posf + " level " + rtos(p_level) + " down to " + itos(target_level) + "." + rtos(level_filter) + " color " + r_color + " alpha " + rtos(r_alpha));
  854. }
  855. _FORCE_INLINE_ static Color _light_capture_voxel_cone_trace(const RasterizerStorage::LightmapCaptureOctree *p_octree, const Vector3 &p_pos, const Vector3 &p_dir, float p_aperture, int p_cell_subdiv) {
  856. float bias = 0.0; //no need for bias here
  857. float max_distance = (Vector3(1, 1, 1) * (1 << (p_cell_subdiv - 1))).length();
  858. float dist = bias;
  859. float alpha = 0.0;
  860. Vector3 color;
  861. Vector3 scolor;
  862. float salpha;
  863. while (dist < max_distance && alpha < 0.95) {
  864. float diameter = MAX(1.0, 2.0 * p_aperture * dist);
  865. _light_capture_sample_octree(p_octree, p_cell_subdiv, p_pos + dist * p_dir, p_dir, log2(diameter), scolor, salpha);
  866. float a = (1.0 - alpha);
  867. color += scolor * a;
  868. alpha += a * salpha;
  869. dist += diameter * 0.5;
  870. }
  871. return Color(color.x, color.y, color.z, alpha);
  872. }
  873. void VisualServerScene::_update_instance_lightmap_captures(Instance *p_instance) {
  874. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  875. static const Vector3 cone_traces[12] = {
  876. Vector3(0, 0, 1),
  877. Vector3(0.866025, 0, 0.5),
  878. Vector3(0.267617, 0.823639, 0.5),
  879. Vector3(-0.700629, 0.509037, 0.5),
  880. Vector3(-0.700629, -0.509037, 0.5),
  881. Vector3(0.267617, -0.823639, 0.5),
  882. Vector3(0, 0, -1),
  883. Vector3(0.866025, 0, -0.5),
  884. Vector3(0.267617, 0.823639, -0.5),
  885. Vector3(-0.700629, 0.509037, -0.5),
  886. Vector3(-0.700629, -0.509037, -0.5),
  887. Vector3(0.267617, -0.823639, -0.5)
  888. };
  889. float cone_aperture = 0.577; // tan(angle) 60 degrees
  890. if (p_instance->lightmap_capture_data.empty()) {
  891. p_instance->lightmap_capture_data.resize(12);
  892. }
  893. //print_line("update captures for pos: " + p_instance->transform.origin);
  894. zeromem(p_instance->lightmap_capture_data.ptrw(), 12 * sizeof(Color));
  895. //this could use some sort of blending..
  896. for (List<Instance *>::Element *E = geom->lightmap_captures.front(); E; E = E->next()) {
  897. const PoolVector<RasterizerStorage::LightmapCaptureOctree> *octree = VSG::storage->lightmap_capture_get_octree_ptr(E->get()->base);
  898. //print_line("octree size: " + itos(octree->size()));
  899. if (octree->size() == 0)
  900. continue;
  901. Transform to_cell_xform = VSG::storage->lightmap_capture_get_octree_cell_transform(E->get()->base);
  902. int cell_subdiv = VSG::storage->lightmap_capture_get_octree_cell_subdiv(E->get()->base);
  903. to_cell_xform = to_cell_xform * E->get()->transform.affine_inverse();
  904. PoolVector<RasterizerStorage::LightmapCaptureOctree>::Read octree_r = octree->read();
  905. Vector3 pos = to_cell_xform.xform(p_instance->transform.origin);
  906. for (int i = 0; i < 12; i++) {
  907. Vector3 dir = to_cell_xform.basis.xform(cone_traces[i]).normalized();
  908. Color capture = _light_capture_voxel_cone_trace(octree_r.ptr(), pos, dir, cone_aperture, cell_subdiv);
  909. p_instance->lightmap_capture_data[i] += capture;
  910. }
  911. }
  912. }
  913. void VisualServerScene::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_shadow_atlas, Scenario *p_scenario) {
  914. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  915. switch (VSG::storage->light_get_type(p_instance->base)) {
  916. case VS::LIGHT_DIRECTIONAL: {
  917. float max_distance = p_cam_projection.get_z_far();
  918. float shadow_max = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
  919. if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
  920. max_distance = MIN(shadow_max, max_distance);
  921. }
  922. max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
  923. float min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
  924. VS::LightDirectionalShadowDepthRangeMode depth_range_mode = VSG::storage->light_directional_get_shadow_depth_range_mode(p_instance->base);
  925. if (depth_range_mode == VS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_OPTIMIZED) {
  926. //optimize min/max
  927. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  928. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  929. Plane base(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2));
  930. //check distance max and min
  931. bool found_items = false;
  932. float z_max = -1e20;
  933. float z_min = 1e20;
  934. for (int i = 0; i < cull_count; i++) {
  935. Instance *instance = instance_shadow_cull_result[i];
  936. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  937. continue;
  938. }
  939. float max, min;
  940. instance->transformed_aabb.project_range_in_plane(base, min, max);
  941. if (max > z_max) {
  942. z_max = max;
  943. }
  944. if (min < z_min) {
  945. z_min = min;
  946. }
  947. found_items = true;
  948. }
  949. if (found_items) {
  950. min_distance = MAX(min_distance, z_min);
  951. max_distance = MIN(max_distance, z_max);
  952. }
  953. }
  954. float range = max_distance - min_distance;
  955. int splits = 0;
  956. switch (VSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
  957. case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits = 1; break;
  958. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits = 2; break;
  959. case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits = 4; break;
  960. }
  961. float distances[5];
  962. distances[0] = min_distance;
  963. for (int i = 0; i < splits; i++) {
  964. distances[i + 1] = min_distance + VSG::storage->light_get_param(p_instance->base, VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
  965. };
  966. distances[splits] = max_distance;
  967. float texture_size = VSG::scene_render->get_directional_light_shadow_size(light->instance);
  968. bool overlap = VSG::storage->light_directional_get_blend_splits(p_instance->base);
  969. float first_radius = 0.0;
  970. for (int i = 0; i < splits; i++) {
  971. // setup a camera matrix for that range!
  972. CameraMatrix camera_matrix;
  973. float aspect = p_cam_projection.get_aspect();
  974. if (p_cam_orthogonal) {
  975. float w, h;
  976. p_cam_projection.get_viewport_size(w, h);
  977. camera_matrix.set_orthogonal(w, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  978. } else {
  979. float fov = p_cam_projection.get_fov();
  980. camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  981. }
  982. //obtain the frustum endpoints
  983. Vector3 endpoints[8]; // frustum plane endpoints
  984. bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
  985. ERR_CONTINUE(!res);
  986. // obtain the light frustm ranges (given endpoints)
  987. Transform transform = p_instance->transform.orthonormalized(); //discard scale and stabilize light
  988. Vector3 x_vec = transform.basis.get_axis(Vector3::AXIS_X).normalized();
  989. Vector3 y_vec = transform.basis.get_axis(Vector3::AXIS_Y).normalized();
  990. Vector3 z_vec = transform.basis.get_axis(Vector3::AXIS_Z).normalized();
  991. //z_vec points agsint the camera, like in default opengl
  992. float x_min = 0.f, x_max = 0.f;
  993. float y_min = 0.f, y_max = 0.f;
  994. float z_min = 0.f, z_max = 0.f;
  995. float x_min_cam = 0.f, x_max_cam = 0.f;
  996. float y_min_cam = 0.f, y_max_cam = 0.f;
  997. float z_min_cam = 0.f, z_max_cam = 0.f;
  998. float bias_scale = 1.0;
  999. //used for culling
  1000. for (int j = 0; j < 8; j++) {
  1001. float d_x = x_vec.dot(endpoints[j]);
  1002. float d_y = y_vec.dot(endpoints[j]);
  1003. float d_z = z_vec.dot(endpoints[j]);
  1004. if (j == 0 || d_x < x_min)
  1005. x_min = d_x;
  1006. if (j == 0 || d_x > x_max)
  1007. x_max = d_x;
  1008. if (j == 0 || d_y < y_min)
  1009. y_min = d_y;
  1010. if (j == 0 || d_y > y_max)
  1011. y_max = d_y;
  1012. if (j == 0 || d_z < z_min)
  1013. z_min = d_z;
  1014. if (j == 0 || d_z > z_max)
  1015. z_max = d_z;
  1016. }
  1017. {
  1018. //camera viewport stuff
  1019. Vector3 center;
  1020. for (int j = 0; j < 8; j++) {
  1021. center += endpoints[j];
  1022. }
  1023. center /= 8.0;
  1024. //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;
  1025. float radius = 0;
  1026. for (int j = 0; j < 8; j++) {
  1027. float d = center.distance_to(endpoints[j]);
  1028. if (d > radius)
  1029. radius = d;
  1030. }
  1031. radius *= texture_size / (texture_size - 2.0); //add a texel by each side
  1032. if (i == 0) {
  1033. first_radius = radius;
  1034. } else {
  1035. bias_scale = radius / first_radius;
  1036. }
  1037. x_max_cam = x_vec.dot(center) + radius;
  1038. x_min_cam = x_vec.dot(center) - radius;
  1039. y_max_cam = y_vec.dot(center) + radius;
  1040. y_min_cam = y_vec.dot(center) - radius;
  1041. z_max_cam = z_vec.dot(center) + radius;
  1042. z_min_cam = z_vec.dot(center) - radius;
  1043. if (depth_range_mode == VS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE) {
  1044. //this trick here is what stabilizes the shadow (make potential jaggies to not move)
  1045. //at the cost of some wasted resolution. Still the quality increase is very well worth it
  1046. float unit = radius * 2.0 / texture_size;
  1047. x_max_cam = Math::stepify(x_max_cam, unit);
  1048. x_min_cam = Math::stepify(x_min_cam, unit);
  1049. y_max_cam = Math::stepify(y_max_cam, unit);
  1050. y_min_cam = Math::stepify(y_min_cam, unit);
  1051. }
  1052. }
  1053. //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree
  1054. Vector<Plane> light_frustum_planes;
  1055. light_frustum_planes.resize(6);
  1056. //right/left
  1057. light_frustum_planes[0] = Plane(x_vec, x_max);
  1058. light_frustum_planes[1] = Plane(-x_vec, -x_min);
  1059. //top/bottom
  1060. light_frustum_planes[2] = Plane(y_vec, y_max);
  1061. light_frustum_planes[3] = Plane(-y_vec, -y_min);
  1062. //near/far
  1063. light_frustum_planes[4] = Plane(z_vec, z_max + 1e6);
  1064. light_frustum_planes[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
  1065. int cull_count = p_scenario->octree.cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  1066. // a pre pass will need to be needed to determine the actual z-near to be used
  1067. Plane near_plane(p_instance->transform.origin, -p_instance->transform.basis.get_axis(2));
  1068. for (int j = 0; j < cull_count; j++) {
  1069. float min, max;
  1070. Instance *instance = instance_shadow_cull_result[j];
  1071. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1072. cull_count--;
  1073. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1074. j--;
  1075. continue;
  1076. }
  1077. instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max);
  1078. instance->depth = near_plane.distance_to(instance->transform.origin);
  1079. instance->depth_layer = 0;
  1080. if (max > z_max)
  1081. z_max = max;
  1082. }
  1083. {
  1084. CameraMatrix ortho_camera;
  1085. real_t half_x = (x_max_cam - x_min_cam) * 0.5;
  1086. real_t half_y = (y_max_cam - y_min_cam) * 0.5;
  1087. ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
  1088. Transform ortho_transform;
  1089. ortho_transform.basis = transform.basis;
  1090. ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
  1091. VSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, 0, distances[i + 1], i, bias_scale);
  1092. }
  1093. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1094. }
  1095. } break;
  1096. case VS::LIGHT_OMNI: {
  1097. VS::LightOmniShadowMode shadow_mode = VSG::storage->light_omni_get_shadow_mode(p_instance->base);
  1098. switch (shadow_mode) {
  1099. case VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID: {
  1100. for (int i = 0; i < 2; i++) {
  1101. //using this one ensures that raster deferred will have it
  1102. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  1103. float z = i == 0 ? -1 : 1;
  1104. Vector<Plane> planes;
  1105. planes.resize(5);
  1106. planes[0] = p_instance->transform.xform(Plane(Vector3(0, 0, z), radius));
  1107. planes[1] = p_instance->transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
  1108. planes[2] = p_instance->transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
  1109. planes[3] = p_instance->transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
  1110. planes[4] = p_instance->transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
  1111. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  1112. Plane near_plane(p_instance->transform.origin, p_instance->transform.basis.get_axis(2) * z);
  1113. for (int j = 0; j < cull_count; j++) {
  1114. Instance *instance = instance_shadow_cull_result[j];
  1115. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1116. cull_count--;
  1117. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1118. j--;
  1119. } else {
  1120. instance->depth = near_plane.distance_to(instance->transform.origin);
  1121. instance->depth_layer = 0;
  1122. }
  1123. }
  1124. VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), p_instance->transform, radius, 0, i);
  1125. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1126. }
  1127. } break;
  1128. case VS::LIGHT_OMNI_SHADOW_CUBE: {
  1129. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  1130. CameraMatrix cm;
  1131. cm.set_perspective(90, 1, 0.01, radius);
  1132. for (int i = 0; i < 6; i++) {
  1133. //using this one ensures that raster deferred will have it
  1134. static const Vector3 view_normals[6] = {
  1135. Vector3(-1, 0, 0),
  1136. Vector3(+1, 0, 0),
  1137. Vector3(0, -1, 0),
  1138. Vector3(0, +1, 0),
  1139. Vector3(0, 0, -1),
  1140. Vector3(0, 0, +1)
  1141. };
  1142. static const Vector3 view_up[6] = {
  1143. Vector3(0, -1, 0),
  1144. Vector3(0, -1, 0),
  1145. Vector3(0, 0, -1),
  1146. Vector3(0, 0, +1),
  1147. Vector3(0, -1, 0),
  1148. Vector3(0, -1, 0)
  1149. };
  1150. Transform xform = p_instance->transform * Transform().looking_at(view_normals[i], view_up[i]);
  1151. Vector<Plane> planes = cm.get_projection_planes(xform);
  1152. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  1153. Plane near_plane(xform.origin, -xform.basis.get_axis(2));
  1154. for (int j = 0; j < cull_count; j++) {
  1155. Instance *instance = instance_shadow_cull_result[j];
  1156. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1157. cull_count--;
  1158. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1159. j--;
  1160. } else {
  1161. instance->depth = near_plane.distance_to(instance->transform.origin);
  1162. instance->depth_layer = 0;
  1163. }
  1164. }
  1165. VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i);
  1166. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1167. }
  1168. //restore the regular DP matrix
  1169. VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), p_instance->transform, radius, 0, 0);
  1170. } break;
  1171. }
  1172. } break;
  1173. case VS::LIGHT_SPOT: {
  1174. float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
  1175. float angle = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  1176. CameraMatrix cm;
  1177. cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);
  1178. Vector<Plane> planes = cm.get_projection_planes(p_instance->transform);
  1179. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
  1180. Plane near_plane(p_instance->transform.origin, -p_instance->transform.basis.get_axis(2));
  1181. for (int j = 0; j < cull_count; j++) {
  1182. Instance *instance = instance_shadow_cull_result[j];
  1183. if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1184. cull_count--;
  1185. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1186. j--;
  1187. } else {
  1188. instance->depth = near_plane.distance_to(instance->transform.origin);
  1189. instance->depth_layer = 0;
  1190. }
  1191. }
  1192. VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, p_instance->transform, radius, 0, 0);
  1193. VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1194. } break;
  1195. }
  1196. }
  1197. void VisualServerScene::render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  1198. // render to mono camera
  1199. Camera *camera = camera_owner.getornull(p_camera);
  1200. ERR_FAIL_COND(!camera);
  1201. /* STEP 1 - SETUP CAMERA */
  1202. CameraMatrix camera_matrix;
  1203. bool ortho = false;
  1204. switch (camera->type) {
  1205. case Camera::ORTHOGONAL: {
  1206. camera_matrix.set_orthogonal(
  1207. camera->size,
  1208. p_viewport_size.width / (float)p_viewport_size.height,
  1209. camera->znear,
  1210. camera->zfar,
  1211. camera->vaspect);
  1212. ortho = true;
  1213. } break;
  1214. case Camera::PERSPECTIVE: {
  1215. camera_matrix.set_perspective(
  1216. camera->fov,
  1217. p_viewport_size.width / (float)p_viewport_size.height,
  1218. camera->znear,
  1219. camera->zfar,
  1220. camera->vaspect);
  1221. ortho = false;
  1222. } break;
  1223. }
  1224. _render_scene(camera->transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), -1);
  1225. }
  1226. void VisualServerScene::render_camera(Ref<ARVRInterface> &p_interface, ARVRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  1227. // render for AR/VR interface
  1228. Camera *camera = camera_owner.getornull(p_camera);
  1229. ERR_FAIL_COND(!camera);
  1230. /* SETUP CAMERA, we are ignoring type and FOV here */
  1231. bool ortho = false;
  1232. float aspect = p_viewport_size.width / (float)p_viewport_size.height;
  1233. CameraMatrix camera_matrix = p_interface->get_projection_for_eye(p_eye, aspect, camera->znear, camera->zfar);
  1234. // We also ignore our camera position, it will have been positioned with a slightly old tracking position.
  1235. // Instead we take our origin point and have our ar/vr interface add fresh tracking data! Whoohoo!
  1236. Transform world_origin = ARVRServer::get_singleton()->get_world_origin();
  1237. Transform cam_transform = p_interface->get_transform_for_eye(p_eye, world_origin);
  1238. _render_scene(cam_transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), -1);
  1239. };
  1240. void VisualServerScene::_render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
  1241. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1242. render_pass++;
  1243. uint32_t camera_layer_mask = p_visible_layers;
  1244. VSG::scene_render->set_scene_pass(render_pass);
  1245. //rasterizer->set_camera(camera->transform, camera_matrix,ortho);
  1246. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  1247. Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
  1248. float z_far = p_cam_projection.get_z_far();
  1249. /* STEP 2 - CULL */
  1250. int cull_count = scenario->octree.cull_convex(planes, instance_cull_result, MAX_INSTANCE_CULL);
  1251. light_cull_count = 0;
  1252. reflection_probe_cull_count = 0;
  1253. //light_samplers_culled=0;
  1254. /* print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0));
  1255. print_line("OTO: "+itos(p_scenario->octree.get_octant_count()));
  1256. //print_line("OTE: "+itos(p_scenario->octree.get_elem_count()));
  1257. print_line("OTP: "+itos(p_scenario->octree.get_pair_count()));
  1258. */
  1259. /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
  1260. //removed, will replace with culling
  1261. /* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */
  1262. for (int i = 0; i < cull_count; i++) {
  1263. Instance *ins = instance_cull_result[i];
  1264. bool keep = false;
  1265. if ((camera_layer_mask & ins->layer_mask) == 0) {
  1266. //failure
  1267. } else if (ins->base_type == VS::INSTANCE_LIGHT && ins->visible) {
  1268. if (ins->visible && light_cull_count < MAX_LIGHTS_CULLED) {
  1269. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  1270. if (!light->geometries.empty()) {
  1271. //do not add this light if no geometry is affected by it..
  1272. light_cull_result[light_cull_count] = ins;
  1273. light_instance_cull_result[light_cull_count] = light->instance;
  1274. if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(ins->base)) {
  1275. VSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later
  1276. }
  1277. light_cull_count++;
  1278. }
  1279. }
  1280. } else if (ins->base_type == VS::INSTANCE_REFLECTION_PROBE && ins->visible) {
  1281. if (ins->visible && reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) {
  1282. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data);
  1283. if (p_reflection_probe != reflection_probe->instance) {
  1284. //avoid entering The Matrix
  1285. if (!reflection_probe->geometries.empty()) {
  1286. //do not add this light if no geometry is affected by it..
  1287. if (reflection_probe->reflection_dirty || VSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) {
  1288. if (!reflection_probe->update_list.in_list()) {
  1289. reflection_probe->render_step = 0;
  1290. reflection_probe_render_list.add_last(&reflection_probe->update_list);
  1291. }
  1292. reflection_probe->reflection_dirty = false;
  1293. }
  1294. if (VSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) {
  1295. reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance;
  1296. reflection_probe_cull_count++;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. } else if (ins->base_type == VS::INSTANCE_GI_PROBE && ins->visible) {
  1302. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data);
  1303. if (!gi_probe->update_element.in_list()) {
  1304. gi_probe_update_list.add(&gi_probe->update_element);
  1305. }
  1306. } else if (((1 << ins->base_type) & VS::INSTANCE_GEOMETRY_MASK) && ins->visible && ins->cast_shadows != VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  1307. keep = true;
  1308. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data);
  1309. if (ins->base_type == VS::INSTANCE_PARTICLES) {
  1310. //particles visible? process them
  1311. VSG::storage->particles_request_process(ins->base);
  1312. //particles visible? request redraw
  1313. VisualServerRaster::redraw_request();
  1314. }
  1315. if (geom->lighting_dirty) {
  1316. int l = 0;
  1317. //only called when lights AABB enter/exit this geometry
  1318. ins->light_instances.resize(geom->lighting.size());
  1319. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  1320. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1321. ins->light_instances[l++] = light->instance;
  1322. }
  1323. geom->lighting_dirty = false;
  1324. }
  1325. if (geom->reflection_dirty) {
  1326. int l = 0;
  1327. //only called when reflection probe AABB enter/exit this geometry
  1328. ins->reflection_probe_instances.resize(geom->reflection_probes.size());
  1329. for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {
  1330. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
  1331. ins->reflection_probe_instances[l++] = reflection_probe->instance;
  1332. }
  1333. geom->reflection_dirty = false;
  1334. }
  1335. if (geom->gi_probes_dirty) {
  1336. int l = 0;
  1337. //only called when reflection probe AABB enter/exit this geometry
  1338. ins->gi_probe_instances.resize(geom->gi_probes.size());
  1339. for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {
  1340. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);
  1341. ins->gi_probe_instances[l++] = gi_probe->probe_instance;
  1342. }
  1343. geom->gi_probes_dirty = false;
  1344. }
  1345. ins->depth = near_plane.distance_to(ins->transform.origin);
  1346. ins->depth_layer = CLAMP(int(ins->depth * 16 / z_far), 0, 15);
  1347. }
  1348. if (!keep) {
  1349. // remove, no reason to keep
  1350. cull_count--;
  1351. SWAP(instance_cull_result[i], instance_cull_result[cull_count]);
  1352. i--;
  1353. ins->last_render_pass = 0; // make invalid
  1354. } else {
  1355. ins->last_render_pass = render_pass;
  1356. }
  1357. }
  1358. /* STEP 5 - PROCESS LIGHTS */
  1359. RID *directional_light_ptr = &light_instance_cull_result[light_cull_count];
  1360. int directional_light_count = 0;
  1361. // directional lights
  1362. {
  1363. Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size());
  1364. int directional_shadow_count = 0;
  1365. for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {
  1366. if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) {
  1367. break;
  1368. }
  1369. if (!E->get()->visible)
  1370. continue;
  1371. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1372. //check shadow..
  1373. if (light) {
  1374. if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(E->get()->base)) {
  1375. lights_with_shadow[directional_shadow_count++] = E->get();
  1376. }
  1377. //add to list
  1378. directional_light_ptr[directional_light_count++] = light->instance;
  1379. }
  1380. }
  1381. VSG::scene_render->set_directional_shadow_count(directional_shadow_count);
  1382. for (int i = 0; i < directional_shadow_count; i++) {
  1383. _light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
  1384. }
  1385. }
  1386. { //setup shadow maps
  1387. //SortArray<Instance*,_InstanceLightsort> sorter;
  1388. //sorter.sort(light_cull_result,light_cull_count);
  1389. for (int i = 0; i < light_cull_count; i++) {
  1390. Instance *ins = light_cull_result[i];
  1391. if (!p_shadow_atlas.is_valid() || !VSG::storage->light_has_shadow(ins->base))
  1392. continue;
  1393. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  1394. float coverage = 0.f;
  1395. { //compute coverage
  1396. Transform cam_xf = p_cam_transform;
  1397. float zn = p_cam_projection.get_z_near();
  1398. Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane
  1399. float vp_w, vp_h; //near plane size in screen coordinates
  1400. p_cam_projection.get_viewport_size(vp_w, vp_h);
  1401. switch (VSG::storage->light_get_type(ins->base)) {
  1402. case VS::LIGHT_OMNI: {
  1403. float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
  1404. //get two points parallel to near plane
  1405. Vector3 points[2] = {
  1406. ins->transform.origin,
  1407. ins->transform.origin + cam_xf.basis.get_axis(0) * radius
  1408. };
  1409. if (!p_cam_orthogonal) {
  1410. //if using perspetive, map them to near plane
  1411. for (int j = 0; j < 2; j++) {
  1412. if (p.distance_to(points[j]) < 0) {
  1413. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  1414. }
  1415. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  1416. }
  1417. }
  1418. float screen_diameter = points[0].distance_to(points[1]) * 2;
  1419. coverage = screen_diameter / (vp_w + vp_h);
  1420. } break;
  1421. case VS::LIGHT_SPOT: {
  1422. float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
  1423. float angle = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  1424. float w = radius * Math::sin(Math::deg2rad(angle));
  1425. float d = radius * Math::cos(Math::deg2rad(angle));
  1426. Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;
  1427. Vector3 points[2] = {
  1428. base,
  1429. base + cam_xf.basis.get_axis(0) * w
  1430. };
  1431. if (!p_cam_orthogonal) {
  1432. //if using perspetive, map them to near plane
  1433. for (int j = 0; j < 2; j++) {
  1434. if (p.distance_to(points[j]) < 0) {
  1435. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  1436. }
  1437. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  1438. }
  1439. }
  1440. float screen_diameter = points[0].distance_to(points[1]) * 2;
  1441. coverage = screen_diameter / (vp_w + vp_h);
  1442. } break;
  1443. default: {
  1444. ERR_PRINT("Invalid Light Type");
  1445. }
  1446. }
  1447. }
  1448. if (light->shadow_dirty) {
  1449. light->last_version++;
  1450. light->shadow_dirty = false;
  1451. }
  1452. bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
  1453. if (redraw) {
  1454. //must redraw!
  1455. _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
  1456. }
  1457. }
  1458. }
  1459. /* ENVIRONMENT */
  1460. RID environment;
  1461. if (p_force_environment.is_valid()) //camera has more environment priority
  1462. environment = p_force_environment;
  1463. else if (scenario->environment.is_valid())
  1464. environment = scenario->environment;
  1465. else
  1466. environment = scenario->fallback_environment;
  1467. /* STEP 6 - PROCESS GEOMETRY AND DRAW SCENE*/
  1468. VSG::scene_render->render_scene(p_cam_transform, p_cam_projection, p_cam_orthogonal, (RasterizerScene::InstanceBase **)instance_cull_result, cull_count, light_instance_cull_result, light_cull_count + directional_light_count, reflection_probe_instance_cull_result, reflection_probe_cull_count, environment, p_shadow_atlas, scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass);
  1469. }
  1470. void VisualServerScene::render_empty_scene(RID p_scenario, RID p_shadow_atlas) {
  1471. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1472. RID environment;
  1473. if (scenario->environment.is_valid())
  1474. environment = scenario->environment;
  1475. else
  1476. environment = scenario->fallback_environment;
  1477. VSG::scene_render->render_scene(Transform(), CameraMatrix(), true, NULL, 0, NULL, 0, NULL, 0, environment, p_shadow_atlas, scenario->reflection_atlas, RID(), 0);
  1478. }
  1479. bool VisualServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) {
  1480. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  1481. Scenario *scenario = p_instance->scenario;
  1482. ERR_FAIL_COND_V(!scenario, true);
  1483. if (p_step == 0) {
  1484. if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
  1485. return true; //sorry, all full :(
  1486. }
  1487. }
  1488. if (p_step >= 0 && p_step < 6) {
  1489. static const Vector3 view_normals[6] = {
  1490. Vector3(-1, 0, 0),
  1491. Vector3(+1, 0, 0),
  1492. Vector3(0, -1, 0),
  1493. Vector3(0, +1, 0),
  1494. Vector3(0, 0, -1),
  1495. Vector3(0, 0, +1)
  1496. };
  1497. Vector3 extents = VSG::storage->reflection_probe_get_extents(p_instance->base);
  1498. Vector3 origin_offset = VSG::storage->reflection_probe_get_origin_offset(p_instance->base);
  1499. float max_distance = VSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);
  1500. Vector3 edge = view_normals[p_step] * extents;
  1501. 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
  1502. max_distance = MAX(max_distance, distance);
  1503. //render cubemap side
  1504. CameraMatrix cm;
  1505. cm.set_perspective(90, 1, 0.01, max_distance);
  1506. static const Vector3 view_up[6] = {
  1507. Vector3(0, -1, 0),
  1508. Vector3(0, -1, 0),
  1509. Vector3(0, 0, -1),
  1510. Vector3(0, 0, +1),
  1511. Vector3(0, -1, 0),
  1512. Vector3(0, -1, 0)
  1513. };
  1514. Transform local_view;
  1515. local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
  1516. Transform xform = p_instance->transform * local_view;
  1517. RID shadow_atlas;
  1518. if (VSG::storage->reflection_probe_renders_shadows(p_instance->base)) {
  1519. shadow_atlas = scenario->reflection_probe_shadow_atlas;
  1520. }
  1521. _render_scene(xform, cm, false, RID(), VSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step);
  1522. } else {
  1523. //do roughness postprocess step until it believes it's done
  1524. return VSG::scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
  1525. }
  1526. return false;
  1527. }
  1528. void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell *p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) {
  1529. if ((uint32_t)p_level == p_header->cell_subdiv - 1) {
  1530. Vector3 emission;
  1531. emission.x = (p_cell[p_idx].emission >> 24) / 255.0;
  1532. emission.y = ((p_cell[p_idx].emission >> 16) & 0xFF) / 255.0;
  1533. emission.z = ((p_cell[p_idx].emission >> 8) & 0xFF) / 255.0;
  1534. float l = (p_cell[p_idx].emission & 0xFF) / 255.0;
  1535. l *= 8.0;
  1536. emission *= l;
  1537. p_local_data[p_idx].energy[0] = uint16_t(emission.x * 1024); //go from 0 to 1024 for light
  1538. p_local_data[p_idx].energy[1] = uint16_t(emission.y * 1024); //go from 0 to 1024 for light
  1539. p_local_data[p_idx].energy[2] = uint16_t(emission.z * 1024); //go from 0 to 1024 for light
  1540. } else {
  1541. p_local_data[p_idx].energy[0] = 0;
  1542. p_local_data[p_idx].energy[1] = 0;
  1543. p_local_data[p_idx].energy[2] = 0;
  1544. int half = (1 << (p_header->cell_subdiv - 1)) >> (p_level + 1);
  1545. for (int i = 0; i < 8; i++) {
  1546. uint32_t child = p_cell[p_idx].children[i];
  1547. if (child == 0xFFFFFFFF)
  1548. continue;
  1549. int x = p_x;
  1550. int y = p_y;
  1551. int z = p_z;
  1552. if (i & 1)
  1553. x += half;
  1554. if (i & 2)
  1555. y += half;
  1556. if (i & 4)
  1557. z += half;
  1558. _gi_probe_fill_local_data(child, p_level + 1, x, y, z, p_cell, p_header, p_local_data, prev_cell);
  1559. }
  1560. }
  1561. //position for each part of the mipmaped texture
  1562. p_local_data[p_idx].pos[0] = p_x >> (p_header->cell_subdiv - p_level - 1);
  1563. p_local_data[p_idx].pos[1] = p_y >> (p_header->cell_subdiv - p_level - 1);
  1564. p_local_data[p_idx].pos[2] = p_z >> (p_header->cell_subdiv - p_level - 1);
  1565. prev_cell[p_level].push_back(p_idx);
  1566. }
  1567. void VisualServerScene::_gi_probe_bake_threads(void *self) {
  1568. VisualServerScene *vss = (VisualServerScene *)self;
  1569. vss->_gi_probe_bake_thread();
  1570. }
  1571. void VisualServerScene::_setup_gi_probe(Instance *p_instance) {
  1572. InstanceGIProbeData *probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);
  1573. if (probe->dynamic.probe_data.is_valid()) {
  1574. VSG::storage->free(probe->dynamic.probe_data);
  1575. probe->dynamic.probe_data = RID();
  1576. }
  1577. probe->dynamic.light_data = VSG::storage->gi_probe_get_dynamic_data(p_instance->base);
  1578. if (probe->dynamic.light_data.size() == 0)
  1579. return;
  1580. //using dynamic data
  1581. PoolVector<int>::Read r = probe->dynamic.light_data.read();
  1582. const GIProbeDataHeader *header = (GIProbeDataHeader *)r.ptr();
  1583. probe->dynamic.local_data.resize(header->cell_count);
  1584. int cell_count = probe->dynamic.local_data.size();
  1585. PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe->dynamic.local_data.write();
  1586. const GIProbeDataCell *cells = (GIProbeDataCell *)&r[16];
  1587. probe->dynamic.level_cell_lists.resize(header->cell_subdiv);
  1588. _gi_probe_fill_local_data(0, 0, 0, 0, 0, cells, header, ldw.ptr(), probe->dynamic.level_cell_lists.ptrw());
  1589. bool compress = VSG::storage->gi_probe_is_compressed(p_instance->base);
  1590. probe->dynamic.compression = compress ? VSG::storage->gi_probe_get_dynamic_data_get_preferred_compression() : RasterizerStorage::GI_PROBE_UNCOMPRESSED;
  1591. probe->dynamic.probe_data = VSG::storage->gi_probe_dynamic_data_create(header->width, header->height, header->depth, probe->dynamic.compression);
  1592. probe->dynamic.bake_dynamic_range = VSG::storage->gi_probe_get_dynamic_range(p_instance->base);
  1593. probe->dynamic.mipmaps_3d.clear();
  1594. probe->dynamic.propagate = VSG::storage->gi_probe_get_propagation(p_instance->base);
  1595. probe->dynamic.grid_size[0] = header->width;
  1596. probe->dynamic.grid_size[1] = header->height;
  1597. probe->dynamic.grid_size[2] = header->depth;
  1598. int size_limit = 1;
  1599. int size_divisor = 1;
  1600. if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  1601. print_line("S3TC");
  1602. size_limit = 4;
  1603. size_divisor = 4;
  1604. }
  1605. for (int i = 0; i < (int)header->cell_subdiv; i++) {
  1606. int x = header->width >> i;
  1607. int y = header->height >> i;
  1608. int z = header->depth >> i;
  1609. //create and clear mipmap
  1610. PoolVector<uint8_t> mipmap;
  1611. int size = x * y * z * 4;
  1612. size /= size_divisor;
  1613. mipmap.resize(size);
  1614. PoolVector<uint8_t>::Write w = mipmap.write();
  1615. zeromem(w.ptr(), size);
  1616. w = PoolVector<uint8_t>::Write();
  1617. probe->dynamic.mipmaps_3d.push_back(mipmap);
  1618. if (x <= size_limit || y <= size_limit || z <= size_limit)
  1619. break;
  1620. }
  1621. probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
  1622. probe->invalid = false;
  1623. probe->dynamic.enabled = true;
  1624. Transform cell_to_xform = VSG::storage->gi_probe_get_to_cell_xform(p_instance->base);
  1625. AABB bounds = VSG::storage->gi_probe_get_bounds(p_instance->base);
  1626. float cell_size = VSG::storage->gi_probe_get_cell_size(p_instance->base);
  1627. probe->dynamic.light_to_cell_xform = cell_to_xform * p_instance->transform.affine_inverse();
  1628. VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance, p_instance->base, probe->dynamic.probe_data);
  1629. VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance, probe->dynamic.light_to_cell_xform);
  1630. VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance, bounds.size / cell_size);
  1631. probe->base_version = VSG::storage->gi_probe_get_version(p_instance->base);
  1632. //if compression is S3TC, fill it up
  1633. if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  1634. //create all blocks
  1635. Vector<Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> > comp_blocks;
  1636. int mipmap_count = probe->dynamic.mipmaps_3d.size();
  1637. comp_blocks.resize(mipmap_count);
  1638. for (int i = 0; i < cell_count; i++) {
  1639. const GIProbeDataCell &c = cells[i];
  1640. const InstanceGIProbeData::LocalData &ld = ldw[i];
  1641. int level = c.level_alpha >> 16;
  1642. int mipmap = header->cell_subdiv - level - 1;
  1643. if (mipmap >= mipmap_count)
  1644. continue; //uninteresting
  1645. int blockx = (ld.pos[0] >> 2);
  1646. int blocky = (ld.pos[1] >> 2);
  1647. int blockz = (ld.pos[2]); //compression is x/y only
  1648. int blockw = (header->width >> mipmap) >> 2;
  1649. int blockh = (header->height >> mipmap) >> 2;
  1650. //print_line("cell "+itos(i)+" level "+itos(level)+"mipmap: "+itos(mipmap)+" pos: "+Vector3(blockx,blocky,blockz)+" size "+Vector2(blockw,blockh));
  1651. uint32_t key = blockz * blockw * blockh + blocky * blockw + blockx;
  1652. Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> &cmap = comp_blocks[mipmap];
  1653. if (!cmap.has(key)) {
  1654. InstanceGIProbeData::CompBlockS3TC k;
  1655. k.offset = key; //use offset as counter first
  1656. k.source_count = 0;
  1657. cmap[key] = k;
  1658. }
  1659. InstanceGIProbeData::CompBlockS3TC &k = cmap[key];
  1660. ERR_CONTINUE(k.source_count == 16);
  1661. k.sources[k.source_count++] = i;
  1662. }
  1663. //fix the blocks, precomputing what is needed
  1664. probe->dynamic.mipmaps_s3tc.resize(mipmap_count);
  1665. for (int i = 0; i < mipmap_count; i++) {
  1666. print_line("S3TC level: " + itos(i) + " blocks: " + itos(comp_blocks[i].size()));
  1667. probe->dynamic.mipmaps_s3tc[i].resize(comp_blocks[i].size());
  1668. PoolVector<InstanceGIProbeData::CompBlockS3TC>::Write w = probe->dynamic.mipmaps_s3tc[i].write();
  1669. int block_idx = 0;
  1670. for (Map<uint32_t, InstanceGIProbeData::CompBlockS3TC>::Element *E = comp_blocks[i].front(); E; E = E->next()) {
  1671. InstanceGIProbeData::CompBlockS3TC k = E->get();
  1672. //PRECOMPUTE ALPHA
  1673. int max_alpha = -100000;
  1674. int min_alpha = k.source_count == 16 ? 100000 : 0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero)
  1675. uint8_t alpha_block[4][4] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };
  1676. for (uint32_t j = 0; j < k.source_count; j++) {
  1677. int alpha = (cells[k.sources[j]].level_alpha >> 8) & 0xFF;
  1678. if (alpha < min_alpha)
  1679. min_alpha = alpha;
  1680. if (alpha > max_alpha)
  1681. max_alpha = alpha;
  1682. //fill up alpha block
  1683. alpha_block[ldw[k.sources[j]].pos[0] % 4][ldw[k.sources[j]].pos[1] % 4] = alpha;
  1684. }
  1685. //use the first mode (8 adjustable levels)
  1686. k.alpha[0] = max_alpha;
  1687. k.alpha[1] = min_alpha;
  1688. uint64_t alpha_bits = 0;
  1689. if (max_alpha != min_alpha) {
  1690. int idx = 0;
  1691. for (int y = 0; y < 4; y++) {
  1692. for (int x = 0; x < 4; x++) {
  1693. //subtract minimum
  1694. uint32_t a = uint32_t(alpha_block[x][y]) - min_alpha;
  1695. //convert range to 3 bits
  1696. a = int((a * 7.0 / (max_alpha - min_alpha)) + 0.5);
  1697. a = CLAMP(a, 0, 7); //just to be sure
  1698. a = 7 - a; //because range is inverted in this mode
  1699. if (a == 0) {
  1700. //do none, remain
  1701. } else if (a == 7) {
  1702. a = 1;
  1703. } else {
  1704. a = a + 1;
  1705. }
  1706. alpha_bits |= uint64_t(a) << (idx * 3);
  1707. idx++;
  1708. }
  1709. }
  1710. }
  1711. k.alpha[2] = (alpha_bits >> 0) & 0xFF;
  1712. k.alpha[3] = (alpha_bits >> 8) & 0xFF;
  1713. k.alpha[4] = (alpha_bits >> 16) & 0xFF;
  1714. k.alpha[5] = (alpha_bits >> 24) & 0xFF;
  1715. k.alpha[6] = (alpha_bits >> 32) & 0xFF;
  1716. k.alpha[7] = (alpha_bits >> 40) & 0xFF;
  1717. w[block_idx++] = k;
  1718. }
  1719. }
  1720. }
  1721. }
  1722. void VisualServerScene::_gi_probe_bake_thread() {
  1723. while (true) {
  1724. probe_bake_sem->wait();
  1725. if (probe_bake_thread_exit) {
  1726. break;
  1727. }
  1728. Instance *to_bake = NULL;
  1729. probe_bake_mutex->lock();
  1730. if (!probe_bake_list.empty()) {
  1731. to_bake = probe_bake_list.front()->get();
  1732. probe_bake_list.pop_front();
  1733. }
  1734. probe_bake_mutex->unlock();
  1735. if (!to_bake)
  1736. continue;
  1737. _bake_gi_probe(to_bake);
  1738. }
  1739. }
  1740. uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv) {
  1741. uint32_t cell = 0;
  1742. int ofs_x = 0;
  1743. int ofs_y = 0;
  1744. int ofs_z = 0;
  1745. int size = 1 << (p_cell_subdiv - 1);
  1746. int half = size / 2;
  1747. if (x < 0 || x >= size)
  1748. return -1;
  1749. if (y < 0 || y >= size)
  1750. return -1;
  1751. if (z < 0 || z >= size)
  1752. return -1;
  1753. for (int i = 0; i < p_cell_subdiv - 1; i++) {
  1754. const GIProbeDataCell *bc = &cells[cell];
  1755. int child = 0;
  1756. if (x >= ofs_x + half) {
  1757. child |= 1;
  1758. ofs_x += half;
  1759. }
  1760. if (y >= ofs_y + half) {
  1761. child |= 2;
  1762. ofs_y += half;
  1763. }
  1764. if (z >= ofs_z + half) {
  1765. child |= 4;
  1766. ofs_z += half;
  1767. }
  1768. cell = bc->children[child];
  1769. if (cell == 0xFFFFFFFF)
  1770. return 0xFFFFFFFF;
  1771. half >>= 1;
  1772. }
  1773. return cell;
  1774. }
  1775. static float _get_normal_advance(const Vector3 &p_normal) {
  1776. Vector3 normal = p_normal;
  1777. Vector3 unorm = normal.abs();
  1778. if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
  1779. // x code
  1780. unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0);
  1781. } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
  1782. // y code
  1783. unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0);
  1784. } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
  1785. // z code
  1786. unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0);
  1787. } else {
  1788. // oh-no we messed up code
  1789. // has to be
  1790. unorm = Vector3(1.0, 0.0, 0.0);
  1791. }
  1792. return 1.0 / normal.dot(unorm);
  1793. }
  1794. void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header, const GIProbeDataCell *cells, InstanceGIProbeData::LocalData *local_data, const uint32_t *leaves, int p_leaf_count, const InstanceGIProbeData::LightCache &light_cache, int p_sign) {
  1795. int light_r = int(light_cache.color.r * light_cache.energy * 1024.0) * p_sign;
  1796. int light_g = int(light_cache.color.g * light_cache.energy * 1024.0) * p_sign;
  1797. int light_b = int(light_cache.color.b * light_cache.energy * 1024.0) * p_sign;
  1798. float limits[3] = { float(header->width), float(header->height), float(header->depth) };
  1799. Plane clip[3];
  1800. int clip_planes = 0;
  1801. switch (light_cache.type) {
  1802. case VS::LIGHT_DIRECTIONAL: {
  1803. float max_len = Vector3(limits[0], limits[1], limits[2]).length() * 1.1;
  1804. Vector3 light_axis = -light_cache.transform.basis.get_axis(2).normalized();
  1805. for (int i = 0; i < 3; i++) {
  1806. if (ABS(light_axis[i]) < CMP_EPSILON)
  1807. continue;
  1808. clip[clip_planes].normal[i] = 1.0;
  1809. if (light_axis[i] < 0) {
  1810. clip[clip_planes].d = limits[i] + 1;
  1811. } else {
  1812. clip[clip_planes].d -= 1.0;
  1813. }
  1814. clip_planes++;
  1815. }
  1816. float distance_adv = _get_normal_advance(light_axis);
  1817. int success_count = 0;
  1818. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  1819. for (int i = 0; i < p_leaf_count; i++) {
  1820. uint32_t idx = leaves[i];
  1821. const GIProbeDataCell *cell = &cells[idx];
  1822. InstanceGIProbeData::LocalData *light = &local_data[idx];
  1823. Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
  1824. to += -light_axis.sign() * 0.47; //make it more likely to receive a ray
  1825. Vector3 norm(
  1826. (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
  1827. (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
  1828. (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
  1829. float att = norm.dot(-light_axis);
  1830. if (att < 0.001) {
  1831. //not lighting towards this
  1832. continue;
  1833. }
  1834. Vector3 from = to - max_len * light_axis;
  1835. for (int j = 0; j < clip_planes; j++) {
  1836. clip[j].intersects_segment(from, to, &from);
  1837. }
  1838. float distance = (to - from).length();
  1839. distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always
  1840. from = to - light_axis * distance;
  1841. uint32_t result = 0xFFFFFFFF;
  1842. while (distance > -distance_adv) { //use this to avoid precision errors
  1843. result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
  1844. if (result != 0xFFFFFFFF) {
  1845. break;
  1846. }
  1847. from += light_axis * distance_adv;
  1848. distance -= distance_adv;
  1849. }
  1850. if (result == idx) {
  1851. //cell hit itself! hooray!
  1852. light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
  1853. light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
  1854. light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
  1855. success_count++;
  1856. }
  1857. }
  1858. // print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
  1859. // print_line("valid cells: " + itos(success_count));
  1860. } break;
  1861. case VS::LIGHT_OMNI:
  1862. case VS::LIGHT_SPOT: {
  1863. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  1864. Vector3 light_pos = light_cache.transform.origin;
  1865. Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized();
  1866. float local_radius = light_cache.radius * light_cache.transform.basis.get_axis(2).length();
  1867. for (int i = 0; i < p_leaf_count; i++) {
  1868. uint32_t idx = leaves[i];
  1869. const GIProbeDataCell *cell = &cells[idx];
  1870. InstanceGIProbeData::LocalData *light = &local_data[idx];
  1871. Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
  1872. to += (light_pos - to).sign() * 0.47; //make it more likely to receive a ray
  1873. Vector3 norm(
  1874. (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
  1875. (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
  1876. (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
  1877. Vector3 light_axis = (to - light_pos).normalized();
  1878. float distance_adv = _get_normal_advance(light_axis);
  1879. float att = norm.dot(-light_axis);
  1880. if (att < 0.001) {
  1881. //not lighting towards this
  1882. continue;
  1883. }
  1884. {
  1885. float d = light_pos.distance_to(to);
  1886. if (d + distance_adv > local_radius)
  1887. continue; // too far away
  1888. float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
  1889. att *= powf(1.0 - dt, light_cache.attenuation);
  1890. }
  1891. if (light_cache.type == VS::LIGHT_SPOT) {
  1892. float angle = Math::rad2deg(acos(light_axis.dot(spot_axis)));
  1893. if (angle > light_cache.spot_angle)
  1894. continue;
  1895. float d = CLAMP(angle / light_cache.spot_angle, 0, 1);
  1896. att *= powf(1.0 - d, light_cache.spot_attenuation);
  1897. }
  1898. clip_planes = 0;
  1899. for (int c = 0; c < 3; c++) {
  1900. if (ABS(light_axis[c]) < CMP_EPSILON)
  1901. continue;
  1902. clip[clip_planes].normal[c] = 1.0;
  1903. if (light_axis[c] < 0) {
  1904. clip[clip_planes].d = limits[c] + 1;
  1905. } else {
  1906. clip[clip_planes].d -= 1.0;
  1907. }
  1908. clip_planes++;
  1909. }
  1910. Vector3 from = light_pos;
  1911. for (int j = 0; j < clip_planes; j++) {
  1912. clip[j].intersects_segment(from, to, &from);
  1913. }
  1914. float distance = (to - from).length();
  1915. distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
  1916. from = to - light_axis * distance;
  1917. uint32_t result = 0xFFFFFFFF;
  1918. while (distance > -distance_adv) { //use this to avoid precision errors
  1919. result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
  1920. if (result != 0xFFFFFFFF) {
  1921. break;
  1922. }
  1923. from += light_axis * distance_adv;
  1924. distance -= distance_adv;
  1925. }
  1926. if (result == idx) {
  1927. //cell hit itself! hooray!
  1928. light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
  1929. light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
  1930. light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
  1931. }
  1932. }
  1933. // print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
  1934. } break;
  1935. }
  1936. }
  1937. void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell *p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate) {
  1938. //average light to upper level
  1939. float divisor = 0;
  1940. float sum[3] = { 0.0, 0.0, 0.0 };
  1941. for (int i = 0; i < 8; i++) {
  1942. uint32_t child = p_cells[p_idx].children[i];
  1943. if (child == 0xFFFFFFFF)
  1944. continue;
  1945. if (p_level + 1 < (int)p_header->cell_subdiv - 1) {
  1946. _bake_gi_downscale_light(child, p_level + 1, p_cells, p_header, p_local_data, p_propagate);
  1947. }
  1948. sum[0] += p_local_data[child].energy[0];
  1949. sum[1] += p_local_data[child].energy[1];
  1950. sum[2] += p_local_data[child].energy[2];
  1951. divisor += 1.0;
  1952. }
  1953. divisor = Math::lerp((float)8.0, divisor, p_propagate);
  1954. sum[0] /= divisor;
  1955. sum[1] /= divisor;
  1956. sum[2] /= divisor;
  1957. //divide by eight for average
  1958. p_local_data[p_idx].energy[0] = Math::fast_ftoi(sum[0]);
  1959. p_local_data[p_idx].energy[1] = Math::fast_ftoi(sum[1]);
  1960. p_local_data[p_idx].energy[2] = Math::fast_ftoi(sum[2]);
  1961. }
  1962. void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) {
  1963. InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
  1964. PoolVector<int>::Read r = probe_data->dynamic.light_data.read();
  1965. const GIProbeDataHeader *header = (const GIProbeDataHeader *)r.ptr();
  1966. const GIProbeDataCell *cells = (const GIProbeDataCell *)&r[16];
  1967. int leaf_count = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].size();
  1968. const uint32_t *leaves = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].ptr();
  1969. PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe_data->dynamic.local_data.write();
  1970. InstanceGIProbeData::LocalData *local_data = ldw.ptr();
  1971. //remove what must be removed
  1972. for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache.front(); E; E = E->next()) {
  1973. RID rid = E->key();
  1974. const InstanceGIProbeData::LightCache &lc = E->get();
  1975. if ((!probe_data->dynamic.light_cache_changes.has(rid) || !(probe_data->dynamic.light_cache_changes[rid] == lc)) && lc.visible) {
  1976. //erase light data
  1977. _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, -1);
  1978. }
  1979. }
  1980. //add what must be added
  1981. for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache_changes.front(); E; E = E->next()) {
  1982. RID rid = E->key();
  1983. const InstanceGIProbeData::LightCache &lc = E->get();
  1984. if ((!probe_data->dynamic.light_cache.has(rid) || !(probe_data->dynamic.light_cache[rid] == lc)) && lc.visible) {
  1985. //add light data
  1986. _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, 1);
  1987. }
  1988. }
  1989. SWAP(probe_data->dynamic.light_cache_changes, probe_data->dynamic.light_cache);
  1990. //downscale to lower res levels
  1991. _bake_gi_downscale_light(0, 0, cells, header, local_data, probe_data->dynamic.propagate);
  1992. //plot result to 3D texture!
  1993. if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_UNCOMPRESSED) {
  1994. for (int i = 0; i < (int)header->cell_subdiv; i++) {
  1995. int stage = header->cell_subdiv - i - 1;
  1996. if (stage >= probe_data->dynamic.mipmaps_3d.size())
  1997. continue; //no mipmap for this one
  1998. //print_line("generating mipmap stage: " + itos(stage));
  1999. int level_cell_count = probe_data->dynamic.level_cell_lists[i].size();
  2000. const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[i].ptr();
  2001. PoolVector<uint8_t>::Write lw = probe_data->dynamic.mipmaps_3d[stage].write();
  2002. uint8_t *mipmapw = lw.ptr();
  2003. uint32_t sizes[3] = { header->width >> stage, header->height >> stage, header->depth >> stage };
  2004. for (int j = 0; j < level_cell_count; j++) {
  2005. uint32_t idx = level_cells[j];
  2006. uint32_t r = (uint32_t(local_data[idx].energy[0]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  2007. uint32_t g = (uint32_t(local_data[idx].energy[1]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  2008. uint32_t b = (uint32_t(local_data[idx].energy[2]) / probe_data->dynamic.bake_dynamic_range) >> 2;
  2009. uint32_t a = (cells[idx].level_alpha >> 8) & 0xFF;
  2010. uint32_t mm_ofs = sizes[0] * sizes[1] * (local_data[idx].pos[2]) + sizes[0] * (local_data[idx].pos[1]) + (local_data[idx].pos[0]);
  2011. mm_ofs *= 4; //for RGBA (4 bytes)
  2012. mipmapw[mm_ofs + 0] = uint8_t(CLAMP(r, 0, 255));
  2013. mipmapw[mm_ofs + 1] = uint8_t(CLAMP(g, 0, 255));
  2014. mipmapw[mm_ofs + 2] = uint8_t(CLAMP(b, 0, 255));
  2015. mipmapw[mm_ofs + 3] = uint8_t(CLAMP(a, 0, 255));
  2016. }
  2017. }
  2018. } else if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
  2019. int mipmap_count = probe_data->dynamic.mipmaps_3d.size();
  2020. for (int mmi = 0; mmi < mipmap_count; mmi++) {
  2021. PoolVector<uint8_t>::Write mmw = probe_data->dynamic.mipmaps_3d[mmi].write();
  2022. int block_count = probe_data->dynamic.mipmaps_s3tc[mmi].size();
  2023. PoolVector<InstanceGIProbeData::CompBlockS3TC>::Read mmr = probe_data->dynamic.mipmaps_s3tc[mmi].read();
  2024. for (int i = 0; i < block_count; i++) {
  2025. const InstanceGIProbeData::CompBlockS3TC &b = mmr[i];
  2026. uint8_t *blockptr = &mmw[b.offset * 16];
  2027. copymem(blockptr, b.alpha, 8); //copy alpha part, which is precomputed
  2028. Vector3 colors[16];
  2029. for (uint32_t j = 0; j < b.source_count; j++) {
  2030. colors[j].x = (local_data[b.sources[j]].energy[0] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  2031. colors[j].y = (local_data[b.sources[j]].energy[1] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  2032. colors[j].z = (local_data[b.sources[j]].energy[2] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
  2033. }
  2034. //super quick and dirty compression
  2035. //find 2 most further apart
  2036. float distance = 0;
  2037. Vector3 from, to;
  2038. if (b.source_count == 16) {
  2039. //all cells are used so, find minmax between them
  2040. int further_apart[2] = { 0, 0 };
  2041. for (uint32_t j = 0; j < b.source_count; j++) {
  2042. for (uint32_t k = j + 1; k < b.source_count; k++) {
  2043. float d = colors[j].distance_squared_to(colors[k]);
  2044. if (d > distance) {
  2045. distance = d;
  2046. further_apart[0] = j;
  2047. further_apart[1] = k;
  2048. }
  2049. }
  2050. }
  2051. from = colors[further_apart[0]];
  2052. to = colors[further_apart[1]];
  2053. } else {
  2054. //if a block is missing, the priority is that this block remains black,
  2055. //otherwise the geometry will appear deformed
  2056. //correct shape wins over correct color in this case
  2057. //average all colors first
  2058. Vector3 average;
  2059. for (uint32_t j = 0; j < b.source_count; j++) {
  2060. average += colors[j];
  2061. }
  2062. average.normalize();
  2063. //find max distance in normal from average
  2064. for (uint32_t j = 0; j < b.source_count; j++) {
  2065. float d = average.dot(colors[j]);
  2066. distance = MAX(d, distance);
  2067. }
  2068. from = Vector3(); //from black
  2069. to = average * distance;
  2070. //find max distance
  2071. }
  2072. int indices[16];
  2073. uint16_t color_0 = 0;
  2074. color_0 = CLAMP(int(from.x * 31), 0, 31) << 11;
  2075. color_0 |= CLAMP(int(from.y * 63), 0, 63) << 5;
  2076. color_0 |= CLAMP(int(from.z * 31), 0, 31);
  2077. uint16_t color_1 = 0;
  2078. color_1 = CLAMP(int(to.x * 31), 0, 31) << 11;
  2079. color_1 |= CLAMP(int(to.y * 63), 0, 63) << 5;
  2080. color_1 |= CLAMP(int(to.z * 31), 0, 31);
  2081. if (color_1 > color_0) {
  2082. SWAP(color_1, color_0);
  2083. SWAP(from, to);
  2084. }
  2085. if (distance > 0) {
  2086. Vector3 dir = (to - from).normalized();
  2087. for (uint32_t j = 0; j < b.source_count; j++) {
  2088. float d = (colors[j] - from).dot(dir) / distance;
  2089. indices[j] = int(d * 3 + 0.5);
  2090. static const int index_swap[4] = { 0, 3, 1, 2 };
  2091. indices[j] = index_swap[CLAMP(indices[j], 0, 3)];
  2092. }
  2093. } else {
  2094. for (uint32_t j = 0; j < b.source_count; j++) {
  2095. indices[j] = 0;
  2096. }
  2097. }
  2098. //by default, 1 is black, otherwise it will be overridden by source
  2099. uint32_t index_block[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
  2100. for (uint32_t j = 0; j < b.source_count; j++) {
  2101. int x = local_data[b.sources[j]].pos[0] % 4;
  2102. int y = local_data[b.sources[j]].pos[1] % 4;
  2103. index_block[y * 4 + x] = indices[j];
  2104. }
  2105. uint32_t encode = 0;
  2106. for (int j = 0; j < 16; j++) {
  2107. encode |= index_block[j] << (j * 2);
  2108. }
  2109. blockptr[8] = color_0 & 0xFF;
  2110. blockptr[9] = (color_0 >> 8) & 0xFF;
  2111. blockptr[10] = color_1 & 0xFF;
  2112. blockptr[11] = (color_1 >> 8) & 0xFF;
  2113. blockptr[12] = encode & 0xFF;
  2114. blockptr[13] = (encode >> 8) & 0xFF;
  2115. blockptr[14] = (encode >> 16) & 0xFF;
  2116. blockptr[15] = (encode >> 24) & 0xFF;
  2117. }
  2118. }
  2119. }
  2120. //send back to main thread to update un little chunks
  2121. if (probe_bake_mutex) {
  2122. probe_bake_mutex->lock();
  2123. }
  2124. probe_data->dynamic.updating_stage = GI_UPDATE_STAGE_UPLOADING;
  2125. if (probe_bake_mutex) {
  2126. probe_bake_mutex->unlock();
  2127. }
  2128. }
  2129. bool VisualServerScene::_check_gi_probe(Instance *p_gi_probe) {
  2130. InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
  2131. probe_data->dynamic.light_cache_changes.clear();
  2132. bool all_equal = true;
  2133. for (List<Instance *>::Element *E = p_gi_probe->scenario->directional_lights.front(); E; E = E->next()) {
  2134. InstanceGIProbeData::LightCache lc;
  2135. lc.type = VSG::storage->light_get_type(E->get()->base);
  2136. lc.color = VSG::storage->light_get_color(E->get()->base);
  2137. lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY) * VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_INDIRECT_ENERGY);
  2138. lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
  2139. lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
  2140. lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  2141. lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
  2142. lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
  2143. lc.visible = E->get()->visible;
  2144. if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self] == lc)) {
  2145. all_equal = false;
  2146. }
  2147. probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
  2148. }
  2149. for (Set<Instance *>::Element *E = probe_data->lights.front(); E; E = E->next()) {
  2150. InstanceGIProbeData::LightCache lc;
  2151. lc.type = VSG::storage->light_get_type(E->get()->base);
  2152. lc.color = VSG::storage->light_get_color(E->get()->base);
  2153. lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY) * VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_INDIRECT_ENERGY);
  2154. lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
  2155. lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
  2156. lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
  2157. lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
  2158. lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
  2159. lc.visible = E->get()->visible;
  2160. if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self] == lc)) {
  2161. all_equal = false;
  2162. }
  2163. probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
  2164. }
  2165. //lighting changed from after to before, must do some updating
  2166. return !all_equal || probe_data->dynamic.light_cache_changes.size() != probe_data->dynamic.light_cache.size();
  2167. }
  2168. void VisualServerScene::render_probes() {
  2169. /* REFLECTION PROBES */
  2170. SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
  2171. bool busy = false;
  2172. while (ref_probe) {
  2173. SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
  2174. RID base = ref_probe->self()->owner->base;
  2175. switch (VSG::storage->reflection_probe_get_update_mode(base)) {
  2176. case VS::REFLECTION_PROBE_UPDATE_ONCE: {
  2177. if (busy) //already rendering something
  2178. break;
  2179. bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
  2180. if (done) {
  2181. reflection_probe_render_list.remove(ref_probe);
  2182. } else {
  2183. ref_probe->self()->render_step++;
  2184. }
  2185. busy = true; //do not render another one of this kind
  2186. } break;
  2187. case VS::REFLECTION_PROBE_UPDATE_ALWAYS: {
  2188. int step = 0;
  2189. bool done = false;
  2190. while (!done) {
  2191. done = _render_reflection_probe_step(ref_probe->self()->owner, step);
  2192. step++;
  2193. }
  2194. reflection_probe_render_list.remove(ref_probe);
  2195. } break;
  2196. }
  2197. ref_probe = next;
  2198. }
  2199. /* GI PROBES */
  2200. SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();
  2201. while (gi_probe) {
  2202. SelfList<InstanceGIProbeData> *next = gi_probe->next();
  2203. InstanceGIProbeData *probe = gi_probe->self();
  2204. Instance *instance_probe = probe->owner;
  2205. //check if probe must be setup, but don't do if on the lighting thread
  2206. bool force_lighting = false;
  2207. if (probe->invalid || (probe->dynamic.updating_stage == GI_UPDATE_STAGE_CHECK && probe->base_version != VSG::storage->gi_probe_get_version(instance_probe->base))) {
  2208. _setup_gi_probe(instance_probe);
  2209. force_lighting = true;
  2210. }
  2211. float propagate = VSG::storage->gi_probe_get_propagation(instance_probe->base);
  2212. if (probe->dynamic.propagate != propagate) {
  2213. probe->dynamic.propagate = propagate;
  2214. force_lighting = true;
  2215. }
  2216. if (probe->invalid == false && probe->dynamic.enabled) {
  2217. switch (probe->dynamic.updating_stage) {
  2218. case GI_UPDATE_STAGE_CHECK: {
  2219. if (_check_gi_probe(instance_probe) || force_lighting) { //send to lighting thread
  2220. #ifndef NO_THREADS
  2221. probe_bake_mutex->lock();
  2222. probe->dynamic.updating_stage = GI_UPDATE_STAGE_LIGHTING;
  2223. probe_bake_list.push_back(instance_probe);
  2224. probe_bake_mutex->unlock();
  2225. probe_bake_sem->post();
  2226. #else
  2227. _bake_gi_probe(instance_probe);
  2228. #endif
  2229. }
  2230. } break;
  2231. case GI_UPDATE_STAGE_LIGHTING: {
  2232. //do none, wait til done!
  2233. } break;
  2234. case GI_UPDATE_STAGE_UPLOADING: {
  2235. // uint64_t us = OS::get_singleton()->get_ticks_usec();
  2236. for (int i = 0; i < (int)probe->dynamic.mipmaps_3d.size(); i++) {
  2237. PoolVector<uint8_t>::Read r = probe->dynamic.mipmaps_3d[i].read();
  2238. VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data, 0, probe->dynamic.grid_size[2] >> i, i, r.ptr());
  2239. }
  2240. probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
  2241. // print_line("UPLOAD TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
  2242. } break;
  2243. }
  2244. }
  2245. //_update_gi_probe(gi_probe->self()->owner);
  2246. gi_probe = next;
  2247. }
  2248. }
  2249. void VisualServerScene::_update_dirty_instance(Instance *p_instance) {
  2250. if (p_instance->update_aabb) {
  2251. _update_instance_aabb(p_instance);
  2252. }
  2253. if (p_instance->update_materials) {
  2254. if (p_instance->base_type == VS::INSTANCE_MESH) {
  2255. //remove materials no longer used and un-own them
  2256. int new_mat_count = VSG::storage->mesh_get_surface_count(p_instance->base);
  2257. for (int i = p_instance->materials.size() - 1; i >= new_mat_count; i--) {
  2258. if (p_instance->materials[i].is_valid()) {
  2259. VSG::storage->material_remove_instance_owner(p_instance->materials[i], p_instance);
  2260. }
  2261. }
  2262. p_instance->materials.resize(new_mat_count);
  2263. int new_blend_shape_count = VSG::storage->mesh_get_blend_shape_count(p_instance->base);
  2264. if (new_blend_shape_count != p_instance->blend_values.size()) {
  2265. p_instance->blend_values.resize(new_blend_shape_count);
  2266. for (int i = 0; i < new_blend_shape_count; i++) {
  2267. p_instance->blend_values[i] = 0;
  2268. }
  2269. }
  2270. }
  2271. if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
  2272. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  2273. bool can_cast_shadows = true;
  2274. if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_OFF) {
  2275. can_cast_shadows = false;
  2276. } else if (p_instance->material_override.is_valid()) {
  2277. can_cast_shadows = VSG::storage->material_casts_shadows(p_instance->material_override);
  2278. } else {
  2279. if (p_instance->base_type == VS::INSTANCE_MESH) {
  2280. RID mesh = p_instance->base;
  2281. if (mesh.is_valid()) {
  2282. bool cast_shadows = false;
  2283. for (int i = 0; i < p_instance->materials.size(); i++) {
  2284. RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : VSG::storage->mesh_surface_get_material(mesh, i);
  2285. if (!mat.is_valid()) {
  2286. cast_shadows = true;
  2287. break;
  2288. }
  2289. if (VSG::storage->material_casts_shadows(mat)) {
  2290. cast_shadows = true;
  2291. break;
  2292. }
  2293. }
  2294. if (!cast_shadows) {
  2295. can_cast_shadows = false;
  2296. }
  2297. }
  2298. } else if (p_instance->base_type == VS::INSTANCE_MULTIMESH) {
  2299. RID mesh = VSG::storage->multimesh_get_mesh(p_instance->base);
  2300. if (mesh.is_valid()) {
  2301. bool cast_shadows = false;
  2302. int sc = VSG::storage->mesh_get_surface_count(mesh);
  2303. for (int i = 0; i < sc; i++) {
  2304. RID mat = VSG::storage->mesh_surface_get_material(mesh, i);
  2305. if (!mat.is_valid()) {
  2306. cast_shadows = true;
  2307. break;
  2308. }
  2309. if (VSG::storage->material_casts_shadows(mat)) {
  2310. cast_shadows = true;
  2311. break;
  2312. }
  2313. }
  2314. if (!cast_shadows) {
  2315. can_cast_shadows = false;
  2316. }
  2317. }
  2318. } else if (p_instance->base_type == VS::INSTANCE_IMMEDIATE) {
  2319. RID mat = VSG::storage->immediate_get_material(p_instance->base);
  2320. if (!mat.is_valid() || VSG::storage->material_casts_shadows(mat)) {
  2321. can_cast_shadows = true;
  2322. } else {
  2323. can_cast_shadows = false;
  2324. }
  2325. } else if (p_instance->base_type == VS::INSTANCE_PARTICLES) {
  2326. bool cast_shadows = false;
  2327. int dp = VSG::storage->particles_get_draw_passes(p_instance->base);
  2328. for (int i = 0; i < dp; i++) {
  2329. RID mesh = VSG::storage->particles_get_draw_pass_mesh(p_instance->base, i);
  2330. if (!mesh.is_valid())
  2331. continue;
  2332. int sc = VSG::storage->mesh_get_surface_count(mesh);
  2333. for (int j = 0; j < sc; j++) {
  2334. RID mat = VSG::storage->mesh_surface_get_material(mesh, j);
  2335. if (!mat.is_valid()) {
  2336. cast_shadows = true;
  2337. break;
  2338. }
  2339. if (VSG::storage->material_casts_shadows(mat)) {
  2340. cast_shadows = true;
  2341. break;
  2342. }
  2343. }
  2344. }
  2345. if (!cast_shadows) {
  2346. can_cast_shadows = false;
  2347. }
  2348. }
  2349. }
  2350. if (can_cast_shadows != geom->can_cast_shadows) {
  2351. //ability to cast shadows change, let lights now
  2352. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  2353. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  2354. light->shadow_dirty = true;
  2355. }
  2356. geom->can_cast_shadows = can_cast_shadows;
  2357. }
  2358. }
  2359. }
  2360. _instance_update_list.remove(&p_instance->update_item);
  2361. _update_instance(p_instance);
  2362. p_instance->update_aabb = false;
  2363. p_instance->update_materials = false;
  2364. }
  2365. void VisualServerScene::update_dirty_instances() {
  2366. VSG::storage->update_dirty_resources();
  2367. while (_instance_update_list.first()) {
  2368. _update_dirty_instance(_instance_update_list.first()->self());
  2369. }
  2370. }
  2371. bool VisualServerScene::free(RID p_rid) {
  2372. if (camera_owner.owns(p_rid)) {
  2373. Camera *camera = camera_owner.get(p_rid);
  2374. camera_owner.free(p_rid);
  2375. memdelete(camera);
  2376. } else if (scenario_owner.owns(p_rid)) {
  2377. Scenario *scenario = scenario_owner.get(p_rid);
  2378. while (scenario->instances.first()) {
  2379. instance_set_scenario(scenario->instances.first()->self()->self, RID());
  2380. }
  2381. VSG::scene_render->free(scenario->reflection_probe_shadow_atlas);
  2382. VSG::scene_render->free(scenario->reflection_atlas);
  2383. scenario_owner.free(p_rid);
  2384. memdelete(scenario);
  2385. } else if (instance_owner.owns(p_rid)) {
  2386. // delete the instance
  2387. update_dirty_instances();
  2388. Instance *instance = instance_owner.get(p_rid);
  2389. instance_set_use_lightmap(p_rid, RID(), RID());
  2390. instance_set_scenario(p_rid, RID());
  2391. instance_set_base(p_rid, RID());
  2392. instance_geometry_set_material_override(p_rid, RID());
  2393. instance_attach_skeleton(p_rid, RID());
  2394. update_dirty_instances(); //in case something changed this
  2395. instance_owner.free(p_rid);
  2396. memdelete(instance);
  2397. } else {
  2398. return false;
  2399. }
  2400. return true;
  2401. }
  2402. VisualServerScene *VisualServerScene::singleton = NULL;
  2403. VisualServerScene::VisualServerScene() {
  2404. #ifndef NO_THREADS
  2405. probe_bake_sem = Semaphore::create();
  2406. probe_bake_mutex = Mutex::create();
  2407. probe_bake_thread = Thread::create(_gi_probe_bake_threads, this);
  2408. probe_bake_thread_exit = false;
  2409. #endif
  2410. render_pass = 1;
  2411. singleton = this;
  2412. }
  2413. VisualServerScene::~VisualServerScene() {
  2414. #ifndef NO_THREADS
  2415. probe_bake_thread_exit = true;
  2416. probe_bake_sem->post();
  2417. Thread::wait_to_finish(probe_bake_thread);
  2418. memdelete(probe_bake_thread);
  2419. memdelete(probe_bake_sem);
  2420. memdelete(probe_bake_mutex);
  2421. #endif
  2422. }