Compare commits

..

26 Commits

Author SHA1 Message Date
9ba3bc754a removed define 2025-02-23 21:56:28 +03:00
3d1844fa0e Merge pull request #28 from orange-cpp/u/orange-cpp/avx2-prediction
U/orange cpp/avx2 prediction
2025-02-23 16:32:27 +03:00
f21d29c6c2 added legacy impl 2025-02-23 10:10:35 +03:00
28a35d5bc9 added more classes 2025-02-23 09:57:29 +03:00
d9684ff73f read me update 2025-02-22 23:34:45 +03:00
900501f37e added language mention 2025-02-22 23:34:45 +03:00
5639cd0eb5 added AVX2 2025-02-22 23:34:45 +03:00
244d01c313 Merge pull request #27 from orange-cpp/u/orange-cpp/unity-build-support
added unity build support
2025-02-22 23:33:03 +03:00
e31ffac103 added unity build support 2025-02-22 23:32:29 +03:00
ae87257adf Merge pull request #26 from orange-cpp/u/orange-cpp/improved-astar
Improved A*
2025-02-22 23:06:33 +03:00
906f5099d1 improvement 2025-02-16 10:57:03 +03:00
96e4e1c9d6 added new method added concept for mat type 2025-02-16 10:06:04 +03:00
872dbe146f Merge pull request #25 from orange-cpp/u/orange-cpp/hotfix
improved cmake+hotfix of clang support
2025-01-17 16:59:30 +03:00
e0dcb65e3f improved cmake+hotfix of clang support 2025-01-17 16:56:47 +03:00
d0c532df39 hot fix 2025-01-06 05:36:27 +03:00
31907ceca3 Merge pull request #24 from orange-cpp/u/orange-cpp/improved-triangle-class
U/orange cpp/improved triangle class
2025-01-06 05:19:27 +03:00
afcfed4834 path 2025-01-06 05:17:42 +03:00
835fd110ba fix 2025-01-06 05:15:12 +03:00
29629a737d added some methods 2025-01-06 05:08:32 +03:00
6a324e8c0e improvement 2025-01-06 04:42:43 +03:00
42c84f2523 added midpoint for triangle class 2025-01-06 04:30:03 +03:00
9a4fb67289 hotfix 2025-01-02 20:32:25 +03:00
824b301d40 small code improvement 2025-01-02 18:40:19 +03:00
dcf466316c Merge pull request #23 from orange-cpp/u/orange-cpp/vec3-angle-calc
added AngleBetween method for Vector3 + tests
2025-01-02 12:54:27 +03:00
dc0bca14c5 added method + tests 2025-01-02 12:52:34 +03:00
b2db06a739 updated read me 2024-12-26 18:52:24 +03:00
33 changed files with 615 additions and 173 deletions

View File

@@ -1,18 +1,15 @@
cmake_minimum_required(VERSION 3.26)
project(omath VERSION 1.0.1)
project(omath VERSION 1.0.1 LANGUAGES CXX)
include(CMakePackageConfigHelpers)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}")
option(OMATH_BUILD_TESTS "Build unit tests" ON)
option(OMATH_THREAT_WARNING_AS_ERROR "Set highest level of warnings and force compiler to treat them as errors" ON)
option(OMATH_BUILD_AS_SHARED_LIBRARY "Build Omath as .so or .dll" OFF)
if (OMATH_BUILD_AS_SHARED_LIBRARY)
add_library(omath SHARED source/Vector3.cpp)
else()
@@ -22,7 +19,17 @@ else()
include/omath/engines/OpenGL/Camera.hpp)
endif()
target_compile_definitions(omath PUBLIC OMATH_EXPORT)
set_target_properties(omath PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
UNITY_BUILD ON
UNITY_BUILD_BATCH_SIZE 20
CXX_STANDARD 23
CXX_STANDARD_REQUIRED ON)
target_compile_features(omath PUBLIC cxx_std_23)
add_subdirectory(source)

View File

