53 lines
1.5 KiB
C++
53 lines
1.5 KiB
C++
#pragma once
|
|
#include <memory>
|
|
#include <string>
|
|
#include <stdexcept>
|
|
#include <random>
|
|
namespace KapitanGame {
|
|
namespace Utils {
|
|
|
|
template<typename ... Args>
|
|
std::string StringFormat(const std::string& format, Args ... args)
|
|
{
|
|
const int sizeS = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
|
|
if (sizeS <= 0) { throw std::runtime_error("Error during formatting."); }
|
|
const auto size = static_cast<size_t>(sizeS);
|
|
const auto buf = std::make_unique<char[]>(size);
|
|
std::snprintf(buf.get(), size, format.c_str(), args ...);
|
|
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
|
|
}
|
|
template <class T>
|
|
constexpr const T& Clamp01(const T& x)
|
|
{
|
|
return Clamp(x, 0.f, 1.f);
|
|
}
|
|
template <class T>
|
|
constexpr const T& Clamp(const T& x, const T& min, const T& max)
|
|
{
|
|
return std::max(std::min(max, x), min);
|
|
}
|
|
template <class T>
|
|
constexpr const T& Lerp(const T& a, const T& b, const float& t)
|
|
{
|
|
return a + (b - a) * t;
|
|
}
|
|
|
|
static std::default_random_engine make_default_random_engine()
|
|
{
|
|
// This gets a source of actual, honest-to-god randomness
|
|
std::random_device source;
|
|
|
|
// Here, we fill an array of random data from the source
|
|
unsigned int random_data[10];
|
|
for (auto& elem : random_data) {
|
|
elem = source();
|
|
}
|
|
|
|
// this creates the random seed sequence out of the random data
|
|
std::seed_seq seq(random_data + 0, random_data + 10);
|
|
return std::default_random_engine{ seq };
|
|
}
|
|
|
|
double RandomNumber();
|
|
}
|
|
} |