rendering_server_scene.cpp 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989
  1. /*************************************************************************/
  2. /* rendering_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 "rendering_server_scene.h"
  31. #include "core/os/os.h"
  32. #include "rendering_server_globals.h"
  33. #include "rendering_server_raster.h"
  34. #include <new>
  35. /* CAMERA API */
  36. RID RenderingServerScene::camera_create() {
  37. Camera *camera = memnew(Camera);
  38. return camera_owner.make_rid(camera);
  39. }
  40. void RenderingServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
  41. Camera *camera = camera_owner.getornull(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 RenderingServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
  49. Camera *camera = camera_owner.getornull(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 RenderingServerScene::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.getornull(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 RenderingServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) {
  66. Camera *camera = camera_owner.getornull(p_camera);
  67. ERR_FAIL_COND(!camera);
  68. camera->transform = p_transform.orthonormalized();
  69. }
  70. void RenderingServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
  71. Camera *camera = camera_owner.getornull(p_camera);
  72. ERR_FAIL_COND(!camera);
  73. camera->visible_layers = p_layers;
  74. }
  75. void RenderingServerScene::camera_set_environment(RID p_camera, RID p_env) {
  76. Camera *camera = camera_owner.getornull(p_camera);
  77. ERR_FAIL_COND(!camera);
  78. camera->env = p_env;
  79. }
  80. void RenderingServerScene::camera_set_camera_effects(RID p_camera, RID p_fx) {
  81. Camera *camera = camera_owner.getornull(p_camera);
  82. ERR_FAIL_COND(!camera);
  83. camera->effects = p_fx;
  84. }
  85. void RenderingServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
  86. Camera *camera = camera_owner.getornull(p_camera);
  87. ERR_FAIL_COND(!camera);
  88. camera->vaspect = p_enable;
  89. }
  90. /* SCENARIO API */
  91. void *RenderingServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int) {
  92. //RenderingServerScene *self = (RenderingServerScene*)p_self;
  93. Instance *A = p_A;
  94. Instance *B = p_B;
  95. //instance indices are designed so greater always contains lesser
  96. if (A->base_type > B->base_type) {
  97. SWAP(A, B); //lesser always first
  98. }
  99. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  100. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  101. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  102. InstanceLightData::PairInfo pinfo;
  103. pinfo.geometry = A;
  104. pinfo.L = geom->lighting.push_back(B);
  105. List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);
  106. if (geom->can_cast_shadows) {
  107. light->shadow_dirty = true;
  108. }
  109. geom->lighting_dirty = true;
  110. return E; //this element should make freeing faster
  111. } else if (B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  112. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  113. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  114. InstanceReflectionProbeData::PairInfo pinfo;
  115. pinfo.geometry = A;
  116. pinfo.L = geom->reflection_probes.push_back(B);
  117. List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo);
  118. geom->reflection_dirty = true;
  119. return E; //this element should make freeing faster
  120. } else if (B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  121. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  122. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  123. InstanceDecalData::PairInfo pinfo;
  124. pinfo.geometry = A;
  125. pinfo.L = geom->decals.push_back(B);
  126. List<InstanceDecalData::PairInfo>::Element *E = decal->geometries.push_back(pinfo);
  127. geom->decal_dirty = true;
  128. return E; //this element should make freeing faster
  129. } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  130. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
  131. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  132. if (A->dynamic_gi) {
  133. InstanceLightmapData::PairInfo pinfo;
  134. pinfo.geometry = A;
  135. pinfo.L = geom->lightmap_captures.push_back(B);
  136. List<InstanceLightmapData::PairInfo>::Element *E = lightmap_data->geometries.push_back(pinfo);
  137. ((RenderingServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
  138. return E; //this element should make freeing faster
  139. } else {
  140. return nullptr;
  141. }
  142. } else if (B->base_type == RS::INSTANCE_GI_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  143. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  144. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  145. InstanceGIProbeData::PairInfo pinfo;
  146. pinfo.geometry = A;
  147. pinfo.L = geom->gi_probes.push_back(B);
  148. List<InstanceGIProbeData::PairInfo>::Element *E;
  149. if (A->dynamic_gi) {
  150. E = gi_probe->dynamic_geometries.push_back(pinfo);
  151. } else {
  152. E = gi_probe->geometries.push_back(pinfo);
  153. }
  154. geom->gi_probes_dirty = true;
  155. return E; //this element should make freeing faster
  156. } else if (B->base_type == RS::INSTANCE_GI_PROBE && A->base_type == RS::INSTANCE_LIGHT) {
  157. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  158. return gi_probe->lights.insert(A);
  159. }
  160. return nullptr;
  161. }
  162. void RenderingServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *udata) {
  163. //RenderingServerScene *self = (RenderingServerScene*)p_self;
  164. Instance *A = p_A;
  165. Instance *B = p_B;
  166. //instance indices are designed so greater always contains lesser
  167. if (A->base_type > B->base_type) {
  168. SWAP(A, B); //lesser always first
  169. }
  170. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  171. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  172. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  173. List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata);
  174. geom->lighting.erase(E->get().L);
  175. light->geometries.erase(E);
  176. if (geom->can_cast_shadows) {
  177. light->shadow_dirty = true;
  178. }
  179. geom->lighting_dirty = true;
  180. } else if (B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  181. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  182. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  183. List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata);
  184. geom->reflection_probes.erase(E->get().L);
  185. reflection_probe->geometries.erase(E);
  186. geom->reflection_dirty = true;
  187. } else if (B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  188. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  189. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  190. List<InstanceDecalData::PairInfo>::Element *E = reinterpret_cast<List<InstanceDecalData::PairInfo>::Element *>(udata);
  191. geom->decals.erase(E->get().L);
  192. decal->geometries.erase(E);
  193. geom->decal_dirty = true;
  194. } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  195. if (udata) { //only for dynamic geometries
  196. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
  197. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  198. List<InstanceLightmapData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightmapData::PairInfo>::Element *>(udata);
  199. geom->lightmap_captures.erase(E->get().L);
  200. lightmap_data->geometries.erase(E);
  201. ((RenderingServerScene *)p_self)->_instance_queue_update(A, false, false); //need to update capture
  202. }
  203. } else if (B->base_type == RS::INSTANCE_GI_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  204. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  205. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  206. List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata);
  207. geom->gi_probes.erase(E->get().L);
  208. if (A->dynamic_gi) {
  209. gi_probe->dynamic_geometries.erase(E);
  210. } else {
  211. gi_probe->geometries.erase(E);
  212. }
  213. geom->gi_probes_dirty = true;
  214. } else if (B->base_type == RS::INSTANCE_GI_PROBE && A->base_type == RS::INSTANCE_LIGHT) {
  215. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
  216. Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata);
  217. gi_probe->lights.erase(E);
  218. }
  219. }
  220. RID RenderingServerScene::scenario_create() {
  221. Scenario *scenario = memnew(Scenario);
  222. ERR_FAIL_COND_V(!scenario, RID());
  223. RID scenario_rid = scenario_owner.make_rid(scenario);
  224. scenario->self = scenario_rid;
  225. scenario->octree.set_pair_callback(_instance_pair, this);
  226. scenario->octree.set_unpair_callback(_instance_unpair, this);
  227. scenario->reflection_probe_shadow_atlas = RSG::scene_render->shadow_atlas_create();
  228. RSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
  229. RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
  230. RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
  231. RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
  232. RSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
  233. scenario->reflection_atlas = RSG::scene_render->reflection_atlas_create();
  234. return scenario_rid;
  235. }
  236. void RenderingServerScene::scenario_set_debug(RID p_scenario, RS::ScenarioDebugMode p_debug_mode) {
  237. Scenario *scenario = scenario_owner.getornull(p_scenario);
  238. ERR_FAIL_COND(!scenario);
  239. scenario->debug = p_debug_mode;
  240. }
  241. void RenderingServerScene::scenario_set_environment(RID p_scenario, RID p_environment) {
  242. Scenario *scenario = scenario_owner.getornull(p_scenario);
  243. ERR_FAIL_COND(!scenario);
  244. scenario->environment = p_environment;
  245. }
  246. void RenderingServerScene::scenario_set_camera_effects(RID p_scenario, RID p_camera_effects) {
  247. Scenario *scenario = scenario_owner.getornull(p_scenario);
  248. ERR_FAIL_COND(!scenario);
  249. scenario->camera_effects = p_camera_effects;
  250. }
  251. void RenderingServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
  252. Scenario *scenario = scenario_owner.getornull(p_scenario);
  253. ERR_FAIL_COND(!scenario);
  254. scenario->fallback_environment = p_environment;
  255. }
  256. void RenderingServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_reflection_size, int p_reflection_count) {
  257. Scenario *scenario = scenario_owner.getornull(p_scenario);
  258. ERR_FAIL_COND(!scenario);
  259. RSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_reflection_size, p_reflection_count);
  260. }
  261. /* INSTANCING API */
  262. void RenderingServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_dependencies) {
  263. if (p_update_aabb) {
  264. p_instance->update_aabb = true;
  265. }
  266. if (p_update_dependencies) {
  267. p_instance->update_dependencies = true;
  268. }
  269. if (p_instance->update_item.in_list()) {
  270. return;
  271. }
  272. _instance_update_list.add(&p_instance->update_item);
  273. }
  274. RID RenderingServerScene::instance_create() {
  275. Instance *instance = memnew(Instance);
  276. ERR_FAIL_COND_V(!instance, RID());
  277. RID instance_rid = instance_owner.make_rid(instance);
  278. instance->self = instance_rid;
  279. return instance_rid;
  280. }
  281. void RenderingServerScene::instance_set_base(RID p_instance, RID p_base) {
  282. Instance *instance = instance_owner.getornull(p_instance);
  283. ERR_FAIL_COND(!instance);
  284. Scenario *scenario = instance->scenario;
  285. if (instance->base_type != RS::INSTANCE_NONE) {
  286. //free anything related to that base
  287. if (scenario && instance->octree_id) {
  288. scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
  289. instance->octree_id = 0;
  290. }
  291. switch (instance->base_type) {
  292. case RS::INSTANCE_LIGHT: {
  293. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  294. if (RSG::storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  295. instance->scenario->dynamic_lights.erase(light->instance);
  296. }
  297. #ifdef DEBUG_ENABLED
  298. if (light->geometries.size()) {
  299. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  300. }
  301. #endif
  302. if (instance->scenario && light->D) {
  303. instance->scenario->directional_lights.erase(light->D);
  304. light->D = nullptr;
  305. }
  306. RSG::scene_render->free(light->instance);
  307. } break;
  308. case RS::INSTANCE_REFLECTION_PROBE: {
  309. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  310. RSG::scene_render->free(reflection_probe->instance);
  311. if (reflection_probe->update_list.in_list()) {
  312. reflection_probe_render_list.remove(&reflection_probe->update_list);
  313. }
  314. } break;
  315. case RS::INSTANCE_DECAL: {
  316. InstanceDecalData *decal = static_cast<InstanceDecalData *>(instance->base_data);
  317. RSG::scene_render->free(decal->instance);
  318. } break;
  319. case RS::INSTANCE_LIGHTMAP: {
  320. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(instance->base_data);
  321. //erase dependencies, since no longer a lightmap
  322. while (lightmap_data->users.front()) {
  323. instance_geometry_set_lightmap(lightmap_data->users.front()->get()->self, RID(), Rect2(), 0);
  324. }
  325. } break;
  326. case RS::INSTANCE_GI_PROBE: {
  327. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  328. #ifdef DEBUG_ENABLED
  329. if (gi_probe->geometries.size()) {
  330. ERR_PRINT("BUG, indexing did not unpair geometries from GIProbe.");
  331. }
  332. #endif
  333. #ifdef DEBUG_ENABLED
  334. if (gi_probe->lights.size()) {
  335. ERR_PRINT("BUG, indexing did not unpair lights from GIProbe.");
  336. }
  337. #endif
  338. if (gi_probe->update_element.in_list()) {
  339. gi_probe_update_list.remove(&gi_probe->update_element);
  340. }
  341. RSG::scene_render->free(gi_probe->probe_instance);
  342. } break;
  343. default: {
  344. }
  345. }
  346. if (instance->base_data) {
  347. memdelete(instance->base_data);
  348. instance->base_data = nullptr;
  349. }
  350. instance->blend_values.clear();
  351. instance->materials.clear();
  352. }
  353. instance->base_type = RS::INSTANCE_NONE;
  354. instance->base = RID();
  355. if (p_base.is_valid()) {
  356. instance->base_type = RSG::storage->get_base_type(p_base);
  357. ERR_FAIL_COND(instance->base_type == RS::INSTANCE_NONE);
  358. switch (instance->base_type) {
  359. case RS::INSTANCE_LIGHT: {
  360. InstanceLightData *light = memnew(InstanceLightData);
  361. if (scenario && RSG::storage->light_get_type(p_base) == RS::LIGHT_DIRECTIONAL) {
  362. light->D = scenario->directional_lights.push_back(instance);
  363. }
  364. light->instance = RSG::scene_render->light_instance_create(p_base);
  365. instance->base_data = light;
  366. } break;
  367. case RS::INSTANCE_MESH:
  368. case RS::INSTANCE_MULTIMESH:
  369. case RS::INSTANCE_IMMEDIATE:
  370. case RS::INSTANCE_PARTICLES: {
  371. InstanceGeometryData *geom = memnew(InstanceGeometryData);
  372. instance->base_data = geom;
  373. if (instance->base_type == RS::INSTANCE_MESH) {
  374. instance->blend_values.resize(RSG::storage->mesh_get_blend_shape_count(p_base));
  375. }
  376. } break;
  377. case RS::INSTANCE_REFLECTION_PROBE: {
  378. InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
  379. reflection_probe->owner = instance;
  380. instance->base_data = reflection_probe;
  381. reflection_probe->instance = RSG::scene_render->reflection_probe_instance_create(p_base);
  382. } break;
  383. case RS::INSTANCE_DECAL: {
  384. InstanceDecalData *decal = memnew(InstanceDecalData);
  385. decal->owner = instance;
  386. instance->base_data = decal;
  387. decal->instance = RSG::scene_render->decal_instance_create(p_base);
  388. } break;
  389. case RS::INSTANCE_LIGHTMAP: {
  390. InstanceLightmapData *lightmap_data = memnew(InstanceLightmapData);
  391. instance->base_data = lightmap_data;
  392. //lightmap_data->instance = RSG::scene_render->lightmap_data_instance_create(p_base);
  393. } break;
  394. case RS::INSTANCE_GI_PROBE: {
  395. InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
  396. instance->base_data = gi_probe;
  397. gi_probe->owner = instance;
  398. if (scenario && !gi_probe->update_element.in_list()) {
  399. gi_probe_update_list.add(&gi_probe->update_element);
  400. }
  401. gi_probe->probe_instance = RSG::scene_render->gi_probe_instance_create(p_base);
  402. } break;
  403. default: {
  404. }
  405. }
  406. instance->base = p_base;
  407. //forcefully update the dependency now, so if for some reason it gets removed, we can immediately clear it
  408. RSG::storage->base_update_dependency(p_base, instance);
  409. }
  410. _instance_queue_update(instance, true, true);
  411. }
  412. void RenderingServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
  413. Instance *instance = instance_owner.getornull(p_instance);
  414. ERR_FAIL_COND(!instance);
  415. if (instance->scenario) {
  416. instance->scenario->instances.remove(&instance->scenario_item);
  417. if (instance->octree_id) {
  418. instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
  419. instance->octree_id = 0;
  420. }
  421. switch (instance->base_type) {
  422. case RS::INSTANCE_LIGHT: {
  423. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  424. #ifdef DEBUG_ENABLED
  425. if (light->geometries.size()) {
  426. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  427. }
  428. #endif
  429. if (light->D) {
  430. instance->scenario->directional_lights.erase(light->D);
  431. light->D = nullptr;
  432. }
  433. } break;
  434. case RS::INSTANCE_REFLECTION_PROBE: {
  435. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  436. RSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
  437. } break;
  438. case RS::INSTANCE_GI_PROBE: {
  439. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  440. #ifdef DEBUG_ENABLED
  441. if (gi_probe->geometries.size()) {
  442. ERR_PRINT("BUG, indexing did not unpair geometries from GIProbe.");
  443. }
  444. #endif
  445. #ifdef DEBUG_ENABLED
  446. if (gi_probe->lights.size()) {
  447. ERR_PRINT("BUG, indexing did not unpair lights from GIProbe.");
  448. }
  449. #endif
  450. if (gi_probe->update_element.in_list()) {
  451. gi_probe_update_list.remove(&gi_probe->update_element);
  452. }
  453. } break;
  454. default: {
  455. }
  456. }
  457. instance->scenario = nullptr;
  458. }
  459. if (p_scenario.is_valid()) {
  460. Scenario *scenario = scenario_owner.getornull(p_scenario);
  461. ERR_FAIL_COND(!scenario);
  462. instance->scenario = scenario;
  463. scenario->instances.add(&instance->scenario_item);
  464. switch (instance->base_type) {
  465. case RS::INSTANCE_LIGHT: {
  466. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  467. if (RSG::storage->light_get_type(instance->base) == RS::LIGHT_DIRECTIONAL) {
  468. light->D = scenario->directional_lights.push_back(instance);
  469. }
  470. } break;
  471. case RS::INSTANCE_GI_PROBE: {
  472. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
  473. if (!gi_probe->update_element.in_list()) {
  474. gi_probe_update_list.add(&gi_probe->update_element);
  475. }
  476. } break;
  477. default: {
  478. }
  479. }
  480. _instance_queue_update(instance, true, true);
  481. }
  482. }
  483. void RenderingServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
  484. Instance *instance = instance_owner.getornull(p_instance);
  485. ERR_FAIL_COND(!instance);
  486. instance->layer_mask = p_mask;
  487. }
  488. void RenderingServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) {
  489. Instance *instance = instance_owner.getornull(p_instance);
  490. ERR_FAIL_COND(!instance);
  491. if (instance->transform == p_transform) {
  492. return; //must be checked to avoid worst evil
  493. }
  494. #ifdef DEBUG_ENABLED
  495. for (int i = 0; i < 4; i++) {
  496. const Vector3 &v = i < 3 ? p_transform.basis.elements[i] : p_transform.origin;
  497. ERR_FAIL_COND(Math::is_inf(v.x));
  498. ERR_FAIL_COND(Math::is_nan(v.x));
  499. ERR_FAIL_COND(Math::is_inf(v.y));
  500. ERR_FAIL_COND(Math::is_nan(v.y));
  501. ERR_FAIL_COND(Math::is_inf(v.z));
  502. ERR_FAIL_COND(Math::is_nan(v.z));
  503. }
  504. #endif
  505. instance->transform = p_transform;
  506. _instance_queue_update(instance, true);
  507. }
  508. void RenderingServerScene::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {
  509. Instance *instance = instance_owner.getornull(p_instance);
  510. ERR_FAIL_COND(!instance);
  511. instance->object_id = p_id;
  512. }
  513. void RenderingServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
  514. Instance *instance = instance_owner.getornull(p_instance);
  515. ERR_FAIL_COND(!instance);
  516. if (instance->update_item.in_list()) {
  517. _update_dirty_instance(instance);
  518. }
  519. ERR_FAIL_INDEX(p_shape, instance->blend_values.size());
  520. instance->blend_values.write[p_shape] = p_weight;
  521. }
  522. void RenderingServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {
  523. Instance *instance = instance_owner.getornull(p_instance);
  524. ERR_FAIL_COND(!instance);
  525. if (instance->base_type == RS::INSTANCE_MESH) {
  526. //may not have been updated yet, may also have not been set yet. When updated will be correcte, worst case
  527. instance->materials.resize(MAX(p_surface + 1, RSG::storage->mesh_get_surface_count(instance->base)));
  528. }
  529. ERR_FAIL_INDEX(p_surface, instance->materials.size());
  530. instance->materials.write[p_surface] = p_material;
  531. _instance_queue_update(instance, false, true);
  532. }
  533. void RenderingServerScene::instance_set_visible(RID p_instance, bool p_visible) {
  534. Instance *instance = instance_owner.getornull(p_instance);
  535. ERR_FAIL_COND(!instance);
  536. if (instance->visible == p_visible) {
  537. return;
  538. }
  539. instance->visible = p_visible;
  540. switch (instance->base_type) {
  541. case RS::INSTANCE_LIGHT: {
  542. if (RSG::storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) {
  543. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_LIGHT, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
  544. }
  545. } break;
  546. case RS::INSTANCE_REFLECTION_PROBE: {
  547. if (instance->octree_id && instance->scenario) {
  548. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_REFLECTION_PROBE, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
  549. }
  550. } break;
  551. case RS::INSTANCE_DECAL: {
  552. if (instance->octree_id && instance->scenario) {
  553. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_DECAL, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
  554. }
  555. } break;
  556. case RS::INSTANCE_LIGHTMAP: {
  557. if (instance->octree_id && instance->scenario) {
  558. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_LIGHTMAP, p_visible ? RS::INSTANCE_GEOMETRY_MASK : 0);
  559. }
  560. } break;
  561. case RS::INSTANCE_GI_PROBE: {
  562. if (instance->octree_id && instance->scenario) {
  563. instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << RS::INSTANCE_GI_PROBE, p_visible ? (RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT)) : 0);
  564. }
  565. } break;
  566. default: {
  567. }
  568. }
  569. }
  570. inline bool is_geometry_instance(RenderingServer::InstanceType p_type) {
  571. return p_type == RS::INSTANCE_MESH || p_type == RS::INSTANCE_MULTIMESH || p_type == RS::INSTANCE_PARTICLES || p_type == RS::INSTANCE_IMMEDIATE;
  572. }
  573. void RenderingServerScene::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
  574. Instance *instance = instance_owner.getornull(p_instance);
  575. ERR_FAIL_COND(!instance);
  576. ERR_FAIL_COND(!is_geometry_instance(instance->base_type));
  577. if (p_aabb != AABB()) {
  578. // Set custom AABB
  579. if (instance->custom_aabb == nullptr) {
  580. instance->custom_aabb = memnew(AABB);
  581. }
  582. *instance->custom_aabb = p_aabb;
  583. } else {
  584. // Clear custom AABB
  585. if (instance->custom_aabb != nullptr) {
  586. memdelete(instance->custom_aabb);
  587. instance->custom_aabb = nullptr;
  588. }
  589. }
  590. if (instance->scenario) {
  591. _instance_queue_update(instance, true, false);
  592. }
  593. }
  594. void RenderingServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
  595. Instance *instance = instance_owner.getornull(p_instance);
  596. ERR_FAIL_COND(!instance);
  597. if (instance->skeleton == p_skeleton) {
  598. return;
  599. }
  600. instance->skeleton = p_skeleton;
  601. if (p_skeleton.is_valid()) {
  602. //update the dependency now, so if cleared, we remove it
  603. RSG::storage->skeleton_update_dependency(p_skeleton, instance);
  604. }
  605. _instance_queue_update(instance, true, true);
  606. }
  607. void RenderingServerScene::instance_set_exterior(RID p_instance, bool p_enabled) {
  608. }
  609. void RenderingServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
  610. Instance *instance = instance_owner.getornull(p_instance);
  611. ERR_FAIL_COND(!instance);
  612. instance->extra_margin = p_margin;
  613. _instance_queue_update(instance, true, false);
  614. }
  615. Vector<ObjectID> RenderingServerScene::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
  616. Vector<ObjectID> instances;
  617. Scenario *scenario = scenario_owner.getornull(p_scenario);
  618. ERR_FAIL_COND_V(!scenario, instances);
  619. const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  620. int culled = 0;
  621. Instance *cull[1024];
  622. culled = scenario->octree.cull_aabb(p_aabb, cull, 1024);
  623. for (int i = 0; i < culled; i++) {
  624. Instance *instance = cull[i];
  625. ERR_CONTINUE(!instance);
  626. if (instance->object_id.is_null()) {
  627. continue;
  628. }
  629. instances.push_back(instance->object_id);
  630. }
  631. return instances;
  632. }
  633. Vector<ObjectID> RenderingServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
  634. Vector<ObjectID> instances;
  635. Scenario *scenario = scenario_owner.getornull(p_scenario);
  636. ERR_FAIL_COND_V(!scenario, instances);
  637. const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  638. int culled = 0;
  639. Instance *cull[1024];
  640. culled = scenario->octree.cull_segment(p_from, p_from + p_to * 10000, cull, 1024);
  641. for (int i = 0; i < culled; i++) {
  642. Instance *instance = cull[i];
  643. ERR_CONTINUE(!instance);
  644. if (instance->object_id.is_null()) {
  645. continue;
  646. }
  647. instances.push_back(instance->object_id);
  648. }
  649. return instances;
  650. }
  651. Vector<ObjectID> RenderingServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
  652. Vector<ObjectID> instances;
  653. Scenario *scenario = scenario_owner.getornull(p_scenario);
  654. ERR_FAIL_COND_V(!scenario, instances);
  655. const_cast<RenderingServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
  656. int culled = 0;
  657. Instance *cull[1024];
  658. culled = scenario->octree.cull_convex(p_convex, cull, 1024);
  659. for (int i = 0; i < culled; i++) {
  660. Instance *instance = cull[i];
  661. ERR_CONTINUE(!instance);
  662. if (instance->object_id.is_null()) {
  663. continue;
  664. }
  665. instances.push_back(instance->object_id);
  666. }
  667. return instances;
  668. }
  669. void RenderingServerScene::instance_geometry_set_flag(RID p_instance, RS::InstanceFlags p_flags, bool p_enabled) {
  670. Instance *instance = instance_owner.getornull(p_instance);
  671. ERR_FAIL_COND(!instance);
  672. //ERR_FAIL_COND(((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK));
  673. switch (p_flags) {
  674. case RS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
  675. instance->baked_light = p_enabled;
  676. } break;
  677. case RS::INSTANCE_FLAG_USE_DYNAMIC_GI: {
  678. if (p_enabled == instance->dynamic_gi) {
  679. //bye, redundant
  680. return;
  681. }
  682. if (instance->octree_id != 0) {
  683. //remove from octree, it needs to be re-paired
  684. instance->scenario->octree.erase(instance->octree_id);
  685. instance->octree_id = 0;
  686. _instance_queue_update(instance, true, true);
  687. }
  688. //once out of octree, can be changed
  689. instance->dynamic_gi = p_enabled;
  690. } break;
  691. case RS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {
  692. instance->redraw_if_visible = p_enabled;
  693. } break;
  694. default: {
  695. }
  696. }
  697. }
  698. void RenderingServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, RS::ShadowCastingSetting p_shadow_casting_setting) {
  699. Instance *instance = instance_owner.getornull(p_instance);
  700. ERR_FAIL_COND(!instance);
  701. instance->cast_shadows = p_shadow_casting_setting;
  702. _instance_queue_update(instance, false, true);
  703. }
  704. void RenderingServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) {
  705. Instance *instance = instance_owner.getornull(p_instance);
  706. ERR_FAIL_COND(!instance);
  707. instance->material_override = p_material;
  708. _instance_queue_update(instance, false, true);
  709. }
  710. void RenderingServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
  711. }
  712. void RenderingServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
  713. }
  714. void RenderingServerScene::instance_geometry_set_lightmap(RID p_instance, RID p_lightmap, const Rect2 &p_lightmap_uv_scale, int p_slice_index) {
  715. Instance *instance = instance_owner.getornull(p_instance);
  716. ERR_FAIL_COND(!instance);
  717. if (instance->lightmap) {
  718. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(((Instance *)instance->lightmap)->base_data);
  719. lightmap_data->users.erase(instance);
  720. instance->lightmap = nullptr;
  721. }
  722. Instance *lightmap_instance = instance_owner.getornull(p_lightmap);
  723. instance->lightmap = lightmap_instance;
  724. instance->lightmap_uv_scale = p_lightmap_uv_scale;
  725. instance->lightmap_slice_index = p_slice_index;
  726. if (lightmap_instance) {
  727. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(lightmap_instance->base_data);
  728. lightmap_data->users.insert(instance);
  729. }
  730. }
  731. void RenderingServerScene::instance_geometry_set_shader_parameter(RID p_instance, const StringName &p_parameter, const Variant &p_value) {
  732. Instance *instance = instance_owner.getornull(p_instance);
  733. ERR_FAIL_COND(!instance);
  734. Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter>::Element *E = instance->instance_shader_parameters.find(p_parameter);
  735. if (!E) {
  736. RasterizerScene::InstanceBase::InstanceShaderParameter isp;
  737. isp.index = -1;
  738. isp.info = PropertyInfo();
  739. isp.value = p_value;
  740. instance->instance_shader_parameters[p_parameter] = isp;
  741. } else {
  742. E->get().value = p_value;
  743. if (E->get().index >= 0 && instance->instance_allocated_shader_parameters) {
  744. //update directly
  745. RSG::storage->global_variables_instance_update(p_instance, E->get().index, p_value);
  746. }
  747. }
  748. }
  749. Variant RenderingServerScene::instance_geometry_get_shader_parameter(RID p_instance, const StringName &p_parameter) const {
  750. const Instance *instance = const_cast<RenderingServerScene *>(this)->instance_owner.getornull(p_instance);
  751. ERR_FAIL_COND_V(!instance, Variant());
  752. if (instance->instance_shader_parameters.has(p_parameter)) {
  753. return instance->instance_shader_parameters[p_parameter].value;
  754. }
  755. return Variant();
  756. }
  757. Variant RenderingServerScene::instance_geometry_get_shader_parameter_default_value(RID p_instance, const StringName &p_parameter) const {
  758. const Instance *instance = const_cast<RenderingServerScene *>(this)->instance_owner.getornull(p_instance);
  759. ERR_FAIL_COND_V(!instance, Variant());
  760. if (instance->instance_shader_parameters.has(p_parameter)) {
  761. return instance->instance_shader_parameters[p_parameter].default_value;
  762. }
  763. return Variant();
  764. }
  765. void RenderingServerScene::instance_geometry_get_shader_parameter_list(RID p_instance, List<PropertyInfo> *p_parameters) const {
  766. const Instance *instance = const_cast<RenderingServerScene *>(this)->instance_owner.getornull(p_instance);
  767. ERR_FAIL_COND(!instance);
  768. const_cast<RenderingServerScene *>(this)->update_dirty_instances();
  769. Vector<StringName> names;
  770. for (Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter>::Element *E = instance->instance_shader_parameters.front(); E; E = E->next()) {
  771. names.push_back(E->key());
  772. }
  773. names.sort_custom<StringName::AlphCompare>();
  774. for (int i = 0; i < names.size(); i++) {
  775. PropertyInfo pinfo = instance->instance_shader_parameters[names[i]].info;
  776. p_parameters->push_back(pinfo);
  777. }
  778. }
  779. void RenderingServerScene::_update_instance(Instance *p_instance) {
  780. p_instance->version++;
  781. if (p_instance->base_type == RS::INSTANCE_LIGHT) {
  782. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  783. RSG::scene_render->light_instance_set_transform(light->instance, p_instance->transform);
  784. RSG::scene_render->light_instance_set_aabb(light->instance, p_instance->transform.xform(p_instance->aabb));
  785. light->shadow_dirty = true;
  786. RS::LightBakeMode bake_mode = RSG::storage->light_get_bake_mode(p_instance->base);
  787. if (RSG::storage->light_get_type(p_instance->base) != RS::LIGHT_DIRECTIONAL && bake_mode != light->bake_mode) {
  788. if (light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  789. p_instance->scenario->dynamic_lights.erase(light->instance);
  790. }
  791. light->bake_mode = bake_mode;
  792. if (light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  793. p_instance->scenario->dynamic_lights.push_back(light->instance);
  794. }
  795. }
  796. uint32_t max_sdfgi_cascade = RSG::storage->light_get_max_sdfgi_cascade(p_instance->base);
  797. if (light->max_sdfgi_cascade != max_sdfgi_cascade) {
  798. light->max_sdfgi_cascade = max_sdfgi_cascade; //should most likely make sdfgi dirty in scenario
  799. }
  800. }
  801. if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
  802. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  803. RSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
  804. reflection_probe->reflection_dirty = true;
  805. }
  806. if (p_instance->base_type == RS::INSTANCE_DECAL) {
  807. InstanceDecalData *decal = static_cast<InstanceDecalData *>(p_instance->base_data);
  808. RSG::scene_render->decal_instance_set_transform(decal->instance, p_instance->transform);
  809. }
  810. if (p_instance->base_type == RS::INSTANCE_GI_PROBE) {
  811. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);
  812. RSG::scene_render->gi_probe_instance_set_transform_to_data(gi_probe->probe_instance, p_instance->transform);
  813. }
  814. if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  815. RSG::storage->particles_set_emission_transform(p_instance->base, p_instance->transform);
  816. }
  817. if (p_instance->aabb.has_no_surface()) {
  818. return;
  819. }
  820. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  821. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  822. //make sure lights are updated if it casts shadow
  823. if (geom->can_cast_shadows) {
  824. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  825. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  826. light->shadow_dirty = true;
  827. }
  828. }
  829. if (!p_instance->lightmap && geom->lightmap_captures.size()) {
  830. //affected by lightmap captures, must update capture info!
  831. _update_instance_lightmap_captures(p_instance);
  832. } else {
  833. if (!p_instance->lightmap_sh.empty()) {
  834. p_instance->lightmap_sh.clear(); //don't need SH
  835. p_instance->lightmap_target_sh.clear(); //don't need SH
  836. }
  837. }
  838. }
  839. if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  840. //if this moved, update the captured objects
  841. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(p_instance->base_data);
  842. //erase dependencies, since no longer a lightmap
  843. for (List<InstanceLightmapData::PairInfo>::Element *E = lightmap_data->geometries.front(); E; E = E->next()) {
  844. Instance *geom = E->get().geometry;
  845. _instance_queue_update(geom, true, false);
  846. }
  847. }
  848. p_instance->mirror = p_instance->transform.basis.determinant() < 0.0;
  849. AABB new_aabb;
  850. new_aabb = p_instance->transform.xform(p_instance->aabb);
  851. p_instance->transformed_aabb = new_aabb;
  852. if (!p_instance->scenario) {
  853. return;
  854. }
  855. if (p_instance->octree_id == 0) {
  856. uint32_t base_type = 1 << p_instance->base_type;
  857. uint32_t pairable_mask = 0;
  858. bool pairable = false;
  859. if (p_instance->base_type == RS::INSTANCE_LIGHT || p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE || p_instance->base_type == RS::INSTANCE_DECAL || p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  860. pairable_mask = p_instance->visible ? RS::INSTANCE_GEOMETRY_MASK : 0;
  861. pairable = true;
  862. }
  863. if (p_instance->base_type == RS::INSTANCE_GI_PROBE) {
  864. //lights and geometries
  865. pairable_mask = p_instance->visible ? RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT) : 0;
  866. pairable = true;
  867. }
  868. // not inside octree
  869. p_instance->octree_id = p_instance->scenario->octree.create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask);
  870. } else {
  871. /*
  872. if (new_aabb==p_instance->data.transformed_aabb)
  873. return;
  874. */
  875. p_instance->scenario->octree.move(p_instance->octree_id, new_aabb);
  876. }
  877. }
  878. void RenderingServerScene::_update_instance_aabb(Instance *p_instance) {
  879. AABB new_aabb;
  880. ERR_FAIL_COND(p_instance->base_type != RS::INSTANCE_NONE && !p_instance->base.is_valid());
  881. switch (p_instance->base_type) {
  882. case RenderingServer::INSTANCE_NONE: {
  883. // do nothing
  884. } break;
  885. case RenderingServer::INSTANCE_MESH: {
  886. if (p_instance->custom_aabb) {
  887. new_aabb = *p_instance->custom_aabb;
  888. } else {
  889. new_aabb = RSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
  890. }
  891. } break;
  892. case RenderingServer::INSTANCE_MULTIMESH: {
  893. if (p_instance->custom_aabb) {
  894. new_aabb = *p_instance->custom_aabb;
  895. } else {
  896. new_aabb = RSG::storage->multimesh_get_aabb(p_instance->base);
  897. }
  898. } break;
  899. case RenderingServer::INSTANCE_IMMEDIATE: {
  900. if (p_instance->custom_aabb) {
  901. new_aabb = *p_instance->custom_aabb;
  902. } else {
  903. new_aabb = RSG::storage->immediate_get_aabb(p_instance->base);
  904. }
  905. } break;
  906. case RenderingServer::INSTANCE_PARTICLES: {
  907. if (p_instance->custom_aabb) {
  908. new_aabb = *p_instance->custom_aabb;
  909. } else {
  910. new_aabb = RSG::storage->particles_get_aabb(p_instance->base);
  911. }
  912. } break;
  913. case RenderingServer::INSTANCE_LIGHT: {
  914. new_aabb = RSG::storage->light_get_aabb(p_instance->base);
  915. } break;
  916. case RenderingServer::INSTANCE_REFLECTION_PROBE: {
  917. new_aabb = RSG::storage->reflection_probe_get_aabb(p_instance->base);
  918. } break;
  919. case RenderingServer::INSTANCE_DECAL: {
  920. new_aabb = RSG::storage->decal_get_aabb(p_instance->base);
  921. } break;
  922. case RenderingServer::INSTANCE_GI_PROBE: {
  923. new_aabb = RSG::storage->gi_probe_get_bounds(p_instance->base);
  924. } break;
  925. case RenderingServer::INSTANCE_LIGHTMAP: {
  926. new_aabb = RSG::storage->lightmap_get_aabb(p_instance->base);
  927. } break;
  928. default: {
  929. }
  930. }
  931. // <Zylann> This is why I didn't re-use Instance::aabb to implement custom AABBs
  932. if (p_instance->extra_margin) {
  933. new_aabb.grow_by(p_instance->extra_margin);
  934. }
  935. p_instance->aabb = new_aabb;
  936. }
  937. void RenderingServerScene::_update_instance_lightmap_captures(Instance *p_instance) {
  938. bool first_set = p_instance->lightmap_sh.size() == 0;
  939. p_instance->lightmap_sh.resize(9); //using SH
  940. p_instance->lightmap_target_sh.resize(9); //using SH
  941. Color *instance_sh = p_instance->lightmap_target_sh.ptrw();
  942. bool inside = false;
  943. Color accum_sh[9];
  944. float accum_blend = 0.0;
  945. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  946. for (List<Instance *>::Element *E = geom->lightmap_captures.front(); E; E = E->next()) {
  947. Instance *lightmap = E->get();
  948. bool interior = RSG::storage->lightmap_is_interior(lightmap->base);
  949. if (inside && !interior) {
  950. continue; //we are inside, ignore exteriors
  951. }
  952. Transform to_bounds = lightmap->transform.affine_inverse();
  953. Vector3 center = p_instance->transform.xform(p_instance->aabb.position + p_instance->aabb.size * 0.5); //use aabb center
  954. Vector3 lm_pos = to_bounds.xform(center);
  955. AABB bounds = RSG::storage->lightmap_get_aabb(lightmap->base);
  956. if (!bounds.has_point(lm_pos)) {
  957. continue; //not in this lightmap
  958. }
  959. Color sh[9];
  960. RSG::storage->lightmap_tap_sh_light(lightmap->base, lm_pos, sh);
  961. //rotate it
  962. Basis rot = lightmap->transform.basis.orthonormalized();
  963. for (int i = 0; i < 3; i++) {
  964. float csh[9];
  965. for (int j = 0; j < 9; j++) {
  966. csh[j] = sh[j][i];
  967. }
  968. rot.rotate_sh(csh);
  969. for (int j = 0; j < 9; j++) {
  970. sh[j][i] = csh[j];
  971. }
  972. }
  973. Vector3 inner_pos = ((lm_pos - bounds.position) / bounds.size) * 2.0 - Vector3(1.0, 1.0, 1.0);
  974. float blend = MAX(inner_pos.x, MAX(inner_pos.y, inner_pos.z));
  975. //make blend more rounded
  976. blend = Math::lerp(inner_pos.length(), blend, blend);
  977. blend *= blend;
  978. blend = MAX(0.0, 1.0 - blend);
  979. if (interior && !inside) {
  980. //do not blend, just replace
  981. for (int j = 0; j < 9; j++) {
  982. accum_sh[j] = sh[j] * blend;
  983. }
  984. accum_blend = blend;
  985. inside = true;
  986. } else {
  987. for (int j = 0; j < 9; j++) {
  988. accum_sh[j] += sh[j] * blend;
  989. }
  990. accum_blend += blend;
  991. }
  992. }
  993. if (accum_blend > 0.0) {
  994. for (int j = 0; j < 9; j++) {
  995. instance_sh[j] = accum_sh[j] / accum_blend;
  996. if (first_set) {
  997. p_instance->lightmap_sh.write[j] = instance_sh[j];
  998. }
  999. }
  1000. }
  1001. }
  1002. bool RenderingServerScene::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_shadow_atlas, Scenario *p_scenario) {
  1003. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1004. Transform light_transform = p_instance->transform;
  1005. light_transform.orthonormalize(); //scale does not count on lights
  1006. bool animated_material_found = false;
  1007. switch (RSG::storage->light_get_type(p_instance->base)) {
  1008. case RS::LIGHT_DIRECTIONAL: {
  1009. real_t max_distance = p_cam_projection.get_z_far();
  1010. real_t shadow_max = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
  1011. if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
  1012. max_distance = MIN(shadow_max, max_distance);
  1013. }
  1014. max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
  1015. real_t min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
  1016. RS::LightDirectionalShadowDepthRangeMode depth_range_mode = RSG::storage->light_directional_get_shadow_depth_range_mode(p_instance->base);
  1017. real_t pancake_size = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE);
  1018. if (depth_range_mode == RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_OPTIMIZED) {
  1019. //optimize min/max
  1020. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  1021. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1022. Plane base(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2));
  1023. //check distance max and min
  1024. bool found_items = false;
  1025. real_t z_max = -1e20;
  1026. real_t z_min = 1e20;
  1027. for (int i = 0; i < cull_count; i++) {
  1028. Instance *instance = instance_shadow_cull_result[i];
  1029. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1030. continue;
  1031. }
  1032. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1033. animated_material_found = true;
  1034. }
  1035. real_t max, min;
  1036. instance->transformed_aabb.project_range_in_plane(base, min, max);
  1037. if (max > z_max) {
  1038. z_max = max;
  1039. }
  1040. if (min < z_min) {
  1041. z_min = min;
  1042. }
  1043. found_items = true;
  1044. }
  1045. if (found_items) {
  1046. min_distance = MAX(min_distance, z_min);
  1047. max_distance = MIN(max_distance, z_max);
  1048. }
  1049. }
  1050. real_t range = max_distance - min_distance;
  1051. int splits = 0;
  1052. switch (RSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
  1053. case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  1054. splits = 1;
  1055. break;
  1056. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  1057. splits = 2;
  1058. break;
  1059. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  1060. splits = 4;
  1061. break;
  1062. }
  1063. real_t distances[5];
  1064. distances[0] = min_distance;
  1065. for (int i = 0; i < splits; i++) {
  1066. distances[i + 1] = min_distance + RSG::storage->light_get_param(p_instance->base, RS::LightParam(RS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
  1067. };
  1068. distances[splits] = max_distance;
  1069. real_t texture_size = RSG::scene_render->get_directional_light_shadow_size(light->instance);
  1070. bool overlap = RSG::storage->light_directional_get_blend_splits(p_instance->base);
  1071. real_t first_radius = 0.0;
  1072. real_t min_distance_bias_scale = pancake_size > 0 ? distances[1] / 10.0 : 0;
  1073. for (int i = 0; i < splits; i++) {
  1074. RENDER_TIMESTAMP("Culling Directional Light split" + itos(i));
  1075. // setup a camera matrix for that range!
  1076. CameraMatrix camera_matrix;
  1077. real_t aspect = p_cam_projection.get_aspect();
  1078. if (p_cam_orthogonal) {
  1079. Vector2 vp_he = p_cam_projection.get_viewport_half_extents();
  1080. camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1081. } else {
  1082. real_t fov = p_cam_projection.get_fov(); //this is actually yfov, because set aspect tries to keep it
  1083. camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1084. }
  1085. //obtain the frustum endpoints
  1086. Vector3 endpoints[8]; // frustum plane endpoints
  1087. bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
  1088. ERR_CONTINUE(!res);
  1089. // obtain the light frustm ranges (given endpoints)
  1090. Transform transform = light_transform; //discard scale and stabilize light
  1091. Vector3 x_vec = transform.basis.get_axis(Vector3::AXIS_X).normalized();
  1092. Vector3 y_vec = transform.basis.get_axis(Vector3::AXIS_Y).normalized();
  1093. Vector3 z_vec = transform.basis.get_axis(Vector3::AXIS_Z).normalized();
  1094. //z_vec points agsint the camera, like in default opengl
  1095. real_t x_min = 0.f, x_max = 0.f;
  1096. real_t y_min = 0.f, y_max = 0.f;
  1097. real_t z_min = 0.f, z_max = 0.f;
  1098. // FIXME: z_max_cam is defined, computed, but not used below when setting up
  1099. // ortho_camera. Commented out for now to fix warnings but should be investigated.
  1100. real_t x_min_cam = 0.f, x_max_cam = 0.f;
  1101. real_t y_min_cam = 0.f, y_max_cam = 0.f;
  1102. real_t z_min_cam = 0.f;
  1103. //real_t z_max_cam = 0.f;
  1104. real_t bias_scale = 1.0;
  1105. real_t aspect_bias_scale = 1.0;
  1106. //used for culling
  1107. for (int j = 0; j < 8; j++) {
  1108. real_t d_x = x_vec.dot(endpoints[j]);
  1109. real_t d_y = y_vec.dot(endpoints[j]);
  1110. real_t d_z = z_vec.dot(endpoints[j]);
  1111. if (j == 0 || d_x < x_min) {
  1112. x_min = d_x;
  1113. }
  1114. if (j == 0 || d_x > x_max) {
  1115. x_max = d_x;
  1116. }
  1117. if (j == 0 || d_y < y_min) {
  1118. y_min = d_y;
  1119. }
  1120. if (j == 0 || d_y > y_max) {
  1121. y_max = d_y;
  1122. }
  1123. if (j == 0 || d_z < z_min) {
  1124. z_min = d_z;
  1125. }
  1126. if (j == 0 || d_z > z_max) {
  1127. z_max = d_z;
  1128. }
  1129. }
  1130. real_t radius = 0;
  1131. real_t soft_shadow_expand = 0;
  1132. Vector3 center;
  1133. {
  1134. //camera viewport stuff
  1135. for (int j = 0; j < 8; j++) {
  1136. center += endpoints[j];
  1137. }
  1138. center /= 8.0;
  1139. //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;
  1140. for (int j = 0; j < 8; j++) {
  1141. real_t d = center.distance_to(endpoints[j]);
  1142. if (d > radius) {
  1143. radius = d;
  1144. }
  1145. }
  1146. radius *= texture_size / (texture_size - 2.0); //add a texel by each side
  1147. if (i == 0) {
  1148. first_radius = radius;
  1149. } else {
  1150. bias_scale = radius / first_radius;
  1151. }
  1152. z_min_cam = z_vec.dot(center) - radius;
  1153. {
  1154. float soft_shadow_angle = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE);
  1155. if (soft_shadow_angle > 0.0 && pancake_size > 0.0) {
  1156. float z_range = (z_vec.dot(center) + radius + pancake_size) - z_min_cam;
  1157. soft_shadow_expand = Math::tan(Math::deg2rad(soft_shadow_angle)) * z_range;
  1158. x_max += soft_shadow_expand;
  1159. y_max += soft_shadow_expand;
  1160. x_min -= soft_shadow_expand;
  1161. y_min -= soft_shadow_expand;
  1162. }
  1163. }
  1164. x_max_cam = x_vec.dot(center) + radius + soft_shadow_expand;
  1165. x_min_cam = x_vec.dot(center) - radius - soft_shadow_expand;
  1166. y_max_cam = y_vec.dot(center) + radius + soft_shadow_expand;
  1167. y_min_cam = y_vec.dot(center) - radius - soft_shadow_expand;
  1168. if (depth_range_mode == RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE) {
  1169. //this trick here is what stabilizes the shadow (make potential jaggies to not move)
  1170. //at the cost of some wasted resolution. Still the quality increase is very well worth it
  1171. real_t unit = radius * 2.0 / texture_size;
  1172. x_max_cam = Math::stepify(x_max_cam, unit);
  1173. x_min_cam = Math::stepify(x_min_cam, unit);
  1174. y_max_cam = Math::stepify(y_max_cam, unit);
  1175. y_min_cam = Math::stepify(y_min_cam, unit);
  1176. }
  1177. }
  1178. //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree
  1179. Vector<Plane> light_frustum_planes;
  1180. light_frustum_planes.resize(6);
  1181. //right/left
  1182. light_frustum_planes.write[0] = Plane(x_vec, x_max);
  1183. light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
  1184. //top/bottom
  1185. light_frustum_planes.write[2] = Plane(y_vec, y_max);
  1186. light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
  1187. //near/far
  1188. light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
  1189. light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
  1190. int cull_count = p_scenario->octree.cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1191. // a pre pass will need to be needed to determine the actual z-near to be used
  1192. Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
  1193. real_t cull_max = 0;
  1194. for (int j = 0; j < cull_count; j++) {
  1195. real_t min, max;
  1196. Instance *instance = instance_shadow_cull_result[j];
  1197. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1198. cull_count--;
  1199. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1200. j--;
  1201. continue;
  1202. }
  1203. instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max);
  1204. instance->depth = near_plane.distance_to(instance->transform.origin);
  1205. instance->depth_layer = 0;
  1206. if (j == 0 || max > cull_max) {
  1207. cull_max = max;
  1208. }
  1209. }
  1210. if (cull_max > z_max) {
  1211. z_max = cull_max;
  1212. }
  1213. if (pancake_size > 0) {
  1214. z_max = z_vec.dot(center) + radius + pancake_size;
  1215. }
  1216. if (aspect != 1.0) {
  1217. // if the aspect is different, then the radius will become larger.
  1218. // if this happens, then bias needs to be adjusted too, as depth will increase
  1219. // to do this, compare the depth of one that would have resulted from a square frustum
  1220. CameraMatrix camera_matrix_square;
  1221. if (p_cam_orthogonal) {
  1222. Vector2 vp_he = camera_matrix.get_viewport_half_extents();
  1223. if (p_cam_vaspect) {
  1224. camera_matrix_square.set_orthogonal(vp_he.x * 2.0, 1.0, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1225. } else {
  1226. camera_matrix_square.set_orthogonal(vp_he.y * 2.0, 1.0, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1227. }
  1228. } else {
  1229. Vector2 vp_he = camera_matrix.get_viewport_half_extents();
  1230. if (p_cam_vaspect) {
  1231. camera_matrix_square.set_frustum(vp_he.x * 2.0, 1.0, Vector2(), distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1232. } else {
  1233. camera_matrix_square.set_frustum(vp_he.y * 2.0, 1.0, Vector2(), distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1234. }
  1235. }
  1236. Vector3 endpoints_square[8]; // frustum plane endpoints
  1237. res = camera_matrix_square.get_endpoints(p_cam_transform, endpoints_square);
  1238. ERR_CONTINUE(!res);
  1239. Vector3 center_square;
  1240. real_t z_max_square = 0;
  1241. for (int j = 0; j < 8; j++) {
  1242. center_square += endpoints_square[j];
  1243. real_t d_z = z_vec.dot(endpoints_square[j]);
  1244. if (j == 0 || d_z > z_max_square) {
  1245. z_max_square = d_z;
  1246. }
  1247. }
  1248. if (cull_max > z_max_square) {
  1249. z_max_square = cull_max;
  1250. }
  1251. center_square /= 8.0;
  1252. real_t radius_square = 0;
  1253. for (int j = 0; j < 8; j++) {
  1254. real_t d = center_square.distance_to(endpoints_square[j]);
  1255. if (d > radius_square) {
  1256. radius_square = d;
  1257. }
  1258. }
  1259. radius_square *= texture_size / (texture_size - 2.0); //add a texel by each side
  1260. if (pancake_size > 0) {
  1261. z_max_square = z_vec.dot(center_square) + radius_square + pancake_size;
  1262. }
  1263. real_t z_min_cam_square = z_vec.dot(center_square) - radius_square;
  1264. aspect_bias_scale = (z_max - z_min_cam) / (z_max_square - z_min_cam_square);
  1265. // this is not entirely perfect, because the cull-adjusted z-max may be different
  1266. // but at least it's warranted that it results in a greater bias, so no acne should be present either way.
  1267. // pancaking also helps with this.
  1268. }
  1269. {
  1270. CameraMatrix ortho_camera;
  1271. real_t half_x = (x_max_cam - x_min_cam) * 0.5;
  1272. real_t half_y = (y_max_cam - y_min_cam) * 0.5;
  1273. ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
  1274. Vector2 uv_scale(1.0 / (x_max_cam - x_min_cam), 1.0 / (y_max_cam - y_min_cam));
  1275. Transform ortho_transform;
  1276. ortho_transform.basis = transform.basis;
  1277. ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
  1278. {
  1279. Vector3 max_in_view = p_cam_transform.affine_inverse().xform(z_vec * cull_max);
  1280. Vector3 dir_in_view = p_cam_transform.xform_inv(z_vec).normalized();
  1281. cull_max = dir_in_view.dot(max_in_view);
  1282. }
  1283. RSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, z_max - z_min_cam, distances[i + 1], i, radius * 2.0 / texture_size, bias_scale * aspect_bias_scale * min_distance_bias_scale, z_max, uv_scale);
  1284. }
  1285. RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1286. }
  1287. } break;
  1288. case RS::LIGHT_OMNI: {
  1289. RS::LightOmniShadowMode shadow_mode = RSG::storage->light_omni_get_shadow_mode(p_instance->base);
  1290. if (shadow_mode == RS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !RSG::scene_render->light_instances_can_render_shadow_cube()) {
  1291. for (int i = 0; i < 2; i++) {
  1292. //using this one ensures that raster deferred will have it
  1293. RENDER_TIMESTAMP("Culling Shadow Paraboloid" + itos(i));
  1294. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1295. real_t z = i == 0 ? -1 : 1;
  1296. Vector<Plane> planes;
  1297. planes.resize(6);
  1298. planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
  1299. planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
  1300. planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
  1301. planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
  1302. planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
  1303. planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
  1304. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1305. Plane near_plane(light_transform.origin, light_transform.basis.get_axis(2) * z);
  1306. for (int j = 0; j < cull_count; j++) {
  1307. Instance *instance = instance_shadow_cull_result[j];
  1308. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1309. cull_count--;
  1310. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1311. j--;
  1312. } else {
  1313. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1314. animated_material_found = true;
  1315. }
  1316. instance->depth = near_plane.distance_to(instance->transform.origin);
  1317. instance->depth_layer = 0;
  1318. }
  1319. }
  1320. RSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, i, 0);
  1321. RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1322. }
  1323. } else { //shadow cube
  1324. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1325. CameraMatrix cm;
  1326. cm.set_perspective(90, 1, 0.01, radius);
  1327. for (int i = 0; i < 6; i++) {
  1328. RENDER_TIMESTAMP("Culling Shadow Cube side" + itos(i));
  1329. //using this one ensures that raster deferred will have it
  1330. static const Vector3 view_normals[6] = {
  1331. Vector3(+1, 0, 0),
  1332. Vector3(-1, 0, 0),
  1333. Vector3(0, -1, 0),
  1334. Vector3(0, +1, 0),
  1335. Vector3(0, 0, +1),
  1336. Vector3(0, 0, -1)
  1337. };
  1338. static const Vector3 view_up[6] = {
  1339. Vector3(0, -1, 0),
  1340. Vector3(0, -1, 0),
  1341. Vector3(0, 0, -1),
  1342. Vector3(0, 0, +1),
  1343. Vector3(0, -1, 0),
  1344. Vector3(0, -1, 0)
  1345. };
  1346. Transform xform = light_transform * Transform().looking_at(view_normals[i], view_up[i]);
  1347. Vector<Plane> planes = cm.get_projection_planes(xform);
  1348. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1349. Plane near_plane(xform.origin, -xform.basis.get_axis(2));
  1350. for (int j = 0; j < cull_count; j++) {
  1351. Instance *instance = instance_shadow_cull_result[j];
  1352. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1353. cull_count--;
  1354. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1355. j--;
  1356. } else {
  1357. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1358. animated_material_found = true;
  1359. }
  1360. instance->depth = near_plane.distance_to(instance->transform.origin);
  1361. instance->depth_layer = 0;
  1362. }
  1363. }
  1364. RSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i, 0);
  1365. RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1366. }
  1367. //restore the regular DP matrix
  1368. RSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, 0, 0);
  1369. }
  1370. } break;
  1371. case RS::LIGHT_SPOT: {
  1372. RENDER_TIMESTAMP("Culling Spot Light");
  1373. real_t radius = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1374. real_t angle = RSG::storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1375. CameraMatrix cm;
  1376. cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);
  1377. Vector<Plane> planes = cm.get_projection_planes(light_transform);
  1378. int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, RS::INSTANCE_GEOMETRY_MASK);
  1379. Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
  1380. for (int j = 0; j < cull_count; j++) {
  1381. Instance *instance = instance_shadow_cull_result[j];
  1382. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
  1383. cull_count--;
  1384. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
  1385. j--;
  1386. } else {
  1387. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1388. animated_material_found = true;
  1389. }
  1390. instance->depth = near_plane.distance_to(instance->transform.origin);
  1391. instance->depth_layer = 0;
  1392. }
  1393. }
  1394. RSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0, 0);
  1395. RSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
  1396. } break;
  1397. }
  1398. return animated_material_found;
  1399. }
  1400. void RenderingServerScene::render_camera(RID p_render_buffers, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  1401. // render to mono camera
  1402. #ifndef _3D_DISABLED
  1403. Camera *camera = camera_owner.getornull(p_camera);
  1404. ERR_FAIL_COND(!camera);
  1405. /* STEP 1 - SETUP CAMERA */
  1406. CameraMatrix camera_matrix;
  1407. bool ortho = false;
  1408. switch (camera->type) {
  1409. case Camera::ORTHOGONAL: {
  1410. camera_matrix.set_orthogonal(
  1411. camera->size,
  1412. p_viewport_size.width / (float)p_viewport_size.height,
  1413. camera->znear,
  1414. camera->zfar,
  1415. camera->vaspect);
  1416. ortho = true;
  1417. } break;
  1418. case Camera::PERSPECTIVE: {
  1419. camera_matrix.set_perspective(
  1420. camera->fov,
  1421. p_viewport_size.width / (float)p_viewport_size.height,
  1422. camera->znear,
  1423. camera->zfar,
  1424. camera->vaspect);
  1425. ortho = false;
  1426. } break;
  1427. case Camera::FRUSTUM: {
  1428. camera_matrix.set_frustum(
  1429. camera->size,
  1430. p_viewport_size.width / (float)p_viewport_size.height,
  1431. camera->offset,
  1432. camera->znear,
  1433. camera->zfar,
  1434. camera->vaspect);
  1435. ortho = false;
  1436. } break;
  1437. }
  1438. RID environment = _render_get_environment(p_camera, p_scenario);
  1439. _prepare_scene(camera->transform, camera_matrix, ortho, camera->vaspect, p_render_buffers, environment, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
  1440. _render_scene(p_render_buffers, camera->transform, camera_matrix, ortho, environment, camera->effects, p_scenario, p_shadow_atlas, RID(), -1);
  1441. #endif
  1442. }
  1443. void RenderingServerScene::render_camera(RID p_render_buffers, Ref<XRInterface> &p_interface, XRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
  1444. // render for AR/VR interface
  1445. Camera *camera = camera_owner.getornull(p_camera);
  1446. ERR_FAIL_COND(!camera);
  1447. /* SETUP CAMERA, we are ignoring type and FOV here */
  1448. float aspect = p_viewport_size.width / (float)p_viewport_size.height;
  1449. CameraMatrix camera_matrix = p_interface->get_projection_for_eye(p_eye, aspect, camera->znear, camera->zfar);
  1450. // We also ignore our camera position, it will have been positioned with a slightly old tracking position.
  1451. // Instead we take our origin point and have our ar/vr interface add fresh tracking data! Whoohoo!
  1452. Transform world_origin = XRServer::get_singleton()->get_world_origin();
  1453. Transform cam_transform = p_interface->get_transform_for_eye(p_eye, world_origin);
  1454. RID environment = _render_get_environment(p_camera, p_scenario);
  1455. // For stereo render we only prepare for our left eye and then reuse the outcome for our right eye
  1456. if (p_eye == XRInterface::EYE_LEFT) {
  1457. // Center our transform, we assume basis is equal.
  1458. Transform mono_transform = cam_transform;
  1459. Transform right_transform = p_interface->get_transform_for_eye(XRInterface::EYE_RIGHT, world_origin);
  1460. mono_transform.origin += right_transform.origin;
  1461. mono_transform.origin *= 0.5;
  1462. // We need to combine our projection frustums for culling.
  1463. // Ideally we should use our clipping planes for this and combine them,
  1464. // however our shadow map logic uses our projection matrix.
  1465. // Note: as our left and right frustums should be mirrored, we don't need our right projection matrix.
  1466. // - get some base values we need
  1467. float eye_dist = (mono_transform.origin - cam_transform.origin).length();
  1468. float z_near = camera_matrix.get_z_near(); // get our near plane
  1469. float z_far = camera_matrix.get_z_far(); // get our far plane
  1470. float width = (2.0 * z_near) / camera_matrix.matrix[0][0];
  1471. float x_shift = width * camera_matrix.matrix[2][0];
  1472. float height = (2.0 * z_near) / camera_matrix.matrix[1][1];
  1473. float y_shift = height * camera_matrix.matrix[2][1];
  1474. // printf("Eye_dist = %f, Near = %f, Far = %f, Width = %f, Shift = %f\n", eye_dist, z_near, z_far, width, x_shift);
  1475. // - calculate our near plane size (horizontal only, right_near is mirrored)
  1476. float left_near = -eye_dist - ((width - x_shift) * 0.5);
  1477. // - calculate our far plane size (horizontal only, right_far is mirrored)
  1478. float left_far = -eye_dist - (z_far * (width - x_shift) * 0.5 / z_near);
  1479. float left_far_right_eye = eye_dist - (z_far * (width + x_shift) * 0.5 / z_near);
  1480. if (left_far > left_far_right_eye) {
  1481. // on displays smaller then double our iod, the right eye far frustrum can overtake the left eyes.
  1482. left_far = left_far_right_eye;
  1483. }
  1484. // - figure out required z-shift
  1485. float slope = (left_far - left_near) / (z_far - z_near);
  1486. float z_shift = (left_near / slope) - z_near;
  1487. // - figure out new vertical near plane size (this will be slightly oversized thanks to our z-shift)
  1488. float top_near = (height - y_shift) * 0.5;
  1489. top_near += (top_near / z_near) * z_shift;
  1490. float bottom_near = -(height + y_shift) * 0.5;
  1491. bottom_near += (bottom_near / z_near) * z_shift;
  1492. // 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);
  1493. // - generate our frustum
  1494. CameraMatrix combined_matrix;
  1495. combined_matrix.set_frustum(left_near, -left_near, bottom_near, top_near, z_near + z_shift, z_far + z_shift);
  1496. // and finally move our camera back
  1497. Transform apply_z_shift;
  1498. apply_z_shift.origin = Vector3(0.0, 0.0, z_shift); // z negative is forward so this moves it backwards
  1499. mono_transform *= apply_z_shift;
  1500. // now prepare our scene with our adjusted transform projection matrix
  1501. _prepare_scene(mono_transform, combined_matrix, false, false, p_render_buffers, environment, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
  1502. } else if (p_eye == XRInterface::EYE_MONO) {
  1503. // For mono render, prepare as per usual
  1504. _prepare_scene(cam_transform, camera_matrix, false, false, p_render_buffers, environment, camera->visible_layers, p_scenario, p_shadow_atlas, RID());
  1505. }
  1506. // And render our scene...
  1507. _render_scene(p_render_buffers, cam_transform, camera_matrix, false, environment, camera->effects, p_scenario, p_shadow_atlas, RID(), -1);
  1508. };
  1509. void RenderingServerScene::_prepare_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_render_buffers, RID p_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, bool p_using_shadows) {
  1510. // Note, in stereo rendering:
  1511. // - p_cam_transform will be a transform in the middle of our two eyes
  1512. // - p_cam_projection is a wider frustrum that encompasses both eyes
  1513. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1514. render_pass++;
  1515. uint32_t camera_layer_mask = p_visible_layers;
  1516. RSG::scene_render->set_scene_pass(render_pass);
  1517. if (p_render_buffers.is_valid()) {
  1518. RSG::scene_render->sdfgi_update(p_render_buffers, p_environment, p_cam_transform.origin); //update conditions for SDFGI (whether its used or not)
  1519. }
  1520. RENDER_TIMESTAMP("Frustum Culling");
  1521. //rasterizer->set_camera(camera->transform, camera_matrix,ortho);
  1522. Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
  1523. Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
  1524. float z_far = p_cam_projection.get_z_far();
  1525. /* STEP 2 - CULL */
  1526. instance_cull_count = scenario->octree.cull_convex(planes, instance_cull_result, MAX_INSTANCE_CULL);
  1527. light_cull_count = 0;
  1528. reflection_probe_cull_count = 0;
  1529. decal_cull_count = 0;
  1530. gi_probe_cull_count = 0;
  1531. lightmap_cull_count = 0;
  1532. //light_samplers_culled=0;
  1533. /*
  1534. print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0));
  1535. print_line("OTO: "+itos(p_scenario->octree.get_octant_count()));
  1536. print_line("OTE: "+itos(p_scenario->octree.get_elem_count()));
  1537. print_line("OTP: "+itos(p_scenario->octree.get_pair_count()));
  1538. */
  1539. /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
  1540. //removed, will replace with culling
  1541. /* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */
  1542. uint64_t frame_number = RSG::rasterizer->get_frame_number();
  1543. float lightmap_probe_update_speed = RSG::storage->lightmap_get_probe_capture_update_speed() * RSG::rasterizer->get_frame_delta_time();
  1544. for (int i = 0; i < instance_cull_count; i++) {
  1545. Instance *ins = instance_cull_result[i];
  1546. bool keep = false;
  1547. if ((camera_layer_mask & ins->layer_mask) == 0) {
  1548. //failure
  1549. } else if (ins->base_type == RS::INSTANCE_LIGHT && ins->visible) {
  1550. if (light_cull_count < MAX_LIGHTS_CULLED) {
  1551. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  1552. if (!light->geometries.empty()) {
  1553. //do not add this light if no geometry is affected by it..
  1554. light_cull_result[light_cull_count] = ins;
  1555. light_instance_cull_result[light_cull_count] = light->instance;
  1556. if (p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(ins->base)) {
  1557. RSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later
  1558. }
  1559. light_cull_count++;
  1560. }
  1561. }
  1562. } else if (ins->base_type == RS::INSTANCE_REFLECTION_PROBE && ins->visible) {
  1563. if (reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) {
  1564. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data);
  1565. if (p_reflection_probe != reflection_probe->instance) {
  1566. //avoid entering The Matrix
  1567. if (!reflection_probe->geometries.empty()) {
  1568. //do not add this light if no geometry is affected by it..
  1569. if (reflection_probe->reflection_dirty || RSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) {
  1570. if (!reflection_probe->update_list.in_list()) {
  1571. reflection_probe->render_step = 0;
  1572. reflection_probe_render_list.add_last(&reflection_probe->update_list);
  1573. }
  1574. reflection_probe->reflection_dirty = false;
  1575. }
  1576. if (RSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) {
  1577. reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance;
  1578. reflection_probe_cull_count++;
  1579. }
  1580. }
  1581. }
  1582. }
  1583. } else if (ins->base_type == RS::INSTANCE_DECAL && ins->visible) {
  1584. if (decal_cull_count < MAX_DECALS_CULLED) {
  1585. InstanceDecalData *decal = static_cast<InstanceDecalData *>(ins->base_data);
  1586. if (!decal->geometries.empty()) {
  1587. //do not add this decal if no geometry is affected by it..
  1588. decal_instance_cull_result[decal_cull_count] = decal->instance;
  1589. decal_cull_count++;
  1590. }
  1591. }
  1592. } else if (ins->base_type == RS::INSTANCE_GI_PROBE && ins->visible) {
  1593. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data);
  1594. if (!gi_probe->update_element.in_list()) {
  1595. gi_probe_update_list.add(&gi_probe->update_element);
  1596. }
  1597. if (gi_probe_cull_count < MAX_GI_PROBES_CULLED) {
  1598. gi_probe_instance_cull_result[gi_probe_cull_count] = gi_probe->probe_instance;
  1599. gi_probe_cull_count++;
  1600. }
  1601. } else if (ins->base_type == RS::INSTANCE_LIGHTMAP && ins->visible) {
  1602. if (lightmap_cull_count < MAX_LIGHTMAPS_CULLED) {
  1603. lightmap_cull_result[lightmap_cull_count] = ins;
  1604. lightmap_cull_count++;
  1605. }
  1606. } else if (((1 << ins->base_type) & RS::INSTANCE_GEOMETRY_MASK) && ins->visible && ins->cast_shadows != RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  1607. keep = true;
  1608. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data);
  1609. if (ins->redraw_if_visible) {
  1610. RenderingServerRaster::redraw_request();
  1611. }
  1612. if (ins->base_type == RS::INSTANCE_PARTICLES) {
  1613. //particles visible? process them
  1614. if (RSG::storage->particles_is_inactive(ins->base)) {
  1615. //but if nothing is going on, don't do it.
  1616. keep = false;
  1617. } else {
  1618. RSG::storage->particles_request_process(ins->base);
  1619. //particles visible? request redraw
  1620. RenderingServerRaster::redraw_request();
  1621. }
  1622. }
  1623. if (geom->lighting_dirty) {
  1624. int l = 0;
  1625. //only called when lights AABB enter/exit this geometry
  1626. ins->light_instances.resize(geom->lighting.size());
  1627. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  1628. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1629. ins->light_instances.write[l++] = light->instance;
  1630. }
  1631. geom->lighting_dirty = false;
  1632. }
  1633. if (geom->reflection_dirty) {
  1634. int l = 0;
  1635. //only called when reflection probe AABB enter/exit this geometry
  1636. ins->reflection_probe_instances.resize(geom->reflection_probes.size());
  1637. for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {
  1638. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
  1639. ins->reflection_probe_instances.write[l++] = reflection_probe->instance;
  1640. }
  1641. geom->reflection_dirty = false;
  1642. }
  1643. if (geom->gi_probes_dirty) {
  1644. int l = 0;
  1645. //only called when reflection probe AABB enter/exit this geometry
  1646. ins->gi_probe_instances.resize(geom->gi_probes.size());
  1647. for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {
  1648. InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);
  1649. ins->gi_probe_instances.write[l++] = gi_probe->probe_instance;
  1650. }
  1651. geom->gi_probes_dirty = false;
  1652. }
  1653. if (ins->last_frame_pass != frame_number && !ins->lightmap_target_sh.empty() && !ins->lightmap_sh.empty()) {
  1654. Color *sh = ins->lightmap_sh.ptrw();
  1655. const Color *target_sh = ins->lightmap_target_sh.ptr();
  1656. for (uint32_t j = 0; j < 9; j++) {
  1657. sh[j] = sh[j].lerp(target_sh[j], MIN(1.0, lightmap_probe_update_speed));
  1658. }
  1659. }
  1660. ins->depth = near_plane.distance_to(ins->transform.origin);
  1661. ins->depth_layer = CLAMP(int(ins->depth * 16 / z_far), 0, 15);
  1662. }
  1663. if (!keep) {
  1664. // remove, no reason to keep
  1665. instance_cull_count--;
  1666. SWAP(instance_cull_result[i], instance_cull_result[instance_cull_count]);
  1667. i--;
  1668. ins->last_render_pass = 0; // make invalid
  1669. } else {
  1670. ins->last_render_pass = render_pass;
  1671. }
  1672. ins->last_frame_pass = frame_number;
  1673. }
  1674. /* STEP 5 - PROCESS LIGHTS */
  1675. RID *directional_light_ptr = &light_instance_cull_result[light_cull_count];
  1676. directional_light_count = 0;
  1677. // directional lights
  1678. {
  1679. Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size());
  1680. int directional_shadow_count = 0;
  1681. for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {
  1682. if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) {
  1683. break;
  1684. }
  1685. if (!E->get()->visible) {
  1686. continue;
  1687. }
  1688. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  1689. //check shadow..
  1690. if (light) {
  1691. if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::storage->light_has_shadow(E->get()->base)) {
  1692. lights_with_shadow[directional_shadow_count++] = E->get();
  1693. }
  1694. //add to list
  1695. directional_light_ptr[directional_light_count++] = light->instance;
  1696. }
  1697. }
  1698. RSG::scene_render->set_directional_shadow_count(directional_shadow_count);
  1699. for (int i = 0; i < directional_shadow_count; i++) {
  1700. RENDER_TIMESTAMP(">Rendering Directional Light " + itos(i));
  1701. _light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_cam_vaspect, p_shadow_atlas, scenario);
  1702. RENDER_TIMESTAMP("<Rendering Directional Light " + itos(i));
  1703. }
  1704. }
  1705. if (p_using_shadows) { //setup shadow maps
  1706. //SortArray<Instance*,_InstanceLightsort> sorter;
  1707. //sorter.sort(light_cull_result,light_cull_count);
  1708. for (int i = 0; i < light_cull_count; i++) {
  1709. Instance *ins = light_cull_result[i];
  1710. if (!p_shadow_atlas.is_valid() || !RSG::storage->light_has_shadow(ins->base)) {
  1711. continue;
  1712. }
  1713. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  1714. float coverage = 0.f;
  1715. { //compute coverage
  1716. Transform cam_xf = p_cam_transform;
  1717. float zn = p_cam_projection.get_z_near();
  1718. Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane
  1719. // near plane half width and height
  1720. Vector2 vp_half_extents = p_cam_projection.get_viewport_half_extents();
  1721. switch (RSG::storage->light_get_type(ins->base)) {
  1722. case RS::LIGHT_OMNI: {
  1723. float radius = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  1724. //get two points parallel to near plane
  1725. Vector3 points[2] = {
  1726. ins->transform.origin,
  1727. ins->transform.origin + cam_xf.basis.get_axis(0) * radius
  1728. };
  1729. if (!p_cam_orthogonal) {
  1730. //if using perspetive, map them to near plane
  1731. for (int j = 0; j < 2; j++) {
  1732. if (p.distance_to(points[j]) < 0) {
  1733. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  1734. }
  1735. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  1736. }
  1737. }
  1738. float screen_diameter = points[0].distance_to(points[1]) * 2;
  1739. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  1740. } break;
  1741. case RS::LIGHT_SPOT: {
  1742. float radius = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  1743. float angle = RSG::storage->light_get_param(ins->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  1744. float w = radius * Math::sin(Math::deg2rad(angle));
  1745. float d = radius * Math::cos(Math::deg2rad(angle));
  1746. Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;
  1747. Vector3 points[2] = {
  1748. base,
  1749. base + cam_xf.basis.get_axis(0) * w
  1750. };
  1751. if (!p_cam_orthogonal) {
  1752. //if using perspetive, map them to near plane
  1753. for (int j = 0; j < 2; j++) {
  1754. if (p.distance_to(points[j]) < 0) {
  1755. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  1756. }
  1757. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  1758. }
  1759. }
  1760. float screen_diameter = points[0].distance_to(points[1]) * 2;
  1761. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  1762. } break;
  1763. default: {
  1764. ERR_PRINT("Invalid Light Type");
  1765. }
  1766. }
  1767. }
  1768. if (light->shadow_dirty) {
  1769. light->last_version++;
  1770. light->shadow_dirty = false;
  1771. }
  1772. bool redraw = RSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
  1773. if (redraw) {
  1774. //must redraw!
  1775. RENDER_TIMESTAMP(">Rendering Light " + itos(i));
  1776. light->shadow_dirty = _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_cam_vaspect, p_shadow_atlas, scenario);
  1777. RENDER_TIMESTAMP("<Rendering Light " + itos(i));
  1778. }
  1779. }
  1780. }
  1781. /* UPDATE SDFGI */
  1782. if (p_render_buffers.is_valid()) {
  1783. uint32_t cascade_index[8];
  1784. uint32_t cascade_sizes[8];
  1785. const RID *cascade_ptrs[8];
  1786. uint32_t cascade_count = 0;
  1787. uint32_t sdfgi_light_cull_count = 0;
  1788. uint32_t prev_cascade = 0xFFFFFFFF;
  1789. for (int i = 0; i < RSG::scene_render->sdfgi_get_pending_region_count(p_render_buffers); i++) {
  1790. AABB region = RSG::scene_render->sdfgi_get_pending_region_bounds(p_render_buffers, i);
  1791. uint32_t region_cascade = RSG::scene_render->sdfgi_get_pending_region_cascade(p_render_buffers, i);
  1792. if (region_cascade != prev_cascade) {
  1793. cascade_sizes[cascade_count] = 0;
  1794. cascade_index[cascade_count] = region_cascade;
  1795. cascade_ptrs[cascade_count] = &sdfgi_light_cull_result[sdfgi_light_cull_count];
  1796. cascade_count++;
  1797. sdfgi_light_cull_pass++;
  1798. prev_cascade = region_cascade;
  1799. }
  1800. uint32_t sdfgi_cull_count = scenario->octree.cull_aabb(region, instance_shadow_cull_result, MAX_INSTANCE_CULL);
  1801. for (uint32_t j = 0; j < sdfgi_cull_count; j++) {
  1802. Instance *ins = instance_shadow_cull_result[j];
  1803. bool keep = false;
  1804. if (ins->base_type == RS::INSTANCE_LIGHT && ins->visible) {
  1805. InstanceLightData *instance_light = (InstanceLightData *)ins->base_data;
  1806. if (instance_light->bake_mode != RS::LIGHT_BAKE_STATIC || region_cascade > instance_light->max_sdfgi_cascade) {
  1807. continue;
  1808. }
  1809. if (sdfgi_light_cull_pass != instance_light->sdfgi_cascade_light_pass && sdfgi_light_cull_count < MAX_LIGHTS_CULLED) {
  1810. instance_light->sdfgi_cascade_light_pass = sdfgi_light_cull_pass;
  1811. sdfgi_light_cull_result[sdfgi_light_cull_count++] = instance_light->instance;
  1812. cascade_sizes[cascade_count - 1]++;
  1813. }
  1814. } else if ((1 << ins->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1815. if (ins->baked_light) {
  1816. keep = true;
  1817. }
  1818. }
  1819. if (!keep) {
  1820. // remove, no reason to keep
  1821. sdfgi_cull_count--;
  1822. SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[sdfgi_cull_count]);
  1823. j--;
  1824. }
  1825. }
  1826. RSG::scene_render->render_sdfgi(p_render_buffers, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, sdfgi_cull_count);
  1827. //have to save updated cascades, then update static lights.
  1828. }
  1829. if (sdfgi_light_cull_count) {
  1830. RSG::scene_render->render_sdfgi_static_lights(p_render_buffers, cascade_count, cascade_index, cascade_ptrs, cascade_sizes);
  1831. }
  1832. RSG::scene_render->sdfgi_update_probes(p_render_buffers, p_environment, directional_light_ptr, directional_light_count, scenario->dynamic_lights.ptr(), scenario->dynamic_lights.size());
  1833. }
  1834. }
  1835. RID RenderingServerScene::_render_get_environment(RID p_camera, RID p_scenario) {
  1836. Camera *camera = camera_owner.getornull(p_camera);
  1837. if (camera && RSG::scene_render->is_environment(camera->env)) {
  1838. return camera->env;
  1839. }
  1840. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1841. if (!scenario) {
  1842. return RID();
  1843. }
  1844. if (RSG::scene_render->is_environment(scenario->environment)) {
  1845. return scenario->environment;
  1846. }
  1847. if (RSG::scene_render->is_environment(scenario->fallback_environment)) {
  1848. return scenario->fallback_environment;
  1849. }
  1850. return RID();
  1851. }
  1852. void RenderingServerScene::_render_scene(RID p_render_buffers, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_environment, RID p_force_camera_effects, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
  1853. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1854. RID camera_effects;
  1855. if (p_force_camera_effects.is_valid()) {
  1856. camera_effects = p_force_camera_effects;
  1857. } else {
  1858. camera_effects = scenario->camera_effects;
  1859. }
  1860. /* PROCESS GEOMETRY AND DRAW SCENE */
  1861. RENDER_TIMESTAMP("Render Scene ");
  1862. RSG::scene_render->render_scene(p_render_buffers, 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, gi_probe_instance_cull_result, gi_probe_cull_count, decal_instance_cull_result, decal_cull_count, (RasterizerScene::InstanceBase **)lightmap_cull_result, lightmap_cull_count, p_environment, camera_effects, p_shadow_atlas, p_reflection_probe.is_valid() ? RID() : scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass);
  1863. }
  1864. void RenderingServerScene::render_empty_scene(RID p_render_buffers, RID p_scenario, RID p_shadow_atlas) {
  1865. #ifndef _3D_DISABLED
  1866. Scenario *scenario = scenario_owner.getornull(p_scenario);
  1867. RID environment;
  1868. if (scenario->environment.is_valid()) {
  1869. environment = scenario->environment;
  1870. } else {
  1871. environment = scenario->fallback_environment;
  1872. }
  1873. RENDER_TIMESTAMP("Render Empty Scene ");
  1874. RSG::scene_render->render_scene(p_render_buffers, Transform(), CameraMatrix(), true, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, environment, RID(), p_shadow_atlas, scenario->reflection_atlas, RID(), 0);
  1875. #endif
  1876. }
  1877. bool RenderingServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) {
  1878. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  1879. Scenario *scenario = p_instance->scenario;
  1880. ERR_FAIL_COND_V(!scenario, true);
  1881. RenderingServerRaster::redraw_request(); //update, so it updates in editor
  1882. if (p_step == 0) {
  1883. if (!RSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
  1884. return true; //all full
  1885. }
  1886. }
  1887. if (p_step >= 0 && p_step < 6) {
  1888. static const Vector3 view_normals[6] = {
  1889. Vector3(+1, 0, 0),
  1890. Vector3(-1, 0, 0),
  1891. Vector3(0, +1, 0),
  1892. Vector3(0, -1, 0),
  1893. Vector3(0, 0, +1),
  1894. Vector3(0, 0, -1)
  1895. };
  1896. static const Vector3 view_up[6] = {
  1897. Vector3(0, -1, 0),
  1898. Vector3(0, -1, 0),
  1899. Vector3(0, 0, +1),
  1900. Vector3(0, 0, -1),
  1901. Vector3(0, -1, 0),
  1902. Vector3(0, -1, 0)
  1903. };
  1904. Vector3 extents = RSG::storage->reflection_probe_get_extents(p_instance->base);
  1905. Vector3 origin_offset = RSG::storage->reflection_probe_get_origin_offset(p_instance->base);
  1906. float max_distance = RSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);
  1907. Vector3 edge = view_normals[p_step] * extents;
  1908. 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
  1909. max_distance = MAX(max_distance, distance);
  1910. //render cubemap side
  1911. CameraMatrix cm;
  1912. cm.set_perspective(90, 1, 0.01, max_distance);
  1913. Transform local_view;
  1914. local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
  1915. Transform xform = p_instance->transform * local_view;
  1916. RID shadow_atlas;
  1917. bool use_shadows = RSG::storage->reflection_probe_renders_shadows(p_instance->base);
  1918. if (use_shadows) {
  1919. shadow_atlas = scenario->reflection_probe_shadow_atlas;
  1920. }
  1921. RENDER_TIMESTAMP("Render Reflection Probe, Step " + itos(p_step));
  1922. _prepare_scene(xform, cm, false, false, RID(), RID(), RSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, use_shadows);
  1923. _render_scene(RID(), xform, cm, false, RID(), RID(), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step);
  1924. } else {
  1925. //do roughness postprocess step until it believes it's done
  1926. RENDER_TIMESTAMP("Post-Process Reflection Probe, Step " + itos(p_step));
  1927. return RSG::scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance);
  1928. }
  1929. return false;
  1930. }
  1931. void RenderingServerScene::render_probes() {
  1932. /* REFLECTION PROBES */
  1933. SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
  1934. bool busy = false;
  1935. while (ref_probe) {
  1936. SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
  1937. RID base = ref_probe->self()->owner->base;
  1938. switch (RSG::storage->reflection_probe_get_update_mode(base)) {
  1939. case RS::REFLECTION_PROBE_UPDATE_ONCE: {
  1940. if (busy) { //already rendering something
  1941. break;
  1942. }
  1943. bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
  1944. if (done) {
  1945. reflection_probe_render_list.remove(ref_probe);
  1946. } else {
  1947. ref_probe->self()->render_step++;
  1948. }
  1949. busy = true; //do not render another one of this kind
  1950. } break;
  1951. case RS::REFLECTION_PROBE_UPDATE_ALWAYS: {
  1952. int step = 0;
  1953. bool done = false;
  1954. while (!done) {
  1955. done = _render_reflection_probe_step(ref_probe->self()->owner, step);
  1956. step++;
  1957. }
  1958. reflection_probe_render_list.remove(ref_probe);
  1959. } break;
  1960. }
  1961. ref_probe = next;
  1962. }
  1963. /* GI PROBES */
  1964. SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();
  1965. if (gi_probe) {
  1966. RENDER_TIMESTAMP("Render GI Probes");
  1967. }
  1968. while (gi_probe) {
  1969. SelfList<InstanceGIProbeData> *next = gi_probe->next();
  1970. InstanceGIProbeData *probe = gi_probe->self();
  1971. //Instance *instance_probe = probe->owner;
  1972. //check if probe must be setup, but don't do if on the lighting thread
  1973. bool cache_dirty = false;
  1974. int cache_count = 0;
  1975. {
  1976. int light_cache_size = probe->light_cache.size();
  1977. const InstanceGIProbeData::LightCache *caches = probe->light_cache.ptr();
  1978. const RID *instance_caches = probe->light_instances.ptr();
  1979. int idx = 0; //must count visible lights
  1980. for (Set<Instance *>::Element *E = probe->lights.front(); E; E = E->next()) {
  1981. Instance *instance = E->get();
  1982. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  1983. if (!instance->visible) {
  1984. continue;
  1985. }
  1986. if (cache_dirty) {
  1987. //do nothing, since idx must count all visible lights anyway
  1988. } else if (idx >= light_cache_size) {
  1989. cache_dirty = true;
  1990. } else {
  1991. const InstanceGIProbeData::LightCache *cache = &caches[idx];
  1992. if (
  1993. instance_caches[idx] != instance_light->instance ||
  1994. cache->has_shadow != RSG::storage->light_has_shadow(instance->base) ||
  1995. cache->type != RSG::storage->light_get_type(instance->base) ||
  1996. cache->transform != instance->transform ||
  1997. cache->color != RSG::storage->light_get_color(instance->base) ||
  1998. cache->energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  1999. cache->bake_energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  2000. cache->radius != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  2001. cache->attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  2002. cache->spot_angle != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  2003. cache->spot_attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
  2004. cache_dirty = true;
  2005. }
  2006. }
  2007. idx++;
  2008. }
  2009. for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) {
  2010. Instance *instance = E->get();
  2011. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2012. if (!instance->visible) {
  2013. continue;
  2014. }
  2015. if (cache_dirty) {
  2016. //do nothing, since idx must count all visible lights anyway
  2017. } else if (idx >= light_cache_size) {
  2018. cache_dirty = true;
  2019. } else {
  2020. const InstanceGIProbeData::LightCache *cache = &caches[idx];
  2021. if (
  2022. instance_caches[idx] != instance_light->instance ||
  2023. cache->has_shadow != RSG::storage->light_has_shadow(instance->base) ||
  2024. cache->type != RSG::storage->light_get_type(instance->base) ||
  2025. cache->transform != instance->transform ||
  2026. cache->color != RSG::storage->light_get_color(instance->base) ||
  2027. cache->energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  2028. cache->bake_energy != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  2029. cache->radius != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  2030. cache->attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  2031. cache->spot_angle != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  2032. cache->spot_attenuation != RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
  2033. cache_dirty = true;
  2034. }
  2035. }
  2036. idx++;
  2037. }
  2038. if (idx != light_cache_size) {
  2039. cache_dirty = true;
  2040. }
  2041. cache_count = idx;
  2042. }
  2043. bool update_lights = RSG::scene_render->gi_probe_needs_update(probe->probe_instance);
  2044. if (cache_dirty) {
  2045. probe->light_cache.resize(cache_count);
  2046. probe->light_instances.resize(cache_count);
  2047. if (cache_count) {
  2048. InstanceGIProbeData::LightCache *caches = probe->light_cache.ptrw();
  2049. RID *instance_caches = probe->light_instances.ptrw();
  2050. int idx = 0; //must count visible lights
  2051. for (Set<Instance *>::Element *E = probe->lights.front(); E; E = E->next()) {
  2052. Instance *instance = E->get();
  2053. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2054. if (!instance->visible) {
  2055. continue;
  2056. }
  2057. InstanceGIProbeData::LightCache *cache = &caches[idx];
  2058. instance_caches[idx] = instance_light->instance;
  2059. cache->has_shadow = RSG::storage->light_has_shadow(instance->base);
  2060. cache->type = RSG::storage->light_get_type(instance->base);
  2061. cache->transform = instance->transform;
  2062. cache->color = RSG::storage->light_get_color(instance->base);
  2063. cache->energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  2064. cache->bake_energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  2065. cache->radius = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  2066. cache->attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  2067. cache->spot_angle = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2068. cache->spot_attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  2069. idx++;
  2070. }
  2071. for (List<Instance *>::Element *E = probe->owner->scenario->directional_lights.front(); E; E = E->next()) {
  2072. Instance *instance = E->get();
  2073. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  2074. if (!instance->visible) {
  2075. continue;
  2076. }
  2077. InstanceGIProbeData::LightCache *cache = &caches[idx];
  2078. instance_caches[idx] = instance_light->instance;
  2079. cache->has_shadow = RSG::storage->light_has_shadow(instance->base);
  2080. cache->type = RSG::storage->light_get_type(instance->base);
  2081. cache->transform = instance->transform;
  2082. cache->color = RSG::storage->light_get_color(instance->base);
  2083. cache->energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  2084. cache->bake_energy = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  2085. cache->radius = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  2086. cache->attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  2087. cache->spot_angle = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2088. cache->spot_attenuation = RSG::storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  2089. idx++;
  2090. }
  2091. }
  2092. update_lights = true;
  2093. }
  2094. instance_cull_count = 0;
  2095. for (List<InstanceGIProbeData::PairInfo>::Element *E = probe->dynamic_geometries.front(); E; E = E->next()) {
  2096. if (instance_cull_count < MAX_INSTANCE_CULL) {
  2097. Instance *ins = E->get().geometry;
  2098. if (!ins->visible) {
  2099. continue;
  2100. }
  2101. InstanceGeometryData *geom = (InstanceGeometryData *)ins->base_data;
  2102. if (geom->gi_probes_dirty) {
  2103. //giprobes may be dirty, so update
  2104. int l = 0;
  2105. //only called when reflection probe AABB enter/exit this geometry
  2106. ins->gi_probe_instances.resize(geom->gi_probes.size());
  2107. for (List<Instance *>::Element *F = geom->gi_probes.front(); F; F = F->next()) {
  2108. InstanceGIProbeData *gi_probe2 = static_cast<InstanceGIProbeData *>(F->get()->base_data);
  2109. ins->gi_probe_instances.write[l++] = gi_probe2->probe_instance;
  2110. }
  2111. geom->gi_probes_dirty = false;
  2112. }
  2113. instance_cull_result[instance_cull_count++] = E->get().geometry;
  2114. }
  2115. }
  2116. RSG::scene_render->gi_probe_update(probe->probe_instance, update_lights, probe->light_instances, instance_cull_count, (RasterizerScene::InstanceBase **)instance_cull_result);
  2117. gi_probe_update_list.remove(gi_probe);
  2118. gi_probe = next;
  2119. }
  2120. }
  2121. void RenderingServerScene::_update_instance_shader_parameters_from_material(Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter> &isparams, const Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter> &existing_isparams, RID p_material) {
  2122. List<RasterizerStorage::InstanceShaderParam> plist;
  2123. RSG::storage->material_get_instance_shader_parameters(p_material, &plist);
  2124. for (List<RasterizerStorage::InstanceShaderParam>::Element *E = plist.front(); E; E = E->next()) {
  2125. StringName name = E->get().info.name;
  2126. if (isparams.has(name)) {
  2127. if (isparams[name].info.type != E->get().info.type) {
  2128. WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E->get().info.name + "', but they do it with different data types. Only the first one (in order) will display correctly.");
  2129. }
  2130. if (isparams[name].index != E->get().index) {
  2131. WARN_PRINT("More than one material in instance export the same instance shader uniform '" + E->get().info.name + "', but they do it with different indices. Only the first one (in order) will display correctly.");
  2132. }
  2133. continue; //first one found always has priority
  2134. }
  2135. RasterizerScene::InstanceBase::InstanceShaderParameter isp;
  2136. isp.index = E->get().index;
  2137. isp.info = E->get().info;
  2138. isp.default_value = E->get().default_value;
  2139. if (existing_isparams.has(name)) {
  2140. isp.value = existing_isparams[name].value;
  2141. } else {
  2142. isp.value = E->get().default_value;
  2143. }
  2144. isparams[name] = isp;
  2145. }
  2146. }
  2147. void RenderingServerScene::_update_dirty_instance(Instance *p_instance) {
  2148. if (p_instance->update_aabb) {
  2149. _update_instance_aabb(p_instance);
  2150. }
  2151. if (p_instance->update_dependencies) {
  2152. p_instance->instance_increase_version();
  2153. if (p_instance->base.is_valid()) {
  2154. RSG::storage->base_update_dependency(p_instance->base, p_instance);
  2155. }
  2156. if (p_instance->material_override.is_valid()) {
  2157. RSG::storage->material_update_dependency(p_instance->material_override, p_instance);
  2158. }
  2159. if (p_instance->base_type == RS::INSTANCE_MESH) {
  2160. //remove materials no longer used and un-own them
  2161. int new_mat_count = RSG::storage->mesh_get_surface_count(p_instance->base);
  2162. p_instance->materials.resize(new_mat_count);
  2163. int new_blend_shape_count = RSG::storage->mesh_get_blend_shape_count(p_instance->base);
  2164. if (new_blend_shape_count != p_instance->blend_values.size()) {
  2165. p_instance->blend_values.resize(new_blend_shape_count);
  2166. for (int i = 0; i < new_blend_shape_count; i++) {
  2167. p_instance->blend_values.write[i] = 0;
  2168. }
  2169. }
  2170. }
  2171. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  2172. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  2173. bool can_cast_shadows = true;
  2174. bool is_animated = false;
  2175. Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter> isparams;
  2176. if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_OFF) {
  2177. can_cast_shadows = false;
  2178. }
  2179. if (p_instance->material_override.is_valid()) {
  2180. if (!RSG::storage->material_casts_shadows(p_instance->material_override)) {
  2181. can_cast_shadows = false;
  2182. }
  2183. is_animated = RSG::storage->material_is_animated(p_instance->material_override);
  2184. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, p_instance->material_override);
  2185. } else {
  2186. if (p_instance->base_type == RS::INSTANCE_MESH) {
  2187. RID mesh = p_instance->base;
  2188. if (mesh.is_valid()) {
  2189. bool cast_shadows = false;
  2190. for (int i = 0; i < p_instance->materials.size(); i++) {
  2191. RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::storage->mesh_surface_get_material(mesh, i);
  2192. if (!mat.is_valid()) {
  2193. cast_shadows = true;
  2194. } else {
  2195. if (RSG::storage->material_casts_shadows(mat)) {
  2196. cast_shadows = true;
  2197. }
  2198. if (RSG::storage->material_is_animated(mat)) {
  2199. is_animated = true;
  2200. }
  2201. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2202. RSG::storage->material_update_dependency(mat, p_instance);
  2203. }
  2204. }
  2205. if (!cast_shadows) {
  2206. can_cast_shadows = false;
  2207. }
  2208. }
  2209. } else if (p_instance->base_type == RS::INSTANCE_MULTIMESH) {
  2210. RID mesh = RSG::storage->multimesh_get_mesh(p_instance->base);
  2211. if (mesh.is_valid()) {
  2212. bool cast_shadows = false;
  2213. int sc = RSG::storage->mesh_get_surface_count(mesh);
  2214. for (int i = 0; i < sc; i++) {
  2215. RID mat = RSG::storage->mesh_surface_get_material(mesh, i);
  2216. if (!mat.is_valid()) {
  2217. cast_shadows = true;
  2218. } else {
  2219. if (RSG::storage->material_casts_shadows(mat)) {
  2220. cast_shadows = true;
  2221. }
  2222. if (RSG::storage->material_is_animated(mat)) {
  2223. is_animated = true;
  2224. }
  2225. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2226. RSG::storage->material_update_dependency(mat, p_instance);
  2227. }
  2228. }
  2229. if (!cast_shadows) {
  2230. can_cast_shadows = false;
  2231. }
  2232. RSG::storage->base_update_dependency(mesh, p_instance);
  2233. }
  2234. } else if (p_instance->base_type == RS::INSTANCE_IMMEDIATE) {
  2235. RID mat = RSG::storage->immediate_get_material(p_instance->base);
  2236. if (!(!mat.is_valid() || RSG::storage->material_casts_shadows(mat))) {
  2237. can_cast_shadows = false;
  2238. }
  2239. if (mat.is_valid() && RSG::storage->material_is_animated(mat)) {
  2240. is_animated = true;
  2241. }
  2242. if (mat.is_valid()) {
  2243. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2244. }
  2245. if (mat.is_valid()) {
  2246. RSG::storage->material_update_dependency(mat, p_instance);
  2247. }
  2248. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  2249. bool cast_shadows = false;
  2250. int dp = RSG::storage->particles_get_draw_passes(p_instance->base);
  2251. for (int i = 0; i < dp; i++) {
  2252. RID mesh = RSG::storage->particles_get_draw_pass_mesh(p_instance->base, i);
  2253. if (!mesh.is_valid()) {
  2254. continue;
  2255. }
  2256. int sc = RSG::storage->mesh_get_surface_count(mesh);
  2257. for (int j = 0; j < sc; j++) {
  2258. RID mat = RSG::storage->mesh_surface_get_material(mesh, j);
  2259. if (!mat.is_valid()) {
  2260. cast_shadows = true;
  2261. } else {
  2262. if (RSG::storage->material_casts_shadows(mat)) {
  2263. cast_shadows = true;
  2264. }
  2265. if (RSG::storage->material_is_animated(mat)) {
  2266. is_animated = true;
  2267. }
  2268. _update_instance_shader_parameters_from_material(isparams, p_instance->instance_shader_parameters, mat);
  2269. RSG::storage->material_update_dependency(mat, p_instance);
  2270. }
  2271. }
  2272. }
  2273. if (!cast_shadows) {
  2274. can_cast_shadows = false;
  2275. }
  2276. }
  2277. }
  2278. if (can_cast_shadows != geom->can_cast_shadows) {
  2279. //ability to cast shadows change, let lights now
  2280. for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
  2281. InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
  2282. light->shadow_dirty = true;
  2283. }
  2284. geom->can_cast_shadows = can_cast_shadows;
  2285. }
  2286. geom->material_is_animated = is_animated;
  2287. p_instance->instance_shader_parameters = isparams;
  2288. if (p_instance->instance_allocated_shader_parameters != (p_instance->instance_shader_parameters.size() > 0)) {
  2289. p_instance->instance_allocated_shader_parameters = (p_instance->instance_shader_parameters.size() > 0);
  2290. if (p_instance->instance_allocated_shader_parameters) {
  2291. p_instance->instance_allocated_shader_parameters_offset = RSG::storage->global_variables_instance_allocate(p_instance->self);
  2292. for (Map<StringName, RasterizerScene::InstanceBase::InstanceShaderParameter>::Element *E = p_instance->instance_shader_parameters.front(); E; E = E->next()) {
  2293. if (E->get().value.get_type() != Variant::NIL) {
  2294. RSG::storage->global_variables_instance_update(p_instance->self, E->get().index, E->get().value);
  2295. }
  2296. }
  2297. } else {
  2298. RSG::storage->global_variables_instance_free(p_instance->self);
  2299. p_instance->instance_allocated_shader_parameters_offset = -1;
  2300. }
  2301. }
  2302. }
  2303. if (p_instance->skeleton.is_valid()) {
  2304. RSG::storage->skeleton_update_dependency(p_instance->skeleton, p_instance);
  2305. }
  2306. p_instance->clean_up_dependencies();
  2307. }
  2308. _instance_update_list.remove(&p_instance->update_item);
  2309. _update_instance(p_instance);
  2310. p_instance->update_aabb = false;
  2311. p_instance->update_dependencies = false;
  2312. }
  2313. void RenderingServerScene::update_dirty_instances() {
  2314. RSG::storage->update_dirty_resources();
  2315. while (_instance_update_list.first()) {
  2316. _update_dirty_instance(_instance_update_list.first()->self());
  2317. }
  2318. }
  2319. bool RenderingServerScene::free(RID p_rid) {
  2320. if (camera_owner.owns(p_rid)) {
  2321. Camera *camera = camera_owner.getornull(p_rid);
  2322. camera_owner.free(p_rid);
  2323. memdelete(camera);
  2324. } else if (scenario_owner.owns(p_rid)) {
  2325. Scenario *scenario = scenario_owner.getornull(p_rid);
  2326. while (scenario->instances.first()) {
  2327. instance_set_scenario(scenario->instances.first()->self()->self, RID());
  2328. }
  2329. RSG::scene_render->free(scenario->reflection_probe_shadow_atlas);
  2330. RSG::scene_render->free(scenario->reflection_atlas);
  2331. scenario_owner.free(p_rid);
  2332. memdelete(scenario);
  2333. } else if (instance_owner.owns(p_rid)) {
  2334. // delete the instance
  2335. update_dirty_instances();
  2336. Instance *instance = instance_owner.getornull(p_rid);
  2337. instance_geometry_set_lightmap(p_rid, RID(), Rect2(), 0);
  2338. instance_set_scenario(p_rid, RID());
  2339. instance_set_base(p_rid, RID());
  2340. instance_geometry_set_material_override(p_rid, RID());
  2341. instance_attach_skeleton(p_rid, RID());
  2342. if (instance->instance_allocated_shader_parameters) {
  2343. //free the used shader parameters
  2344. RSG::storage->global_variables_instance_free(instance->self);
  2345. }
  2346. update_dirty_instances(); //in case something changed this
  2347. instance_owner.free(p_rid);
  2348. memdelete(instance);
  2349. } else {
  2350. return false;
  2351. }
  2352. return true;
  2353. }
  2354. TypedArray<Image> RenderingServerScene::bake_render_uv2(RID p_base, const Vector<RID> &p_material_overrides, const Size2i &p_image_size) {
  2355. return RSG::scene_render->bake_render_uv2(p_base, p_material_overrides, p_image_size);
  2356. }
  2357. RenderingServerScene *RenderingServerScene::singleton = nullptr;
  2358. RenderingServerScene::RenderingServerScene() {
  2359. render_pass = 1;
  2360. singleton = this;
  2361. }
  2362. RenderingServerScene::~RenderingServerScene() {
  2363. }