@@ -11,7 +11,7 @@
Oranges's Math Library (omath) is a comprehensive, open-source library aimed at providing efficient, reliable, and versatile mathematical functions and algorithms. Developed primarily in C++, this library is designed to cater to a wide range of mathematical operations essential in scientific computing, engineering, and academic research.
## Features
## 👁‍🗨 Features
- **Efficiency**: Optimized for performance, ensuring quick computations.
- **Versatility**: Includes a wide array of mathematical functions and algorithms.
- **Ease of Use**: Simplified interface for convenient integration into various projects.
@@ -20,7 +20,7 @@ Oranges's Math Library (omath) is a comprehensive, open-source library aimed at
- **Collision Detection**: Production ready code to handle collision detection by using simple interfaces.
- **No Additional Dependencies**: No additional dependencies need to use OMath except unit test execution
## Getting Started
## Getting Started
### Prerequisites
- C++ Compiler
- CMake (for building the project)
@@ -51,10 +51,10 @@ For detailed commands on installing different versions and more information, ple
3. Build the project using CMake:
```
cmake --preset windows-release -S .
cmake --build cmake-build/build/windows-release --target server -j 6
cmake --build cmake-build/build/windows-release --target omath -j 6
```
Use **\<platform\>-\<build configuration\>** preset to build siutable version for yourself. Like **windows-release** or **linux-release**.
## Usage
## Usage
Simple world to screen function
```c++
TEST(UnitTestProjection, IsPointOnScreen)
@@ -76,11 +76,11 @@ With `omath/projection` module you can achieve simple ESP hack for powered by So
</details>
## Contributing
## 🫵🏻 Contributing
Contributions to `omath` are welcome! Please read `CONTRIBUTING.md` for details on our code of conduct and the process for submitting pull requests.
## License
## 📜 License
This project is licensed under the MIT - see the `LICENSE` file for details.
## Acknowledgments
## 💘 Acknowledgments
- [All contributors](https://github.com/orange-cpp/omath/graphs/contributors)

View File

@@ -22,6 +22,13 @@ namespace omath
COLUMN_MAJOR
};
template<typename M1, typename M2>
concept MatTemplateEqual =
(M1::rows == M2::rows) && (M1::columns == M2::columns) &&
std::is_same_v<typename M1::value_type, typename M2::value_type> &&
(M1::store_type == M2::store_type);
template<size_t Rows = 0, size_t Columns = 0, class Type = float, MatStoreType StoreType = MatStoreType::ROW_MAJOR>
requires std::is_arithmetic_v<Type>
class Mat final

View File

@@ -38,10 +38,7 @@ namespace omath
[[nodiscard]]
float& operator[](size_t row, size_t column)
{
return At(row, column);
}
float& operator[](size_t row, size_t column);
[[nodiscard]]
size_t ColumnsCount() const noexcept;

View File

@@ -0,0 +1,74 @@
//
// Created by Orange on 11/13/2024.
//
#pragma once
#include "omath/Vector3.hpp"
namespace omath
{
template<class Vector>
class Triangle final
{
public:
constexpr Triangle() = default;
constexpr Triangle(const Vector& vertex1, const Vector& vertex2, const Vector& vertex3)
: m_vertex1(vertex1), m_vertex2(vertex2), m_vertex3(vertex3)
{
}
Vector3 m_vertex1;
Vector3 m_vertex2;
Vector3 m_vertex3;
[[nodiscard]]
constexpr Vector3 CalculateNormal() const
{
const auto b = SideBVector();
const auto a = SideAVector();
return b.Cross(a).Normalized();
}
[[nodiscard]]
float SideALength() const
{
return m_vertex1.DistTo(m_vertex2);
}
[[nodiscard]]
float SideBLength() const
{
return m_vertex3.DistTo(m_vertex2);
}
[[nodiscard]]
constexpr Vector3 SideAVector() const
{
return m_vertex1 - m_vertex2;
}
[[nodiscard]]
constexpr float Hypot() const
{
return m_vertex1.DistTo(m_vertex3);
}
[[nodiscard]]
constexpr bool IsRectangular() const
{
const auto sideA = SideALength();
const auto sideB = SideBLength();
const auto hypot = Hypot();
return std::abs(sideA*sideA + sideB*sideB - hypot*hypot) <= 0.0001f;
}
[[nodiscard]]
constexpr Vector3 SideBVector() const
{
return m_vertex3 - m_vertex2;
}
[[nodiscard]]
constexpr Vector3 MidPoint() const
{
return (m_vertex1 + m_vertex2 + m_vertex3) / 3;
}
};
} // namespace omath

View File

@@ -1,33 +0,0 @@
//
// Created by Orange on 11/13/2024.
//
#pragma once
#include "omath/Vector3.hpp"
namespace omath
{
class Triangle3d final
{
public:
Triangle3d(const Vector3& vertex1, const Vector3& vertex2, const Vector3& vertex3);
Vector3 m_vertex1;
Vector3 m_vertex2;
Vector3 m_vertex3;
[[nodiscard]]
Vector3 CalculateNormal() const;
[[nodiscard]]
float SideALength() const;
[[nodiscard]]
float SideBLength() const;
[[nodiscard]]
Vector3 SideAVector() const;
[[nodiscard]]
Vector3 SideBVector() const;
};
}

View File

@@ -7,9 +7,19 @@
#include <cstdint>
#include <functional>
#include "omath/Vector2.hpp"
#include "omath/Angle.hpp"
#include <expected>
#include <immintrin.h>
namespace omath
{
enum class Vector3Error
{
IMPOSSIBLE_BETWEEN_ANGLE,
};
class Vector3 : public Vector2
{
public:
@@ -208,6 +218,25 @@ namespace omath
return Sum2D() + z;
}
[[nodiscard]] std::expected<Angle<float, 0.f, 180.f, AngleFlags::Clamped>, Vector3Error>
AngleBetween(const Vector3& other) const
{
const auto bottom = Length() * other.Length();
if (bottom == 0.f)
return std::unexpected(Vector3Error::IMPOSSIBLE_BETWEEN_ANGLE);
return Angle<float, 0.f, 180.f, AngleFlags::Clamped>::FromRadians(std::acos(Dot(other) / bottom));
}
[[nodiscard]] bool IsPerpendicular(const Vector3& other) const
{
if (const auto angle = AngleBetween(other))
return angle->AsDegrees() == 90.f;
return false;
}
[[nodiscard]] constexpr float Sum2D() const
{
return Vector2::Sum();
@@ -215,7 +244,7 @@ namespace omath
[[nodiscard]] Vector3 ViewAngleTo(const Vector3& other) const;
[[nodiscard]] std::tuple<float, float, float> AsTuple() const
[[nodiscard]] constexpr std::tuple<float, float, float> AsTuple() const
{
return std::make_tuple(x, y, z);
}

View File

@@ -4,7 +4,7 @@
#pragma once
#include "omath/Vector3.hpp"
#include "omath/Triangle3d.hpp"
#include "omath/Triangle.hpp"
namespace omath::collision
{
@@ -27,12 +27,12 @@ namespace omath::collision
[[nodiscard]]
static bool CanTraceLine(const Ray& ray, const Triangle3d& triangle);
static bool CanTraceLine(const Ray& ray, const Triangle<Vector3>& triangle);
// Realization of MöllerTrumbore intersection algorithm
// https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm
[[nodiscard]]
static Vector3 GetRayHitPoint(const Ray& ray, const Triangle3d& triangle);
static Vector3 GetRayHitPoint(const Ray& ray, const Triangle<Vector3>& triangle);
};
}

View File

@@ -9,11 +9,17 @@
namespace omath::pathfinding
{
struct PathNode;
class Astar final
{
public:
[[nodiscard]]
static std::vector<Vector3> FindPath(const Vector3& start, const Vector3& end, const NavigationMesh& navMesh);
private:
[[nodiscard]]
static std::vector<Vector3> ReconstructFinalPath(const std::unordered_map<Vector3, PathNode>& closedList, const Vector3& current);
[[nodiscard]]
static auto GetPerfectNode(const std::unordered_map<Vector3, PathNode>& openList, const Vector3& endVertex);
};
}

View File

@@ -0,0 +1,20 @@
//
// Created by Vlad on 2/23/2025.
//
#pragma once
#include "Projectile.hpp"
#include "Target.hpp"
#include "omath/Vector3.hpp"
namespace omath::projectile_prediction
{
class ProjPredEngine
{
public:
[[nodiscard]]
virtual std::optional<Vector3> MaybeCalculateAimPoint(const Projectile& projectile,
const Target& target) const = 0;
virtual ~ProjPredEngine() = default;
};
} // namespace omath::projectile_prediction

View File

@@ -0,0 +1,26 @@
//
// Created by Vlad on 2/23/2025.
//
#pragma once
#include "ProjPredEngine.hpp"
namespace omath::projectile_prediction
{
class ProjPredEngineAVX2 final : public ProjPredEngine
{
public:
[[nodiscard]] std::optional<Vector3> MaybeCalculateAimPoint(const Projectile& projectile,
const Target& target) const override;
ProjPredEngineAVX2(float gravityConstant, float simulationTimeStep, float maximumSimulationTime);
~ProjPredEngineAVX2() override = default;
private:
[[nodiscard]] static std::optional<float> CalculatePitch(const Vector3& projOrigin, const Vector3& targetPos,
float bulletGravity, float v0, float time);
const float m_gravityConstant;
const float m_simulationTimeStep;
const float m_maximumSimulationTime;
};
} // namespace omath::projectile_prediction

View File

@@ -6,19 +6,22 @@
#include <optional>
#include "omath/Vector3.hpp"
#include "omath/prediction/Projectile.hpp"
#include "omath/prediction/Target.hpp"
#include "omath/projectile_prediction/ProjPredEngine.hpp"
#include "omath/projectile_prediction/Projectile.hpp"
#include "omath/projectile_prediction/Target.hpp"
namespace omath::prediction
namespace omath::projectile_prediction
{
class Engine final
class ProjPredEngineLegacy final : public ProjPredEngine
{
public:
explicit Engine(float gravityConstant, float simulationTimeStep,
float maximumSimulationTime, float distanceTolerance);
explicit ProjPredEngineLegacy(float gravityConstant, float simulationTimeStep, float maximumSimulationTime,
float distanceTolerance);
[[nodiscard]]
std::optional<Vector3> MaybeCalculateAimPoint(const Projectile& projectile, const Target& target) const;
std::optional<Vector3> MaybeCalculateAimPoint(const Projectile& projectile,
const Target& target) const override;
private:
const float m_gravityConstant;
@@ -32,7 +35,7 @@ namespace omath::prediction
[[nodiscard]]
bool IsProjectileReachedTarget(const Vector3& targetPosition, const Projectile& projectile, float pitch, float time) const;
bool IsProjectileReachedTarget(const Vector3& targetPosition, const Projectile& projectile, float pitch,
float time) const;
};
}
} // namespace omath::projectile_prediction

View File

@@ -5,7 +5,7 @@
#pragma once
#include "omath/Vector3.hpp"
namespace omath::prediction
namespace omath::projectile_prediction
{
class Projectile final
{

View File

@@ -5,7 +5,7 @@
#pragma once
#include "omath/Vector3.hpp"
namespace omath::prediction
namespace omath::projectile_prediction
{
class Target final
{

View File

@@ -24,7 +24,7 @@ namespace omath::projection
return m_width / m_height;
}
};
using FieldOfView = const Angle<float, 0.f, 180.f, AngleFlags::Clamped>;
using FieldOfView = Angle<float, 0.f, 180.f, AngleFlags::Clamped>;
template<class Mat4x4Type, class ViewAnglesType>
class Camera

View File

@@ -4,10 +4,9 @@ target_sources(omath PRIVATE
color.cpp
Vector4.cpp
Vector2.cpp
Triangle3d.cpp
)
add_subdirectory(prediction)
add_subdirectory(projectile_prediction)
add_subdirectory(pathfinding)
add_subdirectory(projection)
add_subdirectory(collision)

View File

@@ -74,6 +74,11 @@ namespace omath
{
return m_rows;
}
float& Matrix::operator[](const size_t row, const size_t column)
{
return At(row, column);
}
Matrix::Matrix(Matrix&& other) noexcept
{

View File

@@ -1,36 +0,0 @@
#include "omath/Triangle3d.hpp"
namespace omath
{
Triangle3d::Triangle3d(const Vector3 &vertex1, const Vector3 &vertex2, const Vector3 &vertex3)
: m_vertex1(vertex1), m_vertex2(vertex2), m_vertex3(vertex3)
{
}
Vector3 Triangle3d::CalculateNormal() const
{
return (m_vertex1 - m_vertex2).Cross(m_vertex3 - m_vertex1).Normalized();
}
float Triangle3d::SideALength() const
{
return m_vertex1.DistTo(m_vertex2);
}
float Triangle3d::SideBLength() const
{
return m_vertex3.DistTo(m_vertex2);
}
Vector3 Triangle3d::SideAVector() const
{
return m_vertex1 - m_vertex2;
}
Vector3 Triangle3d::SideBVector() const
{
return m_vertex3 - m_vertex2;
}
}

View File

@@ -5,7 +5,7 @@
namespace omath::collision
{
bool LineTracer::CanTraceLine(const Ray &ray, const Triangle3d &triangle)
bool LineTracer::CanTraceLine(const Ray& ray, const Triangle<Vector3>& triangle)
{
return GetRayHitPoint(ray, triangle) == ray.end;
}
@@ -19,7 +19,7 @@ namespace omath::collision
return DirectionVector().Normalized();
}
Vector3 LineTracer::GetRayHitPoint(const Ray &ray, const Triangle3d &triangle)
Vector3 LineTracer::GetRayHitPoint(const Ray& ray, const Triangle<Vector3>& triangle)
{
constexpr float kEpsilon = std::numeric_limits<float>::epsilon();
@@ -41,7 +41,7 @@ namespace omath::collision
const auto u = t.Dot(p) * invDet;
if ((u < 0 && std::abs(u) > kEpsilon) || (u > 1 && std::abs(u-1) > kEpsilon))
if ((u < 0 && std::abs(u) > kEpsilon) || (u > 1 && std::abs(u - 1) > kEpsilon))
return ray.end;
const auto q = t.Cross(sideA);
@@ -59,4 +59,4 @@ namespace omath::collision
return ray.start + rayDir * tHit;
}
}
} // namespace omath::collision

View File

@@ -9,7 +9,7 @@ namespace omath::opengl
{
Camera::Camera(const Vector3& position, const ViewAngles& viewAngles, const projection::ViewPort& viewPort,
const Angle<float, 0, 180, AngleFlags::Clamped>& fov, const float near, const float far) :
const Angle<float, 0.f, 180.f, AngleFlags::Clamped>& fov, const float near, const float far) :
projection::Camera<Mat4x4, ViewAngles>(position, viewAngles, viewPort, fov, near, far)
{
}

View File

@@ -3,10 +3,10 @@
//
#include "omath/pathfinding/Astar.hpp"
#include <algorithm>
#include <optional>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
namespace omath::pathfinding
@@ -18,45 +18,83 @@ namespace omath::pathfinding
};
std::vector<Vector3> Astar::FindPath(const Vector3 &start, const Vector3 &end, const NavigationMesh &navMesh)
std::vector<Vector3> Astar::ReconstructFinalPath(const std::unordered_map<Vector3, PathNode>& closedList,
const Vector3& current)
{
std::vector<Vector3> path;
std::optional currentOpt = current;
while (currentOpt)
{
path.push_back(*currentOpt);
auto it = closedList.find(*currentOpt);
if (it == closedList.end())
break;
currentOpt = it->second.cameFrom;
}
std::ranges::reverse(path);
return path;
}
auto Astar::GetPerfectNode(const std::unordered_map<Vector3, PathNode>& openList, const Vector3& endVertex)
{
return std::ranges::min_element(openList,
[&endVertex](const auto& a, const auto& b)
{
const float fA = a.second.gCost + a.first.DistTo(endVertex);
const float fB = b.second.gCost + b.first.DistTo(endVertex);
return fA < fB;
});
}
std::vector<Vector3> Astar::FindPath(const Vector3& start, const Vector3& end, const NavigationMesh& navMesh)
{
std::unordered_map<Vector3, PathNode> closedList;
std::unordered_map<Vector3, PathNode> openList;
const auto startVertex = navMesh.GetClosestVertex(start).value();
const auto endVertex = navMesh.GetClosestVertex(end).value();
auto maybeStartVertex = navMesh.GetClosestVertex(start);
auto maybeEndVertex = navMesh.GetClosestVertex(end);
if (!maybeStartVertex || !maybeEndVertex)
return {};
const auto startVertex = maybeStartVertex.value();
const auto endVertex = maybeEndVertex.value();
openList.emplace(startVertex, PathNode{std::nullopt, 0.f});
while (!openList.empty())
{
const auto perfectVertex = *std::ranges::min_element(openList,
[&endVertex](const auto& a, const auto& b) -> bool
{
const auto aCost = a.second.gCost + a.first.DistTo(endVertex);
const auto bCost = b.second.gCost + b.first.DistTo(endVertex);
return aCost < bCost;
});
auto currentIt = GetPerfectNode(openList, endVertex);
closedList.emplace(perfectVertex);
openList.erase(perfectVertex.first);
const auto current = currentIt->first;
const auto currentNode = currentIt->second;
for (const auto& neighbor : navMesh.GetNeighbors(perfectVertex.first))
if (!closedList.contains(neighbor))
openList.emplace(neighbor, PathNode{perfectVertex.first, neighbor.DistTo(perfectVertex.first) + perfectVertex.second.gCost});
if (current == endVertex)
return ReconstructFinalPath(closedList, current);
if (perfectVertex.first != endVertex)
continue;
closedList.emplace(current, currentNode);
openList.erase(currentIt);
std::vector<Vector3> path = {};
for (const auto& neighbor: navMesh.GetNeighbors(current))
{
if (closedList.contains(neighbor))
continue;
for (std::optional current = perfectVertex.first; current; current = closedList.at(*current).cameFrom )
path.push_back(current.value());
const float tentativeGCost = currentNode.gCost + neighbor.DistTo(current);
return path;
const auto openIt = openList.find(neighbor);
if (openIt == openList.end() || tentativeGCost < openIt->second.gCost)
openList[neighbor] = PathNode{current, tentativeGCost};
}
}
return {};
}
}
} // namespace omath::pathfinding

View File

@@ -1 +0,0 @@
target_sources(omath PRIVATE Engine.cpp Projectile.cpp Target.cpp)

View File

@@ -0,0 +1 @@
target_sources(omath PRIVATE ProjPredEngineLegacy.cpp Projectile.cpp Target.cpp ProjPredEngineAVX2.cpp ProjPredEngine.cpp)

View File

@@ -0,0 +1,10 @@
//
// Created by Vlad on 2/23/2025.
//
#include "omath/projectile_prediction/ProjPredEngine.hpp"
namespace omath::projectile_prediction
{
} // namespace omath::projectile_prediction

View File

@@ -0,0 +1,138 @@
//
// Created by Vlad on 2/23/2025.
//
#include "omath/projectile_prediction/ProjPredEngineAVX2.hpp"
namespace omath::projectile_prediction
{
std::optional<Vector3> ProjPredEngineAVX2::MaybeCalculateAimPoint(const Projectile& projectile,
const Target& target) const
{
const float bulletGravity = m_gravityConstant * projectile.m_gravityScale;
const float v0 = projectile.m_launchSpeed;
const float v0Sqr = v0 * v0;
const Vector3 projOrigin = projectile.m_origin;
constexpr int SIMD_FACTOR = 8;
float currentTime = m_simulationTimeStep;
for (; currentTime <= m_maximumSimulationTime; currentTime += m_simulationTimeStep * SIMD_FACTOR)
{
const __m256 times =
_mm256_setr_ps(currentTime, currentTime + m_simulationTimeStep,
currentTime + m_simulationTimeStep * 2, currentTime + m_simulationTimeStep * 3,
currentTime + m_simulationTimeStep * 4, currentTime + m_simulationTimeStep * 5,
currentTime + m_simulationTimeStep * 6, currentTime + m_simulationTimeStep * 7);
const __m256 targetX =
_mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.x), times, _mm256_set1_ps(target.m_origin.x));
const __m256 targetY =
_mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.y), times, _mm256_set1_ps(target.m_origin.y));
const __m256 timesSq = _mm256_mul_ps(times, times);
const __m256 targetZ = _mm256_fmadd_ps(_mm256_set1_ps(target.m_velocity.z), times,
_mm256_fnmadd_ps(_mm256_set1_ps(0.5f * m_gravityConstant), timesSq,
_mm256_set1_ps(target.m_origin.z)));
const __m256 deltaX = _mm256_sub_ps(targetX, _mm256_set1_ps(projOrigin.x));
const __m256 deltaY = _mm256_sub_ps(targetY, _mm256_set1_ps(projOrigin.y));
const __m256 deltaZ = _mm256_sub_ps(targetZ, _mm256_set1_ps(projOrigin.z));
const __m256 dSqr = _mm256_add_ps(_mm256_mul_ps(deltaX, deltaX), _mm256_mul_ps(deltaY, deltaY));
const __m256 bgTimesSq = _mm256_mul_ps(_mm256_set1_ps(bulletGravity), timesSq);
const __m256 term = _mm256_add_ps(deltaZ, _mm256_mul_ps(_mm256_set1_ps(0.5f), bgTimesSq));
const __m256 termSq = _mm256_mul_ps(term, term);
const __m256 numerator = _mm256_add_ps(dSqr, termSq);
const __m256 denominator = _mm256_add_ps(timesSq, _mm256_set1_ps(1e-8f)); // Avoid division by zero
const __m256 requiredV0Sqr = _mm256_div_ps(numerator, denominator);
const __m256 v0SqrVec = _mm256_set1_ps(v0Sqr + 1e-3f);
const __m256 mask = _mm256_cmp_ps(requiredV0Sqr, v0SqrVec, _CMP_LE_OQ);
const unsigned validMask = _mm256_movemask_ps(mask);
if (!validMask)
continue;
alignas(32) float validTimes[SIMD_FACTOR];
_mm256_store_ps(validTimes, times);
for (int i = 0; i < SIMD_FACTOR; ++i)
{
if (!(validMask & (1 << i)))
continue;
const float candidateTime = validTimes[i];
if (candidateTime > m_maximumSimulationTime)
continue;
// Fine search around candidate time
for (float fineTime = candidateTime - m_simulationTimeStep * 2;
fineTime <= candidateTime + m_simulationTimeStep * 2; fineTime += m_simulationTimeStep)
{
if (fineTime < 0)
continue;
const Vector3 targetPos = target.PredictPosition(fineTime, m_gravityConstant);
const auto pitch = CalculatePitch(projOrigin, targetPos, bulletGravity, v0, fineTime);
if (!pitch)
continue;
const Vector3 delta = targetPos - projOrigin;
const float d = std::sqrt(delta.x * delta.x + delta.y * delta.y);
const float height = d * std::tan(angles::DegreesToRadians(*pitch));
return Vector3(targetPos.x, targetPos.y, projOrigin.z + height);
}
}
}
// Fallback scalar processing for remaining times
for (; currentTime <= m_maximumSimulationTime; currentTime += m_simulationTimeStep)
{
const Vector3 targetPos = target.PredictPosition(currentTime, m_gravityConstant);
const auto pitch = CalculatePitch(projOrigin, targetPos, bulletGravity, v0, currentTime);
if (!pitch)
continue;
const Vector3 delta = targetPos - projOrigin;
const float d = std::sqrt(delta.x * delta.x + delta.y * delta.y);
const float height = d * std::tan(angles::DegreesToRadians(*pitch));
return Vector3(targetPos.x, targetPos.y, projOrigin.z + height);
}
return std::nullopt;
}
ProjPredEngineAVX2::ProjPredEngineAVX2(const float gravityConstant, const float simulationTimeStep,
const float maximumSimulationTime) :
m_gravityConstant(gravityConstant), m_simulationTimeStep(maximumSimulationTime),
m_maximumSimulationTime(simulationTimeStep)
{
}
std::optional<float> ProjPredEngineAVX2::CalculatePitch(const Vector3& projOrigin, const Vector3& targetPos,
const float bulletGravity, const float v0, const float time)
{
if (time <= 0.0f)
return std::nullopt;
const Vector3 delta = targetPos - projOrigin;
const float dSqr = delta.x * delta.x + delta.y * delta.y;
const float h = delta.z;
const float term = h + 0.5f * bulletGravity * time * time;
const float requiredV0Sqr = (dSqr + term * term) / (time * time);
const float v0Sqr = v0 * v0;
if (requiredV0Sqr > v0Sqr + 1e-3f)
return std::nullopt;
if (dSqr == 0.0f)
return term >= 0.0f ? 90.0f : -90.0f;
const float d = std::sqrt(dSqr);
const float tanTheta = term / d;
return angles::RadiansToDegrees(std::atan(tanTheta));
}
} // namespace omath::projectile_prediction

View File

@@ -1,25 +1,18 @@
//
// Created by Vlad on 6/9/2024.
//
#include "omath/prediction/Engine.hpp"
#include "omath/projectile_prediction/ProjPredEngineLegacy.hpp"
#include <cmath>
#include <omath/Angles.hpp>
namespace omath::prediction
namespace omath::projectile_prediction
{
Engine::Engine(const float gravityConstant, const float simulationTimeStep,
const float maximumSimulationTime, const float distanceTolerance)
: m_gravityConstant(gravityConstant),
m_simulationTimeStep(simulationTimeStep),
m_maximumSimulationTime(maximumSimulationTime),
m_distanceTolerance(distanceTolerance)
ProjPredEngineLegacy::ProjPredEngineLegacy(const float gravityConstant, const float simulationTimeStep,
const float maximumSimulationTime, const float distanceTolerance) :
m_gravityConstant(gravityConstant), m_simulationTimeStep(simulationTimeStep),
m_maximumSimulationTime(maximumSimulationTime), m_distanceTolerance(distanceTolerance)
{
}
std::optional<Vector3> Engine::MaybeCalculateAimPoint(const Projectile &projectile, const Target &target) const
std::optional<Vector3> ProjPredEngineLegacy::MaybeCalculateAimPoint(const Projectile& projectile,
const Target& target) const
{
for (float time = 0.f; time < m_maximumSimulationTime; time += m_simulationTimeStep)
{
@@ -28,7 +21,7 @@ namespace omath::prediction
const auto projectilePitch = MaybeCalculateProjectileLaunchPitchAngle(projectile, predictedTargetPosition);
if (!projectilePitch.has_value()) [[unlikely]]
continue;
continue;
if (!IsProjectileReachedTarget(predictedTargetPosition, projectile, projectilePitch.value(), time))
continue;
@@ -41,8 +34,9 @@ namespace omath::prediction
return std::nullopt;
}
std::optional<float> Engine::MaybeCalculateProjectileLaunchPitchAngle(const Projectile &projectile,
const Vector3 &targetPosition) const
std::optional<float>
ProjPredEngineLegacy::MaybeCalculateProjectileLaunchPitchAngle(const Projectile& projectile,
const Vector3& targetPosition) const
{
const auto bulletGravity = m_gravityConstant * projectile.m_gravityScale;
const auto delta = targetPosition - projectile.m_origin;
@@ -51,11 +45,11 @@ namespace omath::prediction
const auto distance2dSqr = distance2d * distance2d;
const auto launchSpeedSqr = projectile.m_launchSpeed * projectile.m_launchSpeed;
float root = launchSpeedSqr * launchSpeedSqr - bulletGravity * (bulletGravity *
distance2dSqr + 2.0f * delta.z * launchSpeedSqr);
float root = launchSpeedSqr * launchSpeedSqr -
bulletGravity * (bulletGravity * distance2dSqr + 2.0f * delta.z * launchSpeedSqr);
if (root < 0.0f) [[unlikely]]
return std::nullopt;
return std::nullopt;
root = std::sqrt(root);
const float angle = std::atan((launchSpeedSqr - root) / (bulletGravity * distance2d));
@@ -63,12 +57,12 @@ namespace omath::prediction
return angles::RadiansToDegrees(angle);
}
bool Engine::IsProjectileReachedTarget(const Vector3 &targetPosition, const Projectile &projectile,
const float pitch, const float time) const
bool ProjPredEngineLegacy::IsProjectileReachedTarget(const Vector3& targetPosition, const Projectile& projectile,
const float pitch, const float time) const
{
const auto yaw = projectile.m_origin.ViewAngleTo(targetPosition).y;
const auto projectilePosition = projectile.PredictPosition(pitch, yaw, time, m_gravityConstant);
return projectilePosition.DistTo(targetPosition) <= m_distanceTolerance;
}
}
} // namespace omath::projectile_prediction

View File

@@ -2,11 +2,11 @@
// Created by Vlad on 6/9/2024.
//
#include "omath/prediction/Projectile.hpp"
#include <cmath>
#include "omath/projectile_prediction/Projectile.hpp"
#include <omath/engines/Source/Formulas.hpp>
namespace omath::prediction
namespace omath::projectile_prediction
{
Vector3 Projectile::PredictPosition(const float pitch, const float yaw, const float time, const float gravity) const
{

View File

@@ -2,7 +2,7 @@
// Created by Vlad on 6/9/2024.
//
#include "omath/prediction/Target.hpp"
#include "omath/projectile_prediction/Projectile.hpp"
namespace omath::prediction

View File

@@ -1,7 +1,6 @@
enable_testing()
project(unit-tests)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}")
include(GoogleTest)
add_executable(unit-tests
@@ -18,6 +17,7 @@ add_executable(unit-tests
general/UnitTestAngles.cpp
general/UnitTestViewAngles.cpp
general/UnitTestAngle.cpp
general/UnitTestTriangle.cpp
engines/UnitTestOpenGL.cpp
engines/UnitTestUnityEngine.cpp
@@ -25,6 +25,15 @@ add_executable(unit-tests
)
set_target_properties(unit-tests PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
UNITY_BUILD ON
UNITY_BUILD_BATCH_SIZE 20
CXX_STANDARD 23
CXX_STANDARD_REQUIRED ON)
target_link_libraries(unit-tests PRIVATE gtest gtest_main omath)
gtest_discover_tests(unit-tests)

View File

@@ -1,6 +1,6 @@
#include "gtest/gtest.h"
#include "omath/collision/LineTracer.hpp"
#include "omath/Triangle3d.hpp"
#include "omath/Triangle.hpp"
#include "omath/Vector3.hpp"
using namespace omath;
@@ -13,7 +13,7 @@ protected:
Vector3 vertex1{0.0f, 0.0f, 0.0f};
Vector3 vertex2{1.0f, 0.0f, 0.0f};
Vector3 vertex3{0.0f, 1.0f, 0.0f};
Triangle3d triangle{vertex1, vertex2, vertex3};
Triangle<Vector3> triangle{vertex1, vertex2, vertex3};
};
// Test that a ray intersecting the triangle returns false for CanTraceLine
@@ -71,7 +71,7 @@ TEST_F(LineTracerTest, TriangleFarBeyondRayEndPoint)
constexpr Ray ray{{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}};
// Define a triangle far beyond the ray's endpoint
const Triangle3d distantTriangle{
constexpr Triangle<Vector3> distantTriangle{
{1000.0f, 1000.0f, 1000.0f}, {1001.0f, 1000.0f, 1000.0f}, {1000.0f, 1001.0f, 1000.0f}
};

View File

@@ -1,15 +1,17 @@
#include <gtest/gtest.h>
#include <omath/prediction/Engine.hpp>
#include <omath/projectile_prediction/ProjPredEngineLegacy.hpp>
TEST(UnitTestPrediction, PredictionTest)
{
constexpr omath::prediction::Target target{
constexpr omath::projectile_prediction::Target target{
.m_origin = {100, 0, 90}, .m_velocity = {0, 0, 0}, .m_isAirborne = false};
constexpr omath::prediction::Projectile proj = {.m_origin = {3,2,1}, .m_launchSpeed = 5000, .m_gravityScale= 0.4};
const auto viewPoint = omath::prediction::Engine(400, 1.f / 1000.f, 50, 5.f).MaybeCalculateAimPoint(proj, target);
constexpr omath::projectile_prediction::Projectile proj = {
.m_origin = {3, 2, 1}, .m_launchSpeed = 5000, .m_gravityScale = 0.4};
const auto viewPoint =
omath::projectile_prediction::ProjPredEngineLegacy(400, 1.f / 1000.f, 50, 5.f).MaybeCalculateAimPoint(proj, target);
const auto [pitch, yaw, _] = proj.m_origin.ViewAngleTo(viewPoint.value()).AsTuple();
EXPECT_NEAR(42.547142, pitch, 0.0001f);
EXPECT_NEAR(-1.181189, yaw, 0.0001f);
}
EXPECT_NEAR(42.547142, pitch, 0.01f);
EXPECT_NEAR(-1.181189, yaw, 0.01f);
}

View File

@@ -0,0 +1,132 @@
//
// Created by Orange on 1/6/2025.
//
#include "omath/Triangle.hpp"
#include <gtest/gtest.h>
#include <omath/Vector3.hpp>
#include <cmath> // For std::sqrt, std::isinf, std::isnan
using namespace omath;
class UnitTestTriangle : public ::testing::Test
{
protected:
// Define some Triangles to use in tests
Triangle<Vector3> t1;
Triangle<Vector3> t2;
Triangle<Vector3> t3;
constexpr void SetUp() override
{
// Triangle with vertices (0, 0, 0), (1, 0, 0), (0, 1, 0)
t1 = Triangle<Vector3>(
Vector3(0.0f, 0.0f, 0.0f),
Vector3(1.0f, 0.0f, 0.0f),
Vector3(0.0f, 1.0f, 0.0f)
);
// Triangle with vertices (1, 2, 3), (4, 5, 6), (7, 8, 9)
t2 = Triangle<Vector3>(
Vector3(1.0f, 2.0f, 3.0f),
Vector3(4.0f, 5.0f, 6.0f),
Vector3(7.0f, 8.0f, 9.0f)
);
// An isosceles right triangle
t3 = Triangle<Vector3>(
Vector3(0.0f, 0.0f, 0.0f),
Vector3(2.0f, 0.0f, 0.0f),
Vector3(0.0f, 2.0f, 0.0f)
);
}
};
// Test constructor and vertices
TEST_F(UnitTestTriangle, Constructor)
{
constexpr Triangle<Vector3> t(
Vector3(1.0f, 2.0f, 3.0f),
Vector3(4.0f, 5.0f, 6.0f),
Vector3(7.0f, 8.0f, 9.0f)
);
EXPECT_FLOAT_EQ(t.m_vertex1.x, 1.0f);
EXPECT_FLOAT_EQ(t.m_vertex1.y, 2.0f);
EXPECT_FLOAT_EQ(t.m_vertex1.z, 3.0f);
EXPECT_FLOAT_EQ(t.m_vertex2.x, 4.0f);
EXPECT_FLOAT_EQ(t.m_vertex2.y, 5.0f);
EXPECT_FLOAT_EQ(t.m_vertex2.z, 6.0f);
EXPECT_FLOAT_EQ(t.m_vertex3.x, 7.0f);
EXPECT_FLOAT_EQ(t.m_vertex3.y, 8.0f);
EXPECT_FLOAT_EQ(t.m_vertex3.z, 9.0f);
}
// Test CalculateNormal
TEST_F(UnitTestTriangle, CalculateNormal)
{
// For t1, the normal should point in the +Z direction (0, 0, 1) or (0, 0, -1)
const Vector3 normal_t1 = t1.CalculateNormal();
// Check if it's normalized and pointed along Z (sign can differ, so use absolute check)
EXPECT_NEAR(std::fabs(normal_t1.z), 1.0f, 1e-5f);
EXPECT_NEAR(normal_t1.Length(), 1.0f, 1e-5f);
// For t3, we expect the normal to be along +Z as well
const Vector3 normal_t3 = t3.CalculateNormal();
EXPECT_NEAR(std::fabs(normal_t3.z), 1.0f, 1e-5f);
}
// Test side lengths
TEST_F(UnitTestTriangle, SideLengths)
{
// For t1 side lengths
EXPECT_FLOAT_EQ(t1.SideALength(), std::sqrt(1.0f)); // distance between (0,0,0) and (1,0,0)
EXPECT_FLOAT_EQ(t1.SideBLength(), std::sqrt(1.0f + 1.0f)); // distance between (4,5,6) & (7,8,9)... but we are testing t1, so let's be accurate:
// Actually, for t1: vertex2=(1,0,0), vertex3=(0,1,0)
// Dist between (0,1,0) and (1,0,0) = sqrt((1-0)^2 + (0-1)^2) = sqrt(1 + 1) = sqrt(2)
EXPECT_FLOAT_EQ(t1.SideBLength(), std::sqrt(2.0f));
// For t3, side a = distance between vertex1=(0,0,0) and vertex2=(2,0,0), which is 2
// side b = distance between vertex3=(0,2,0) and vertex2=(2,0,0), which is sqrt(2^2 + (-2)^2)= sqrt(8)= 2.828...
// We'll just check side a first:
EXPECT_FLOAT_EQ(t3.SideALength(), 2.0f);
// Then side b:
EXPECT_FLOAT_EQ(t3.SideBLength(), std::sqrt(8.0f));
}
// Test side vectors
TEST_F(UnitTestTriangle, SideVectors)
{
const Vector3 sideA_t1 = t1.SideAVector(); // m_vertex1 - m_vertex2
EXPECT_FLOAT_EQ(sideA_t1.x, 0.0f - 1.0f);
EXPECT_FLOAT_EQ(sideA_t1.y, 0.0f - 0.0f);
EXPECT_FLOAT_EQ(sideA_t1.z, 0.0f - 0.0f);
const Vector3 sideB_t1 = t1.SideBVector(); // m_vertex3 - m_vertex2
EXPECT_FLOAT_EQ(sideB_t1.x, 0.0f - 1.0f);
EXPECT_FLOAT_EQ(sideB_t1.y, 1.0f - 0.0f);
EXPECT_FLOAT_EQ(sideB_t1.z, 0.0f - 0.0f);
}
TEST_F(UnitTestTriangle, IsRectangular)
{
EXPECT_TRUE(Triangle<Vector3>({2,0,0}, {}, {0,2,0}).IsRectangular());
}
// Test midpoint
TEST_F(UnitTestTriangle, MidPoint)
{
// For t1, midpoint of (0,0,0), (1,0,0), (0,1,0)
const Vector3 mid1 = t1.MidPoint();
EXPECT_FLOAT_EQ(mid1.x, (0.0f + 1.0f + 0.0f) / 3.0f);
EXPECT_FLOAT_EQ(mid1.y, (0.0f + 0.0f + 1.0f) / 3.0f);
EXPECT_FLOAT_EQ(mid1.z, 0.0f);
// For t2, midpoint of (1,2,3), (4,5,6), (7,8,9)
const Vector3 mid2 = t2.MidPoint();
EXPECT_FLOAT_EQ(mid2.x, (1.0f + 4.0f + 7.0f) / 3.0f);
EXPECT_FLOAT_EQ(mid2.y, (2.0f + 5.0f + 8.0f) / 3.0f);
EXPECT_FLOAT_EQ(mid2.z, (3.0f + 6.0f + 9.0f) / 3.0f);
}

View File

@@ -387,6 +387,21 @@ TEST_F(UnitTestVector3, AsTuple)
EXPECT_FLOAT_EQ(std::get<2>(tuple), v1.z);
}
// Test AsTuple method
TEST_F(UnitTestVector3, AngleBeatween)
{
EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).AngleBetween({1, 0 ,0}).value().AsDegrees(), 90.0f);
EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).AngleBetween({0.0f, 0.0f, 1.0f}).value().AsDegrees(), 0.0f);
EXPECT_FALSE(Vector3(0.0f, 0.0f, 0.0f).AngleBetween({0.0f, 0.0f, 1.0f}).has_value());
}
TEST_F(UnitTestVector3, IsPerpendicular)
{
EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).IsPerpendicular({1, 0 ,0}), true);
EXPECT_EQ(Vector3(0.0f, 0.0f, 1.0f).IsPerpendicular({0.0f, 0.0f, 1.0f}), false);
EXPECT_FALSE(Vector3(0.0f, 0.0f, 0.0f).IsPerpendicular({0.0f, 0.0f, 1.0f}));
}
// Static assertions (compile-time checks)
static_assert(Vector3(1.0f, 2.0f, 3.0f).LengthSqr() == 14.0f, "LengthSqr should be 14");
static_assert(Vector3(1.0f, 2.0f, 3.0f).Dot(Vector3(4.0f, 5.0f, 6.0f)) == 32.0f, "Dot product should be 32");