ObjectStreamIn.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Core/Factory.h>
  5. #include <Jolt/Core/UnorderedSet.h>
  6. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  7. #include <Jolt/ObjectStream/ObjectStreamTextIn.h>
  8. #include <Jolt/ObjectStream/ObjectStreamBinaryIn.h>
  9. #include <Jolt/ObjectStream/SerializableObject.h>
  10. JPH_NAMESPACE_BEGIN
  11. ObjectStreamIn::ObjectStreamIn(istream &inStream) :
  12. mStream(inStream)
  13. {
  14. }
  15. bool ObjectStreamIn::GetInfo(istream &inStream, EStreamType &outType, int &outVersion, int &outRevision)
  16. {
  17. // Read header and check if it is the correct format, e.g. "TOS 1.00"
  18. char header[9];
  19. memset(header, 0, 9);
  20. inStream.read(header, 8);
  21. if ((header[0] == 'B' || header[0] == 'T') && header[1] == 'O' && header[2] == 'S'
  22. && (header[3] == ' ' || isdigit(header[3])) && isdigit(header[4])
  23. && header[5] == '.' && isdigit(header[6]) && isdigit(header[7]))
  24. {
  25. // Check if this is a binary or text objectfile
  26. switch (header[0])
  27. {
  28. case 'T': outType = ObjectStream::EStreamType::Text; break;
  29. case 'B': outType = ObjectStream::EStreamType::Binary; break;
  30. default: JPH_ASSERT(false); break;
  31. }
  32. // Extract version and revision
  33. header[5] = '\0';
  34. outVersion = atoi(&header[3]);
  35. outRevision = atoi(&header[6]);
  36. return true;
  37. }
  38. Trace("ObjectStreamIn: Not a valid object stream.");
  39. return false;
  40. }
  41. ObjectStreamIn *ObjectStreamIn::Open(istream &inStream)
  42. {
  43. // Check if file is an ObjectStream of the correct version and revision
  44. EStreamType type;
  45. int version;
  46. int revision;
  47. if (GetInfo(inStream, type, version, revision))
  48. {
  49. if (version == sVersion && revision == sRevision)
  50. {
  51. // Create an input stream of the correct type
  52. switch (type)
  53. {
  54. case EStreamType::Text: return new ObjectStreamTextIn(inStream);
  55. case EStreamType::Binary: return new ObjectStreamBinaryIn(inStream);
  56. default: JPH_ASSERT(false);
  57. }
  58. }
  59. else
  60. {
  61. Trace("ObjectStreamIn: Different version stream (%d.%02d, expected %d.%02d).", version, revision, sVersion, sRevision);
  62. }
  63. }
  64. return nullptr;
  65. }
  66. void *ObjectStreamIn::Read(const RTTI *inRTTI)
  67. {
  68. using ObjectSet = UnorderedSet<void *>;
  69. // Read all information on the stream
  70. void *main_object = nullptr;
  71. bool continue_reading = true;
  72. for (;;)
  73. {
  74. // Get type of next operation
  75. EOSDataType data_type;
  76. if (!ReadDataType(data_type))
  77. break;
  78. if (data_type == EOSDataType::Declare)
  79. {
  80. // Read type declaration
  81. if (!ReadRTTI())
  82. {
  83. Trace("ObjectStreamIn: Fatal error while reading class description for class %s.", inRTTI->GetName());
  84. continue_reading = false;
  85. break;
  86. }
  87. }
  88. else if (data_type == EOSDataType::Object)
  89. {
  90. const RTTI *rtti;
  91. void *object = ReadObject(rtti);
  92. if (!main_object && object)
  93. {
  94. // This is the first and thus main object of the file.
  95. if (rtti->IsKindOf(inRTTI))
  96. {
  97. // Object is of correct type
  98. main_object = object;
  99. }
  100. else
  101. {
  102. Trace("ObjectStreamIn: Main object of different type. Expected %s, but found %s.", inRTTI->GetName(), rtti->GetName());
  103. continue_reading = false;
  104. break;
  105. }
  106. }
  107. }
  108. else
  109. {
  110. // Invalid or out of place token found
  111. Trace("ObjectStreamIn: Invalid or out of place token found.");
  112. continue_reading = false;
  113. break;
  114. }
  115. }
  116. // Resolve links (pointer, references)
  117. if (continue_reading)
  118. {
  119. // Resolve links
  120. ObjectSet referenced_objects;
  121. for (Link &link : mUnresolvedLinks)
  122. {
  123. IdentifierMap::const_iterator j = mIdentifierMap.find(link.mIdentifier);
  124. if (j != mIdentifierMap.end() && j->second.mRTTI->IsKindOf(link.mRTTI))
  125. {
  126. const ObjectInfo &obj_info = j->second;
  127. // Set pointer
  128. *link.mPointer = obj_info.mInstance;
  129. // Increment refcount if it was a referencing pointer
  130. if (link.mRefCountOffset != -1)
  131. ++(*(uint32 *)(((uint8 *)obj_info.mInstance) + link.mRefCountOffset));
  132. // Add referenced object to the list
  133. if (referenced_objects.find(obj_info.mInstance) == referenced_objects.end())
  134. referenced_objects.insert(obj_info.mInstance);
  135. }
  136. else
  137. {
  138. // Referenced object not found, set pointer to nullptr
  139. Trace("ObjectStreamIn: Setting incorrect pointer to class of type %s to nullptr.", link.mRTTI->GetName());
  140. *link.mPointer = nullptr;
  141. }
  142. }
  143. // Release unreferenced objects except the main object
  144. for (const IdentifierMap::value_type &j : mIdentifierMap)
  145. {
  146. const ObjectInfo &obj_info = j.second;
  147. if (obj_info.mInstance != main_object)
  148. {
  149. ObjectSet::const_iterator k = referenced_objects.find(obj_info.mInstance);
  150. if (k == referenced_objects.end())
  151. {
  152. Trace("ObjectStreamIn: Releasing unreferenced object of type %s.", obj_info.mRTTI->GetName());
  153. obj_info.mRTTI->DestructObject(obj_info.mInstance);
  154. }
  155. }
  156. }
  157. return main_object;
  158. }
  159. else
  160. {
  161. // Release all objects if a fatal error occurred
  162. for (const IdentifierMap::value_type &i : mIdentifierMap)
  163. {
  164. const ObjectInfo &obj_info = i.second;
  165. obj_info.mRTTI->DestructObject(obj_info.mInstance);
  166. }
  167. return nullptr;
  168. }
  169. }
  170. void *ObjectStreamIn::ReadObject(const RTTI *& outRTTI)
  171. {
  172. // Read the object class
  173. void *object = nullptr;
  174. String class_name;
  175. if (ReadName(class_name))
  176. {
  177. // Get class description
  178. ClassDescriptionMap::iterator i = mClassDescriptionMap.find(class_name);
  179. if (i != mClassDescriptionMap.end())
  180. {
  181. const ClassDescription &class_desc = i->second;
  182. // Read object identifier
  183. Identifier identifier;
  184. if (ReadIdentifier(identifier))
  185. {
  186. // Check if this object can be read or must be skipped
  187. if (identifier != sNullIdentifier
  188. && class_desc.mRTTI
  189. && !class_desc.mRTTI->IsAbstract())
  190. {
  191. // Create object instance
  192. outRTTI = class_desc.mRTTI;
  193. object = outRTTI->CreateObject();
  194. // Read object attributes
  195. if (ReadClassData(class_desc, object))
  196. {
  197. // Add object to identifier map
  198. mIdentifierMap.try_emplace(identifier, object, outRTTI);
  199. }
  200. else
  201. {
  202. // Fatal error while reading attributes, release object
  203. outRTTI->DestructObject(object);
  204. object = nullptr;
  205. }
  206. }
  207. else
  208. {
  209. // Skip this object
  210. // TODO: This operation can fail, but there is no check yet
  211. Trace("ObjectStreamIn: Found uncreatable object %s.", class_name.c_str());
  212. ReadClassData(class_desc, nullptr);
  213. }
  214. }
  215. }
  216. else
  217. {
  218. // TODO: This is a fatal error, but this function has no way of indicating this
  219. Trace("ObjectStreamIn: Found object of unknown class %s.", class_name.c_str());
  220. }
  221. }
  222. return object;
  223. }
  224. bool ObjectStreamIn::ReadRTTI()
  225. {
  226. // Read class name and find it's attribute info
  227. String class_name;
  228. if (!ReadName(class_name))
  229. return false;
  230. // Find class
  231. const RTTI *rtti = Factory::sInstance->Find(class_name.c_str());
  232. if (rtti == nullptr)
  233. Trace("ObjectStreamIn: Unknown class: \"%s\".", class_name.c_str());
  234. // Insert class description
  235. ClassDescription &class_desc = mClassDescriptionMap.try_emplace(class_name, rtti).first->second;
  236. // Read the number of entries in the description
  237. uint32 count;
  238. if (!ReadCount(count))
  239. return false;
  240. // Read the entries
  241. for (uint32 i = 0; i < count; ++i)
  242. {
  243. AttributeDescription attribute;
  244. // Read name
  245. String attribute_name;
  246. if (!ReadName(attribute_name))
  247. return false;
  248. // Read type
  249. if (!ReadDataType(attribute.mDataType))
  250. return false;
  251. // Read array depth
  252. while (attribute.mDataType == EOSDataType::Array)
  253. {
  254. ++attribute.mArrayDepth;
  255. if (!ReadDataType(attribute.mDataType))
  256. return false;
  257. }
  258. // Read instance/pointer class name
  259. if ((attribute.mDataType == EOSDataType::Instance || attribute.mDataType == EOSDataType::Pointer)
  260. && !ReadName(attribute.mClassName))
  261. return false;
  262. // Find attribute in rtti
  263. if (rtti)
  264. {
  265. // Find attribute index
  266. for (int idx = 0; idx < rtti->GetAttributeCount(); ++idx)
  267. {
  268. const SerializableAttribute &attr = rtti->GetAttribute(idx);
  269. if (strcmp(attr.GetName(), attribute_name.c_str()) == 0)
  270. {
  271. attribute.mIndex = idx;
  272. break;
  273. }
  274. }
  275. // Check if attribute is of expected type
  276. if (attribute.mIndex >= 0)
  277. {
  278. const SerializableAttribute &attr = rtti->GetAttribute(attribute.mIndex);
  279. if (!attr.IsType(attribute.mArrayDepth, attribute.mDataType, attribute.mClassName.c_str()))
  280. attribute.mIndex = -1;
  281. }
  282. }
  283. // Add attribute to the class description
  284. class_desc.mAttributes.push_back(attribute);
  285. }
  286. return true;
  287. }
  288. bool ObjectStreamIn::ReadClassData(const char *inClassName, void *inInstance)
  289. {
  290. // Find the class description
  291. ClassDescriptionMap::iterator i = mClassDescriptionMap.find(inClassName);
  292. if (i != mClassDescriptionMap.end())
  293. return ReadClassData(i->second, inInstance);
  294. return false;
  295. }
  296. bool ObjectStreamIn::ReadClassData(const ClassDescription &inClassDesc, void *inInstance)
  297. {
  298. // Read data for this class
  299. bool continue_reading = true;
  300. for (const AttributeDescription &attr_desc : inClassDesc.mAttributes)
  301. {
  302. // Read or skip the attribute data
  303. if (attr_desc.mIndex >= 0 && inInstance)
  304. {
  305. const SerializableAttribute &attr = inClassDesc.mRTTI->GetAttribute(attr_desc.mIndex);
  306. continue_reading = attr.ReadData(*this, inInstance);
  307. }
  308. else
  309. continue_reading = SkipAttributeData(attr_desc.mArrayDepth, attr_desc.mDataType, attr_desc.mClassName.c_str());
  310. if (!continue_reading)
  311. break;
  312. }
  313. return continue_reading;
  314. }
  315. bool ObjectStreamIn::ReadPointerData(const RTTI *inRTTI, void **inPointer, int inRefCountOffset)
  316. {
  317. Identifier identifier;
  318. if (ReadIdentifier(identifier))
  319. {
  320. if (identifier == sNullIdentifier)
  321. {
  322. // Set nullptr pointer
  323. inPointer = nullptr;
  324. }
  325. else
  326. {
  327. // Put pointer on the list to be resolved later on
  328. mUnresolvedLinks.emplace_back();
  329. mUnresolvedLinks.back().mPointer = inPointer;
  330. mUnresolvedLinks.back().mRefCountOffset = inRefCountOffset;
  331. mUnresolvedLinks.back().mIdentifier = identifier;
  332. mUnresolvedLinks.back().mRTTI = inRTTI;
  333. }
  334. return true;
  335. }
  336. return false;
  337. }
  338. bool ObjectStreamIn::SkipAttributeData(int inArrayDepth, EOSDataType inDataType, const char *inClassName)
  339. {
  340. bool continue_reading = true;
  341. // Get number of items to read
  342. uint32 count = 1;
  343. for (; inArrayDepth > 0; --inArrayDepth)
  344. {
  345. uint32 temporary;
  346. if (ReadCount(temporary))
  347. {
  348. // Multiply for multi dimensional arrays
  349. count *= temporary;
  350. }
  351. else
  352. {
  353. // Fatal error while reading array size
  354. continue_reading = false;
  355. break;
  356. }
  357. }
  358. // Read data for all items
  359. if (continue_reading)
  360. {
  361. if (inDataType == EOSDataType::Instance)
  362. {
  363. // Get the class description
  364. ClassDescriptionMap::iterator i = mClassDescriptionMap.find(inClassName);
  365. if (i != mClassDescriptionMap.end())
  366. {
  367. for (; count > 0 && continue_reading; --count)
  368. continue_reading = ReadClassData(i->second, nullptr);
  369. }
  370. else
  371. {
  372. continue_reading = false;
  373. Trace("ObjectStreamIn: Found instance of unknown class %s.", inClassName);
  374. }
  375. }
  376. else
  377. {
  378. for (; count > 0 && continue_reading; --count)
  379. {
  380. switch (inDataType)
  381. {
  382. case EOSDataType::Pointer:
  383. {
  384. Identifier temporary;
  385. continue_reading = ReadIdentifier(temporary);
  386. break;
  387. }
  388. case EOSDataType::T_uint8:
  389. {
  390. uint8 temporary;
  391. continue_reading = ReadPrimitiveData(temporary);
  392. break;
  393. }
  394. case EOSDataType::T_uint16:
  395. {
  396. uint16 temporary;
  397. continue_reading = ReadPrimitiveData(temporary);
  398. break;
  399. }
  400. case EOSDataType::T_int:
  401. {
  402. int temporary;
  403. continue_reading = ReadPrimitiveData(temporary);
  404. break;
  405. }
  406. case EOSDataType::T_uint32:
  407. {
  408. uint32 temporary;
  409. continue_reading = ReadPrimitiveData(temporary);
  410. break;
  411. }
  412. case EOSDataType::T_uint64:
  413. {
  414. uint64 temporary;
  415. continue_reading = ReadPrimitiveData(temporary);
  416. break;
  417. }
  418. case EOSDataType::T_float:
  419. {
  420. float temporary;
  421. continue_reading = ReadPrimitiveData(temporary);
  422. break;
  423. }
  424. case EOSDataType::T_bool:
  425. {
  426. bool temporary;
  427. continue_reading = ReadPrimitiveData(temporary);
  428. break;
  429. }
  430. case EOSDataType::T_String:
  431. {
  432. String temporary;
  433. continue_reading = ReadPrimitiveData(temporary);
  434. break;
  435. }
  436. case EOSDataType::T_Float3:
  437. {
  438. Float3 temporary;
  439. continue_reading = ReadPrimitiveData(temporary);
  440. break;
  441. }
  442. case EOSDataType::T_Vec3:
  443. {
  444. Vec3 temporary;
  445. continue_reading = ReadPrimitiveData(temporary);
  446. break;
  447. }
  448. case EOSDataType::T_Vec4:
  449. {
  450. Vec4 temporary;
  451. continue_reading = ReadPrimitiveData(temporary);
  452. break;
  453. }
  454. case EOSDataType::T_Quat:
  455. {
  456. Quat temporary;
  457. continue_reading = ReadPrimitiveData(temporary);
  458. break;
  459. }
  460. case EOSDataType::T_Mat44:
  461. {
  462. Mat44 temporary;
  463. continue_reading = ReadPrimitiveData(temporary);
  464. break;
  465. }
  466. case EOSDataType::Array:
  467. case EOSDataType::Object:
  468. case EOSDataType::Declare:
  469. case EOSDataType::Instance:
  470. case EOSDataType::Invalid:
  471. default:
  472. continue_reading = false;
  473. break;
  474. }
  475. }
  476. }
  477. }
  478. return continue_reading;
  479. }
  480. JPH_NAMESPACE_END