libcruft-util/vector.cpp

103 lines
2.6 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2011 Danny Robson <danny@nerdcruft.net>
*/
#include "vector.hpp"
#include "debug/assert.hpp"
#include "std.hpp"
#include <cmath>
using cruft::vector;
using cruft::vector3f;
using cruft::vector3d;
///////////////////////////////////////////////////////////////////////////////
template <typename T>
vector<2,T>
cruft::polar_to_cartesian (vector<2,T> v)
{
return cruft::vector<2,T> {
v[0] * std::cos (v[1]),
v[0] * std::sin (v[1])
};
}
//-----------------------------------------------------------------------------
template <typename T>
vector<2,T>
cruft::cartesian_to_polar (vector<2,T> v)
{
return cruft::vector<2,T> {
std::hypot (v.x, v.y),
std::atan2 (v.y, v.x)
};
}
///////////////////////////////////////////////////////////////////////////////
template <typename T>
vector<3,T>
cruft::from_euler (vector<2,T> euler)
{
return normalised (cruft::vector<3,T> {
std::sin (euler.x) * std::cos (euler.y),
std::cos (euler.x),
-std::sin (euler.x) * std::sin (euler.y),
});
}
template cruft::vector3f cruft::from_euler (cruft::vector2f);
template cruft::vector3d cruft::from_euler (cruft::vector2d);
//-----------------------------------------------------------------------------
template <typename T>
vector<2,T>
cruft::to_euler (vector<3,T> vec)
{
CHECK (is_normalised (vec));
return {
std::acos (vec.y),
-std::atan2 (vec.z, vec.x),
};
}
template cruft::vector2f cruft::to_euler (cruft::vector3f);
template cruft::vector2d cruft::to_euler (cruft::vector3d);
///////////////////////////////////////////////////////////////////////////////
template <size_t S, typename T>
struct cruft::debug::validator<vector<S,T>> {
static bool
is_valid (vector<S,T> const& val)
{
return std::all_of (
std::begin (val.data),
std::end (val.data),
[] (auto v) { return !std::isnan (v); }
);
}
};
///////////////////////////////////////////////////////////////////////////////
#define INSTANTIATE_S_T(S,T) \
template struct cruft::vector<(S),T>; \
template struct cruft::debug::validator<vector<(S),T>>;
MAP_CRUFT_COORD_PARAMS(INSTANTIATE_S_T)
//-----------------------------------------------------------------------------
template vector<2,float> cruft::polar_to_cartesian (cruft::vector<2,float>);
template vector<2,float> cruft::cartesian_to_polar (cruft::vector<2,float>);