Serializable.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "Deserializer.h"
  26. #include "Log.h"
  27. #include "Serializable.h"
  28. #include "Serializer.h"
  29. #include "XMLElement.h"
  30. #include "DebugNew.h"
  31. OBJECTTYPESTATIC(Serializable);
  32. Serializable::Serializable(Context* context) :
  33. Object(context),
  34. serverFrameNumber_(0),
  35. networkAttributes_(0),
  36. loading_(false)
  37. {
  38. }
  39. Serializable::~Serializable()
  40. {
  41. }
  42. void Serializable::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  43. {
  44. // Check for accessor function mode
  45. if (attr.accessor_)
  46. {
  47. attr.accessor_->Set(this, src);
  48. return;
  49. }
  50. // Calculate the destination address
  51. void* dest = reinterpret_cast<unsigned char*>(this) + attr.offset_;
  52. switch (attr.type_)
  53. {
  54. case VAR_INT:
  55. // If enum type, use the low 8 bits only (assume full value to be initialized)
  56. if (attr.enumNames_)
  57. *(reinterpret_cast<unsigned char*>(dest)) = src.GetInt();
  58. else
  59. *(reinterpret_cast<int*>(dest)) = src.GetInt();
  60. break;
  61. case VAR_BOOL:
  62. *(reinterpret_cast<bool*>(dest)) = src.GetBool();
  63. break;
  64. case VAR_FLOAT:
  65. *(reinterpret_cast<float*>(dest)) = src.GetFloat();
  66. break;
  67. case VAR_VECTOR2:
  68. *(reinterpret_cast<Vector2*>(dest)) = src.GetVector2();
  69. break;
  70. case VAR_VECTOR3:
  71. *(reinterpret_cast<Vector3*>(dest)) = src.GetVector3();
  72. break;
  73. case VAR_VECTOR4:
  74. *(reinterpret_cast<Vector4*>(dest)) = src.GetVector4();
  75. break;
  76. case VAR_QUATERNION:
  77. *(reinterpret_cast<Quaternion*>(dest)) = src.GetQuaternion();
  78. break;
  79. case VAR_COLOR:
  80. *(reinterpret_cast<Color*>(dest)) = src.GetColor();
  81. break;
  82. case VAR_STRING:
  83. *(reinterpret_cast<String*>(dest)) = src.GetString();
  84. break;
  85. case VAR_BUFFER:
  86. *(reinterpret_cast<PODVector<unsigned char>*>(dest)) = src.GetBuffer();
  87. break;
  88. case VAR_RESOURCEREF:
  89. *(reinterpret_cast<ResourceRef*>(dest)) = src.GetResourceRef();
  90. break;
  91. case VAR_RESOURCEREFLIST:
  92. *(reinterpret_cast<ResourceRefList*>(dest)) = src.GetResourceRefList();
  93. break;
  94. case VAR_VARIANTVECTOR:
  95. *(reinterpret_cast<VariantVector*>(dest)) = src.GetVariantVector();
  96. break;
  97. case VAR_VARIANTMAP:
  98. *(reinterpret_cast<VariantMap*>(dest)) = src.GetVariantMap();
  99. break;
  100. }
  101. }
  102. void Serializable::OnGetAttribute(const AttributeInfo& attr, Variant& dest)
  103. {
  104. // Check for accessor function mode
  105. if (attr.accessor_)
  106. {
  107. attr.accessor_->Get(this, dest);
  108. return;
  109. }
  110. // Calculate the source address
  111. void* src = reinterpret_cast<unsigned char*>(this) + attr.offset_;
  112. switch (attr.type_)
  113. {
  114. case VAR_INT:
  115. // If enum type, use the low 8 bits only
  116. if (attr.enumNames_)
  117. dest = *(reinterpret_cast<const unsigned char*>(src));
  118. else
  119. dest = *(reinterpret_cast<const int*>(src));
  120. break;
  121. case VAR_BOOL:
  122. dest = *(reinterpret_cast<const bool*>(src));
  123. break;
  124. case VAR_FLOAT:
  125. dest = *(reinterpret_cast<const float*>(src));
  126. break;
  127. case VAR_VECTOR2:
  128. dest = *(reinterpret_cast<const Vector2*>(src));
  129. break;
  130. case VAR_VECTOR3:
  131. dest = *(reinterpret_cast<const Vector3*>(src));
  132. break;
  133. case VAR_VECTOR4:
  134. dest = *(reinterpret_cast<const Vector4*>(src));
  135. break;
  136. case VAR_QUATERNION:
  137. dest = *(reinterpret_cast<const Quaternion*>(src));
  138. break;
  139. case VAR_COLOR:
  140. dest = *(reinterpret_cast<const Color*>(src));
  141. break;
  142. case VAR_STRING:
  143. dest = *(reinterpret_cast<const String*>(src));
  144. break;
  145. case VAR_BUFFER:
  146. dest = *(reinterpret_cast<const PODVector<unsigned char>*>(src));
  147. break;
  148. case VAR_RESOURCEREF:
  149. dest = *(reinterpret_cast<const ResourceRef*>(src));
  150. break;
  151. case VAR_RESOURCEREFLIST:
  152. dest = *(reinterpret_cast<const ResourceRefList*>(src));
  153. break;
  154. case VAR_VARIANTVECTOR:
  155. dest = *(reinterpret_cast<const VariantVector*>(src));
  156. break;
  157. case VAR_VARIANTMAP:
  158. dest = *(reinterpret_cast<const VariantMap*>(src));
  159. break;
  160. }
  161. }
  162. bool Serializable::Load(Deserializer& source)
  163. {
  164. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  165. if (!attributes)
  166. return true;
  167. loading_ = true;
  168. for (unsigned i = 0; i < attributes->Size(); ++i)
  169. {
  170. const AttributeInfo& attr = attributes->At(i);
  171. if (!(attr.mode_ & AM_FILE))
  172. continue;
  173. if (source.IsEof())
  174. {
  175. LOGERROR("Could not load " + GetTypeName() + ", stream not open or at end");
  176. loading_ = false;
  177. return false;
  178. }
  179. OnSetAttribute(attr, source.ReadVariant(attr.type_));
  180. }
  181. loading_ = false;
  182. return true;
  183. }
  184. bool Serializable::Save(Serializer& dest)
  185. {
  186. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  187. if (!attributes)
  188. return true;
  189. Variant value;
  190. for (unsigned i = 0; i < attributes->Size(); ++i)
  191. {
  192. const AttributeInfo& attr = attributes->At(i);
  193. if (!(attr.mode_ & AM_FILE))
  194. continue;
  195. OnGetAttribute(attr, value);
  196. if (!dest.WriteVariantData(value))
  197. {
  198. LOGERROR("Could not save " + GetTypeName() + ", writing to stream failed");
  199. return false;
  200. }
  201. }
  202. return true;
  203. }
  204. bool Serializable::LoadXML(const XMLElement& source)
  205. {
  206. if (source.IsNull())
  207. {
  208. LOGERROR("Could not load " + GetTypeName() + ", null source element");
  209. return false;
  210. }
  211. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  212. if (!attributes)
  213. return true;
  214. loading_ = true;
  215. XMLElement attrElem = source.GetChild("attribute");
  216. unsigned startIndex = 0;
  217. while (attrElem)
  218. {
  219. const char* name = attrElem.GetAttribute("name");
  220. unsigned i = startIndex;
  221. unsigned attempts = attributes->Size();
  222. while (attempts)
  223. {
  224. const AttributeInfo& attr = attributes->At(i);
  225. if ((attr.mode_ & AM_FILE) && attr.name_ == name)
  226. {
  227. // If enums specified, do enum lookup and int assignment. Otherwise assign the variant directly
  228. if (attr.enumNames_)
  229. {
  230. const char* value = attrElem.GetAttribute("value");
  231. const String* enumPtr = attr.enumNames_;
  232. int enumValue = 0;
  233. bool enumFound = false;
  234. while (enumPtr->Length())
  235. {
  236. if (*enumPtr == value)
  237. {
  238. enumFound = true;
  239. break;
  240. }
  241. ++enumPtr;
  242. ++enumValue;
  243. }
  244. if (enumFound)
  245. OnSetAttribute(attr, Variant(enumValue));
  246. else
  247. LOGWARNING("Unknown enum value " + String(value) + " in attribute " + String(attr.name_));
  248. }
  249. else
  250. OnSetAttribute(attr, attrElem.GetVariantValue(attr.type_));
  251. startIndex = (i + 1) % attributes->Size();
  252. break;
  253. }
  254. else
  255. {
  256. i = (i + 1) % attributes->Size();
  257. --attempts;
  258. }
  259. }
  260. if (!attempts)
  261. LOGWARNING("Unknown attribute " + String(name) + " in XML data");
  262. attrElem = attrElem.GetNext("attribute");
  263. }
  264. loading_ = false;
  265. return true;
  266. }
  267. bool Serializable::SaveXML(XMLElement& dest)
  268. {
  269. if (dest.IsNull())
  270. {
  271. LOGERROR("Could not save " + GetTypeName() + ", null destination element");
  272. return false;
  273. }
  274. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  275. if (!attributes)
  276. return true;
  277. Variant value;
  278. for (unsigned i = 0; i < attributes->Size(); ++i)
  279. {
  280. const AttributeInfo& attr = attributes->At(i);
  281. if (!(attr.mode_ & AM_FILE))
  282. continue;
  283. XMLElement attrElem = dest.CreateChild("attribute");
  284. attrElem.SetAttribute("name", attr.name_.CString());
  285. OnGetAttribute(attr, value);
  286. // If enums specified, set as an enum string. Otherwise set directly as a Variant
  287. if (attr.enumNames_)
  288. {
  289. int enumValue = value.GetInt();
  290. attrElem.SetAttribute("value", attr.enumNames_[enumValue].CString());
  291. }
  292. else
  293. attrElem.SetVariantValue(value);
  294. }
  295. return true;
  296. }
  297. bool Serializable::SetAttribute(unsigned index, const Variant& value)
  298. {
  299. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  300. if (!attributes)
  301. {
  302. LOGERROR(GetTypeName() + " has no attributes");
  303. return false;
  304. }
  305. if (index >= attributes->Size())
  306. {
  307. LOGERROR("Attribute index out of bounds");
  308. return false;
  309. }
  310. const AttributeInfo& attr = attributes->At(index);
  311. // Check that the new value's type matches the attribute type
  312. if (value.GetType() == attr.type_)
  313. {
  314. OnSetAttribute(attr, value);
  315. return true;
  316. }
  317. else
  318. {
  319. LOGERROR("Could not set attribute " + String(attr.name_) + ": expected type " + Variant::GetTypeName(attr.type_) +
  320. " but got " + value.GetTypeName());
  321. return false;
  322. }
  323. }
  324. bool Serializable::SetAttribute(const String& name, const Variant& value)
  325. {
  326. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  327. if (!attributes)
  328. {
  329. LOGERROR(GetTypeName() + " has no attributes");
  330. return false;
  331. }
  332. for (Vector<AttributeInfo>::ConstIterator i = attributes->Begin(); i != attributes->End(); ++i)
  333. {
  334. if (i->name_ == name)
  335. {
  336. // Check that the new value's type matches the attribute type
  337. if (value.GetType() == i->type_)
  338. {
  339. OnSetAttribute(*i, value);
  340. return true;
  341. }
  342. else
  343. {
  344. LOGERROR("Could not set attribute " + String(i->name_) + ": expected type " + Variant::GetTypeName(i->type_)
  345. + " but got " + value.GetTypeName());
  346. return false;
  347. }
  348. }
  349. }
  350. LOGERROR("Could not find attribute " + String(name) + " in " + GetTypeName());
  351. return false;
  352. }
  353. void Serializable::WriteInitialDeltaUpdate(unsigned frameNumber, Serializer& dest, PODVector<unsigned char>& deltaUpdateBits,
  354. Vector<Variant>& replicationState)
  355. {
  356. networkAttributes_ = GetNetworkAttributes();
  357. if (!networkAttributes_)
  358. return;
  359. unsigned numAttributes = networkAttributes_->Size();
  360. // Get current attribute values if necessary
  361. if (frameNumber != serverFrameNumber_ || currentState_.Empty())
  362. {
  363. currentState_.Resize(numAttributes);
  364. for (unsigned i = 0; i < numAttributes; ++i)
  365. {
  366. const AttributeInfo& attr = networkAttributes_->At(i);
  367. OnGetAttribute(attr, currentState_[i]);
  368. }
  369. serverFrameNumber_ = frameNumber;
  370. }
  371. replicationState.Resize(numAttributes);
  372. deltaUpdateBits.Resize((numAttributes + 7) >> 3);
  373. for (unsigned i = 0; i < deltaUpdateBits.Size(); ++i)
  374. deltaUpdateBits[i] = 0;
  375. // Copy attributes to replication state and compare against defaults
  376. for (unsigned i = 0; i < numAttributes; ++i)
  377. {
  378. const AttributeInfo& attr = networkAttributes_->At(i);
  379. replicationState[i] = currentState_[i];
  380. if (replicationState[i] != attr.defaultValue_)
  381. deltaUpdateBits[i >> 3] |= (1 << (i & 7));
  382. }
  383. // First write the change bitfield, then attribute data for non-default attributes
  384. dest.Write(&deltaUpdateBits[0], deltaUpdateBits.Size());
  385. for (unsigned i = 0; i < numAttributes; ++i)
  386. {
  387. if (deltaUpdateBits[i >> 3] & (1 << (i & 7)))
  388. dest.WriteVariantData(replicationState[i]);
  389. }
  390. }
  391. void Serializable::PrepareUpdates(unsigned frameNumber, PODVector<unsigned char>& deltaUpdateBits,
  392. Vector<Variant>& replicationState, bool& deltaUpdate, bool& latestData)
  393. {
  394. deltaUpdate = false;
  395. latestData = false;
  396. if (!networkAttributes_ || currentState_.Empty())
  397. return;
  398. unsigned numAttributes = networkAttributes_->Size();
  399. // Get current attribute values if necessary
  400. if (frameNumber != serverFrameNumber_)
  401. {
  402. for (unsigned i = 0; i < numAttributes; ++i)
  403. {
  404. const AttributeInfo& attr = networkAttributes_->At(i);
  405. OnGetAttribute(attr, currentState_[i]);
  406. }
  407. serverFrameNumber_ = frameNumber;
  408. }
  409. deltaUpdateBits.Resize((numAttributes + 7) >> 3);
  410. for (unsigned i = 0; i < deltaUpdateBits.Size(); ++i)
  411. deltaUpdateBits[i] = 0;
  412. for (unsigned i = 0; i < numAttributes; ++i)
  413. {
  414. if (currentState_[i] != replicationState[i])
  415. {
  416. const AttributeInfo& attr = networkAttributes_->At(i);
  417. replicationState[i] = currentState_[i];
  418. if (attr.mode_ & AM_LATESTDATA)
  419. latestData = true;
  420. else
  421. {
  422. deltaUpdate = true;
  423. deltaUpdateBits[i >> 3] |= 1 << (i & 7);
  424. }
  425. }
  426. }
  427. }
  428. void Serializable::WriteDeltaUpdate(Serializer& dest, PODVector<unsigned char>& deltaUpdateBits, Vector<Variant>& replicationState)
  429. {
  430. if (!networkAttributes_)
  431. return;
  432. unsigned numAttributes = networkAttributes_->Size();
  433. // First write the change bitfield, then attribute data for changed attributes
  434. dest.Write(&deltaUpdateBits[0], deltaUpdateBits.Size());
  435. for (unsigned i = 0; i < numAttributes; ++i)
  436. {
  437. if (deltaUpdateBits[i >> 3] & (1 << (i & 7)))
  438. dest.WriteVariantData(replicationState[i]);
  439. }
  440. }
  441. void Serializable::WriteLatestDataUpdate(Serializer& dest, Vector<Variant>& replicationState)
  442. {
  443. if (!networkAttributes_)
  444. return;
  445. unsigned numAttributes = networkAttributes_->Size();
  446. for (unsigned i = 0; i < numAttributes; ++i)
  447. {
  448. if (networkAttributes_->At(i).mode_ & AM_LATESTDATA)
  449. dest.WriteVariantData(replicationState[i]);
  450. }
  451. }
  452. void Serializable::ReadDeltaUpdate(Deserializer& source, PODVector<unsigned char>& deltaUpdateBits)
  453. {
  454. const Vector<AttributeInfo>* attributes = GetNetworkAttributes();
  455. if (!attributes)
  456. return;
  457. unsigned numAttributes = attributes->Size();
  458. deltaUpdateBits.Resize((numAttributes + 7) >> 3);
  459. source.Read(&deltaUpdateBits[0], deltaUpdateBits.Size());
  460. for (unsigned i = 0; i < numAttributes && !source.IsEof(); ++i)
  461. {
  462. const AttributeInfo& attr = attributes->At(i);
  463. if (deltaUpdateBits[i >> 3] & (1 << (i & 7)))
  464. OnSetAttribute(attr, source.ReadVariant(attr.type_));
  465. }
  466. }
  467. void Serializable::ReadLatestDataUpdate(Deserializer& source)
  468. {
  469. const Vector<AttributeInfo>* attributes = GetNetworkAttributes();
  470. if (!attributes)
  471. return;
  472. unsigned numAttributes = attributes->Size();
  473. for (unsigned i = 0; i < numAttributes && !source.IsEof(); ++i)
  474. {
  475. const AttributeInfo& attr = attributes->At(i);
  476. if (attr.mode_ & AM_LATESTDATA)
  477. OnSetAttribute(attr, source.ReadVariant(attr.type_));
  478. }
  479. }
  480. Variant Serializable::GetAttribute(unsigned index)
  481. {
  482. Variant ret;
  483. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  484. if (!attributes || index >= attributes->Size())
  485. return ret;
  486. OnGetAttribute(attributes->At(index), ret);
  487. return ret;
  488. }
  489. Variant Serializable::GetAttribute(const String& name)
  490. {
  491. Variant ret;
  492. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  493. if (!attributes)
  494. {
  495. LOGERROR(GetTypeName() + " has no attributes");
  496. return ret;
  497. }
  498. for (Vector<AttributeInfo>::ConstIterator i = attributes->Begin(); i != attributes->End(); ++i)
  499. {
  500. if (i->name_ == name)
  501. {
  502. OnGetAttribute(*i, ret);
  503. return ret;
  504. }
  505. }
  506. LOGERROR("Could not find attribute " + String(name) + " in " + GetTypeName());
  507. return ret;
  508. }
  509. unsigned Serializable::GetNumAttributes() const
  510. {
  511. const Vector<AttributeInfo>* attributes = context_->GetAttributes(GetType());
  512. return attributes ? attributes->Size() : 0;
  513. }
  514. unsigned Serializable::GetNumNetworkAttributes() const
  515. {
  516. const Vector<AttributeInfo>* attributes = context_->GetNetworkAttributes(GetType());
  517. return attributes ? attributes->Size() : 0;
  518. }
  519. const Vector<AttributeInfo>* Serializable::GetAttributes() const
  520. {
  521. return context_->GetAttributes(GetType());
  522. }
  523. const Vector<AttributeInfo>* Serializable::GetNetworkAttributes() const
  524. {
  525. return context_->GetNetworkAttributes(GetType());
  526. }