shape_cast_2d.cpp 18 KB

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