blob: 9abf4c76bf28814b3c72b826086933e4c412a308 [file] [log] [blame]
Chia-I Wud3e77a62014-08-18 14:39:31 +08001/*
Courtney Goeltzenleuchter9cc421e2015-04-08 15:36:08 -06002 * Vulkan
Chia-I Wud3e77a62014-08-18 14:39:31 +08003 *
4 * Copyright (C) 2014 LunarG, Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
Chia-I Wu44e42362014-09-02 08:32:09 +080023 *
24 * Authors:
25 * Chia-I Wu <olv@lunarg.com>
Chia-I Wud3e77a62014-08-18 14:39:31 +080026 */
27
28#include "icd-utils.h"
29
30/* stolen from Mesa */
31uint16_t u_float_to_half(float f)
32{
33 union fi {
34 float f;
35 uint32_t ui;
36 };
37
38 uint32_t sign_mask = 0x80000000;
39 uint32_t round_mask = ~0xfff;
40 uint32_t f32inf = 0xff << 23;
41 uint32_t f16inf = 0x1f << 23;
42 uint32_t sign;
43 union fi magic;
44 union fi f32;
45 uint16_t f16;
46
47 magic.ui = 0xf << 23;
48
49 f32.f = f;
50
51 /* Sign */
52 sign = f32.ui & sign_mask;
53 f32.ui ^= sign;
54
55 if (f32.ui == f32inf) {
56 /* Inf */
57 f16 = 0x7c00;
58 } else if (f32.ui > f32inf) {
59 /* NaN */
60 f16 = 0x7e00;
61 } else {
62 /* Number */
63 f32.ui &= round_mask;
64 f32.f *= magic.f;
65 f32.ui -= round_mask;
66
67 /*
68 * Clamp to max finite value if overflowed.
69 * OpenGL has completely undefined rounding behavior for float to
70 * half-float conversions, and this matches what is mandated for float
71 * to fp11/fp10, which recommend round-to-nearest-finite too.
72 * (d3d10 is deeply unhappy about flushing such values to infinity, and
73 * while it also mandates round-to-zero it doesn't care nearly as much
74 * about that.)
75 */
76 if (f32.ui > f16inf)
77 f32.ui = f16inf - 1;
78
79 f16 = f32.ui >> 13;
80 }
81
82 /* Sign */
83 f16 |= sign >> 16;
84
85 return f16;
86}