shape_cast_2d.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*************************************************************************/
  2. /* shape_cast_2d.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 "shape_cast_2d.h"
  31. #include "core/config/engine.h"
  32. #include "core/core_string_names.h"
  33. #include "scene/2d/collision_object_2d.h"
  34. #include "scene/2d/physics_body_2d.h"
  35. #include "scene/resources/circle_shape_2d.h"
  36. #include "servers/physics_2d/godot_physics_server_2d.h"
  37. void ShapeCast2D::set_target_position(const Vector2 &p_point) {
  38. target_position = p_point;
  39. if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || get_tree()->is_debugging_collisions_hint())) {
  40. queue_redraw();
  41. }
  42. }
  43. Vector2 ShapeCast2D::get_target_position() const {
  44. return target_position;
  45. }
  46. void ShapeCast2D::set_margin(real_t p_margin) {
  47. margin = p_margin;
  48. }
  49. real_t ShapeCast2D::get_margin() const {
  50. return margin;
  51. }
  52. void ShapeCast2D::set_max_results(int p_max_results) {
  53. max_results = p_max_results;
  54. }
  55. int ShapeCast2D::get_max_results() const {
  56. return max_results;
  57. }
  58. void ShapeCast2D::set_collision_mask(uint32_t p_mask) {
  59. collision_mask = p_mask;
  60. }
  61. uint32_t ShapeCast2D::get_collision_mask() const {
  62. return collision_mask;
  63. }
  64. void ShapeCast2D::set_collision_mask_value(int p_layer_number, bool p_value) {
  65. ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
  66. ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
  67. uint32_t mask = get_collision_mask();
  68. if (p_value) {
  69. mask |= 1 << (p_layer_number - 1);
  70. } else {
  71. mask &= ~(1 << (p_layer_number - 1));
  72. }
  73. set_collision_mask(mask);
  74. }
  75. bool ShapeCast2D::get_collision_mask_value(int p_layer_number) const {
  76. ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
  77. ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
  78. return get_collision_mask() & (1 << (p_layer_number - 1));
  79. }
  80. int ShapeCast2D::get_collision_count() const {
  81. return result.size();
  82. }
  83. bool ShapeCast2D::is_colliding() const {
  84. return collided;
  85. }
  86. Object *ShapeCast2D::get_collider(int p_idx) const {
  87. ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), nullptr, "No collider found.");
  88. if (result[p_idx].collider_id.is_null()) {
  89. return nullptr;
  90. }
  91. return ObjectDB::get_instance(result[p_idx].collider_id);
  92. }
  93. int ShapeCast2D::get_collider_shape(int p_idx) const {
  94. ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), -1, "No collider shape found.");
  95. return result[p_idx].shape;
  96. }
  97. Vector2 ShapeCast2D::get_collision_point(int p_idx) const {
  98. ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), Vector2(), "No collision point found.");
  99. return result[p_idx].point;
  100. }
  101. Vector2 ShapeCast2D::get_collision_normal(int p_idx) const {
  102. ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), Vector2(), "No collision normal found.");
  103. return result[p_idx].normal;
  104. }
  105. real_t ShapeCast2D::get_closest_collision_safe_fraction() const {
  106. return collision_safe_fraction;
  107. }
  108. real_t ShapeCast2D::get_closest_collision_unsafe_fraction() const {
  109. return collision_unsafe_fraction;
  110. }
  111. void ShapeCast2D::set_enabled(bool p_enabled) {
  112. enabled = p_enabled;
  113. queue_redraw();
  114. if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) {
  115. set_physics_process_internal(p_enabled);
  116. }
  117. if (!p_enabled) {
  118. collided = false;
  119. }
  120. }
  121. bool ShapeCast2D::is_enabled() const {
  122. return enabled;
  123. }
  124. void ShapeCast2D::set_shape(const Ref<Shape2D> &p_shape) {
  125. shape = p_shape;
  126. if (p_shape.is_valid()) {
  127. shape->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &ShapeCast2D::_redraw_shape));
  128. shape_rid = shape->get_rid();
  129. }
  130. update_configuration_warnings();
  131. queue_redraw();
  132. }
  133. Ref<Shape2D> ShapeCast2D::get_shape() const {
  134. return shape;
  135. }
  136. void ShapeCast2D::set_exclude_parent_body(bool p_exclude_parent_body) {
  137. if (exclude_parent_body == p_exclude_parent_body) {
  138. return;
  139. }
  140. exclude_parent_body = p_exclude_parent_body;
  141. if (!is_inside_tree()) {
  142. return;
  143. }
  144. if (Object::cast_to<CollisionObject2D>(get_parent())) {
  145. if (exclude_parent_body) {
  146. exclude.insert(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());
  147. } else {
  148. exclude.erase(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());
  149. }
  150. }
  151. }
  152. bool ShapeCast2D::get_exclude_parent_body() const {
  153. return exclude_parent_body;
  154. }
  155. void ShapeCast2D::_redraw_shape() {
  156. queue_redraw();
  157. }
  158. void ShapeCast2D::_notification(int p_what) {
  159. switch (p_what) {
  160. case NOTIFICATION_ENTER_TREE: {
  161. if (enabled && !Engine::get_singleton()->is_editor_hint()) {
  162. set_physics_process_internal(true);
  163. } else {
  164. set_physics_process_internal(false);
  165. }
  166. if (Object::cast_to<CollisionObject2D>(get_parent())) {
  167. if (exclude_parent_body) {
  168. exclude.insert(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());
  169. } else {
  170. exclude.erase(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());
  171. }
  172. }
  173. } break;
  174. case NOTIFICATION_EXIT_TREE: {
  175. if (enabled) {
  176. set_physics_process_internal(false);
  177. }
  178. } break;
  179. case NOTIFICATION_DRAW: {
  180. #ifdef TOOLS_ENABLED
  181. ERR_FAIL_COND(!is_inside_tree());
  182. if (!Engine::get_singleton()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) {
  183. break;
  184. }
  185. if (shape.is_null()) {
  186. break;
  187. }
  188. Color draw_col = collided ? Color(1.0, 0.01, 0) : get_tree()->get_debug_collisions_color();
  189. if (!enabled) {
  190. float g = draw_col.get_v();
  191. draw_col.r = g;
  192. draw_col.g = g;
  193. draw_col.b = g;
  194. }
  195. // Draw continuous chain of shapes along the cast.
  196. const int steps = MAX(2, target_position.length() / shape->get_rect().get_size().length() * 4);
  197. for (int i = 0; i <= steps; ++i) {
  198. Vector2 t = (real_t(i) / steps) * target_position;
  199. draw_set_transform(t, 0.0, Size2(1, 1));
  200. shape->draw(get_canvas_item(), draw_col);
  201. }
  202. draw_set_transform(Vector2(), 0.0, Size2(1, 1));
  203. // Draw an arrow indicating where the ShapeCast is pointing to.
  204. if (target_position != Vector2()) {
  205. const real_t max_arrow_size = 6;
  206. const real_t line_width = 1.4;
  207. bool no_line = target_position.length() < line_width;
  208. real_t arrow_size = CLAMP(target_position.length() * 2 / 3, line_width, max_arrow_size);
  209. if (no_line) {
  210. arrow_size = target_position.length();
  211. } else {
  212. draw_line(Vector2(), target_position - target_position.normalized() * arrow_size, draw_col, line_width);
  213. }
  214. Transform2D xf;
  215. xf.rotate(target_position.angle());
  216. xf.translate_local(Vector2(no_line ? 0 : target_position.length() - arrow_size, 0));
  217. Vector<Vector2> pts = {
  218. xf.xform(Vector2(arrow_size, 0)),
  219. xf.xform(Vector2(0, 0.5 * arrow_size)),
  220. xf.xform(Vector2(0, -0.5 * arrow_size))
  221. };
  222. Vector<Color> cols = { draw_col, draw_col, draw_col };
  223. draw_primitive(pts, cols, Vector<Vector2>());
  224. }
  225. #endif
  226. } break;
  227. case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
  228. if (!enabled) {
  229. break;
  230. }
  231. _update_shapecast_state();
  232. } break;
  233. }
  234. }
  235. void ShapeCast2D::_update_shapecast_state() {
  236. result.clear();
  237. ERR_FAIL_COND_MSG(shape.is_null(), "Invalid shape.");
  238. Ref<World2D> w2d = get_world_2d();
  239. ERR_FAIL_COND(w2d.is_null());
  240. PhysicsDirectSpaceState2D *dss = PhysicsServer2D::get_singleton()->space_get_direct_state(w2d->get_space());
  241. ERR_FAIL_COND(!dss);
  242. Transform2D gt = get_global_transform();
  243. PhysicsDirectSpaceState2D::ShapeParameters params;
  244. params.shape_rid = shape_rid;
  245. params.transform = gt;
  246. params.motion = gt.basis_xform(target_position);
  247. params.margin = margin;
  248. params.exclude = exclude;
  249. params.collision_mask = collision_mask;
  250. params.collide_with_bodies = collide_with_bodies;
  251. params.collide_with_areas = collide_with_areas;
  252. collision_safe_fraction = 0.0;
  253. collision_unsafe_fraction = 0.0;
  254. bool prev_collision_state = collided;
  255. if (target_position != Vector2()) {
  256. dss->cast_motion(params, collision_safe_fraction, collision_unsafe_fraction);
  257. if (collision_unsafe_fraction < 1.0) {
  258. // Move shape transform to the point of impact,
  259. // so we can collect contact info at that point.
  260. gt.set_origin(gt.get_origin() + params.motion * (collision_unsafe_fraction + CMP_EPSILON));
  261. params.transform = gt;
  262. }
  263. }
  264. // Regardless of whether the shape is stuck or it's moved along
  265. // the motion vector, we'll only consider static collisions from now on.
  266. params.motion = Vector2();
  267. bool intersected = true;
  268. while (intersected && result.size() < max_results) {
  269. PhysicsDirectSpaceState2D::ShapeRestInfo info;
  270. intersected = dss->rest_info(params, &info);
  271. if (intersected) {
  272. result.push_back(info);
  273. params.exclude.insert(info.rid);
  274. }
  275. }
  276. collided = !result.is_empty();
  277. if (prev_collision_state != collided) {
  278. queue_redraw();
  279. }
  280. }
  281. void ShapeCast2D::force_shapecast_update() {
  282. _update_shapecast_state();
  283. }
  284. void ShapeCast2D::add_exception_rid(const RID &p_rid) {
  285. exclude.insert(p_rid);
  286. }
  287. void ShapeCast2D::add_exception(const CollisionObject2D *p_node) {
  288. ERR_FAIL_NULL_MSG(p_node, "The passed Node must be an instance of CollisionObject2D.");
  289. add_exception_rid(p_node->get_rid());
  290. }
  291. void ShapeCast2D::remove_exception_rid(const RID &p_rid) {
  292. exclude.erase(p_rid);
  293. }
  294. void ShapeCast2D::remove_exception(const CollisionObject2D *p_node) {
  295. ERR_FAIL_NULL_MSG(p_node, "The passed Node must be an instance of CollisionObject2D.");
  296. remove_exception_rid(p_node->get_rid());
  297. }
  298. void ShapeCast2D::clear_exceptions() {
  299. exclude.clear();
  300. }
  301. void ShapeCast2D::set_collide_with_areas(bool p_clip) {
  302. collide_with_areas = p_clip;
  303. }
  304. bool ShapeCast2D::is_collide_with_areas_enabled() const {
  305. return collide_with_areas;
  306. }
  307. void ShapeCast2D::set_collide_with_bodies(bool p_clip) {
  308. collide_with_bodies = p_clip;
  309. }
  310. bool ShapeCast2D::is_collide_with_bodies_enabled() const {
  311. return collide_with_bodies;
  312. }
  313. Array ShapeCast2D::_get_collision_result() const {
  314. Array ret;
  315. for (int i = 0; i < result.size(); ++i) {
  316. const PhysicsDirectSpaceState2D::ShapeRestInfo &sri = result[i];
  317. Dictionary col;
  318. col["point"] = sri.point;
  319. col["normal"] = sri.normal;
  320. col["rid"] = sri.rid;
  321. col["collider"] = ObjectDB::get_instance(sri.collider_id);
  322. col["collider_id"] = sri.collider_id;
  323. col["shape"] = sri.shape;
  324. col["linear_velocity"] = sri.linear_velocity;
  325. ret.push_back(col);
  326. }
  327. return ret;
  328. }
  329. TypedArray<String> ShapeCast2D::get_configuration_warnings() const {
  330. TypedArray<String> warnings = Node2D::get_configuration_warnings();
  331. if (shape.is_null()) {
  332. warnings.push_back(RTR("This node cannot interact with other objects unless a Shape2D is assigned."));
  333. }
  334. return warnings;
  335. }
  336. void ShapeCast2D::_bind_methods() {
  337. ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &ShapeCast2D::set_enabled);
  338. ClassDB::bind_method(D_METHOD("is_enabled"), &ShapeCast2D::is_enabled);
  339. ClassDB::bind_method(D_METHOD("set_shape", "shape"), &ShapeCast2D::set_shape);
  340. ClassDB::bind_method(D_METHOD("get_shape"), &ShapeCast2D::get_shape);
  341. ClassDB::bind_method(D_METHOD("set_target_position", "local_point"), &ShapeCast2D::set_target_position);
  342. ClassDB::bind_method(D_METHOD("get_target_position"), &ShapeCast2D::get_target_position);
  343. ClassDB::bind_method(D_METHOD("set_margin", "margin"), &ShapeCast2D::set_margin);
  344. ClassDB::bind_method(D_METHOD("get_margin"), &ShapeCast2D::get_margin);
  345. ClassDB::bind_method(D_METHOD("set_max_results", "max_results"), &ShapeCast2D::set_max_results);
  346. ClassDB::bind_method(D_METHOD("get_max_results"), &ShapeCast2D::get_max_results);
  347. ClassDB::bind_method(D_METHOD("is_colliding"), &ShapeCast2D::is_colliding);
  348. ClassDB::bind_method(D_METHOD("get_collision_count"), &ShapeCast2D::get_collision_count);
  349. ClassDB::bind_method(D_METHOD("force_shapecast_update"), &ShapeCast2D::force_shapecast_update);
  350. ClassDB::bind_method(D_METHOD("get_collider", "index"), &ShapeCast2D::get_collider);
  351. ClassDB::bind_method(D_METHOD("get_collider_shape", "index"), &ShapeCast2D::get_collider_shape);
  352. ClassDB::bind_method(D_METHOD("get_collision_point", "index"), &ShapeCast2D::get_collision_point);
  353. ClassDB::bind_method(D_METHOD("get_collision_normal", "index"), &ShapeCast2D::get_collision_normal);
  354. ClassDB::bind_method(D_METHOD("get_closest_collision_safe_fraction"), &ShapeCast2D::get_closest_collision_safe_fraction);
  355. ClassDB::bind_method(D_METHOD("get_closest_collision_unsafe_fraction"), &ShapeCast2D::get_closest_collision_unsafe_fraction);
  356. ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &ShapeCast2D::add_exception_rid);
  357. ClassDB::bind_method(D_METHOD("add_exception", "node"), &ShapeCast2D::add_exception);
  358. ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &ShapeCast2D::remove_exception_rid);
  359. ClassDB::bind_method(D_METHOD("remove_exception", "node"), &ShapeCast2D::remove_exception);
  360. ClassDB::bind_method(D_METHOD("clear_exceptions"), &ShapeCast2D::clear_exceptions);
  361. ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &ShapeCast2D::set_collision_mask);
  362. ClassDB::bind_method(D_METHOD("get_collision_mask"), &ShapeCast2D::get_collision_mask);
  363. ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &ShapeCast2D::set_collision_mask_value);
  364. ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &ShapeCast2D::get_collision_mask_value);
  365. ClassDB::bind_method(D_METHOD("set_exclude_parent_body", "mask"), &ShapeCast2D::set_exclude_parent_body);
  366. ClassDB::bind_method(D_METHOD("get_exclude_parent_body"), &ShapeCast2D::get_exclude_parent_body);
  367. ClassDB::bind_method(D_METHOD("set_collide_with_areas", "enable"), &ShapeCast2D::set_collide_with_areas);
  368. ClassDB::bind_method(D_METHOD("is_collide_with_areas_enabled"), &ShapeCast2D::is_collide_with_areas_enabled);
  369. ClassDB::bind_method(D_METHOD("set_collide_with_bodies", "enable"), &ShapeCast2D::set_collide_with_bodies);
  370. ClassDB::bind_method(D_METHOD("is_collide_with_bodies_enabled"), &ShapeCast2D::is_collide_with_bodies_enabled);
  371. ClassDB::bind_method(D_METHOD("_get_collision_result"), &ShapeCast2D::_get_collision_result);
  372. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
  373. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), "set_shape", "get_shape");
  374. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "exclude_parent"), "set_exclude_parent_body", "get_exclude_parent_body");
  375. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "target_position", PROPERTY_HINT_NONE, "suffix:px"), "set_target_position", "get_target_position");
  376. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "margin", PROPERTY_HINT_RANGE, "0,100,0.01,suffix:px"), "set_margin", "get_margin");
  377. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_results"), "set_max_results", "get_max_results");
  378. ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask");
  379. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "collision_result", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "", "_get_collision_result");
  380. ADD_GROUP("Collide With", "collide_with");
  381. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_areas", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collide_with_areas", "is_collide_with_areas_enabled");
  382. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_bodies", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collide_with_bodies", "is_collide_with_bodies_enabled");
  383. }