nuclear@0: /************************************************************************************ nuclear@0: nuclear@0: PublicHeader: n/a nuclear@0: Filename : OVR_BitStream.h nuclear@0: Content : A generic serialization toolkit for packing data to a binary stream. nuclear@0: Created : June 10, 2014 nuclear@0: Authors : Kevin Jenkins nuclear@0: nuclear@0: Copyright : Copyright 2014 Oculus VR, LLC All Rights reserved. nuclear@0: nuclear@0: Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); nuclear@0: you may not use the Oculus VR Rift SDK except in compliance with the License, nuclear@0: which is provided at the time of installation or download, or which nuclear@0: otherwise accompanies this software in either electronic or hard copy form. nuclear@0: nuclear@0: You may obtain a copy of the License at nuclear@0: nuclear@0: http://www.oculusvr.com/licenses/LICENSE-3.2 nuclear@0: nuclear@0: Unless required by applicable law or agreed to in writing, the Oculus VR SDK nuclear@0: distributed under the License is distributed on an "AS IS" BASIS, nuclear@0: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. nuclear@0: See the License for the specific language governing permissions and nuclear@0: limitations under the License. nuclear@0: nuclear@0: ************************************************************************************/ nuclear@0: nuclear@0: #ifndef OVR_Bitstream_h nuclear@0: #define OVR_Bitstream_h nuclear@0: nuclear@0: #include nuclear@0: #include "../Kernel/OVR_Types.h" nuclear@0: #include "../Kernel/OVR_Std.h" nuclear@0: #include "../Kernel/OVR_String.h" nuclear@0: nuclear@0: namespace OVR { namespace Net { nuclear@0: nuclear@0: typedef uint32_t BitSize_t; nuclear@0: #define BITSTREAM_STACK_ALLOCATION_SIZE 256 nuclear@0: #define BITS_TO_BYTES(x) (((x)+7)>>3) nuclear@0: #define BYTES_TO_BITS(x) ((x)<<3) nuclear@0: nuclear@0: nuclear@0: //----------------------------------------------------------------------------- nuclear@0: // BitStream nuclear@0: nuclear@0: // Generic serialization class to binary stream nuclear@0: class BitStream : public NewOverrideBase nuclear@0: { nuclear@0: public: nuclear@0: /// Default Constructor nuclear@0: BitStream(); nuclear@0: nuclear@0: /// \brief Create the bitstream, with some number of bytes to immediately allocate. nuclear@0: /// \details There is no benefit to calling this, unless you know exactly how many bytes you need and it is greater than BITSTREAM_STACK_ALLOCATION_SIZE. nuclear@0: /// In that case all it does is save you one or more realloc calls. nuclear@0: /// \param[in] initialBytesToAllocate the number of bytes to pre-allocate. nuclear@0: BitStream( const unsigned int initialBytesToAllocate ); nuclear@0: nuclear@0: /// \brief Initialize the BitStream, immediately setting the data it contains to a predefined pointer. nuclear@0: /// \details Set \a _copyData to true if you want to make an internal copy of the data you are passing. Set it to false to just save a pointer to the data. nuclear@0: /// You shouldn't call Write functions with \a _copyData as false, as this will write to unallocated memory nuclear@0: /// 99% of the time you will use this function to cast Packet::data to a bitstream for reading, in which case you should write something as follows: nuclear@0: /// \code nuclear@0: /// RakNet::BitStream bs(packet->data, packet->length, false); nuclear@0: /// \endcode nuclear@0: /// \param[in] _data An array of bytes. nuclear@0: /// \param[in] lengthInBytes Size of the \a _data. nuclear@0: /// \param[in] _copyData true or false to make a copy of \a _data or not. nuclear@0: BitStream( char* _data, const unsigned int lengthInBytes, bool _copyData ); nuclear@0: nuclear@0: // Destructor nuclear@0: ~BitStream(); nuclear@0: nuclear@0: public: nuclear@0: /// Resets the bitstream for reuse. nuclear@0: void Reset( void ); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. nuclear@0: /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] inOutTemplateVar The value to write nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: template nuclear@0: bool Serialize(bool writeToBitstream, templateType &inOutTemplateVar); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. nuclear@0: /// \details If the current value is different from the last value nuclear@0: /// the current value will be written. Otherwise, a single bit will be written nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] inOutCurrentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: template nuclear@0: bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue); nuclear@0: nuclear@0: /// \brief Bidirectional version of SerializeDelta when you don't know what the last value is, or there is no last value. nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] inOutCurrentValue The current value to write nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: template nuclear@0: bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. nuclear@0: /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] inOutTemplateVar The value to write nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: template nuclear@0: bool SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. nuclear@0: /// \details If the current value is different from the last value nuclear@0: /// the current value will be written. Otherwise, a single bit will be written nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] inOutCurrentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: template nuclear@0: bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue); nuclear@0: nuclear@0: /// \brief Save as SerializeCompressedDelta(templateType ¤tValue, const templateType &lastValue) when we have an unknown second parameter nuclear@0: /// \return true on data read. False on insufficient data in bitstream nuclear@0: template nuclear@0: bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutTemplateVar); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize an array or casted stream or raw data. This does NOT do endian swapping. nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] inOutByteArray a byte buffer nuclear@0: /// \param[in] numberOfBytes the size of \a input in bytes nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: bool Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes ); nuclear@0: nuclear@0: /// \brief Serialize a float into 2 bytes, spanning the range between \a floatMin and \a floatMax nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] inOutFloat The float to write nuclear@0: /// \param[in] floatMin Predetermined minimum value of f nuclear@0: /// \param[in] floatMax Predetermined maximum value of f nuclear@0: bool SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax); nuclear@0: nuclear@0: /// Serialize one type casted to another (smaller) type, to save bandwidth nuclear@0: /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t nuclear@0: /// Example: int num=53; SerializeCasted(true, num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes) nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] value The value to serialize nuclear@0: template nuclear@0: bool SerializeCasted( bool writeToBitstream, sourceType &value ); nuclear@0: nuclear@0: /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range nuclear@0: /// Then serialize only those bits nuclear@0: /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] value Integer value to write, which should be between \a minimum and \a maximum nuclear@0: /// \param[in] minimum Minimum value of \a value nuclear@0: /// \param[in] maximum Maximum value of \a value nuclear@0: /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates nuclear@0: template nuclear@0: bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); nuclear@0: /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum nuclear@0: template nuclear@0: bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. nuclear@0: /// \details Will further compress y or z axis aligned vectors. nuclear@0: /// Accurate to 1/32767.5. nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12. nuclear@0: /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important. nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] w w nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each. nuclear@0: /// \details Use 6 bytes instead of 36 nuclear@0: /// Lossy, although the result is renormalized nuclear@0: /// \return true on success, false on failure. nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool SerializeOrthMatrix( nuclear@0: bool writeToBitstream, nuclear@0: templateType &m00, templateType &m01, templateType &m02, nuclear@0: templateType &m10, templateType &m11, templateType &m12, nuclear@0: templateType &m20, templateType &m21, templateType &m22 ); nuclear@0: nuclear@0: /// \brief Bidirectional serialize/deserialize numberToSerialize bits to/from the input. nuclear@0: /// \details Right aligned data means in the case of a partial byte, the bits are aligned nuclear@0: /// from the right (bit 0) rather than the left (as in the normal nuclear@0: /// internal representation) You would set this to true when nuclear@0: /// writing user data, and false when copying bitstream data, such nuclear@0: /// as writing one bitstream to another nuclear@0: /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data nuclear@0: /// \param[in] inOutByteArray The data nuclear@0: /// \param[in] numberOfBitsToSerialize The number of bits to write nuclear@0: /// \param[in] rightAlignedBits if true data will be right aligned nuclear@0: /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. nuclear@0: bool SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits = true ); nuclear@0: nuclear@0: /// \brief Write any integral type to a bitstream. nuclear@0: /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// \param[in] inTemplateVar The value to write nuclear@0: template nuclear@0: void Write(const templateType &inTemplateVar); nuclear@0: nuclear@0: /// \brief Write the dereferenced pointer to any integral type to a bitstream. nuclear@0: /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// \param[in] inTemplateVar The value to write nuclear@0: template nuclear@0: void WritePtr(templateType *inTemplateVar); nuclear@0: nuclear@0: /// \brief Write any integral type to a bitstream. nuclear@0: /// \details If the current value is different from the last value nuclear@0: /// the current value will be written. Otherwise, a single bit will be written nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against nuclear@0: template nuclear@0: void WriteDelta(const templateType ¤tValue, const templateType &lastValue); nuclear@0: nuclear@0: /// \brief WriteDelta when you don't know what the last value is, or there is no last value. nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: template nuclear@0: void WriteDelta(const templateType ¤tValue); nuclear@0: nuclear@0: /// \brief Write any integral type to a bitstream. nuclear@0: /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// \param[in] inTemplateVar The value to write nuclear@0: template nuclear@0: void WriteCompressed(const templateType &inTemplateVar); nuclear@0: nuclear@0: /// \brief Write any integral type to a bitstream. nuclear@0: /// \details If the current value is different from the last value nuclear@0: /// the current value will be written. Otherwise, a single bit will be written nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against nuclear@0: template nuclear@0: void WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue); nuclear@0: nuclear@0: /// \brief Save as WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) when we have an unknown second parameter nuclear@0: template nuclear@0: void WriteCompressedDelta(const templateType ¤tValue); nuclear@0: nuclear@0: /// \brief Read any integral type from a bitstream. nuclear@0: /// \details Define __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: /// \return true on success, false on failure. nuclear@0: template nuclear@0: bool Read(templateType &outTemplateVar); nuclear@0: nuclear@0: /// \brief Read any integral type from a bitstream. nuclear@0: /// \details If the written value differed from the value compared against in the write function, nuclear@0: /// var will be updated. Otherwise it will retain the current value. nuclear@0: /// ReadDelta is only valid from a previous call to WriteDelta nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: /// \return true on success, false on failure. nuclear@0: template nuclear@0: bool ReadDelta(templateType &outTemplateVar); nuclear@0: nuclear@0: /// \brief Read any integral type from a bitstream. nuclear@0: /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: /// \return true on success, false on failure. nuclear@0: template nuclear@0: bool ReadCompressed(templateType &outTemplateVar); nuclear@0: nuclear@0: /// \brief Read any integral type from a bitstream. nuclear@0: /// \details If the written value differed from the value compared against in the write function, nuclear@0: /// var will be updated. Otherwise it will retain the current value. nuclear@0: /// the current value will be updated. nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// ReadCompressedDelta is only valid from a previous call to WriteDelta nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: /// \return true on success, false on failure. nuclear@0: template nuclear@0: bool ReadCompressedDelta(templateType &outTemplateVar); nuclear@0: nuclear@0: /// \brief Read one bitstream to another. nuclear@0: /// \param[in] numberOfBits bits to read nuclear@0: /// \param bitStream the bitstream to read into from nuclear@0: /// \return true on success, false on failure. nuclear@0: bool Read( BitStream *bitStream, BitSize_t numberOfBits ); nuclear@0: bool Read( BitStream *bitStream ); nuclear@0: bool Read( BitStream &bitStream, BitSize_t numberOfBits ); nuclear@0: bool Read( BitStream &bitStream ); nuclear@0: nuclear@0: /// \brief Write an array or casted stream or raw data. This does NOT do endian swapping. nuclear@0: /// \param[in] inputByteArray a byte buffer nuclear@0: /// \param[in] numberOfBytes the size of \a input in bytes nuclear@0: void Write( const char* inputByteArray, const unsigned int numberOfBytes ); nuclear@0: nuclear@0: /// \brief Write one bitstream to another. nuclear@0: /// \param[in] numberOfBits bits to write nuclear@0: /// \param bitStream the bitstream to copy from nuclear@0: void Write( BitStream *bitStream, BitSize_t numberOfBits ); nuclear@0: void Write( BitStream *bitStream ); nuclear@0: void Write( BitStream &bitStream, BitSize_t numberOfBits ); nuclear@0: void Write( BitStream &bitStream );\ nuclear@0: nuclear@0: /// \brief Write a float into 2 bytes, spanning the range between \a floatMin and \a floatMax nuclear@0: /// \param[in] x The float to write nuclear@0: /// \param[in] floatMin Predetermined minimum value of f nuclear@0: /// \param[in] floatMax Predetermined maximum value of f nuclear@0: void WriteFloat16( float x, float floatMin, float floatMax ); nuclear@0: nuclear@0: /// Write one type serialized as another (smaller) type, to save bandwidth nuclear@0: /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t nuclear@0: /// Example: int num=53; WriteCasted(num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes) nuclear@0: /// \param[in] value The value to write nuclear@0: template nuclear@0: void WriteCasted( const sourceType &value ); nuclear@0: nuclear@0: /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range nuclear@0: /// Then write only those bits nuclear@0: /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program nuclear@0: /// \param[in] value Integer value to write, which should be between \a minimum and \a maximum nuclear@0: /// \param[in] minimum Minimum value of \a value nuclear@0: /// \param[in] maximum Maximum value of \a value nuclear@0: /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Read(). nuclear@0: template nuclear@0: void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); nuclear@0: /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum nuclear@0: template nuclear@0: void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); nuclear@0: nuclear@0: /// \brief Write a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. nuclear@0: /// \details Will further compress y or z axis aligned vectors. nuclear@0: /// Accurate to 1/32767.5. nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: template // templateType for this function must be a float or double nuclear@0: void WriteNormVector( templateType x, templateType y, templateType z ); nuclear@0: nuclear@0: /// \brief Write a vector, using 10 bytes instead of 12. nuclear@0: /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, nuclear@0: /// so only use if accuracy is not important. nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: template // templateType for this function must be a float or double nuclear@0: void WriteVector( templateType x, templateType y, templateType z ); nuclear@0: nuclear@0: /// \brief Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. nuclear@0: /// \param[in] w w nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: template // templateType for this function must be a float or double nuclear@0: void WriteNormQuat( templateType w, templateType x, templateType y, templateType z); nuclear@0: nuclear@0: /// \brief Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each. nuclear@0: /// \details Use 6 bytes instead of 36 nuclear@0: /// Lossy, although the result is renormalized nuclear@0: template // templateType for this function must be a float or double nuclear@0: void WriteOrthMatrix( nuclear@0: templateType m00, templateType m01, templateType m02, nuclear@0: templateType m10, templateType m11, templateType m12, nuclear@0: templateType m20, templateType m21, templateType m22 ); nuclear@0: nuclear@0: /// \brief Read an array or casted stream of byte. nuclear@0: /// \details The array is raw data. There is no automatic endian conversion with this function nuclear@0: /// \param[in] output The result byte array. It should be larger than @em numberOfBytes. nuclear@0: /// \param[in] numberOfBytes The number of byte to read nuclear@0: /// \return true on success false if there is some missing bytes. nuclear@0: bool Read( char* output, const unsigned int numberOfBytes ); nuclear@0: nuclear@0: /// \brief Read a float into 2 bytes, spanning the range between \a floatMin and \a floatMax nuclear@0: /// \param[in] outFloat The float to read nuclear@0: /// \param[in] floatMin Predetermined minimum value of f nuclear@0: /// \param[in] floatMax Predetermined maximum value of f nuclear@0: bool ReadFloat16( float &outFloat, float floatMin, float floatMax ); nuclear@0: nuclear@0: /// Read one type serialized to another (smaller) type, to save bandwidth nuclear@0: /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t nuclear@0: /// Example: int num; ReadCasted(num); would read 1 bytefrom the stream, and put the value in an integer nuclear@0: /// \param[in] value The value to write nuclear@0: template nuclear@0: bool ReadCasted( sourceType &value ); nuclear@0: nuclear@0: /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range nuclear@0: /// Then read only those bits nuclear@0: /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program nuclear@0: /// \param[in] value Integer value to read, which should be between \a minimum and \a maximum nuclear@0: /// \param[in] minimum Minimum value of \a value nuclear@0: /// \param[in] maximum Maximum value of \a value nuclear@0: /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Write(). nuclear@0: template nuclear@0: bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); nuclear@0: /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum nuclear@0: template nuclear@0: bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); nuclear@0: nuclear@0: /// \brief Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. nuclear@0: /// \details Will further compress y or z axis aligned vectors. nuclear@0: /// Accurate to 1/32767.5. nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: /// \return true on success, false on failure. nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool ReadNormVector( templateType &x, templateType &y, templateType &z ); nuclear@0: nuclear@0: /// \brief Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector. nuclear@0: /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, nuclear@0: /// so only use if accuracy is not important. nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: /// \return true on success, false on failure. nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool ReadVector( templateType &x, templateType &y, templateType &z ); nuclear@0: nuclear@0: /// \brief Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. nuclear@0: /// \param[in] w w nuclear@0: /// \param[in] x x nuclear@0: /// \param[in] y y nuclear@0: /// \param[in] z z nuclear@0: /// \return true on success, false on failure. nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z); nuclear@0: nuclear@0: /// \brief Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolatig the 4th. nuclear@0: /// \details Use 6 bytes instead of 36 nuclear@0: /// Lossy, although the result is renormalized nuclear@0: /// \return true on success, false on failure. nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool ReadOrthMatrix( nuclear@0: templateType &m00, templateType &m01, templateType &m02, nuclear@0: templateType &m10, templateType &m11, templateType &m12, nuclear@0: templateType &m20, templateType &m21, templateType &m22 ); nuclear@0: nuclear@0: /// \brief Sets the read pointer back to the beginning of your data. nuclear@0: void ResetReadPointer( void ); nuclear@0: nuclear@0: /// \brief Sets the write pointer back to the beginning of your data. nuclear@0: void ResetWritePointer( void ); nuclear@0: nuclear@0: /// \brief This is good to call when you are done with the stream to make nuclear@0: /// sure you didn't leave any data left over void nuclear@0: void AssertStreamEmpty( void ); nuclear@0: nuclear@0: /// \brief RAKNET_DEBUG_PRINTF the bits in the stream. Great for debugging. nuclear@0: void PrintBits( char *out ) const; nuclear@0: void PrintBits( void ) const; nuclear@0: void PrintHex( char *out ) const; nuclear@0: void PrintHex( void ) const; nuclear@0: nuclear@0: /// \brief Ignore data we don't intend to read nuclear@0: /// \param[in] numberOfBits The number of bits to ignore nuclear@0: void IgnoreBits( const BitSize_t numberOfBits ); nuclear@0: nuclear@0: /// \brief Ignore data we don't intend to read nuclear@0: /// \param[in] numberOfBits The number of bytes to ignore nuclear@0: void IgnoreBytes( const unsigned int numberOfBytes ); nuclear@0: nuclear@0: /// \brief Move the write pointer to a position on the array. nuclear@0: /// \param[in] offset the offset from the start of the array. nuclear@0: /// \attention nuclear@0: /// \details Dangerous if you don't know what you are doing! nuclear@0: /// For efficiency reasons you can only write mid-stream if your data is byte aligned. nuclear@0: void SetWriteOffset( const BitSize_t offset ); nuclear@0: nuclear@0: /// \brief Returns the length in bits of the stream nuclear@0: inline BitSize_t GetNumberOfBitsUsed( void ) const {return GetWriteOffset();} nuclear@0: inline BitSize_t GetWriteOffset( void ) const {return numberOfBitsUsed;} nuclear@0: nuclear@0: /// \brief Returns the length in bytes of the stream nuclear@0: inline BitSize_t GetNumberOfBytesUsed( void ) const {return BITS_TO_BYTES( numberOfBitsUsed );} nuclear@0: nuclear@0: /// \brief Returns the number of bits into the stream that we have read nuclear@0: inline BitSize_t GetReadOffset( void ) const {return readOffset;} nuclear@0: nuclear@0: /// \brief Sets the read bit index nuclear@0: void SetReadOffset( const BitSize_t newReadOffset ) {readOffset=newReadOffset;} nuclear@0: nuclear@0: /// \brief Returns the number of bits left in the stream that haven't been read nuclear@0: inline BitSize_t GetNumberOfUnreadBits( void ) const {return numberOfBitsUsed - readOffset;} nuclear@0: nuclear@0: /// \brief Makes a copy of the internal data for you \a _data will point to nuclear@0: /// the stream. Partial bytes are left aligned. nuclear@0: /// \param[out] _data The allocated copy of GetData() nuclear@0: /// \return The length in bits of the stream. nuclear@0: BitSize_t CopyData( unsigned char** _data ) const; nuclear@0: nuclear@0: /// \internal nuclear@0: /// Set the stream to some initial data. nuclear@0: void SetData( unsigned char *inByteArray ); nuclear@0: nuclear@0: /// Gets the data that BitStream is writing to / reading from. nuclear@0: /// Partial bytes are left aligned. nuclear@0: /// \return A pointer to the internal state nuclear@0: inline char* GetData( void ) const {return (char*) data;} nuclear@0: nuclear@0: /// \brief Write numberToWrite bits from the input source. nuclear@0: /// \details Right aligned data means in the case of a partial byte, the bits are aligned nuclear@0: /// from the right (bit 0) rather than the left (as in the normal nuclear@0: /// internal representation) You would set this to true when nuclear@0: /// writing user data, and false when copying bitstream data, such nuclear@0: /// as writing one bitstream to another. nuclear@0: /// \param[in] inByteArray The data nuclear@0: /// \param[in] numberOfBitsToWrite The number of bits to write nuclear@0: /// \param[in] rightAlignedBits if true data will be right aligned nuclear@0: void WriteBits( const unsigned char* inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits = true ); nuclear@0: nuclear@0: /// \brief Align the bitstream to the byte boundary and then write the nuclear@0: /// specified number of bits. nuclear@0: /// \details This is faster than WriteBits but nuclear@0: /// wastes the bits to do the alignment and requires you to call nuclear@0: /// ReadAlignedBits at the corresponding read position. nuclear@0: /// \param[in] inByteArray The data nuclear@0: /// \param[in] numberOfBytesToWrite The size of input. nuclear@0: void WriteAlignedBytes( const unsigned char *inByteArray, const unsigned int numberOfBytesToWrite ); nuclear@0: nuclear@0: // Endian swap bytes already in the bitstream nuclear@0: void EndianSwapBytes( int byteOffset, int length ); nuclear@0: nuclear@0: /// \brief Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite nuclear@0: /// \param[in] inByteArray The data nuclear@0: /// \param[in] inputLength The size of input. nuclear@0: /// \param[in] maxBytesToWrite Max bytes to write nuclear@0: void WriteAlignedBytesSafe( const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite ); nuclear@0: nuclear@0: /// \brief Read bits, starting at the next aligned bits. nuclear@0: /// \details Note that the modulus 8 starting offset of the sequence must be the same as nuclear@0: /// was used with WriteBits. This will be a problem with packet nuclear@0: /// coalescence unless you byte align the coalesced packets. nuclear@0: /// \param[in] inOutByteArray The byte array larger than @em numberOfBytesToRead nuclear@0: /// \param[in] numberOfBytesToRead The number of byte to read from the internal state nuclear@0: /// \return true if there is enough byte. nuclear@0: bool ReadAlignedBytes( unsigned char *inOutByteArray, const unsigned int numberOfBytesToRead ); nuclear@0: nuclear@0: /// \brief Reads what was written by WriteAlignedBytesSafe. nuclear@0: /// \param[in] inOutByteArray The data nuclear@0: /// \param[in] maxBytesToRead Maximum number of bytes to read nuclear@0: /// \return true on success, false on failure. nuclear@0: bool ReadAlignedBytesSafe( char *inOutByteArray, int &inputLength, const int maxBytesToRead ); nuclear@0: bool ReadAlignedBytesSafe( char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ); nuclear@0: nuclear@0: /// \brief Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to nuclear@0: /// \param[in] outByteArray outByteArray will be deleted if it is not a pointer to 0 nuclear@0: /// \return true on success, false on failure. nuclear@0: bool ReadAlignedBytesSafeAlloc( char **outByteArray, int &inputLength, const unsigned int maxBytesToRead ); nuclear@0: bool ReadAlignedBytesSafeAlloc( char **outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ); nuclear@0: nuclear@0: /// \brief Align the next write and/or read to a byte boundary. nuclear@0: /// \details This can be used to 'waste' bits to byte align for efficiency reasons It nuclear@0: /// can also be used to force coalesced bitstreams to start on byte nuclear@0: /// boundaries so so WriteAlignedBits and ReadAlignedBits both nuclear@0: /// calculate the same offset when aligning. nuclear@0: inline void AlignWriteToByteBoundary( void ) {numberOfBitsUsed += 8 - ( (( numberOfBitsUsed - 1 ) & 7) + 1 );} nuclear@0: nuclear@0: /// \brief Align the next write and/or read to a byte boundary. nuclear@0: /// \details This can be used to 'waste' bits to byte align for efficiency reasons It nuclear@0: /// can also be used to force coalesced bitstreams to start on byte nuclear@0: /// boundaries so so WriteAlignedBits and ReadAlignedBits both nuclear@0: /// calculate the same offset when aligning. nuclear@0: inline void AlignReadToByteBoundary( void ) {readOffset += 8 - ( (( readOffset - 1 ) & 7 ) + 1 );} nuclear@0: nuclear@0: /// \brief Read \a numberOfBitsToRead bits to the output source. nuclear@0: /// \details alignBitsToRight should be set to true to convert internal nuclear@0: /// bitstream data to userdata. It should be false if you used nuclear@0: /// WriteBits with rightAlignedBits false nuclear@0: /// \param[in] inOutByteArray The resulting bits array nuclear@0: /// \param[in] numberOfBitsToRead The number of bits to read nuclear@0: /// \param[in] alignBitsToRight if true bits will be right aligned. nuclear@0: /// \return true if there is enough bits to read nuclear@0: bool ReadBits( unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight = true ); nuclear@0: nuclear@0: /// \brief Write a 0 nuclear@0: void Write0( void ); nuclear@0: nuclear@0: /// \brief Write a 1 nuclear@0: void Write1( void ); nuclear@0: nuclear@0: /// \brief Reads 1 bit and returns true if that bit is 1 and false if it is 0. nuclear@0: bool ReadBit( void ); nuclear@0: nuclear@0: /// \brief If we used the constructor version with copy data off, this nuclear@0: /// *makes sure it is set to on and the data pointed to is copied. nuclear@0: void AssertCopyData( void ); nuclear@0: nuclear@0: /// \brief Use this if you pass a pointer copy to the constructor nuclear@0: /// *(_copyData==false) and want to overallocate to prevent nuclear@0: /// reallocation. nuclear@0: void SetNumberOfBitsAllocated( const BitSize_t lengthInBits ); nuclear@0: nuclear@0: /// \brief Reallocates (if necessary) in preparation of writing numberOfBitsToWrite nuclear@0: void AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite ); nuclear@0: nuclear@0: /// \internal nuclear@0: /// \return How many bits have been allocated internally nuclear@0: BitSize_t GetNumberOfBitsAllocated(void) const; nuclear@0: nuclear@0: /// Write zeros until the bitstream is filled up to \a bytes nuclear@0: void PadWithZeroToByteLength( unsigned int bytes ); nuclear@0: nuclear@0: /// Get the number of leading zeros for a number nuclear@0: /// \param[in] x Number to test nuclear@0: static int NumberOfLeadingZeroes( uint8_t x ); nuclear@0: static int NumberOfLeadingZeroes( uint16_t x ); nuclear@0: static int NumberOfLeadingZeroes( uint32_t x ); nuclear@0: static int NumberOfLeadingZeroes( uint64_t x ); nuclear@0: static int NumberOfLeadingZeroes( int8_t x ); nuclear@0: static int NumberOfLeadingZeroes( int16_t x ); nuclear@0: static int NumberOfLeadingZeroes( int32_t x ); nuclear@0: static int NumberOfLeadingZeroes( int64_t x ); nuclear@0: nuclear@0: /// \internal Unrolled inner loop, for when performance is critical nuclear@0: void WriteAlignedVar8(const char *inByteArray); nuclear@0: /// \internal Unrolled inner loop, for when performance is critical nuclear@0: bool ReadAlignedVar8(char *inOutByteArray); nuclear@0: /// \internal Unrolled inner loop, for when performance is critical nuclear@0: void WriteAlignedVar16(const char *inByteArray); nuclear@0: /// \internal Unrolled inner loop, for when performance is critical nuclear@0: bool ReadAlignedVar16(char *inOutByteArray); nuclear@0: /// \internal Unrolled inner loop, for when performance is critical nuclear@0: void WriteAlignedVar32(const char *inByteArray); nuclear@0: /// \internal Unrolled inner loop, for when performance is critical nuclear@0: bool ReadAlignedVar32(char *inOutByteArray); nuclear@0: nuclear@0: inline void Write(const char * const inStringVar) nuclear@0: { nuclear@0: uint16_t l = (uint16_t) OVR_strlen(inStringVar); nuclear@0: Write(l); nuclear@0: WriteAlignedBytes((const unsigned char*) inStringVar, (const unsigned int) l); nuclear@0: } nuclear@0: inline void Write(const unsigned char * const inTemplateVar) nuclear@0: { nuclear@0: Write((const char*)inTemplateVar); nuclear@0: } nuclear@0: inline void Write(char * const inTemplateVar) nuclear@0: { nuclear@0: Write((const char*)inTemplateVar); nuclear@0: } nuclear@0: inline void Write(unsigned char * const inTemplateVar) nuclear@0: { nuclear@0: Write((const char*)inTemplateVar); nuclear@0: } nuclear@0: nuclear@0: /// ---- Member function template specialization declarations ---- nuclear@0: // Used for VC7 nuclear@0: #if defined(OVR_CC_MSVC) && _MSC_VER == 1300 nuclear@0: /// Write a bool to a bitstream. nuclear@0: /// \param[in] var The value to write nuclear@0: template <> nuclear@0: void Write(const bool &var); nuclear@0: nuclear@0: /// Write a RakNetGUID to a bitsteam nuclear@0: /// \param[in] var The value to write nuclear@0: template <> nuclear@0: void Write(const RakNetGuid &var); nuclear@0: nuclear@0: /// Write a string to a bitstream nuclear@0: /// \param[in] var The value to write nuclear@0: template <> nuclear@0: void Write(const char* const &var); nuclear@0: template <> nuclear@0: void Write(const unsigned char* const &var); nuclear@0: template <> nuclear@0: void Write(char* const &var); nuclear@0: template <> nuclear@0: void Write(unsigned char* const &var); nuclear@0: template <> nuclear@0: void Write(const OVR::String &var); nuclear@0: nuclear@0: /// \brief Write a bool delta. nuclear@0: /// \details Same thing as just calling Write nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against nuclear@0: template <> nuclear@0: void WriteDelta(const bool ¤tValue, const bool &lastValue); nuclear@0: nuclear@0: template <> nuclear@0: void WriteCompressed(const bool &var); nuclear@0: nuclear@0: /// For values between -1 and 1 nuclear@0: template <> nuclear@0: void WriteCompressed(const float &var); nuclear@0: nuclear@0: /// For values between -1 and 1 nuclear@0: template <> nuclear@0: void WriteCompressed(const double &var); nuclear@0: nuclear@0: /// \brief Write a bool delta. nuclear@0: /// \details Same thing as just calling Write nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against nuclear@0: template <> nuclear@0: void WriteCompressedDelta(const bool ¤tValue, const bool &lastValue); nuclear@0: nuclear@0: /// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue) nuclear@0: /// when we have an unknown second bool nuclear@0: template <> nuclear@0: void WriteCompressedDelta(const bool ¤tValue); nuclear@0: nuclear@0: /// \brief Read a bool from a bitstream. nuclear@0: /// \param[in] var The value to read nuclear@0: /// \return true on success, false on failure. nuclear@0: template <> nuclear@0: bool Read(bool &var); nuclear@0: nuclear@0: /// \brief Read a String from a bitstream. nuclear@0: /// \param[in] var The value to read nuclear@0: /// \return true on success, false on failure. nuclear@0: template <> nuclear@0: bool Read(char *&var); nuclear@0: template <> nuclear@0: bool Read(wchar_t *&var); nuclear@0: template <> nuclear@0: bool Read(unsigned char *&var); nuclear@0: nuclear@0: /// \brief Read a bool from a bitstream. nuclear@0: /// \param[in] var The value to read nuclear@0: /// \return true on success, false on failure. nuclear@0: template <> nuclear@0: bool ReadDelta(bool &var); nuclear@0: nuclear@0: template <> nuclear@0: bool ReadCompressed(bool &var); nuclear@0: nuclear@0: template <> nuclear@0: bool ReadCompressed(float &var); nuclear@0: nuclear@0: /// For values between -1 and 1 nuclear@0: /// \return true on success, false on failure. nuclear@0: template <> nuclear@0: bool ReadCompressed(double &var); nuclear@0: nuclear@0: template <> nuclear@0: bool ReadCompressed(char* &var); nuclear@0: template <> nuclear@0: bool ReadCompressed(wchar_t* &var); nuclear@0: template <> nuclear@0: bool ReadCompressed(unsigned char *&var); nuclear@0: template <> nuclear@0: bool ReadCompressed(OVR::String &var); nuclear@0: nuclear@0: /// \brief Read a bool from a bitstream. nuclear@0: /// \param[in] var The value to read nuclear@0: /// \return true on success, false on failure. nuclear@0: template <> nuclear@0: bool ReadCompressedDelta(bool &var); nuclear@0: #endif nuclear@0: nuclear@0: inline static bool DoEndianSwap(void) { nuclear@0: #ifndef __BITSTREAM_NATIVE_END nuclear@0: return IsNetworkOrder()==false; nuclear@0: #else nuclear@0: return false; nuclear@0: #endif nuclear@0: } nuclear@0: inline static bool IsBigEndian(void) nuclear@0: { nuclear@0: return IsNetworkOrder(); nuclear@0: } nuclear@0: inline static bool IsNetworkOrder(void) {bool r = IsNetworkOrderInternal(); return r;} nuclear@0: // Not inline, won't compile on PC due to winsock include errors nuclear@0: static bool IsNetworkOrderInternal(void); nuclear@0: static void ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length); nuclear@0: static void ReverseBytesInPlace(unsigned char *inOutData,const unsigned int length); nuclear@0: nuclear@0: private: nuclear@0: nuclear@0: BitStream( const BitStream & /*invalid*/) : numberOfBitsUsed(0), numberOfBitsAllocated(0), readOffset(0),data(NULL), copyData(false) { nuclear@0: OVR_ASSERT(0); nuclear@0: } nuclear@0: nuclear@0: BitStream& operator = ( const BitStream& /*invalid*/ ) { nuclear@0: OVR_ASSERT(0); nuclear@0: static BitStream i; nuclear@0: return i; nuclear@0: } nuclear@0: nuclear@0: /// \brief Assume the input source points to a native type, compress and write it. nuclear@0: void WriteCompressed( const unsigned char* inByteArray, const unsigned int size, const bool unsignedData ); nuclear@0: nuclear@0: /// \brief Assume the input source points to a compressed native type. Decompress and read it. nuclear@0: bool ReadCompressed( unsigned char* inOutByteArray, const unsigned int size, const bool unsignedData ); nuclear@0: nuclear@0: nuclear@0: BitSize_t numberOfBitsUsed; nuclear@0: nuclear@0: BitSize_t numberOfBitsAllocated; nuclear@0: nuclear@0: BitSize_t readOffset; nuclear@0: nuclear@0: unsigned char *data; nuclear@0: nuclear@0: /// true if the internal buffer is copy of the data passed to the constructor nuclear@0: bool copyData; nuclear@0: nuclear@0: /// BitStreams that use less than BITSTREAM_STACK_ALLOCATION_SIZE use the stack, rather than the heap to store data. It switches over if BITSTREAM_STACK_ALLOCATION_SIZE is exceeded nuclear@0: unsigned char stackData[BITSTREAM_STACK_ALLOCATION_SIZE]; nuclear@0: }; nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::Serialize(bool writeToBitstream, templateType &inOutTemplateVar) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: Write(inOutTemplateVar); nuclear@0: else nuclear@0: return Read(inOutTemplateVar); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteDelta(inOutCurrentValue, lastValue); nuclear@0: else nuclear@0: return ReadDelta(inOutCurrentValue); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteDelta(inOutCurrentValue); nuclear@0: else nuclear@0: return ReadDelta(inOutCurrentValue); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteCompressed(inOutTemplateVar); nuclear@0: else nuclear@0: return ReadCompressed(inOutTemplateVar); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteCompressedDelta(inOutCurrentValue,lastValue); nuclear@0: else nuclear@0: return ReadCompressedDelta(inOutCurrentValue); nuclear@0: return true; nuclear@0: } nuclear@0: //Stoppedhere nuclear@0: template nuclear@0: inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteCompressedDelta(inOutCurrentValue); nuclear@0: else nuclear@0: return ReadCompressedDelta(inOutCurrentValue); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: inline bool BitStream::Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes ) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: Write(inOutByteArray, numberOfBytes); nuclear@0: else nuclear@0: return Read(inOutByteArray, numberOfBytes); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: bool BitStream::SerializeCasted( bool writeToBitstream, sourceType &value ) nuclear@0: { nuclear@0: if (writeToBitstream) WriteCasted(value); nuclear@0: else return ReadCasted(value); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange ) nuclear@0: { nuclear@0: int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); nuclear@0: return SerializeBitsFromIntegerRange(writeToBitstream,value,minimum,maximum,requiredBits,allowOutsideRange); nuclear@0: } nuclear@0: template nuclear@0: bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange ) nuclear@0: { nuclear@0: if (writeToBitstream) WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); nuclear@0: else return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteNormVector(x,y,z); nuclear@0: else nuclear@0: return ReadNormVector(x,y,z); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteVector(x,y,z); nuclear@0: else nuclear@0: return ReadVector(x,y,z); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteNormQuat(w,x,y,z); nuclear@0: else nuclear@0: return ReadNormQuat(w,x,y,z); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline bool BitStream::SerializeOrthMatrix( nuclear@0: bool writeToBitstream, nuclear@0: templateType &m00, templateType &m01, templateType &m02, nuclear@0: templateType &m10, templateType &m11, templateType &m12, nuclear@0: templateType &m20, templateType &m21, templateType &m22 ) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); nuclear@0: else nuclear@0: return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: inline bool BitStream::SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits ) nuclear@0: { nuclear@0: if (writeToBitstream) nuclear@0: WriteBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits); nuclear@0: else nuclear@0: return ReadBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits); nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline void BitStream::Write(const templateType &inTemplateVar) nuclear@0: { nuclear@0: #ifdef OVR_CC_MSVC nuclear@0: #pragma warning(disable:4127) // conditional expression is constant nuclear@0: #endif nuclear@0: if (sizeof(inTemplateVar)==1) nuclear@0: WriteBits( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true ); nuclear@0: else nuclear@0: { nuclear@0: #ifndef __BITSTREAM_NATIVE_END nuclear@0: if (DoEndianSwap()) nuclear@0: { nuclear@0: unsigned char output[sizeof(templateType)]; nuclear@0: ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType)); nuclear@0: WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ); nuclear@0: } nuclear@0: else nuclear@0: #endif nuclear@0: WriteBits( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true ); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: inline void BitStream::WritePtr(templateType *inTemplateVar) nuclear@0: { nuclear@0: #ifdef OVR_CC_MSVC nuclear@0: #pragma warning(disable:4127) // conditional expression is constant nuclear@0: #endif nuclear@0: if (sizeof(templateType)==1) nuclear@0: WriteBits( ( unsigned char* ) inTemplateVar, sizeof( templateType ) * 8, true ); nuclear@0: else nuclear@0: { nuclear@0: #ifndef __BITSTREAM_NATIVE_END nuclear@0: if (DoEndianSwap()) nuclear@0: { nuclear@0: unsigned char output[sizeof(templateType)]; nuclear@0: ReverseBytes((unsigned char*) inTemplateVar, output, sizeof(templateType)); nuclear@0: WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ); nuclear@0: } nuclear@0: else nuclear@0: #endif nuclear@0: WriteBits( ( unsigned char* ) inTemplateVar, sizeof(templateType) * 8, true ); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: /// \brief Write a bool to a bitstream. nuclear@0: /// \param[in] inTemplateVar The value to write nuclear@0: template <> nuclear@0: inline void BitStream::Write(const bool &inTemplateVar) nuclear@0: { nuclear@0: if ( inTemplateVar ) nuclear@0: Write1(); nuclear@0: else nuclear@0: Write0(); nuclear@0: } nuclear@0: nuclear@0: nuclear@0: /// \brief Write a string to a bitstream. nuclear@0: /// \param[in] var The value to write nuclear@0: template <> nuclear@0: inline void BitStream::Write(const OVR::String &inTemplateVar) nuclear@0: { nuclear@0: uint16_t l = (uint16_t) inTemplateVar.GetLength(); nuclear@0: Write(l); nuclear@0: WriteAlignedBytes((const unsigned char*) inTemplateVar.ToCStr(), (const unsigned int) l); nuclear@0: } nuclear@0: template <> nuclear@0: inline void BitStream::Write(const char * const &inStringVar) nuclear@0: { nuclear@0: uint16_t l = (uint16_t) strlen(inStringVar); nuclear@0: Write(l); nuclear@0: WriteAlignedBytes((const unsigned char*) inStringVar, (const unsigned int) l); nuclear@0: } nuclear@0: template <> nuclear@0: inline void BitStream::Write(const unsigned char * const &inTemplateVar) nuclear@0: { nuclear@0: Write((const char*)inTemplateVar); nuclear@0: } nuclear@0: template <> nuclear@0: inline void BitStream::Write(char * const &inTemplateVar) nuclear@0: { nuclear@0: Write((const char*)inTemplateVar); nuclear@0: } nuclear@0: template <> nuclear@0: inline void BitStream::Write(unsigned char * const &inTemplateVar) nuclear@0: { nuclear@0: Write((const char*)inTemplateVar); nuclear@0: } nuclear@0: nuclear@0: /// \brief Write any integral type to a bitstream. nuclear@0: /// \details If the current value is different from the last value nuclear@0: /// the current value will be written. Otherwise, a single bit will be written nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against nuclear@0: template nuclear@0: inline void BitStream::WriteDelta(const templateType ¤tValue, const templateType &lastValue) nuclear@0: { nuclear@0: if (currentValue==lastValue) nuclear@0: { nuclear@0: Write(false); nuclear@0: } nuclear@0: else nuclear@0: { nuclear@0: Write(true); nuclear@0: Write(currentValue); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: /// \brief Write a bool delta. Same thing as just calling Write nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against nuclear@0: template <> nuclear@0: inline void BitStream::WriteDelta(const bool ¤tValue, const bool &lastValue) nuclear@0: { nuclear@0: (void) lastValue; nuclear@0: nuclear@0: Write(currentValue); nuclear@0: } nuclear@0: nuclear@0: /// \brief WriteDelta when you don't know what the last value is, or there is no last value. nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: template nuclear@0: inline void BitStream::WriteDelta(const templateType ¤tValue) nuclear@0: { nuclear@0: Write(true); nuclear@0: Write(currentValue); nuclear@0: } nuclear@0: nuclear@0: /// \brief Write any integral type to a bitstream. nuclear@0: /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// \param[in] inTemplateVar The value to write nuclear@0: template nuclear@0: inline void BitStream::WriteCompressed(const templateType &inTemplateVar) nuclear@0: { nuclear@0: #ifdef OVR_CC_MSVC nuclear@0: #pragma warning(disable:4127) // conditional expression is constant nuclear@0: #endif nuclear@0: if (sizeof(inTemplateVar)==1) nuclear@0: WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true ); nuclear@0: else nuclear@0: { nuclear@0: #ifndef __BITSTREAM_NATIVE_END nuclear@0: #ifdef OVR_CC_MSVC nuclear@0: #pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'uint16_t', possible loss of data nuclear@0: #endif nuclear@0: nuclear@0: if (DoEndianSwap()) nuclear@0: { nuclear@0: unsigned char output[sizeof(templateType)]; nuclear@0: ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType)); nuclear@0: WriteCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true ); nuclear@0: } nuclear@0: else nuclear@0: #endif nuclear@0: WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true ); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: template <> nuclear@0: inline void BitStream::WriteCompressed(const bool &inTemplateVar) nuclear@0: { nuclear@0: Write(inTemplateVar); nuclear@0: } nuclear@0: nuclear@0: /// For values between -1 and 1 nuclear@0: template <> nuclear@0: inline void BitStream::WriteCompressed(const float &inTemplateVar) nuclear@0: { nuclear@0: OVR_ASSERT(inTemplateVar > -1.01f && inTemplateVar < 1.01f); nuclear@0: float varCopy=inTemplateVar; nuclear@0: if (varCopy < -1.0f) nuclear@0: varCopy=-1.0f; nuclear@0: if (varCopy > 1.0f) nuclear@0: varCopy=1.0f; nuclear@0: Write((uint16_t)((varCopy+1.0f)*32767.5f)); nuclear@0: } nuclear@0: nuclear@0: /// For values between -1 and 1 nuclear@0: template <> nuclear@0: inline void BitStream::WriteCompressed(const double &inTemplateVar) nuclear@0: { nuclear@0: OVR_ASSERT(inTemplateVar > -1.01 && inTemplateVar < 1.01); nuclear@0: double varCopy=inTemplateVar; nuclear@0: if (varCopy < -1.0f) nuclear@0: varCopy=-1.0f; nuclear@0: if (varCopy > 1.0f) nuclear@0: varCopy=1.0f; nuclear@0: Write((uint32_t)((varCopy+1.0)*2147483648.0)); nuclear@0: } nuclear@0: nuclear@0: /// \brief Write any integral type to a bitstream. nuclear@0: /// \details If the current value is different from the last value nuclear@0: /// the current value will be written. Otherwise, a single bit will be written nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against nuclear@0: template nuclear@0: inline void BitStream::WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) nuclear@0: { nuclear@0: if (currentValue==lastValue) nuclear@0: { nuclear@0: Write(false); nuclear@0: } nuclear@0: else nuclear@0: { nuclear@0: Write(true); nuclear@0: WriteCompressed(currentValue); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: /// \brief Write a bool delta. Same thing as just calling Write nuclear@0: /// \param[in] currentValue The current value to write nuclear@0: /// \param[in] lastValue The last value to compare against nuclear@0: template <> nuclear@0: inline void BitStream::WriteCompressedDelta(const bool ¤tValue, const bool &lastValue) nuclear@0: { nuclear@0: (void) lastValue; nuclear@0: nuclear@0: Write(currentValue); nuclear@0: } nuclear@0: nuclear@0: /// \brief Save as WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) nuclear@0: /// when we have an unknown second parameter nuclear@0: template nuclear@0: inline void BitStream::WriteCompressedDelta(const templateType ¤tValue) nuclear@0: { nuclear@0: Write(true); nuclear@0: WriteCompressed(currentValue); nuclear@0: } nuclear@0: nuclear@0: /// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue) nuclear@0: /// when we have an unknown second bool nuclear@0: template <> nuclear@0: inline void BitStream::WriteCompressedDelta(const bool ¤tValue) nuclear@0: { nuclear@0: Write(currentValue); nuclear@0: } nuclear@0: nuclear@0: /// \brief Read any integral type from a bitstream. Define __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: template nuclear@0: inline bool BitStream::Read(templateType &outTemplateVar) nuclear@0: { nuclear@0: #ifdef OVR_CC_MSVC nuclear@0: #pragma warning(disable:4127) // conditional expression is constant nuclear@0: #endif nuclear@0: if (sizeof(outTemplateVar)==1) nuclear@0: return ReadBits( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true ); nuclear@0: else nuclear@0: { nuclear@0: #ifndef __BITSTREAM_NATIVE_END nuclear@0: #ifdef OVR_CC_MSVC nuclear@0: #pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'uint16_t', possible loss of data nuclear@0: #endif nuclear@0: if (DoEndianSwap()) nuclear@0: { nuclear@0: unsigned char output[sizeof(templateType)]; nuclear@0: if (ReadBits( ( unsigned char* ) output, sizeof(templateType) * 8, true )) nuclear@0: { nuclear@0: ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType)); nuclear@0: return true; nuclear@0: } nuclear@0: return false; nuclear@0: } nuclear@0: else nuclear@0: #endif nuclear@0: return ReadBits( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true ); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: /// \brief Read a bool from a bitstream. nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: template <> nuclear@0: inline bool BitStream::Read(bool &outTemplateVar) nuclear@0: { nuclear@0: if ( readOffset + 1 > numberOfBitsUsed ) nuclear@0: return false; nuclear@0: nuclear@0: if ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) // Is it faster to just write it out here? nuclear@0: outTemplateVar = true; nuclear@0: else nuclear@0: outTemplateVar = false; nuclear@0: nuclear@0: // Has to be on a different line for Mac nuclear@0: readOffset++; nuclear@0: nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template <> nuclear@0: inline bool BitStream::Read(OVR::String &outTemplateVar) nuclear@0: { nuclear@0: bool b; nuclear@0: uint16_t l; nuclear@0: b=Read(l); nuclear@0: if (b && l>0) nuclear@0: { nuclear@0: AlignReadToByteBoundary(); nuclear@0: outTemplateVar.AssignString((const char*) (data + ( readOffset >> 3 )), (size_t) l); nuclear@0: IgnoreBytes(l); nuclear@0: } nuclear@0: else nuclear@0: { nuclear@0: AlignReadToByteBoundary(); nuclear@0: } nuclear@0: return b; nuclear@0: } nuclear@0: template <> nuclear@0: inline bool BitStream::Read(char *&varString) nuclear@0: { nuclear@0: bool b; nuclear@0: uint16_t l; nuclear@0: b=Read(l); nuclear@0: if (b && l>0) nuclear@0: { nuclear@0: memcpy(varString, data + ( readOffset >> 3 ), l); nuclear@0: IgnoreBytes(l); nuclear@0: } nuclear@0: else nuclear@0: { nuclear@0: AlignReadToByteBoundary(); nuclear@0: } nuclear@0: return b; nuclear@0: } nuclear@0: template <> nuclear@0: inline bool BitStream::Read(unsigned char *&varString) nuclear@0: { nuclear@0: bool b; nuclear@0: uint16_t l; nuclear@0: b=Read(l); nuclear@0: if (b && l>0) nuclear@0: { nuclear@0: memcpy(varString, data + ( readOffset >> 3 ), l); nuclear@0: IgnoreBytes(l); nuclear@0: } nuclear@0: else nuclear@0: { nuclear@0: AlignReadToByteBoundary(); nuclear@0: } nuclear@0: return b; nuclear@0: } nuclear@0: nuclear@0: /// \brief Read any integral type from a bitstream. nuclear@0: /// \details If the written value differed from the value compared against in the write function, nuclear@0: /// var will be updated. Otherwise it will retain the current value. nuclear@0: /// ReadDelta is only valid from a previous call to WriteDelta nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: template nuclear@0: inline bool BitStream::ReadDelta(templateType &outTemplateVar) nuclear@0: { nuclear@0: bool dataWritten; nuclear@0: bool success; nuclear@0: success=Read(dataWritten); nuclear@0: if (dataWritten) nuclear@0: success=Read(outTemplateVar); nuclear@0: return success; nuclear@0: } nuclear@0: nuclear@0: /// \brief Read a bool from a bitstream. nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: template <> nuclear@0: inline bool BitStream::ReadDelta(bool &outTemplateVar) nuclear@0: { nuclear@0: return Read(outTemplateVar); nuclear@0: } nuclear@0: nuclear@0: /// \brief Read any integral type from a bitstream. nuclear@0: /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: template nuclear@0: inline bool BitStream::ReadCompressed(templateType &outTemplateVar) nuclear@0: { nuclear@0: #ifdef OVR_CC_MSVC nuclear@0: #pragma warning(disable:4127) // conditional expression is constant nuclear@0: #endif nuclear@0: if (sizeof(outTemplateVar)==1) nuclear@0: return ReadCompressed( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true ); nuclear@0: else nuclear@0: { nuclear@0: #ifndef __BITSTREAM_NATIVE_END nuclear@0: if (DoEndianSwap()) nuclear@0: { nuclear@0: unsigned char output[sizeof(templateType)]; nuclear@0: if (ReadCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true )) nuclear@0: { nuclear@0: ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType)); nuclear@0: return true; nuclear@0: } nuclear@0: return false; nuclear@0: } nuclear@0: else nuclear@0: #endif nuclear@0: return ReadCompressed( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true ); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: template <> nuclear@0: inline bool BitStream::ReadCompressed(bool &outTemplateVar) nuclear@0: { nuclear@0: return Read(outTemplateVar); nuclear@0: } nuclear@0: nuclear@0: /// For values between -1 and 1 nuclear@0: template <> nuclear@0: inline bool BitStream::ReadCompressed(float &outTemplateVar) nuclear@0: { nuclear@0: uint16_t compressedFloat; nuclear@0: if (Read(compressedFloat)) nuclear@0: { nuclear@0: outTemplateVar = ((float)compressedFloat / 32767.5f - 1.0f); nuclear@0: return true; nuclear@0: } nuclear@0: return false; nuclear@0: } nuclear@0: nuclear@0: /// For values between -1 and 1 nuclear@0: template <> nuclear@0: inline bool BitStream::ReadCompressed(double &outTemplateVar) nuclear@0: { nuclear@0: uint32_t compressedFloat; nuclear@0: if (Read(compressedFloat)) nuclear@0: { nuclear@0: outTemplateVar = ((double)compressedFloat / 2147483648.0 - 1.0); nuclear@0: return true; nuclear@0: } nuclear@0: return false; nuclear@0: } nuclear@0: nuclear@0: /// \brief Read any integral type from a bitstream. nuclear@0: /// \details If the written value differed from the value compared against in the write function, nuclear@0: /// var will be updated. Otherwise it will retain the current value. nuclear@0: /// the current value will be updated. nuclear@0: /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. nuclear@0: /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type nuclear@0: /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte nuclear@0: /// ReadCompressedDelta is only valid from a previous call to WriteDelta nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: template nuclear@0: inline bool BitStream::ReadCompressedDelta(templateType &outTemplateVar) nuclear@0: { nuclear@0: bool dataWritten; nuclear@0: bool success; nuclear@0: success=Read(dataWritten); nuclear@0: if (dataWritten) nuclear@0: success=ReadCompressed(outTemplateVar); nuclear@0: return success; nuclear@0: } nuclear@0: nuclear@0: /// \brief Read a bool from a bitstream. nuclear@0: /// \param[in] outTemplateVar The value to read nuclear@0: template <> nuclear@0: inline bool BitStream::ReadCompressedDelta(bool &outTemplateVar) nuclear@0: { nuclear@0: return Read(outTemplateVar); nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: void BitStream::WriteCasted( const sourceType &value ) nuclear@0: { nuclear@0: destinationType val = (destinationType) value; nuclear@0: Write(val); nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, bool allowOutsideRange ) nuclear@0: { nuclear@0: int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); nuclear@0: WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); nuclear@0: } nuclear@0: template nuclear@0: void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, const int requiredBits, bool allowOutsideRange ) nuclear@0: { nuclear@0: OVR_ASSERT(maximum>=minimum); nuclear@0: OVR_ASSERT(allowOutsideRange==true || (value>=minimum && value<=maximum)); nuclear@0: if (allowOutsideRange) nuclear@0: { nuclear@0: if (valuemaximum) nuclear@0: { nuclear@0: Write(true); nuclear@0: Write(value); nuclear@0: return; nuclear@0: } nuclear@0: Write(false); nuclear@0: } nuclear@0: templateType valueOffMin=value-minimum; nuclear@0: if (IsBigEndian()==true) nuclear@0: { nuclear@0: unsigned char output[sizeof(templateType)]; nuclear@0: ReverseBytes((unsigned char*)&valueOffMin, output, sizeof(templateType)); nuclear@0: WriteBits(output,requiredBits); nuclear@0: } nuclear@0: else nuclear@0: { nuclear@0: WriteBits((unsigned char*) &valueOffMin,requiredBits); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: template // templateType for this function must be a float or double nuclear@0: void BitStream::WriteNormVector( templateType x, templateType y, templateType z ) nuclear@0: { nuclear@0: #ifdef _DEBUG nuclear@0: OVR_ASSERT(x <= 1.01 && y <= 1.01 && z <= 1.01 && x >= -1.01 && y >= -1.01 && z >= -1.01); nuclear@0: #endif nuclear@0: nuclear@0: WriteFloat16((float)x,-1.0f,1.0f); nuclear@0: WriteFloat16((float)y,-1.0f,1.0f); nuclear@0: WriteFloat16((float)z,-1.0f,1.0f); nuclear@0: } nuclear@0: nuclear@0: template // templateType for this function must be a float or double nuclear@0: void BitStream::WriteVector( templateType x, templateType y, templateType z ) nuclear@0: { nuclear@0: templateType magnitude = sqrt(x * x + y * y + z * z); nuclear@0: Write((float)magnitude); nuclear@0: if (magnitude > 0.00001f) nuclear@0: { nuclear@0: WriteCompressed((float)(x/magnitude)); nuclear@0: WriteCompressed((float)(y/magnitude)); nuclear@0: WriteCompressed((float)(z/magnitude)); nuclear@0: // Write((uint16_t)((x/magnitude+1.0f)*32767.5f)); nuclear@0: // Write((uint16_t)((y/magnitude+1.0f)*32767.5f)); nuclear@0: // Write((uint16_t)((z/magnitude+1.0f)*32767.5f)); nuclear@0: } nuclear@0: } nuclear@0: nuclear@0: template // templateType for this function must be a float or double nuclear@0: void BitStream::WriteNormQuat( templateType w, templateType x, templateType y, templateType z) nuclear@0: { nuclear@0: Write((bool)(w<0.0)); nuclear@0: Write((bool)(x<0.0)); nuclear@0: Write((bool)(y<0.0)); nuclear@0: Write((bool)(z<0.0)); nuclear@0: Write((uint16_t)(fabs(x)*65535.0)); nuclear@0: Write((uint16_t)(fabs(y)*65535.0)); nuclear@0: Write((uint16_t)(fabs(z)*65535.0)); nuclear@0: // Leave out w and calculate it on the target nuclear@0: } nuclear@0: nuclear@0: template // templateType for this function must be a float or double nuclear@0: void BitStream::WriteOrthMatrix( nuclear@0: templateType m00, templateType m01, templateType m02, nuclear@0: templateType m10, templateType m11, templateType m12, nuclear@0: templateType m20, templateType m21, templateType m22 ) nuclear@0: { nuclear@0: nuclear@0: double qw; nuclear@0: double qx; nuclear@0: double qy; nuclear@0: double qz; nuclear@0: nuclear@0: // Convert matrix to quat nuclear@0: // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ nuclear@0: float sum; nuclear@0: sum = 1 + m00 + m11 + m22; nuclear@0: if (sum < 0.0f) sum=0.0f; nuclear@0: qw = sqrt( sum ) / 2; nuclear@0: sum = 1 + m00 - m11 - m22; nuclear@0: if (sum < 0.0f) sum=0.0f; nuclear@0: qx = sqrt( sum ) / 2; nuclear@0: sum = 1 - m00 + m11 - m22; nuclear@0: if (sum < 0.0f) sum=0.0f; nuclear@0: qy = sqrt( sum ) / 2; nuclear@0: sum = 1 - m00 - m11 + m22; nuclear@0: if (sum < 0.0f) sum=0.0f; nuclear@0: qz = sqrt( sum ) / 2; nuclear@0: if (qw < 0.0) qw=0.0; nuclear@0: if (qx < 0.0) qx=0.0; nuclear@0: if (qy < 0.0) qy=0.0; nuclear@0: if (qz < 0.0) qz=0.0; nuclear@0: #ifdef OVR_OS_WIN32 nuclear@0: qx = _copysign( (double) qx, (double) (m21 - m12) ); nuclear@0: qy = _copysign( (double) qy, (double) (m02 - m20) ); nuclear@0: qz = _copysign( (double) qz, (double) (m10 - m01) ); nuclear@0: #else nuclear@0: qx = copysign( (double) qx, (double) (m21 - m12) ); nuclear@0: qy = copysign( (double) qy, (double) (m02 - m20) ); nuclear@0: qz = copysign( (double) qz, (double) (m10 - m01) ); nuclear@0: #endif nuclear@0: nuclear@0: WriteNormQuat(qw,qx,qy,qz); nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: bool BitStream::ReadCasted( sourceType &value ) nuclear@0: { nuclear@0: serializationType val; nuclear@0: bool success = Read(val); nuclear@0: value=(sourceType) val; nuclear@0: return success; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange ) nuclear@0: { nuclear@0: int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); nuclear@0: return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); nuclear@0: } nuclear@0: template nuclear@0: bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange ) nuclear@0: { nuclear@0: OVR_ASSERT_AND_UNUSED(maximum>=minimum, maximum); nuclear@0: if (allowOutsideRange) nuclear@0: { nuclear@0: bool isOutsideRange; nuclear@0: Read(isOutsideRange); nuclear@0: if (isOutsideRange) nuclear@0: return Read(value); nuclear@0: } nuclear@0: unsigned char output[sizeof(templateType)]; nuclear@0: memset(output,0,sizeof(output)); nuclear@0: bool success = ReadBits(output,requiredBits); nuclear@0: if (success) nuclear@0: { nuclear@0: if (IsBigEndian()==true) nuclear@0: ReverseBytesInPlace(output,sizeof(output)); nuclear@0: memcpy(&value,output,sizeof(output)); nuclear@0: nuclear@0: value+=minimum; nuclear@0: } nuclear@0: nuclear@0: return success; nuclear@0: } nuclear@0: nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool BitStream::ReadNormVector( templateType &x, templateType &y, templateType &z ) nuclear@0: { nuclear@0: float xIn,yIn,zIn; nuclear@0: ReadFloat16(xIn,-1.0f,1.0f); nuclear@0: ReadFloat16(yIn,-1.0f,1.0f); nuclear@0: ReadFloat16(zIn,-1.0f,1.0f); nuclear@0: x=xIn; nuclear@0: y=yIn; nuclear@0: z=zIn; nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool BitStream::ReadVector( templateType &x, templateType &y, templateType &z ) nuclear@0: { nuclear@0: float magnitude; nuclear@0: //uint16_t sx,sy,sz; nuclear@0: if (!Read(magnitude)) nuclear@0: return false; nuclear@0: if (magnitude>0.00001f) nuclear@0: { nuclear@0: // Read(sx); nuclear@0: // Read(sy); nuclear@0: // if (!Read(sz)) nuclear@0: // return false; nuclear@0: // x=((float)sx / 32767.5f - 1.0f) * magnitude; nuclear@0: // y=((float)sy / 32767.5f - 1.0f) * magnitude; nuclear@0: // z=((float)sz / 32767.5f - 1.0f) * magnitude; nuclear@0: float cx=0.0f,cy=0.0f,cz=0.0f; nuclear@0: ReadCompressed(cx); nuclear@0: ReadCompressed(cy); nuclear@0: if (!ReadCompressed(cz)) nuclear@0: return false; nuclear@0: x=cx; nuclear@0: y=cy; nuclear@0: z=cz; nuclear@0: x*=magnitude; nuclear@0: y*=magnitude; nuclear@0: z*=magnitude; nuclear@0: } nuclear@0: else nuclear@0: { nuclear@0: x=0.0; nuclear@0: y=0.0; nuclear@0: z=0.0; nuclear@0: } nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool BitStream::ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z) nuclear@0: { nuclear@0: bool cwNeg=false, cxNeg=false, cyNeg=false, czNeg=false; nuclear@0: uint16_t cx,cy,cz; nuclear@0: Read(cwNeg); nuclear@0: Read(cxNeg); nuclear@0: Read(cyNeg); nuclear@0: Read(czNeg); nuclear@0: Read(cx); nuclear@0: Read(cy); nuclear@0: if (!Read(cz)) nuclear@0: return false; nuclear@0: nuclear@0: // Calculate w from x,y,z nuclear@0: x=(templateType)(cx/65535.0); nuclear@0: y=(templateType)(cy/65535.0); nuclear@0: z=(templateType)(cz/65535.0); nuclear@0: if (cxNeg) x=-x; nuclear@0: if (cyNeg) y=-y; nuclear@0: if (czNeg) z=-z; nuclear@0: float difference = 1.0f - x*x - y*y - z*z; nuclear@0: if (difference < 0.0f) nuclear@0: difference=0.0f; nuclear@0: w = (templateType)(sqrt(difference)); nuclear@0: if (cwNeg) nuclear@0: w=-w; nuclear@0: nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template // templateType for this function must be a float or double nuclear@0: bool BitStream::ReadOrthMatrix( nuclear@0: templateType &m00, templateType &m01, templateType &m02, nuclear@0: templateType &m10, templateType &m11, templateType &m12, nuclear@0: templateType &m20, templateType &m21, templateType &m22 ) nuclear@0: { nuclear@0: float qw,qx,qy,qz; nuclear@0: if (!ReadNormQuat(qw,qx,qy,qz)) nuclear@0: return false; nuclear@0: nuclear@0: // Quat to orthogonal rotation matrix nuclear@0: // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm nuclear@0: double sqw = (double)qw*(double)qw; nuclear@0: double sqx = (double)qx*(double)qx; nuclear@0: double sqy = (double)qy*(double)qy; nuclear@0: double sqz = (double)qz*(double)qz; nuclear@0: m00 = (templateType)(sqx - sqy - sqz + sqw); // since sqw + sqx + sqy + sqz =1 nuclear@0: m11 = (templateType)(-sqx + sqy - sqz + sqw); nuclear@0: m22 = (templateType)(-sqx - sqy + sqz + sqw); nuclear@0: nuclear@0: double tmp1 = (double)qx*(double)qy; nuclear@0: double tmp2 = (double)qz*(double)qw; nuclear@0: m10 = (templateType)(2.0 * (tmp1 + tmp2)); nuclear@0: m01 = (templateType)(2.0 * (tmp1 - tmp2)); nuclear@0: nuclear@0: tmp1 = (double)qx*(double)qz; nuclear@0: tmp2 = (double)qy*(double)qw; nuclear@0: m20 =(templateType)(2.0 * (tmp1 - tmp2)); nuclear@0: m02 = (templateType)(2.0 * (tmp1 + tmp2)); nuclear@0: tmp1 = (double)qy*(double)qz; nuclear@0: tmp2 = (double)qx*(double)qw; nuclear@0: m21 = (templateType)(2.0 * (tmp1 + tmp2)); nuclear@0: m12 = (templateType)(2.0 * (tmp1 - tmp2)); nuclear@0: nuclear@0: return true; nuclear@0: } nuclear@0: nuclear@0: template nuclear@0: BitStream& operator<<(BitStream& out, templateType& c) nuclear@0: { nuclear@0: out.Write(c); nuclear@0: return out; nuclear@0: } nuclear@0: template nuclear@0: BitStream& operator>>(BitStream& in, templateType& c) nuclear@0: { nuclear@0: bool success = in.Read(c); nuclear@0: (void)success; nuclear@0: nuclear@0: OVR_ASSERT(success); nuclear@0: return in; nuclear@0: } nuclear@0: nuclear@0: nuclear@0: }} // OVR::Net nuclear@0: nuclear@0: #endif