diff options
Diffstat (limited to 'core/math')
-rw-r--r-- | core/math/SCsub | 33 | ||||
-rw-r--r-- | core/math/a_star.cpp | 281 | ||||
-rw-r--r-- | core/math/a_star.h | 41 | ||||
-rw-r--r-- | core/math/basis.cpp | 7 | ||||
-rw-r--r-- | core/math/basis.h | 8 | ||||
-rw-r--r-- | core/math/bsp_tree.h | 4 | ||||
-rw-r--r-- | core/math/camera_matrix.h | 4 | ||||
-rw-r--r-- | core/math/crypto_core.cpp | 157 | ||||
-rw-r--r-- | core/math/delaunay.h | 4 | ||||
-rw-r--r-- | core/math/disjoint_set.cpp (renamed from core/math/crypto_core.h) | 63 | ||||
-rw-r--r-- | core/math/disjoint_set.h | 155 | ||||
-rw-r--r-- | core/math/expression.cpp | 11 | ||||
-rw-r--r-- | core/math/geometry.cpp | 151 | ||||
-rw-r--r-- | core/math/geometry.h | 224 | ||||
-rw-r--r-- | core/math/math_funcs.cpp | 2 | ||||
-rw-r--r-- | core/math/math_funcs.h | 22 | ||||
-rw-r--r-- | core/math/octree.h | 9 | ||||
-rw-r--r-- | core/math/quat.h | 4 | ||||
-rw-r--r-- | core/math/rect2.h | 4 | ||||
-rw-r--r-- | core/math/transform.cpp | 5 | ||||
-rw-r--r-- | core/math/transform.h | 76 | ||||
-rw-r--r-- | core/math/transform_2d.h | 31 | ||||
-rw-r--r-- | core/math/vector2.cpp | 13 | ||||
-rw-r--r-- | core/math/vector2.h | 24 | ||||
-rw-r--r-- | core/math/vector3.cpp | 15 | ||||
-rw-r--r-- | core/math/vector3.h | 62 |
26 files changed, 721 insertions, 689 deletions
diff --git a/core/math/SCsub b/core/math/SCsub index 0995298a4b..be438fcfbe 100644 --- a/core/math/SCsub +++ b/core/math/SCsub @@ -2,37 +2,6 @@ Import('env') -env_math = env.Clone() # Maybe make one specific for crypto? - -is_builtin = env["builtin_mbedtls"] -has_module = env["module_mbedtls_enabled"] - -if is_builtin or not has_module: - # Use our headers for builtin or if the module is not going to be compiled. - # We decided not to depend on system mbedtls just for these few files that can - # be easily extracted. - env_math.Prepend(CPPPATH=["#thirdparty/mbedtls/include"]) - -# MbedTLS core functions (for CryptoCore). -# If the mbedtls module is compiled we don't need to add the .c files with our -# custom config since they will be built by the module itself. -# Only if the module is not enabled, we must compile here the required sources -# to make a "light" build with only the necessary mbedtls files. -if not has_module: - env_thirdparty = env_math.Clone() - env_thirdparty.disable_warnings() - # Custom config file - env_thirdparty.Append(CPPDEFINES=[('MBEDTLS_CONFIG_FILE', '\\"thirdparty/mbedtls/include/godot_core_mbedtls_config.h\\"')]) - thirdparty_mbedtls_dir = "#thirdparty/mbedtls/library/" - thirdparty_mbedtls_sources = [ - "aes.c", - "base64.c", - "md5.c", - "sha1.c", - "sha256.c", - "godot_core_mbedtls_platform.c" - ] - thirdparty_mbedtls_sources = [thirdparty_mbedtls_dir + file for file in thirdparty_mbedtls_sources] - env_thirdparty.add_source_files(env.core_sources, thirdparty_mbedtls_sources) +env_math = env.Clone() env_math.add_source_files(env.core_sources, "*.cpp") diff --git a/core/math/a_star.cpp b/core/math/a_star.cpp index b61119d8df..ae2b56e7b7 100644 --- a/core/math/a_star.cpp +++ b/core/math/a_star.cpp @@ -40,7 +40,17 @@ int AStar::get_available_point_id() const { return 1; } - return points.back()->key() + 1; + // calculate our new next available point id if bigger than before or next id already contained in set of points. + if (points.has(last_free_id)) { + int cur_new_id = last_free_id; + while (points.has(cur_new_id)) { + cur_new_id++; + } + int &non_const = const_cast<int &>(last_free_id); + non_const = cur_new_id; + } + + return last_free_id; } void AStar::add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale) { @@ -48,7 +58,10 @@ void AStar::add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale) { ERR_FAIL_COND(p_id < 0); ERR_FAIL_COND(p_weight_scale < 1); - if (!points.has(p_id)) { + Point *found_pt; + bool p_exists = points.lookup(p_id, found_pt); + + if (!p_exists) { Point *pt = memnew(Point); pt->id = p_id; pt->pos = p_pos; @@ -57,84 +70,98 @@ void AStar::add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale) { pt->open_pass = 0; pt->closed_pass = 0; pt->enabled = true; - points[p_id] = pt; + points.set(p_id, pt); } else { - points[p_id]->pos = p_pos; - points[p_id]->weight_scale = p_weight_scale; + found_pt->pos = p_pos; + found_pt->weight_scale = p_weight_scale; } } Vector3 AStar::get_point_position(int p_id) const { - ERR_FAIL_COND_V(!points.has(p_id), Vector3()); + Point *p; + bool p_exists = points.lookup(p_id, p); + ERR_FAIL_COND_V(!p_exists, Vector3()); - return points[p_id]->pos; + return p->pos; } void AStar::set_point_position(int p_id, const Vector3 &p_pos) { - ERR_FAIL_COND(!points.has(p_id)); + Point *p; + bool p_exists = points.lookup(p_id, p); + ERR_FAIL_COND(!p_exists); - points[p_id]->pos = p_pos; + p->pos = p_pos; } real_t AStar::get_point_weight_scale(int p_id) const { - ERR_FAIL_COND_V(!points.has(p_id), 0); + Point *p; + bool p_exists = points.lookup(p_id, p); + ERR_FAIL_COND_V(!p_exists, 0); - return points[p_id]->weight_scale; + return p->weight_scale; } void AStar::set_point_weight_scale(int p_id, real_t p_weight_scale) { - ERR_FAIL_COND(!points.has(p_id)); + Point *p; + bool p_exists = points.lookup(p_id, p); + ERR_FAIL_COND(!p_exists); ERR_FAIL_COND(p_weight_scale < 1); - points[p_id]->weight_scale = p_weight_scale; + p->weight_scale = p_weight_scale; } void AStar::remove_point(int p_id) { - ERR_FAIL_COND(!points.has(p_id)); - - Point *p = points[p_id]; + Point *p; + bool p_exists = points.lookup(p_id, p); + ERR_FAIL_COND(!p_exists); - for (Set<Point *>::Element *E = p->neighbours.front(); E; E = E->next()) { + for (OAHashMap<int, Point *>::Iterator it = p->neighbours.iter(); it.valid; it = p->neighbours.next_iter(it)) { - Segment s(p_id, E->get()->id); + Segment s(p_id, (*it.key)); segments.erase(s); - E->get()->neighbours.erase(p); - E->get()->unlinked_neighbours.erase(p); + (*it.value)->neighbours.remove(p->id); + (*it.value)->unlinked_neighbours.remove(p->id); } - for (Set<Point *>::Element *E = p->unlinked_neighbours.front(); E; E = E->next()) { + for (OAHashMap<int, Point *>::Iterator it = p->unlinked_neighbours.iter(); it.valid; it = p->unlinked_neighbours.next_iter(it)) { - Segment s(p_id, E->get()->id); + Segment s(p_id, (*it.key)); segments.erase(s); - E->get()->neighbours.erase(p); - E->get()->unlinked_neighbours.erase(p); + (*it.value)->neighbours.remove(p->id); + (*it.value)->unlinked_neighbours.remove(p->id); } memdelete(p); - points.erase(p_id); + points.remove(p_id); + last_free_id = p_id; } void AStar::connect_points(int p_id, int p_with_id, bool bidirectional) { - ERR_FAIL_COND(!points.has(p_id)); - ERR_FAIL_COND(!points.has(p_with_id)); ERR_FAIL_COND(p_id == p_with_id); - Point *a = points[p_id]; - Point *b = points[p_with_id]; - a->neighbours.insert(b); + Point *a; + bool from_exists = points.lookup(p_id, a); + ERR_FAIL_COND(!from_exists); + + Point *b; + bool to_exists = points.lookup(p_with_id, b); + ERR_FAIL_COND(!to_exists); - if (bidirectional) - b->neighbours.insert(a); - else - b->unlinked_neighbours.insert(a); + a->neighbours.set(b->id, b); + + if (bidirectional) { + b->neighbours.set(a->id, a); + } else { + b->unlinked_neighbours.set(a->id, a); + } Segment s(p_id, p_with_id); if (s.from == p_id) { @@ -147,6 +174,7 @@ void AStar::connect_points(int p_id, int p_with_id, bool bidirectional) { segments.insert(s); } + void AStar::disconnect_points(int p_id, int p_with_id) { Segment s(p_id, p_with_id); @@ -154,12 +182,18 @@ void AStar::disconnect_points(int p_id, int p_with_id) { segments.erase(s); - Point *a = points[p_id]; - Point *b = points[p_with_id]; - a->neighbours.erase(b); - a->unlinked_neighbours.erase(b); - b->neighbours.erase(a); - b->unlinked_neighbours.erase(a); + Point *a; + bool a_exists = points.lookup(p_id, a); + CRASH_COND(!a_exists); + + Point *b; + bool b_exists = points.lookup(p_with_id, b); + CRASH_COND(!b_exists); + + a->neighbours.remove(b->id); + a->unlinked_neighbours.remove(b->id); + b->neighbours.remove(a->id); + b->unlinked_neighbours.remove(a->id); } bool AStar::has_point(int p_id) const { @@ -171,8 +205,8 @@ Array AStar::get_points() { Array point_list; - for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) { - point_list.push_back(E->key()); + for (OAHashMap<int, Point *>::Iterator it = points.iter(); it.valid; it = points.next_iter(it)) { + point_list.push_back(*(it.key)); } return point_list; @@ -180,14 +214,14 @@ Array AStar::get_points() { PoolVector<int> AStar::get_point_connections(int p_id) { - ERR_FAIL_COND_V(!points.has(p_id), PoolVector<int>()); + Point *p; + bool p_exists = points.lookup(p_id, p); + ERR_FAIL_COND_V(!p_exists, PoolVector<int>()); PoolVector<int> point_list; - Point *p = points[p_id]; - - for (Set<Point *>::Element *E = p->neighbours.front(); E; E = E->next()) { - point_list.push_back(E->get()->id); + for (OAHashMap<int, Point *>::Iterator it = p->neighbours.iter(); it.valid; it = p->neighbours.next_iter(it)) { + point_list.push_back((*it.key)); } return point_list; @@ -201,27 +235,41 @@ bool AStar::are_points_connected(int p_id, int p_with_id) const { void AStar::clear() { - for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) { - - memdelete(E->get()); + last_free_id = 0; + for (OAHashMap<int, Point *>::Iterator it = points.iter(); it.valid; it = points.next_iter(it)) { + memdelete(*(it.value)); } segments.clear(); points.clear(); } -int AStar::get_closest_point(const Vector3 &p_point) const { +int AStar::get_point_count() const { + return points.get_num_elements(); +} + +int AStar::get_point_capacity() const { + return points.get_capacity(); +} + +void AStar::reserve_space(int p_num_nodes) { + ERR_FAIL_COND_MSG(p_num_nodes <= 0, "New capacity must be greater than 0, was: " + itos(p_num_nodes) + "."); + ERR_FAIL_COND_MSG((uint32_t)p_num_nodes < points.get_capacity(), "New capacity must be greater than current capacity: " + itos(points.get_capacity()) + ", new was: " + itos(p_num_nodes) + "."); + points.reserve(p_num_nodes); +} + +int AStar::get_closest_point(const Vector3 &p_point, bool p_include_disabled) const { int closest_id = -1; real_t closest_dist = 1e20; - for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) { + for (OAHashMap<int, Point *>::Iterator it = points.iter(); it.valid; it = points.next_iter(it)) { + + if (!p_include_disabled && !(*it.value)->enabled) continue; // Disabled points should not be considered. - if (!E->get()->enabled) - continue; //Disabled points should not be considered - real_t d = p_point.distance_squared_to(E->get()->pos); + real_t d = p_point.distance_squared_to((*it.value)->pos); if (closest_id < 0 || d < closest_dist) { closest_dist = d; - closest_id = E->key(); + closest_id = *(it.key); } } @@ -230,8 +278,8 @@ int AStar::get_closest_point(const Vector3 &p_point) const { Vector3 AStar::get_closest_position_in_segment(const Vector3 &p_point) const { - real_t closest_dist = 1e20; bool found = false; + real_t closest_dist = 1e20; Vector3 closest_point; for (const Set<Segment>::Element *E = segments.front(); E; E = E->next()) { @@ -262,8 +310,7 @@ bool AStar::_solve(Point *begin_point, Point *end_point) { pass++; - if (!end_point->enabled) - return false; + if (!end_point->enabled) return false; bool found_route = false; @@ -272,13 +319,9 @@ bool AStar::_solve(Point *begin_point, Point *end_point) { begin_point->g_score = 0; begin_point->f_score = _estimate_cost(begin_point->id, end_point->id); - open_list.push_back(begin_point); - while (true) { - - if (open_list.size() == 0) // No path found - break; + while (!open_list.empty()) { Point *p = open_list[0]; // The currently processed point @@ -291,24 +334,23 @@ bool AStar::_solve(Point *begin_point, Point *end_point) { open_list.remove(open_list.size() - 1); p->closed_pass = pass; // Mark the point as closed - for (Set<Point *>::Element *E = p->neighbours.front(); E; E = E->next()) { + for (OAHashMap<int, Point *>::Iterator it = p->neighbours.iter(); it.valid; it = p->neighbours.next_iter(it)) { - Point *e = E->get(); // The neighbour point + Point *e = *(it.value); // The neighbour point - if (!e->enabled || e->closed_pass == pass) + if (!e->enabled || e->closed_pass == pass) { continue; + } real_t tentative_g_score = p->g_score + _compute_cost(p->id, e->id) * e->weight_scale; bool new_point = false; - if (e->open_pass != pass) { // The point wasn't inside the open list - + if (e->open_pass != pass) { // The point wasn't inside the open list. e->open_pass = pass; open_list.push_back(e); new_point = true; - } else if (tentative_g_score >= e->g_score) { // The new path is worse than the previous - + } else if (tentative_g_score >= e->g_score) { // The new path is worse than the previous. continue; } @@ -316,10 +358,11 @@ bool AStar::_solve(Point *begin_point, Point *end_point) { e->g_score = tentative_g_score; e->f_score = e->g_score + _estimate_cost(e->id, end_point->id); - if (new_point) // The position of the new points is already known + if (new_point) { // The position of the new points is already known. sorter.push_heap(0, open_list.size() - 1, 0, e, open_list.ptrw()); - else + } else { sorter.push_heap(0, open_list.find(e), 0, e, open_list.ptrw()); + } } } @@ -331,7 +374,15 @@ float AStar::_estimate_cost(int p_from_id, int p_to_id) { if (get_script_instance() && get_script_instance()->has_method(SceneStringNames::get_singleton()->_estimate_cost)) return get_script_instance()->call(SceneStringNames::get_singleton()->_estimate_cost, p_from_id, p_to_id); - return points[p_from_id]->pos.distance_to(points[p_to_id]->pos); + Point *from_point; + bool from_exists = points.lookup(p_from_id, from_point); + CRASH_COND(!from_exists); + + Point *to_point; + bool to_exists = points.lookup(p_to_id, to_point); + CRASH_COND(!to_exists); + + return from_point->pos.distance_to(to_point->pos); } float AStar::_compute_cost(int p_from_id, int p_to_id) { @@ -339,16 +390,26 @@ float AStar::_compute_cost(int p_from_id, int p_to_id) { if (get_script_instance() && get_script_instance()->has_method(SceneStringNames::get_singleton()->_compute_cost)) return get_script_instance()->call(SceneStringNames::get_singleton()->_compute_cost, p_from_id, p_to_id); - return points[p_from_id]->pos.distance_to(points[p_to_id]->pos); + Point *from_point; + bool from_exists = points.lookup(p_from_id, from_point); + CRASH_COND(!from_exists); + + Point *to_point; + bool to_exists = points.lookup(p_to_id, to_point); + CRASH_COND(!to_exists); + + return from_point->pos.distance_to(to_point->pos); } PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) { - ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector<Vector3>()); - ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector<Vector3>()); + Point *a; + bool from_exists = points.lookup(p_from_id, a); + ERR_FAIL_COND_V(!from_exists, PoolVector<Vector3>()); - Point *a = points[p_from_id]; - Point *b = points[p_to_id]; + Point *b; + bool to_exists = points.lookup(p_to_id, b); + ERR_FAIL_COND_V(!to_exists, PoolVector<Vector3>()); if (a == b) { PoolVector<Vector3> ret; @@ -360,11 +421,8 @@ PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) { Point *end_point = b; bool found_route = _solve(begin_point, end_point); + if (!found_route) return PoolVector<Vector3>(); - if (!found_route) - return PoolVector<Vector3>(); - - // Midpoints Point *p = end_point; int pc = 1; // Begin point while (p != begin_point) { @@ -393,11 +451,13 @@ PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) { PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) { - ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector<int>()); - ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector<int>()); + Point *a; + bool from_exists = points.lookup(p_from_id, a); + ERR_FAIL_COND_V(!from_exists, PoolVector<int>()); - Point *a = points[p_from_id]; - Point *b = points[p_to_id]; + Point *b; + bool to_exists = points.lookup(p_to_id, b); + ERR_FAIL_COND_V(!to_exists, PoolVector<int>()); if (a == b) { PoolVector<int> ret; @@ -409,11 +469,8 @@ PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) { Point *end_point = b; bool found_route = _solve(begin_point, end_point); + if (!found_route) return PoolVector<int>(); - if (!found_route) - return PoolVector<int>(); - - // Midpoints Point *p = end_point; int pc = 1; // Begin point while (p != begin_point) { @@ -442,16 +499,20 @@ PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) { void AStar::set_point_disabled(int p_id, bool p_disabled) { - ERR_FAIL_COND(!points.has(p_id)); + Point *p; + bool p_exists = points.lookup(p_id, p); + ERR_FAIL_COND(!p_exists); - points[p_id]->enabled = !p_disabled; + p->enabled = !p_disabled; } bool AStar::is_point_disabled(int p_id) const { - ERR_FAIL_COND_V(!points.has(p_id), false); + Point *p; + bool p_exists = points.lookup(p_id, p); + ERR_FAIL_COND_V(!p_exists, false); - return !points[p_id]->enabled; + return !p->enabled; } void AStar::_bind_methods() { @@ -474,9 +535,12 @@ void AStar::_bind_methods() { ClassDB::bind_method(D_METHOD("disconnect_points", "id", "to_id"), &AStar::disconnect_points); ClassDB::bind_method(D_METHOD("are_points_connected", "id", "to_id"), &AStar::are_points_connected); + ClassDB::bind_method(D_METHOD("get_point_count"), &AStar::get_point_count); + ClassDB::bind_method(D_METHOD("get_point_capacity"), &AStar::get_point_capacity); + ClassDB::bind_method(D_METHOD("reserve_space", "num_nodes"), &AStar::reserve_space); ClassDB::bind_method(D_METHOD("clear"), &AStar::clear); - ClassDB::bind_method(D_METHOD("get_closest_point", "to_position"), &AStar::get_closest_point); + ClassDB::bind_method(D_METHOD("get_closest_point", "to_position", "include_disabled"), &AStar::get_closest_point, DEFVAL(false)); ClassDB::bind_method(D_METHOD("get_closest_position_in_segment", "to_position"), &AStar::get_closest_position_in_segment); ClassDB::bind_method(D_METHOD("get_point_path", "from_id", "to_id"), &AStar::get_point_path); @@ -487,13 +551,11 @@ void AStar::_bind_methods() { } AStar::AStar() { - + last_free_id = 0; pass = 1; } AStar::~AStar() { - - pass = 1; clear(); } @@ -560,12 +622,24 @@ bool AStar2D::are_points_connected(int p_id, int p_with_id) const { return astar.are_points_connected(p_id, p_with_id); } +int AStar2D::get_point_count() const { + return astar.get_point_count(); +} + +int AStar2D::get_point_capacity() const { + return astar.get_point_capacity(); +} + void AStar2D::clear() { astar.clear(); } -int AStar2D::get_closest_point(const Vector2 &p_point) const { - return astar.get_closest_point(Vector3(p_point.x, p_point.y, 0)); +void AStar2D::reserve_space(int p_num_nodes) { + astar.reserve_space(p_num_nodes); +} + +int AStar2D::get_closest_point(const Vector2 &p_point, bool p_include_disabled) const { + return astar.get_closest_point(Vector3(p_point.x, p_point.y, 0), p_include_disabled); } Vector2 AStar2D::get_closest_position_in_segment(const Vector2 &p_point) const { @@ -614,9 +688,12 @@ void AStar2D::_bind_methods() { ClassDB::bind_method(D_METHOD("disconnect_points", "id", "to_id"), &AStar2D::disconnect_points); ClassDB::bind_method(D_METHOD("are_points_connected", "id", "to_id"), &AStar2D::are_points_connected); + ClassDB::bind_method(D_METHOD("get_point_count"), &AStar2D::get_point_count); + ClassDB::bind_method(D_METHOD("get_point_capacity"), &AStar2D::get_point_capacity); + ClassDB::bind_method(D_METHOD("reserve_space", "num_nodes"), &AStar2D::reserve_space); ClassDB::bind_method(D_METHOD("clear"), &AStar2D::clear); - ClassDB::bind_method(D_METHOD("get_closest_point", "to_position"), &AStar2D::get_closest_point); + ClassDB::bind_method(D_METHOD("get_closest_point", "to_position", "include_disabled"), &AStar2D::get_closest_point, DEFVAL(false)); ClassDB::bind_method(D_METHOD("get_closest_position_in_segment", "to_position"), &AStar2D::get_closest_position_in_segment); ClassDB::bind_method(D_METHOD("get_point_path", "from_id", "to_id"), &AStar2D::get_point_path); diff --git a/core/math/a_star.h b/core/math/a_star.h index ec333efc1d..0a5d3e992c 100644 --- a/core/math/a_star.h +++ b/core/math/a_star.h @@ -31,8 +31,8 @@ #ifndef ASTAR_H #define ASTAR_H +#include "core/oa_hash_map.h" #include "core/reference.h" -#include "core/self_list.h" /** A* pathfinding algorithm @@ -44,19 +44,21 @@ class AStar : public Reference { GDCLASS(AStar, Reference); - uint64_t pass; - struct Point { + Point() : + neighbours(4u), + unlinked_neighbours(4u) {} + int id; Vector3 pos; real_t weight_scale; bool enabled; - Set<Point *> neighbours; - Set<Point *> unlinked_neighbours; + OAHashMap<int, Point *> neighbours; + OAHashMap<int, Point *> unlinked_neighbours; - // Used for pathfinding + // Used for pathfinding. Point *prev_point; real_t g_score; real_t f_score; @@ -64,16 +66,15 @@ class AStar : public Reference { uint64_t closed_pass; }; - Map<int, Point *> points; - struct SortPoints { - _FORCE_INLINE_ bool operator()(const Point *A, const Point *B) const { // Returns true when the Point A is worse than Point B - if (A->f_score > B->f_score) + _FORCE_INLINE_ bool operator()(const Point *A, const Point *B) const { // Returns true when the Point A is worse than Point B. + if (A->f_score > B->f_score) { return true; - else if (A->f_score < B->f_score) + } else if (A->f_score < B->f_score) { return false; - else - return A->g_score < B->g_score; // If the f_costs are the same then prioritize the points that are further away from the start + } else { + return A->g_score < B->g_score; // If the f_costs are the same then prioritize the points that are further away from the start. + } } }; @@ -101,6 +102,10 @@ class AStar : public Reference { } }; + int last_free_id; + uint64_t pass; + + OAHashMap<int, Point *> points; Set<Segment> segments; bool _solve(Point *begin_point, Point *end_point); @@ -131,9 +136,12 @@ public: void disconnect_points(int p_id, int p_with_id); bool are_points_connected(int p_id, int p_with_id) const; + int get_point_count() const; + int get_point_capacity() const; + void reserve_space(int p_num_nodes); void clear(); - int get_closest_point(const Vector3 &p_point) const; + int get_closest_point(const Vector3 &p_point, bool p_include_disabled = false) const; Vector3 get_closest_position_in_segment(const Vector3 &p_point) const; PoolVector<Vector3> get_point_path(int p_from_id, int p_to_id); @@ -170,9 +178,12 @@ public: void disconnect_points(int p_id, int p_with_id); bool are_points_connected(int p_id, int p_with_id) const; + int get_point_count() const; + int get_point_capacity() const; + void reserve_space(int p_num_nodes); void clear(); - int get_closest_point(const Vector2 &p_point) const; + int get_closest_point(const Vector2 &p_point, bool p_include_disabled = false) const; Vector2 get_closest_position_in_segment(const Vector2 &p_point) const; PoolVector<Vector2> get_point_path(int p_from_id, int p_to_id); diff --git a/core/math/basis.cpp b/core/math/basis.cpp index 400f342018..0a491010e2 100644 --- a/core/math/basis.cpp +++ b/core/math/basis.cpp @@ -618,10 +618,7 @@ Basis::operator String() const { Quat Basis::get_quat() const { #ifdef MATH_CHECKS - if (!is_rotation()) { - ERR_EXPLAIN("Basis must be normalized in order to be casted to a Quaternion. Use get_rotation_quat() or call orthonormalized() instead."); - ERR_FAIL_V(Quat()); - } + ERR_FAIL_COND_V_MSG(!is_rotation(), Quat(), "Basis must be normalized in order to be casted to a Quaternion. Use get_rotation_quat() or call orthonormalized() instead."); #endif /* Allow getting a quaternion from an unnormalized transform */ Basis m = *this; @@ -810,7 +807,7 @@ void Basis::set_quat(const Quat &p_quat) { void Basis::set_axis_angle(const Vector3 &p_axis, real_t p_phi) { // Rotation matrix from axis and angle, see https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_angle #ifdef MATH_CHECKS - ERR_FAIL_COND(!p_axis.is_normalized()); + ERR_FAIL_COND_MSG(!p_axis.is_normalized(), "Axis must be normalized."); #endif Vector3 axis_sq(p_axis.x * p_axis.x, p_axis.y * p_axis.y, p_axis.z * p_axis.z); real_t cosine = Math::cos(p_phi); diff --git a/core/math/basis.h b/core/math/basis.h index d3adad3d90..4be4ea4cd3 100644 --- a/core/math/basis.h +++ b/core/math/basis.h @@ -28,17 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -// Circular dependency between Vector3 and Basis :/ -#include "core/math/vector3.h" - #ifndef BASIS_H #define BASIS_H #include "core/math/quat.h" - -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ +#include "core/math/vector3.h" class Basis { public: diff --git a/core/math/bsp_tree.h b/core/math/bsp_tree.h index a7a3697990..90b5e8322a 100644 --- a/core/math/bsp_tree.h +++ b/core/math/bsp_tree.h @@ -38,9 +38,7 @@ #include "core/pool_vector.h" #include "core/variant.h" #include "core/vector.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ + class BSP_Tree { public: enum { diff --git a/core/math/camera_matrix.h b/core/math/camera_matrix.h index 3bcf48f5da..63cc88553d 100644 --- a/core/math/camera_matrix.h +++ b/core/math/camera_matrix.h @@ -34,10 +34,6 @@ #include "core/math/rect2.h" #include "core/math/transform.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ - struct CameraMatrix { enum Planes { diff --git a/core/math/crypto_core.cpp b/core/math/crypto_core.cpp deleted file mode 100644 index d7ba54e469..0000000000 --- a/core/math/crypto_core.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/*************************************************************************/ -/* crypto_core.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "crypto_core.h" - -#include <mbedtls/aes.h> -#include <mbedtls/base64.h> -#include <mbedtls/md5.h> -#include <mbedtls/sha1.h> -#include <mbedtls/sha256.h> - -// MD5 -CryptoCore::MD5Context::MD5Context() { - ctx = memalloc(sizeof(mbedtls_md5_context)); - mbedtls_md5_init((mbedtls_md5_context *)ctx); -} - -CryptoCore::MD5Context::~MD5Context() { - mbedtls_md5_free((mbedtls_md5_context *)ctx); - memfree((mbedtls_md5_context *)ctx); -} - -Error CryptoCore::MD5Context::start() { - int ret = mbedtls_md5_starts_ret((mbedtls_md5_context *)ctx); - return ret ? FAILED : OK; -} - -Error CryptoCore::MD5Context::update(uint8_t *p_src, size_t p_len) { - int ret = mbedtls_md5_update_ret((mbedtls_md5_context *)ctx, p_src, p_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::MD5Context::finish(unsigned char r_hash[16]) { - int ret = mbedtls_md5_finish_ret((mbedtls_md5_context *)ctx, r_hash); - return ret ? FAILED : OK; -} - -// SHA256 -CryptoCore::SHA256Context::SHA256Context() { - ctx = memalloc(sizeof(mbedtls_sha256_context)); - mbedtls_sha256_init((mbedtls_sha256_context *)ctx); -} - -CryptoCore::SHA256Context::~SHA256Context() { - mbedtls_sha256_free((mbedtls_sha256_context *)ctx); - memfree((mbedtls_sha256_context *)ctx); -} - -Error CryptoCore::SHA256Context::start() { - int ret = mbedtls_sha256_starts_ret((mbedtls_sha256_context *)ctx, 0); - return ret ? FAILED : OK; -} - -Error CryptoCore::SHA256Context::update(uint8_t *p_src, size_t p_len) { - int ret = mbedtls_sha256_update_ret((mbedtls_sha256_context *)ctx, p_src, p_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::SHA256Context::finish(unsigned char r_hash[16]) { - int ret = mbedtls_sha256_finish_ret((mbedtls_sha256_context *)ctx, r_hash); - return ret ? FAILED : OK; -} - -// AES256 -CryptoCore::AESContext::AESContext() { - ctx = memalloc(sizeof(mbedtls_aes_context)); - mbedtls_aes_init((mbedtls_aes_context *)ctx); -} - -CryptoCore::AESContext::~AESContext() { - mbedtls_aes_free((mbedtls_aes_context *)ctx); - memfree((mbedtls_aes_context *)ctx); -} - -Error CryptoCore::AESContext::set_encode_key(const uint8_t *p_key, size_t p_bits) { - int ret = mbedtls_aes_setkey_enc((mbedtls_aes_context *)ctx, p_key, p_bits); - return ret ? FAILED : OK; -} - -Error CryptoCore::AESContext::set_decode_key(const uint8_t *p_key, size_t p_bits) { - int ret = mbedtls_aes_setkey_dec((mbedtls_aes_context *)ctx, p_key, p_bits); - return ret ? FAILED : OK; -} - -Error CryptoCore::AESContext::encrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]) { - int ret = mbedtls_aes_crypt_ecb((mbedtls_aes_context *)ctx, MBEDTLS_AES_ENCRYPT, p_src, r_dst); - return ret ? FAILED : OK; -} - -Error CryptoCore::AESContext::decrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]) { - int ret = mbedtls_aes_crypt_ecb((mbedtls_aes_context *)ctx, MBEDTLS_AES_DECRYPT, p_src, r_dst); - return ret ? FAILED : OK; -} - -// CryptoCore -String CryptoCore::b64_encode_str(const uint8_t *p_src, int p_src_len) { - int b64len = p_src_len / 3 * 4 + 4 + 1; - PoolVector<uint8_t> b64buff; - b64buff.resize(b64len); - PoolVector<uint8_t>::Write w64 = b64buff.write(); - size_t strlen = 0; - int ret = b64_encode(&w64[0], b64len, &strlen, p_src, p_src_len); - w64[strlen] = 0; - return ret ? String() : (const char *)&w64[0]; -} - -Error CryptoCore::b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) { - int ret = mbedtls_base64_encode(r_dst, p_dst_len, r_len, p_src, p_src_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len) { - int ret = mbedtls_base64_decode(r_dst, p_dst_len, r_len, p_src, p_src_len); - return ret ? FAILED : OK; -} - -Error CryptoCore::md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]) { - int ret = mbedtls_md5_ret(p_src, p_src_len, r_hash); - return ret ? FAILED : OK; -} - -Error CryptoCore::sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]) { - int ret = mbedtls_sha1_ret(p_src, p_src_len, r_hash); - return ret ? FAILED : OK; -} - -Error CryptoCore::sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]) { - int ret = mbedtls_sha256_ret(p_src, p_src_len, r_hash, 0); - return ret ? FAILED : OK; -} diff --git a/core/math/delaunay.h b/core/math/delaunay.h index ed52c506db..3f8013a3e6 100644 --- a/core/math/delaunay.h +++ b/core/math/delaunay.h @@ -80,11 +80,11 @@ public: } static bool edge_compare(const Vector<Vector2> &p_vertices, const Edge &p_a, const Edge &p_b) { - if (Math::is_zero_approx(p_vertices[p_a.edge[0]].distance_to(p_vertices[p_b.edge[0]])) && Math::is_zero_approx(p_vertices[p_a.edge[1]].distance_to(p_vertices[p_b.edge[1]]))) { + if (p_vertices[p_a.edge[0]] == p_vertices[p_b.edge[0]] && p_vertices[p_a.edge[1]] == p_vertices[p_b.edge[1]]) { return true; } - if (Math::is_zero_approx(p_vertices[p_a.edge[0]].distance_to(p_vertices[p_b.edge[1]])) && Math::is_zero_approx(p_vertices[p_a.edge[1]].distance_to(p_vertices[p_b.edge[0]]))) { + if (p_vertices[p_a.edge[0]] == p_vertices[p_b.edge[1]] && p_vertices[p_a.edge[1]] == p_vertices[p_b.edge[0]]) { return true; } diff --git a/core/math/crypto_core.h b/core/math/disjoint_set.cpp index e28cb5a792..c9d47aa0ae 100644 --- a/core/math/crypto_core.h +++ b/core/math/disjoint_set.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* crypto_core.h */ +/* disjoint_set.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,63 +28,4 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef CRYPTO_CORE_H -#define CRYPTO_CORE_H - -#include "core/reference.h" - -class CryptoCore { - -public: - class MD5Context { - - private: - void *ctx; // To include, or not to include... - - public: - MD5Context(); - ~MD5Context(); - - Error start(); - Error update(uint8_t *p_src, size_t p_len); - Error finish(unsigned char r_hash[16]); - }; - - class SHA256Context { - - private: - void *ctx; // To include, or not to include... - - public: - SHA256Context(); - ~SHA256Context(); - - Error start(); - Error update(uint8_t *p_src, size_t p_len); - Error finish(unsigned char r_hash[16]); - }; - - class AESContext { - - private: - void *ctx; // To include, or not to include... - - public: - AESContext(); - ~AESContext(); - - Error set_encode_key(const uint8_t *p_key, size_t p_bits); - Error set_decode_key(const uint8_t *p_key, size_t p_bits); - Error encrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]); - Error decrypt_ecb(const uint8_t p_src[16], uint8_t r_dst[16]); - }; - - static String b64_encode_str(const uint8_t *p_src, int p_src_len); - static Error b64_encode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len); - static Error b64_decode(uint8_t *r_dst, int p_dst_len, size_t *r_len, const uint8_t *p_src, int p_src_len); - - static Error md5(const uint8_t *p_src, int p_src_len, unsigned char r_hash[16]); - static Error sha1(const uint8_t *p_src, int p_src_len, unsigned char r_hash[20]); - static Error sha256(const uint8_t *p_src, int p_src_len, unsigned char r_hash[32]); -}; -#endif // CRYPTO_CORE_H +#include "disjoint_set.h" diff --git a/core/math/disjoint_set.h b/core/math/disjoint_set.h new file mode 100644 index 0000000000..c9b3d0b65d --- /dev/null +++ b/core/math/disjoint_set.h @@ -0,0 +1,155 @@ +/*************************************************************************/ +/* disjoint_set.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef DISJOINT_SET_H +#define DISJOINT_SET_H + +#include "core/map.h" +#include "core/vector.h" + +/** + @author Marios Staikopoulos <marios@staik.net> +*/ + +/* This DisjointSet class uses Find with path compression and Union by rank */ +template <typename T, class C = Comparator<T>, class AL = DefaultAllocator> +class DisjointSet { + + struct Element { + T object; + Element *parent = nullptr; + int rank = 0; + }; + + typedef Map<T, Element *, C, AL> MapT; + + MapT elements; + + Element *get_parent(Element *element); + + _FORCE_INLINE_ Element *insert_or_get(T object); + +public: + ~DisjointSet(); + + _FORCE_INLINE_ void insert(T object) { (void)insert_or_get(object); } + + void create_union(T a, T b); + + void get_representatives(Vector<T> &out_roots); + + void get_members(Vector<T> &out_members, T representative); +}; + +/* FUNCTIONS */ + +template <typename T, class C, class AL> +DisjointSet<T, C, AL>::~DisjointSet() { + for (typename MapT::Element *itr = elements.front(); itr != nullptr; itr = itr->next()) { + memdelete_allocator<Element, AL>(itr->value()); + } +} + +template <typename T, class C, class AL> +typename DisjointSet<T, C, AL>::Element *DisjointSet<T, C, AL>::get_parent(Element *element) { + if (element->parent != element) { + element->parent = get_parent(element->parent); + } + + return element->parent; +} + +template <typename T, class C, class AL> +typename DisjointSet<T, C, AL>::Element *DisjointSet<T, C, AL>::insert_or_get(T object) { + typename MapT::Element *itr = elements.find(object); + if (itr != nullptr) { + return itr->value(); + } + + Element *new_element = memnew_allocator(Element, AL); + new_element->object = object; + new_element->parent = new_element; + elements.insert(object, new_element); + + return new_element; +} + +template <typename T, class C, class AL> +void DisjointSet<T, C, AL>::create_union(T a, T b) { + + Element *x = insert_or_get(a); + Element *y = insert_or_get(b); + + Element *x_root = get_parent(x); + Element *y_root = get_parent(y); + + // Already in the same set + if (x_root == y_root) + return; + + // Not in the same set, merge + if (x_root->rank < y_root->rank) { + SWAP(x_root, y_root); + } + + // Merge y_root into x_root + y_root->parent = x_root; + if (x_root->rank == y_root->rank) { + ++x_root->rank; + } +} + +template <typename T, class C, class AL> +void DisjointSet<T, C, AL>::get_representatives(Vector<T> &out_representatives) { + for (typename MapT::Element *itr = elements.front(); itr != nullptr; itr = itr->next()) { + Element *element = itr->value(); + if (element->parent == element) { + out_representatives.push_back(element->object); + } + } +} + +template <typename T, class C, class AL> +void DisjointSet<T, C, AL>::get_members(Vector<T> &out_members, T representative) { + typename MapT::Element *rep_itr = elements.find(representative); + ERR_FAIL_COND(rep_itr == nullptr); + + Element *rep_element = rep_itr->value(); + ERR_FAIL_COND(rep_element->parent != rep_element); + + for (typename MapT::Element *itr = elements.front(); itr != nullptr; itr = itr->next()) { + Element *parent = get_parent(itr->value()); + if (parent == rep_element) { + out_members.push_back(itr->key()); + } + } +} + +#endif diff --git a/core/math/expression.cpp b/core/math/expression.cpp index 15eea1d308..46f81ce5c3 100644 --- a/core/math/expression.cpp +++ b/core/math/expression.cpp @@ -2161,10 +2161,8 @@ Error Expression::parse(const String &p_expression, const Vector<String> &p_inpu } Variant Expression::execute(Array p_inputs, Object *p_base, bool p_show_error) { - if (error_set) { - ERR_EXPLAIN("There was previously a parse error: " + error_str); - ERR_FAIL_V(Variant()); - } + + ERR_FAIL_COND_V_MSG(error_set, Variant(), "There was previously a parse error: " + error_str + "."); execution_error = false; Variant output; @@ -2173,10 +2171,7 @@ Variant Expression::execute(Array p_inputs, Object *p_base, bool p_show_error) { if (err) { execution_error = true; error_str = error_txt; - if (p_show_error) { - ERR_EXPLAIN(error_str); - ERR_FAIL_V(Variant()); - } + ERR_FAIL_COND_V_MSG(p_show_error, Variant(), error_str); } return output; diff --git a/core/math/geometry.cpp b/core/math/geometry.cpp index 8314cb827c..e0ead8446f 100644 --- a/core/math/geometry.cpp +++ b/core/math/geometry.cpp @@ -34,9 +34,10 @@ #include "thirdparty/misc/clipper.hpp" #include "thirdparty/misc/triangulator.h" -#define SCALE_FACTOR 100000.0 // based on CMP_EPSILON +#define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON. -/* this implementation is very inefficient, commenting unless bugs happen. See the other one. +// This implementation is very inefficient, commenting unless bugs happen. See the other one. +/* bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) { Vector<int> indices = Geometry::triangulate_polygon(p_polygon); @@ -124,8 +125,8 @@ struct _FaceClassify { }; static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) { - /* connect faces, error will occur if an edge is shared between more than 2 faces */ - /* clear connections */ + // Connect faces, error will occur if an edge is shared between more than 2 faces. + // Clear connections. bool error = false; @@ -195,13 +196,6 @@ static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) { if (p_faces[i].links[j].face == -1) p_faces[i].valid = false; } - /*printf("face %i is valid: %i, group %i. connected to %i:%i,%i:%i,%i:%i\n",i,p_faces[i].valid,p_faces[i].group, - p_faces[i].links[0].face, - p_faces[i].links[0].edge, - p_faces[i].links[1].face, - p_faces[i].links[1].edge, - p_faces[i].links[2].face, - p_faces[i].links[2].edge);*/ } return error; } @@ -247,12 +241,9 @@ PoolVector<PoolVector<Face3> > Geometry::separate_objects(PoolVector<Face3> p_ar bool error = _connect_faces(_fcptr, len, -1); - if (error) { + ERR_FAIL_COND_V_MSG(error, PoolVector<PoolVector<Face3> >(), "Invalid geometry."); - ERR_FAIL_COND_V(error, PoolVector<PoolVector<Face3> >()); // invalid geometry - } - - /* group connected faces in separate objects */ + // Group connected faces in separate objects. int group = 0; for (int i = 0; i < len; i++) { @@ -264,7 +255,7 @@ PoolVector<PoolVector<Face3> > Geometry::separate_objects(PoolVector<Face3> p_ar } } - /* group connected faces in separate objects */ + // Group connected faces in separate objects. for (int i = 0; i < len; i++) { @@ -376,7 +367,7 @@ static inline void _plot_face(uint8_t ***p_cell_status, int x, int y, int z, int static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z) { if (p_cell_status[x][y][z] & 3) - return; // nothing to do, already used and/or visited + return; // Nothing to do, already used and/or visited. p_cell_status[x][y][z] = _CELL_PREV_FIRST; @@ -384,29 +375,20 @@ static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, uint8_t &c = p_cell_status[x][y][z]; - //printf("at %i,%i,%i\n",x,y,z); - if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) { - /* Haven't been in here, mark as outside */ + // Haven't been in here, mark as outside. p_cell_status[x][y][z] |= _CELL_EXTERIOR; - //printf("not marked as anything, marking exterior\n"); } - //printf("cell step is %i\n",(c&_CELL_STEP_MASK)); - if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) { - /* if not done, increase step */ + // If not done, increase step. c += 1 << 2; - //printf("incrementing cell step\n"); } if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) { - /* Go back */ - //printf("done, going back a cell\n"); - + // Go back. switch (c & _CELL_PREV_MASK) { case _CELL_PREV_FIRST: { - //printf("at end, finished marking\n"); return; } break; case _CELL_PREV_Y_POS: { @@ -440,8 +422,6 @@ static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, continue; } - //printf("attempting new cell!\n"); - int next_x = x, next_y = y, next_z = z; uint8_t prev = 0; @@ -475,8 +455,6 @@ static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, default: ERR_FAIL(); } - //printf("testing if new cell will be ok...!\n"); - if (next_x < 0 || next_x >= len_x) continue; if (next_y < 0 || next_y >= len_y) @@ -484,13 +462,9 @@ static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, if (next_z < 0 || next_z >= len_z) continue; - //printf("testing if new cell is traversable\n"); - if (p_cell_status[next_x][next_y][next_z] & 3) continue; - //printf("move to it\n"); - x = next_x; y = next_y; z = next_z; @@ -507,17 +481,6 @@ static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, i if (p_cell_status[x][y][z] & _CELL_EXTERIOR) return; -/* static const Vector3 vertices[8]={ - Vector3(0,0,0), - Vector3(0,0,1), - Vector3(0,1,0), - Vector3(0,1,1), - Vector3(1,0,0), - Vector3(1,0,1), - Vector3(1,1,0), - Vector3(1,1,1), - }; -*/ #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1) static const uint8_t indices[6][4] = { @@ -529,22 +492,6 @@ static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, i { 0, 4, 6, 2 }, }; - /* - - {0,1,2,3}, - {0,1,4,5}, - {0,2,4,6}, - {4,5,6,7}, - {2,3,7,6}, - {1,3,5,7}, - - {0,2,3,1}, - {0,1,5,4}, - {0,4,6,2}, - {7,6,4,5}, - {7,3,2,6}, - {7,5,1,3}, -*/ for (int i = 0; i < 6; i++) { @@ -607,9 +554,9 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e } } - global_aabb.grow_by(0.01); // avoid numerical error + global_aabb.grow_by(0.01); // Avoid numerical error. - // determine amount of cells in grid axis + // Determine amount of cells in grid axis. int div_x, div_y, div_z; if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH) @@ -632,7 +579,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e voxelsize.y /= div_y; voxelsize.z /= div_z; - // create and initialize cells to zero + // Create and initialize cells to zero. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x); for (int i = 0; i < div_x; i++) { @@ -650,7 +597,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e } } - // plot faces into cells + // Plot faces into cells. for (int i = 0; i < face_count; i++) { @@ -662,7 +609,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f); } - // determine which cells connect to the outside by traversing the outside and recursively flood-fill marking + // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking. for (int i = 0; i < div_x; i++) { @@ -691,7 +638,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e } } - // build faces for the inside-outside cell divisors + // Build faces for the inside-outside cell divisors. PoolVector<Face3> wrapped_faces; @@ -706,7 +653,7 @@ PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_e } } - // transform face vertices to global coords + // Transform face vertices to global coords. int wrapped_faces_count = wrapped_faces.size(); PoolVector<Face3>::Write wrapped_facesw = wrapped_faces.write(); @@ -753,7 +700,7 @@ Vector<Vector<Vector2> > Geometry::decompose_polygon_in_convex(Vector<Point2> po inp.SetOrientation(TRIANGULATOR_CCW); in_poly.push_back(inp); TriangulatorPartition tpart; - if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { //failed! + if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed. ERR_PRINT("Convex decomposing failed!"); return decomp; } @@ -765,7 +712,7 @@ Vector<Vector<Vector2> > Geometry::decompose_polygon_in_convex(Vector<Point2> po decomp.write[idx].resize(tp.GetNumPoints()); - for (int i = 0; i < tp.GetNumPoints(); i++) { + for (int64_t i = 0; i < tp.GetNumPoints(); i++) { decomp.write[idx].write[i] = tp.GetPoint(i); } @@ -781,7 +728,7 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes #define SUBPLANE_SIZE 1024.0 - real_t subplane_size = 1024.0; // should compute this from the actual plane + real_t subplane_size = 1024.0; // Should compute this from the actual plane. for (int i = 0; i < p_planes.size(); i++) { Plane p = p_planes[i]; @@ -789,7 +736,7 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes Vector3 ref = Vector3(0.0, 1.0, 0.0); if (ABS(p.normal.dot(ref)) > 0.95) - ref = Vector3(0.0, 0.0, 1.0); // change axis + ref = Vector3(0.0, 0.0, 1.0); // Change axis. Vector3 right = p.normal.cross(ref).normalized(); Vector3 up = p.normal.cross(right).normalized(); @@ -827,20 +774,20 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes real_t dist0 = clip.distance_to(edge0_A); real_t dist1 = clip.distance_to(edge1_A); - if (dist0 <= 0) { // behind plane + if (dist0 <= 0) { // Behind plane. new_vertices.push_back(vertices[k]); } - // check for different sides and non coplanar + // Check for different sides and non coplanar. if ((dist0 * dist1) < 0) { - // calculate intersection + // Calculate intersection. Vector3 rel = edge1_A - edge0_A; real_t den = clip.normal.dot(rel); if (Math::is_zero_approx(den)) - continue; // point too short + continue; // Point too short. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den; Vector3 inters = edge0_A + rel * dist; @@ -854,11 +801,11 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes if (vertices.size() < 3) continue; - //result is a clockwise face + // Result is a clockwise face. MeshData::Face face; - // add face indices + // Add face indices. for (int j = 0; j < vertices.size(); j++) { int idx = -1; @@ -882,7 +829,7 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes face.plane = p; mesh.faces.push_back(face); - //add edge + // Add edge. for (int j = 0; j < face.indices.size(); j++) { @@ -972,7 +919,7 @@ PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int for (int j = 1; j <= p_lats; j++) { - //todo this is stupid, fix + // FIXME: This is stupid. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized(); Vector3 pos = angle * p_radius; planes.push_back(Plane(pos, angle)); @@ -1032,12 +979,12 @@ struct _AtlasWorkRectResult { void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) { - //super simple, almost brute force scanline stacking fitter - //it's pretty basic for now, but it tries to make sure that the aspect ratio of the - //resulting atlas is somehow square. This is necessary because video cards have limits - //on texture size (usually 2048 or 4096), so the more square a texture, the more chances - //it will work in every hardware. - // for example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a + // Super simple, almost brute force scanline stacking fitter. + // It's pretty basic for now, but it tries to make sure that the aspect ratio of the + // resulting atlas is somehow square. This is necessary because video cards have limits. + // On texture size (usually 2048 or 4096), so the more square a texture, the more chances. + // It will work in every hardware. + // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a // 256x8192 atlas (won't work anywhere). ERR_FAIL_COND(p_rects.size() == 0); @@ -1066,7 +1013,7 @@ void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_resu for (int j = 0; j < w; j++) hmax.write[j] = 0; - //place them + // Place them. int ofs = 0; int limit_h = 0; for (int j = 0; j < wrects.size(); j++) { @@ -1101,7 +1048,7 @@ void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_resu if (end_w > max_w) max_w = end_w; - if (ofs == 0 || end_h > limit_h) //while h limit not reached, keep stacking + if (ofs == 0 || end_h > limit_h) // While h limit not reached, keep stacking. ofs += wrects[j].s.width; } @@ -1112,7 +1059,7 @@ void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_resu results.push_back(result); } - //find the result with the best aspect ratio + // Find the result with the best aspect ratio. int best = -1; real_t best_aspect = 1e20; @@ -1152,7 +1099,7 @@ Vector<Vector<Point2> > Geometry::_polypaths_do_operation(PolyBooleanOperation p } Path path_a, path_b; - // Need to scale points (Clipper's requirement for robust computation) + // Need to scale points (Clipper's requirement for robust computation). for (int i = 0; i != p_polypath_a.size(); ++i) { path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR); } @@ -1160,19 +1107,19 @@ Vector<Vector<Point2> > Geometry::_polypaths_do_operation(PolyBooleanOperation p path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR); } Clipper clp; - clp.AddPath(path_a, ptSubject, !is_a_open); // forward compatible with Clipper 10.0.0 - clp.AddPath(path_b, ptClip, true); // polylines cannot be set as clip + clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0. + clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip. Paths paths; if (is_a_open) { - PolyTree tree; // needed to populate polylines + PolyTree tree; // Needed to populate polylines. clp.Execute(op, tree); OpenPathsFromPolyTree(tree, paths); } else { - clp.Execute(op, paths); // works on closed polygons only + clp.Execute(op, paths); // Works on closed polygons only. } - // Have to scale points down now + // Have to scale points down now. Vector<Vector<Point2> > polypaths; for (Paths::size_type i = 0; i < paths.size(); ++i) { @@ -1214,16 +1161,16 @@ Vector<Vector<Point2> > Geometry::_polypath_offset(const Vector<Point2> &p_polyp ClipperOffset co; Path path; - // Need to scale points (Clipper's requirement for robust computation) + // Need to scale points (Clipper's requirement for robust computation). for (int i = 0; i != p_polypath.size(); ++i) { path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR); } co.AddPath(path, jt, et); Paths paths; - co.Execute(paths, p_delta * SCALE_FACTOR); // inflate/deflate + co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate. - // Have to scale points down now + // Have to scale points down now. Vector<Vector<Point2> > polypaths; for (Paths::size_type i = 0; i < paths.size(); ++i) { diff --git a/core/math/geometry.h b/core/math/geometry.h index e4f3ff799e..8b0a51c651 100644 --- a/core/math/geometry.h +++ b/core/math/geometry.h @@ -41,47 +41,43 @@ #include "core/print_string.h" #include "core/vector.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ - class Geometry { Geometry(); public: static real_t get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) { - Vector2 d1 = q1 - p1; // Direction vector of segment S1 - Vector2 d2 = q2 - p2; // Direction vector of segment S2 + Vector2 d1 = q1 - p1; // Direction vector of segment S1. + Vector2 d2 = q2 - p2; // Direction vector of segment S2. Vector2 r = p1 - p2; - real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative - real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative + real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative. + real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative. real_t f = d2.dot(r); real_t s, t; - // Check if either or both segments degenerate into points + // Check if either or both segments degenerate into points. if (a <= CMP_EPSILON && e <= CMP_EPSILON) { - // Both segments degenerate into points + // Both segments degenerate into points. c1 = p1; c2 = p2; return Math::sqrt((c1 - c2).dot(c1 - c2)); } if (a <= CMP_EPSILON) { - // First segment degenerates into a point + // First segment degenerates into a point. s = 0.0; t = f / e; // s = 0 => t = (b*s + f) / e = f / e t = CLAMP(t, 0.0, 1.0); } else { real_t c = d1.dot(r); if (e <= CMP_EPSILON) { - // Second segment degenerates into a point + // Second segment degenerates into a point. t = 0.0; s = CLAMP(-c / a, 0.0, 1.0); // t = 0 => s = (b*t - c) / a = -c / a } else { - // The general nondegenerate case starts here + // The general nondegenerate case starts here. real_t b = d1.dot(d2); - real_t denom = a * e - b * b; // Always nonnegative + real_t denom = a * e - b * b; // Always nonnegative. // If segments not parallel, compute closest point on L1 to L2 and - // clamp to segment S1. Else pick arbitrary s (here 0) + // clamp to segment S1. Else pick arbitrary s (here 0). if (denom != 0.0) { s = CLAMP((b * f - c * e) / denom, 0.0, 1.0); } else @@ -92,7 +88,7 @@ public: //If t in [0,1] done. Else clamp t, recompute s for the new value // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a - // and clamp s to [0, 1] + // and clamp s to [0, 1]. if (t < 0.0) { t = 0.0; s = CLAMP(-c / a, 0.0, 1.0); @@ -109,14 +105,14 @@ public: static void get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2, Vector3 &c1, Vector3 &c2) { -//do the function 'd' as defined by pb. I think is is dot product of some sort +// Do the function 'd' as defined by pb. I think is is dot product of some sort. #define d_of(m, n, o, p) ((m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z)) - //calculate the parametric position on the 2 curves, mua and mub + // Calculate the parametric position on the 2 curves, mua and mub. real_t mua = (d_of(p1, q1, q2, q1) * d_of(q2, q1, p2, p1) - d_of(p1, q1, p2, p1) * d_of(q2, q1, q2, q1)) / (d_of(p2, p1, p2, p1) * d_of(q2, q1, q2, q1) - d_of(q2, q1, p2, p1) * d_of(q2, q1, p2, p1)); real_t mub = (d_of(p1, q1, q2, q1) + mua * d_of(q2, q1, p2, p1)) / d_of(q2, q1, q2, q1); - //clip the value between [0..1] constraining the solution to lie on the original curves + // Clip the value between [0..1] constraining the solution to lie on the original curves. if (mua < 0) mua = 0; if (mub < 0) mub = 0; if (mua > 1) mua = 1; @@ -129,38 +125,38 @@ public: Vector3 u = p_to_a - p_from_a; Vector3 v = p_to_b - p_from_b; Vector3 w = p_from_a - p_to_a; - real_t a = u.dot(u); // always >= 0 + real_t a = u.dot(u); // Always >= 0 real_t b = u.dot(v); - real_t c = v.dot(v); // always >= 0 + real_t c = v.dot(v); // Always >= 0 real_t d = u.dot(w); real_t e = v.dot(w); - real_t D = a * c - b * b; // always >= 0 + real_t D = a * c - b * b; // Always >= 0 real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 - // compute the line parameters of the two closest points - if (D < CMP_EPSILON) { // the lines are almost parallel - sN = 0.0; // force using point P0 on segment S1 - sD = 1.0; // to prevent possible division by 0.0 later + // Compute the line parameters of the two closest points. + if (D < CMP_EPSILON) { // The lines are almost parallel. + sN = 0.0; // Force using point P0 on segment S1 + sD = 1.0; // to prevent possible division by 0.0 later. tN = e; tD = c; - } else { // get the closest points on the infinite lines + } else { // Get the closest points on the infinite lines sN = (b * e - c * d); tN = (a * e - b * d); - if (sN < 0.0) { // sc < 0 => the s=0 edge is visible + if (sN < 0.0) { // sc < 0 => the s=0 edge is visible. sN = 0.0; tN = e; tD = c; - } else if (sN > sD) { // sc > 1 => the s=1 edge is visible + } else if (sN > sD) { // sc > 1 => the s=1 edge is visible. sN = sD; tN = e + b; tD = c; } } - if (tN < 0.0) { // tc < 0 => the t=0 edge is visible + if (tN < 0.0) { // tc < 0 => the t=0 edge is visible. tN = 0.0; - // recompute sc for this edge + // Recompute sc for this edge. if (-d < 0.0) sN = 0.0; else if (-d > a) @@ -169,9 +165,9 @@ public: sN = -d; sD = a; } - } else if (tN > tD) { // tc > 1 => the t=1 edge is visible + } else if (tN > tD) { // tc > 1 => the t=1 edge is visible. tN = tD; - // recompute sc for this edge + // Recompute sc for this edge. if ((-d + b) < 0.0) sN = 0; else if ((-d + b) > a) @@ -181,14 +177,14 @@ public: sD = a; } } - // finally do the division to get sc and tc + // Finally do the division to get sc and tc. sc = (Math::is_zero_approx(sN) ? 0.0 : sN / sD); tc = (Math::is_zero_approx(tN) ? 0.0 : tN / tD); - // get the difference of the two closest points + // Get the difference of the two closest points. Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc) - return dP.length(); // return the closest distance + return dP.length(); // Return the closest distance. } static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) { @@ -196,7 +192,7 @@ public: Vector3 e2 = p_v2 - p_v0; Vector3 h = p_dir.cross(e2); real_t a = e1.dot(h); - if (Math::is_zero_approx(a)) // parallel test + if (Math::is_zero_approx(a)) // Parallel test. return false; real_t f = 1.0 / a; @@ -214,16 +210,15 @@ public: if (v < 0.0 || u + v > 1.0) return false; - // at this stage we can compute t to find out where - // the intersection point is on the line + // At this stage we can compute t to find out where + // the intersection point is on the line. real_t t = f * e2.dot(q); if (t > 0.00001) { // ray intersection if (r_res) *r_res = p_from + p_dir * t; return true; - } else // this means that there is a line intersection - // but not a ray intersection + } else // This means that there is a line intersection but not a ray intersection. return false; } @@ -234,7 +229,7 @@ public: Vector3 e2 = p_v2 - p_v0; Vector3 h = rel.cross(e2); real_t a = e1.dot(h); - if (Math::is_zero_approx(a)) // parallel test + if (Math::is_zero_approx(a)) // Parallel test. return false; real_t f = 1.0 / a; @@ -252,16 +247,15 @@ public: if (v < 0.0 || u + v > 1.0) return false; - // at this stage we can compute t to find out where - // the intersection point is on the line + // At this stage we can compute t to find out where + // the intersection point is on the line. real_t t = f * e2.dot(q); - if (t > CMP_EPSILON && t <= 1.0) { // ray intersection + if (t > CMP_EPSILON && t <= 1.0) { // Ray intersection. if (r_res) *r_res = p_from + rel * t; return true; - } else // this means that there is a line intersection - // but not a ray intersection + } else // This means that there is a line intersection but not a ray intersection. return false; } @@ -271,13 +265,11 @@ public: Vector3 rel = (p_to - p_from); real_t rel_l = rel.length(); if (rel_l < CMP_EPSILON) - return false; // both points are the same + return false; // Both points are the same. Vector3 normal = rel / rel_l; real_t sphere_d = normal.dot(sphere_pos); - //Vector3 ray_closest=normal*sphere_d; - real_t ray_distance = sphere_pos.distance_to(normal * sphere_d); if (ray_distance >= p_sphere_radius) @@ -289,7 +281,7 @@ public: if (inters_d2 >= CMP_EPSILON) inters_d -= Math::sqrt(inters_d2); - // check in segment + // Check in segment. if (inters_d < 0 || inters_d > rel_l) return false; @@ -308,9 +300,9 @@ public: Vector3 rel = (p_to - p_from); real_t rel_l = rel.length(); if (rel_l < CMP_EPSILON) - return false; // both points are the same + return false; // Both points are the same. - // first check if they are parallel + // First check if they are parallel. Vector3 normal = (rel / rel_l); Vector3 crs = normal.cross(Vector3(0, 0, 1)); real_t crs_l = crs.length(); @@ -318,8 +310,7 @@ public: Vector3 z_dir; if (crs_l < CMP_EPSILON) { - //blahblah parallel - z_dir = Vector3(1, 0, 0); //any x/y vector ok + z_dir = Vector3(1, 0, 0); // Any x/y vector OK. } else { z_dir = crs / crs_l; } @@ -327,12 +318,12 @@ public: real_t dist = z_dir.dot(p_from); if (dist >= p_radius) - return false; // too far away + return false; // Too far away. - // convert to 2D + // Convert to 2D. real_t w2 = p_radius * p_radius - dist * dist; if (w2 < CMP_EPSILON) - return false; //avoid numerical error + return false; // Avoid numerical error. Size2 size(Math::sqrt(w2), p_height * 0.5); Vector3 x_dir = z_dir.cross(Vector3(0, 0, 1)).normalized(); @@ -379,7 +370,7 @@ public: return false; } - // convert to 3D again + // Convert to 3D again. Vector3 result = p_from + (rel * min); Vector3 res_normal = result; @@ -420,19 +411,18 @@ public: real_t den = p.normal.dot(dir); - //printf("den is %i\n",den); if (Math::abs(den) <= CMP_EPSILON) - continue; // ignore parallel plane + continue; // Ignore parallel plane. real_t dist = -p.distance_to(p_from) / den; if (den > 0) { - //backwards facing plane + // Backwards facing plane. if (dist < max) max = dist; } else { - //front facing plane + // Front facing plane. if (dist > min) { min = dist; min_index = i; @@ -440,8 +430,8 @@ public: } } - if (max <= min || min < 0 || min > rel_l || min_index == -1) // exit conditions - return false; // no intersection + if (max <= min || min < 0 || min > rel_l || min_index == -1) // Exit conditions. + return false; // No intersection. if (p_res) *p_res = p_from + dir * min; @@ -457,16 +447,16 @@ public: Vector3 n = p_segment[1] - p_segment[0]; real_t l2 = n.length_squared(); if (l2 < 1e-20) - return p_segment[0]; // both points are the same, just give any + return p_segment[0]; // Both points are the same, just give any. real_t d = n.dot(p) / l2; if (d <= 0.0) - return p_segment[0]; // before first point + return p_segment[0]; // Before first point. else if (d >= 1.0) - return p_segment[1]; // after first point + return p_segment[1]; // After first point. else - return p_segment[0] + n * d; // inside + return p_segment[0] + n * d; // Inside. } static Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 *p_segment) { @@ -475,11 +465,11 @@ public: Vector3 n = p_segment[1] - p_segment[0]; real_t l2 = n.length_squared(); if (l2 < 1e-20) - return p_segment[0]; // both points are the same, just give any + return p_segment[0]; // Both points are the same, just give any. real_t d = n.dot(p) / l2; - return p_segment[0] + n * d; // inside + return p_segment[0] + n * d; // Inside. } static Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 *p_segment) { @@ -488,16 +478,16 @@ public: Vector2 n = p_segment[1] - p_segment[0]; real_t l2 = n.length_squared(); if (l2 < 1e-20) - return p_segment[0]; // both points are the same, just give any + return p_segment[0]; // Both points are the same, just give any. real_t d = n.dot(p) / l2; if (d <= 0.0) - return p_segment[0]; // before first point + return p_segment[0]; // Before first point. else if (d >= 1.0) - return p_segment[1]; // after first point + return p_segment[1]; // After first point. else - return p_segment[0] + n * d; // inside + return p_segment[0] + n * d; // Inside. } static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) { @@ -512,27 +502,25 @@ public: return (cn.cross(an) > 0) == orientation; } - //static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon); - static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 *p_segment) { Vector2 p = p_point - p_segment[0]; Vector2 n = p_segment[1] - p_segment[0]; real_t l2 = n.length_squared(); if (l2 < 1e-20) - return p_segment[0]; // both points are the same, just give any + return p_segment[0]; // Both points are the same, just give any. real_t d = n.dot(p) / l2; - return p_segment[0] + n * d; // inside + return p_segment[0] + n * d; // Inside. } static bool line_intersects_line_2d(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b, Vector2 &r_result) { - // see http://paulbourke.net/geometry/pointlineplane/ + // See http://paulbourke.net/geometry/pointlineplane/ const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y; - if (Math::is_zero_approx(denom)) { // parallel? + if (Math::is_zero_approx(denom)) { // Parallel? return false; } @@ -560,11 +548,11 @@ public: real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y); - // Fail if segment C-D crosses line A-B outside of segment A-B. + // Fail if segment C-D crosses line A-B outside of segment A-B. if (ABpos < 0 || ABpos > 1.0) return false; - // (4) Apply the discovered position to line A-B in the original coordinate system. + // (4) Apply the discovered position to line A-B in the original coordinate system. if (r_result) *r_result = p_from_a + B * ABpos; @@ -597,7 +585,7 @@ public: real_t d = p_normal.dot(p_sphere_pos) - p_normal.dot(p_triangle[0]); - if (d > p_sphere_radius || d < -p_sphere_radius) // not touching the plane of the face, return + if (d > p_sphere_radius || d < -p_sphere_radius) // Not touching the plane of the face, return. return false; Vector3 contact = p_sphere_pos - (p_normal * d); @@ -617,25 +605,25 @@ public: for (int i = 0; i < 3; i++) { - // check edge cylinder + // Check edge cylinder. Vector3 n1 = verts[i] - verts[i + 1]; Vector3 n2 = p_sphere_pos - verts[i + 1]; - ///@TODO i could discard by range here to make the algorithm quicker? dunno.. + ///@TODO Maybe discard by range here to make the algorithm quicker. - // check point within cylinder radius + // Check point within cylinder radius. Vector3 axis = n1.cross(n2).cross(n1); - axis.normalize(); // ugh + axis.normalize(); real_t ad = axis.dot(n2); if (ABS(ad) > p_sphere_radius) { - // no chance with this edge, too far away + // No chance with this edge, too far away. continue; } - // check point within edge capsule cylinder + // Check point within edge capsule cylinder. /** 4th TEST INSIDE EDGE POINTS **/ real_t sphere_at = n1.dot(n2); @@ -644,8 +632,7 @@ public: r_triangle_contact = p_sphere_pos - axis * (axis.dot(n2)); r_sphere_contact = p_sphere_pos - axis * p_sphere_radius; - // point inside here - //printf("solved inside edge\n"); + // Point inside here. return true; } @@ -655,48 +642,51 @@ public: Vector3 n = (p_sphere_pos - verts[i + 1]).normalized(); - //r_triangle_contact=verts[i+1]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2)); r_triangle_contact = verts[i + 1]; r_sphere_contact = p_sphere_pos - n * p_sphere_radius; - //printf("solved inside point segment 1\n"); return true; } if (n2.distance_squared_to(n1) < r2) { Vector3 n = (p_sphere_pos - verts[i]).normalized(); - //r_triangle_contact=verts[i]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2)); r_triangle_contact = verts[i]; r_sphere_contact = p_sphere_pos - n * p_sphere_radius; - //printf("solved inside point segment 1\n"); return true; } - break; // It's pointless to continue at this point, so save some cpu cycles + break; // It's pointless to continue at this point, so save some CPU cycles. } return false; } + static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) { + + return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius; + } + static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) { Vector2 line_vec = p_to - p_from; Vector2 vec_to_line = p_from - p_circle_pos; - /* create a quadratic formula of the form ax^2 + bx + c = 0 */ + // Create a quadratic formula of the form ax^2 + bx + c = 0 real_t a, b, c; a = line_vec.dot(line_vec); b = 2 * vec_to_line.dot(line_vec); c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius; - /* solve for t */ + // Solve for t. real_t sqrtterm = b * b - 4 * a * c; - /* if the term we intend to square root is less than 0 then the answer won't be real, so it definitely won't be t in the range 0 to 1 */ + // If the term we intend to square root is less than 0 then the answer won't be real, + // so it definitely won't be t in the range 0 to 1. if (sqrtterm < 0) return -1; - /* if we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection) then the following can be skipped and we can just return the equivalent of res1 */ + // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection) + // then the following can be skipped and we can just return the equivalent of res1. sqrtterm = Math::sqrt(sqrtterm); real_t res1 = (-b - sqrtterm) / (2 * a); real_t res2 = (-b + sqrtterm) / (2 * a); @@ -722,7 +712,6 @@ public: int outside_count = 0; for (int a = 0; a < polygon.size(); a++) { - //real_t p_plane.d = (*this) * polygon[a]; real_t dist = p_plane.distance_to(polygon[a]); if (dist < -CMP_POINT_IN_PLANE_EPSILON) { location_cache[a] = LOC_INSIDE; @@ -739,11 +728,11 @@ public: if (outside_count == 0) { - return polygon; // no changes + return polygon; // No changes. } else if (inside_count == 0) { - return Vector<Vector3>(); //empty + return Vector<Vector3>(); // Empty. } long previous = polygon.size() - 1; @@ -838,22 +827,11 @@ public: static Vector<Vector<Point2> > offset_polyline_2d(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) { - ERR_EXPLAIN("Attempt to offset a polyline like a polygon (use offset_polygon_2d instead)."); - ERR_FAIL_COND_V(p_end_type == END_POLYGON, Vector<Vector<Point2> >()); + ERR_FAIL_COND_V_MSG(p_end_type == END_POLYGON, Vector<Vector<Point2> >(), "Attempt to offset a polyline like a polygon (use offset_polygon_2d instead)."); return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type); } - static Vector<Point2> transform_points_2d(const Vector<Point2> &p_points, const Transform2D &p_mat) { - - Vector<Point2> points; - - for (int i = 0; i < p_points.size(); ++i) { - points.push_back(p_mat.xform(p_points[i])); - } - return points; - } - static Vector<int> triangulate_delaunay_2d(const Vector<Vector2> &p_points) { Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points); @@ -899,7 +877,7 @@ public: return sum > 0.0f; } - /* alternate implementation that should be faster */ + // Alternate implementation that should be faster. static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) { int c = p_polygon.size(); if (c < 3) @@ -915,7 +893,8 @@ public: further_away_opposite.y = MIN(p[i].y, further_away_opposite.y); } - further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312); // make point outside that won't intersect with points in segment from p_point + // Make point outside that won't intersect with points in segment from p_point. + further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312); int intersections = 0; for (int i = 0; i < c; i++) { @@ -931,7 +910,8 @@ public: static PoolVector<PoolVector<Face3> > separate_objects(PoolVector<Face3> p_array); - static PoolVector<Face3> wrap_geometry(PoolVector<Face3> p_array, real_t *p_error = NULL); ///< create a "wrap" that encloses the given geometry + // Create a "wrap" that encloses the given geometry. + static PoolVector<Face3> wrap_geometry(PoolVector<Face3> p_array, real_t *p_error = NULL); struct MeshData { @@ -1013,17 +993,17 @@ public: Vector<Point2> H; H.resize(2 * n); - // Sort points lexicographically + // Sort points lexicographically. P.sort(); - // Build lower hull + // Build lower hull. for (int i = 0; i < n; ++i) { while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) k--; H.write[k++] = P[i]; } - // Build upper hull + // Build upper hull. for (int i = n - 2, t = k + 1; i >= 0; i--) { while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) k--; diff --git a/core/math/math_funcs.cpp b/core/math/math_funcs.cpp index f04e40cb6c..50fcdb2c13 100644 --- a/core/math/math_funcs.cpp +++ b/core/math/math_funcs.cpp @@ -30,6 +30,8 @@ #include "math_funcs.h" +#include "core/error_macros.h" + RandomPCG Math::default_rand(RandomPCG::DEFAULT_SEED, RandomPCG::DEFAULT_INC); #define PHI 0x9e3779b9 diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h index a712356ddc..9078abea68 100644 --- a/core/math/math_funcs.h +++ b/core/math/math_funcs.h @@ -255,16 +255,16 @@ public: static _ALWAYS_INLINE_ float round(float p_val) { return (p_val >= 0) ? Math::floor(p_val + 0.5) : -Math::floor(-p_val + 0.5); } static _ALWAYS_INLINE_ int64_t wrapi(int64_t value, int64_t min, int64_t max) { - int64_t rng = max - min; - return (rng != 0) ? min + ((((value - min) % rng) + rng) % rng) : min; + int64_t range = max - min; + return range == 0 ? min : min + ((((value - min) % range) + range) % range); } static _ALWAYS_INLINE_ double wrapf(double value, double min, double max) { - double rng = max - min; - return (!is_equal_approx(rng, 0.0)) ? value - (rng * Math::floor((value - min) / rng)) : min; + double range = max - min; + return is_zero_approx(range) ? min : value - (range * Math::floor((value - min) / range)); } static _ALWAYS_INLINE_ float wrapf(float value, float min, float max) { - float rng = max - min; - return (!is_equal_approx(rng, 0.0f)) ? value - (rng * Math::floor((value - min) / rng)) : min; + float range = max - min; + return is_zero_approx(range) ? min : value - (range * Math::floor((value - min) / range)); } // double only, as these functions are mainly used by the editor and not performance-critical, @@ -300,6 +300,11 @@ public: } static _ALWAYS_INLINE_ bool is_equal_approx(real_t a, real_t b) { + // Check for exact equality first, required to handle "infinity" values. + if (a == b) { + return true; + } + // Then check for approximate equality. real_t tolerance = CMP_EPSILON * abs(a); if (tolerance < CMP_EPSILON) { tolerance = CMP_EPSILON; @@ -308,6 +313,11 @@ public: } static _ALWAYS_INLINE_ bool is_equal_approx(real_t a, real_t b, real_t tolerance) { + // Check for exact equality first, required to handle "infinity" values. + if (a == b) { + return true; + } + // Then check for approximate equality. return abs(a - b) < tolerance; } diff --git a/core/math/octree.h b/core/math/octree.h index d6fc9776bc..db15c8a1f8 100644 --- a/core/math/octree.h +++ b/core/math/octree.h @@ -38,10 +38,6 @@ #include "core/print_string.h" #include "core/variant.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ - typedef uint32_t OctreeElementID; #define OCTREE_ELEMENT_INVALID_ID 0 @@ -568,10 +564,7 @@ void Octree<T, use_pairs, AL>::_ensure_valid_root(const AABB &p_aabb) { while (!base.encloses(p_aabb)) { - if (base.size.x > OCTREE_SIZE_LIMIT) { - ERR_EXPLAIN("Octree upper size limit reeached, does the AABB supplied contain NAN?"); - ERR_FAIL(); - } + ERR_FAIL_COND_MSG(base.size.x > OCTREE_SIZE_LIMIT, "Octree upper size limit reached, does the AABB supplied contain NAN?"); Octant *gp = memnew_allocator(Octant, AL); octant_count++; diff --git a/core/math/quat.h b/core/math/quat.h index 8ed2fa7cc2..3d6602e466 100644 --- a/core/math/quat.h +++ b/core/math/quat.h @@ -38,10 +38,6 @@ #include "core/math/math_funcs.h" #include "core/ustring.h" -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ - class Quat { public: real_t x, y, z, w; diff --git a/core/math/rect2.h b/core/math/rect2.h index d636aa223f..f58756ee40 100644 --- a/core/math/rect2.h +++ b/core/math/rect2.h @@ -99,8 +99,8 @@ struct Rect2 { inline bool encloses(const Rect2 &p_rect) const { return (p_rect.position.x >= position.x) && (p_rect.position.y >= position.y) && - ((p_rect.position.x + p_rect.size.x) < (position.x + size.x)) && - ((p_rect.position.y + p_rect.size.y) < (position.y + size.y)); + ((p_rect.position.x + p_rect.size.x) <= (position.x + size.x)) && + ((p_rect.position.y + p_rect.size.y) <= (position.y + size.y)); } _FORCE_INLINE_ bool has_no_area() const { diff --git a/core/math/transform.cpp b/core/math/transform.cpp index 7ff7cac914..4056975da8 100644 --- a/core/math/transform.cpp +++ b/core/math/transform.cpp @@ -213,3 +213,8 @@ Transform::Transform(const Basis &p_basis, const Vector3 &p_origin) : basis(p_basis), origin(p_origin) { } + +Transform::Transform(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz, real_t ox, real_t oy, real_t oz) { + basis = Basis(xx, xy, xz, yx, yy, yz, zx, zy, zz); + origin = Vector3(ox, oy, oz); +} diff --git a/core/math/transform.h b/core/math/transform.h index 2f43f6b035..90e2b07583 100644 --- a/core/math/transform.h +++ b/core/math/transform.h @@ -34,10 +34,7 @@ #include "core/math/aabb.h" #include "core/math/basis.h" #include "core/math/plane.h" - -/** - @author Juan Linietsky <reduzio@gmail.com> -*/ +#include "core/pool_vector.h" class Transform { public: @@ -86,6 +83,9 @@ public: _FORCE_INLINE_ AABB xform(const AABB &p_aabb) const; _FORCE_INLINE_ AABB xform_inv(const AABB &p_aabb) const; + _FORCE_INLINE_ PoolVector<Vector3> xform(const PoolVector<Vector3> &p_array) const; + _FORCE_INLINE_ PoolVector<Vector3> xform_inv(const PoolVector<Vector3> &p_array) const; + void operator*=(const Transform &p_transform); Transform operator*(const Transform &p_transform) const; @@ -108,6 +108,7 @@ public: operator String() const; + Transform(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz, real_t ox, real_t oy, real_t oz); Transform(const Basis &p_basis, const Vector3 &p_origin = Vector3()); Transform() {} }; @@ -157,22 +158,29 @@ _FORCE_INLINE_ Plane Transform::xform_inv(const Plane &p_plane) const { } _FORCE_INLINE_ AABB Transform::xform(const AABB &p_aabb) const { - /* define vertices */ - Vector3 x = basis.get_axis(0) * p_aabb.size.x; - Vector3 y = basis.get_axis(1) * p_aabb.size.y; - Vector3 z = basis.get_axis(2) * p_aabb.size.z; - Vector3 pos = xform(p_aabb.position); - //could be even further optimized - AABB new_aabb; - new_aabb.position = pos; - new_aabb.expand_to(pos + x); - new_aabb.expand_to(pos + y); - new_aabb.expand_to(pos + z); - new_aabb.expand_to(pos + x + y); - new_aabb.expand_to(pos + x + z); - new_aabb.expand_to(pos + y + z); - new_aabb.expand_to(pos + x + y + z); - return new_aabb; + + /* http://dev.theomader.com/transform-bounding-boxes/ */ + Vector3 min = p_aabb.position; + Vector3 max = p_aabb.position + p_aabb.size; + Vector3 tmin, tmax; + for (int i = 0; i < 3; i++) { + tmin[i] = tmax[i] = origin[i]; + for (int j = 0; j < 3; j++) { + real_t e = basis[i][j] * min[j]; + real_t f = basis[i][j] * max[j]; + if (e < f) { + tmin[i] += e; + tmax[i] += f; + } else { + tmin[i] += f; + tmax[i] += e; + } + } + } + AABB r_aabb; + r_aabb.position = tmin; + r_aabb.size = tmax - tmin; + return r_aabb; } _FORCE_INLINE_ AABB Transform::xform_inv(const AABB &p_aabb) const { @@ -201,4 +209,32 @@ _FORCE_INLINE_ AABB Transform::xform_inv(const AABB &p_aabb) const { return ret; } +PoolVector<Vector3> Transform::xform(const PoolVector<Vector3> &p_array) const { + + PoolVector<Vector3> array; + array.resize(p_array.size()); + + PoolVector<Vector3>::Read r = p_array.read(); + PoolVector<Vector3>::Write w = array.write(); + + for (int i = 0; i < p_array.size(); ++i) { + w[i] = xform(r[i]); + } + return array; +} + +PoolVector<Vector3> Transform::xform_inv(const PoolVector<Vector3> &p_array) const { + + PoolVector<Vector3> array; + array.resize(p_array.size()); + + PoolVector<Vector3>::Read r = p_array.read(); + PoolVector<Vector3>::Write w = array.write(); + + for (int i = 0; i < p_array.size(); ++i) { + w[i] = xform_inv(r[i]); + } + return array; +} + #endif // TRANSFORM_H diff --git a/core/math/transform_2d.h b/core/math/transform_2d.h index c44678674a..e8b44ab197 100644 --- a/core/math/transform_2d.h +++ b/core/math/transform_2d.h @@ -32,6 +32,7 @@ #define TRANSFORM_2D_H #include "core/math/rect2.h" // also includes vector2, math_funcs, and ustring +#include "core/pool_vector.h" struct Transform2D { // Warning #1: basis of Transform2D is stored differently from Basis. In terms of elements array, the basis matrix looks like "on paper": @@ -110,6 +111,8 @@ struct Transform2D { _FORCE_INLINE_ Vector2 xform_inv(const Vector2 &p_vec) const; _FORCE_INLINE_ Rect2 xform(const Rect2 &p_rect) const; _FORCE_INLINE_ Rect2 xform_inv(const Rect2 &p_rect) const; + _FORCE_INLINE_ PoolVector<Vector2> xform(const PoolVector<Vector2> &p_array) const; + _FORCE_INLINE_ PoolVector<Vector2> xform_inv(const PoolVector<Vector2> &p_array) const; operator String() const; @@ -199,4 +202,32 @@ Rect2 Transform2D::xform_inv(const Rect2 &p_rect) const { return new_rect; } +PoolVector<Vector2> Transform2D::xform(const PoolVector<Vector2> &p_array) const { + + PoolVector<Vector2> array; + array.resize(p_array.size()); + + PoolVector<Vector2>::Read r = p_array.read(); + PoolVector<Vector2>::Write w = array.write(); + + for (int i = 0; i < p_array.size(); ++i) { + w[i] = xform(r[i]); + } + return array; +} + +PoolVector<Vector2> Transform2D::xform_inv(const PoolVector<Vector2> &p_array) const { + + PoolVector<Vector2> array; + array.resize(p_array.size()); + + PoolVector<Vector2>::Read r = p_array.read(); + PoolVector<Vector2>::Write w = array.write(); + + for (int i = 0; i < p_array.size(); ++i) { + w[i] = xform_inv(r[i]); + } + return array; +} + #endif // TRANSFORM_2D_H diff --git a/core/math/vector2.cpp b/core/math/vector2.cpp index 779a28be66..972bccc0ac 100644 --- a/core/math/vector2.cpp +++ b/core/math/vector2.cpp @@ -98,6 +98,11 @@ real_t Vector2::cross(const Vector2 &p_other) const { return x * p_other.y - y * p_other.x; } +Vector2 Vector2::sign() const { + + return Vector2(SGN(x), SGN(y)); +} + Vector2 Vector2::floor() const { return Vector2(Math::floor(x), Math::floor(y)); @@ -121,6 +126,14 @@ Vector2 Vector2::rotated(real_t p_by) const { return v; } +Vector2 Vector2::posmod(const real_t p_mod) const { + return Vector2(Math::fposmod(x, p_mod), Math::fposmod(y, p_mod)); +} + +Vector2 Vector2::posmodv(const Vector2 &p_modv) const { + return Vector2(Math::fposmod(x, p_modv.x), Math::fposmod(y, p_modv.y)); +} + Vector2 Vector2::project(const Vector2 &p_b) const { return p_b * (dot(p_b) / p_b.length_squared()); } diff --git a/core/math/vector2.h b/core/math/vector2.h index 78a1641c1e..1a73831891 100644 --- a/core/math/vector2.h +++ b/core/math/vector2.h @@ -38,6 +38,11 @@ struct Vector2i; struct Vector2 { + enum Axis { + AXIS_X, + AXIS_Y, + }; + union { real_t x; real_t width; @@ -69,6 +74,8 @@ struct Vector2 { real_t dot(const Vector2 &p_other) const; real_t cross(const Vector2 &p_other) const; + Vector2 posmod(const real_t p_mod) const; + Vector2 posmodv(const Vector2 &p_modv) const; Vector2 project(const Vector2 &p_b) const; Vector2 plane_project(real_t p_d, const Vector2 &p_vec) const; @@ -107,8 +114,10 @@ struct Vector2 { bool operator==(const Vector2 &p_vec2) const; bool operator!=(const Vector2 &p_vec2) const; - bool operator<(const Vector2 &p_vec2) const { return (Math::is_equal_approx(x, p_vec2.x)) ? (y < p_vec2.y) : (x < p_vec2.x); } - bool operator<=(const Vector2 &p_vec2) const { return (Math::is_equal_approx(x, p_vec2.x)) ? (y <= p_vec2.y) : (x < p_vec2.x); } + bool operator<(const Vector2 &p_vec2) const { return Math::is_equal_approx(x, p_vec2.x) ? (y < p_vec2.y) : (x < p_vec2.x); } + bool operator>(const Vector2 &p_vec2) const { return Math::is_equal_approx(x, p_vec2.x) ? (y > p_vec2.y) : (x > p_vec2.x); } + bool operator<=(const Vector2 &p_vec2) const { return Math::is_equal_approx(x, p_vec2.x) ? (y <= p_vec2.y) : (x < p_vec2.x); } + bool operator>=(const Vector2 &p_vec2) const { return Math::is_equal_approx(x, p_vec2.x) ? (y >= p_vec2.y) : (x > p_vec2.x); } real_t angle() const; @@ -129,6 +138,7 @@ struct Vector2 { return Vector2(y, -x); } + Vector2 sign() const; Vector2 floor() const; Vector2 ceil() const; Vector2 round() const; @@ -141,10 +151,7 @@ struct Vector2 { x = p_x; y = p_y; } - _FORCE_INLINE_ Vector2() { - x = 0; - y = 0; - } + _FORCE_INLINE_ Vector2() { x = y = 0; } }; _FORCE_INLINE_ Vector2 Vector2::plane_project(real_t p_d, const Vector2 &p_vec) const { @@ -262,6 +269,11 @@ typedef Vector2 Point2; struct Vector2i { + enum Axis { + AXIS_X, + AXIS_Y, + }; + union { int x; int width; diff --git a/core/math/vector3.cpp b/core/math/vector3.cpp index 73927821cf..ebc1599820 100644 --- a/core/math/vector3.cpp +++ b/core/math/vector3.cpp @@ -134,6 +134,21 @@ Vector3 Vector3::move_toward(const Vector3 &p_to, const real_t p_delta) const { return len <= p_delta || len < CMP_EPSILON ? p_to : v + vd / len * p_delta; } +Basis Vector3::outer(const Vector3 &p_b) const { + + Vector3 row0(x * p_b.x, x * p_b.y, x * p_b.z); + Vector3 row1(y * p_b.x, y * p_b.y, y * p_b.z); + Vector3 row2(z * p_b.x, z * p_b.y, z * p_b.z); + + return Basis(row0, row1, row2); +} + +Basis Vector3::to_diagonal_matrix() const { + return Basis(x, 0, 0, + 0, y, 0, + 0, 0, z); +} + Vector3::operator String() const { return (rtos(x) + ", " + rtos(y) + ", " + rtos(z)); diff --git a/core/math/vector3.h b/core/math/vector3.h index 45bdfee487..de1743d88f 100644 --- a/core/math/vector3.h +++ b/core/math/vector3.h @@ -31,9 +31,7 @@ #ifndef VECTOR3_H #define VECTOR3_H -#include "core/math/math_defs.h" #include "core/math/math_funcs.h" -#include "core/typedefs.h" #include "core/ustring.h" class Basis; @@ -98,8 +96,8 @@ struct Vector3 { _FORCE_INLINE_ Vector3 cross(const Vector3 &p_b) const; _FORCE_INLINE_ real_t dot(const Vector3 &p_b) const; - _FORCE_INLINE_ Basis outer(const Vector3 &p_b) const; - _FORCE_INLINE_ Basis to_diagonal_matrix() const; + Basis outer(const Vector3 &p_b) const; + Basis to_diagonal_matrix() const; _FORCE_INLINE_ Vector3 abs() const; _FORCE_INLINE_ Vector3 floor() const; @@ -110,6 +108,8 @@ struct Vector3 { _FORCE_INLINE_ real_t distance_to(const Vector3 &p_b) const; _FORCE_INLINE_ real_t distance_squared_to(const Vector3 &p_b) const; + _FORCE_INLINE_ Vector3 posmod(const real_t p_mod) const; + _FORCE_INLINE_ Vector3 posmodv(const Vector3 &p_modv) const; _FORCE_INLINE_ Vector3 project(const Vector3 &p_b) const; _FORCE_INLINE_ real_t angle_to(const Vector3 &p_b) const; @@ -141,20 +141,19 @@ struct Vector3 { _FORCE_INLINE_ bool operator!=(const Vector3 &p_v) const; _FORCE_INLINE_ bool operator<(const Vector3 &p_v) const; _FORCE_INLINE_ bool operator<=(const Vector3 &p_v) const; + _FORCE_INLINE_ bool operator>(const Vector3 &p_v) const; + _FORCE_INLINE_ bool operator>=(const Vector3 &p_v) const; operator String() const; - _FORCE_INLINE_ Vector3() { x = y = z = 0; } _FORCE_INLINE_ Vector3(real_t p_x, real_t p_y, real_t p_z) { x = p_x; y = p_y; z = p_z; } + _FORCE_INLINE_ Vector3() { x = y = z = 0; } }; -// Should be included after class definition, otherwise we get circular refs -#include "core/math/basis.h" - Vector3 Vector3::cross(const Vector3 &p_b) const { Vector3 ret( @@ -170,21 +169,6 @@ real_t Vector3::dot(const Vector3 &p_b) const { return x * p_b.x + y * p_b.y + z * p_b.z; } -Basis Vector3::outer(const Vector3 &p_b) const { - - Vector3 row0(x * p_b.x, x * p_b.y, x * p_b.z); - Vector3 row1(y * p_b.x, y * p_b.y, y * p_b.z); - Vector3 row2(z * p_b.x, z * p_b.y, z * p_b.z); - - return Basis(row0, row1, row2); -} - -Basis Vector3::to_diagonal_matrix() const { - return Basis(x, 0, 0, - 0, y, 0, - 0, 0, z); -} - Vector3 Vector3::abs() const { return Vector3(Math::abs(x), Math::abs(y), Math::abs(z)); @@ -233,6 +217,14 @@ real_t Vector3::distance_squared_to(const Vector3 &p_b) const { return (p_b - *this).length_squared(); } +Vector3 Vector3::posmod(const real_t p_mod) const { + return Vector3(Math::fposmod(x, p_mod), Math::fposmod(y, p_mod), Math::fposmod(z, p_mod)); +} + +Vector3 Vector3::posmodv(const Vector3 &p_modv) const { + return Vector3(Math::fposmod(x, p_modv.x), Math::fposmod(y, p_modv.y), Math::fposmod(z, p_modv.z)); +} + Vector3 Vector3::project(const Vector3 &p_b) const { return p_b * (dot(p_b) / p_b.length_squared()); } @@ -357,6 +349,18 @@ bool Vector3::operator<(const Vector3 &p_v) const { } } +bool Vector3::operator>(const Vector3 &p_v) const { + + if (Math::is_equal_approx(x, p_v.x)) { + if (Math::is_equal_approx(y, p_v.y)) + return z > p_v.z; + else + return y > p_v.y; + } else { + return x > p_v.x; + } +} + bool Vector3::operator<=(const Vector3 &p_v) const { if (Math::is_equal_approx(x, p_v.x)) { @@ -369,6 +373,18 @@ bool Vector3::operator<=(const Vector3 &p_v) const { } } +bool Vector3::operator>=(const Vector3 &p_v) const { + + if (Math::is_equal_approx(x, p_v.x)) { + if (Math::is_equal_approx(y, p_v.y)) + return z >= p_v.z; + else + return y > p_v.y; + } else { + return x > p_v.x; + } +} + _FORCE_INLINE_ Vector3 vec3_cross(const Vector3 &p_a, const Vector3 &p_b) { return p_a.cross(p_b); |