portal_tracer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /*************************************************************************/
  2. /* portal_tracer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "portal_tracer.h"
  31. #include "portal_renderer.h"
  32. #include "servers/visual/visual_server_globals.h"
  33. #include "servers/visual/visual_server_scene.h"
  34. PortalTracer::PlanesPool::PlanesPool() {
  35. reset();
  36. // preallocate the vectors to a reasonable size
  37. for (int n = 0; n < POOL_MAX; n++) {
  38. _planes[n].resize(32);
  39. }
  40. }
  41. void PortalTracer::PlanesPool::reset() {
  42. for (int n = 0; n < POOL_MAX; n++) {
  43. _freelist[n] = POOL_MAX - n - 1;
  44. }
  45. _num_free = POOL_MAX;
  46. }
  47. unsigned int PortalTracer::PlanesPool::request() {
  48. if (!_num_free) {
  49. return -1;
  50. }
  51. _num_free--;
  52. return _freelist[_num_free];
  53. }
  54. void PortalTracer::PlanesPool::free(unsigned int ui) {
  55. DEV_ASSERT(ui < POOL_MAX);
  56. DEV_ASSERT(_num_free < POOL_MAX);
  57. _freelist[_num_free] = ui;
  58. _num_free++;
  59. }
  60. void PortalTracer::trace_debug_sprawl(PortalRenderer &p_portal_renderer, const Vector3 &p_pos, int p_start_room_id, TraceResult &r_result) {
  61. _portal_renderer = &p_portal_renderer;
  62. _trace_start_point = p_pos;
  63. _result = &r_result;
  64. // all the statics should be not hit to start with
  65. _result->clear();
  66. // new test, new tick, to prevent hitting objects more than once
  67. // on a test.
  68. _tick++;
  69. // if the camera is not in a room do nothing
  70. if (p_start_room_id == -1) {
  71. return;
  72. }
  73. trace_debug_sprawl_recursive(0, p_start_room_id);
  74. }
  75. void PortalTracer::trace(PortalRenderer &p_portal_renderer, const Vector3 &p_pos, const LocalVector<Plane> &p_planes, int p_start_room_id, TraceResult &r_result) {
  76. // store local versions to prevent passing around recursive functions
  77. _portal_renderer = &p_portal_renderer;
  78. _trace_start_point = p_pos;
  79. _result = &r_result;
  80. // The near and far clipping planes needs special treatment. The problem is, if it is
  81. // say a metre from the camera, it will clip out a portal immediately in front of the camera.
  82. // as a result we want to use the near clipping plane for objects, but construct a fake
  83. // near plane at exactly the position of the camera, to clip out portals that are behind us.
  84. _near_and_far_planes[0] = p_planes[0];
  85. _near_and_far_planes[1] = p_planes[1];
  86. // all the statics should be not hit to start with
  87. _result->clear();
  88. // new test, new tick, to prevent hitting objects more than once
  89. // on a test.
  90. _tick++;
  91. // if the camera is not in a room do nothing
  92. // (this will return no hits, but is unlikely because the find_rooms lookup will return the nearest
  93. // room even if not inside)
  94. if (p_start_room_id == -1) {
  95. return;
  96. }
  97. // start off the trace with the planes from the camera
  98. LocalVector<Plane> cam_planes;
  99. cam_planes = p_planes;
  100. if (p_portal_renderer.get_cull_using_pvs()) {
  101. trace_pvs(p_start_room_id, cam_planes);
  102. } else {
  103. // alternative : instead of copying straight, we create the first (near) clipping
  104. // plane manually, at 0 distance from the camera. This ensures that portals will not be
  105. // missed, while still culling portals and objects behind us. If we use the actual near clipping plane
  106. // then a portal in front of the camera may not be seen through, giving glitches
  107. cam_planes[0] = Plane(p_pos, cam_planes[0].normal);
  108. TraceParams params;
  109. params.use_pvs = p_portal_renderer.get_pvs().is_loaded();
  110. // create bitfield
  111. if (params.use_pvs) {
  112. const PVS &pvs = _portal_renderer->get_pvs();
  113. if (!pvs.get_pvs_size()) {
  114. params.use_pvs = false;
  115. } else {
  116. // decompress a simple to read roomlist bitfield (could use bits maybe but bytes ok for now)
  117. params.decompressed_room_pvs = nullptr;
  118. params.decompressed_room_pvs = (uint8_t *)alloca(sizeof(uint8_t) * pvs.get_pvs_size());
  119. memset(params.decompressed_room_pvs, 0, sizeof(uint8_t) * pvs.get_pvs_size());
  120. const VSRoom &source_room = _portal_renderer->get_room(p_start_room_id);
  121. for (int n = 0; n < source_room._pvs_size; n++) {
  122. int room_id = pvs.get_pvs_room_id(source_room._pvs_first + n);
  123. params.decompressed_room_pvs[room_id] = 255;
  124. }
  125. }
  126. }
  127. trace_recursive(params, 0, p_start_room_id, cam_planes);
  128. }
  129. }
  130. void PortalTracer::cull_roamers(const VSRoom &p_room, const LocalVector<Plane> &p_planes) {
  131. int num_roamers = p_room._roamer_pool_ids.size();
  132. for (int n = 0; n < num_roamers; n++) {
  133. uint32_t pool_id = p_room._roamer_pool_ids[n];
  134. PortalRenderer::Moving &moving = _portal_renderer->get_pool_moving(pool_id);
  135. // done already?
  136. if (moving.last_tick_hit == _tick) {
  137. continue;
  138. }
  139. if (test_cull_inside(moving.exact_aabb, p_planes)) {
  140. if (!_occlusion_culler.cull_aabb(moving.exact_aabb)) {
  141. // mark as done (and on visible list)
  142. moving.last_tick_hit = _tick;
  143. _result->visible_roamer_pool_ids.push_back(pool_id);
  144. }
  145. }
  146. }
  147. }
  148. void PortalTracer::cull_statics_debug_sprawl(const VSRoom &p_room) {
  149. int num_statics = p_room._static_ids.size();
  150. for (int n = 0; n < num_statics; n++) {
  151. uint32_t static_id = p_room._static_ids[n];
  152. // VSStatic &stat = _portal_renderer->get_static(static_id);
  153. // deal with dynamic stats
  154. // if (stat.dynamic) {
  155. // VSG::scene->_instance_get_transformed_aabb(stat.instance, stat.aabb);
  156. // }
  157. // set the visible bit if not set
  158. if (!_result->bf_visible_statics.check_and_set(static_id)) {
  159. _result->visible_static_ids.push_back(static_id);
  160. }
  161. }
  162. }
  163. void PortalTracer::cull_statics(const VSRoom &p_room, const LocalVector<Plane> &p_planes) {
  164. int num_statics = p_room._static_ids.size();
  165. for (int n = 0; n < num_statics; n++) {
  166. uint32_t static_id = p_room._static_ids[n];
  167. VSStatic &stat = _portal_renderer->get_static(static_id);
  168. // deal with dynamic stats
  169. if (stat.dynamic) {
  170. VSG::scene->_instance_get_transformed_aabb(stat.instance, stat.aabb);
  171. }
  172. // estimate the radius .. for now
  173. const AABB &bb = stat.aabb;
  174. // print("\t\t\tculling object " + pObj->get_name());
  175. if (test_cull_inside(bb, p_planes)) {
  176. if (_occlusion_culler.cull_aabb(bb)) {
  177. continue;
  178. }
  179. // bypass the bitfield for now and just show / hide
  180. //stat.show(bShow);
  181. // set the visible bit if not set
  182. if (_result->bf_visible_statics.check_and_set(static_id)) {
  183. // if wasn't previously set, add to the visible list
  184. _result->visible_static_ids.push_back(static_id);
  185. }
  186. }
  187. } // for n through statics
  188. }
  189. int PortalTracer::trace_globals(const LocalVector<Plane> &p_planes, VSInstance **p_result_array, int first_result, int p_result_max, uint32_t p_mask, bool p_override_camera) {
  190. uint32_t num_globals = _portal_renderer->get_num_moving_globals();
  191. int current_result = first_result;
  192. if (!p_override_camera) {
  193. for (uint32_t n = 0; n < num_globals; n++) {
  194. const PortalRenderer::Moving &moving = _portal_renderer->get_moving_global(n);
  195. #ifdef PORTAL_RENDERER_STORE_MOVING_RIDS
  196. // debug check the instance is valid
  197. void *vss_instance = VSG::scene->_instance_get_from_rid(moving.instance_rid);
  198. if (vss_instance) {
  199. #endif
  200. if (test_cull_inside(moving.exact_aabb, p_planes, false)) {
  201. if (VSG::scene->_instance_cull_check(moving.instance, p_mask)) {
  202. p_result_array[current_result++] = moving.instance;
  203. // full up?
  204. if (current_result >= p_result_max) {
  205. return current_result;
  206. }
  207. }
  208. }
  209. #ifdef PORTAL_RENDERER_STORE_MOVING_RIDS
  210. } else {
  211. WARN_PRINT("vss instance is null " + PortalRenderer::_addr_to_string(moving.instance));
  212. }
  213. #endif
  214. }
  215. } // if not override camera
  216. else {
  217. // If we are overriding the camera there is a potential problem in the editor:
  218. // gizmos BEHIND the override camera will not be drawn.
  219. // As this should be editor only and performance is not critical, we will just disable
  220. // frustum culling for global objects when the camera is overridden.
  221. for (uint32_t n = 0; n < num_globals; n++) {
  222. const PortalRenderer::Moving &moving = _portal_renderer->get_moving_global(n);
  223. if (VSG::scene->_instance_cull_check(moving.instance, p_mask)) {
  224. p_result_array[current_result++] = moving.instance;
  225. // full up?
  226. if (current_result >= p_result_max) {
  227. return current_result;
  228. }
  229. }
  230. }
  231. } // if override camera
  232. return current_result;
  233. }
  234. void PortalTracer::trace_debug_sprawl_recursive(int p_depth, int p_room_id) {
  235. if (p_depth > 1) {
  236. return;
  237. }
  238. // prevent too much depth
  239. ERR_FAIL_COND_MSG(p_depth > 8, "Portal Depth Limit reached");
  240. // get the room
  241. const VSRoom &room = _portal_renderer->get_room(p_room_id);
  242. int num_portals = room._portal_ids.size();
  243. for (int p = 0; p < num_portals; p++) {
  244. const VSPortal &portal = _portal_renderer->get_portal(room._portal_ids[p]);
  245. if (!portal._active) {
  246. continue;
  247. }
  248. cull_statics_debug_sprawl(room);
  249. // everything depends on whether the portal is incoming or outgoing.
  250. int outgoing = 1;
  251. int room_a_id = portal._linkedroom_ID[0];
  252. if (room_a_id != p_room_id) {
  253. outgoing = 0;
  254. DEV_ASSERT(portal._linkedroom_ID[1] == p_room_id);
  255. }
  256. // trace through this portal to the next room
  257. int linked_room_id = portal._linkedroom_ID[outgoing];
  258. if (linked_room_id != -1) {
  259. trace_debug_sprawl_recursive(p_depth + 1, linked_room_id);
  260. } // if a linked room exists
  261. } // for p through portals
  262. }
  263. void PortalTracer::trace_pvs(int p_source_room_id, const LocalVector<Plane> &p_planes) {
  264. const PVS &pvs = _portal_renderer->get_pvs();
  265. const VSRoom &source_room = _portal_renderer->get_room(p_source_room_id);
  266. for (int r = 0; r < source_room._pvs_size; r++) {
  267. int room_id = pvs.get_pvs_room_id(source_room._pvs_first + r);
  268. // get the room
  269. const VSRoom &room = _portal_renderer->get_room(room_id);
  270. cull_statics(room, p_planes);
  271. cull_roamers(room, p_planes);
  272. }
  273. }
  274. void PortalTracer::trace_recursive(const TraceParams &p_params, int p_depth, int p_room_id, const LocalVector<Plane> &p_planes, int p_from_external_room_id) {
  275. // prevent too much depth
  276. if (p_depth > _depth_limit) {
  277. WARN_PRINT_ONCE("Portal Depth Limit reached (seeing through too many portals)");
  278. return;
  279. }
  280. // get the room
  281. const VSRoom &room = _portal_renderer->get_room(p_room_id);
  282. // set up the occlusion culler as a one off
  283. _occlusion_culler.prepare(*_portal_renderer, room, _trace_start_point, p_planes, &_near_and_far_planes[0]);
  284. cull_statics(room, p_planes);
  285. cull_roamers(room, p_planes);
  286. int num_portals = room._portal_ids.size();
  287. for (int p = 0; p < num_portals; p++) {
  288. const VSPortal &portal = _portal_renderer->get_portal(room._portal_ids[p]);
  289. // portals can be switched on and off at runtime, like opening and closing a door
  290. if (!portal._active) {
  291. continue;
  292. }
  293. // everything depends on whether the portal is incoming or outgoing.
  294. // if incoming we reverse the logic.
  295. int outgoing = 1;
  296. int room_a_id = portal._linkedroom_ID[0];
  297. if (room_a_id != p_room_id) {
  298. outgoing = 0;
  299. DEV_ASSERT(portal._linkedroom_ID[1] == p_room_id);
  300. }
  301. // trace through this portal to the next room
  302. int linked_room_id = portal._linkedroom_ID[outgoing];
  303. // cull by PVS
  304. if (p_params.use_pvs && (!p_params.decompressed_room_pvs[linked_room_id])) {
  305. continue;
  306. }
  307. // cull by portal angle to camera.
  308. // much better way of culling portals by direction to camera...
  309. // instead of using dot product with a varying view direction, we simply find which side of the portal
  310. // plane the camera is on! If it is behind, the portal can be seen through, if in front, it can't
  311. real_t dist_cam = portal._plane.distance_to(_trace_start_point);
  312. if (!outgoing) {
  313. dist_cam = -dist_cam;
  314. }
  315. if (dist_cam >= 0.0) {
  316. continue;
  317. }
  318. // is it culled by the planes?
  319. VSPortal::ClipResult overall_res = VSPortal::ClipResult::CLIP_INSIDE;
  320. // while clipping to the planes we maintain a list of partial planes, so we can add them to the
  321. // recursive next iteration of planes to check
  322. static LocalVector<int> partial_planes;
  323. partial_planes.clear();
  324. // for portals, we want to ignore the near clipping plane, as we might be right on the edge of a doorway
  325. // and still want to look through the portal.
  326. // so earlier we have set it that the first plane (ASSUMING that plane zero is the near clipping plane)
  327. // starts from the camera position, and NOT the actual near clipping plane.
  328. // if we need quite a distant near plane, we may need a different strategy.
  329. for (uint32_t l = 0; l < p_planes.size(); l++) {
  330. VSPortal::ClipResult res = portal.clip_with_plane(p_planes[l]);
  331. switch (res) {
  332. case VSPortal::ClipResult::CLIP_OUTSIDE: {
  333. overall_res = res;
  334. } break;
  335. case VSPortal::ClipResult::CLIP_PARTIAL: {
  336. // if the portal intersects one of the planes, we should take this plane into account
  337. // in the next call of this recursive trace, because it can be used to cull out more objects
  338. overall_res = res;
  339. partial_planes.push_back(l);
  340. } break;
  341. default: // suppress warning
  342. break;
  343. }
  344. // if the portal was totally outside the 'frustum' then we can ignore it
  345. if (overall_res == VSPortal::ClipResult::CLIP_OUTSIDE)
  346. break;
  347. }
  348. // this portal is culled
  349. if (overall_res == VSPortal::ClipResult::CLIP_OUTSIDE) {
  350. continue;
  351. }
  352. // Don't allow portals from internal to external room to be followed
  353. // if the external room has already been processed in this trace stack. This prevents
  354. // unneeded processing, and also prevents recursive feedback where you
  355. // see into internal room -> external room and back into the same internal room
  356. // via the same portal.
  357. if (portal._internal && (linked_room_id != -1)) {
  358. if (outgoing) {
  359. if (linked_room_id == p_from_external_room_id) {
  360. continue;
  361. }
  362. } else {
  363. // We are entering an internal portal from an external room.
  364. // set the external room id, so we can recognise this when we are
  365. // later exiting the internal rooms.
  366. // Note that as we can only store 1 previous external room, this system
  367. // won't work completely correctly when you have 2 levels of internal room
  368. // and you can see from roomgroup a -> b -> c. However this should just result
  369. // in a little slower culling for that particular view, and hopefully will not break
  370. // with recursive loop looking through the same portal multiple times. (don't think this
  371. // is possible in this scenario).
  372. p_from_external_room_id = p_room_id;
  373. }
  374. }
  375. // occlusion culling of portals
  376. if (_occlusion_culler.cull_sphere(portal._pt_center, portal._bounding_sphere_radius)) {
  377. continue;
  378. }
  379. // hopefully the portal actually leads somewhere...
  380. if (linked_room_id != -1) {
  381. // we need some new planes
  382. unsigned int pool_mem = _planes_pool.request();
  383. // if the planes pool is not empty, we got some planes, and can recurse
  384. if (pool_mem != (unsigned int)-1) {
  385. // get a new vector of planes from the pool
  386. LocalVector<Plane> &new_planes = _planes_pool.get(pool_mem);
  387. // makes sure there are none left over (as the pool may not clear them)
  388. new_planes.clear();
  389. // if portal is totally inside the planes, don't copy the old planes ..
  390. // i.e. we can now cull using the portal and forget about the rest of the frustum (yay)
  391. // note that this loses the far clipping plane .. but that shouldn't be important usually?
  392. // (maybe we might need to account for this in future .. look for issues)
  393. if (overall_res != VSPortal::ClipResult::CLIP_INSIDE) {
  394. // if it WASN'T totally inside the existing frustum, we also need to add any existing planes
  395. // that cut the portal.
  396. for (uint32_t n = 0; n < partial_planes.size(); n++) {
  397. new_planes.push_back(p_planes[partial_planes[n]]);
  398. }
  399. }
  400. // we will always add the portals planes. This could probably be optimized, as some
  401. // portal planes may be culled out by partial planes... NYI
  402. portal.add_planes(_trace_start_point, new_planes, outgoing != 0);
  403. // always add the far plane. It is likely the portal is inside the far plane,
  404. // but it is still needed in future for culling portals and objects.
  405. // note that there is a small possibility of far plane being added twice here
  406. // in some situations, but I don't think it should be a problem.
  407. // The fake near plane BTW is almost never added (otherwise it would prematurely
  408. // break traversal through the portals), so near clipping must be done
  409. // explicitly on objects.
  410. new_planes.push_back(_near_and_far_planes[1]);
  411. // go and do the whole lot again in the next room
  412. trace_recursive(p_params, p_depth + 1, linked_room_id, new_planes, p_from_external_room_id);
  413. // no longer need these planes, return them to the pool
  414. _planes_pool.free(pool_mem);
  415. } // pool mem allocated
  416. else {
  417. // planes pool is empty!
  418. // This will happen if the view goes through shedloads of portals
  419. // The solution is either to increase the plane pool size, or not build levels
  420. // with views through multiple portals. Looking through multiple portals is likely to be
  421. // slow anyway because of the number of planes to test.
  422. WARN_PRINT_ONCE("planes pool is empty");
  423. // note we also have a depth check at the top of this function. Which will probably get hit
  424. // before the pool gets empty.
  425. }
  426. } // if a linked room exists
  427. } // for p through portals
  428. }
  429. int PortalTracer::occlusion_cull(PortalRenderer &p_portal_renderer, const Vector3 &p_point, const Vector<Plane> &p_convex, VSInstance **p_result_array, int p_num_results) {
  430. // silly conversion of vector to local vector
  431. // can this be avoided? NYI
  432. // pretty cheap anyway as it will just copy 6 planes, max a few times per frame...
  433. static LocalVector<Plane> local_planes;
  434. if ((int)local_planes.size() != p_convex.size()) {
  435. local_planes.resize(p_convex.size());
  436. }
  437. for (int n = 0; n < p_convex.size(); n++) {
  438. local_planes[n] = p_convex[n];
  439. }
  440. _occlusion_culler.prepare_generic(p_portal_renderer, p_portal_renderer.get_occluders_active_list(), p_point, local_planes);
  441. // cull each instance
  442. int count = p_num_results;
  443. AABB bb;
  444. for (int n = 0; n < count; n++) {
  445. VSInstance *instance = p_result_array[n];
  446. // this will return false for GLOBAL instances, so we don't occlusion cull gizmos
  447. if (VSG::scene->_instance_get_transformed_aabb_for_occlusion(instance, bb)) {
  448. if (_occlusion_culler.cull_aabb(bb)) {
  449. // remove from list with unordered swap from the end of list
  450. p_result_array[n] = p_result_array[count - 1];
  451. count--;
  452. n--; // repeat this element, as it will have changed
  453. }
  454. }
  455. }
  456. return count;
  457. }