visual_server_scene.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. /**************************************************************************/
  2. /* visual_server_scene.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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. #ifndef VISUAL_SERVER_SCENE_H
  31. #define VISUAL_SERVER_SCENE_H
  32. #include "servers/visual/rasterizer.h"
  33. #include "core/math/bvh.h"
  34. #include "core/math/geometry.h"
  35. #include "core/math/octree.h"
  36. #include "core/os/semaphore.h"
  37. #include "core/os/thread.h"
  38. #include "core/safe_refcount.h"
  39. #include "core/self_list.h"
  40. #include "portals/portal_renderer.h"
  41. #include "servers/arvr/arvr_interface.h"
  42. class VisualServerLightCuller;
  43. class VisualServerScene {
  44. public:
  45. enum {
  46. MAX_INSTANCE_CULL = 65536,
  47. MAX_LIGHTS_CULLED = 4096,
  48. MAX_REFLECTION_PROBES_CULLED = 4096,
  49. MAX_ROOM_CULL = 32,
  50. MAX_EXTERIOR_PORTALS = 128,
  51. };
  52. uint64_t render_pass;
  53. static VisualServerScene *singleton;
  54. /* EVENT QUEUING */
  55. void tick();
  56. void pre_draw(bool p_will_draw);
  57. /* CAMERA API */
  58. struct Scenario;
  59. struct Camera : public RID_Data {
  60. enum Type {
  61. PERSPECTIVE,
  62. ORTHOGONAL,
  63. FRUSTUM
  64. };
  65. Type type;
  66. float fov;
  67. float znear, zfar;
  68. float size;
  69. Vector2 offset;
  70. uint32_t visible_layers;
  71. RID env;
  72. Transform transform;
  73. bool vaspect : 1;
  74. int32_t previous_room_id_hint;
  75. Camera() {
  76. visible_layers = 0xFFFFFFFF;
  77. fov = 70;
  78. type = PERSPECTIVE;
  79. znear = 0.05;
  80. zfar = 100;
  81. size = 1.0;
  82. offset = Vector2();
  83. vaspect = false;
  84. previous_room_id_hint = -1;
  85. }
  86. };
  87. mutable RID_Owner<Camera> camera_owner;
  88. virtual RID camera_create();
  89. virtual void camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far);
  90. virtual void camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far);
  91. virtual void camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far);
  92. virtual void camera_set_transform(RID p_camera, const Transform &p_transform);
  93. virtual void camera_set_cull_mask(RID p_camera, uint32_t p_layers);
  94. virtual void camera_set_environment(RID p_camera, RID p_env);
  95. virtual void camera_set_use_vertical_aspect(RID p_camera, bool p_enable);
  96. /* SCENARIO API */
  97. struct Instance;
  98. // common interface for all spatial partitioning schemes
  99. // this is a bit excessive boilerplatewise but can be removed if we decide to stick with one method
  100. // note this is actually the BVH id +1, so that visual server can test against zero
  101. // for validity to maintain compatibility with octree (where 0 indicates invalid)
  102. typedef uint32_t SpatialPartitionID;
  103. class SpatialPartitioningScene {
  104. public:
  105. virtual SpatialPartitionID create(Instance *p_userdata, const AABB &p_aabb, int p_subindex, bool p_pairable, uint32_t p_pairable_type, uint32_t pairable_mask) = 0;
  106. virtual void erase(SpatialPartitionID p_handle) = 0;
  107. virtual void move(SpatialPartitionID p_handle, const AABB &p_aabb) = 0;
  108. virtual void activate(SpatialPartitionID p_handle, const AABB &p_aabb) {}
  109. virtual void deactivate(SpatialPartitionID p_handle) {}
  110. virtual void force_collision_check(SpatialPartitionID p_handle) {}
  111. virtual void update() {}
  112. virtual void update_collisions() {}
  113. virtual void set_pairable(Instance *p_instance, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) = 0;
  114. virtual int cull_convex(const Vector<Plane> &p_convex, Instance **p_result_array, int p_result_max, uint32_t p_mask = 0xFFFFFFFF) = 0;
  115. virtual int cull_aabb(const AABB &p_aabb, Instance **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF) = 0;
  116. virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, Instance **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF) = 0;
  117. typedef void *(*PairCallback)(void *, uint32_t, Instance *, int, uint32_t, Instance *, int);
  118. typedef void (*UnpairCallback)(void *, uint32_t, Instance *, int, uint32_t, Instance *, int, void *);
  119. virtual void set_pair_callback(PairCallback p_callback, void *p_userdata) = 0;
  120. virtual void set_unpair_callback(UnpairCallback p_callback, void *p_userdata) = 0;
  121. // bvh specific
  122. virtual void params_set_node_expansion(real_t p_value) {}
  123. virtual void params_set_pairing_expansion(real_t p_value) {}
  124. // octree specific
  125. virtual void set_balance(float p_balance) {}
  126. virtual ~SpatialPartitioningScene() {}
  127. };
  128. class SpatialPartitioningScene_Octree : public SpatialPartitioningScene {
  129. Octree_CL<Instance, true> _octree;
  130. public:
  131. SpatialPartitionID create(Instance *p_userdata, const AABB &p_aabb, int p_subindex, bool p_pairable, uint32_t p_pairable_type, uint32_t pairable_mask);
  132. void erase(SpatialPartitionID p_handle);
  133. void move(SpatialPartitionID p_handle, const AABB &p_aabb);
  134. void set_pairable(Instance *p_instance, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask);
  135. int cull_convex(const Vector<Plane> &p_convex, Instance **p_result_array, int p_result_max, uint32_t p_mask = 0xFFFFFFFF);
  136. int cull_aabb(const AABB &p_aabb, Instance **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF);
  137. int cull_segment(const Vector3 &p_from, const Vector3 &p_to, Instance **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF);
  138. void set_pair_callback(PairCallback p_callback, void *p_userdata);
  139. void set_unpair_callback(UnpairCallback p_callback, void *p_userdata);
  140. void set_balance(float p_balance);
  141. };
  142. class SpatialPartitioningScene_BVH : public SpatialPartitioningScene {
  143. template <class T>
  144. class UserPairTestFunction {
  145. public:
  146. static bool user_pair_check(const T *p_a, const T *p_b) {
  147. // return false if no collision, decided by masks etc
  148. return true;
  149. }
  150. };
  151. template <class T>
  152. class UserCullTestFunction {
  153. // write this logic once for use in all routines
  154. // double check this as a possible source of bugs in future.
  155. static bool _cull_pairing_mask_test_hit(uint32_t p_maskA, uint32_t p_typeA, uint32_t p_maskB, uint32_t p_typeB) {
  156. // double check this as a possible source of bugs in future.
  157. bool A_match_B = p_maskA & p_typeB;
  158. if (!A_match_B) {
  159. bool B_match_A = p_maskB & p_typeA;
  160. if (!B_match_A) {
  161. return false;
  162. }
  163. }
  164. return true;
  165. }
  166. public:
  167. static bool user_cull_check(const T *p_a, const T *p_b) {
  168. DEV_ASSERT(p_a);
  169. DEV_ASSERT(p_b);
  170. uint32_t a_mask = p_a->bvh_pairable_mask;
  171. uint32_t a_type = p_a->bvh_pairable_type;
  172. uint32_t b_mask = p_b->bvh_pairable_mask;
  173. uint32_t b_type = p_b->bvh_pairable_type;
  174. if (!_cull_pairing_mask_test_hit(a_mask, a_type, b_mask, b_type)) {
  175. return false;
  176. }
  177. return true;
  178. }
  179. };
  180. private:
  181. // Note that SpatialPartitionIDs are +1 based when stored in visual server, to enable 0 to indicate invalid ID.
  182. BVH_Manager<Instance, 2, true, 256, UserPairTestFunction<Instance>, UserCullTestFunction<Instance>> _bvh;
  183. Instance *_dummy_cull_object;
  184. uint32_t find_tree_id_and_collision_mask(bool p_pairable, uint32_t &r_tree_collision_mask) const {
  185. // "pairable" (lights etc) can pair with geometry (non pairable) or other pairables.
  186. // Geometry never pairs with other geometry, so we can eliminate geometry - geometry collision checks.
  187. // Additionally, when lights are made invisible their p_pairable_mask is set to zero to stop their collisions.
  188. // We could potentially choose `tree_collision_mask` based on whether p_pairable_mask is zero,
  189. // in order to catch invisible lights, but in practice these instances will already have been deactivated within
  190. // the BVH so this step is unnecessary. So we can keep the simpler logic of geometry collides with pairable,
  191. // pairable collides with everything.
  192. r_tree_collision_mask = !p_pairable ? 2 : 3;
  193. // Returns tree_id.
  194. return p_pairable ? 1 : 0;
  195. }
  196. public:
  197. SpatialPartitioningScene_BVH();
  198. ~SpatialPartitioningScene_BVH();
  199. SpatialPartitionID create(Instance *p_userdata, const AABB &p_aabb, int p_subindex, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask);
  200. void erase(SpatialPartitionID p_handle);
  201. void move(SpatialPartitionID p_handle, const AABB &p_aabb);
  202. void activate(SpatialPartitionID p_handle, const AABB &p_aabb);
  203. void deactivate(SpatialPartitionID p_handle);
  204. void force_collision_check(SpatialPartitionID p_handle);
  205. void update();
  206. void update_collisions();
  207. void set_pairable(Instance *p_instance, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask);
  208. int cull_convex(const Vector<Plane> &p_convex, Instance **p_result_array, int p_result_max, uint32_t p_mask = 0xFFFFFFFF);
  209. int cull_aabb(const AABB &p_aabb, Instance **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF);
  210. int cull_segment(const Vector3 &p_from, const Vector3 &p_to, Instance **p_result_array, int p_result_max, int *p_subindex_array = nullptr, uint32_t p_mask = 0xFFFFFFFF);
  211. void set_pair_callback(PairCallback p_callback, void *p_userdata);
  212. void set_unpair_callback(UnpairCallback p_callback, void *p_userdata);
  213. void params_set_node_expansion(real_t p_value) { _bvh.params_set_node_expansion(p_value); }
  214. void params_set_pairing_expansion(real_t p_value) { _bvh.params_set_pairing_expansion(p_value); }
  215. };
  216. struct Scenario : RID_Data {
  217. VS::ScenarioDebugMode debug;
  218. RID self;
  219. SpatialPartitioningScene *sps;
  220. PortalRenderer _portal_renderer;
  221. List<Instance *> directional_lights;
  222. RID environment;
  223. RID fallback_environment;
  224. RID reflection_probe_shadow_atlas;
  225. RID reflection_atlas;
  226. SelfList<Instance>::List instances;
  227. Scenario();
  228. ~Scenario() { memdelete(sps); }
  229. };
  230. mutable RID_Owner<Scenario> scenario_owner;
  231. static void *_instance_pair(void *p_self, SpatialPartitionID, Instance *p_A, int, SpatialPartitionID, Instance *p_B, int);
  232. static void _instance_unpair(void *p_self, SpatialPartitionID, Instance *p_A, int, SpatialPartitionID, Instance *p_B, int, void *);
  233. virtual RID scenario_create();
  234. virtual void scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode);
  235. virtual void scenario_set_environment(RID p_scenario, RID p_environment);
  236. virtual void scenario_set_fallback_environment(RID p_scenario, RID p_environment);
  237. virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv);
  238. /* INSTANCING API */
  239. struct InstanceBaseData {
  240. virtual ~InstanceBaseData() {}
  241. };
  242. struct Instance : RasterizerScene::InstanceBase {
  243. RID self;
  244. //scenario stuff
  245. SpatialPartitionID spatial_partition_id;
  246. // rooms & portals
  247. OcclusionHandle occlusion_handle; // handle of instance in occlusion system (or 0)
  248. VisualServer::InstancePortalMode portal_mode;
  249. Scenario *scenario;
  250. SelfList<Instance> scenario_item;
  251. //aabb stuff
  252. bool update_aabb;
  253. bool update_materials;
  254. SelfList<Instance> update_item;
  255. AABB aabb;
  256. AABB transformed_aabb;
  257. AABB *custom_aabb; // <Zylann> would using aabb directly with a bool be better?
  258. float sorting_offset;
  259. bool use_aabb_center;
  260. float extra_margin;
  261. uint32_t object_id;
  262. float lod_begin;
  263. float lod_end;
  264. float lod_begin_hysteresis;
  265. float lod_end_hysteresis;
  266. RID lod_instance;
  267. // These are used for the user cull testing function
  268. // in the BVH, this is precached rather than recalculated each time.
  269. uint32_t bvh_pairable_mask;
  270. uint32_t bvh_pairable_type;
  271. uint64_t last_render_pass;
  272. uint64_t last_frame_pass;
  273. uint64_t version; // changes to this, and changes to base increase version
  274. InstanceBaseData *base_data;
  275. virtual void base_removed() {
  276. singleton->instance_set_base(self, RID());
  277. }
  278. virtual void base_changed(bool p_aabb, bool p_materials) {
  279. singleton->_instance_queue_update(this, p_aabb, p_materials);
  280. }
  281. Instance() :
  282. scenario_item(this),
  283. update_item(this) {
  284. spatial_partition_id = 0;
  285. scenario = nullptr;
  286. update_aabb = false;
  287. update_materials = false;
  288. extra_margin = 0;
  289. object_id = 0;
  290. visible = true;
  291. occlusion_handle = 0;
  292. portal_mode = VisualServer::InstancePortalMode::INSTANCE_PORTAL_MODE_STATIC;
  293. lod_begin = 0;
  294. lod_end = 0;
  295. lod_begin_hysteresis = 0;
  296. lod_end_hysteresis = 0;
  297. bvh_pairable_mask = 0;
  298. bvh_pairable_type = 0;
  299. last_render_pass = 0;
  300. last_frame_pass = 0;
  301. version = 1;
  302. base_data = nullptr;
  303. custom_aabb = nullptr;
  304. sorting_offset = 0.0f;
  305. use_aabb_center = true;
  306. }
  307. ~Instance() {
  308. if (base_data) {
  309. memdelete(base_data);
  310. }
  311. if (custom_aabb) {
  312. memdelete(custom_aabb);
  313. }
  314. }
  315. };
  316. SelfList<Instance>::List _instance_update_list;
  317. // fixed timestep interpolation
  318. virtual void set_physics_interpolation_enabled(bool p_enabled);
  319. struct InterpolationData {
  320. void notify_free_instance(RID p_rid, Instance &r_instance);
  321. LocalVector<RID> instance_interpolate_update_list;
  322. LocalVector<RID> instance_transform_update_lists[2];
  323. LocalVector<RID> *instance_transform_update_list_curr = &instance_transform_update_lists[0];
  324. LocalVector<RID> *instance_transform_update_list_prev = &instance_transform_update_lists[1];
  325. bool interpolation_enabled = false;
  326. } _interpolation_data;
  327. void _instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials = false);
  328. struct InstanceGeometryData : public InstanceBaseData {
  329. List<Instance *> lighting;
  330. bool lighting_dirty;
  331. bool can_cast_shadows;
  332. bool material_is_animated;
  333. List<Instance *> reflection_probes;
  334. bool reflection_dirty;
  335. List<Instance *> gi_probes;
  336. bool gi_probes_dirty;
  337. List<Instance *> lightmap_captures;
  338. InstanceGeometryData() {
  339. lighting_dirty = true;
  340. reflection_dirty = true;
  341. can_cast_shadows = true;
  342. material_is_animated = true;
  343. gi_probes_dirty = true;
  344. }
  345. };
  346. struct InstanceReflectionProbeData : public InstanceBaseData {
  347. Instance *owner;
  348. struct PairInfo {
  349. List<Instance *>::Element *L; //reflection iterator in geometry
  350. Instance *geometry;
  351. };
  352. List<PairInfo> geometries;
  353. RID instance;
  354. bool reflection_dirty;
  355. SelfList<InstanceReflectionProbeData> update_list;
  356. int render_step;
  357. int32_t previous_room_id_hint;
  358. InstanceReflectionProbeData() :
  359. update_list(this) {
  360. reflection_dirty = true;
  361. render_step = -1;
  362. previous_room_id_hint = -1;
  363. }
  364. };
  365. SelfList<InstanceReflectionProbeData>::List reflection_probe_render_list;
  366. struct InstanceLightData : public InstanceBaseData {
  367. struct PairInfo {
  368. List<Instance *>::Element *L; //light iterator in geometry
  369. Instance *geometry;
  370. };
  371. RID instance;
  372. uint64_t last_version;
  373. List<Instance *>::Element *D; // directional light in scenario
  374. List<PairInfo> geometries;
  375. Instance *baked_light;
  376. int32_t previous_room_id_hint;
  377. private:
  378. // Instead of a single dirty flag, we maintain a count
  379. // so that we can detect lights that are being made dirty
  380. // each frame, and switch on tighter caster culling.
  381. int32_t shadow_dirty_count;
  382. uint32_t light_update_frame_id;
  383. bool light_intersects_multiple_cameras;
  384. uint32_t light_intersects_multiple_cameras_timeout_frame_id;
  385. public:
  386. bool is_shadow_dirty() const { return shadow_dirty_count != 0; }
  387. void make_shadow_dirty() { shadow_dirty_count = light_intersects_multiple_cameras ? 1 : 2; }
  388. void detect_light_intersects_multiple_cameras(uint32_t p_frame_id) {
  389. // We need to detect the case where shadow updates are occurring
  390. // more than once per frame. In this case, we need to turn off
  391. // tighter caster culling, so situation reverts to one full shadow update
  392. // per frame (light_intersects_multiple_cameras is set).
  393. if (p_frame_id == light_update_frame_id) {
  394. light_intersects_multiple_cameras = true;
  395. light_intersects_multiple_cameras_timeout_frame_id = p_frame_id + 60;
  396. } else {
  397. // When shadow_volume_intersects_multiple_cameras is set, we
  398. // want to detect the situation this is no longer the case, via a timeout.
  399. // The system can go back to tighter caster culling in this situation.
  400. // Having a long-ish timeout prevents rapid cycling.
  401. if (light_intersects_multiple_cameras && (p_frame_id >= light_intersects_multiple_cameras_timeout_frame_id)) {
  402. light_intersects_multiple_cameras = false;
  403. light_intersects_multiple_cameras_timeout_frame_id = UINT32_MAX;
  404. }
  405. }
  406. light_update_frame_id = p_frame_id;
  407. }
  408. void decrement_shadow_dirty() {
  409. shadow_dirty_count--;
  410. DEV_ASSERT(shadow_dirty_count >= 0);
  411. }
  412. // Shadow updates can either full (everything in the shadow volume)
  413. // or closely culled to the camera frustum.
  414. bool is_shadow_update_full() const { return shadow_dirty_count == 0; }
  415. InstanceLightData() {
  416. shadow_dirty_count = 1;
  417. light_update_frame_id = UINT32_MAX;
  418. light_intersects_multiple_cameras_timeout_frame_id = UINT32_MAX;
  419. light_intersects_multiple_cameras = false;
  420. D = nullptr;
  421. last_version = 0;
  422. baked_light = nullptr;
  423. previous_room_id_hint = -1;
  424. }
  425. };
  426. struct InstanceGIProbeData : public InstanceBaseData {
  427. Instance *owner;
  428. struct PairInfo {
  429. List<Instance *>::Element *L; //gi probe iterator in geometry
  430. Instance *geometry;
  431. };
  432. List<PairInfo> geometries;
  433. Set<Instance *> lights;
  434. struct LightCache {
  435. VS::LightType type;
  436. Transform transform;
  437. Color color;
  438. float energy;
  439. float radius;
  440. float attenuation;
  441. float spot_angle;
  442. float spot_attenuation;
  443. bool visible;
  444. bool operator==(const LightCache &p_cache) {
  445. return (type == p_cache.type &&
  446. transform == p_cache.transform &&
  447. color == p_cache.color &&
  448. energy == p_cache.energy &&
  449. radius == p_cache.radius &&
  450. attenuation == p_cache.attenuation &&
  451. spot_angle == p_cache.spot_angle &&
  452. spot_attenuation == p_cache.spot_attenuation &&
  453. visible == p_cache.visible);
  454. }
  455. bool operator!=(const LightCache &p_cache) {
  456. return !operator==(p_cache);
  457. }
  458. LightCache() {
  459. type = VS::LIGHT_DIRECTIONAL;
  460. energy = 1.0;
  461. radius = 1.0;
  462. attenuation = 1.0;
  463. spot_angle = 1.0;
  464. spot_attenuation = 1.0;
  465. visible = true;
  466. }
  467. };
  468. struct LocalData {
  469. uint16_t pos[3];
  470. uint16_t energy[3]; //using 0..1024 for float range 0..1. integer is needed for deterministic add/remove of lights
  471. };
  472. struct CompBlockS3TC {
  473. uint32_t offset; //offset in mipmap
  474. uint32_t source_count; //sources
  475. uint32_t sources[16]; //id for each source
  476. uint8_t alpha[8]; //alpha block is pre-computed
  477. };
  478. struct Dynamic {
  479. Map<RID, LightCache> light_cache;
  480. Map<RID, LightCache> light_cache_changes;
  481. PoolVector<int> light_data;
  482. PoolVector<LocalData> local_data;
  483. Vector<Vector<uint32_t>> level_cell_lists;
  484. RID probe_data;
  485. bool enabled;
  486. int bake_dynamic_range;
  487. RasterizerStorage::GIProbeCompression compression;
  488. Vector<PoolVector<uint8_t>> mipmaps_3d;
  489. Vector<PoolVector<CompBlockS3TC>> mipmaps_s3tc; //for s3tc
  490. int updating_stage;
  491. float propagate;
  492. int grid_size[3];
  493. Transform light_to_cell_xform;
  494. } dynamic;
  495. RID probe_instance;
  496. bool invalid;
  497. uint32_t base_version;
  498. SelfList<InstanceGIProbeData> update_element;
  499. InstanceGIProbeData() :
  500. update_element(this) {
  501. invalid = true;
  502. base_version = 0;
  503. dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
  504. }
  505. };
  506. SelfList<InstanceGIProbeData>::List gi_probe_update_list;
  507. struct InstanceLightmapCaptureData : public InstanceBaseData {
  508. struct PairInfo {
  509. List<Instance *>::Element *L; //iterator in geometry
  510. Instance *geometry;
  511. };
  512. List<PairInfo> geometries;
  513. Set<Instance *> users;
  514. InstanceLightmapCaptureData() {
  515. }
  516. };
  517. int instance_cull_count;
  518. Instance *instance_cull_result[MAX_INSTANCE_CULL];
  519. Instance *instance_shadow_cull_result[MAX_INSTANCE_CULL]; //used for generating shadowmaps
  520. Instance *light_cull_result[MAX_LIGHTS_CULLED];
  521. RID light_instance_cull_result[MAX_LIGHTS_CULLED];
  522. int light_cull_count;
  523. int directional_light_count;
  524. VisualServerLightCuller *light_culler;
  525. RID reflection_probe_instance_cull_result[MAX_REFLECTION_PROBES_CULLED];
  526. int reflection_probe_cull_count;
  527. RID_Owner<Instance> instance_owner;
  528. virtual RID instance_create();
  529. virtual void instance_set_base(RID p_instance, RID p_base);
  530. virtual void instance_set_scenario(RID p_instance, RID p_scenario);
  531. virtual void instance_set_layer_mask(RID p_instance, uint32_t p_mask);
  532. virtual void instance_set_pivot_data(RID p_instance, float p_sorting_offset, bool p_use_aabb_center);
  533. virtual void instance_set_transform(RID p_instance, const Transform &p_transform);
  534. virtual void instance_set_interpolated(RID p_instance, bool p_interpolated);
  535. virtual void instance_reset_physics_interpolation(RID p_instance);
  536. virtual void instance_attach_object_instance_id(RID p_instance, ObjectID p_id);
  537. virtual void instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight);
  538. virtual void instance_set_surface_material(RID p_instance, int p_surface, RID p_material);
  539. virtual void instance_set_visible(RID p_instance, bool p_visible);
  540. virtual void instance_set_use_lightmap(RID p_instance, RID p_lightmap_instance, RID p_lightmap, int p_lightmap_slice, const Rect2 &p_lightmap_uv_rect);
  541. virtual void instance_set_custom_aabb(RID p_instance, AABB p_aabb);
  542. virtual void instance_attach_skeleton(RID p_instance, RID p_skeleton);
  543. virtual void instance_set_exterior(RID p_instance, bool p_enabled);
  544. virtual void instance_set_extra_visibility_margin(RID p_instance, real_t p_margin);
  545. // Portals
  546. virtual void instance_set_portal_mode(RID p_instance, VisualServer::InstancePortalMode p_mode);
  547. bool _instance_get_transformed_aabb(RID p_instance, AABB &r_aabb);
  548. bool _instance_get_transformed_aabb_for_occlusion(VSInstance *p_instance, AABB &r_aabb) const {
  549. r_aabb = ((Instance *)p_instance)->transformed_aabb;
  550. return ((Instance *)p_instance)->portal_mode != VisualServer::INSTANCE_PORTAL_MODE_GLOBAL;
  551. }
  552. void *_instance_get_from_rid(RID p_instance);
  553. bool _instance_cull_check(VSInstance *p_instance, uint32_t p_cull_mask) const {
  554. uint32_t pairable_type = 1 << ((Instance *)p_instance)->base_type;
  555. return pairable_type & p_cull_mask;
  556. }
  557. ObjectID _instance_get_object_ID(VSInstance *p_instance) const {
  558. if (p_instance) {
  559. return ((Instance *)p_instance)->object_id;
  560. }
  561. return 0;
  562. }
  563. private:
  564. void _instance_create_occlusion_rep(Instance *p_instance);
  565. void _instance_destroy_occlusion_rep(Instance *p_instance);
  566. public:
  567. struct Ghost : RID_Data {
  568. // all interactions with actual ghosts are indirect, as the ghost is part of the scenario
  569. Scenario *scenario = nullptr;
  570. uint32_t object_id = 0;
  571. RGhostHandle rghost_handle = 0; // handle in occlusion system (or 0)
  572. AABB aabb;
  573. virtual ~Ghost() {
  574. if (scenario) {
  575. if (rghost_handle) {
  576. scenario->_portal_renderer.rghost_destroy(rghost_handle);
  577. rghost_handle = 0;
  578. }
  579. scenario = nullptr;
  580. }
  581. }
  582. };
  583. RID_Owner<Ghost> ghost_owner;
  584. virtual RID ghost_create();
  585. virtual void ghost_set_scenario(RID p_ghost, RID p_scenario, ObjectID p_id, const AABB &p_aabb);
  586. virtual void ghost_update(RID p_ghost, const AABB &p_aabb);
  587. private:
  588. void _ghost_create_occlusion_rep(Ghost *p_ghost);
  589. void _ghost_destroy_occlusion_rep(Ghost *p_ghost);
  590. public:
  591. /* PORTALS API */
  592. struct Portal : RID_Data {
  593. // all interactions with actual portals are indirect, as the portal is part of the scenario
  594. uint32_t scenario_portal_id = 0;
  595. Scenario *scenario = nullptr;
  596. virtual ~Portal() {
  597. if (scenario) {
  598. scenario->_portal_renderer.portal_destroy(scenario_portal_id);
  599. scenario = nullptr;
  600. scenario_portal_id = 0;
  601. }
  602. }
  603. };
  604. RID_Owner<Portal> portal_owner;
  605. virtual RID portal_create();
  606. virtual void portal_set_scenario(RID p_portal, RID p_scenario);
  607. virtual void portal_set_geometry(RID p_portal, const Vector<Vector3> &p_points, real_t p_margin);
  608. virtual void portal_link(RID p_portal, RID p_room_from, RID p_room_to, bool p_two_way);
  609. virtual void portal_set_active(RID p_portal, bool p_active);
  610. /* ROOMGROUPS API */
  611. struct RoomGroup : RID_Data {
  612. // all interactions with actual roomgroups are indirect, as the roomgroup is part of the scenario
  613. uint32_t scenario_roomgroup_id = 0;
  614. Scenario *scenario = nullptr;
  615. virtual ~RoomGroup() {
  616. if (scenario) {
  617. scenario->_portal_renderer.roomgroup_destroy(scenario_roomgroup_id);
  618. scenario = nullptr;
  619. scenario_roomgroup_id = 0;
  620. }
  621. }
  622. };
  623. RID_Owner<RoomGroup> roomgroup_owner;
  624. virtual RID roomgroup_create();
  625. virtual void roomgroup_prepare(RID p_roomgroup, ObjectID p_roomgroup_object_id);
  626. virtual void roomgroup_set_scenario(RID p_roomgroup, RID p_scenario);
  627. virtual void roomgroup_add_room(RID p_roomgroup, RID p_room);
  628. /* OCCLUDERS API */
  629. struct OccluderInstance : RID_Data {
  630. uint32_t scenario_occluder_id = 0;
  631. Scenario *scenario = nullptr;
  632. virtual ~OccluderInstance() {
  633. if (scenario) {
  634. scenario->_portal_renderer.occluder_instance_destroy(scenario_occluder_id);
  635. scenario = nullptr;
  636. scenario_occluder_id = 0;
  637. }
  638. }
  639. };
  640. RID_Owner<OccluderInstance> occluder_instance_owner;
  641. struct OccluderResource : RID_Data {
  642. uint32_t occluder_resource_id = 0;
  643. void destroy(PortalResources &r_portal_resources) {
  644. r_portal_resources.occluder_resource_destroy(occluder_resource_id);
  645. occluder_resource_id = 0;
  646. }
  647. virtual ~OccluderResource() {
  648. DEV_ASSERT(occluder_resource_id == 0);
  649. }
  650. };
  651. RID_Owner<OccluderResource> occluder_resource_owner;
  652. virtual RID occluder_instance_create();
  653. virtual void occluder_instance_set_scenario(RID p_occluder_instance, RID p_scenario);
  654. virtual void occluder_instance_link_resource(RID p_occluder_instance, RID p_occluder_resource);
  655. virtual void occluder_instance_set_transform(RID p_occluder_instance, const Transform &p_xform);
  656. virtual void occluder_instance_set_active(RID p_occluder_instance, bool p_active);
  657. virtual RID occluder_resource_create();
  658. virtual void occluder_resource_prepare(RID p_occluder_resource, VisualServer::OccluderType p_type);
  659. virtual void occluder_resource_spheres_update(RID p_occluder_resource, const Vector<Plane> &p_spheres);
  660. virtual void occluder_resource_mesh_update(RID p_occluder_resource, const Geometry::OccluderMeshData &p_mesh_data);
  661. virtual void set_use_occlusion_culling(bool p_enable);
  662. // editor only .. slow
  663. virtual Geometry::MeshData occlusion_debug_get_current_polys(RID p_scenario) const;
  664. const PortalResources &get_portal_resources() const {
  665. return _portal_resources;
  666. }
  667. PortalResources &get_portal_resources() {
  668. return _portal_resources;
  669. }
  670. /* ROOMS API */
  671. struct Room : RID_Data {
  672. // all interactions with actual rooms are indirect, as the room is part of the scenario
  673. uint32_t scenario_room_id = 0;
  674. Scenario *scenario = nullptr;
  675. virtual ~Room() {
  676. if (scenario) {
  677. scenario->_portal_renderer.room_destroy(scenario_room_id);
  678. scenario = nullptr;
  679. scenario_room_id = 0;
  680. }
  681. }
  682. };
  683. RID_Owner<Room> room_owner;
  684. virtual RID room_create();
  685. virtual void room_set_scenario(RID p_room, RID p_scenario);
  686. virtual void room_add_instance(RID p_room, RID p_instance, const AABB &p_aabb, const Vector<Vector3> &p_object_pts);
  687. virtual void room_add_ghost(RID p_room, ObjectID p_object_id, const AABB &p_aabb);
  688. virtual void room_set_bound(RID p_room, ObjectID p_room_object_id, const Vector<Plane> &p_convex, const AABB &p_aabb, const Vector<Vector3> &p_verts);
  689. virtual void room_prepare(RID p_room, int32_t p_priority);
  690. virtual void rooms_and_portals_clear(RID p_scenario);
  691. virtual void rooms_unload(RID p_scenario, String p_reason);
  692. virtual void rooms_finalize(RID p_scenario, bool p_generate_pvs, bool p_cull_using_pvs, bool p_use_secondary_pvs, bool p_use_signals, String p_pvs_filename, bool p_use_simple_pvs, bool p_log_pvs_generation);
  693. virtual void rooms_override_camera(RID p_scenario, bool p_override, const Vector3 &p_point, const Vector<Plane> *p_convex);
  694. virtual void rooms_set_active(RID p_scenario, bool p_active);
  695. virtual void rooms_set_params(RID p_scenario, int p_portal_depth_limit, real_t p_roaming_expansion_margin);
  696. virtual void rooms_set_debug_feature(RID p_scenario, VisualServer::RoomsDebugFeature p_feature, bool p_active);
  697. virtual void rooms_update_gameplay_monitor(RID p_scenario, const Vector<Vector3> &p_camera_positions);
  698. // don't use this in a game
  699. virtual bool rooms_is_loaded(RID p_scenario) const;
  700. virtual void callbacks_register(VisualServerCallbacks *p_callbacks);
  701. VisualServerCallbacks *get_callbacks() const {
  702. return _visual_server_callbacks;
  703. }
  704. // don't use these in a game!
  705. virtual Vector<ObjectID> instances_cull_aabb(const AABB &p_aabb, RID p_scenario = RID()) const;
  706. virtual Vector<ObjectID> instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario = RID()) const;
  707. virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario = RID()) const;
  708. // internal (uses portals when available)
  709. int _cull_convex_from_point(Scenario *p_scenario, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, const Vector<Plane> &p_convex, Instance **p_result_array, int p_result_max, int32_t &r_previous_room_id_hint, uint32_t p_mask = 0xFFFFFFFF);
  710. void _rooms_instance_update(Instance *p_instance, const AABB &p_aabb);
  711. virtual void instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled);
  712. virtual void instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting);
  713. virtual void instance_geometry_set_material_override(RID p_instance, RID p_material);
  714. virtual void instance_geometry_set_material_overlay(RID p_instance, RID p_material);
  715. _FORCE_INLINE_ void _update_instance(Instance *p_instance);
  716. _FORCE_INLINE_ void _update_instance_aabb(Instance *p_instance);
  717. _FORCE_INLINE_ void _update_dirty_instance(Instance *p_instance);
  718. _FORCE_INLINE_ void _update_instance_lightmap_captures(Instance *p_instance);
  719. _FORCE_INLINE_ bool _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, uint32_t p_visible_layers = 0xFFFFFF);
  720. void _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, int32_t &r_previous_room_id_hint);
  721. void _render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, const int p_eye, bool p_cam_orthogonal, RID p_force_environment, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass);
  722. void render_empty_scene(RID p_scenario, RID p_shadow_atlas);
  723. void render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas);
  724. void render_camera(Ref<ARVRInterface> &p_interface, ARVRInterface::Eyes p_eye, RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas);
  725. void update_dirty_instances();
  726. // interpolation
  727. void update_interpolation_tick(bool p_process = true);
  728. void update_interpolation_frame(bool p_process = true);
  729. //probes
  730. struct GIProbeDataHeader {
  731. uint32_t version;
  732. uint32_t cell_subdiv;
  733. uint32_t width;
  734. uint32_t height;
  735. uint32_t depth;
  736. uint32_t cell_count;
  737. uint32_t leaf_cell_count;
  738. };
  739. struct GIProbeDataCell {
  740. uint32_t children[8];
  741. uint32_t albedo;
  742. uint32_t emission;
  743. uint32_t normal;
  744. uint32_t level_alpha;
  745. };
  746. enum {
  747. GI_UPDATE_STAGE_CHECK,
  748. GI_UPDATE_STAGE_LIGHTING,
  749. GI_UPDATE_STAGE_UPLOADING,
  750. };
  751. void _gi_probe_bake_thread();
  752. static void _gi_probe_bake_threads(void *);
  753. bool probe_bake_thread_exit;
  754. Thread probe_bake_thread;
  755. Semaphore probe_bake_sem;
  756. Mutex probe_bake_mutex;
  757. List<Instance *> probe_bake_list;
  758. bool _render_reflection_probe_step(Instance *p_instance, int p_step);
  759. void _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);
  760. _FORCE_INLINE_ uint32_t _gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv);
  761. void _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);
  762. void _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);
  763. void _bake_gi_probe(Instance *p_gi_probe);
  764. bool _check_gi_probe(Instance *p_gi_probe);
  765. void _setup_gi_probe(Instance *p_instance);
  766. void render_probes();
  767. bool free(RID p_rid);
  768. private:
  769. bool _use_bvh;
  770. VisualServerCallbacks *_visual_server_callbacks;
  771. PortalResources _portal_resources;
  772. public:
  773. VisualServerScene();
  774. virtual ~VisualServerScene();
  775. };
  776. #endif // VISUAL_SERVER_SCENE_H