2
0

visual_server_scene.cpp 95 KB

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