bitStream.cpp 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "core/stream/bitStream.h"
  24. #include "core/strings/stringFunctions.h"
  25. #include "math/mathIO.h"
  26. #include "console/consoleObject.h"
  27. #include "platform/platformNet.h"
  28. #include "core/bitVector.h"
  29. static BitStream gPacketStream(NULL, 0);
  30. static U8 gPacketBuffer[Net::MaxPacketDataSize];
  31. // bitstream utility functions
  32. void BitStream::clearStringBuffer()
  33. {
  34. static char stringBuf[256];
  35. stringBuf[0] = 0;
  36. // setStringBuffer( stringBuf );
  37. }
  38. void BitStream::setStringBuffer(char buffer[256])
  39. {
  40. // stringBuffer = buffer;
  41. }
  42. BitStream *BitStream::getPacketStream(U32 writeSize)
  43. {
  44. if(!writeSize)
  45. writeSize = Net::MaxPacketDataSize;
  46. gPacketStream.setBuffer(gPacketBuffer, writeSize, Net::MaxPacketDataSize);
  47. gPacketStream.setPosition(0);
  48. return &gPacketStream;
  49. }
  50. void BitStream::sendPacketStream(const NetAddress *addr)
  51. {
  52. Net::sendto(addr, gPacketStream.getBuffer(), gPacketStream.getPosition());
  53. }
  54. // CodeReview WTF is this additional IsEqual? - BJG, 3/29/07
  55. inline bool IsEqual(F32 a, F32 b) { return a == b; }
  56. ResizeBitStream::ResizeBitStream(U32 minSpace, U32 initialSize) : BitStream(NULL, 0, 0)
  57. {
  58. mMinSpace = minSpace;
  59. if(!initialSize)
  60. initialSize = minSpace * 2;
  61. U8 *buf = (U8 *) dMalloc(initialSize);
  62. setBuffer(buf, initialSize, initialSize);
  63. }
  64. ResizeBitStream::~ResizeBitStream()
  65. {
  66. dFree(mDataPtr);
  67. }
  68. void ResizeBitStream::validate()
  69. {
  70. if(getPosition() + mMinSpace > bufSize)
  71. {
  72. bufSize = getPosition() + mMinSpace * 2;
  73. mDataPtr = (U8 *) dRealloc(mDataPtr, bufSize);
  74. maxReadBitNum = bufSize << 3;
  75. maxWriteBitNum = bufSize << 3;
  76. }
  77. }
  78. class HuffmanProcessor
  79. {
  80. static const U32 csm_charFreqs[256];
  81. bool m_tablesBuilt;
  82. void buildTables();
  83. struct HuffNode {
  84. U32 pop;
  85. S16 index0;
  86. S16 index1;
  87. };
  88. struct HuffLeaf {
  89. U32 pop;
  90. U8 numBits;
  91. U8 symbol;
  92. U32 code; // no code should be longer than 32 bits.
  93. };
  94. // We have to be a bit careful with these, mSince they are pointers...
  95. struct HuffWrap {
  96. HuffNode* pNode;
  97. HuffLeaf* pLeaf;
  98. public:
  99. HuffWrap() : pNode(NULL), pLeaf(NULL) { }
  100. void set(HuffLeaf* in_leaf) { pNode = NULL; pLeaf = in_leaf; }
  101. void set(HuffNode* in_node) { pLeaf = NULL; pNode = in_node; }
  102. U32 getPop() { if (pNode) return pNode->pop; else return pLeaf->pop; }
  103. };
  104. Vector<HuffNode> m_huffNodes;
  105. Vector<HuffLeaf> m_huffLeaves;
  106. S16 determineIndex(HuffWrap&);
  107. void generateCodes(BitStream&, S32, S32);
  108. public:
  109. HuffmanProcessor() : m_tablesBuilt(false) { }
  110. static HuffmanProcessor g_huffProcessor;
  111. bool readHuffBuffer(BitStream* pStream, char* out_pBuffer, S32 maxLen);
  112. bool writeHuffBuffer(BitStream* pStream, const char* out_pBuffer, S32 maxLen);
  113. };
  114. HuffmanProcessor HuffmanProcessor::g_huffProcessor;
  115. void BitStream::setBuffer(void *bufPtr, S32 size, S32 maxSize)
  116. {
  117. mDataPtr = (U8 *) bufPtr;
  118. bitNum = 0;
  119. bufSize = size;
  120. maxReadBitNum = size << 3;
  121. if(maxSize < 0)
  122. maxSize = size;
  123. maxWriteBitNum = maxSize << 3;
  124. error = false;
  125. clearCompressionPoint();
  126. }
  127. U32 BitStream::getPosition() const
  128. {
  129. return (bitNum + 7) >> 3;
  130. }
  131. bool BitStream::setPosition(const U32 pos)
  132. {
  133. bitNum = pos << 3;
  134. return (true);
  135. }
  136. U32 BitStream::getStreamSize()
  137. {
  138. return bufSize;
  139. }
  140. U8 *BitStream::getBytePtr()
  141. {
  142. return mDataPtr + getPosition();
  143. }
  144. U32 BitStream::getReadByteSize()
  145. {
  146. return (maxReadBitNum >> 3) - getPosition();
  147. }
  148. U32 BitStream::getWriteByteSize()
  149. {
  150. return (maxWriteBitNum >> 3) - getPosition();
  151. }
  152. void BitStream::clear()
  153. {
  154. dMemset(mDataPtr, 0, bufSize);
  155. }
  156. void BitStream::writeClassId(U32 classId, U32 classType, U32 classGroup)
  157. {
  158. AssertFatal(classType < NetClassTypesCount, "Out of range class type.");
  159. AssertFatal(classGroup < NetClassGroupsCount, "Out of range class group.");
  160. AssertFatal(classId < AbstractClassRep::NetClassCount[classGroup][classType], "Out of range class id.");
  161. AssertFatal(AbstractClassRep::NetClassCount[classGroup][classType] < (1 << AbstractClassRep::NetClassBitSize[classGroup][classType]),
  162. "NetClassBitSize too small!");
  163. writeInt(classId, AbstractClassRep::NetClassBitSize[classGroup][classType]);
  164. }
  165. S32 BitStream::readClassId(U32 classType, U32 classGroup)
  166. {
  167. AssertFatal(classType < NetClassTypesCount, "Out of range class type.");
  168. AssertFatal(classGroup < NetClassGroupsCount, "Out of range class group.");
  169. AssertFatal(AbstractClassRep::NetClassCount[classGroup][classType] < (1 << AbstractClassRep::NetClassBitSize[classGroup][classType]),
  170. "NetClassBitSize too small!");
  171. S32 ret = readInt(AbstractClassRep::NetClassBitSize[classGroup][classType]);
  172. AssertFatal(ret < AbstractClassRep::NetClassCount[classGroup][classType], "BitStream::readClassId - unexpected class ID!");
  173. if(ret >= AbstractClassRep::NetClassCount[classGroup][classType])
  174. return -1;
  175. return ret;
  176. }
  177. void BitStream::writeBits(S32 bitCount, const void *bitPtr)
  178. {
  179. if(!bitCount)
  180. return;
  181. if((bitCount + bitNum) > maxWriteBitNum)
  182. {
  183. error = true;
  184. AssertFatal(false, avar("BitStream::writeBits - Out of range write [(%i+%i)/%i]", bitCount, bitNum, maxWriteBitNum));
  185. return;
  186. }
  187. // [tom, 8/17/2006] This is probably a lot lamer then it needs to be. However,
  188. // at least it doesnt clobber data or overrun the buffer like the old code did.
  189. const U8 *ptr = (U8 *)bitPtr;
  190. for(S32 srcBitNum = 0;srcBitNum < bitCount;srcBitNum++)
  191. {
  192. if((*(ptr + (srcBitNum >> 3)) & (1 << (srcBitNum & 0x7))) != 0)
  193. *(mDataPtr + (bitNum >> 3)) |= (1 << (bitNum & 0x7));
  194. else
  195. *(mDataPtr + (bitNum >> 3)) &= ~(1 << (bitNum & 0x7));
  196. bitNum++;
  197. }
  198. }
  199. void BitStream::setBit(S32 bitCount, bool set)
  200. {
  201. if(set)
  202. *(mDataPtr + (bitCount >> 3)) |= (1 << (bitCount & 0x7));
  203. else
  204. *(mDataPtr + (bitCount >> 3)) &= ~(1 << (bitCount & 0x7));
  205. }
  206. bool BitStream::testBit(S32 bitCount)
  207. {
  208. return (*(mDataPtr + (bitCount >> 3)) & (1 << (bitCount & 0x7))) != 0;
  209. }
  210. bool BitStream::writeFlag(bool val)
  211. {
  212. if((bitNum + 1) > maxWriteBitNum)
  213. {
  214. error = true;
  215. AssertFatal(false, avar("BitStream::writeFlag - Out of range write [%i/%i]", bitNum+1, maxWriteBitNum));
  216. return false;
  217. }
  218. if(val)
  219. *(mDataPtr + (bitNum >> 3)) |= (1 << (bitNum & 0x7));
  220. else
  221. *(mDataPtr + (bitNum >> 3)) &= ~(1 << (bitNum & 0x7));
  222. bitNum++;
  223. return (val);
  224. }
  225. void BitStream::readBits(S32 bitCount, void *bitPtr)
  226. {
  227. if(!bitCount)
  228. return;
  229. if(bitCount + bitNum > maxReadBitNum)
  230. {
  231. error = true;
  232. //AssertFatal(false, "Out of range read");
  233. AssertWarn(false, "Out of range read");
  234. return;
  235. }
  236. U8 *stPtr = mDataPtr + (bitNum >> 3);
  237. S32 byteCount = (bitCount + 7) >> 3;
  238. U8 *ptr = (U8 *) bitPtr;
  239. S32 downShift = bitNum & 0x7;
  240. S32 upShift = 8 - downShift;
  241. U8 curB = *stPtr;
  242. const U8 *stEnd = mDataPtr + bufSize;
  243. while(byteCount--)
  244. {
  245. stPtr++;
  246. U8 nextB = stPtr < stEnd ? *stPtr : 0;
  247. *ptr++ = (curB >> downShift) | (nextB << upShift);
  248. curB = nextB;
  249. }
  250. bitNum += bitCount;
  251. }
  252. bool BitStream::_read(U32 size, void *dataPtr)
  253. {
  254. readBits(size << 3, dataPtr);
  255. return true;
  256. }
  257. bool BitStream::_write(U32 size, const void *dataPtr)
  258. {
  259. writeBits(size << 3, dataPtr);
  260. return true;
  261. }
  262. S32 BitStream::readInt(S32 bitCount)
  263. {
  264. S32 ret = 0;
  265. readBits(bitCount, &ret);
  266. ret = convertLEndianToHost(ret);
  267. if(bitCount == 32)
  268. return ret;
  269. else
  270. ret &= (1 << bitCount) - 1;
  271. return ret;
  272. }
  273. void BitStream::writeInt(S32 val, S32 bitCount)
  274. {
  275. AssertFatal((bitCount == 32) || ((val >> bitCount) == 0), avar("BitStream::writeInt: value out of range: %i/%i (%i bits)", val, 1 << bitCount, bitCount));
  276. val = convertHostToLEndian(val);
  277. writeBits(bitCount, &val);
  278. }
  279. void BitStream::writeFloat(F32 f, S32 bitCount)
  280. {
  281. auto maxInt = (1U << bitCount) - 1;
  282. U32 i;
  283. if (f < POINT_EPSILON)
  284. {
  285. // Special case: <= 0 serializes to 0
  286. i = 0.0f;
  287. }
  288. else if (f == 0.5)
  289. {
  290. // Special case: 0.5 serializes to maxInt / 2 + 1
  291. i = maxInt / 2 + 1;
  292. }
  293. else if (f > (1.0f- POINT_EPSILON))
  294. {
  295. // Special case: >= 1 serializes to maxInt
  296. i = maxInt;
  297. }
  298. else
  299. {
  300. // Serialize normally but round the number
  301. i = static_cast<U32>(roundf(f * maxInt));
  302. }
  303. writeInt(i, bitCount);
  304. }
  305. F32 BitStream::readFloat(S32 bitCount)
  306. {
  307. auto maxInt = (1U << bitCount) - 1;
  308. auto i = static_cast<U32>(readInt(bitCount));
  309. if (i == 0)
  310. return 0;
  311. if (i == maxInt / 2 + 1)
  312. return 0.5;
  313. if (i == maxInt)
  314. return 1;
  315. return i / static_cast<F32>(maxInt);
  316. }
  317. void BitStream::writeSignedFloat(F32 f, S32 bitCount)
  318. {
  319. writeFloat((f + 1) / 2, bitCount);
  320. }
  321. F32 BitStream::readSignedFloat(S32 bitCount)
  322. {
  323. return readFloat(bitCount) * 2 - 1;
  324. }
  325. void BitStream::writeSignedInt(S32 value, S32 bitCount)
  326. {
  327. if(writeFlag(value < 0))
  328. writeInt(-value, bitCount - 1);
  329. else
  330. writeInt(value, bitCount - 1);
  331. }
  332. S32 BitStream::readSignedInt(S32 bitCount)
  333. {
  334. if(readFlag())
  335. return -readInt(bitCount - 1);
  336. else
  337. return readInt(bitCount - 1);
  338. }
  339. void BitStream::writeNormalVector(const Point3F& vec, S32 bitCount)
  340. {
  341. F32 phi = mAtan2(vec.x, vec.y) / M_PI;
  342. F32 theta = mAtan2(vec.z, mSqrt(vec.x*vec.x + vec.y*vec.y)) / (M_PI/2.0);
  343. writeSignedFloat(phi, bitCount+1);
  344. writeSignedFloat(theta, bitCount);
  345. }
  346. void BitStream::readNormalVector(Point3F *vec, S32 bitCount)
  347. {
  348. F32 phi = readSignedFloat(bitCount+1) * M_PI;
  349. F32 theta = readSignedFloat(bitCount) * (M_PI/2.0);
  350. vec->x = mSin(phi)*mCos(theta);
  351. vec->y = mCos(phi)*mCos(theta);
  352. vec->z = mSin(theta);
  353. }
  354. Point3F BitStream::dumbDownNormal(const Point3F& vec, S32 bitCount)
  355. {
  356. U8 buffer[128];
  357. BitStream temp(buffer, 128);
  358. temp.writeNormalVector(vec, bitCount);
  359. temp.setCurPos(0);
  360. Point3F ret;
  361. temp.readNormalVector(&ret, bitCount);
  362. return ret;
  363. }
  364. void BitStream::writeVector( Point3F vec, F32 maxMag, S32 magBits, S32 normalBits )
  365. {
  366. F32 mag = vec.len();
  367. // If its zero length then we're done.
  368. if ( !writeFlag( mag > 0.0f ) )
  369. return;
  370. // Write the magnitude compressed unless its greater than the maximum.
  371. if ( writeFlag( mag < maxMag ) )
  372. writeFloat( mag / maxMag, magBits );
  373. else
  374. write( mag );
  375. // Finally write the normal part.
  376. vec *= 1.0f / mag;
  377. writeNormalVector( vec, normalBits );
  378. }
  379. void BitStream::readVector( Point3F *outVec, F32 maxMag, S32 magBits, S32 normalBits )
  380. {
  381. // Nothing more to do if we got a zero length vector.
  382. if ( !readFlag() )
  383. {
  384. outVec->set(0,0,0);
  385. return;
  386. }
  387. // Read the compressed or uncompressed magnitude.
  388. F32 mag;
  389. if ( readFlag() )
  390. mag = readFloat( magBits ) * maxMag;
  391. else
  392. read( &mag );
  393. // Finally read the normal and reconstruct the vector.
  394. readNormalVector( outVec, normalBits );
  395. *outVec *= mag;
  396. }
  397. void BitStream::writeAffineTransform(const MatrixF& matrix)
  398. {
  399. // AssertFatal(matrix.isAffine() == true,
  400. // "BitStream::writeAffineTransform: Error, must write only affine transforms!");
  401. Point3F pos;
  402. matrix.getColumn(3, &pos);
  403. mathWrite(*this, pos);
  404. QuatF q(matrix);
  405. q.normalize();
  406. write(q.x);
  407. write(q.y);
  408. write(q.z);
  409. writeFlag(q.w < 0.0);
  410. }
  411. void BitStream::readAffineTransform(MatrixF* matrix)
  412. {
  413. Point3F pos;
  414. QuatF q;
  415. mathRead(*this, &pos);
  416. read(&q.x);
  417. read(&q.y);
  418. read(&q.z);
  419. q.w = mSqrt(1.0 - getMin(F32(((q.x * q.x) + (q.y * q.y) + (q.z * q.z))), 1.f));
  420. if (readFlag())
  421. q.w = -q.w;
  422. q.setMatrix(matrix);
  423. matrix->setColumn(3, pos);
  424. // AssertFatal(matrix->isAffine() == true,
  425. // "BitStream::readAffineTransform: Error, transform should be affine after this function!");
  426. }
  427. void BitStream::writeQuat( const QuatF& quat, U32 bitCount )
  428. {
  429. F32 quatVals[4] = { quat.x, quat.y, quat.z, quat.w };
  430. bool flipQuat = (quatVals[0] < 0);
  431. F32 maxVal = mFabs(quatVals[0]);
  432. S32 idxMax = 0;
  433. for (S32 i = 1; i < 4; ++i)
  434. {
  435. if (mFabs(quatVals[i]) > maxVal)
  436. {
  437. idxMax = i;
  438. maxVal = mFabs(quatVals[i]);
  439. flipQuat = (quatVals[i] < 0);
  440. }
  441. }
  442. writeInt(idxMax, 2);
  443. for (S32 i = 0; i < 4; ++i)
  444. {
  445. if (i == idxMax)
  446. continue;
  447. F32 curValue = (flipQuat ? -quatVals[i] : quatVals[i]) * (F32) M_SQRT2;
  448. writeSignedFloat( curValue, bitCount );
  449. }
  450. }
  451. void BitStream::readQuat( QuatF *outQuat, U32 bitCount )
  452. {
  453. F32 quatVals[4];
  454. F32 sum = 0.0f;
  455. S32 idxMax = readInt( 2 );
  456. for (S32 i = 0; i < 4; ++i)
  457. {
  458. if (i == idxMax)
  459. continue;
  460. quatVals[i] = readSignedFloat( bitCount ) * M_SQRTHALF_F;
  461. sum += quatVals[i] * quatVals[i];
  462. }
  463. if (sum > 1.0f)
  464. quatVals[idxMax] = 1.0f;
  465. else
  466. quatVals[idxMax] = mSqrt(1.0f - sum);
  467. outQuat->set(quatVals[0], quatVals[1], quatVals[2], quatVals[3]);
  468. }
  469. void BitStream::writeBits( const BitVector &bitvec )
  470. {
  471. U32 size = bitvec.getSize();
  472. if ( writeFlag( size <= 127 ) )
  473. writeInt( size, 7 );
  474. else
  475. write( size );
  476. writeBits( bitvec.getSize(), bitvec.getBits() );
  477. }
  478. void BitStream::readBits( BitVector *bitvec )
  479. {
  480. U32 size;
  481. if ( readFlag() ) // size <= 127
  482. size = readInt( 7 );
  483. else
  484. read( &size );
  485. bitvec->setSize( size );
  486. readBits( size, bitvec->getBits() );
  487. }
  488. //----------------------------------------------------------------------------
  489. void BitStream::clearCompressionPoint()
  490. {
  491. mCompressPoint.set(0,0,0);
  492. }
  493. void BitStream::setCompressionPoint(const Point3F& p)
  494. {
  495. mCompressPoint = p;
  496. }
  497. static U32 gBitCounts[4] = {
  498. 16, 18, 20, 32
  499. };
  500. void BitStream::writeCompressedPoint(const Point3F& p,F32 scale)
  501. {
  502. // Same # of bits for all axis
  503. Point3F vec;
  504. F32 invScale = 1 / scale;
  505. U32 type;
  506. vec = p - mCompressPoint;
  507. F32 dist = vec.len() * invScale;
  508. if(dist < (1 << 15))
  509. type = 0;
  510. else if(dist < (1 << 17))
  511. type = 1;
  512. else if(dist < (1 << 19))
  513. type = 2;
  514. else
  515. type = 3;
  516. writeInt(type, 2);
  517. if (type != 3)
  518. {
  519. type = gBitCounts[type];
  520. writeSignedInt(S32(vec.x * invScale + 0.5f),type);
  521. writeSignedInt(S32(vec.y * invScale + 0.5f),type);
  522. writeSignedInt(S32(vec.z * invScale + 0.5f),type);
  523. }
  524. else
  525. {
  526. write(p.x);
  527. write(p.y);
  528. write(p.z);
  529. }
  530. }
  531. void BitStream::readCompressedPoint(Point3F* p,F32 scale)
  532. {
  533. // Same # of bits for all axis
  534. U32 type = readInt(2);
  535. if(type == 3)
  536. {
  537. read(&p->x);
  538. read(&p->y);
  539. read(&p->z);
  540. }
  541. else
  542. {
  543. type = gBitCounts[type];
  544. p->x = (F32)readSignedInt(type);
  545. p->y = (F32)readSignedInt(type);
  546. p->z = (F32)readSignedInt(type);
  547. p->x = mCompressPoint.x + p->x * scale;
  548. p->y = mCompressPoint.y + p->y * scale;
  549. p->z = mCompressPoint.z + p->z * scale;
  550. }
  551. }
  552. //------------------------------------------------------------------------------
  553. InfiniteBitStream::InfiniteBitStream()
  554. {
  555. //
  556. }
  557. InfiniteBitStream::~InfiniteBitStream()
  558. {
  559. //
  560. }
  561. void InfiniteBitStream::reset()
  562. {
  563. // Rewing back to beginning
  564. setPosition(0);
  565. }
  566. void InfiniteBitStream::validate(U32 upcomingBytes)
  567. {
  568. if(getPosition() + upcomingBytes + mMinSpace > bufSize)
  569. {
  570. bufSize = getPosition() + upcomingBytes + mMinSpace;
  571. mDataPtr = (U8 *) dRealloc(mDataPtr, bufSize);
  572. maxReadBitNum = bufSize << 3;
  573. maxWriteBitNum = bufSize << 3;
  574. }
  575. }
  576. void InfiniteBitStream::compact()
  577. {
  578. // Prepare to copy...
  579. U32 oldSize = bufSize;
  580. U8 *tmp = (U8*)dMalloc(bufSize);
  581. // Copy things...
  582. bufSize = getPosition() + mMinSpace * 2;
  583. dMemcpy(tmp, mDataPtr, oldSize);
  584. // And clean up.
  585. dFree(mDataPtr);
  586. mDataPtr = tmp;
  587. maxReadBitNum = bufSize << 3;
  588. maxWriteBitNum = bufSize << 3;
  589. }
  590. void InfiniteBitStream::writeToStream(Stream &s)
  591. {
  592. s.write(getPosition(), mDataPtr);
  593. }
  594. //------------------------------------------------------------------------------
  595. void BitStream::readString(char buf[256])
  596. {
  597. if(stringBuffer)
  598. {
  599. if(readFlag())
  600. {
  601. S32 offset = readInt(8);
  602. HuffmanProcessor::g_huffProcessor.readHuffBuffer(this, stringBuffer + offset, 256 - offset);
  603. dStrcpy(buf, stringBuffer, 256);
  604. return;
  605. }
  606. }
  607. HuffmanProcessor::g_huffProcessor.readHuffBuffer(this, buf, 256);
  608. if(stringBuffer)
  609. dStrcpy(stringBuffer, buf, 256);
  610. }
  611. void BitStream::writeString(const char *string, S32 maxLen)
  612. {
  613. if(!string)
  614. string = "";
  615. if(stringBuffer)
  616. {
  617. S32 j;
  618. for(j = 0; j < maxLen && stringBuffer[j] == string[j] && string[j];j++)
  619. ;
  620. dStrncpy(stringBuffer, string, maxLen);
  621. stringBuffer[maxLen] = 0;
  622. if(writeFlag(j > 2))
  623. {
  624. writeInt(j, 8);
  625. HuffmanProcessor::g_huffProcessor.writeHuffBuffer(this, string + j, maxLen - j);
  626. return;
  627. }
  628. }
  629. HuffmanProcessor::g_huffProcessor.writeHuffBuffer(this, string, maxLen);
  630. }
  631. void HuffmanProcessor::buildTables()
  632. {
  633. AssertFatal(m_tablesBuilt == false, "Cannot build tables twice!");
  634. m_tablesBuilt = true;
  635. S32 i;
  636. // First, construct the array of wraps...
  637. //
  638. m_huffLeaves.setSize(256);
  639. m_huffNodes.reserve(256);
  640. m_huffNodes.increment();
  641. for (i = 0; i < 256; i++) {
  642. HuffLeaf& rLeaf = m_huffLeaves[i];
  643. rLeaf.pop = csm_charFreqs[i] + 1;
  644. rLeaf.symbol = U8(i);
  645. dMemset(&rLeaf.code, 0, sizeof(rLeaf.code));
  646. rLeaf.numBits = 0;
  647. }
  648. S32 currWraps = 256;
  649. HuffWrap* pWrap = new HuffWrap[256];
  650. for (i = 0; i < 256; i++) {
  651. pWrap[i].set(&m_huffLeaves[i]);
  652. }
  653. while (currWraps != 1) {
  654. U32 min1 = 0xfffffffe, min2 = 0xffffffff;
  655. S32 index1 = -1, index2 = -1;
  656. for (i = 0; i < currWraps; i++) {
  657. if (pWrap[i].getPop() < min1) {
  658. min2 = min1;
  659. index2 = index1;
  660. min1 = pWrap[i].getPop();
  661. index1 = i;
  662. } else if (pWrap[i].getPop() < min2) {
  663. min2 = pWrap[i].getPop();
  664. index2 = i;
  665. }
  666. }
  667. AssertFatal(index1 != -1 && index2 != -1 && index1 != index2, "hrph");
  668. // Create a node for this...
  669. m_huffNodes.increment();
  670. HuffNode& rNode = m_huffNodes.last();
  671. rNode.pop = pWrap[index1].getPop() + pWrap[index2].getPop();
  672. rNode.index0 = determineIndex(pWrap[index1]);
  673. rNode.index1 = determineIndex(pWrap[index2]);
  674. S32 mergeIndex = index1 > index2 ? index2 : index1;
  675. S32 nukeIndex = index1 > index2 ? index1 : index2;
  676. pWrap[mergeIndex].set(&rNode);
  677. if (index2 != (currWraps - 1)) {
  678. pWrap[nukeIndex] = pWrap[currWraps - 1];
  679. }
  680. currWraps--;
  681. }
  682. AssertFatal(currWraps == 1, "wrong wraps?");
  683. AssertFatal(pWrap[0].pNode != NULL && pWrap[0].pLeaf == NULL, "Wrong wrap type!");
  684. // Ok, now we have one wrap, which is a node. we need to make sure that this
  685. // is the first node in the node list.
  686. m_huffNodes[0] = *(pWrap[0].pNode);
  687. delete [] pWrap;
  688. U32 code = 0;
  689. BitStream bs(&code, 4);
  690. generateCodes(bs, 0, 0);
  691. }
  692. void HuffmanProcessor::generateCodes(BitStream& rBS, S32 index, S32 depth)
  693. {
  694. if (index < 0) {
  695. // leaf node, copy the code in, and back out...
  696. HuffLeaf& rLeaf = m_huffLeaves[-(index + 1)];
  697. dMemcpy(&rLeaf.code, rBS.mDataPtr, sizeof(rLeaf.code));
  698. rLeaf.numBits = depth;
  699. } else {
  700. HuffNode& rNode = m_huffNodes[index];
  701. S32 pos = rBS.getCurPos();
  702. rBS.writeFlag(false);
  703. generateCodes(rBS, rNode.index0, depth + 1);
  704. rBS.setCurPos(pos);
  705. rBS.writeFlag(true);
  706. generateCodes(rBS, rNode.index1, depth + 1);
  707. rBS.setCurPos(pos);
  708. }
  709. }
  710. S16 HuffmanProcessor::determineIndex(HuffWrap& rWrap)
  711. {
  712. if (rWrap.pLeaf != NULL) {
  713. AssertFatal(rWrap.pNode == NULL, "Got a non-NULL pNode in a HuffWrap with a non-NULL leaf.");
  714. return -((rWrap.pLeaf - m_huffLeaves.address()) + 1);
  715. } else {
  716. AssertFatal(rWrap.pNode != NULL, "Got a NULL pNode in a HuffWrap with a NULL leaf.");
  717. return rWrap.pNode - m_huffNodes.address();
  718. }
  719. }
  720. bool HuffmanProcessor::readHuffBuffer(BitStream* pStream, char* out_pBuffer, S32 maxLen=256)
  721. {
  722. if (m_tablesBuilt == false)
  723. buildTables();
  724. if (pStream->readFlag()) {
  725. S32 len = pStream->readInt(8);
  726. if (len >= maxLen) {
  727. len = maxLen;
  728. }
  729. for (S32 i = 0; i < len; i++) {
  730. S32 index = 0;
  731. while (true) {
  732. if (index >= 0) {
  733. if (pStream->readFlag() == true) {
  734. index = m_huffNodes[index].index1;
  735. } else {
  736. index = m_huffNodes[index].index0;
  737. }
  738. } else {
  739. out_pBuffer[i] = m_huffLeaves[-(index+1)].symbol;
  740. break;
  741. }
  742. }
  743. }
  744. out_pBuffer[len] = '\0';
  745. return true;
  746. } else {
  747. // Uncompressed string...
  748. U32 len = pStream->readInt(8);
  749. if (len >= maxLen) {
  750. len = maxLen;
  751. }
  752. pStream->read(len, out_pBuffer);
  753. out_pBuffer[len] = '\0';
  754. return true;
  755. }
  756. }
  757. bool HuffmanProcessor::writeHuffBuffer(BitStream* pStream, const char* out_pBuffer, S32 maxLen)
  758. {
  759. if (out_pBuffer == NULL) {
  760. pStream->writeFlag(false);
  761. pStream->writeInt(0, 8);
  762. return true;
  763. }
  764. if (m_tablesBuilt == false)
  765. buildTables();
  766. S32 len = out_pBuffer ? dStrlen(out_pBuffer) : 0;
  767. AssertWarn(len <= 255, "String TOO long for writeString");
  768. AssertWarn(len <= 255, out_pBuffer);
  769. if (len > maxLen)
  770. len = maxLen;
  771. S32 numBits = 0;
  772. S32 i;
  773. for (i = 0; i < len; i++)
  774. numBits += m_huffLeaves[(unsigned char)out_pBuffer[i]].numBits;
  775. if (numBits >= (len * 8)) {
  776. pStream->writeFlag(false);
  777. pStream->writeInt(len, 8);
  778. pStream->write(len, out_pBuffer);
  779. } else {
  780. pStream->writeFlag(true);
  781. pStream->writeInt(len, 8);
  782. for (i = 0; i < len; i++) {
  783. HuffLeaf& rLeaf = m_huffLeaves[((unsigned char)out_pBuffer[i])];
  784. pStream->writeBits(rLeaf.numBits, &rLeaf.code);
  785. }
  786. }
  787. return true;
  788. }
  789. const U32 HuffmanProcessor::csm_charFreqs[256] = {
  790. 0 ,
  791. 0 ,
  792. 0 ,
  793. 0 ,
  794. 0 ,
  795. 0 ,
  796. 0 ,
  797. 0 ,
  798. 0 ,
  799. 329 ,
  800. 21 ,
  801. 0 ,
  802. 0 ,
  803. 0 ,
  804. 0 ,
  805. 0 ,
  806. 0 ,
  807. 0 ,
  808. 0 ,
  809. 0 ,
  810. 0 ,
  811. 0 ,
  812. 0 ,
  813. 0 ,
  814. 0 ,
  815. 0 ,
  816. 0 ,
  817. 0 ,
  818. 0 ,
  819. 0 ,
  820. 0 ,
  821. 0 ,
  822. 2809 ,
  823. 68 ,
  824. 0 ,
  825. 27 ,
  826. 0 ,
  827. 58 ,
  828. 3 ,
  829. 62 ,
  830. 4 ,
  831. 7 ,
  832. 0 ,
  833. 0 ,
  834. 15 ,
  835. 65 ,
  836. 554 ,
  837. 3 ,
  838. 394 ,
  839. 404 ,
  840. 189 ,
  841. 117 ,
  842. 30 ,
  843. 51 ,
  844. 27 ,
  845. 15 ,
  846. 34 ,
  847. 32 ,
  848. 80 ,
  849. 1 ,
  850. 142 ,
  851. 3 ,
  852. 142 ,
  853. 39 ,
  854. 0 ,
  855. 144 ,
  856. 125 ,
  857. 44 ,
  858. 122 ,
  859. 275 ,
  860. 70 ,
  861. 135 ,
  862. 61 ,
  863. 127 ,
  864. 8 ,
  865. 12 ,
  866. 113 ,
  867. 246 ,
  868. 122 ,
  869. 36 ,
  870. 185 ,
  871. 1 ,
  872. 149 ,
  873. 309 ,
  874. 335 ,
  875. 12 ,
  876. 11 ,
  877. 14 ,
  878. 54 ,
  879. 151 ,
  880. 0 ,
  881. 0 ,
  882. 2 ,
  883. 0 ,
  884. 0 ,
  885. 211 ,
  886. 0 ,
  887. 2090 ,
  888. 344 ,
  889. 736 ,
  890. 993 ,
  891. 2872 ,
  892. 701 ,
  893. 605 ,
  894. 646 ,
  895. 1552 ,
  896. 328 ,
  897. 305 ,
  898. 1240 ,
  899. 735 ,
  900. 1533 ,
  901. 1713 ,
  902. 562 ,
  903. 3 ,
  904. 1775 ,
  905. 1149 ,
  906. 1469 ,
  907. 979 ,
  908. 407 ,
  909. 553 ,
  910. 59 ,
  911. 279 ,
  912. 31 ,
  913. 0 ,
  914. 0 ,
  915. 0 ,
  916. 68 ,
  917. 0 ,
  918. 0 ,
  919. 0 ,
  920. 0 ,
  921. 0 ,
  922. 0 ,
  923. 0 ,
  924. 0 ,
  925. 0 ,
  926. 0 ,
  927. 0 ,
  928. 0 ,
  929. 0 ,
  930. 0 ,
  931. 0 ,
  932. 0 ,
  933. 0 ,
  934. 0 ,
  935. 0 ,
  936. 0 ,
  937. 0 ,
  938. 0 ,
  939. 0 ,
  940. 0 ,
  941. 0 ,
  942. 0 ,
  943. 0 ,
  944. 0 ,
  945. 0 ,
  946. 0 ,
  947. 0 ,
  948. 0 ,
  949. 0 ,
  950. 0 ,
  951. 0 ,
  952. 0 ,
  953. 0 ,
  954. 0 ,
  955. 0 ,
  956. 0 ,
  957. 0 ,
  958. 0 ,
  959. 0 ,
  960. 0 ,
  961. 0 ,
  962. 0 ,
  963. 0 ,
  964. 0 ,
  965. 0 ,
  966. 0 ,
  967. 0 ,
  968. 0 ,
  969. 0 ,
  970. 0 ,
  971. 0 ,
  972. 0 ,
  973. 0 ,
  974. 0 ,
  975. 0 ,
  976. 0 ,
  977. 0 ,
  978. 0 ,
  979. 0 ,
  980. 0 ,
  981. 0 ,
  982. 0 ,
  983. 0 ,
  984. 0 ,
  985. 0 ,
  986. 0 ,
  987. 0 ,
  988. 0 ,
  989. 0 ,
  990. 0 ,
  991. 0 ,
  992. 0 ,
  993. 0 ,
  994. 0 ,
  995. 0 ,
  996. 0 ,
  997. 0 ,
  998. 0 ,
  999. 0 ,
  1000. 0 ,
  1001. 0 ,
  1002. 0 ,
  1003. 0 ,
  1004. 0 ,
  1005. 0 ,
  1006. 0 ,
  1007. 0 ,
  1008. 0 ,
  1009. 0 ,
  1010. 0 ,
  1011. 0 ,
  1012. 0 ,
  1013. 0 ,
  1014. 0 ,
  1015. 0 ,
  1016. 0 ,
  1017. 0 ,
  1018. 0 ,
  1019. 0 ,
  1020. 0 ,
  1021. 0 ,
  1022. 0 ,
  1023. 0 ,
  1024. 0 ,
  1025. 0 ,
  1026. 0 ,
  1027. 0 ,
  1028. 0 ,
  1029. 0 ,
  1030. 0 ,
  1031. 0 ,
  1032. 0 ,
  1033. 0 ,
  1034. 0 ,
  1035. 0 ,
  1036. 0 ,
  1037. 0 ,
  1038. 0 ,
  1039. 0 ,
  1040. 0 ,
  1041. 0 ,
  1042. 0 ,
  1043. 0 ,
  1044. 0 ,
  1045. 0
  1046. };