mirror of
https://github.com/orange-cpp/omath.git
synced 2026-04-19 07:43:27 +00:00
Compare commits
12 Commits
v5.1.0.rc3
...
feature/ph
| Author | SHA1 | Date | |
|---|---|---|---|
| 69e9735063 | |||
| 35b8510cf4 | |||
| ba662e44e2 | |||
| 2002bcca83 | |||
| ffacba71e2 | |||
| 6081a9c426 | |||
| 8bbd504356 | |||
| 1d54039f57 | |||
| 93fc93d4f6 | |||
| b8a578774c | |||
| bfa6c77776 | |||
| 1341ef9925 |
@@ -34,6 +34,8 @@ option(OMATH_ENABLE_FORCE_INLINE
|
||||
|
||||
option(OMATH_ENABLE_LUA
|
||||
"omath bindings for lua" OFF)
|
||||
option(OMATH_ENABLE_PHYSX
|
||||
"PhysX-backed collider implementations" OFF)
|
||||
if(VCPKG_MANIFEST_FEATURES)
|
||||
foreach(omath_feature IN LISTS VCPKG_MANIFEST_FEATURES)
|
||||
if(omath_feature STREQUAL "imgui")
|
||||
@@ -48,6 +50,8 @@ if(VCPKG_MANIFEST_FEATURES)
|
||||
set(OMATH_BUILD_EXAMPLES ON)
|
||||
elseif(omath_feature STREQUAL "lua")
|
||||
set(OMATH_ENABLE_LUA ON)
|
||||
elseif(omath_feature STREQUAL "physx")
|
||||
set(OMATH_ENABLE_PHYSX ON)
|
||||
endif()
|
||||
|
||||
endforeach()
|
||||
@@ -78,6 +82,7 @@ if(${PROJECT_IS_TOP_LEVEL})
|
||||
message(STATUS "[${PROJECT_NAME}]: Coverage feature status ${OMATH_ENABLE_COVERAGE}")
|
||||
message(STATUS "[${PROJECT_NAME}]: Valgrind feature status ${OMATH_ENABLE_VALGRIND}")
|
||||
message(STATUS "[${PROJECT_NAME}]: Lua feature status ${OMATH_ENABLE_LUA}")
|
||||
message(STATUS "[${PROJECT_NAME}]: PhysX feature status ${OMATH_ENABLE_PHYSX}")
|
||||
endif()
|
||||
|
||||
file(GLOB_RECURSE OMATH_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/source/*.cpp")
|
||||
@@ -100,6 +105,13 @@ if (OMATH_ENABLE_LUA)
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE ${SOL2_INCLUDE_DIRS})
|
||||
endif ()
|
||||
|
||||
if (OMATH_ENABLE_PHYSX)
|
||||
target_compile_definitions(${PROJECT_NAME} PUBLIC OMATH_ENABLE_PHYSX)
|
||||
|
||||
find_package(unofficial-omniverse-physx-sdk CONFIG REQUIRED)
|
||||
target_link_libraries(${PROJECT_NAME} PUBLIC unofficial::omniverse-physx-sdk::sdk)
|
||||
endif ()
|
||||
|
||||
add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
|
||||
|
||||
target_compile_definitions(${PROJECT_NAME} PUBLIC OMATH_VERSION="${PROJECT_VERSION}")
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
"hidden": true,
|
||||
"inherits": ["linux-base", "vcpkg-base"],
|
||||
"cacheVariables": {
|
||||
"VCPKG_MANIFEST_FEATURES": "tests;imgui;avx2;lua"
|
||||
"VCPKG_MANIFEST_FEATURES": "tests;imgui;avx2;lua;physx"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
59
include/omath/collision/physx_box_collider.hpp
Normal file
59
include/omath/collision/physx_box_collider.hpp
Normal file
@@ -0,0 +1,59 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include "collider_interface.hpp"
|
||||
#include <PxPhysicsAPI.h>
|
||||
|
||||
namespace omath::collision
|
||||
{
|
||||
/// Axis-aligned box collider backed by PhysX PxBoxGeometry.
|
||||
/// Half-extents are stored in PhysX convention (positive values along each axis).
|
||||
class PhysXBoxCollider final : public ColliderInterface<Vector3<float>>
|
||||
{
|
||||
public:
|
||||
/// @param half_extents Half-widths along X, Y and Z axes (all must be > 0).
|
||||
/// @param origin World-space centre of the box.
|
||||
explicit PhysXBoxCollider(const VectorType& half_extents, const VectorType& origin = {})
|
||||
: m_geometry(physx::PxVec3(half_extents.x, half_extents.y, half_extents.z))
|
||||
, m_origin(origin)
|
||||
{
|
||||
}
|
||||
|
||||
/// Support function: returns the world-space point on the box furthest in @p direction.
|
||||
/// For a box, the furthest point along d is origin + (sign(d.x)*hx, sign(d.y)*hy, sign(d.z)*hz).
|
||||
[[nodiscard]]
|
||||
VectorType find_abs_furthest_vertex_position(const VectorType& direction) const override
|
||||
{
|
||||
const auto& he = m_geometry.halfExtents;
|
||||
return {
|
||||
m_origin.x + (direction.x >= 0.f ? he.x : -he.x),
|
||||
m_origin.y + (direction.y >= 0.f ? he.y : -he.y),
|
||||
m_origin.z + (direction.z >= 0.f ? he.z : -he.z),
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const VectorType& get_origin() const override { return m_origin; }
|
||||
|
||||
void set_origin(const VectorType& new_origin) override { m_origin = new_origin; }
|
||||
|
||||
[[nodiscard]]
|
||||
const physx::PxBoxGeometry& get_geometry() const { return m_geometry; }
|
||||
|
||||
/// Update half-extents at runtime.
|
||||
void set_half_extents(const VectorType& half_extents)
|
||||
{
|
||||
m_geometry = physx::PxBoxGeometry(physx::PxVec3(half_extents.x, half_extents.y, half_extents.z));
|
||||
}
|
||||
|
||||
private:
|
||||
physx::PxBoxGeometry m_geometry;
|
||||
VectorType m_origin;
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
137
include/omath/collision/physx_rigid_body.hpp
Normal file
137
include/omath/collision/physx_rigid_body.hpp
Normal file
@@ -0,0 +1,137 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include "collider_interface.hpp"
|
||||
#include "physx_world.hpp"
|
||||
#include <PxPhysicsAPI.h>
|
||||
#include <extensions/PxRigidBodyExt.h>
|
||||
#include <cmath>
|
||||
|
||||
namespace omath::collision
|
||||
{
|
||||
/// Dynamic rigid body backed by a PhysX PxRigidDynamic actor.
|
||||
/// Implements ColliderInterface so it can participate in both omath GJK
|
||||
/// and PhysX simulation-based collision resolution.
|
||||
///
|
||||
/// Ownership: the actor is added to the world's scene on construction
|
||||
/// and removed + released on destruction.
|
||||
class PhysXRigidBody final : public ColliderInterface<Vector3<float>>
|
||||
{
|
||||
public:
|
||||
/// @param world PhysXWorld that owns the scene.
|
||||
/// @param geometry Shape geometry (PxBoxGeometry, PxSphereGeometry, …).
|
||||
/// @param origin Initial world-space position.
|
||||
/// @param density Mass density used to compute mass and inertia.
|
||||
PhysXRigidBody(PhysXWorld& world, const physx::PxGeometry& geometry,
|
||||
const VectorType& origin = {}, float density = 1.f)
|
||||
: m_world(world)
|
||||
, m_geometry(geometry)
|
||||
{
|
||||
const physx::PxTransform pose(physx::PxVec3(origin.x, origin.y, origin.z));
|
||||
m_actor = world.get_physics().createRigidDynamic(pose);
|
||||
|
||||
physx::PxShape* shape = world.get_physics().createShape(
|
||||
geometry, world.get_default_material(), true);
|
||||
m_actor->attachShape(*shape);
|
||||
shape->release();
|
||||
|
||||
physx::PxRigidBodyExt::updateMassAndInertia(*m_actor, density);
|
||||
world.get_scene().addActor(*m_actor);
|
||||
}
|
||||
|
||||
~PhysXRigidBody() override
|
||||
{
|
||||
m_world.get_scene().removeActor(*m_actor);
|
||||
m_actor->release();
|
||||
}
|
||||
|
||||
PhysXRigidBody(const PhysXRigidBody&) = delete;
|
||||
PhysXRigidBody& operator=(const PhysXRigidBody&) = delete;
|
||||
|
||||
// ── ColliderInterface ────────────────────────────────────────────────
|
||||
|
||||
/// Support function — delegates to the stored geometry type so the body
|
||||
/// can be used with omath GJK alongside the non-simulated colliders.
|
||||
[[nodiscard]]
|
||||
VectorType find_abs_furthest_vertex_position(const VectorType& direction) const override
|
||||
{
|
||||
const VectorType o = get_origin();
|
||||
switch (m_geometry.getType())
|
||||
{
|
||||
case physx::PxGeometryType::eBOX:
|
||||
{
|
||||
const auto& he = m_geometry.box().halfExtents;
|
||||
return {
|
||||
o.x + (direction.x >= 0.f ? he.x : -he.x),
|
||||
o.y + (direction.y >= 0.f ? he.y : -he.y),
|
||||
o.z + (direction.z >= 0.f ? he.z : -he.z),
|
||||
};
|
||||
}
|
||||
case physx::PxGeometryType::eSPHERE:
|
||||
{
|
||||
const float r = m_geometry.sphere().radius;
|
||||
const float len = std::sqrt(direction.x * direction.x +
|
||||
direction.y * direction.y +
|
||||
direction.z * direction.z);
|
||||
if (len == 0.f)
|
||||
return o;
|
||||
const float inv = r / len;
|
||||
return { o.x + direction.x * inv,
|
||||
o.y + direction.y * inv,
|
||||
o.z + direction.z * inv };
|
||||
}
|
||||
default:
|
||||
return o; // unsupported geometry — return centre
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const VectorType& get_origin() const override
|
||||
{
|
||||
const auto& p = m_actor->getGlobalPose().p;
|
||||
m_cached_origin = { p.x, p.y, p.z };
|
||||
return m_cached_origin;
|
||||
}
|
||||
|
||||
void set_origin(const VectorType& new_origin) override
|
||||
{
|
||||
physx::PxTransform pose = m_actor->getGlobalPose();
|
||||
pose.p = physx::PxVec3(new_origin.x, new_origin.y, new_origin.z);
|
||||
m_actor->setGlobalPose(pose);
|
||||
}
|
||||
|
||||
// ── PhysX-specific API ───────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] physx::PxRigidDynamic& get_actor() { return *m_actor; }
|
||||
[[nodiscard]] const physx::PxRigidDynamic& get_actor() const { return *m_actor; }
|
||||
|
||||
void set_linear_velocity(const VectorType& v)
|
||||
{
|
||||
m_actor->setLinearVelocity(physx::PxVec3(v.x, v.y, v.z));
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
VectorType get_linear_velocity() const
|
||||
{
|
||||
const auto& v = m_actor->getLinearVelocity();
|
||||
return { v.x, v.y, v.z };
|
||||
}
|
||||
|
||||
void set_kinematic(bool enabled)
|
||||
{
|
||||
m_actor->setRigidBodyFlag(physx::PxRigidBodyFlag::eKINEMATIC, enabled);
|
||||
}
|
||||
|
||||
private:
|
||||
PhysXWorld& m_world;
|
||||
physx::PxGeometryHolder m_geometry;
|
||||
physx::PxRigidDynamic* m_actor{nullptr};
|
||||
mutable VectorType m_cached_origin{};
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
64
include/omath/collision/physx_sphere_collider.hpp
Normal file
64
include/omath/collision/physx_sphere_collider.hpp
Normal file
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include "collider_interface.hpp"
|
||||
#include <PxPhysicsAPI.h>
|
||||
#include <cmath>
|
||||
|
||||
namespace omath::collision
|
||||
{
|
||||
/// Sphere collider backed by PhysX PxSphereGeometry.
|
||||
class PhysXSphereCollider final : public ColliderInterface<Vector3<float>>
|
||||
{
|
||||
public:
|
||||
/// @param radius Sphere radius (must be > 0).
|
||||
/// @param origin World-space centre of the sphere.
|
||||
explicit PhysXSphereCollider(float radius, const VectorType& origin = {})
|
||||
: m_geometry(radius)
|
||||
, m_origin(origin)
|
||||
{
|
||||
}
|
||||
|
||||
/// Support function: returns the world-space point on the sphere furthest in @p direction.
|
||||
/// For a sphere that is simply origin + normalize(direction) * radius.
|
||||
[[nodiscard]]
|
||||
VectorType find_abs_furthest_vertex_position(const VectorType& direction) const override
|
||||
{
|
||||
const float len = std::sqrt(direction.x * direction.x +
|
||||
direction.y * direction.y +
|
||||
direction.z * direction.z);
|
||||
if (len == 0.f)
|
||||
return m_origin;
|
||||
|
||||
const float inv = m_geometry.radius / len;
|
||||
return {
|
||||
m_origin.x + direction.x * inv,
|
||||
m_origin.y + direction.y * inv,
|
||||
m_origin.z + direction.z * inv,
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const VectorType& get_origin() const override { return m_origin; }
|
||||
|
||||
void set_origin(const VectorType& new_origin) override { m_origin = new_origin; }
|
||||
|
||||
[[nodiscard]]
|
||||
const physx::PxSphereGeometry& get_geometry() const { return m_geometry; }
|
||||
|
||||
[[nodiscard]]
|
||||
float get_radius() const { return m_geometry.radius; }
|
||||
|
||||
void set_radius(float radius) { m_geometry = physx::PxSphereGeometry(radius); }
|
||||
|
||||
private:
|
||||
physx::PxSphereGeometry m_geometry;
|
||||
VectorType m_origin;
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
82
include/omath/collision/physx_world.hpp
Normal file
82
include/omath/collision/physx_world.hpp
Normal file
@@ -0,0 +1,82 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include <PxPhysicsAPI.h>
|
||||
|
||||
namespace omath::collision
|
||||
{
|
||||
/// RAII owner of a PhysX Foundation + Physics + Scene.
|
||||
/// One world per simulation context; not copyable or movable.
|
||||
class PhysXWorld final
|
||||
{
|
||||
public:
|
||||
explicit PhysXWorld(physx::PxVec3 gravity = {0.f, -9.81f, 0.f},
|
||||
physx::PxU32 cpu_threads = 2)
|
||||
{
|
||||
m_foundation = PxCreateFoundation(PX_PHYSICS_VERSION, m_allocator, m_error_callback);
|
||||
|
||||
m_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *m_foundation,
|
||||
physx::PxTolerancesScale{});
|
||||
|
||||
physx::PxSceneDesc desc(m_physics->getTolerancesScale());
|
||||
desc.gravity = gravity;
|
||||
desc.cpuDispatcher = physx::PxDefaultCpuDispatcherCreate(cpu_threads);
|
||||
m_dispatcher = static_cast<physx::PxDefaultCpuDispatcher*>(desc.cpuDispatcher);
|
||||
desc.filterShader = physx::PxDefaultSimulationFilterShader;
|
||||
|
||||
m_scene = m_physics->createScene(desc);
|
||||
|
||||
// Default material: static friction 0.5, dynamic friction 0.5, restitution 0.
|
||||
m_default_material = m_physics->createMaterial(0.5f, 0.5f, 0.f);
|
||||
}
|
||||
|
||||
~PhysXWorld()
|
||||
{
|
||||
m_scene->release();
|
||||
m_dispatcher->release();
|
||||
m_default_material->release();
|
||||
m_physics->release();
|
||||
m_foundation->release();
|
||||
}
|
||||
|
||||
PhysXWorld(const PhysXWorld&) = delete;
|
||||
PhysXWorld& operator=(const PhysXWorld&) = delete;
|
||||
|
||||
/// Advance the simulation by @p dt seconds and block until results are ready.
|
||||
void step(float dt)
|
||||
{
|
||||
m_scene->simulate(dt);
|
||||
m_scene->fetchResults(true);
|
||||
}
|
||||
|
||||
[[nodiscard]] physx::PxPhysics& get_physics() { return *m_physics; }
|
||||
[[nodiscard]] physx::PxScene& get_scene() { return *m_scene; }
|
||||
[[nodiscard]] physx::PxMaterial& get_default_material() { return *m_default_material; }
|
||||
|
||||
/// Add an infinite static ground plane at y = @p y_level facing +Y.
|
||||
physx::PxRigidStatic* add_ground_plane(float y_level = 0.f)
|
||||
{
|
||||
physx::PxRigidStatic* plane = PxCreatePlane(
|
||||
*m_physics,
|
||||
physx::PxPlane(0.f, 1.f, 0.f, -y_level),
|
||||
*m_default_material);
|
||||
m_scene->addActor(*plane);
|
||||
return plane;
|
||||
}
|
||||
|
||||
private:
|
||||
physx::PxDefaultAllocator m_allocator{};
|
||||
physx::PxDefaultErrorCallback m_error_callback{};
|
||||
physx::PxFoundation* m_foundation{nullptr};
|
||||
physx::PxPhysics* m_physics{nullptr};
|
||||
physx::PxDefaultCpuDispatcher* m_dispatcher{nullptr};
|
||||
physx::PxScene* m_scene{nullptr};
|
||||
physx::PxMaterial* m_default_material{nullptr};
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
@@ -6,7 +6,9 @@
|
||||
|
||||
#include "omath/linear_algebra/vector3.hpp"
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace omath::pathfinding
|
||||
@@ -28,10 +30,20 @@ namespace omath::pathfinding
|
||||
[[nodiscard]]
|
||||
bool empty() const;
|
||||
|
||||
[[nodiscard]] std::vector<uint8_t> serialize() const noexcept;
|
||||
// Events -- per-vertex optional tag (e.g. "jump", "teleport")
|
||||
void set_event(const Vector3<float>& vertex, const std::string_view& event_id);
|
||||
void clear_event(const Vector3<float>& vertex);
|
||||
|
||||
void deserialize(const std::vector<uint8_t>& raw) noexcept;
|
||||
[[nodiscard]]
|
||||
std::optional<std::string> get_event(const Vector3<float>& vertex) const noexcept;
|
||||
|
||||
[[nodiscard]] std::string serialize() const noexcept;
|
||||
|
||||
void deserialize(const std::string& raw);
|
||||
|
||||
std::unordered_map<Vector3<float>, std::vector<Vector3<float>>> m_vertex_map;
|
||||
|
||||
private:
|
||||
std::unordered_map<Vector3<float>, std::string> m_vertex_events;
|
||||
};
|
||||
} // namespace omath::pathfinding
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <omath/utility/section_scan_result.hpp>
|
||||
#include <sol/sol.hpp>
|
||||
#endif
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
@@ -101,4 +100,5 @@ namespace omath::lua
|
||||
return *result;
|
||||
};
|
||||
}
|
||||
} // namespace omath::lua
|
||||
} // namespace omath::lua
|
||||
#endif
|
||||
@@ -3,9 +3,9 @@
|
||||
//
|
||||
#include "omath/pathfinding/navigation_mesh.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace omath::pathfinding
|
||||
{
|
||||
std::expected<Vector3<float>, std::string>
|
||||
@@ -30,77 +30,72 @@ namespace omath::pathfinding
|
||||
return m_vertex_map.empty();
|
||||
}
|
||||
|
||||
std::vector<uint8_t> NavigationMesh::serialize() const noexcept
|
||||
void NavigationMesh::set_event(const Vector3<float>& vertex, const std::string_view& event_id)
|
||||
{
|
||||
std::vector<std::uint8_t> raw;
|
||||
if (!m_vertex_map.contains(vertex))
|
||||
throw std::invalid_argument(std::format("Vertex '{}' not found", vertex));
|
||||
|
||||
// Pre-calculate total size for better performance
|
||||
std::size_t total_size = 0;
|
||||
for (const auto& [vertex, neighbors] : m_vertex_map)
|
||||
{
|
||||
total_size += sizeof(vertex) + sizeof(std::uint16_t) + sizeof(Vector3<float>) * neighbors.size();
|
||||
}
|
||||
raw.reserve(total_size);
|
||||
|
||||
auto dump_to_vector = [&raw]<typename T>(const T& t)
|
||||
{
|
||||
const auto* byte_ptr = reinterpret_cast<const std::uint8_t*>(&t);
|
||||
raw.insert(raw.end(), byte_ptr, byte_ptr + sizeof(T));
|
||||
};
|
||||
|
||||
for (const auto& [vertex, neighbors] : m_vertex_map)
|
||||
{
|
||||
// Clamp neighbors count to fit in uint16_t (prevents silent data corruption)
|
||||
// NOTE: If neighbors.size() > 65535, only the first 65535 neighbors will be serialized.
|
||||
// This is a limitation of the current serialization format using uint16_t for count.
|
||||
const auto clamped_count =
|
||||
std::min<std::size_t>(neighbors.size(), std::numeric_limits<std::uint16_t>::max());
|
||||
const auto neighbors_count = static_cast<std::uint16_t>(clamped_count);
|
||||
|
||||
dump_to_vector(vertex);
|
||||
dump_to_vector(neighbors_count);
|
||||
|
||||
// Only serialize up to the clamped count
|
||||
for (std::size_t i = 0; i < clamped_count; ++i)
|
||||
dump_to_vector(neighbors[i]);
|
||||
}
|
||||
return raw;
|
||||
m_vertex_events[vertex] = event_id;
|
||||
}
|
||||
|
||||
void NavigationMesh::deserialize(const std::vector<uint8_t>& raw) noexcept
|
||||
void NavigationMesh::clear_event(const Vector3<float>& vertex)
|
||||
{
|
||||
auto load_from_vector = [](const std::vector<uint8_t>& vec, std::size_t& offset, auto& value)
|
||||
m_vertex_events.erase(vertex);
|
||||
}
|
||||
|
||||
std::optional<std::string> NavigationMesh::get_event(const Vector3<float>& vertex) const noexcept
|
||||
{
|
||||
const auto it = m_vertex_events.find(vertex);
|
||||
if (it == m_vertex_events.end())
|
||||
return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
|
||||
// Serialization format per vertex line:
|
||||
// x y z neighbor_count event_id
|
||||
// where event_id is "-" when no event is set.
|
||||
// Neighbor lines follow: nx ny nz
|
||||
|
||||
std::string NavigationMesh::serialize() const noexcept
|
||||
{
|
||||
std::ostringstream oss;
|
||||
for (const auto& [vertex, neighbors] : m_vertex_map)
|
||||
{
|
||||
if (offset + sizeof(value) > vec.size())
|
||||
throw std::runtime_error("Deserialize: Invalid input data size.");
|
||||
const auto event_it = m_vertex_events.find(vertex);
|
||||
const std::string& event = (event_it != m_vertex_events.end()) ? event_it->second : "-";
|
||||
|
||||
std::copy_n(vec.data() + offset, sizeof(value), reinterpret_cast<uint8_t*>(&value));
|
||||
offset += sizeof(value);
|
||||
};
|
||||
oss << vertex.x << ' ' << vertex.y << ' ' << vertex.z << ' ' << neighbors.size() << ' ' << event << '\n';
|
||||
|
||||
for (const auto& n : neighbors)
|
||||
oss << n.x << ' ' << n.y << ' ' << n.z << '\n';
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
void NavigationMesh::deserialize(const std::string& raw)
|
||||
{
|
||||
m_vertex_map.clear();
|
||||
m_vertex_events.clear();
|
||||
std::istringstream iss(raw);
|
||||
|
||||
std::size_t offset = 0;
|
||||
|
||||
while (offset < raw.size())
|
||||
Vector3<float> vertex;
|
||||
std::size_t neighbors_count;
|
||||
std::string event;
|
||||
while (iss >> vertex.x >> vertex.y >> vertex.z >> neighbors_count >> event)
|
||||
{
|
||||
Vector3<float> vertex;
|
||||
load_from_vector(raw, offset, vertex);
|
||||
|
||||
std::uint16_t neighbors_count;
|
||||
load_from_vector(raw, offset, neighbors_count);
|
||||
|
||||
std::vector<Vector3<float>> neighbors;
|
||||
neighbors.reserve(neighbors_count);
|
||||
|
||||
for (std::size_t i = 0; i < neighbors_count; ++i)
|
||||
{
|
||||
Vector3<float> neighbor;
|
||||
load_from_vector(raw, offset, neighbor);
|
||||
neighbors.push_back(neighbor);
|
||||
Vector3<float> n;
|
||||
if (!(iss >> n.x >> n.y >> n.z))
|
||||
throw std::runtime_error("Deserialize: Unexpected end of data.");
|
||||
neighbors.push_back(n);
|
||||
}
|
||||
|
||||
m_vertex_map.emplace(vertex, std::move(neighbors));
|
||||
|
||||
if (event != "-")
|
||||
m_vertex_events.emplace(vertex, std::move(event));
|
||||
}
|
||||
}
|
||||
} // namespace omath::pathfinding
|
||||
|
||||
@@ -8,6 +8,29 @@
|
||||
using namespace omath;
|
||||
using namespace omath::pathfinding;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static NavigationMesh make_linear_chain(int length)
|
||||
{
|
||||
// 0 -> 1 -> 2 -> ... -> length-1 (directed)
|
||||
NavigationMesh nav;
|
||||
for (int i = 0; i < length; ++i)
|
||||
{
|
||||
const Vector3<float> v{static_cast<float>(i), 0.f, 0.f};
|
||||
if (i + 1 < length)
|
||||
nav.m_vertex_map[v] = {Vector3<float>{static_cast<float>(i + 1), 0.f, 0.f}};
|
||||
else
|
||||
nav.m_vertex_map[v] = {};
|
||||
}
|
||||
return nav;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Basic reachability
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AStarExtra, TrivialNeighbor)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
@@ -78,7 +101,7 @@ TEST(AStarExtra, LongerPathAvoidsBlock)
|
||||
constexpr Vector3<float> goal = idx(2, 1);
|
||||
const auto path = Astar::find_path(start, goal, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.front(), goal); // Astar convention: single-element or endpoint present
|
||||
EXPECT_EQ(path.front(), goal);
|
||||
}
|
||||
|
||||
TEST(AstarTests, TrivialDirectNeighborPath)
|
||||
@@ -91,9 +114,6 @@ TEST(AstarTests, TrivialDirectNeighborPath)
|
||||
nav.m_vertex_map.emplace(v2, std::vector<Vector3<float>>{v1});
|
||||
|
||||
const auto path = Astar::find_path(v1, v2, nav);
|
||||
// Current A* implementation returns the end vertex as the reconstructed
|
||||
// path (single-element) in the simple neighbor scenario. Assert that the
|
||||
// endpoint is present and reachable.
|
||||
ASSERT_EQ(path.size(), 1u);
|
||||
EXPECT_EQ(path.front(), v2);
|
||||
}
|
||||
@@ -133,4 +153,155 @@ TEST(unit_test_a_star, finding_right_path)
|
||||
mesh.m_vertex_map[{0.f, 2.f, 0.f}] = {{0.f, 3.f, 0.f}};
|
||||
mesh.m_vertex_map[{0.f, 3.f, 0.f}] = {};
|
||||
std::ignore = omath::pathfinding::Astar::find_path({}, {0.f, 3.f, 0.f}, mesh);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Directed edges
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, DirectedEdge_ForwardPathExists)
|
||||
{
|
||||
// A -> B only; path from A to B should succeed
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[a] = {b};
|
||||
nav.m_vertex_map[b] = {}; // no edge back
|
||||
|
||||
const auto path = Astar::find_path(a, b, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), b);
|
||||
}
|
||||
|
||||
TEST(AstarTests, DirectedEdge_ReversePathMissing)
|
||||
{
|
||||
// A -> B only; path from B to A should fail
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[a] = {b};
|
||||
nav.m_vertex_map[b] = {};
|
||||
|
||||
const auto path = Astar::find_path(b, a, nav);
|
||||
EXPECT_TRUE(path.empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vertex snapping
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, OffMeshStart_SnapsToNearestVertex)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> v1{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> v2{10.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[v1] = {v2};
|
||||
nav.m_vertex_map[v2] = {v1};
|
||||
|
||||
// Start is slightly off v1 but closer to it than to v2
|
||||
constexpr Vector3<float> off_start{0.1f, 0.f, 0.f};
|
||||
const auto path = Astar::find_path(off_start, v2, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), v2);
|
||||
}
|
||||
|
||||
TEST(AstarTests, OffMeshEnd_SnapsToNearestVertex)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> v1{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> v2{10.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[v1] = {v2};
|
||||
nav.m_vertex_map[v2] = {v1};
|
||||
|
||||
// Goal is slightly off v2 but closer to it than to v1
|
||||
constexpr Vector3<float> off_goal{9.9f, 0.f, 0.f};
|
||||
const auto path = Astar::find_path(v1, off_goal, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), v2);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cycle handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, CyclicGraph_FindsPathWithoutLooping)
|
||||
{
|
||||
// Triangle: A <-> B <-> C <-> A
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> c{0.5f, 1.f, 0.f};
|
||||
nav.m_vertex_map[a] = {b, c};
|
||||
nav.m_vertex_map[b] = {a, c};
|
||||
nav.m_vertex_map[c] = {a, b};
|
||||
|
||||
const auto path = Astar::find_path(a, c, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), c);
|
||||
}
|
||||
|
||||
TEST(AstarTests, SelfLoopVertex_DoesNotBreakSearch)
|
||||
{
|
||||
// Vertex with itself as a neighbor
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[a] = {a, b}; // self-loop on a
|
||||
nav.m_vertex_map[b] = {a};
|
||||
|
||||
const auto path = Astar::find_path(a, b, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), b);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Longer chains
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, LinearChain_ReachesEnd)
|
||||
{
|
||||
constexpr int kLength = 10;
|
||||
const NavigationMesh nav = make_linear_chain(kLength);
|
||||
|
||||
const Vector3<float> start{0.f, 0.f, 0.f};
|
||||
const Vector3<float> goal{static_cast<float>(kLength - 1), 0.f, 0.f};
|
||||
|
||||
const auto path = Astar::find_path(start, goal, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), goal);
|
||||
}
|
||||
|
||||
TEST(AstarTests, LinearChain_MidpointReachable)
|
||||
{
|
||||
constexpr int kLength = 6;
|
||||
const NavigationMesh nav = make_linear_chain(kLength);
|
||||
|
||||
const Vector3<float> start{0.f, 0.f, 0.f};
|
||||
const Vector3<float> mid{3.f, 0.f, 0.f};
|
||||
|
||||
const auto path = Astar::find_path(start, mid, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), mid);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Serialize -> pathfind integration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, PathfindAfterSerializeDeserialize)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> c{2.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[a] = {b};
|
||||
nav.m_vertex_map[b] = {a, c};
|
||||
nav.m_vertex_map[c] = {b};
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
const auto path = Astar::find_path(a, c, nav2);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), c);
|
||||
}
|
||||
|
||||
@@ -7,19 +7,18 @@ using namespace omath::pathfinding;
|
||||
TEST(NavigationMeshTests, SerializeDeserializeRoundTrip)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
Vector3<float> a{0.f,0.f,0.f};
|
||||
Vector3<float> b{1.f,0.f,0.f};
|
||||
Vector3<float> c{0.f,1.f,0.f};
|
||||
Vector3<float> a{0.f, 0.f, 0.f};
|
||||
Vector3<float> b{1.f, 0.f, 0.f};
|
||||
Vector3<float> c{0.f, 1.f, 0.f};
|
||||
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{b,c});
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{b, c});
|
||||
nav.m_vertex_map.emplace(b, std::vector<Vector3<float>>{a});
|
||||
nav.m_vertex_map.emplace(c, std::vector<Vector3<float>>{a});
|
||||
|
||||
auto data = nav.serialize();
|
||||
std::string data = nav.serialize();
|
||||
NavigationMesh nav2;
|
||||
EXPECT_NO_THROW(nav2.deserialize(data));
|
||||
|
||||
// verify neighbors preserved
|
||||
EXPECT_EQ(nav2.m_vertex_map.size(), nav.m_vertex_map.size());
|
||||
EXPECT_EQ(nav2.get_neighbors(a).size(), 2u);
|
||||
}
|
||||
@@ -27,7 +26,223 @@ TEST(NavigationMeshTests, SerializeDeserializeRoundTrip)
|
||||
TEST(NavigationMeshTests, GetClosestVertexWhenEmpty)
|
||||
{
|
||||
const NavigationMesh nav;
|
||||
constexpr Vector3<float> p{5.f,5.f,5.f};
|
||||
constexpr Vector3<float> p{5.f, 5.f, 5.f};
|
||||
const auto res = nav.get_closest_vertex(p);
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, SerializeEmptyMesh)
|
||||
{
|
||||
const NavigationMesh nav;
|
||||
const std::string data = nav.serialize();
|
||||
EXPECT_TRUE(data.empty());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, DeserializeEmptyString)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
EXPECT_NO_THROW(nav.deserialize(""));
|
||||
EXPECT_TRUE(nav.empty());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, SerializeProducesHumanReadableText)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
nav.m_vertex_map.emplace(Vector3<float>{1.f, 2.f, 3.f}, std::vector<Vector3<float>>{{4.f, 5.f, 6.f}});
|
||||
|
||||
const std::string data = nav.serialize();
|
||||
|
||||
// Must contain the vertex and neighbor coords as plain text
|
||||
EXPECT_NE(data.find("1"), std::string::npos);
|
||||
EXPECT_NE(data.find("2"), std::string::npos);
|
||||
EXPECT_NE(data.find("3"), std::string::npos);
|
||||
EXPECT_NE(data.find("4"), std::string::npos);
|
||||
EXPECT_NE(data.find("5"), std::string::npos);
|
||||
EXPECT_NE(data.find("6"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, DeserializeRestoresNeighborValues)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 2.f, 3.f};
|
||||
const Vector3<float> n1{4.f, 5.f, 6.f};
|
||||
const Vector3<float> n2{7.f, 8.f, 9.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{n1, n2});
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
ASSERT_EQ(nav2.m_vertex_map.count(v), 1u);
|
||||
const auto& neighbors = nav2.get_neighbors(v);
|
||||
ASSERT_EQ(neighbors.size(), 2u);
|
||||
EXPECT_EQ(neighbors[0], n1);
|
||||
EXPECT_EQ(neighbors[1], n2);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, DeserializeOverwritesPreviousData)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
|
||||
// Load a different mesh into the same object
|
||||
NavigationMesh other;
|
||||
const Vector3<float> a{10.f, 20.f, 30.f};
|
||||
other.m_vertex_map.emplace(a, std::vector<Vector3<float>>{});
|
||||
|
||||
nav.deserialize(other.serialize());
|
||||
|
||||
EXPECT_EQ(nav.m_vertex_map.size(), 1u);
|
||||
EXPECT_EQ(nav.m_vertex_map.count(v), 0u);
|
||||
EXPECT_EQ(nav.m_vertex_map.count(a), 1u);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, RoundTripNegativeAndFractionalCoords)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{-1.5f, 0.25f, -3.75f};
|
||||
const Vector3<float> n{100.f, -200.f, 0.001f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{n});
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
ASSERT_EQ(nav2.m_vertex_map.count(v), 1u);
|
||||
const auto& neighbors = nav2.get_neighbors(v);
|
||||
ASSERT_EQ(neighbors.size(), 1u);
|
||||
EXPECT_NEAR(neighbors[0].x, n.x, 1e-3f);
|
||||
EXPECT_NEAR(neighbors[0].y, n.y, 1e-3f);
|
||||
EXPECT_NEAR(neighbors[0].z, n.z, 1e-3f);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, GetClosestVertexReturnsNearest)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> a{0.f, 0.f, 0.f};
|
||||
const Vector3<float> b{10.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{});
|
||||
nav.m_vertex_map.emplace(b, std::vector<Vector3<float>>{});
|
||||
|
||||
const auto res = nav.get_closest_vertex({1.f, 0.f, 0.f});
|
||||
ASSERT_TRUE(res.has_value());
|
||||
EXPECT_EQ(res.value(), a);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, VertexWithNoNeighborsRoundTrip)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{5.f, 5.f, 5.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
ASSERT_EQ(nav2.m_vertex_map.count(v), 1u);
|
||||
EXPECT_TRUE(nav2.get_neighbors(v).empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vertex events
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(NavigationMeshTests, SetEventOnNonExistentVertexThrows)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{99.f, 99.f, 99.f};
|
||||
EXPECT_THROW(nav.set_event(v, "jump"), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, EventNotSetByDefault)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{0.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
|
||||
EXPECT_FALSE(nav.get_event(v).has_value());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, SetAndGetEvent)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
nav.set_event(v, "jump");
|
||||
|
||||
const auto event = nav.get_event(v);
|
||||
ASSERT_TRUE(event.has_value());
|
||||
EXPECT_EQ(event.value(), "jump");
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, OverwriteEvent)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
nav.set_event(v, "jump");
|
||||
nav.set_event(v, "teleport");
|
||||
|
||||
EXPECT_EQ(nav.get_event(v).value(), "teleport");
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, ClearEvent)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
nav.set_event(v, "jump");
|
||||
nav.clear_event(v);
|
||||
|
||||
EXPECT_FALSE(nav.get_event(v).has_value());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, EventRoundTripSerialization)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> a{0.f, 0.f, 0.f};
|
||||
const Vector3<float> b{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{b});
|
||||
nav.m_vertex_map.emplace(b, std::vector<Vector3<float>>{});
|
||||
nav.set_event(b, "jump");
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
ASSERT_FALSE(nav2.get_event(a).has_value());
|
||||
ASSERT_TRUE(nav2.get_event(b).has_value());
|
||||
EXPECT_EQ(nav2.get_event(b).value(), "jump");
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, MultipleEventsRoundTrip)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> a{0.f, 0.f, 0.f};
|
||||
const Vector3<float> b{1.f, 0.f, 0.f};
|
||||
const Vector3<float> c{2.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{});
|
||||
nav.m_vertex_map.emplace(b, std::vector<Vector3<float>>{});
|
||||
nav.m_vertex_map.emplace(c, std::vector<Vector3<float>>{});
|
||||
nav.set_event(a, "spawn");
|
||||
nav.set_event(c, "teleport");
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
EXPECT_EQ(nav2.get_event(a).value(), "spawn");
|
||||
EXPECT_FALSE(nav2.get_event(b).has_value());
|
||||
EXPECT_EQ(nav2.get_event(c).value(), "teleport");
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, DeserializeClearsOldEvents)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{0.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
nav.set_event(v, "jump");
|
||||
|
||||
// Deserialize a mesh that has no events
|
||||
NavigationMesh empty_events;
|
||||
empty_events.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
|
||||
nav.deserialize(empty_events.serialize());
|
||||
EXPECT_FALSE(nav.get_event(v).has_value());
|
||||
}
|
||||
|
||||
341
tests/general/unit_test_physx_colliders.cpp
Normal file
341
tests/general/unit_test_physx_colliders.cpp
Normal file
@@ -0,0 +1,341 @@
|
||||
//
|
||||
// Created by orange-cpp
|
||||
//
|
||||
#ifdef OMATH_ENABLE_PHYSX
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/collision/gjk_algorithm.hpp>
|
||||
#include <omath/collision/physx_box_collider.hpp>
|
||||
#include <omath/collision/physx_rigid_body.hpp>
|
||||
#include <omath/collision/physx_sphere_collider.hpp>
|
||||
#include <omath/collision/physx_world.hpp>
|
||||
|
||||
using namespace omath::collision;
|
||||
using omath::Vector3;
|
||||
|
||||
// ─── PhysXBoxCollider ────────────────────────────────────────────────────────
|
||||
|
||||
TEST(PhysXBoxCollider, DefaultOriginIsZero)
|
||||
{
|
||||
PhysXBoxCollider box({1.f, 1.f, 1.f});
|
||||
EXPECT_EQ(box.get_origin(), Vector3<float>(0.f, 0.f, 0.f));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, SetAndGetOrigin)
|
||||
{
|
||||
PhysXBoxCollider box({1.f, 1.f, 1.f}, {3.f, 4.f, 5.f});
|
||||
EXPECT_EQ(box.get_origin(), Vector3<float>(3.f, 4.f, 5.f));
|
||||
|
||||
box.set_origin({-1.f, 0.f, 2.f});
|
||||
EXPECT_EQ(box.get_origin(), Vector3<float>(-1.f, 0.f, 2.f));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, FurthestPointPositiveDirection)
|
||||
{
|
||||
// Box centred at origin with half-extents (2, 3, 4).
|
||||
// Direction (+x, +y, +z) → furthest corner is (+2, +3, +4).
|
||||
PhysXBoxCollider box({2.f, 3.f, 4.f});
|
||||
const auto p = box.find_abs_furthest_vertex_position({1.f, 1.f, 1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 2.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 3.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 4.f);
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, FurthestPointNegativeDirection)
|
||||
{
|
||||
// Direction (-x, -y, -z) → furthest corner is (-2, -3, -4).
|
||||
PhysXBoxCollider box({2.f, 3.f, 4.f});
|
||||
const auto p = box.find_abs_furthest_vertex_position({-1.f, -1.f, -1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, -2.f);
|
||||
EXPECT_FLOAT_EQ(p.y, -3.f);
|
||||
EXPECT_FLOAT_EQ(p.z, -4.f);
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, FurthestPointMixedDirection)
|
||||
{
|
||||
// Direction (+x, -y, +z) → furthest corner is (+2, -3, +4).
|
||||
PhysXBoxCollider box({2.f, 3.f, 4.f});
|
||||
const auto p = box.find_abs_furthest_vertex_position({1.f, -1.f, 1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 2.f);
|
||||
EXPECT_FLOAT_EQ(p.y, -3.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 4.f);
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, FurthestPointWithNonZeroOrigin)
|
||||
{
|
||||
// Box at (10, 0, 0), half-extents (1, 1, 1). Direction +x → (11, 1, 1).
|
||||
PhysXBoxCollider box({1.f, 1.f, 1.f}, {10.f, 0.f, 0.f});
|
||||
const auto p = box.find_abs_furthest_vertex_position({1.f, 1.f, 1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 11.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 1.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 1.f);
|
||||
}
|
||||
|
||||
TEST(PhysXBoxCollider, SetHalfExtentsUpdatesGeometry)
|
||||
{
|
||||
PhysXBoxCollider box({1.f, 1.f, 1.f});
|
||||
box.set_half_extents({5.f, 6.f, 7.f});
|
||||
|
||||
const auto& he = box.get_geometry().halfExtents;
|
||||
EXPECT_FLOAT_EQ(he.x, 5.f);
|
||||
EXPECT_FLOAT_EQ(he.y, 6.f);
|
||||
EXPECT_FLOAT_EQ(he.z, 7.f);
|
||||
|
||||
// Furthest vertex must reflect the new extents.
|
||||
const auto p = box.find_abs_furthest_vertex_position({1.f, 1.f, 1.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 5.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 6.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 7.f);
|
||||
}
|
||||
|
||||
// ─── PhysXSphereCollider ─────────────────────────────────────────────────────
|
||||
|
||||
TEST(PhysXSphereCollider, DefaultOriginIsZero)
|
||||
{
|
||||
PhysXSphereCollider sphere(1.f);
|
||||
EXPECT_EQ(sphere.get_origin(), Vector3<float>(0.f, 0.f, 0.f));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, SetAndGetOrigin)
|
||||
{
|
||||
PhysXSphereCollider sphere(1.f, {1.f, 2.f, 3.f});
|
||||
EXPECT_EQ(sphere.get_origin(), Vector3<float>(1.f, 2.f, 3.f));
|
||||
|
||||
sphere.set_origin({-5.f, 0.f, 0.f});
|
||||
EXPECT_EQ(sphere.get_origin(), Vector3<float>(-5.f, 0.f, 0.f));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, FurthestPointAlongPureXAxis)
|
||||
{
|
||||
// Direction (1,0,0), radius 3 → furthest point is (3, 0, 0).
|
||||
PhysXSphereCollider sphere(3.f);
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({1.f, 0.f, 0.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 3.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 0.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 0.f);
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, FurthestPointAlongDiagonal)
|
||||
{
|
||||
// Direction (1,1,0), radius 1 → furthest point at distance 1 from origin.
|
||||
PhysXSphereCollider sphere(1.f);
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({1.f, 1.f, 0.f});
|
||||
const float dist = std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
|
||||
EXPECT_NEAR(dist, 1.f, 1e-5f);
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, FurthestPointWithNonZeroOrigin)
|
||||
{
|
||||
// Sphere at (5, 0, 0), radius 2. Direction +x → (7, 0, 0).
|
||||
PhysXSphereCollider sphere(2.f, {5.f, 0.f, 0.f});
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({1.f, 0.f, 0.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 7.f);
|
||||
EXPECT_FLOAT_EQ(p.y, 0.f);
|
||||
EXPECT_FLOAT_EQ(p.z, 0.f);
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, ZeroDirectionReturnsOrigin)
|
||||
{
|
||||
PhysXSphereCollider sphere(5.f, {1.f, 2.f, 3.f});
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({0.f, 0.f, 0.f});
|
||||
EXPECT_EQ(p, sphere.get_origin());
|
||||
}
|
||||
|
||||
TEST(PhysXSphereCollider, SetRadiusUpdatesGeometry)
|
||||
{
|
||||
PhysXSphereCollider sphere(1.f);
|
||||
sphere.set_radius(10.f);
|
||||
EXPECT_FLOAT_EQ(sphere.get_radius(), 10.f);
|
||||
|
||||
// Furthest point along +x should now be at x = 10.
|
||||
const auto p = sphere.find_abs_furthest_vertex_position({1.f, 0.f, 0.f});
|
||||
EXPECT_FLOAT_EQ(p.x, 10.f);
|
||||
}
|
||||
|
||||
// ─── GJK: Box vs Box ─────────────────────────────────────────────────────────
|
||||
|
||||
using GjkBox = omath::collision::GjkAlgorithm<PhysXBoxCollider>;
|
||||
using GjkSphere = omath::collision::GjkAlgorithm<PhysXSphereCollider>;
|
||||
|
||||
TEST(PhysXBoxGjk, CollidingOverlap)
|
||||
{
|
||||
// Two unit boxes: A at origin, B shifted by 0.5 — clearly overlapping.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {0.5f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, NotCollidingTouching)
|
||||
{
|
||||
// Boxes exactly touching on the +X face: A[-1,1] and B[1,3] along X.
|
||||
// GJK treats boundary contact (Minkowski difference passes through origin) as non-collision.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {2.f, 0.f, 0.f});
|
||||
EXPECT_FALSE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, CollidingSlightOverlap)
|
||||
{
|
||||
// Boxes overlapping by 0.1 along X: A[-1,1] and B[0.9,2.9].
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {1.9f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, NotCollidingSeparated)
|
||||
{
|
||||
// Boxes separated by a gap: A[-1,1] and B[3,5] along X.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {4.f, 0.f, 0.f});
|
||||
EXPECT_FALSE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, CollidingSameOrigin)
|
||||
{
|
||||
// Same position — fully overlapping.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f});
|
||||
EXPECT_TRUE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, NotCollidingDiagonalSeparation)
|
||||
{
|
||||
// Boxes separated along a diagonal so no axis-aligned faces overlap.
|
||||
const PhysXBoxCollider a({1.f, 1.f, 1.f});
|
||||
const PhysXBoxCollider b({1.f, 1.f, 1.f}, {3.f, 3.f, 3.f});
|
||||
EXPECT_FALSE(GjkBox::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXBoxGjk, DifferentSizesColliding)
|
||||
{
|
||||
// Large box vs small box inside it.
|
||||
const PhysXBoxCollider large({5.f, 5.f, 5.f});
|
||||
const PhysXBoxCollider small_box({1.f, 1.f, 1.f}, {2.f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkBox::is_collide(large, small_box));
|
||||
}
|
||||
|
||||
// ─── GJK: Sphere vs Sphere ───────────────────────────────────────────────────
|
||||
|
||||
TEST(PhysXSphereGjk, CollidingOverlap)
|
||||
{
|
||||
// Radii 1 each, centres 1 apart — overlapping.
|
||||
const PhysXSphereCollider a(1.f);
|
||||
const PhysXSphereCollider b(1.f, {1.f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereGjk, CollidingSameOrigin)
|
||||
{
|
||||
const PhysXSphereCollider a(1.f);
|
||||
const PhysXSphereCollider b(1.f);
|
||||
EXPECT_TRUE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereGjk, NotCollidingSeparated)
|
||||
{
|
||||
// Radii 1 each, centres 3 apart — gap of 1.
|
||||
const PhysXSphereCollider a(1.f);
|
||||
const PhysXSphereCollider b(1.f, {3.f, 0.f, 0.f});
|
||||
EXPECT_FALSE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereGjk, DifferentRadiiColliding)
|
||||
{
|
||||
// r=2 and r=1, centres 2.5 apart — still overlapping.
|
||||
const PhysXSphereCollider a(2.f);
|
||||
const PhysXSphereCollider b(1.f, {2.5f, 0.f, 0.f});
|
||||
EXPECT_TRUE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
TEST(PhysXSphereGjk, DifferentRadiiNotColliding)
|
||||
{
|
||||
// r=1 and r=1, centres 5 apart — separated.
|
||||
const PhysXSphereCollider a(1.f);
|
||||
const PhysXSphereCollider b(1.f, {5.f, 0.f, 0.f});
|
||||
EXPECT_FALSE(GjkSphere::is_collide(a, b));
|
||||
}
|
||||
|
||||
// ─── PhysX simulation-based collision resolution ─────────────────────────────
|
||||
|
||||
// Helper: step the world N times with a fixed dt.
|
||||
static void step_n(omath::collision::PhysXWorld& world, int n, float dt = 1.f / 60.f)
|
||||
{
|
||||
for (int i = 0; i < n; ++i)
|
||||
world.step(dt);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, BoxFallsAndStopsOnGround)
|
||||
{
|
||||
// A box dropped from y=5 should come to rest at y≈0.5 (half-extent) above the ground plane.
|
||||
omath::collision::PhysXWorld world;
|
||||
world.add_ground_plane(0.f);
|
||||
|
||||
omath::collision::PhysXRigidBody box(world, physx::PxBoxGeometry(0.5f, 0.5f, 0.5f),
|
||||
{0.f, 5.f, 0.f});
|
||||
|
||||
step_n(world, 300); // ~5 simulated seconds
|
||||
|
||||
EXPECT_NEAR(box.get_origin().y, 0.5f, 0.05f);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, SphereFallsAndStopsOnGround)
|
||||
{
|
||||
// A sphere of radius 1 dropped from y=5 should rest at y≈1.
|
||||
omath::collision::PhysXWorld world;
|
||||
world.add_ground_plane(0.f);
|
||||
|
||||
omath::collision::PhysXRigidBody sphere(world, physx::PxSphereGeometry(1.f),
|
||||
{0.f, 5.f, 0.f});
|
||||
|
||||
step_n(world, 300);
|
||||
|
||||
EXPECT_NEAR(sphere.get_origin().y, 1.f, 0.05f);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, TwoBoxesCollideSeparate)
|
||||
{
|
||||
// Two boxes launched toward each other — after collision they must be
|
||||
// further apart than their combined half-extents (no overlap).
|
||||
omath::collision::PhysXWorld world({0.f, 0.f, 0.f}); // no gravity
|
||||
|
||||
omath::collision::PhysXRigidBody left (world, physx::PxBoxGeometry(0.5f, 0.5f, 0.5f), {-3.f, 0.f, 0.f});
|
||||
omath::collision::PhysXRigidBody right(world, physx::PxBoxGeometry(0.5f, 0.5f, 0.5f), { 3.f, 0.f, 0.f});
|
||||
|
||||
left.set_linear_velocity({ 5.f, 0.f, 0.f});
|
||||
right.set_linear_velocity({-5.f, 0.f, 0.f});
|
||||
|
||||
step_n(world, 120); // 2 simulated seconds
|
||||
|
||||
const float distance = right.get_origin().x - left.get_origin().x;
|
||||
// Boxes must not be overlapping (combined extents = 1.0).
|
||||
EXPECT_GE(distance, 1.0f);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, BoxGetOriginMatchesSetOrigin)
|
||||
{
|
||||
// Kinematic teleport — set_origin must immediately reflect in get_origin.
|
||||
omath::collision::PhysXWorld world;
|
||||
omath::collision::PhysXRigidBody box(world, physx::PxBoxGeometry(1.f, 1.f, 1.f));
|
||||
box.set_kinematic(true);
|
||||
|
||||
box.set_origin({7.f, 3.f, -2.f});
|
||||
|
||||
EXPECT_NEAR(box.get_origin().x, 7.f, 1e-4f);
|
||||
EXPECT_NEAR(box.get_origin().y, 3.f, 1e-4f);
|
||||
EXPECT_NEAR(box.get_origin().z, -2.f, 1e-4f);
|
||||
}
|
||||
|
||||
TEST(PhysXSimulation, BoxFallsUnderGravity)
|
||||
{
|
||||
// Without a floor, a box should be lower after simulation than its start.
|
||||
omath::collision::PhysXWorld world; // default gravity -9.81 Y
|
||||
omath::collision::PhysXRigidBody box(world, physx::PxBoxGeometry(0.5f, 0.5f, 0.5f),
|
||||
{0.f, 10.f, 0.f});
|
||||
|
||||
const float y_start = box.get_origin().y;
|
||||
step_n(world, 60); // 1 simulated second
|
||||
|
||||
EXPECT_LT(box.get_origin().y, y_start);
|
||||
}
|
||||
|
||||
#endif // OMATH_ENABLE_PHYSX
|
||||
66
tests/lua/pe_scanner_tests.lua
Normal file
66
tests/lua/pe_scanner_tests.lua
Normal file
@@ -0,0 +1,66 @@
|
||||
-- PatternScanner tests: generic scan over a Lua string buffer
|
||||
|
||||
function PatternScanner_FindsExactPattern()
|
||||
local buf = "\x90\x01\x02\x03\x04"
|
||||
local offset = omath.PatternScanner.scan(buf, "90 01 02")
|
||||
assert(offset ~= nil, "expected pattern to be found")
|
||||
assert(offset == 0, "expected offset 0, got " .. tostring(offset))
|
||||
end
|
||||
|
||||
function PatternScanner_FindsPatternAtNonZeroOffset()
|
||||
local buf = "\x00\x00\xAB\xCD\xEF"
|
||||
local offset = omath.PatternScanner.scan(buf, "AB CD EF")
|
||||
assert(offset ~= nil, "expected pattern to be found")
|
||||
assert(offset == 2, "expected offset 2, got " .. tostring(offset))
|
||||
end
|
||||
|
||||
function PatternScanner_WildcardMatches()
|
||||
local buf = "\xDE\xAD\xBE\xEF"
|
||||
local offset = omath.PatternScanner.scan(buf, "DE ?? BE")
|
||||
assert(offset ~= nil, "expected wildcard match")
|
||||
assert(offset == 0)
|
||||
end
|
||||
|
||||
function PatternScanner_ReturnsNilWhenNotFound()
|
||||
local buf = "\x01\x02\x03"
|
||||
local offset = omath.PatternScanner.scan(buf, "AA BB CC")
|
||||
assert(offset == nil, "expected nil for not-found pattern")
|
||||
end
|
||||
|
||||
function PatternScanner_ReturnsNilForEmptyBuffer()
|
||||
local offset = omath.PatternScanner.scan("", "90 01")
|
||||
assert(offset == nil)
|
||||
end
|
||||
|
||||
-- PePatternScanner tests: scan_in_module uses FAKE_MODULE_BASE injected from C++
|
||||
-- The fake module contains {0x90, 0x01, 0x02, 0x03, 0x04} placed at raw offset 0x200
|
||||
|
||||
function PeScanner_FindsExactPattern()
|
||||
local addr = omath.PePatternScanner.scan_in_module(FAKE_MODULE_BASE, "90 01 02")
|
||||
assert(addr ~= nil, "expected pattern to be found in module")
|
||||
local offset = addr - FAKE_MODULE_BASE
|
||||
assert(offset == 0x200, string.format("expected offset 0x200, got 0x%X", offset))
|
||||
end
|
||||
|
||||
function PeScanner_WildcardMatches()
|
||||
local addr = omath.PePatternScanner.scan_in_module(FAKE_MODULE_BASE, "90 ?? 02")
|
||||
assert(addr ~= nil, "expected wildcard match in module")
|
||||
local offset = addr - FAKE_MODULE_BASE
|
||||
assert(offset == 0x200, string.format("expected offset 0x200, got 0x%X", offset))
|
||||
end
|
||||
|
||||
function PeScanner_ReturnsNilWhenNotFound()
|
||||
local addr = omath.PePatternScanner.scan_in_module(FAKE_MODULE_BASE, "AA BB CC DD")
|
||||
assert(addr == nil, "expected nil for not-found pattern")
|
||||
end
|
||||
|
||||
function PeScanner_CustomSectionFallsBackToNil()
|
||||
-- Request a section that doesn't exist in our fake module
|
||||
local addr = omath.PePatternScanner.scan_in_module(FAKE_MODULE_BASE, "90 01 02", ".rdata")
|
||||
assert(addr == nil, "expected nil for wrong section name")
|
||||
end
|
||||
|
||||
-- SectionScanResult: verify the type is registered and tostring works on a C++-returned value
|
||||
function SectionScanResult_TypeIsRegistered()
|
||||
assert(omath.SectionScanResult ~= nil, "SectionScanResult type should be registered")
|
||||
end
|
||||
113
tests/lua/unit_test_lua_pe_scanner.cpp
Normal file
113
tests/lua/unit_test_lua_pe_scanner.cpp
Normal file
@@ -0,0 +1,113 @@
|
||||
//
|
||||
// Created by orange on 10.03.2026.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <lua.hpp>
|
||||
#include <omath/lua/lua.hpp>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
std::vector<std::uint8_t> make_fake_pe_module(std::uint32_t base_of_code, std::uint32_t size_code,
|
||||
const std::vector<std::uint8_t>& code_bytes)
|
||||
{
|
||||
constexpr std::uint32_t e_lfanew = 0x80;
|
||||
constexpr std::uint32_t nt_sig = 0x4550;
|
||||
constexpr std::uint16_t opt_magic = 0x020B; // PE32+
|
||||
constexpr std::uint16_t num_sections = 1;
|
||||
constexpr std::uint16_t opt_hdr_size = 0xF0;
|
||||
constexpr std::uint32_t section_table_off = e_lfanew + 4 + 20 + opt_hdr_size;
|
||||
constexpr std::uint32_t section_hdr_size = 40;
|
||||
constexpr std::uint32_t text_chars = 0x60000020;
|
||||
|
||||
const std::uint32_t headers_end = section_table_off + section_hdr_size;
|
||||
const std::uint32_t code_end = base_of_code + size_code;
|
||||
const std::uint32_t total_size = std::max(headers_end, code_end) + 0x100;
|
||||
std::vector<std::uint8_t> buf(total_size, 0);
|
||||
|
||||
auto w16 = [&](std::size_t off, std::uint16_t v) { std::memcpy(buf.data() + off, &v, 2); };
|
||||
auto w32 = [&](std::size_t off, std::uint32_t v) { std::memcpy(buf.data() + off, &v, 4); };
|
||||
auto w64 = [&](std::size_t off, std::uint64_t v) { std::memcpy(buf.data() + off, &v, 8); };
|
||||
|
||||
w16(0x00, 0x5A4D);
|
||||
w32(0x3C, e_lfanew);
|
||||
w32(e_lfanew, nt_sig);
|
||||
|
||||
const std::size_t fh = e_lfanew + 4;
|
||||
w16(fh + 2, num_sections);
|
||||
w16(fh + 16, opt_hdr_size);
|
||||
|
||||
const std::size_t opt = fh + 20;
|
||||
w16(opt + 0, opt_magic);
|
||||
w32(opt + 4, size_code);
|
||||
w32(opt + 20, base_of_code);
|
||||
w64(opt + 24, 0);
|
||||
w32(opt + 32, 0x1000);
|
||||
w32(opt + 36, 0x200);
|
||||
w32(opt + 56, code_end);
|
||||
w32(opt + 60, headers_end);
|
||||
w32(opt + 108, 0);
|
||||
|
||||
const std::size_t sh = section_table_off;
|
||||
std::memcpy(buf.data() + sh, ".text", 5);
|
||||
w32(sh + 8, size_code);
|
||||
w32(sh + 12, base_of_code);
|
||||
w32(sh + 16, size_code);
|
||||
w32(sh + 20, base_of_code);
|
||||
w32(sh + 36, text_chars);
|
||||
|
||||
if (base_of_code + code_bytes.size() <= buf.size())
|
||||
std::memcpy(buf.data() + base_of_code, code_bytes.data(), code_bytes.size());
|
||||
|
||||
return buf;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class LuaPeScanner : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
lua_State* L = nullptr;
|
||||
std::vector<std::uint8_t> m_fake_module;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x90, 0x01, 0x02, 0x03, 0x04};
|
||||
m_fake_module = make_fake_pe_module(0x200, static_cast<std::uint32_t>(code.size()), code);
|
||||
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
omath::lua::LuaInterpreter::register_lib(L);
|
||||
|
||||
lua_pushinteger(L, static_cast<lua_Integer>(
|
||||
reinterpret_cast<std::uintptr_t>(m_fake_module.data())));
|
||||
lua_setglobal(L, "FAKE_MODULE_BASE");
|
||||
|
||||
if (luaL_dofile(L, LUA_SCRIPTS_DIR "/pe_scanner_tests.lua") != LUA_OK)
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
void TearDown() override { lua_close(L); }
|
||||
|
||||
void check(const char* func_name)
|
||||
{
|
||||
lua_getglobal(L, func_name);
|
||||
if (lua_pcall(L, 0, 0, 0) != LUA_OK)
|
||||
{
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LuaPeScanner, PatternScanner_FindsExactPattern) { check("PatternScanner_FindsExactPattern"); }
|
||||
TEST_F(LuaPeScanner, PatternScanner_FindsPatternAtOffset) { check("PatternScanner_FindsPatternAtNonZeroOffset"); }
|
||||
TEST_F(LuaPeScanner, PatternScanner_WildcardMatches) { check("PatternScanner_WildcardMatches"); }
|
||||
TEST_F(LuaPeScanner, PatternScanner_ReturnsNilWhenNotFound) { check("PatternScanner_ReturnsNilWhenNotFound"); }
|
||||
TEST_F(LuaPeScanner, PatternScanner_ReturnsNilForEmptyBuffer){ check("PatternScanner_ReturnsNilForEmptyBuffer"); }
|
||||
TEST_F(LuaPeScanner, PeScanner_FindsExactPattern) { check("PeScanner_FindsExactPattern"); }
|
||||
TEST_F(LuaPeScanner, PeScanner_WildcardMatches) { check("PeScanner_WildcardMatches"); }
|
||||
TEST_F(LuaPeScanner, PeScanner_ReturnsNilWhenNotFound) { check("PeScanner_ReturnsNilWhenNotFound"); }
|
||||
TEST_F(LuaPeScanner, PeScanner_CustomSectionFallsBackToNil) { check("PeScanner_CustomSectionFallsBackToNil"); }
|
||||
TEST_F(LuaPeScanner, SectionScanResult_TypeIsRegistered) { check("SectionScanResult_TypeIsRegistered"); }
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"default-registry": {
|
||||
"kind": "git",
|
||||
"baseline": "b1b19307e2d2ec1eefbdb7ea069de7d4bcd31f01",
|
||||
"baseline": "efa4634bd526b87559684607d2cbbdeeec0f07d8",
|
||||
"repository": "https://github.com/microsoft/vcpkg"
|
||||
},
|
||||
"registries": [
|
||||
|
||||
@@ -52,6 +52,13 @@
|
||||
"lua",
|
||||
"sol2"
|
||||
]
|
||||
},
|
||||
"physx": {
|
||||
"description": "PhysX-backed collider implementations",
|
||||
"dependencies": [
|
||||
"physx"
|
||||
],
|
||||
"supports": "(windows & x64 & !mingw & !uwp) | (linux & x64) | (linux & arm64)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user