Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1293 lines
28 KiB

  1. //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //=============================================================================//
  8. #include "bitbuf.h"
  9. #include "coordsize.h"
  10. #include "mathlib/vector.h"
  11. #include "mathlib/mathlib.h"
  12. #include "tier1/strtools.h"
  13. #include "bitvec.h"
  14. #include "vstdlib/random.h"
  15. // FIXME: Can't use this until we get multithreaded allocations in tier0 working for tools
  16. // This is used by VVIS and fails to link
  17. // NOTE: This must be the last file included!!!
  18. //#include "tier0/memdbgon.h"
  19. #ifdef _X360
  20. // mandatory ... wary of above comment and isolating, tier0 is built as MT though
  21. #include "tier0/memdbgon.h"
  22. #endif
  23. #include "stdio.h"
  24. #ifndef NDEBUG
  25. static volatile char const *pDebugString;
  26. #define DEBUG_LINK_CHECK pDebugString = "tier1.lib built debug!"
  27. #else
  28. #define DEBUG_LINK_CHECK
  29. #endif
  30. void CBitWrite::StartWriting( void *pData, int nBytes, int iStartBit, int nBits )
  31. {
  32. // Make sure it's dword aligned and padded.
  33. DEBUG_LINK_CHECK;
  34. Assert( (nBytes % 4) == 0 );
  35. Assert(((uintp)pData & 3) == 0);
  36. Assert( iStartBit == 0 );
  37. m_pData = (uint32 *) pData;
  38. m_pDataOut = m_pData;
  39. m_nDataBytes = nBytes;
  40. if ( nBits == -1 )
  41. {
  42. m_nDataBits = nBytes << 3;
  43. }
  44. else
  45. {
  46. Assert( nBits <= nBytes*8 );
  47. m_nDataBits = nBits;
  48. }
  49. m_bOverflow = false;
  50. m_nOutBufWord = 0;
  51. m_nOutBitsAvail = 32;
  52. m_pBufferEnd = m_pDataOut + ( nBytes >> 2 );
  53. }
  54. const uint32 CBitBuffer::s_nMaskTable[33] = {
  55. 0,
  56. ( 1 << 1 ) - 1,
  57. ( 1 << 2 ) - 1,
  58. ( 1 << 3 ) - 1,
  59. ( 1 << 4 ) - 1,
  60. ( 1 << 5 ) - 1,
  61. ( 1 << 6 ) - 1,
  62. ( 1 << 7 ) - 1,
  63. ( 1 << 8 ) - 1,
  64. ( 1 << 9 ) - 1,
  65. ( 1 << 10 ) - 1,
  66. ( 1 << 11 ) - 1,
  67. ( 1 << 12 ) - 1,
  68. ( 1 << 13 ) - 1,
  69. ( 1 << 14 ) - 1,
  70. ( 1 << 15 ) - 1,
  71. ( 1 << 16 ) - 1,
  72. ( 1 << 17 ) - 1,
  73. ( 1 << 18 ) - 1,
  74. ( 1 << 19 ) - 1,
  75. ( 1 << 20 ) - 1,
  76. ( 1 << 21 ) - 1,
  77. ( 1 << 22 ) - 1,
  78. ( 1 << 23 ) - 1,
  79. ( 1 << 24 ) - 1,
  80. ( 1 << 25 ) - 1,
  81. ( 1 << 26 ) - 1,
  82. ( 1 << 27 ) - 1,
  83. ( 1 << 28 ) - 1,
  84. ( 1 << 29 ) - 1,
  85. ( 1 << 30 ) - 1,
  86. 0x7fffffff,
  87. 0xffffffff,
  88. };
  89. bool CBitWrite::WriteString( const char *pStr )
  90. {
  91. if(pStr)
  92. {
  93. while( *pStr )
  94. {
  95. WriteChar( * ( pStr++ ) );
  96. }
  97. }
  98. WriteChar( 0 );
  99. return !IsOverflowed();
  100. }
  101. void CBitWrite::WriteLongLong(int64 val)
  102. {
  103. uint *pLongs = (uint*)&val;
  104. // Insert the two DWORDS according to network endian
  105. const short endianIndex = 0x0100;
  106. byte *idx = (byte*)&endianIndex;
  107. WriteUBitLong(pLongs[*idx++], sizeof(int32) << 3);
  108. WriteUBitLong(pLongs[*idx], sizeof(int32) << 3);
  109. }
  110. bool CBitWrite::WriteBits(const void *pInData, int nBits)
  111. {
  112. unsigned char *pOut = (unsigned char*)pInData;
  113. int nBitsLeft = nBits;
  114. // Bounds checking..
  115. if ( ( GetNumBitsWritten() + nBits) > m_nDataBits )
  116. {
  117. SetOverflowFlag();
  118. CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, m_pDebugName );
  119. return false;
  120. }
  121. // !! speed!! need fast paths
  122. // write remaining bytes
  123. while ( nBitsLeft >= 8 )
  124. {
  125. WriteUBitLong( *pOut, 8, false );
  126. ++pOut;
  127. nBitsLeft -= 8;
  128. }
  129. // write remaining bits
  130. if ( nBitsLeft )
  131. {
  132. WriteUBitLong( *pOut, nBitsLeft, false );
  133. }
  134. return !IsOverflowed();
  135. }
  136. void CBitWrite::WriteBytes( const void *pBuf, int nBytes )
  137. {
  138. WriteBits(pBuf, nBytes << 3);
  139. }
  140. void CBitWrite::WriteBitCoord (const float f)
  141. {
  142. int signbit = (f <= -COORD_RESOLUTION);
  143. int intval = (int)abs(f);
  144. int fractval = abs((int)(f*COORD_DENOMINATOR)) & (COORD_DENOMINATOR-1);
  145. // Send the bit flags that indicate whether we have an integer part and/or a fraction part.
  146. WriteOneBit( intval );
  147. WriteOneBit( fractval );
  148. if ( intval || fractval )
  149. {
  150. // Send the sign bit
  151. WriteOneBit( signbit );
  152. // Send the integer if we have one.
  153. if ( intval )
  154. {
  155. // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1]
  156. intval--;
  157. WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS );
  158. }
  159. // Send the fraction if we have one
  160. if ( fractval )
  161. {
  162. WriteUBitLong( (unsigned int)fractval, COORD_FRACTIONAL_BITS );
  163. }
  164. }
  165. }
  166. void CBitWrite::WriteBitCoordMP (const float f, EBitCoordType coordType )
  167. {
  168. bool bIntegral = ( coordType == kCW_Integral );
  169. bool bLowPrecision = ( coordType == kCW_LowPrecision );
  170. int signbit = (f <= -( bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION ));
  171. int intval = (int)abs(f);
  172. int fractval = bLowPrecision ?
  173. ( abs((int)(f*COORD_DENOMINATOR_LOWPRECISION)) & (COORD_DENOMINATOR_LOWPRECISION-1) ) :
  174. ( abs((int)(f*COORD_DENOMINATOR)) & (COORD_DENOMINATOR-1) );
  175. bool bInBounds = intval < (1 << COORD_INTEGER_BITS_MP );
  176. WriteOneBit( bInBounds );
  177. if ( bIntegral )
  178. {
  179. // Send the sign bit
  180. WriteOneBit( intval );
  181. if ( intval )
  182. {
  183. WriteOneBit( signbit );
  184. // Send the integer if we have one.
  185. // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1]
  186. intval--;
  187. if ( bInBounds )
  188. {
  189. WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS_MP );
  190. }
  191. else
  192. {
  193. WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS );
  194. }
  195. }
  196. }
  197. else
  198. {
  199. // Send the bit flags that indicate whether we have an integer part and/or a fraction part.
  200. WriteOneBit( intval );
  201. // Send the sign bit
  202. WriteOneBit( signbit );
  203. // Send the integer if we have one.
  204. if ( intval )
  205. {
  206. // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1]
  207. intval--;
  208. if ( bInBounds )
  209. {
  210. WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS_MP );
  211. }
  212. else
  213. {
  214. WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS );
  215. }
  216. }
  217. WriteUBitLong( (unsigned int)fractval, bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS );
  218. }
  219. }
  220. void CBitWrite::WriteBitCellCoord( const float f, int bits, EBitCoordType coordType )
  221. {
  222. Assert( f >= 0.0f ); // cell coords can't be negative
  223. Assert( f < ( 1 << bits ) );
  224. bool bIntegral = ( coordType == kCW_Integral );
  225. bool bLowPrecision = ( coordType == kCW_LowPrecision );
  226. int intval = (int)abs(f);
  227. int fractval = bLowPrecision ?
  228. ( abs((int)(f*COORD_DENOMINATOR_LOWPRECISION)) & (COORD_DENOMINATOR_LOWPRECISION-1) ) :
  229. ( abs((int)(f*COORD_DENOMINATOR)) & (COORD_DENOMINATOR-1) );
  230. if ( bIntegral )
  231. {
  232. WriteUBitLong( (unsigned int)intval, bits );
  233. }
  234. else
  235. {
  236. WriteUBitLong( (unsigned int)intval, bits );
  237. WriteUBitLong( (unsigned int)fractval, bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS );
  238. }
  239. }
  240. void CBitWrite::SeekToBit( int nBit )
  241. {
  242. TempFlush();
  243. m_pDataOut = m_pData + ( nBit / 32 );
  244. m_nOutBufWord = LoadLittleDWord( m_pDataOut, 0 );
  245. m_nOutBitsAvail = 32 - ( nBit & 31 );
  246. }
  247. void CBitWrite::WriteBitVec3Coord( const Vector& fa )
  248. {
  249. int xflag, yflag, zflag;
  250. xflag = (fa[0] >= COORD_RESOLUTION) || (fa[0] <= -COORD_RESOLUTION);
  251. yflag = (fa[1] >= COORD_RESOLUTION) || (fa[1] <= -COORD_RESOLUTION);
  252. zflag = (fa[2] >= COORD_RESOLUTION) || (fa[2] <= -COORD_RESOLUTION);
  253. WriteOneBit( xflag );
  254. WriteOneBit( yflag );
  255. WriteOneBit( zflag );
  256. if ( xflag )
  257. WriteBitCoord( fa[0] );
  258. if ( yflag )
  259. WriteBitCoord( fa[1] );
  260. if ( zflag )
  261. WriteBitCoord( fa[2] );
  262. }
  263. void CBitWrite::WriteBitNormal( float f )
  264. {
  265. int signbit = (f <= -NORMAL_RESOLUTION);
  266. // NOTE: Since +/-1 are valid values for a normal, I'm going to encode that as all ones
  267. unsigned int fractval = abs( (int)(f*NORMAL_DENOMINATOR) );
  268. // clamp..
  269. if (fractval > NORMAL_DENOMINATOR)
  270. fractval = NORMAL_DENOMINATOR;
  271. // Send the sign bit
  272. WriteOneBit( signbit );
  273. // Send the fractional component
  274. WriteUBitLong( fractval, NORMAL_FRACTIONAL_BITS );
  275. }
  276. void CBitWrite::WriteBitVec3Normal( const Vector& fa )
  277. {
  278. int xflag, yflag;
  279. xflag = (fa[0] >= NORMAL_RESOLUTION) || (fa[0] <= -NORMAL_RESOLUTION);
  280. yflag = (fa[1] >= NORMAL_RESOLUTION) || (fa[1] <= -NORMAL_RESOLUTION);
  281. WriteOneBit( xflag );
  282. WriteOneBit( yflag );
  283. if ( xflag )
  284. WriteBitNormal( fa[0] );
  285. if ( yflag )
  286. WriteBitNormal( fa[1] );
  287. // Write z sign bit
  288. int signbit = (fa[2] <= -NORMAL_RESOLUTION);
  289. WriteOneBit( signbit );
  290. }
  291. void CBitWrite::WriteBitAngle( float fAngle, int numbits )
  292. {
  293. unsigned int shift = GetBitForBitnum(numbits);
  294. unsigned int mask = shift - 1;
  295. int d = (int)( (fAngle / 360.0) * shift );
  296. d &= mask;
  297. WriteUBitLong((unsigned int)d, numbits);
  298. }
  299. bool CBitWrite::WriteBitsFromBuffer( bf_read *pIn, int nBits )
  300. {
  301. // This could be optimized a little by
  302. while ( nBits > 32 )
  303. {
  304. WriteUBitLong( pIn->ReadUBitLong( 32 ), 32 );
  305. nBits -= 32;
  306. }
  307. WriteUBitLong( pIn->ReadUBitLong( nBits ), nBits );
  308. return !IsOverflowed() && !pIn->IsOverflowed();
  309. }
  310. void CBitWrite::WriteBitAngles( const QAngle& fa )
  311. {
  312. // FIXME:
  313. Vector tmp( fa.x, fa.y, fa.z );
  314. WriteBitVec3Coord( tmp );
  315. }
  316. bool CBitRead::Seek( int nPosition )
  317. {
  318. bool bSucc = true;
  319. if ( nPosition < 0 || nPosition > m_nDataBits)
  320. {
  321. SetOverflowFlag();
  322. bSucc = false;
  323. nPosition = m_nDataBits;
  324. }
  325. int nHead = m_nDataBytes & 3; // non-multiple-of-4 bytes at head of buffer. We put the "round off"
  326. // at the head to make reading and detecting the end efficient.
  327. int nByteOfs = nPosition / 8;
  328. if ( ( m_nDataBytes < 4 ) || ( nHead && ( nByteOfs < nHead ) ) )
  329. {
  330. // partial first dword
  331. uint8 const *pPartial = ( uint8 const *) m_pData;
  332. if ( m_pData )
  333. {
  334. m_nInBufWord = *( pPartial++ );
  335. if ( nHead > 1 )
  336. m_nInBufWord |= ( *pPartial++ ) << 8;
  337. if ( nHead > 2 )
  338. m_nInBufWord |= ( *pPartial++ ) << 16;
  339. }
  340. m_pDataIn = ( uint32 const * ) pPartial;
  341. m_nInBufWord >>= ( nPosition & 31 );
  342. m_nBitsAvail = ( nHead << 3 ) - ( nPosition & 31 );
  343. }
  344. else
  345. {
  346. int nAdjPosition = nPosition - ( nHead << 3 );
  347. m_pDataIn = reinterpret_cast<uint32 const *> (
  348. reinterpret_cast<uint8 const *>( m_pData ) + ( ( nAdjPosition / 32 ) << 2 ) + nHead );
  349. if ( m_pData )
  350. {
  351. m_nBitsAvail = 32;
  352. GrabNextDWord();
  353. }
  354. else
  355. {
  356. m_nInBufWord = 0;
  357. m_nBitsAvail = 1;
  358. }
  359. m_nInBufWord >>= ( nAdjPosition & 31 );
  360. m_nBitsAvail = MIN( m_nBitsAvail, 32 - ( nAdjPosition & 31 ) ); // in case grabnextdword overflowed
  361. }
  362. return bSucc;
  363. }
  364. void CBitRead::StartReading( const void *pData, int nBytes, int iStartBit, int nBits )
  365. {
  366. DEBUG_LINK_CHECK;
  367. // Make sure it's dword aligned and padded.
  368. Assert(((uintp)pData & 3) == 0);
  369. m_pData = (uint32 *) pData;
  370. m_pDataIn = m_pData;
  371. m_nDataBytes = nBytes;
  372. if ( nBits == -1 )
  373. {
  374. m_nDataBits = nBytes << 3;
  375. }
  376. else
  377. {
  378. Assert( nBits <= nBytes*8 );
  379. m_nDataBits = nBits;
  380. }
  381. m_bOverflow = false;
  382. m_pBufferEnd = reinterpret_cast<uint32 const *> ( reinterpret_cast< uint8 const *> (m_pData) + nBytes );
  383. if ( m_pData )
  384. Seek( iStartBit );
  385. }
  386. bool CBitRead::ReadString( char *pStr, int maxLen, bool bLine, int *pOutNumChars )
  387. {
  388. Assert( maxLen != 0 );
  389. bool bTooSmall = false;
  390. int iChar = 0;
  391. while(1)
  392. {
  393. char val = ReadChar();
  394. if ( val == 0 )
  395. break;
  396. else if ( bLine && val == '\n' )
  397. break;
  398. if ( iChar < (maxLen-1) )
  399. {
  400. pStr[iChar] = val;
  401. ++iChar;
  402. }
  403. else
  404. {
  405. bTooSmall = true;
  406. }
  407. }
  408. // Make sure it's null-terminated.
  409. Assert( iChar < maxLen );
  410. pStr[iChar] = 0;
  411. if ( pOutNumChars )
  412. *pOutNumChars = iChar;
  413. return !IsOverflowed() && !bTooSmall;
  414. }
  415. bool CBitRead::ReadWString( OUT_Z_CAP(maxLenInChars) wchar_t *pStr, int maxLenInChars, bool bLine, int *pOutNumChars )
  416. {
  417. Assert( maxLenInChars != 0 );
  418. bool bTooSmall = false;
  419. int iChar = 0;
  420. while(1)
  421. {
  422. wchar val = ReadShort();
  423. if ( val == 0 )
  424. break;
  425. else if ( bLine && val == L'\n' )
  426. break;
  427. if ( iChar < (maxLenInChars-1) )
  428. {
  429. pStr[iChar] = val;
  430. ++iChar;
  431. }
  432. else
  433. {
  434. bTooSmall = true;
  435. }
  436. }
  437. // Make sure it's null-terminated.
  438. Assert( iChar < maxLenInChars );
  439. pStr[iChar] = 0;
  440. if ( pOutNumChars )
  441. *pOutNumChars = iChar;
  442. return !IsOverflowed() && !bTooSmall;
  443. }
  444. char* CBitRead::ReadAndAllocateString( bool *pOverflow )
  445. {
  446. char str[2048];
  447. int nChars;
  448. bool bOverflow = !ReadString( str, sizeof( str ), false, &nChars );
  449. if ( pOverflow )
  450. *pOverflow = bOverflow;
  451. // Now copy into the output and return it;
  452. char *pRet = new char[ nChars + 1 ];
  453. for ( int i=0; i <= nChars; i++ )
  454. pRet[i] = str[i];
  455. return pRet;
  456. }
  457. int64 CBitRead::ReadLongLong( void )
  458. {
  459. int64 retval;
  460. uint *pLongs = (uint*)&retval;
  461. // Read the two DWORDs according to network endian
  462. const short endianIndex = 0x0100;
  463. byte *idx = (byte*)&endianIndex;
  464. pLongs[*idx++] = ReadUBitLong(sizeof(int32) << 3);
  465. pLongs[*idx] = ReadUBitLong(sizeof(int32) << 3);
  466. return retval;
  467. }
  468. // Read 1-5 bytes in order to extract a 32-bit unsigned value from the
  469. // stream. 7 data bits are extracted from each byte with the 8th bit used
  470. // to indicate whether the loop should continue.
  471. // This allows variable size numbers to be stored with tolerable
  472. // efficiency. Numbers sizes that can be stored for various numbers of
  473. // encoded bits are:
  474. // 8-bits: 0-127
  475. // 16-bits: 128-16383
  476. // 24-bits: 16384-2097151
  477. // 32-bits: 2097152-268435455
  478. // 40-bits: 268435456-0xFFFFFFFF
  479. uint32 CBitRead::ReadVarInt32()
  480. {
  481. uint32 result = 0;
  482. int count = 0;
  483. uint32 b;
  484. do
  485. {
  486. if ( count == bitbuf::kMaxVarint32Bytes )
  487. {
  488. return result;
  489. }
  490. b = ReadUBitLong( 8 );
  491. result |= (b & 0x7F) << (7 * count);
  492. ++count;
  493. } while (b & 0x80);
  494. return result;
  495. }
  496. uint64 CBitRead::ReadVarInt64()
  497. {
  498. uint64 result = 0;
  499. int count = 0;
  500. uint64 b;
  501. do
  502. {
  503. if ( count == bitbuf::kMaxVarintBytes )
  504. {
  505. return result;
  506. }
  507. b = ReadUBitLong( 8 );
  508. result |= static_cast<uint64>(b & 0x7F) << (7 * count);
  509. ++count;
  510. } while (b & 0x80);
  511. return result;
  512. }
  513. void CBitRead::ReadBits(void *pOutData, int nBits)
  514. {
  515. unsigned char *pOut = (unsigned char*)pOutData;
  516. int nBitsLeft = nBits;
  517. // align output to dword boundary
  518. while( ((uintp)pOut & 3) != 0 && nBitsLeft >= 8 )
  519. {
  520. *pOut = (unsigned char)ReadUBitLong(8);
  521. ++pOut;
  522. nBitsLeft -= 8;
  523. }
  524. // X360TBD: Can't read dwords in ReadBits because they'll get swapped
  525. if ( IsPC() )
  526. {
  527. // read dwords
  528. while ( nBitsLeft >= 32 )
  529. {
  530. *((uint32*)pOut) = ReadUBitLong(32);
  531. pOut += sizeof(uint32);
  532. nBitsLeft -= 32;
  533. }
  534. }
  535. // read remaining bytes
  536. while ( nBitsLeft >= 8 )
  537. {
  538. *pOut = ReadUBitLong(8);
  539. ++pOut;
  540. nBitsLeft -= 8;
  541. }
  542. // read remaining bits
  543. if ( nBitsLeft )
  544. {
  545. *pOut = ReadUBitLong(nBitsLeft);
  546. }
  547. }
  548. bool CBitRead::ReadBytes(void *pOut, int nBytes)
  549. {
  550. ReadBits(pOut, nBytes << 3);
  551. return !IsOverflowed();
  552. }
  553. float CBitRead::ReadBitAngle( int numbits )
  554. {
  555. float shift = (float)( GetBitForBitnum(numbits) );
  556. int i = ReadUBitLong( numbits );
  557. float fReturn = (float)i * (360.0 / shift);
  558. return fReturn;
  559. }
  560. // Basic Coordinate Routines (these contain bit-field size AND fixed point scaling constants)
  561. float CBitRead::ReadBitCoord (void)
  562. {
  563. int intval=0,fractval=0,signbit=0;
  564. float value = 0.0;
  565. // Read the required integer and fraction flags
  566. intval = ReadOneBit();
  567. fractval = ReadOneBit();
  568. // If we got either parse them, otherwise it's a zero.
  569. if ( intval || fractval )
  570. {
  571. // Read the sign bit
  572. signbit = ReadOneBit();
  573. // If there's an integer, read it in
  574. if ( intval )
  575. {
  576. // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE]
  577. intval = ReadUBitLong( COORD_INTEGER_BITS ) + 1;
  578. }
  579. // If there's a fraction, read it in
  580. if ( fractval )
  581. {
  582. fractval = ReadUBitLong( COORD_FRACTIONAL_BITS );
  583. }
  584. // Calculate the correct floating point value
  585. value = intval + ((float)fractval * COORD_RESOLUTION);
  586. // Fixup the sign if negative.
  587. if ( signbit )
  588. value = -value;
  589. }
  590. return value;
  591. }
  592. float CBitRead::ReadBitCoordMP( EBitCoordType coordType )
  593. {
  594. bool bIntegral = ( coordType == kCW_Integral );
  595. bool bLowPrecision = ( coordType == kCW_LowPrecision );
  596. int intval=0,fractval=0,signbit=0;
  597. float value = 0.0;
  598. bool bInBounds = ReadOneBit() ? true : false;
  599. if ( bIntegral )
  600. {
  601. // Read the required integer and fraction flags
  602. intval = ReadOneBit();
  603. // If we got either parse them, otherwise it's a zero.
  604. if ( intval )
  605. {
  606. // Read the sign bit
  607. signbit = ReadOneBit();
  608. // If there's an integer, read it in
  609. // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE]
  610. if ( bInBounds )
  611. {
  612. value = ReadUBitLong( COORD_INTEGER_BITS_MP ) + 1;
  613. }
  614. else
  615. {
  616. value = ReadUBitLong( COORD_INTEGER_BITS ) + 1;
  617. }
  618. }
  619. }
  620. else
  621. {
  622. // Read the required integer and fraction flags
  623. intval = ReadOneBit();
  624. // Read the sign bit
  625. signbit = ReadOneBit();
  626. // If we got either parse them, otherwise it's a zero.
  627. if ( intval )
  628. {
  629. if ( bInBounds )
  630. {
  631. intval = ReadUBitLong( COORD_INTEGER_BITS_MP ) + 1;
  632. }
  633. else
  634. {
  635. intval = ReadUBitLong( COORD_INTEGER_BITS ) + 1;
  636. }
  637. }
  638. // If there's a fraction, read it in
  639. fractval = ReadUBitLong( bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS );
  640. // Calculate the correct floating point value
  641. value = intval + ((float)fractval * ( bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION ) );
  642. }
  643. // Fixup the sign if negative.
  644. if ( signbit )
  645. value = -value;
  646. return value;
  647. }
  648. float CBitRead::ReadBitCellCoord( int bits, EBitCoordType coordType )
  649. {
  650. #if defined( BB_PROFILING )
  651. VPROF( "bf_write::ReadBitCoordMP" );
  652. #endif
  653. bool bIntegral = ( coordType == kCW_Integral );
  654. bool bLowPrecision = ( coordType == kCW_LowPrecision );
  655. int intval=0,fractval=0;
  656. float value = 0.0;
  657. if ( bIntegral )
  658. {
  659. value = ReadUBitLong( bits );
  660. }
  661. else
  662. {
  663. intval = ReadUBitLong( bits );
  664. // If there's a fraction, read it in
  665. fractval = ReadUBitLong( bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS );
  666. // Calculate the correct floating point value
  667. value = intval + ((float)fractval * ( bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION ) );
  668. }
  669. return value;
  670. }
  671. void CBitRead::ReadBitVec3Coord( Vector& fa )
  672. {
  673. int xflag, yflag, zflag;
  674. // This vector must be initialized! Otherwise, If any of the flags aren't set,
  675. // the corresponding component will not be read and will be stack garbage.
  676. fa.Init( 0, 0, 0 );
  677. xflag = ReadOneBit();
  678. yflag = ReadOneBit();
  679. zflag = ReadOneBit();
  680. if ( xflag )
  681. fa[0] = ReadBitCoord();
  682. if ( yflag )
  683. fa[1] = ReadBitCoord();
  684. if ( zflag )
  685. fa[2] = ReadBitCoord();
  686. }
  687. float CBitRead::ReadBitNormal (void)
  688. {
  689. // Read the sign bit
  690. int signbit = ReadOneBit();
  691. // Read the fractional part
  692. unsigned int fractval = ReadUBitLong( NORMAL_FRACTIONAL_BITS );
  693. // Calculate the correct floating point value
  694. float value = (float)fractval * NORMAL_RESOLUTION;
  695. // Fixup the sign if negative.
  696. if ( signbit )
  697. value = -value;
  698. return value;
  699. }
  700. void CBitRead::ReadBitVec3Normal( Vector& fa )
  701. {
  702. int xflag = ReadOneBit();
  703. int yflag = ReadOneBit();
  704. if (xflag)
  705. fa[0] = ReadBitNormal();
  706. else
  707. fa[0] = 0.0f;
  708. if (yflag)
  709. fa[1] = ReadBitNormal();
  710. else
  711. fa[1] = 0.0f;
  712. // The first two imply the third (but not its sign)
  713. int znegative = ReadOneBit();
  714. float fafafbfb = fa[0] * fa[0] + fa[1] * fa[1];
  715. if (fafafbfb < 1.0f)
  716. fa[2] = sqrt( 1.0f - fafafbfb );
  717. else
  718. fa[2] = 0.0f;
  719. if (znegative)
  720. fa[2] = -fa[2];
  721. }
  722. void CBitRead::ReadBitAngles( QAngle& fa )
  723. {
  724. Vector tmp;
  725. ReadBitVec3Coord( tmp );
  726. fa.Init( tmp.x, tmp.y, tmp.z );
  727. }
  728. //--------------------------------------------------------------------------------------------------------------------------------------------------------------------
  729. //--------------------------------------------------------------------------------------------------------------------------------------------------------------------
  730. /*
  731. // Tests
  732. #define TEST_BITBUF
  733. #ifndef TEST_BITBUF
  734. void TestBitBufs()
  735. {
  736. }
  737. #else //TEST_BITBUF
  738. enum EBitBufTestFields
  739. {
  740. kBBTF_ULONG,
  741. kBBTF_BYTES,
  742. #if 0
  743. // kBBTF_UBVAR,
  744. kBBTF_FLOAT,
  745. kBBTF_CHAR,
  746. kBBTF_BYTE,
  747. kBBTF_SHORT,
  748. kBBTF_STRING,
  749. kBBTF_LONGLONG,
  750. #endif
  751. kBBTF_Count
  752. };
  753. static char bitbuf_string[] = "Life's but a walking shadow, a poor player.";
  754. static char bitsbuf[ sizeof( bitbuf_string ) ];
  755. template < class TWriter >
  756. float TestBitBufferWriter( void *buffer, int bufsize, int seed, int numtests, bool log = false )
  757. {
  758. CFastTimer timer;
  759. timer.Start();
  760. TWriter writer( "TestBufferWriter", buffer, bufsize );
  761. // Fill it up with the writer
  762. RandomSeed( seed );
  763. int bitTotal = 0;
  764. for ( int i = 0; i < numtests; ++i )
  765. {
  766. if ( writer.IsOverflowed() )
  767. {
  768. printf("writer: OVERFLOW!" );
  769. }
  770. if ( writer.GetNumBitsWritten() != bitTotal )
  771. {
  772. printf("writer: bitTotal MISMATCH!\n");
  773. }
  774. int testtype = RandomInt( 0, kBBTF_Count - 1 );
  775. switch ( testtype )
  776. {
  777. case kBBTF_ULONG:
  778. {
  779. int bits = RandomInt( 0, ( sizeof( uint32 ) << 3 ) - 1 );
  780. uint32 n = (uint32)RandomInt( 0, 0x7fff );
  781. if ( bits )
  782. {
  783. n &= (1 << bits) - 1;
  784. }
  785. else
  786. {
  787. bits = 32;
  788. }
  789. if (log) printf("\t%3d: write ULONG: %u, %d bits\n", i, n, bits );
  790. writer.WriteUBitLong( n, bits );
  791. bitTotal += bits;
  792. }
  793. break;
  794. case kBBTF_BYTES:
  795. {
  796. int bytes = RandomInt( 1, sizeof( bitsbuf ) );
  797. if (log) printf("\t%3d: write BYTES: %d bytes\n", i, bytes );
  798. writer.WriteBytes( bitsbuf, bytes );
  799. bitTotal += bytes << 3;
  800. }
  801. break;
  802. #if 0
  803. case kBBTF_SLONG:
  804. {
  805. int bits = RandomInt( 2, sizeof( int32 ) << 3 );
  806. int32 n = (int32)RandomInt( 0, 0x7fff ) & ( ( 1 << ( bits - 1 ) ) - 1 );
  807. if ( RandomInt( 0, 1 ) < 1 )
  808. {
  809. n = -n;
  810. }
  811. if (log) printf("\t%3d: write SLONG: %d, %d bits\n", i, n, bits );
  812. writer.WriteSBitLong( n, bits );
  813. bitTotal += bits;
  814. }
  815. break;
  816. case kBBTF_UBVAR:
  817. {
  818. unsigned int n = (unsigned int)RandomInt( 0, 0x7fff );
  819. if (log) printf("\t%3d: write UBVAR: %u\n", i, n );
  820. writer.WriteUBitVar( n );
  821. }
  822. break;
  823. case kBBTF_FLOAT:
  824. {
  825. float n = RandomFloat( 0.0f, FLT_MAX );
  826. if (log) printf("\t%3d: write FLOAT: %f\n", i, n );
  827. writer.WriteFloat( n );
  828. bitTotal += sizeof(float)<<3;;
  829. }
  830. break;
  831. case kBBTF_CHAR:
  832. {
  833. char n = (char)RandomInt( 0, 0x7f );
  834. if (log) printf("\t%3d: write CHAR: %d\n", i, n );
  835. writer.WriteChar( n );
  836. bitTotal += sizeof(char)<<3;;
  837. }
  838. break;
  839. case kBBTF_BYTE:
  840. {
  841. unsigned char n = (unsigned char)RandomInt( 0, 0xff );
  842. if (log) printf("\t%3d: write BYTE: %d\n", i, n );
  843. writer.WriteByte( n );
  844. bitTotal += sizeof(unsigned char)<<3;;
  845. }
  846. break;
  847. case kBBTF_SHORT:
  848. {
  849. short n = (short)RandomInt( 0, 0x7fff );
  850. if (log) printf("\t%3d: write SHORT: %d\n", i, n );
  851. writer.WriteShort( n );
  852. bitTotal += sizeof(short)<<3;;
  853. }
  854. break;
  855. case kBBTF_STRING:
  856. {
  857. writer.WriteString( bitbuf_string );
  858. if (log) printf("\t%3d: write STRING\n", i );
  859. bitTotal += (sizeof(char)<<3) * ( strlen( bitbuf_string ) + 1 );
  860. }
  861. break;
  862. case kBBTF_LONGLONG:
  863. {
  864. int64 low = RandomInt( 0, 0x7fff );
  865. int64 high = RandomInt( 0, 0x7fff );
  866. int64 n = (high << 32) | low;
  867. if (log) printf("\t%3d: write LONGLONG: %lld\n", i, n );
  868. writer.WriteLongLong( n );
  869. bitTotal += sizeof(int64)<<3;
  870. }
  871. break;
  872. #endif
  873. }
  874. }
  875. writer.GetData(); // insure a flush
  876. timer.End();
  877. return timer.GetDuration().GetMicrosecondsF();
  878. }
  879. template < class TReader >
  880. float TestBitBufferReader( void *buffer, int bufsize, int seed, int numtests, bool log = false )
  881. {
  882. CFastTimer timer;
  883. timer.Start();
  884. TReader reader( "TestBufferReader", buffer, bufsize );
  885. // And let's read it back to ensure it all got written correctly
  886. // Fill it up with the writer
  887. RandomSeed( seed );
  888. for ( int i = 0; i < numtests; ++i )
  889. {
  890. int testtype = RandomInt( 0, kBBTF_Count - 1 );
  891. switch ( testtype )
  892. {
  893. case kBBTF_ULONG:
  894. {
  895. int bits = RandomInt( 0, ( sizeof( uint32 ) << 3 ) - 1 );
  896. uint32 n = (uint32)RandomInt( 0, 0x7fff );
  897. if ( bits )
  898. {
  899. n &= (1 << bits) - 1;
  900. }
  901. else
  902. {
  903. bits = 32;
  904. }
  905. uint32 v = reader.ReadUBitLong( bits );
  906. if (log) printf("\t%3d: read ULONG: %u, %d bits, GOT: %u\n", i, n, bits, v );
  907. if ( v != n )
  908. {
  909. printf("\t%3d: Mismatched ULONG: read %u instead of %u\n", i, v, n );
  910. }
  911. }
  912. break;
  913. case kBBTF_BYTES:
  914. {
  915. int bytes = RandomInt( 1, sizeof( bitsbuf ) );
  916. char readbuf[ sizeof( bitsbuf ) ];
  917. reader.ReadBytes( readbuf, bytes );
  918. if (log) printf("\t%3d: read BYTES: %d bytes\n", i, bytes );
  919. if ( Q_memcmp( bitsbuf, readbuf, bytes ) )
  920. {
  921. printf("\t%3d: Mismatched BYTES\n", i);
  922. }
  923. }
  924. break;
  925. #if 0
  926. case kBBTF_BYTE:
  927. {
  928. unsigned char n = (unsigned char)RandomInt( 0, 0xff );
  929. unsigned char v = reader.ReadByte();
  930. if (log) printf("\t%3d: read BYTE: %d, GOT: %d\n", i, n, v );
  931. if ( v != n )
  932. {
  933. printf("\t%3d: Mismatched BYTE: read %d instead of %d\n", i, v, n );
  934. }
  935. }
  936. break;
  937. case kBBTF_SLONG:
  938. {
  939. int bits = RandomInt( 2, sizeof( int32 ) << 3 );
  940. int32 n = (int32)RandomInt( 0, 0x7fff ) & ( ( 1 << ( bits - 1 ) ) - 1 );
  941. if ( RandomInt( 0, 1 ) < 1 )
  942. {
  943. n = -n;
  944. }
  945. int32 v = reader.ReadSBitLong( bits );
  946. if (log) printf("\t%3d: read SLONG: %d, %d bits, GOT: %d\n", i, n, bits, v );
  947. if ( v != n )
  948. {
  949. printf("\t%3d: Mismatched SLONG: read %d instead of %d\n", i, v, n );
  950. }
  951. }
  952. break;
  953. case kBBTF_UBVAR:
  954. {
  955. unsigned int n = (unsigned int)RandomInt( 0, 0x7fff );
  956. unsigned int v = reader.ReadUBitVar();
  957. if (log) printf("\t%3d: read UBVAR: %u, GOT: %u\n", i, n, v );
  958. if ( v != n )
  959. {
  960. printf("\t%3d: Mismatched UBVAR: read %u instead of %u\n", i, v, n );
  961. }
  962. }
  963. break;
  964. case kBBTF_FLOAT:
  965. {
  966. float n = RandomFloat( 0.0f, FLT_MAX );
  967. float v = reader.ReadFloat();
  968. if (log) printf("\t%3d: read FLOAT: %f, GOT: %f\n", i, n, v );
  969. // if ( v != n )
  970. // {
  971. // printf("\t%3d: Mismatched FLOAT: read %f instead of %f (d=%f)\n", i, v, n, v - n );
  972. // }
  973. }
  974. break;
  975. case kBBTF_CHAR:
  976. {
  977. char n = (char)RandomInt( 0, 0x7f );
  978. char v = reader.ReadChar();
  979. if (log) printf("\t%3d: read CHAR: %d, GOT: %d\n", i, n, v );
  980. if ( v != n )
  981. {
  982. printf("\t%3d: Mismatched CHAR: read %d instead of %d\n", i, v, n );
  983. }
  984. }
  985. break;
  986. case kBBTF_SHORT:
  987. {
  988. short n = (short)RandomInt( 0, 0x7fff );
  989. short v = reader.ReadShort();
  990. if (log) printf("\t%3d: read SHORT: %d, GOT: %d\n", i, n, v );
  991. if ( v != n )
  992. {
  993. printf("\t%3d: Mismatched SHORT: read %d instead of %d\n", i, v, n );
  994. }
  995. }
  996. break;
  997. case kBBTF_STRING:
  998. {
  999. char readbuf[ sizeof( bitbuf_string ) ];
  1000. reader.ReadString( readbuf, sizeof( readbuf ) );
  1001. if (log) printf("\t%3d: read STRING\n", i );
  1002. if ( Q_strcmp( bitbuf_string, readbuf ) )
  1003. {
  1004. printf("\t%3d: Mismatched STRING\n", i);
  1005. }
  1006. }
  1007. break;
  1008. case kBBTF_LONGLONG:
  1009. {
  1010. int64 low = RandomInt( 0, 0x7fff );
  1011. int64 high = RandomInt( 0, 0x7fff );
  1012. int64 n = (high << 32) | low;
  1013. int64 v = reader.ReadLongLong();
  1014. if (log) printf("\t%3d: read LONGLONG: %lld, GOT: %lld\n", i, n, v );
  1015. if ( v != n )
  1016. {
  1017. printf("\t%3d: Mismatched LONGLONG: read %lld instead of %lld\n", i, v, n );
  1018. }
  1019. }
  1020. break;
  1021. #endif
  1022. }
  1023. }
  1024. timer.End();
  1025. return timer.GetDuration().GetMicrosecondsF();
  1026. }
  1027. //-----------------------------------------------------------------------------
  1028. void TestBitBufs()
  1029. {
  1030. const int repeatCount = 1024;
  1031. const int testItemCount = 1024;
  1032. const bool debugWriteReads = false;
  1033. size_t bufsize = 1024*1024;
  1034. unsigned char *buffer = (unsigned char *)malloc( bufsize );
  1035. {
  1036. bf_write bitsbuf_writer( bitsbuf, sizeof(bitsbuf) );
  1037. bitsbuf_writer.WriteBytes( bitbuf_string, sizeof(bitsbuf) );
  1038. }
  1039. {
  1040. CFastTimer timer;
  1041. printf("TestBuffer< bf_write, bf_read >: START\n" );
  1042. timer.Start();
  1043. float avgTotalWrite = 0.0f;
  1044. float avgTotalRead = 0.0f;
  1045. int seed = 1;
  1046. for ( int count = 0; count < repeatCount; ++count, ++seed )
  1047. {
  1048. V_memset( buffer, 0, bufsize );
  1049. avgTotalWrite += TestBitBufferWriter< bf_write >( buffer, bufsize, seed, testItemCount, debugWriteReads );
  1050. avgTotalRead += TestBitBufferReader< bf_read >( buffer, bufsize, seed, testItemCount, debugWriteReads );
  1051. }
  1052. timer.End();
  1053. printf("TestBuffer< bf_write, bf_read >: END: %d times, total %4.4fus, average write %4.4f, average read %4.4f\n",
  1054. repeatCount, timer.GetDuration().GetMicrosecondsF(), avgTotalWrite / repeatCount, avgTotalRead / repeatCount );
  1055. }
  1056. if ( 1 )
  1057. {
  1058. CFastTimer timer;
  1059. printf("TestBuffer< CBitWrite, bf_read >: START\n" );
  1060. timer.Start();
  1061. float avgTotalWrite = 0.0f;
  1062. float avgTotalRead = 0.0f;
  1063. int seed = 1;
  1064. for ( int count = 0; count < repeatCount; ++count, ++seed )
  1065. {
  1066. V_memset( buffer, 0, bufsize );
  1067. avgTotalWrite += TestBitBufferWriter< CBitWrite >( buffer, bufsize, seed, testItemCount, debugWriteReads );
  1068. avgTotalRead += TestBitBufferReader< bf_read >( buffer, bufsize, seed, testItemCount, debugWriteReads );
  1069. }
  1070. timer.End();
  1071. printf("TestBuffer< CBitWrite, bf_read >: END: %d times, total %4.4fus, average write %4.4f, average read %4.4f\n",
  1072. repeatCount, timer.GetDuration().GetMicrosecondsF(), avgTotalWrite / repeatCount, avgTotalRead / repeatCount );
  1073. }
  1074. free( buffer );
  1075. }
  1076. #endif //TEST_BITBUF
  1077. */