blob: fea54ac87ef18ad53ca2e672f9ed58822606524e [file] [log] [blame]
John Bauman89401822014-05-06 15:04:28 -04001// SwiftShader Software Renderer
2//
3// Copyright(c) 2005-2011 TransGaming Inc.
4//
5// All rights reserved. No part of this software may be copied, distributed, transmitted,
6// transcribed, stored in a retrieval system, translated into any human or computer
7// language by any means, or disclosed to third parties without the explicit written
8// agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express
9// or implied, including but not limited to any patent rights, are granted to you.
10//
11
12#include "Half.hpp"
13
14namespace sw
15{
16 half::half(float fp32)
17 {
18 unsigned int fp32i = *(unsigned int*)&fp32;
19 unsigned int sign = (fp32i & 0x80000000) >> 16;
20 unsigned int abs = fp32i & 0x7FFFFFFF;
21
22 if(abs > 0x47FFEFFF) // Infinity
23 {
24 fp16i = sign | 0x7FFF;
25 }
26 else if(abs < 0x38800000) // Denormal
27 {
28 unsigned int mantissa = (abs & 0x007FFFFF) | 0x00800000;
29 int e = 113 - (abs >> 23);
30
31 if(e < 24)
32 {
33 abs = mantissa >> e;
34 }
35 else
36 {
37 abs = 0;
38 }
39
40 fp16i = sign | (abs + 0x00000FFF + ((abs >> 13) & 1)) >> 13;
41 }
42 else
43 {
44 fp16i = sign | (abs + 0xC8000000 + 0x00000FFF + ((abs >> 13) & 1)) >> 13;
45 }
46 }
47
48 half::operator float() const
49 {
50 unsigned int fp32i;
51
52 int s = (fp16i >> 15) & 0x00000001;
53 int e = (fp16i >> 10) & 0x0000001F;
54 int m = fp16i & 0x000003FF;
55
56 if(e == 0)
57 {
58 if(m == 0)
59 {
60 fp32i = s << 31;
61
62 return (float&)fp32i;
63 }
64 else
65 {
66 while(!(m & 0x00000400))
67 {
68 m <<= 1;
69 e -= 1;
70 }
71
72 e += 1;
73 m &= ~0x00000400;
74 }
75 }
76
77 e = e + (127 - 15);
78 m = m << 13;
79
80 fp32i = (s << 31) | (e << 23) | m;
81
82 return (float&)fp32i;
83 }
84
85 half &half::operator=(half h)
86 {
87 fp16i = h.fp16i;
88
89 return *this;
90 }
91
92
93 half &half::operator=(float f)
94 {
95 *this = half(f);
96
97 return *this;
98 }
99}