visual_server_scene.cpp 113 KB

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