diff --git a/.gitignore b/.gitignore index 4c14ae29..701c80ce 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ build/ build-wasm/ +build_test/ .cache/ compile_commands.json *.out.* @@ -21,4 +22,4 @@ venv/ src/vamp/_core/*.pyi /.mypy_cache/ .DS_store -vamp-web/ \ No newline at end of file +vamp-web/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e7d646d..24cf89f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -71,6 +71,7 @@ target_link_libraries_system(vamp_cpp Eigen3::Eigen nigh pdqsort + cdd ) # Link SIMDxorshift if available diff --git a/README.md b/README.md index f291248b..30c77267 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ VAMP fetches the following external dependencies via [CPM](https://github.com/cp - [`nigh`](https://github.com/KavrakiLab/nigh): a fork of the original [`nigh`](https://github.com/UNC-Robotics/nigh) [[4]](#4) to better use our vector types - [`pdqsort`](https://github.com/orlp/pdqsort): for fast sorting - [`SIMDxorshift`](https://github.com/lemire/SIMDxorshift): alternative fast random numbers for x86 machines +- [`cddlib`](https://github.com/cddlib/cddlib): for convex polytope vertex/halfspace conversion Download the code: ```bash @@ -117,7 +118,7 @@ pip install . ``` If you want to install all Python dependencies to run the examples, specify those optional dependencies: ```bash -pip install .[examples,heightmaps] +pip install .[examples,heightmaps,polytopes] ``` If you have installed the `examples` dependencies, test your installation by running: ```bash @@ -328,6 +329,12 @@ These objects can be created with the following: - `vamp.Cuboid(center, euler_xyz, half_extents)`: a cuboid specified by the frame and then half-extents (radii) along the X, Y, and Z axes in its local frame. - `vamp.Heightfield` via `vamp.make_heightfield` / `vamp.png_to_heightfield`: a heightfield specified by pixel intensity in an image file, scaled over specified dimensions. - Pointclouds via `add_pointcloud()` in `vamp.Environment`. This will construct a CAPT from the provided list of points, the minimum and maximum robot sphere radii, and radius for each point in the pointcloud. +- `vamp.ConvexPolytope`: a convex polytope obstacle defined by halfspace planes and/or vertices. Can be constructed in several ways: + - `ConvexPolytope.from_vertices(vertices)`: from a numpy array of vertices + - `ConvexPolytope.from_planes(planes)`: from halfspace planes as `List[[nx, ny, nz, d]]` where the interior satisfies `nx*x + ny*y + nz*z <= d` + - `ConvexPolytope.from_both(vertices, planes)`: from both representations simultaneously + - `vamp.mesh_to_polytopes(filename, position, scale, convex_decomposition, name)`: helper function to load a mesh file and convert it to a list of `ConvexPolytope` obstacles. Supports convex hull or convex decomposition of non-convex meshes. Requires `trimesh`. + See the `src/impl/vamp/collision/` folder for more information. Some robots (currently, the UR5, Panda, and Fetch) support attaching custom geometry (a collection of spheres) to the end-effector via `vamp.Attachment(relative_position, relative_quaternion_xyzw)`. @@ -379,7 +386,7 @@ Inside `impl/vamp`, the code is divided into the following directories: - [ ] Batch configuration validation - [ ] Planning subgroups - [X] Object attachment at end-effector -- [ ] Mesh collision checking +- [X] Mesh collision checking - [X] Pointcloud collision checking - [ ] Manifold-constrained planning - [ ] Time-optimal trajectory parameterization diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index a032aaff..3dc5474c 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -50,6 +50,42 @@ if(VAMP_INSTALL_CPP_LIBRARY) export(EXPORT pdqsort_TARGETS FILE ${CMAKE_CURRENT_BINARY_DIR}/cmake/pdqsortTargets.cmake NAMESPACE pdqsort::) endif() +# cddlib for convex polytope vertex/halfspace conversion +CPMAddPackage( + NAME cddlib + GITHUB_REPOSITORY cddlib/cddlib + GIT_TAG 0.94m +) + +if(cddlib_SOURCE_DIR) + # cddlib uses autotools... + add_library(cdd STATIC + ${cddlib_SOURCE_DIR}/lib-src/cddcore.c + ${cddlib_SOURCE_DIR}/lib-src/cddlp.c + ${cddlib_SOURCE_DIR}/lib-src/cddmp.c + ${cddlib_SOURCE_DIR}/lib-src/cddio.c + ${cddlib_SOURCE_DIR}/lib-src/cddlib.c + ${cddlib_SOURCE_DIR}/lib-src/cddproj.c + ${cddlib_SOURCE_DIR}/lib-src/setoper.c + ) + target_include_directories(cdd PUBLIC + $ + ) + set_target_properties(cdd PROPERTIES POSITION_INDEPENDENT_CODE ON) + + if(VAMP_INSTALL_CPP_LIBRARY) + install(TARGETS cdd + EXPORT cdd_TARGETS + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + ) + install(EXPORT cdd_TARGETS FILE cddTargets.cmake NAMESPACE cdd:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/cdd) + export(EXPORT cdd_TARGETS FILE ${CMAKE_CURRENT_BINARY_DIR}/cmake/cddTargets.cmake NAMESPACE cdd::) + endif() +endif() + # SIMDxorshift for x86_64 systems (includes macOS Intel and Linux x86_64) # Explicitly exclude Emscripten since it doesn't support AVX if(NOT EMSCRIPTEN AND (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "AMD64")) diff --git a/pyproject.toml b/pyproject.toml index 40625266..490ffbc1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,7 @@ dependencies = ["numpy"] [project.optional-dependencies] examples = ["fire", "pybullet", "pyyaml", "tqdm", "pandas", "tabulate", "xmltodict"] heightmaps = ["pillow"] +polytopes = ["trimesh", "vhacdx", "scipy"] [project.urls] Homepage = "https://github.com/KavrakiLab/vamp" diff --git a/resources/objects/Stanford_Bunny.stl b/resources/objects/Stanford_Bunny.stl new file mode 100644 index 00000000..bec02fcb Binary files /dev/null and b/resources/objects/Stanford_Bunny.stl differ diff --git a/scripts/mesh_test.py b/scripts/mesh_test.py new file mode 100644 index 00000000..0815da48 --- /dev/null +++ b/scripts/mesh_test.py @@ -0,0 +1,104 @@ +from pathlib import Path +import vamp +from fire import Fire + +# Starting configuration +a = [-1., 1., 0., -0.8, 0, 2.5, 0.785] + +# Goal configuration +b = [1., 1., 0., -0.8, 0, 2.5, 0.785] + + +def main( + mesh_file: str = None, + position: tuple = (0.5, 0.0, 0.0), + scale: float = 0.01, + decompose: bool = False, + max_convex_hulls: int = 10, + benchmark: bool = False, + n_trials: int = 100, + visualize: bool = True, + planner: str = "rrtc", + sampler_name: str = "halton", + skip_rng_iterations: int = 0, + **kwargs, + ): + + if mesh_file is None: + mesh_path = Path(__file__).parent.parent / "resources" / "objects" / "Stanford_Bunny.stl" + else: + mesh_path = Path(mesh_file) + + if not mesh_path.exists(): + raise FileNotFoundError(f"Mesh file not found: {mesh_path}") + + polytopes = vamp.mesh_to_polytopes( + mesh_path, + position = position, + scale = scale, + convex_decomposition = decompose, + name = "mesh", + maxConvexHulls = max_convex_hulls + ) + + (vamp_module, planner_func, plan_settings, + simp_settings) = vamp.configure_robot_and_planner_with_kwargs("panda", planner, **kwargs) + + sampler = getattr(vamp_module, sampler_name)() + sampler.skip(skip_rng_iterations) + + def create_environment(): + e = vamp.Environment() + for polytope in polytopes: + e.add_polytope(polytope) + return e + + if benchmark: + import pandas as pd + + results = [] + for _ in range(n_trials): + e = create_environment() + + if vamp.panda.validate(a, e) and vamp.panda.validate(b, e): + result = planner_func(a, b, e, plan_settings, sampler) + simple = vamp_module.simplify(result.path, e, simp_settings, sampler) + results.append(vamp.results_to_dict(result, simple)) + + df = pd.DataFrame.from_dict(results) + + # Convert to microseconds + df["planning_time"] = df["planning_time"].dt.microseconds + df["simplification_time"] = df["simplification_time"].dt.microseconds + + # Get summary statistics + stats = df[[ + "planning_time", + "simplification_time", + "initial_path_cost", + "simplified_path_cost", + "planning_iterations" + ]].describe() + + print(stats) + + if visualize: + from vamp import pybullet_interface as vpb + + robot_dir = Path(__file__).parent.parent / 'resources' / 'panda' + sim = vpb.PyBulletSimulator(str(robot_dir / f"panda_spherized.urdf"), vamp_module.joint_names(), True) + + e = create_environment() + for polytope in polytopes: + sim.add_polytope(polytope) + + result = planner_func(a, b, e, plan_settings, sampler) + simple = vamp_module.simplify(result.path, e, simp_settings, sampler) + + simple.path.interpolate_to_resolution(vamp.panda.resolution()) + + sim.animate(simple.path) + + +if __name__ == "__main__": + Fire(main) diff --git a/src/impl/vamp/bindings/python/environment.cc b/src/impl/vamp/bindings/python/environment.cc index 53bbf43e..d3fad9fa 100644 --- a/src/impl/vamp/bindings/python/environment.cc +++ b/src/impl/vamp/bindings/python/environment.cc @@ -108,6 +108,101 @@ void vamp::binding::init_environment(nanobind::module_ &pymodule) .def_ro("zs", &vc::HeightField::zs) .def_ro("data", &vc::HeightField::data); + nb::class_>(pymodule, "ConvexPolytope") + .def( + "__init__", + [](vc::ConvexPolytope *q, const std::vector> &planes) + { new (q) vc::ConvexPolytope(vf::polytope::from_planes(planes)); }, + "planes"_a, + "Constructor from halfplanes as [nx, ny, nz, d].") + .def( + "__init__", + [](vc::ConvexPolytope *q, + const nb::ndarray, nb::device::cpu> &vertices) + { + std::vector vx, vy, vz; + const std::size_t num_vertices = vertices.shape(0); + vx.reserve(num_vertices); + vy.reserve(num_vertices); + vz.reserve(num_vertices); + + for (std::size_t i = 0; i < num_vertices; ++i) + { + vx.emplace_back(vertices(i, 0)); + vy.emplace_back(vertices(i, 1)); + vz.emplace_back(vertices(i, 2)); + } + + new (q) vc::ConvexPolytope(vf::polytope::from_vertices(vx, vy, vz)); + }, + "vertices"_a, + "Constructor from vertices array.") + .def_static( + "from_planes", + &vf::polytope::from_planes, + "planes"_a, + "Create from halfplanes as List[[nx, ny, nz, d]].") + .def_static( + "from_vertices", + [](const nb::ndarray, nb::device::cpu> &vertices) + { + std::vector vx, vy, vz; + const std::size_t num_vertices = vertices.shape(0); + vx.reserve(num_vertices); + vy.reserve(num_vertices); + vz.reserve(num_vertices); + + for (std::size_t i = 0; i < num_vertices; ++i) + { + vx.emplace_back(vertices(i, 0)); + vy.emplace_back(vertices(i, 1)); + vz.emplace_back(vertices(i, 2)); + } + + return vf::polytope::from_vertices(vx, vy, vz); + }, + "vertices"_a, + "Create from vertices array.") + .def_static( + "from_both", + [](const nb::ndarray, nb::device::cpu> &vertices, + const nb::ndarray, nb::device::cpu> &planes) + { + std::vector> verts; + std::vector> plns; + const std::size_t num_vertices = vertices.shape(0); + const std::size_t num_planes = planes.shape(0); + verts.reserve(num_vertices); + plns.reserve(num_planes); + + for (auto i = 0U; i < num_vertices; ++i) + { + verts.emplace_back(std::array{vertices(i, 0), vertices(i, 1), vertices(i, 2)}); + } + + for (auto i = 0U; i < num_planes; ++i) + { + plns.emplace_back( + std::array{planes(i, 0), planes(i, 1), planes(i, 2), planes(i, 3)}); + } + + return vf::polytope::from_both(verts, plns); + }, + "vertices"_a, + "planes"_a, + "Create from both vertices array and planes array.") + .def_ro("num_planes", &vc::ConvexPolytope::num_planes) + .def_ro("nx", &vc::ConvexPolytope::nx) + .def_ro("ny", &vc::ConvexPolytope::ny) + .def_ro("nz", &vc::ConvexPolytope::nz) + .def_ro("d", &vc::ConvexPolytope::d) + .def_ro("num_vertices", &vc::ConvexPolytope::num_vertices) + .def_ro("vx", &vc::ConvexPolytope::vx) + .def_ro("vy", &vc::ConvexPolytope::vy) + .def_ro("vz", &vc::ConvexPolytope::vz) + .def_ro("min_distance", &vc::ConvexPolytope::min_distance) + .def_rw("name", &vc::ConvexPolytope::name); + nb::class_>(pymodule, "Environment") .def(nb::init<>()) .def( @@ -149,6 +244,13 @@ void vamp::binding::init_environment(nanobind::module_ &pymodule) "add_heightfield", [](vc::Environment &e, const vc::HeightField &s) { e.heightfields.emplace_back(s); }) + .def( + "add_polytope", + [](vc::Environment &e, const vc::ConvexPolytope &p) + { + e.polytopes.emplace_back(p); + e.sort(); + }) .def( "add_pointcloud", [](vc::Environment &e, diff --git a/src/impl/vamp/collision/environment.hh b/src/impl/vamp/collision/environment.hh index a380bf85..047055e5 100644 --- a/src/impl/vamp/collision/environment.hh +++ b/src/impl/vamp/collision/environment.hh @@ -21,6 +21,7 @@ namespace vamp::collision std::vector> cuboids; std::vector> z_aligned_cuboids; std::vector> heightfields; + std::vector> polytopes; std::vector pointclouds; std::optional> attachments; @@ -35,6 +36,7 @@ namespace vamp::collision , cuboids(other.cuboids.begin(), other.cuboids.end()) , z_aligned_cuboids(other.z_aligned_cuboids.begin(), other.z_aligned_cuboids.end()) , heightfields(other.heightfields.begin(), other.heightfields.end()) + , polytopes(other.polytopes.begin(), other.polytopes.end()) , pointclouds(other.pointclouds.begin(), other.pointclouds.end()) , attachments(other.template clone_attachments()) { @@ -66,6 +68,10 @@ namespace vamp::collision z_aligned_cuboids.begin(), z_aligned_cuboids.end(), [](const auto &a, const auto &b) { return a.min_distance < b.min_distance; }); + std::sort( + polytopes.begin(), + polytopes.end(), + [](const auto &a, const auto &b) { return a.min_distance < b.min_distance; }); } private: diff --git a/src/impl/vamp/collision/factory.hh b/src/impl/vamp/collision/factory.hh index 6c201a14..5c6a9eb8 100644 --- a/src/impl/vamp/collision/factory.hh +++ b/src/impl/vamp/collision/factory.hh @@ -6,6 +6,7 @@ #include #include #include +#include #include @@ -421,4 +422,85 @@ namespace vamp::collision::factory data); } } // namespace heightfield + + namespace polytope + { + // Construct a convex polytope from arrays of plane coefficients + // Each plane is defined as nx*x + ny*y + nz*z <= d + // Normals should be unit vectors pointing outward from the polytope interior + inline static auto flat( + const std::vector &nx, + const std::vector &ny, + const std::vector &nz, + const std::vector &d) -> collision::ConvexPolytope + { + auto data = collision::halfspaces_to_vertices(nx, ny, nz, d); + return collision::ConvexPolytope( + data.nx.size(), data.nx, data.ny, data.nz, data.d, data.vx.size(), data.vx, data.vy, data.vz); + } + + // Construct from a vector of halfspaces + inline static auto from_planes(const std::vector> &planes) + -> collision::ConvexPolytope + { + auto data = collision::halfspaces_to_vertices(planes); + return collision::ConvexPolytope( + data.nx.size(), data.nx, data.ny, data.nz, data.d, data.vx.size(), data.vx, data.vy, data.vz); + } + + // Construct from vertices + inline static auto from_vertices( + const std::vector &vx, + const std::vector &vy, + const std::vector &vz) -> collision::ConvexPolytope + { + auto data = collision::vertices_to_halfspaces(vx, vy, vz); + return collision::ConvexPolytope( + data.nx.size(), data.nx, data.ny, data.nz, data.d, data.vx.size(), data.vx, data.vy, data.vz); + } + + // Construct from a vector of vertices + inline static auto from_vertices(const std::vector> &vertices) + -> collision::ConvexPolytope + { + auto data = collision::vertices_to_halfspaces(vertices); + return collision::ConvexPolytope( + data.nx.size(), data.nx, data.ny, data.nz, data.d, data.vx.size(), data.vx, data.vy, data.vz); + } + + // Construct from both representations + inline static auto from_both( + const std::vector> &vertices, + const std::vector> &planes) noexcept -> collision::ConvexPolytope + { + std::vector nx, ny, nz, d; + nx.reserve(planes.size()); + ny.reserve(planes.size()); + nz.reserve(planes.size()); + d.reserve(planes.size()); + + for (const auto &plane : planes) + { + nx.emplace_back(plane[0]); + ny.emplace_back(plane[1]); + nz.emplace_back(plane[2]); + d.emplace_back(plane[3]); + } + + std::vector vx, vy, vz; + vx.reserve(vertices.size()); + vy.reserve(vertices.size()); + vz.reserve(vertices.size()); + + for (const auto &v : vertices) + { + vx.emplace_back(v[0]); + vy.emplace_back(v[1]); + vz.emplace_back(v[2]); + } + + return collision::ConvexPolytope( + planes.size(), nx, ny, nz, d, vertices.size(), vx, vy, vz); + } + } // namespace polytope } // namespace vamp::collision::factory diff --git a/src/impl/vamp/collision/gjk.hh b/src/impl/vamp/collision/gjk.hh new file mode 100644 index 00000000..9b9967b0 --- /dev/null +++ b/src/impl/vamp/collision/gjk.hh @@ -0,0 +1,359 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +// Scalar GJK distance queries between a point and the convex hull of a set of vertices. Ported from +// the `carom-env` polytope implementation in rumple. + +namespace vamp::collision::gjk +{ + using Point = Eigen::Vector3f; + + inline constexpr float epsilon = std::numeric_limits::epsilon(); + + // The vertex, among those given by parallel coordinate arrays `xs`/`ys`/`zs` of length `n`, + // furthest in direction `d` (the GJK support function). + inline auto + support(const float *xs, const float *ys, const float *zs, std::size_t n, const Point &d) noexcept + -> Point + { + using Coords = Eigen::Map; + const auto size = static_cast(n); + + Eigen::Index best; + (Coords(xs, size) * d.x() + Coords(ys, size) * d.y() + Coords(zs, size) * d.z()).maxCoeff(&best); + return {xs[best], ys[best], zs[best]}; + } + + // A fixed-capacity stack of up to 4 points (the largest possible simplex in 3D GJK), so that the + // collision-check hot path never allocates. + struct Simplex + { + std::array points; + std::uint8_t len; + + static auto single(const Point &a) noexcept -> Simplex + { + return Simplex{{a, a, a, a}, 1}; + } + + static auto triangle(const Point &a, const Point &b, const Point &c) noexcept -> Simplex + { + return Simplex{{a, b, c, c}, 3}; + } + + void push(const Point &p) noexcept + { + points[len] = p; + ++len; + } + + // Whether `p` (numerically) already appears in this simplex. + [[nodiscard]] auto contains(const Point &p) const noexcept -> bool + { + for (auto i = 0U; i < len; ++i) + { + if ((p - points[i]).squaredNorm() <= epsilon) + { + return true; + } + } + + return false; + } + + void set1(const Point &a) noexcept + { + points[0] = a; + len = 1; + } + + void set2(const Point &a, const Point &b) noexcept + { + points[0] = a; + points[1] = b; + len = 2; + } + }; + + inline auto closest_on_segment(Simplex &simplex) noexcept -> Point + { + const Point a = simplex.points[0]; + const Point b = simplex.points[1]; + const Point ab = b - a; + const float denom = ab.squaredNorm(); + if (denom <= epsilon) + { + simplex.set1(a); + return a; + } + + const float t = -a.dot(ab) / denom; + if (t <= 0.F) + { + simplex.set1(a); + return a; + } + + if (t >= 1.F) + { + simplex.set1(b); + return b; + } + + return a + t * ab; + } + + // Closest point to the origin on triangle `simplex[0..3]`, using the standard Voronoi-region test + // (Ericson, "Real-Time Collision Detection", `ClosestPtPointTriangle`), specialized to a query + // point of the origin. Reduces `simplex` to whichever vertex/edge/face is closest. + inline auto closest_on_triangle(Simplex &simplex) noexcept -> Point + { + const Point a = simplex.points[0]; + const Point b = simplex.points[1]; + const Point c = simplex.points[2]; + + const Point ab = b - a; + const Point ac = c - a; + + const float d1 = -ab.dot(a); + const float d2 = -ac.dot(a); + if (d1 <= 0.F and d2 <= 0.F) + { + simplex.set1(a); + return a; + } + + const float d3 = -ab.dot(b); + const float d4 = -ac.dot(b); + if (d3 >= 0.F and d4 <= d3) + { + simplex.set1(b); + return b; + } + + const float vc = d1 * d4 - d3 * d2; + if (vc <= 0.F and d1 >= 0.F and d3 <= 0.F) + { + const float v = d1 / (d1 - d3); + simplex.set2(a, b); + return a + v * ab; + } + + const float d5 = -ab.dot(c); + const float d6 = -ac.dot(c); + if (d6 >= 0.F and d5 <= d6) + { + simplex.set1(c); + return c; + } + + const float vb = d5 * d2 - d1 * d6; + if (vb <= 0.F and d2 >= 0.F and d6 <= 0.F) + { + const float w = d2 / (d2 - d6); + simplex.set2(a, c); + return a + w * ac; + } + + const float va = d3 * d6 - d5 * d4; + if (va <= 0.F and (d4 - d3) >= 0.F and (d5 - d6) >= 0.F) + { + const float w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + simplex.set2(b, c); + return b + w * (c - b); + } + + const float denom = 1.F / (va + vb + vc); + const float v = vb * denom; + const float w = vc * denom; + return a + v * ab + w * ac; + } + + // Whether the origin and vertex `d` lie on opposite sides of the plane through `a`, `b`, `c` or + // `d` is coplanar with `a`, `b`, `c`. + inline auto point_outside_face(const Point &a, const Point &b, const Point &c, const Point &d) noexcept + -> bool + { + const Point normal = (b - a).cross(c - a); + const float sign_origin = -normal.dot(a); + const float sign_d = normal.dot(d - a); + return sign_origin * sign_d <= 0.F; + } + + // Closest point to the origin on tetrahedron `simplex[0..4]`, following Ericson's + // `ClosestPtPointTetrahedron`: test each face plane to see whether the origin is outside of it, and + // if so consider the closest point on that face. Returns `std::nullopt` if the origin is inside all + // four face planes, i.e. inside the tetrahedron. + inline auto closest_on_tetrahedron(Simplex &simplex) noexcept -> std::optional + { + const Point a = simplex.points[0]; + const Point b = simplex.points[1]; + const Point c = simplex.points[2]; + const Point d = simplex.points[3]; + + float best_sq = std::numeric_limits::max(); + Point best_point = a; + Simplex best_simplex = Simplex::triangle(a, b, c); + bool outside_any = false; + + const std::array, 4> faces = {{ + {a, b, c, d}, + {a, c, d, b}, + {a, d, b, c}, + {b, d, c, a}, + }}; + + for (const auto &[x, y, z, w] : faces) + { + if (point_outside_face(x, y, z, w)) + { + outside_any = true; + auto face = Simplex::triangle(x, y, z); + const Point p = closest_on_triangle(face); + const float sq = p.squaredNorm(); + if (sq < best_sq) + { + best_sq = sq; + best_point = p; + best_simplex = face; + } + } + } + + if (outside_any) + { + simplex = best_simplex; + return best_point; + } + + return std::nullopt; + } + + // Reduce `simplex` to the smallest sub-simplex containing the point on it closest to the origin, + // and return that closest point. Returns `std::nullopt` if the origin lies inside the simplex (only + // possible when `simplex` is a tetrahedron), which means the query point is inside the polytope. + inline auto closest_on_simplex(Simplex &simplex) noexcept -> std::optional + { + switch (simplex.len) + { + case 1: + return simplex.points[0]; + case 2: + return closest_on_segment(simplex); + case 3: + return closest_on_triangle(simplex); + default: + return closest_on_tetrahedron(simplex); + } + } + + // The core GJK loop, computing the squared distance from the convex hull of the `n` vertices given + // by parallel coordinate arrays `xs`/`ys`/`zs` to `point`, using `seed` to seed the initial search + // direction. + // + // If `radius_sq` is set, the loop is allowed to return as soon as it can prove that the true squared + // distance is on one side of `radius_sq` or the other, rather than running to full convergence. The + // returned value is only guaranteed to be on the correct side of `radius_sq`, not necessarily the + // exact distance. If `radius_sq` is unset, the loop always converges and returns the exact squared + // distance. + // + // Returns the largest finite float if there are no vertices, since the distance to an empty set is + // unbounded. This is not infinity because VAMP's Release builds under clang on x86 assume no value is + // ever infinite (`-fno-honor-infinities`). + inline auto sql2( + const float *xs, + const float *ys, + const float *zs, + std::size_t n, + const Point &point, + const Point &seed, + std::optional radius_sq = std::nullopt) noexcept -> float + { + if (n == 0) + { + return std::numeric_limits::max(); + } + + Point direction = seed - point; + if (direction.squaredNorm() <= epsilon) + { + direction = Point::UnitX(); + } + + // simplex always stores points with `point` subtracted + auto simplex = Simplex::single(support(xs, ys, zs, n, direction) - point); + Point closest = simplex.points[0]; + + const std::size_t max_iterations = n + 8; + for (auto iter = 0U; iter < max_iterations; ++iter) + { + const float dist_sq = closest.squaredNorm(); + if (dist_sq <= epsilon) + { + return 0.F; + } + + // `closest` is always a point of the polytope, so `dist_sq` is a valid upper bound on the + // true distance: if it is already within the ball, we are done. + if (radius_sq and dist_sq <= *radius_sq) + { + return dist_sq; + } + + direction = -closest; + const Point new_point = support(xs, ys, zs, n, direction) - point; + + const float d_new = new_point.dot(direction); + const float d_closest = closest.dot(direction); + + // `new_point` is a supporting point of the polytope in `direction`, so the whole polytope + // lies on its near side of the hyperplane through it: if even that hyperplane is farther + // from the origin than `r`, the polytope can't collide. + if (radius_sq and d_new < 0.F and d_new * d_new > *radius_sq * dist_sq) + { + return dist_sq; + } + + // If no candidate point makes enough progress, or the support function just re-found a + // point already in the simplex (which would make it degenerate), we've converged. + const float tolerance = epsilon * (1.F + std::abs(d_closest)); + if (d_new - d_closest <= tolerance or simplex.contains(new_point)) + { + return dist_sq; + } + + simplex.push(new_point); + const auto reduced = closest_on_simplex(simplex); + if (not reduced) + { + return 0.F; + } + + // The check above is only a heuristic lower bound on how much `new_point` could improve the + // distance, computed from the *old* simplex: on an exactly degenerate (e.g. coplanar) + // sub-simplex, `closest_on_tetrahedron`'s face tests can end up deterministically dropping + // the same vertex that floating-point noise in `direction` just as deterministically + // re-selects, cycling forever without either heuristic above ever firing. Comparing the + // actual squared distance before and after the simplex update catches that case directly, + // since a true cycle makes no real progress here even when the heuristic above claims + // otherwise. + const float new_dist_sq = reduced->squaredNorm(); + if (dist_sq - new_dist_sq <= tolerance) + { + return new_dist_sq; + } + + closest = *reduced; + } + + return closest.squaredNorm(); + } +} // namespace vamp::collision::gjk diff --git a/src/impl/vamp/collision/polytope_convert.hh b/src/impl/vamp/collision/polytope_convert.hh new file mode 100644 index 00000000..c1b8b327 --- /dev/null +++ b/src/impl/vamp/collision/polytope_convert.hh @@ -0,0 +1,216 @@ +#pragma once + +#include +#include +#include +#include + +extern "C" +{ +#include +#include +} + +namespace vamp::collision +{ + struct PolytopeData + { + std::vector nx, ny, nz, d; + std::vector vx, vy, vz; + }; + + inline void cdd_init() + { + static bool initialized = false; + if (not initialized) + { + dd_set_global_constants(); + initialized = true; + } + } + + inline auto vertices_to_halfspaces( + const std::vector &vx, + const std::vector &vy, + const std::vector &vz) -> PolytopeData + { + cdd_init(); + + const std::size_t num_vertices = vx.size(); + if (num_vertices < 4) + { + throw std::invalid_argument("Need at least 4 vertices for a 3D convex polytope"); + } + + PolytopeData result; + result.vx = vx; + result.vy = vy; + result.vz = vz; + + // Each row is [1, x, y, z] for a vertex (1 indicates vertex, not ray) + dd_MatrixPtr vertices_matrix = dd_CreateMatrix(num_vertices, 4); + vertices_matrix->representation = dd_Generator; + vertices_matrix->numbtype = dd_Real; + + for (auto i = 0U; i < num_vertices; ++i) + { + dd_set_d(vertices_matrix->matrix[i][0], 1.0); + dd_set_d(vertices_matrix->matrix[i][1], static_cast(vx[i])); + dd_set_d(vertices_matrix->matrix[i][2], static_cast(vy[i])); + dd_set_d(vertices_matrix->matrix[i][3], static_cast(vz[i])); + } + + dd_ErrorType err = dd_NoError; + dd_PolyhedraPtr poly = dd_DDMatrix2Poly(vertices_matrix, &err); + + if (err != dd_NoError or poly == nullptr) + { + dd_FreeMatrix(vertices_matrix); + if (poly) + { + dd_FreePolyhedra(poly); + } + throw std::runtime_error("cddlib: Failed to convert vertices to halfspaces"); + } + + dd_MatrixPtr inequalities = dd_CopyInequalities(poly); + + result.nx.reserve(inequalities->rowsize); + result.ny.reserve(inequalities->rowsize); + result.nz.reserve(inequalities->rowsize); + result.d.reserve(inequalities->rowsize); + + for (dd_rowrange i = 0; i < inequalities->rowsize; ++i) + { + // cddlib format: b + a1*x1 + a2*x2 + a3*x3 >= 0 + // We want: nx*x + ny*y + nz*z <= d + // So: -a1*x - a2*y - a3*z <= b + double b = dd_get_d(inequalities->matrix[i][0]); + double a1 = dd_get_d(inequalities->matrix[i][1]); + double a2 = dd_get_d(inequalities->matrix[i][2]); + double a3 = dd_get_d(inequalities->matrix[i][3]); + + // Normalize the plane equation + double norm = std::sqrt(a1 * a1 + a2 * a2 + a3 * a3); + if (norm > 1e-10) + { + result.nx.emplace_back(static_cast(-a1 / norm)); + result.ny.emplace_back(static_cast(-a2 / norm)); + result.nz.emplace_back(static_cast(-a3 / norm)); + result.d.emplace_back(static_cast(b / norm)); + } + } + + dd_FreeMatrix(inequalities); + dd_FreePolyhedra(poly); + dd_FreeMatrix(vertices_matrix); + + return result; + } + + inline auto halfspaces_to_vertices( + const std::vector &nx, + const std::vector &ny, + const std::vector &nz, + const std::vector &d) -> PolytopeData + { + cdd_init(); + + const std::size_t num_planes = nx.size(); + if (num_planes < 4) + { + throw std::invalid_argument("Need at least 4 halfspaces for a bounded 3D polytope"); + } + + PolytopeData result; + result.nx = nx; + result.ny = ny; + result.nz = nz; + result.d = d; + + dd_MatrixPtr ineq_matrix = dd_CreateMatrix(num_planes, 4); + ineq_matrix->representation = dd_Inequality; + ineq_matrix->numbtype = dd_Real; + + for (std::size_t i = 0; i < num_planes; ++i) + { + dd_set_d(ineq_matrix->matrix[i][0], static_cast(d[i])); + dd_set_d(ineq_matrix->matrix[i][1], static_cast(-nx[i])); + dd_set_d(ineq_matrix->matrix[i][2], static_cast(-ny[i])); + dd_set_d(ineq_matrix->matrix[i][3], static_cast(-nz[i])); + } + + dd_ErrorType err = dd_NoError; + dd_PolyhedraPtr poly = dd_DDMatrix2Poly(ineq_matrix, &err); + + if (err != dd_NoError || poly == nullptr) + { + dd_FreeMatrix(ineq_matrix); + if (poly) + { + dd_FreePolyhedra(poly); + } + throw std::runtime_error("cddlib: Failed to convert halfspaces to vertices"); + } + + dd_MatrixPtr generators = dd_CopyGenerators(poly); + + result.vx.reserve(generators->rowsize); + result.vy.reserve(generators->rowsize); + result.vz.reserve(generators->rowsize); + + for (dd_rowrange i = 0; i < generators->rowsize; ++i) + { + double type = dd_get_d(generators->matrix[i][0]); + if (type > 0.5) + { + result.vx.emplace_back(static_cast(dd_get_d(generators->matrix[i][1]))); + result.vy.emplace_back(static_cast(dd_get_d(generators->matrix[i][2]))); + result.vz.emplace_back(static_cast(dd_get_d(generators->matrix[i][3]))); + } + } + + dd_FreeMatrix(generators); + dd_FreePolyhedra(poly); + dd_FreeMatrix(ineq_matrix); + + return result; + } + + inline auto vertices_to_halfspaces(const std::vector> &vertices) -> PolytopeData + { + std::vector vx, vy, vz; + vx.reserve(vertices.size()); + vy.reserve(vertices.size()); + vz.reserve(vertices.size()); + + for (const auto &v : vertices) + { + vx.emplace_back(v[0]); + vy.emplace_back(v[1]); + vz.emplace_back(v[2]); + } + + return vertices_to_halfspaces(vx, vy, vz); + } + + inline auto halfspaces_to_vertices(const std::vector> &planes) -> PolytopeData + { + std::vector nx, ny, nz, d; + nx.reserve(planes.size()); + ny.reserve(planes.size()); + nz.reserve(planes.size()); + d.reserve(planes.size()); + + for (const auto &p : planes) + { + nx.emplace_back(p[0]); + ny.emplace_back(p[1]); + nz.emplace_back(p[2]); + d.emplace_back(p[3]); + } + + return halfspaces_to_vertices(nx, ny, nz, d); + } + +} // namespace vamp::collision diff --git a/src/impl/vamp/collision/shapes.hh b/src/impl/vamp/collision/shapes.hh index 19b001ba..03da6615 100644 --- a/src/impl/vamp/collision/shapes.hh +++ b/src/impl/vamp/collision/shapes.hh @@ -1,11 +1,15 @@ #pragma once #include -#include +#include +#include +#include #include #include +#include +#include #include namespace vamp::collision @@ -310,4 +314,143 @@ namespace vamp::collision { } }; + + // A convex polytope with dual representation: + // - H-representation: half-planes + // - V-representation: vertices + template + struct ConvexPolytope : public Shape + { + // Halfspaces + std::size_t num_planes; + std::vector nx; // plane normals + std::vector ny; + std::vector nz; + std::vector d; // plane offsets (n.x <= d defines interior) + + // Vertices + std::size_t num_vertices; + std::vector vx; + std::vector vy; + std::vector vz; + + // Oriented bounding box for broadphase + Cuboid obb; + + ConvexPolytope() = default; + + explicit ConvexPolytope( + std::size_t num_planes, + const std::vector &nx, + const std::vector &ny, + const std::vector &nz, + const std::vector &d, + std::size_t num_vertices, + const std::vector &vx, + const std::vector &vy, + const std::vector &vz) + : Shape() + , num_planes(num_planes) + , nx(nx) + , ny(ny) + , nz(nz) + , d(d) + , num_vertices(num_vertices) + , vx(vx) + , vy(vy) + , vz(vz) + { + obb = compute_obb(); + Shape::min_distance = compute_min_distance(); + } + + inline auto compute_min_distance() -> DataT + { + // Exact distance from the origin to the polytope. + + if (num_vertices == 0) + { + return DataT(std::numeric_limits::max()); + } + + const float dist_sq = gjk::sql2( + vx.data(), + vy.data(), + vz.data(), + num_vertices, + Eigen::Vector3f::Zero(), + Eigen::Vector3f(vx[0], vy[0], vz[0])); + return DataT(std::sqrt(dist_sq)); + } + + inline auto compute_obb() -> Cuboid + { + const auto n = static_cast(num_vertices); + Eigen::Matrix3Xf vertices(3, n); + vertices.row(0) = Eigen::Map(vx.data(), n); + vertices.row(1) = Eigen::Map(vy.data(), n); + vertices.row(2) = Eigen::Map(vz.data(), n); + + // Principal axes of the vertex distribution + const Eigen::Matrix3Xf centered = vertices.colwise() - vertices.rowwise().mean(); + const Eigen::SelfAdjointEigenSolver solver(centered * centered.transpose()); + Eigen::Matrix3f axes = solver.eigenvectors(); + + if (axes.determinant() < 0) + { + axes.col(0) *= -1; + } + + // Extents of the vertices along each axis + const Eigen::Matrix3Xf projected = axes.transpose() * vertices; + const Eigen::Vector3f lo = projected.rowwise().minCoeff(); + const Eigen::Vector3f hi = projected.rowwise().maxCoeff(); + + const Eigen::Vector3f center = axes * (lo + hi) * 0.5F; + const Eigen::Vector3f half = (hi - lo) * 0.5F; + const Eigen::Vector3f axis_0 = axes.col(0); + const Eigen::Vector3f axis_1 = axes.col(1); + const Eigen::Vector3f axis_2 = axes.col(2); + + return Cuboid( + DataT(center.x()), + DataT(center.y()), + DataT(center.z()), + DataT(axis_0.x()), + DataT(axis_0.y()), + DataT(axis_0.z()), + DataT(axis_1.x()), + DataT(axis_1.y()), + DataT(axis_1.z()), + DataT(axis_2.x()), + DataT(axis_2.y()), + DataT(axis_2.z()), + DataT(half.x()), + DataT(half.y()), + DataT(half.z())); + } + + template + explicit ConvexPolytope(const ConvexPolytope &other) + : Shape(other) + , num_planes(other.num_planes) + , nx(other.nx.size()) + , ny(other.ny.size()) + , nz(other.nz.size()) + , d(other.d.size()) + , num_vertices(other.num_vertices) + , vx(other.vx) + , vy(other.vy) + , vz(other.vz) + , obb(other.obb) + { + for (auto i = 0U; i < other.nx.size(); ++i) + { + nx[i] = DataT(other.nx[i]); + ny[i] = DataT(other.ny[i]); + nz[i] = DataT(other.nz[i]); + d[i] = DataT(other.d[i]); + } + } + }; } // namespace vamp::collision diff --git a/src/impl/vamp/collision/sphere_polytope.hh b/src/impl/vamp/collision/sphere_polytope.hh new file mode 100644 index 00000000..34fd9096 --- /dev/null +++ b/src/impl/vamp/collision/sphere_polytope.hh @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include +#include + +namespace vamp::collision +{ + // Test a block of spheres against a convex polytope. The polytope's oriented bounding box acts as a + // SIMD broadphase, and each sphere that survives it is checked exactly with a scalar GJK distance + // query against the polytope's vertices, seeded from the sphere's closest point on the bounding box. + // + // The result has a negative lane if and only if some sphere collides with the polytope. + // As soon as one colliding sphere is found, the remaining spheres are skipped and keep their broadphase + // value, so the result tells whether any sphere collides, but not necessarily which ones. + template + inline auto sphere_polytope( + const ConvexPolytope &p, + const DataT &cx, + const DataT &cy, + const DataT &cz, + const DataT &r) noexcept -> DataT + { + const auto rsq = r * r; + const auto obb_dist = sphere_cuboid(p.obb, cx, cy, cz, rsq); + + if (obb_dist.test_zero()) + { + return obb_dist; + } + + // Closest point on the bounding box to each sphere center, used to seed the GJK search direction + const auto &b = p.obb; + const auto xs = cx - b.x; + const auto ys = cy - b.y; + const auto zs = cz - b.z; + const auto t1 = clamp(dot_3(b.axis_1_x, b.axis_1_y, b.axis_1_z, xs, ys, zs), -b.axis_1_r, b.axis_1_r); + const auto t2 = clamp(dot_3(b.axis_2_x, b.axis_2_y, b.axis_2_z, xs, ys, zs), -b.axis_2_r, b.axis_2_r); + const auto t3 = clamp(dot_3(b.axis_3_x, b.axis_3_y, b.axis_3_z, xs, ys, zs), -b.axis_3_r, b.axis_3_r); + const auto seed_x = b.x + b.axis_1_x * t1 + b.axis_2_x * t2 + b.axis_3_x * t3; + const auto seed_y = b.y + b.axis_1_y * t1 + b.axis_2_y * t2 + b.axis_3_y * t3; + const auto seed_z = b.z + b.axis_1_z * t1 + b.axis_2_z * t2 + b.axis_3_z * t3; + + auto result = obb_dist.to_array(); + const auto x_arr = cx.to_array(); + const auto y_arr = cy.to_array(); + const auto z_arr = cz.to_array(); + const auto rsq_arr = rsq.to_array(); + const auto sx_arr = seed_x.to_array(); + const auto sy_arr = seed_y.to_array(); + const auto sz_arr = seed_z.to_array(); + + // do each lane sequentially. + // I tried many times to figure out a good block-parallel way to do this, but it was always faster to + // do simple sequential GJK. + for (auto lane = 0U; lane < result.size(); ++lane) + { + if (not(result[lane] < 0.F)) + { + continue; + } + + const float r_sq = rsq_arr[lane]; + const float dist_sq = gjk::sql2( + p.vx.data(), + p.vy.data(), + p.vz.data(), + p.num_vertices, + Eigen::Vector3f(x_arr[lane], y_arr[lane], z_arr[lane]), + Eigen::Vector3f(sx_arr[lane], sy_arr[lane], sz_arr[lane]), + r_sq); + + result[lane] = dist_sq - r_sq; + if (result[lane] < 0.F) + { + break; + } + } + + return DataT(result.data(), false); + } + + template + inline auto sphere_polytope(const ConvexPolytope &p, const Sphere &s) noexcept -> DataT + { + return sphere_polytope(p, s.x, s.y, s.z, s.r); + } +} // namespace vamp::collision diff --git a/src/impl/vamp/collision/validity.hh b/src/impl/vamp/collision/validity.hh index b555c13e..f460bc72 100644 --- a/src/impl/vamp/collision/validity.hh +++ b/src/impl/vamp/collision/validity.hh @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace vamp @@ -137,6 +138,20 @@ namespace vamp } } + for (const auto &ep : e.polytopes) + { + const auto diff = ep.min_distance - max_extent; + if (diff.test_zero()) + { + break; + } + + if (not collision::sphere_polytope(ep, sx, sy, sz, sr).test_zero()) + { + return true; + } + } + const std::array positions = {sx, sy, sz}; for (const auto &pc : e.pointclouds) { @@ -245,6 +260,20 @@ namespace vamp } } + for (const auto &ep : e.polytopes) + { + const auto diff = ep.min_distance - max_extent; + if (diff.test_zero()) + { + break; + } + + if (not collision::sphere_polytope(ep, sx, sy, sz, sr).test_zero()) + { + objects.emplace_back(ep.name); + } + } + return objects; } diff --git a/src/vamp/__init__.py b/src/vamp/__init__.py index 032ea17f..2da2ea7c 100644 --- a/src/vamp/__init__.py +++ b/src/vamp/__init__.py @@ -1,6 +1,7 @@ __all__ = [ "robots", "png_to_heightfield", + "mesh_to_polytopes", "configure_robot_and_planner_with_kwargs", "problem_dict_to_vamp", "results_to_dict", @@ -9,6 +10,7 @@ "Sphere", "Cuboid", "Cylinder", + "ConvexPolytope", "RRTCSettings", "PRMSettings", "PRMNeighborParams", @@ -22,8 +24,7 @@ ] from pathlib import Path -from typing import Any, Dict, Optional, Tuple, Union, List -import importlib +from typing import Any, Dict, Tuple, Union, List from numpy import float32 from numpy.typing import NDArray @@ -33,6 +34,7 @@ from ._core import Sphere as Sphere from ._core import Cuboid as Cuboid from ._core import Cylinder as Cylinder +from ._core import ConvexPolytope as ConvexPolytope from ._core import Attachment as Attachment from ._core import Environment as Environment from ._core import PRMNeighborParams as PRMNeighborParams @@ -68,6 +70,54 @@ def png_to_heightfield( return _core.make_heightfield(center, scaling, array.shape, list(array.flatten())) +def mesh_to_polytopes( + filename: Path, + position: Tuple[float, float, float] = (0.0, 0.0, 0.0), + scale: float = 1.0, + convex_decomposition: bool = False, + name: str = "mesh", + **decomposition_kwargs, + ) -> List[ConvexPolytope]: + import trimesh + import numpy as np + + mesh = trimesh.load(str(filename), force = 'mesh') + + def hull_to_polytope(hull, scale, position, polytope_name): + vertices = (np.array(hull.vertices) * scale + position).astype(np.float32) + normals = np.array(hull.face_normals).astype(np.float32) + face_vertices = hull.vertices[hull.faces[:, 0]] + d_orig = np.sum(normals * face_vertices, axis = 1) + d_transformed = (d_orig * scale + np.sum(normals * position, axis = 1)).astype(np.float32) + planes = np.column_stack([normals, d_transformed]).astype(np.float32) + + polytope = ConvexPolytope.from_both(vertices, planes) + polytope.name = polytope_name + return polytope + + if convex_decomposition: + parts = trimesh.decomposition.convex_decomposition(mesh, **decomposition_kwargs) + if not isinstance(parts, list): + parts = [parts] + + polytopes = [] + for i, part_data in enumerate(parts): + if isinstance(part_data, dict): + part_mesh = trimesh.Trimesh(**part_data) + else: + part_mesh = part_data + + hull = part_mesh.convex_hull + polytope_name = f"{name}_{i}" if len(parts) > 1 else name + polytopes.append(hull_to_polytope(hull, scale, position, polytope_name)) + + return polytopes + + else: + hull = mesh.convex_hull + return [hull_to_polytope(hull, scale, position, name)] + + def configure_robot_and_planner_with_kwargs(robot_name: str, planner_name: str, **kwargs): robot_module = getattr(_core, robot_name) try: diff --git a/src/vamp/pybullet_interface.py b/src/vamp/pybullet_interface.py index 2c5cdc05..e0ac502b 100644 --- a/src/vamp/pybullet_interface.py +++ b/src/vamp/pybullet_interface.py @@ -253,6 +253,62 @@ def add_sphere( return multibody_id + def add_polytope( + self, + polytope, + name: Optional[str] = None, + color: Optional[Union[List[float], str]] = None, + ): + from scipy.spatial import ConvexHull + + vertices = np.column_stack([polytope.vx, polytope.vy, polytope.vz]) + hull = ConvexHull(vertices) + + # Normals aren't always outward facing... + centroid = vertices.mean(axis = 0) + corrected_simplices = [] + for simplex in hull.simplices: + v0, v1, v2 = vertices[simplex] + normal = np.cross(v1 - v0, v2 - v0) + face_center = (v0 + v1 + v2) / 3 + to_face = face_center - centroid + if np.dot(normal, to_face) < 0: + corrected_simplices.append([simplex[0], simplex[2], simplex[1]]) + else: + corrected_simplices.append(simplex.tolist()) + indices = np.array(corrected_simplices).flatten().tolist() + + with DisableRendering(self.client): + col_shape_id = self.client.createCollisionShape( + pb.GEOM_MESH, + vertices = vertices.tolist(), + indices = indices, + ) + + vis_shape_id = self.client.createVisualShape( + pb.GEOM_MESH, + vertices = vertices.tolist(), + indices = indices, + rgbaColor = handle_color(name or polytope.name, color), + ) + + multibody_id = self.client.createMultiBody( + baseCollisionShapeIndex = col_shape_id, + baseVisualShapeIndex = vis_shape_id, + basePosition = [0, 0, 0], + ) + + display_name = name or polytope.name + if display_name: + centroid = vertices.mean(axis = 0) + self.client.addUserDebugText( + text = display_name, + textPosition = centroid.tolist(), + textColorRGB = [0., 0., 0.], + ) + + return multibody_id + def update_object_position( self, multibody_id: int, position: Position, rot_xywz: XYZWQuaternion = [0, 0, 0, 1] ): diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b0b1bafc..a211dec7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -5,6 +5,7 @@ add_executable(vamp_tests test_vector.cc test_halton.cc test_capt.cc + test_polytope.cc ) target_link_libraries(vamp_tests PRIVATE vamp_cpp Catch2::Catch2WithMain) diff --git a/tests/test_polytope.cc b/tests/test_polytope.cc new file mode 100644 index 00000000..a5e37c02 --- /dev/null +++ b/tests/test_polytope.cc @@ -0,0 +1,350 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +using Catch::Approx; +using vamp::FloatVector; +using vamp::FloatVectorWidth; +namespace vc = vamp::collision; + +namespace +{ + using Vertices = std::vector>; + using V = FloatVector; + + auto make_polytope(const Vertices &points) -> vc::ConvexPolytope + { + std::vector vx, vy, vz; + for (const auto &[x, y, z] : points) + { + vx.push_back(x); + vy.push_back(y); + vz.push_back(z); + } + + // GJK only needs the vertices, so skip the halfspace representation + return vc::ConvexPolytope(0, {}, {}, {}, {}, points.size(), vx, vy, vz); + } + + auto box(const Eigen::AlignedBox3f &aabb) -> Vertices + { + Vertices corners; + for (auto i = 0U; i < 8; ++i) + { + const Eigen::Vector3f c = aabb.corner(static_cast(i)); + corners.push_back({c.x(), c.y(), c.z()}); + } + + return corners; + } + + auto cube() -> Vertices + { + return box({Eigen::Vector3f::Constant(-1.F), Eigen::Vector3f::Constant(1.F)}); + } + + auto tetrahedron() -> Vertices + { + return {{0.F, 0.F, 0.F}, {1.F, 0.F, 0.F}, {0.F, 1.F, 0.F}, {0.F, 0.F, 1.F}}; + } + + // Exact squared distance from a point to the convex hull of `points` + auto sql2_to(const Vertices &points, float x, float y, float z) -> float + { + const auto p = make_polytope(points); + return vc::gjk::sql2( + p.vx.data(), + p.vy.data(), + p.vz.data(), + p.num_vertices, + Eigen::Vector3f(x, y, z), + Eigen::Vector3f(p.vx[0], p.vy[0], p.vz[0])); + } + + // Collision of a single sphere via the full SIMD path (every lane holds the same sphere) + auto collides_ball(const vc::ConvexPolytope &p, float x, float y, float z, float r) -> bool + { + return not vc::sphere_polytope(p, V::fill(x), V::fill(y), V::fill(z), V::fill(r)).test_zero(); + } + + auto collides_ball(const Vertices &points, float x, float y, float z, float r) -> bool + { + return collides_ball(vc::ConvexPolytope(make_polytope(points)), x, y, z, r); + } +} // namespace + +TEST_CASE("GJK distance from a point inside a cube is zero", "[collision][polytope]") +{ + REQUIRE(sql2_to(cube(), 0.F, 0.F, 0.F) == 0.F); + REQUIRE(sql2_to(cube(), 0.5F, -0.5F, 0.2F) == 0.F); +} + +TEST_CASE("GJK distance to cube face and vertex", "[collision][polytope]") +{ + REQUIRE(sql2_to(cube(), 2.F, 0.F, 0.F) == Approx(1.F)); + REQUIRE(sql2_to(cube(), 2.F, 2.F, 2.F) == Approx(3.F)); +} + +TEST_CASE("GJK distance to degenerate polytopes", "[collision][polytope]") +{ + REQUIRE(sql2_to({{1.F, 2.F, 3.F}}, 1.F, 2.F, 0.F) == Approx(9.F)); + REQUIRE(sql2_to({{0.F, 0.F, 0.F}, {2.F, 0.F, 0.F}}, 1.F, 1.F, 0.F) == Approx(1.F)); + + const Vertices triangle = {{0.F, 0.F, 0.F}, {1.F, 0.F, 0.F}, {0.F, 1.F, 0.F}}; + REQUIRE(sql2_to(triangle, 0.F, 0.F, 1.F) == Approx(1.F)); + REQUIRE(sql2_to(triangle, 0.25F, 0.25F, 1.F) == Approx(1.F)); +} + +TEST_CASE("GJK distance to tetrahedron", "[collision][polytope]") +{ + REQUIRE(sql2_to(tetrahedron(), 0.25F, 0.25F, 0.25F) == 0.F); + REQUIRE(sql2_to(tetrahedron(), 10.F, 10.F, 10.F) == Approx(841.F / 3.F)); +} + +TEST_CASE("GJK distance to no vertices is unbounded", "[collision][polytope]") +{ + REQUIRE( + vc::gjk::sql2(nullptr, nullptr, nullptr, 0, Eigen::Vector3f::Zero(), Eigen::Vector3f::Zero()) == + std::numeric_limits::max()); +} + +TEST_CASE("Sphere-polytope collision boundaries", "[collision][polytope]") +{ + REQUIRE(collides_ball(cube(), 0.F, 0.F, 0.F, 1e-3F)); + REQUIRE(collides_ball(cube(), 0.5F, -0.5F, 0.2F, 1e-3F)); + + REQUIRE(collides_ball(cube(), 2.F, 0.F, 0.F, 1.01F)); + REQUIRE_FALSE(collides_ball(cube(), 2.F, 0.F, 0.F, 0.99F)); + + const float vertex_dist = std::sqrt(3.F); + REQUIRE(collides_ball(cube(), 2.F, 2.F, 2.F, vertex_dist + 0.01F)); + REQUIRE_FALSE(collides_ball(cube(), 2.F, 2.F, 2.F, vertex_dist - 0.01F)); + + const float face_dist = std::sqrt(841.F / 3.F); + REQUIRE(collides_ball(tetrahedron(), 10.F, 10.F, 10.F, face_dist + 0.01F)); + REQUIRE_FALSE(collides_ball(tetrahedron(), 10.F, 10.F, 10.F, face_dist - 0.01F)); +} + +TEST_CASE( + "Sphere-polytope catches spheres near an edge but outside the halfspace projection", + "[collision][polytope]") +{ + // A thin slab rotated 45 degrees about z; a sphere near its long edge is within the OBB of the slab + // but only touches it through the edge + const Vertices diamond = { + {1.F, 0.F, -1.F}, + {0.F, 1.F, -1.F}, + {-1.F, 0.F, -1.F}, + {0.F, -1.F, -1.F}, + {1.F, 0.F, 1.F}, + {0.F, 1.F, 1.F}, + {-1.F, 0.F, 1.F}, + {0.F, -1.F, 1.F}, + }; + + // Distance from (0.6, 0.6, 0) to the face x + y = 1 is 0.2 / sqrt(2) + const float d = 0.2F / std::sqrt(2.F); + REQUIRE(collides_ball(diamond, 0.6F, 0.6F, 0.F, d + 0.01F)); + REQUIRE_FALSE(collides_ball(diamond, 0.6F, 0.6F, 0.F, d - 0.01F)); +} + +TEST_CASE("Sphere-polytope with random boxes matches closed-form AABB distance", "[collision][polytope]") +{ + std::mt19937 rng(2024); + std::uniform_real_distribution center(-5.F, 5.F); + std::uniform_real_distribution half_width(0.05F, 3.F); + std::uniform_real_distribution query(-10.F, 10.F); + std::uniform_real_distribution radius(0.F, 8.F); + + for (auto i = 0U; i < 1000; ++i) + { + const Eigen::Vector3f c(center(rng), center(rng), center(rng)); + const Eigen::Vector3f h(half_width(rng), half_width(rng), half_width(rng)); + const Eigen::AlignedBox3f aabb(c - h, c + h); + + const auto corners = box(aabb); + const float x = query(rng); + const float y = query(rng); + const float z = query(rng); + const float r = radius(rng); + + const float expected = aabb.squaredExteriorDistance(Eigen::Vector3f(x, y, z)); + const float actual = sql2_to(corners, x, y, z); + REQUIRE(actual == Approx(expected).epsilon(1e-4).margin(1e-4)); + + // Skip radii too close to the boundary to be decided robustly in single precision + if (std::abs(expected - r * r) > 1e-3F * (1.F + expected)) + { + REQUIRE(collides_ball(corners, x, y, z, r) == (expected < r * r)); + } + } +} + +TEST_CASE("Sphere-polytope SIMD lanes match per-sphere exact distance", "[collision][polytope]") +{ + std::mt19937 rng(99); + std::uniform_int_distribution count(1, 20); + std::uniform_real_distribution coord(-3.F, 3.F); + std::uniform_real_distribution query(-6.F, 6.F); + std::uniform_real_distribution radius(0.F, 4.F); + + std::size_t num_colliding = 0; + std::size_t num_free = 0; + for (auto i = 0U; i < 1000; ++i) + { + Vertices points(count(rng)); + for (auto &p : points) + { + p = {coord(rng), coord(rng), coord(rng)}; + } + + const auto polytope = make_polytope(points); + const vc::ConvexPolytope simd_polytope(polytope); + + alignas(V::S::Alignment) std::array xs, ys, zs, rs; + bool expected = false; + bool ambiguous = false; + for (auto lane = 0U; lane < V::num_scalars_rounded; ++lane) + { + xs[lane] = query(rng); + ys[lane] = query(rng); + zs[lane] = query(rng); + rs[lane] = radius(rng); + + const float dist_sq = sql2_to(points, xs[lane], ys[lane], zs[lane]); + const float r_sq = rs[lane] * rs[lane]; + expected = expected or dist_sq < r_sq; + ambiguous = ambiguous or std::abs(dist_sq - r_sq) < 1e-3F * (1.F + dist_sq); + + // Every lane should agree with its own single-sphere query + if (std::abs(dist_sq - r_sq) > 1e-3F * (1.F + dist_sq)) + { + REQUIRE( + collides_ball(simd_polytope, xs[lane], ys[lane], zs[lane], rs[lane]) == (dist_sq < r_sq)); + } + } + + if (ambiguous) + { + continue; + } + + const bool actual = + not vc::sphere_polytope(simd_polytope, V(xs.data()), V(ys.data()), V(zs.data()), V(rs.data())) + .test_zero(); + REQUIRE(actual == expected); + (actual ? num_colliding : num_free) += 1; + } + + // Make sure the fuzzing covers both outcomes + REQUIRE(num_colliding > 100); + REQUIRE(num_free > 100); +} + +TEST_CASE("GJK converges on coplanar box faces", "[collision][polytope]") +{ + // Regression case from rumple: the query point projects onto the interior of a box face, whose four + // corners are exactly coplanar + const Eigen::AlignedBox3f aabb( + Eigen::Vector3f(-5.368625309902576F, 1.5278480492984203F, -2.156301447748132F), + Eigen::Vector3f(-1.66844997461571F, 5.422646906343829F, 3.0607879685535417F)); + const float x = -4.743856992006581F; + const float y = 2.1847375590127527F; + const float z = -4.426160100672689F; + + REQUIRE( + sql2_to(box(aabb), x, y, z) == + Approx(aabb.squaredExteriorDistance(Eigen::Vector3f(x, y, z))).epsilon(1e-5)); +} + +TEST_CASE("Polytope min_distance is a lower bound on distance from the origin", "[collision][polytope]") +{ + // A large wall whose nearest vertex is far from the origin, but whose nearest face is close + const auto wall = + make_polytope(box({Eigen::Vector3f(0.5F, -10.F, -10.F), Eigen::Vector3f(1.F, 10.F, 10.F)})); + REQUIRE(wall.min_distance == Approx(0.5F)); +} + +TEST_CASE("Environment detects polytope collisions past the nearest-vertex cutoff", "[collision][polytope]") +{ + vc::Environment env; + env.polytopes.emplace_back( + make_polytope(box({Eigen::Vector3f(0.5F, -10.F, -10.F), Eigen::Vector3f(1.F, 10.F, 10.F)}))); + env.sort(); + + const vc::Environment simd_env(env); + REQUIRE(vamp::sphere_environment_in_collision(simd_env, V::fill(0.4F), V::fill(0.F), V::fill(0.F), 0.2F)); + REQUIRE_FALSE( + vamp::sphere_environment_in_collision(simd_env, V::fill(0.2F), V::fill(0.F), V::fill(0.F), 0.2F)); +} + +TEST_CASE("Polytopes built from halfspaces collide correctly", "[collision][polytope]") +{ + // Unit cube [-1, 1]^3 given by its six faces + const std::vector> planes = { + {1.F, 0.F, 0.F, 1.F}, + {-1.F, 0.F, 0.F, 1.F}, + {0.F, 1.F, 0.F, 1.F}, + {0.F, -1.F, 0.F, 1.F}, + {0.F, 0.F, 1.F, 1.F}, + {0.F, 0.F, -1.F, 1.F}, + }; + + const vc::ConvexPolytope p(vamp::collision::factory::polytope::from_planes(planes)); + REQUIRE(p.num_vertices == 8); + REQUIRE(collides_ball(p, 2.F, 0.F, 0.F, 1.01F)); + REQUIRE_FALSE(collides_ball(p, 2.F, 0.F, 0.F, 0.99F)); + REQUIRE(collides_ball(p, 2.F, 2.F, 2.F, std::sqrt(3.F) + 0.01F)); + REQUIRE_FALSE(collides_ball(p, 2.F, 2.F, 2.F, std::sqrt(3.F) - 0.01F)); +} + +TEST_CASE("Polytope OBB tightly bounds its vertices", "[collision][polytope]") +{ + std::mt19937 rng(7); + std::uniform_int_distribution count(1, 30); + std::uniform_real_distribution coord(-3.F, 3.F); + + for (auto i = 0U; i < 200; ++i) + { + Vertices points(count(rng)); + for (auto &p : points) + { + p = {coord(rng), coord(rng), coord(rng)}; + } + + const auto obb = make_polytope(points).obb; + const Eigen::Vector3f center(obb.x, obb.y, obb.z); + Eigen::Matrix3f axes; + axes << obb.axis_1_x, obb.axis_2_x, obb.axis_3_x, // + obb.axis_1_y, obb.axis_2_y, obb.axis_3_y, // + obb.axis_1_z, obb.axis_2_z, obb.axis_3_z; + const Eigen::Vector3f half(obb.axis_1_r, obb.axis_2_r, obb.axis_3_r); + + REQUIRE(axes.isUnitary(1e-4F)); + REQUIRE(axes.determinant() == Approx(1.F).margin(1e-4)); + + // Every vertex lies inside the box, and every face of the box touches some vertex + Eigen::Vector3f max_extent = Eigen::Vector3f::Constant(-1.F); + for (const auto &[x, y, z] : points) + { + const Eigen::Vector3f local = (axes.transpose() * (Eigen::Vector3f(x, y, z) - center)).cwiseAbs(); + REQUIRE(((local - half).array() <= 1e-4F).all()); + max_extent = max_extent.cwiseMax(local); + } + + REQUIRE(max_extent.isApprox(half, 1e-4F)); + } +}