2
0

visual_server_scene.cpp 114 KB

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