From 32da717a55ce29d109d5a8850623f5106412f09c Mon Sep 17 00:00:00 2001 From: lisyarus Date: Sun, 26 Feb 2023 23:46:06 +0300 Subject: [PATCH] Add float -> normalized (un)signed 8/16-bit converters to gfx --- libs/gfx/include/psemek/gfx/attribs.hpp | 56 +++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/libs/gfx/include/psemek/gfx/attribs.hpp b/libs/gfx/include/psemek/gfx/attribs.hpp index 8ae48a37..ea0c9d0a 100644 --- a/libs/gfx/include/psemek/gfx/attribs.hpp +++ b/libs/gfx/include/psemek/gfx/attribs.hpp @@ -445,4 +445,60 @@ namespace psemek::gfx } } + inline std::int8_t to_signed_8bit(float x) + { + return static_cast(geom::clamp((0.5f * x + 0.5f) * 255.f - 128.f, {-128.f, 127.f})); + } + + inline std::uint8_t to_unsigned_8bit(float x) + { + return static_cast(geom::clamp(x * 255.f, {0.f, 255.f})); + } + + inline std::int16_t to_signed_16bit(float x) + { + return static_cast(geom::clamp((0.5f * x + 0.5f) * 65535.f - 32768.f, {-32768.f, 32767.f})); + } + + inline std::uint16_t to_unsigned_16bit(float x) + { + return static_cast(geom::clamp(x * 65535.f, {0.f, 65535.f})); + } + + template + geom::vector to_signed_8bit(geom::vector const & v) + { + geom::vector result; + for (std::size_t i = 0; i < D; ++i) + result[i] = to_signed_8bit(v[i]); + return result; + } + + template + geom::vector to_unsigned_8bit(geom::vector const & v) + { + geom::vector result; + for (std::size_t i = 0; i < D; ++i) + result[i] = to_unsigned_8bit(v[i]); + return result; + } + + template + geom::vector to_signed_16bit(geom::vector const & v) + { + geom::vector result; + for (std::size_t i = 0; i < D; ++i) + result[i] = to_signed_16bit(v[i]); + return result; + } + + template + geom::vector to_unsigned_16bit(geom::vector const & v) + { + geom::vector result; + for (std::size_t i = 0; i < D; ++i) + result[i] = to_unsigned_16bit(v[i]); + return result; + } + }