From 416a71f744c8071c94f0257cb7d3a35b2593f051 Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Mon, 21 Aug 2023 07:05:34 +0200 Subject: [PATCH] Spectre/Math: Adding Vector2UnProject() --- include/Spectre/Math/Math.h | 5 +++++ source/Math/Math.cpp | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/include/Spectre/Math/Math.h b/include/Spectre/Math/Math.h index 34f725c..24839f9 100644 --- a/include/Spectre/Math/Math.h +++ b/include/Spectre/Math/Math.h @@ -2,6 +2,8 @@ #ifndef SPECTRE_MATH_MATH_H #define SPECTRE_MATH_MATH_H +#include "Transform.h" +#include "Vector4.h" #include "Vector3.h" #include "Vector2.h" #include "Matrix4.h" @@ -32,6 +34,9 @@ namespace sp { namespace math float bottom, float top, float zNear = -1.0f, float zFar = 1.0f); + // + Vector2f Vector2UnProject(Vector2f point, Transform InverseMVP, Vector4u screen); + // Create a 2D rotation matrix. (rotation around Z-axis) Matrix4f rotation(float theta); diff --git a/source/Math/Math.cpp b/source/Math/Math.cpp index 2be138a..5f984c7 100644 --- a/source/Math/Math.cpp +++ b/source/Math/Math.cpp @@ -1,5 +1,6 @@ #include +#include #include namespace sp { namespace math @@ -47,6 +48,16 @@ namespace sp { namespace math ); } + Vector2f Vector2UnProject(Vector2f point, Transform InverseMVP, Vector4u screen) { + + // Convert to NDC from pixel cordinates first using screen size + point.x = -1.f + 2.f * (point.x - screen.x) / screen.z; + point.y = 1.f - 2.f * (point.y - screen.y) / screen.w; + + // Then transform the point using the inverse MVP matrix. + return InverseMVP.transformPoint(point); + } + Matrix4f rotation(float theta) { float r = deg2rad(theta);