I'm trying to write a 3D model exporter addon for Blender in Python and need some help.
The spec of the 3D format uses some compression on the vertices, there is a vertex buffer that contains vertices as 32bit floats. When this is compressed it is stored as 16bit float or half precision float.
I've seen lots of examples online of code in C to convert a 32bit float to 16bit float but not much luck with Python.
I was wondering if anyone here can help?
So far I've attempted to take some of the code here conversion of float and put it into Python. I managed to get this working and testing with a triangulated cube rendered only half the cube.
F16_EXPONENT_BITS = 0x1F
F16_EXPONENT_SHIFT = 10
F16_EXPONENT_BIAS = 15
F16_MANTISSA_BITS = 0x3ff
F16_MANTISSA_SHIFT = (23 - F16_EXPONENT_SHIFT)
F16_MAX_EXPONENT = (F16_EXPONENT_BITS << F16_EXPONENT_SHIFT)
for byte in self._byteBuffer:
f32 = int(byte)
f16 = 0
sign = (f32 >> 16) & 0x8000
exponent = ((f32 >> 23) & 0xff) - 127
mantissa = f32 & 0x007fffff
if exponent == 128:
f16 = sign | F16_MAX_EXPONENT
if mantissa:
f16 |= (mantissa & F16_MANTISSA_BITS)
elif exponent > 15:
f16 = sign | F16_MAX_EXPONENT
elif exponent > -15:
exponent += F16_EXPONENT_BIAS
mantissa >>= F16_MANTISSA_SHIFT
f16 = sign | exponent << F16_EXPONENT_SHIFT | mantissa
else:
f16 = sign
file.write(struct.pack(">H",f16))