Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
Half.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
11#pragma once
12
13#include "./Types.hpp"
14
15#include <cstring>
16
17namespace esengine {
18
25inline u16 packHalf(f32 value) {
26 u32 bits = 0;
27 std::memcpy(&bits, &value, sizeof(bits));
28 const u32 sign = (bits >> 16) & 0x8000u;
29 const i32 exponent = static_cast<i32>((bits >> 23) & 0xFFu) - 127 + 15;
30 const u32 mantissa = bits & 0x7FFFFFu;
31 if (exponent >= 31) return static_cast<u16>(sign | 0x7C00u);
32 if (exponent <= 0) {
33 if (exponent < -10) return static_cast<u16>(sign);
34 const u32 shift = static_cast<u32>(14 - exponent);
35 const u32 subnormal = (mantissa | 0x800000u) >> shift;
36 return static_cast<u16>(sign | (subnormal + ((mantissa >> (shift - 1)) & 1u)));
37 }
38 const u32 half = sign | (static_cast<u32>(exponent) << 10) | (mantissa >> 13);
39 return static_cast<u16>(half + ((mantissa & 0x1FFFu) > 0x1000u ? 1u : 0u));
40}
41
42} // namespace esengine
Core type definitions and utilities for ESEngine.
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
u16 packHalf(f32 value)
IEEE binary32 to binary16.
Definition Half.hpp:25
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
float f32
32-bit floating point
Definition Types.hpp:59