b3Serializer.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #ifndef B3_SERIALIZER_H
  14. #define B3_SERIALIZER_H
  15. #include "Bullet3Common/b3Scalar.h" // has definitions like B3_FORCE_INLINE
  16. #include "Bullet3Common/b3StackAlloc.h"
  17. #include "Bullet3Common/b3HashMap.h"
  18. #if !defined( __CELLOS_LV2__) && !defined(__MWERKS__)
  19. #include <memory.h>
  20. #endif
  21. #include <string.h>
  22. extern char b3s_bulletDNAstr[];
  23. extern int b3s_bulletDNAlen;
  24. extern char b3s_bulletDNAstr64[];
  25. extern int b3s_bulletDNAlen64;
  26. B3_FORCE_INLINE int b3StrLen(const char* str)
  27. {
  28. if (!str)
  29. return(0);
  30. int len = 0;
  31. while (*str != 0)
  32. {
  33. str++;
  34. len++;
  35. }
  36. return len;
  37. }
  38. class b3Chunk
  39. {
  40. public:
  41. int m_chunkCode;
  42. int m_length;
  43. void *m_oldPtr;
  44. int m_dna_nr;
  45. int m_number;
  46. };
  47. enum b3SerializationFlags
  48. {
  49. B3_SERIALIZE_NO_BVH = 1,
  50. B3_SERIALIZE_NO_TRIANGLEINFOMAP = 2,
  51. B3_SERIALIZE_NO_DUPLICATE_ASSERT = 4
  52. };
  53. class b3Serializer
  54. {
  55. public:
  56. virtual ~b3Serializer() {}
  57. virtual const unsigned char* getBufferPointer() const = 0;
  58. virtual int getCurrentBufferSize() const = 0;
  59. virtual b3Chunk* allocate(size_t size, int numElements) = 0;
  60. virtual void finalizeChunk(b3Chunk* chunk, const char* structType, int chunkCode,void* oldPtr)= 0;
  61. virtual void* findPointer(void* oldPtr) = 0;
  62. virtual void* getUniquePointer(void*oldPtr) = 0;
  63. virtual void startSerialization() = 0;
  64. virtual void finishSerialization() = 0;
  65. virtual const char* findNameForPointer(const void* ptr) const = 0;
  66. virtual void registerNameForPointer(const void* ptr, const char* name) = 0;
  67. virtual void serializeName(const char* ptr) = 0;
  68. virtual int getSerializationFlags() const = 0;
  69. virtual void setSerializationFlags(int flags) = 0;
  70. };
  71. #define B3_HEADER_LENGTH 12
  72. #if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
  73. # define B3_MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
  74. #else
  75. # define B3_MAKE_ID(a,b,c,d) ( (int)(d)<<24 | (int)(c)<<16 | (b)<<8 | (a) )
  76. #endif
  77. #define B3_SOFTBODY_CODE B3_MAKE_ID('S','B','D','Y')
  78. #define B3_COLLISIONOBJECT_CODE B3_MAKE_ID('C','O','B','J')
  79. #define B3_RIGIDBODY_CODE B3_MAKE_ID('R','B','D','Y')
  80. #define B3_CONSTRAINT_CODE B3_MAKE_ID('C','O','N','S')
  81. #define B3_BOXSHAPE_CODE B3_MAKE_ID('B','O','X','S')
  82. #define B3_QUANTIZED_BVH_CODE B3_MAKE_ID('Q','B','V','H')
  83. #define B3_TRIANLGE_INFO_MAP B3_MAKE_ID('T','M','A','P')
  84. #define B3_SHAPE_CODE B3_MAKE_ID('S','H','A','P')
  85. #define B3_ARRAY_CODE B3_MAKE_ID('A','R','A','Y')
  86. #define B3_SBMATERIAL_CODE B3_MAKE_ID('S','B','M','T')
  87. #define B3_SBNODE_CODE B3_MAKE_ID('S','B','N','D')
  88. #define B3_DYNAMICSWORLD_CODE B3_MAKE_ID('D','W','L','D')
  89. #define B3_DNA_CODE B3_MAKE_ID('D','N','A','1')
  90. struct b3PointerUid
  91. {
  92. union
  93. {
  94. void* m_ptr;
  95. int m_uniqueIds[2];
  96. };
  97. };
  98. ///The b3DefaultSerializer is the main Bullet serialization class.
  99. ///The constructor takes an optional argument for backwards compatibility, it is recommended to leave this empty/zero.
  100. class b3DefaultSerializer : public b3Serializer
  101. {
  102. b3AlignedObjectArray<char*> mTypes;
  103. b3AlignedObjectArray<short*> mStructs;
  104. b3AlignedObjectArray<short> mTlens;
  105. b3HashMap<b3HashInt, int> mStructReverse;
  106. b3HashMap<b3HashString,int> mTypeLookup;
  107. b3HashMap<b3HashPtr,void*> m_chunkP;
  108. b3HashMap<b3HashPtr,const char*> m_nameMap;
  109. b3HashMap<b3HashPtr,b3PointerUid> m_uniquePointers;
  110. int m_uniqueIdGenerator;
  111. int m_totalSize;
  112. unsigned char* m_buffer;
  113. int m_currentSize;
  114. void* m_dna;
  115. int m_dnaLength;
  116. int m_serializationFlags;
  117. b3AlignedObjectArray<b3Chunk*> m_chunkPtrs;
  118. protected:
  119. virtual void* findPointer(void* oldPtr)
  120. {
  121. void** ptr = m_chunkP.find(oldPtr);
  122. if (ptr && *ptr)
  123. return *ptr;
  124. return 0;
  125. }
  126. void writeDNA()
  127. {
  128. b3Chunk* dnaChunk = allocate(m_dnaLength,1);
  129. memcpy(dnaChunk->m_oldPtr,m_dna,m_dnaLength);
  130. finalizeChunk(dnaChunk,"DNA1",B3_DNA_CODE, m_dna);
  131. }
  132. int getReverseType(const char *type) const
  133. {
  134. b3HashString key(type);
  135. const int* valuePtr = mTypeLookup.find(key);
  136. if (valuePtr)
  137. return *valuePtr;
  138. return -1;
  139. }
  140. void initDNA(const char* bdnaOrg,int dnalen)
  141. {
  142. ///was already initialized
  143. if (m_dna)
  144. return;
  145. int littleEndian= 1;
  146. littleEndian= ((char*)&littleEndian)[0];
  147. m_dna = b3AlignedAlloc(dnalen,16);
  148. memcpy(m_dna,bdnaOrg,dnalen);
  149. m_dnaLength = dnalen;
  150. int *intPtr=0;
  151. short *shtPtr=0;
  152. char *cp = 0;int dataLen =0;
  153. intPtr = (int*)m_dna;
  154. /*
  155. SDNA (4 bytes) (magic number)
  156. NAME (4 bytes)
  157. <nr> (4 bytes) amount of names (int)
  158. <string>
  159. <string>
  160. */
  161. if (strncmp((const char*)m_dna, "SDNA", 4)==0)
  162. {
  163. // skip ++ NAME
  164. intPtr++; intPtr++;
  165. }
  166. // Parse names
  167. if (!littleEndian)
  168. *intPtr = b3SwapEndian(*intPtr);
  169. dataLen = *intPtr;
  170. intPtr++;
  171. cp = (char*)intPtr;
  172. int i;
  173. for ( i=0; i<dataLen; i++)
  174. {
  175. while (*cp)cp++;
  176. cp++;
  177. }
  178. cp = b3AlignPointer(cp,4);
  179. /*
  180. TYPE (4 bytes)
  181. <nr> amount of types (int)
  182. <string>
  183. <string>
  184. */
  185. intPtr = (int*)cp;
  186. b3Assert(strncmp(cp, "TYPE", 4)==0); intPtr++;
  187. if (!littleEndian)
  188. *intPtr = b3SwapEndian(*intPtr);
  189. dataLen = *intPtr;
  190. intPtr++;
  191. cp = (char*)intPtr;
  192. for (i=0; i<dataLen; i++)
  193. {
  194. mTypes.push_back(cp);
  195. while (*cp)cp++;
  196. cp++;
  197. }
  198. cp = b3AlignPointer(cp,4);
  199. /*
  200. TLEN (4 bytes)
  201. <len> (short) the lengths of types
  202. <len>
  203. */
  204. // Parse type lens
  205. intPtr = (int*)cp;
  206. b3Assert(strncmp(cp, "TLEN", 4)==0); intPtr++;
  207. dataLen = (int)mTypes.size();
  208. shtPtr = (short*)intPtr;
  209. for (i=0; i<dataLen; i++, shtPtr++)
  210. {
  211. if (!littleEndian)
  212. shtPtr[0] = b3SwapEndian(shtPtr[0]);
  213. mTlens.push_back(shtPtr[0]);
  214. }
  215. if (dataLen & 1) shtPtr++;
  216. /*
  217. STRC (4 bytes)
  218. <nr> amount of structs (int)
  219. <typenr>
  220. <nr_of_elems>
  221. <typenr>
  222. <namenr>
  223. <typenr>
  224. <namenr>
  225. */
  226. intPtr = (int*)shtPtr;
  227. cp = (char*)intPtr;
  228. b3Assert(strncmp(cp, "STRC", 4)==0); intPtr++;
  229. if (!littleEndian)
  230. *intPtr = b3SwapEndian(*intPtr);
  231. dataLen = *intPtr ;
  232. intPtr++;
  233. shtPtr = (short*)intPtr;
  234. for (i=0; i<dataLen; i++)
  235. {
  236. mStructs.push_back (shtPtr);
  237. if (!littleEndian)
  238. {
  239. shtPtr[0]= b3SwapEndian(shtPtr[0]);
  240. shtPtr[1]= b3SwapEndian(shtPtr[1]);
  241. int len = shtPtr[1];
  242. shtPtr+= 2;
  243. for (int a=0; a<len; a++, shtPtr+=2)
  244. {
  245. shtPtr[0]= b3SwapEndian(shtPtr[0]);
  246. shtPtr[1]= b3SwapEndian(shtPtr[1]);
  247. }
  248. } else
  249. {
  250. shtPtr+= (2*shtPtr[1])+2;
  251. }
  252. }
  253. // build reverse lookups
  254. for (i=0; i<(int)mStructs.size(); i++)
  255. {
  256. short *strc = mStructs.at(i);
  257. mStructReverse.insert(strc[0], i);
  258. mTypeLookup.insert(b3HashString(mTypes[strc[0]]),i);
  259. }
  260. }
  261. public:
  262. b3DefaultSerializer(int totalSize=0)
  263. :m_totalSize(totalSize),
  264. m_currentSize(0),
  265. m_dna(0),
  266. m_dnaLength(0),
  267. m_serializationFlags(0)
  268. {
  269. m_buffer = m_totalSize?(unsigned char*)b3AlignedAlloc(totalSize,16):0;
  270. const bool VOID_IS_8 = ((sizeof(void*)==8));
  271. #ifdef B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
  272. if (VOID_IS_8)
  273. {
  274. #if _WIN64
  275. initDNA((const char*)b3s_bulletDNAstr64,b3s_bulletDNAlen64);
  276. #else
  277. b3Assert(0);
  278. #endif
  279. } else
  280. {
  281. #ifndef _WIN64
  282. initDNA((const char*)b3s_bulletDNAstr,b3s_bulletDNAlen);
  283. #else
  284. b3Assert(0);
  285. #endif
  286. }
  287. #else //B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
  288. if (VOID_IS_8)
  289. {
  290. initDNA((const char*)b3s_bulletDNAstr64,b3s_bulletDNAlen64);
  291. } else
  292. {
  293. initDNA((const char*)b3s_bulletDNAstr,b3s_bulletDNAlen);
  294. }
  295. #endif //B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
  296. }
  297. virtual ~b3DefaultSerializer()
  298. {
  299. if (m_buffer)
  300. b3AlignedFree(m_buffer);
  301. if (m_dna)
  302. b3AlignedFree(m_dna);
  303. }
  304. void writeHeader(unsigned char* buffer) const
  305. {
  306. #ifdef B3_USE_DOUBLE_PRECISION
  307. memcpy(buffer, "BULLETd", 7);
  308. #else
  309. memcpy(buffer, "BULLETf", 7);
  310. #endif //B3_USE_DOUBLE_PRECISION
  311. int littleEndian= 1;
  312. littleEndian= ((char*)&littleEndian)[0];
  313. if (sizeof(void*)==8)
  314. {
  315. buffer[7] = '-';
  316. } else
  317. {
  318. buffer[7] = '_';
  319. }
  320. if (littleEndian)
  321. {
  322. buffer[8]='v';
  323. } else
  324. {
  325. buffer[8]='V';
  326. }
  327. buffer[9] = '2';
  328. buffer[10] = '8';
  329. buffer[11] = '1';
  330. }
  331. virtual void startSerialization()
  332. {
  333. m_uniqueIdGenerator= 1;
  334. if (m_totalSize)
  335. {
  336. unsigned char* buffer = internalAlloc(B3_HEADER_LENGTH);
  337. writeHeader(buffer);
  338. }
  339. }
  340. virtual void finishSerialization()
  341. {
  342. writeDNA();
  343. //if we didn't pre-allocate a buffer, we need to create a contiguous buffer now
  344. int mysize = 0;
  345. if (!m_totalSize)
  346. {
  347. if (m_buffer)
  348. b3AlignedFree(m_buffer);
  349. m_currentSize += B3_HEADER_LENGTH;
  350. m_buffer = (unsigned char*)b3AlignedAlloc(m_currentSize,16);
  351. unsigned char* currentPtr = m_buffer;
  352. writeHeader(m_buffer);
  353. currentPtr += B3_HEADER_LENGTH;
  354. mysize+=B3_HEADER_LENGTH;
  355. for (int i=0;i< m_chunkPtrs.size();i++)
  356. {
  357. int curLength = sizeof(b3Chunk)+m_chunkPtrs[i]->m_length;
  358. memcpy(currentPtr,m_chunkPtrs[i], curLength);
  359. b3AlignedFree(m_chunkPtrs[i]);
  360. currentPtr+=curLength;
  361. mysize+=curLength;
  362. }
  363. }
  364. mTypes.clear();
  365. mStructs.clear();
  366. mTlens.clear();
  367. mStructReverse.clear();
  368. mTypeLookup.clear();
  369. m_chunkP.clear();
  370. m_nameMap.clear();
  371. m_uniquePointers.clear();
  372. m_chunkPtrs.clear();
  373. }
  374. virtual void* getUniquePointer(void*oldPtr)
  375. {
  376. if (!oldPtr)
  377. return 0;
  378. b3PointerUid* uptr = (b3PointerUid*)m_uniquePointers.find(oldPtr);
  379. if (uptr)
  380. {
  381. return uptr->m_ptr;
  382. }
  383. m_uniqueIdGenerator++;
  384. b3PointerUid uid;
  385. uid.m_uniqueIds[0] = m_uniqueIdGenerator;
  386. uid.m_uniqueIds[1] = m_uniqueIdGenerator;
  387. m_uniquePointers.insert(oldPtr,uid);
  388. return uid.m_ptr;
  389. }
  390. virtual const unsigned char* getBufferPointer() const
  391. {
  392. return m_buffer;
  393. }
  394. virtual int getCurrentBufferSize() const
  395. {
  396. return m_currentSize;
  397. }
  398. virtual void finalizeChunk(b3Chunk* chunk, const char* structType, int chunkCode,void* oldPtr)
  399. {
  400. if (!(m_serializationFlags&B3_SERIALIZE_NO_DUPLICATE_ASSERT))
  401. {
  402. b3Assert(!findPointer(oldPtr));
  403. }
  404. chunk->m_dna_nr = getReverseType(structType);
  405. chunk->m_chunkCode = chunkCode;
  406. void* uniquePtr = getUniquePointer(oldPtr);
  407. m_chunkP.insert(oldPtr,uniquePtr);//chunk->m_oldPtr);
  408. chunk->m_oldPtr = uniquePtr;//oldPtr;
  409. }
  410. virtual unsigned char* internalAlloc(size_t size)
  411. {
  412. unsigned char* ptr = 0;
  413. if (m_totalSize)
  414. {
  415. ptr = m_buffer+m_currentSize;
  416. m_currentSize += int(size);
  417. b3Assert(m_currentSize<m_totalSize);
  418. } else
  419. {
  420. ptr = (unsigned char*)b3AlignedAlloc(size,16);
  421. m_currentSize += int(size);
  422. }
  423. return ptr;
  424. }
  425. virtual b3Chunk* allocate(size_t size, int numElements)
  426. {
  427. unsigned char* ptr = internalAlloc(int(size)*numElements+sizeof(b3Chunk));
  428. unsigned char* data = ptr + sizeof(b3Chunk);
  429. b3Chunk* chunk = (b3Chunk*)ptr;
  430. chunk->m_chunkCode = 0;
  431. chunk->m_oldPtr = data;
  432. chunk->m_length = int(size)*numElements;
  433. chunk->m_number = numElements;
  434. m_chunkPtrs.push_back(chunk);
  435. return chunk;
  436. }
  437. virtual const char* findNameForPointer(const void* ptr) const
  438. {
  439. const char*const * namePtr = m_nameMap.find(ptr);
  440. if (namePtr && *namePtr)
  441. return *namePtr;
  442. return 0;
  443. }
  444. virtual void registerNameForPointer(const void* ptr, const char* name)
  445. {
  446. m_nameMap.insert(ptr,name);
  447. }
  448. virtual void serializeName(const char* name)
  449. {
  450. if (name)
  451. {
  452. //don't serialize name twice
  453. if (findPointer((void*)name))
  454. return;
  455. int len = b3StrLen(name);
  456. if (len)
  457. {
  458. int newLen = len+1;
  459. int padding = ((newLen+3)&~3)-newLen;
  460. newLen += padding;
  461. //serialize name string now
  462. b3Chunk* chunk = allocate(sizeof(char),newLen);
  463. char* destinationName = (char*)chunk->m_oldPtr;
  464. for (int i=0;i<len;i++)
  465. {
  466. destinationName[i] = name[i];
  467. }
  468. destinationName[len] = 0;
  469. finalizeChunk(chunk,"char",B3_ARRAY_CODE,(void*)name);
  470. }
  471. }
  472. }
  473. virtual int getSerializationFlags() const
  474. {
  475. return m_serializationFlags;
  476. }
  477. virtual void setSerializationFlags(int flags)
  478. {
  479. m_serializationFlags = flags;
  480. }
  481. };
  482. #endif //B3_SERIALIZER_H