atcprintf() is now fully re-entrant, meaning translations can be used from inside translations
1 //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
7 //=============================================================================//
10 #include "coordsize.h"
12 #include "mathlib/math_base.h"
13 #include "vstdlib/strtools.h"
16 // FIXME: Can't use this until we get multithreaded allocations in tier0 working for tools
17 // This is used by VVIS and fails to link
18 // NOTE: This must be the last file included!!!
19 //#include "tier0/memdbgon.h"
22 // mandatory ... wary of above comment and isolating, tier0 is built as MT though
23 #include "tier0/memdbgon.h"
26 static BitBufErrorHandler g_BitBufErrorHandler = 0;
29 void InternalBitBufErrorHandler( BitBufErrorType errorType, const char *pDebugName )
31 if ( g_BitBufErrorHandler )
32 g_BitBufErrorHandler( errorType, pDebugName );
36 void SetBitBufErrorHandler( BitBufErrorHandler fn )
38 g_BitBufErrorHandler = fn;
42 // #define BB_PROFILING
45 // Precalculated bit masks for WriteUBitLong. Using these tables instead of
46 // doing the calculations gives a 33% speedup in WriteUBitLong.
47 unsigned long g_BitWriteMasks[32][33];
50 unsigned long g_ExtraMasks[32];
52 class CBitWriteMasksInit
57 for( unsigned int startbit=0; startbit < 32; startbit++ )
59 for( unsigned int nBitsLeft=0; nBitsLeft < 33; nBitsLeft++ )
61 unsigned int endbit = startbit + nBitsLeft;
62 g_BitWriteMasks[startbit][nBitsLeft] = (1 << startbit) - 1;
64 g_BitWriteMasks[startbit][nBitsLeft] |= ~((1 << endbit) - 1);
68 for ( unsigned int maskBit=0; maskBit < 32; maskBit++ )
69 g_ExtraMasks[maskBit] = (1 << maskBit) - 1;
72 CBitWriteMasksInit g_BitWriteMasksInit;
75 // ---------------------------------------------------------------------------------------- //
77 // ---------------------------------------------------------------------------------------- //
83 m_nDataBits = -1; // set to -1 so we generate overflow on any operation
86 m_bAssertOnOverflow = true;
90 bf_write::bf_write( const char *pDebugName, void *pData, int nBytes, int nBits )
92 m_bAssertOnOverflow = true;
93 m_pDebugName = pDebugName;
94 StartWriting( pData, nBytes, 0, nBits );
97 bf_write::bf_write( void *pData, int nBytes, int nBits )
99 m_bAssertOnOverflow = true;
100 StartWriting( pData, nBytes, 0, nBits );
103 void bf_write::StartWriting( void *pData, int nBytes, int iStartBit, int nBits )
105 // Make sure it's dword aligned and padded.
106 Assert( (nBytes % 4) == 0 );
107 Assert(((unsigned long)pData & 3) == 0);
109 m_pData = (unsigned char*)pData;
110 m_nDataBytes = nBytes;
114 m_nDataBits = nBytes << 3;
118 Assert( nBits <= nBytes*8 );
122 m_iCurBit = iStartBit;
126 void bf_write::Reset()
133 void bf_write::SetAssertOnOverflow( bool bAssert )
135 m_bAssertOnOverflow = bAssert;
139 const char* bf_write::GetDebugName()
145 void bf_write::SetDebugName( const char *pDebugName )
147 m_pDebugName = pDebugName;
151 void bf_write::SeekToBit( int bitPos )
157 // Sign bit comes first
158 void bf_write::WriteSBitLong( int data, int numbits )
160 // Do we have a valid # of bits to encode with?
161 Assert( numbits >= 1 );
163 // Note: it does this wierdness here so it's bit-compatible with regular integer data in the buffer.
164 // (Some old code writes direct integers right into the buffer).
170 // Make sure it doesn't overflow.
174 Assert( data >= -(1 << (numbits-1)) );
178 Assert( data < (1 << (numbits-1)) );
183 WriteUBitLong( (unsigned int)(0x80000000 + data), numbits - 1, false );
188 WriteUBitLong((unsigned int)data, numbits - 1);
193 // writes an unsigned integer with variable bit length
194 void bf_write::WriteUBitVar( unsigned int data )
196 unsigned int bits = 0;
197 unsigned int base = 0;
199 while (data > (base<<1))
205 // how many bits do we use
207 WriteUBitLong( 0, bits );
214 WriteUBitLong( data - base , bits );
217 void bf_write::WriteBitLong(unsigned int data, int numbits, bool bSigned)
220 WriteSBitLong((int)data, numbits);
222 WriteUBitLong(data, numbits);
225 bool bf_write::WriteBits(const void *pInData, int nBits)
227 #if defined( BB_PROFILING )
228 VPROF( "bf_write::WriteBits" );
231 unsigned char *pOut = (unsigned char*)pInData;
232 int nBitsLeft = nBits;
234 if((m_iCurBit+nBits) > m_nDataBits)
237 CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
241 // Get output dword-aligned.
242 while(((unsigned long)pOut & 3) != 0 && nBitsLeft >= 8)
245 WriteUBitLong( *pOut, 8, false );
250 // check if we can use fast memcpy if m_iCurBit is byte aligned
251 if ( (nBitsLeft >= 32) && (m_iCurBit & 7) == 0 )
253 int numbytes = (nBitsLeft >> 3);
254 int numbits = numbytes << 3;
257 // TODO: May not need this check anymore
258 if((m_iCurBit+numbits) > m_nDataBits)
260 m_iCurBit = m_nDataBits;
262 CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
266 Q_memcpy( m_pData+(m_iCurBit>>3), pOut, numbytes );
268 nBitsLeft -= numbits;
269 m_iCurBit += numbits;
273 while(nBitsLeft >= 32)
275 WriteUBitLong( *((unsigned long*)pOut), 32, false );
276 pOut += sizeof(unsigned long);
280 // Read the remaining bytes.
281 while(nBitsLeft >= 8)
283 WriteUBitLong( *pOut, 8, false );
288 // Read the remaining bits.
291 WriteUBitLong( *pOut, nBitsLeft, false );
294 return !IsOverflowed();
298 bool bf_write::WriteBitsFromBuffer( bf_read *pIn, int nBits )
300 // This could be optimized a little by
303 WriteUBitLong( pIn->ReadUBitLong( 32 ), 32 );
307 WriteUBitLong( pIn->ReadUBitLong( nBits ), nBits );
308 return !IsOverflowed() && !pIn->IsOverflowed();
312 void bf_write::WriteBitAngle( float fAngle, int numbits )
318 shift = (1<<numbits);
321 d = (int)( (fAngle / 360.0) * shift );
324 WriteUBitLong((unsigned int)d, numbits);
327 void bf_write::WriteBitCoord (const float f)
329 #if defined( BB_PROFILING )
330 VPROF( "bf_write::WriteBitCoord" );
332 int signbit = (f <= -COORD_RESOLUTION);
333 int intval = abs(static_cast<int>(f));
334 int fractval = abs((int)(f*COORD_DENOMINATOR)) & (COORD_DENOMINATOR-1);
337 // Send the bit flags that indicate whether we have an integer part and/or a fraction part.
338 WriteOneBit( intval );
339 WriteOneBit( fractval );
341 if ( intval || fractval )
344 WriteOneBit( signbit );
346 // Send the integer if we have one.
349 // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1]
351 WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS );
354 // Send the fraction if we have one
357 WriteUBitLong( (unsigned int)fractval, COORD_FRACTIONAL_BITS );
362 void bf_write::WriteBitFloat(float val)
366 Assert(sizeof(long) == sizeof(float));
367 Assert(sizeof(float) == 4);
370 intVal = *reinterpret_cast<long *>(v);
371 WriteUBitLong( intVal, 32 );
374 void bf_write::WriteBitVec3Coord( const Vector& fa )
376 int xflag, yflag, zflag;
378 xflag = (fa[0] >= COORD_RESOLUTION) || (fa[0] <= -COORD_RESOLUTION);
379 yflag = (fa[1] >= COORD_RESOLUTION) || (fa[1] <= -COORD_RESOLUTION);
380 zflag = (fa[2] >= COORD_RESOLUTION) || (fa[2] <= -COORD_RESOLUTION);
382 WriteOneBit( xflag );
383 WriteOneBit( yflag );
384 WriteOneBit( zflag );
387 WriteBitCoord( fa[0] );
389 WriteBitCoord( fa[1] );
391 WriteBitCoord( fa[2] );
394 void bf_write::WriteBitNormal( float f )
396 int signbit = (f <= -NORMAL_RESOLUTION);
398 // NOTE: Since +/-1 are valid values for a normal, I'm going to encode that as all ones
399 unsigned int fractval = abs( (int)(f*NORMAL_DENOMINATOR) );
402 if (fractval > NORMAL_DENOMINATOR)
403 fractval = NORMAL_DENOMINATOR;
406 WriteOneBit( signbit );
408 // Send the fractional component
409 WriteUBitLong( fractval, NORMAL_FRACTIONAL_BITS );
412 void bf_write::WriteBitVec3Normal( const Vector& fa )
416 xflag = (fa[0] >= NORMAL_RESOLUTION) || (fa[0] <= -NORMAL_RESOLUTION);
417 yflag = (fa[1] >= NORMAL_RESOLUTION) || (fa[1] <= -NORMAL_RESOLUTION);
419 WriteOneBit( xflag );
420 WriteOneBit( yflag );
423 WriteBitNormal( fa[0] );
425 WriteBitNormal( fa[1] );
428 int signbit = (fa[2] <= -NORMAL_RESOLUTION);
429 WriteOneBit( signbit );
432 void bf_write::WriteBitAngles( const QAngle& fa )
435 Vector tmp( fa.x, fa.y, fa.z );
436 WriteBitVec3Coord( tmp );
439 void bf_write::WriteChar(int val)
441 WriteSBitLong(val, sizeof(char) << 3);
444 void bf_write::WriteByte(int val)
446 WriteUBitLong(val, sizeof(unsigned char) << 3);
449 void bf_write::WriteShort(int val)
451 WriteSBitLong(val, sizeof(short) << 3);
454 void bf_write::WriteWord(int val)
456 WriteUBitLong(val, sizeof(unsigned short) << 3);
459 void bf_write::WriteLong(long val)
461 WriteSBitLong(val, sizeof(long) << 3);
464 void bf_write::WriteFloat(float val)
466 WriteBits(&val, sizeof(val) << 3);
469 bool bf_write::WriteBytes( const void *pBuf, int nBytes )
471 return WriteBits(pBuf, nBytes << 3);
474 bool bf_write::WriteString(const char *pStr)
482 } while( *(pStr-1) != 0 );
489 return !IsOverflowed();
492 // ---------------------------------------------------------------------------------------- //
494 // ---------------------------------------------------------------------------------------- //
500 m_nDataBits = -1; // set to -1 so we overflow on any operation
503 m_bAssertOnOverflow = true;
507 bf_read::bf_read( const void *pData, int nBytes, int nBits )
509 m_bAssertOnOverflow = true;
510 StartReading( pData, nBytes, 0, nBits );
513 bf_read::bf_read( const char *pDebugName, const void *pData, int nBytes, int nBits )
515 m_bAssertOnOverflow = true;
516 m_pDebugName = pDebugName;
517 StartReading( pData, nBytes, 0, nBits );
520 void bf_read::StartReading( const void *pData, int nBytes, int iStartBit, int nBits )
522 // Make sure we're dword aligned.
523 Assert(((unsigned long)pData & 3) == 0);
525 m_pData = (unsigned char*)pData;
526 m_nDataBytes = nBytes;
530 m_nDataBits = m_nDataBytes << 3;
534 Assert( nBits <= nBytes*8 );
538 m_iCurBit = iStartBit;
542 void bf_read::Reset()
548 void bf_read::SetAssertOnOverflow( bool bAssert )
550 m_bAssertOnOverflow = bAssert;
553 const char* bf_read::GetDebugName()
558 void bf_read::SetDebugName( const char *pName )
560 m_pDebugName = pName;
563 unsigned int bf_read::CheckReadUBitLong(int numbits)
565 // Ok, just read bits out.
569 for(i=0; i < numbits; i++)
571 nBitValue = ReadOneBitNoCheck();
574 m_iCurBit -= numbits;
579 bool bf_read::ReadBits(void *pOutData, int nBits)
581 #if defined( BB_PROFILING )
582 VPROF( "bf_write::ReadBits" );
585 unsigned char *pOut = (unsigned char*)pOutData;
586 int nBitsLeft = nBits;
589 // Get output dword-aligned.
590 while(((unsigned long)pOut & 3) != 0 && nBitsLeft >= 8)
592 *pOut = (unsigned char)ReadUBitLong(8);
598 while(nBitsLeft >= 32)
600 *((unsigned long*)pOut) = ReadUBitLong(32);
601 pOut += sizeof(unsigned long);
605 // Read the remaining bytes.
606 while(nBitsLeft >= 8)
608 *pOut = ReadUBitLong(8);
613 // Read the remaining bits.
616 *pOut = ReadUBitLong(nBitsLeft);
619 return !IsOverflowed();
622 float bf_read::ReadBitAngle( int numbits )
628 shift = (float)( 1 << numbits );
630 i = ReadUBitLong( numbits );
631 fReturn = (float)i * (360.0 / shift);
636 unsigned int bf_read::PeekUBitLong( int numbits )
641 int nShifts = numbits;
646 savebf = *this; // Save current state info
649 for(i=0; i < numbits; i++)
651 nBitValue = ReadOneBit();
653 // Append to current stream
663 Con_Printf( "PeekBitLong: %i %i\n", nShifts, (unsigned int)r );
669 // Append numbits least significant bits from data to the current bit stream
670 int bf_read::ReadSBitLong( int numbits )
674 r = ReadUBitLong(numbits - 1);
676 // Note: it does this wierdness here so it's bit-compatible with regular integer data in the buffer.
677 // (Some old code writes direct integers right into the buffer).
680 r = -((1 << (numbits-1)) - r);
685 unsigned int bf_read::ReadUBitVar()
687 int bits = 0; // how many bits are used to encode delta offset
689 // how many bits do we use
690 while ( ReadOneBit() == 0 )
693 unsigned int data = (1<<bits)-1;
697 data += ReadUBitLong( bits );
703 unsigned int bf_read::ReadBitLong(int numbits, bool bSigned)
706 return (unsigned int)ReadSBitLong(numbits);
708 return ReadUBitLong(numbits);
712 // Basic Coordinate Routines (these contain bit-field size AND fixed point scaling constants)
713 float bf_read::ReadBitCoord (void)
715 #if defined( BB_PROFILING )
716 VPROF( "bf_write::ReadBitCoord" );
718 int intval=0,fractval=0,signbit=0;
722 // Read the required integer and fraction flags
723 intval = ReadOneBit();
724 fractval = ReadOneBit();
726 // If we got either parse them, otherwise it's a zero.
727 if ( intval || fractval )
730 signbit = ReadOneBit();
732 // If there's an integer, read it in
735 // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE]
736 intval = ReadUBitLong( COORD_INTEGER_BITS ) + 1;
739 // If there's a fraction, read it in
742 fractval = ReadUBitLong( COORD_FRACTIONAL_BITS );
745 // Calculate the correct floating point value
746 value = intval + ((float)fractval * COORD_RESOLUTION);
748 // Fixup the sign if negative.
756 void bf_read::ReadBitVec3Coord( Vector& fa )
758 int xflag, yflag, zflag;
760 // This vector must be initialized! Otherwise, If any of the flags aren't set,
761 // the corresponding component will not be read and will be stack garbage.
764 xflag = ReadOneBit();
765 yflag = ReadOneBit();
766 zflag = ReadOneBit();
769 fa[0] = ReadBitCoord();
771 fa[1] = ReadBitCoord();
773 fa[2] = ReadBitCoord();
776 float bf_read::ReadBitNormal (void)
779 int signbit = ReadOneBit();
781 // Read the fractional part
782 unsigned int fractval = ReadUBitLong( NORMAL_FRACTIONAL_BITS );
784 // Calculate the correct floating point value
785 float value = (float)fractval * NORMAL_RESOLUTION;
787 // Fixup the sign if negative.
794 void bf_read::ReadBitVec3Normal( Vector& fa )
796 int xflag = ReadOneBit();
797 int yflag = ReadOneBit();
800 fa[0] = ReadBitNormal();
805 fa[1] = ReadBitNormal();
809 // The first two imply the third (but not its sign)
810 int znegative = ReadOneBit();
812 float fafafbfb = fa[0] * fa[0] + fa[1] * fa[1];
814 fa[2] = sqrt( 1.0f - fafafbfb );
822 void bf_read::ReadBitAngles( QAngle& fa )
825 ReadBitVec3Coord( tmp );
826 fa.Init( tmp.x, tmp.y, tmp.z );
829 int bf_read::ReadChar()
831 return ReadSBitLong(sizeof(char) << 3);
834 int bf_read::ReadByte()
836 return ReadUBitLong(sizeof(unsigned char) << 3);
839 int bf_read::ReadShort()
841 return ReadSBitLong(sizeof(short) << 3);
844 int bf_read::ReadWord()
846 return ReadUBitLong(sizeof(unsigned short) << 3);
849 long bf_read::ReadLong()
851 return ReadSBitLong(sizeof(long) << 3);
854 float bf_read::ReadFloat()
857 Assert( sizeof(ret) == 4 );
862 bool bf_read::ReadBytes(void *pOut, int nBytes)
864 return ReadBits(pOut, nBytes << 3);
867 bool bf_read::ReadString( char *pStr, int maxLen, bool bLine, int *pOutNumChars )
869 Assert( maxLen != 0 );
871 bool bTooSmall = false;
875 char val = ReadChar();
878 else if ( bLine && val == '\n' )
881 if ( iChar < (maxLen-1) )
892 // Make sure it's null-terminated.
893 Assert( iChar < maxLen );
897 *pOutNumChars = iChar;
899 return !IsOverflowed() && !bTooSmall;
903 char* bf_read::ReadAndAllocateString( bool *pOverflow )
908 bool bOverflow = !ReadString( str, sizeof( str ), false, &nChars );
910 *pOverflow = bOverflow;
912 // Now copy into the output and return it;
913 char *pRet = new char[ nChars + 1 ];
914 for ( int i=0; i <= nChars; i++ )
921 bool bf_read::Seek(int iBit)
926 m_iCurBit = m_nDataBits;
929 else if(iBit > m_nDataBits)
932 m_iCurBit = m_nDataBits;
942 void bf_read::ExciseBits( int startbit, int bitstoremove )
944 int endbit = startbit + bitstoremove;
945 int remaining_to_end = m_nDataBits - endbit;
948 temp.StartWriting( (void *)m_pData, m_nDataBits << 3, startbit );
952 for ( int i = 0; i < remaining_to_end; i++ )
954 temp.WriteOneBit( ReadOneBit() );
959 m_nDataBits -= bitstoremove;
960 m_nDataBytes = m_nDataBits >> 3;