blob: 2c0b8707709ca5873e86d34790c231771a302e32 [file] [log] [blame]
Chia-I Wud3e77a62014-08-18 14:39:31 +08001/*
2 * XGL
3 *
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.
23 */
24
25#include "icd-utils.h"
26
27/* stolen from Mesa */
28uint16_t u_float_to_half(float f)
29{
30 union fi {
31 float f;
32 uint32_t ui;
33 };
34
35 uint32_t sign_mask = 0x80000000;
36 uint32_t round_mask = ~0xfff;
37 uint32_t f32inf = 0xff << 23;
38 uint32_t f16inf = 0x1f << 23;
39 uint32_t sign;
40 union fi magic;
41 union fi f32;
42 uint16_t f16;
43
44 magic.ui = 0xf << 23;
45
46 f32.f = f;
47
48 /* Sign */
49 sign = f32.ui & sign_mask;
50 f32.ui ^= sign;
51
52 if (f32.ui == f32inf) {
53 /* Inf */
54 f16 = 0x7c00;
55 } else if (f32.ui > f32inf) {
56 /* NaN */
57 f16 = 0x7e00;
58 } else {
59 /* Number */
60 f32.ui &= round_mask;
61 f32.f *= magic.f;
62 f32.ui -= round_mask;
63
64 /*
65 * Clamp to max finite value if overflowed.
66 * OpenGL has completely undefined rounding behavior for float to
67 * half-float conversions, and this matches what is mandated for float
68 * to fp11/fp10, which recommend round-to-nearest-finite too.
69 * (d3d10 is deeply unhappy about flushing such values to infinity, and
70 * while it also mandates round-to-zero it doesn't care nearly as much
71 * about that.)
72 */
73 if (f32.ui > f16inf)
74 f32.ui = f16inf - 1;
75
76 f16 = f32.ui >> 13;
77 }
78
79 /* Sign */
80 f16 |= sign >> 16;
81
82 return f16;
83}