Serializable.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. //
  2. // Copyright (c) 2008-2022 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../IO/Deserializer.h"
  25. #include "../IO/Log.h"
  26. #include "../IO/Serializer.h"
  27. #include "../Resource/XMLElement.h"
  28. #include "../Resource/JSONValue.h"
  29. #include "../Scene/ReplicationState.h"
  30. #include "../Scene/SceneEvents.h"
  31. #include "../Scene/Serializable.h"
  32. #include "../DebugNew.h"
  33. using namespace std;
  34. namespace Urho3D
  35. {
  36. static unsigned RemapAttributeIndex(const Vector<AttributeInfo>* attributes, const AttributeInfo& netAttr, unsigned netAttrIndex)
  37. {
  38. if (!attributes)
  39. return netAttrIndex; // Could not remap
  40. for (unsigned i = 0; i < attributes->Size(); ++i)
  41. {
  42. const AttributeInfo& attr = attributes->At(i);
  43. // Compare accessor to avoid name string compare
  44. if (attr.accessor_.Get() && attr.accessor_.Get() == netAttr.accessor_.Get())
  45. return i;
  46. }
  47. return netAttrIndex; // Could not remap
  48. }
  49. Serializable::Serializable(Context* context) :
  50. Object(context),
  51. setInstanceDefault_(false),
  52. temporary_(false)
  53. {
  54. }
  55. Serializable::~Serializable() = default;
  56. void Serializable::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  57. {
  58. // TODO: may be could use an observer pattern here
  59. if (setInstanceDefault_)
  60. SetInstanceDefault(attr.name_, src);
  61. // Check for accessor function mode
  62. if (attr.accessor_)
  63. {
  64. attr.accessor_->Set(this, src);
  65. return;
  66. }
  67. // Get the destination address
  68. assert(attr.ptr_);
  69. void* dest = attr.ptr_;
  70. switch (attr.type_)
  71. {
  72. case VAR_INT:
  73. // If enum type, use the low 8 bits only
  74. if (attr.enumNames_)
  75. *(reinterpret_cast<unsigned char*>(dest)) = src.GetInt();
  76. else
  77. *(reinterpret_cast<int*>(dest)) = src.GetInt();
  78. break;
  79. case VAR_INT64:
  80. *(reinterpret_cast<long long*>(dest)) = src.GetInt64();
  81. break;
  82. case VAR_BOOL:
  83. *(reinterpret_cast<bool*>(dest)) = src.GetBool();
  84. break;
  85. case VAR_FLOAT:
  86. *(reinterpret_cast<float*>(dest)) = src.GetFloat();
  87. break;
  88. case VAR_VECTOR2:
  89. *(reinterpret_cast<Vector2*>(dest)) = src.GetVector2();
  90. break;
  91. case VAR_VECTOR3:
  92. *(reinterpret_cast<Vector3*>(dest)) = src.GetVector3();
  93. break;
  94. case VAR_VECTOR4:
  95. *(reinterpret_cast<Vector4*>(dest)) = src.GetVector4();
  96. break;
  97. case VAR_QUATERNION:
  98. *(reinterpret_cast<Quaternion*>(dest)) = src.GetQuaternion();
  99. break;
  100. case VAR_COLOR:
  101. *(reinterpret_cast<Color*>(dest)) = src.GetColor();
  102. break;
  103. case VAR_STRING:
  104. *(reinterpret_cast<String*>(dest)) = src.GetString();
  105. break;
  106. case VAR_BUFFER:
  107. *(reinterpret_cast<PODVector<unsigned char>*>(dest)) = src.GetBuffer();
  108. break;
  109. case VAR_RESOURCEREF:
  110. *(reinterpret_cast<ResourceRef*>(dest)) = src.GetResourceRef();
  111. break;
  112. case VAR_RESOURCEREFLIST:
  113. *(reinterpret_cast<ResourceRefList*>(dest)) = src.GetResourceRefList();
  114. break;
  115. case VAR_VARIANTVECTOR:
  116. *(reinterpret_cast<VariantVector*>(dest)) = src.GetVariantVector();
  117. break;
  118. case VAR_STRINGVECTOR:
  119. *(reinterpret_cast<StringVector*>(dest)) = src.GetStringVector();
  120. break;
  121. case VAR_VARIANTMAP:
  122. *(reinterpret_cast<VariantMap*>(dest)) = src.GetVariantMap();
  123. break;
  124. case VAR_INTRECT:
  125. *(reinterpret_cast<IntRect*>(dest)) = src.GetIntRect();
  126. break;
  127. case VAR_INTVECTOR2:
  128. *(reinterpret_cast<IntVector2*>(dest)) = src.GetIntVector2();
  129. break;
  130. case VAR_INTVECTOR3:
  131. *(reinterpret_cast<IntVector3*>(dest)) = src.GetIntVector3();
  132. break;
  133. case VAR_DOUBLE:
  134. *(reinterpret_cast<double*>(dest)) = src.GetDouble();
  135. break;
  136. default:
  137. URHO3D_LOGERROR("Unsupported attribute type for OnSetAttribute()");
  138. return;
  139. }
  140. // If it is a network attribute then mark it for next network update
  141. if (attr.mode_ & AM_NET)
  142. MarkNetworkUpdate();
  143. }
  144. void Serializable::OnGetAttribute(const AttributeInfo& attr, Variant& dest) const
  145. {
  146. // Check for accessor function mode
  147. if (attr.accessor_)
  148. {
  149. attr.accessor_->Get(this, dest);
  150. return;
  151. }
  152. // Get the source address
  153. assert(attr.ptr_);
  154. const void* src = attr.ptr_;
  155. switch (attr.type_)
  156. {
  157. case VAR_INT:
  158. // If enum type, use the low 8 bits only
  159. if (attr.enumNames_)
  160. dest = *(reinterpret_cast<const unsigned char*>(src));
  161. else
  162. dest = *(reinterpret_cast<const int*>(src));
  163. break;
  164. case VAR_INT64:
  165. dest = *(reinterpret_cast<const long long*>(src));
  166. break;
  167. case VAR_BOOL:
  168. dest = *(reinterpret_cast<const bool*>(src));
  169. break;
  170. case VAR_FLOAT:
  171. dest = *(reinterpret_cast<const float*>(src));
  172. break;
  173. case VAR_VECTOR2:
  174. dest = *(reinterpret_cast<const Vector2*>(src));
  175. break;
  176. case VAR_VECTOR3:
  177. dest = *(reinterpret_cast<const Vector3*>(src));
  178. break;
  179. case VAR_VECTOR4:
  180. dest = *(reinterpret_cast<const Vector4*>(src));
  181. break;
  182. case VAR_QUATERNION:
  183. dest = *(reinterpret_cast<const Quaternion*>(src));
  184. break;
  185. case VAR_COLOR:
  186. dest = *(reinterpret_cast<const Color*>(src));
  187. break;
  188. case VAR_STRING:
  189. dest = *(reinterpret_cast<const String*>(src));
  190. break;
  191. case VAR_BUFFER:
  192. dest = *(reinterpret_cast<const PODVector<unsigned char>*>(src));
  193. break;
  194. case VAR_RESOURCEREF:
  195. dest = *(reinterpret_cast<const ResourceRef*>(src));
  196. break;
  197. case VAR_RESOURCEREFLIST:
  198. dest = *(reinterpret_cast<const ResourceRefList*>(src));
  199. break;
  200. case VAR_VARIANTVECTOR:
  201. dest = *(reinterpret_cast<const VariantVector*>(src));
  202. break;
  203. case VAR_STRINGVECTOR:
  204. dest = *(reinterpret_cast<const StringVector*>(src));
  205. break;
  206. case VAR_VARIANTMAP:
  207. dest = *(reinterpret_cast<const VariantMap*>(src));
  208. break;
  209. case VAR_INTRECT:
  210. dest = *(reinterpret_cast<const IntRect*>(src));
  211. break;
  212. case VAR_INTVECTOR2:
  213. dest = *(reinterpret_cast<const IntVector2*>(src));
  214. break;
  215. case VAR_INTVECTOR3:
  216. dest = *(reinterpret_cast<const IntVector3*>(src));
  217. break;
  218. case VAR_DOUBLE:
  219. dest = *(reinterpret_cast<const double*>(src));
  220. break;
  221. default:
  222. URHO3D_LOGERROR("Unsupported attribute type for OnGetAttribute()");
  223. return;
  224. }
  225. }
  226. const Vector<AttributeInfo>* Serializable::GetAttributes() const
  227. {
  228. return context_->GetAttributes(GetType());
  229. }
  230. const Vector<AttributeInfo>* Serializable::GetNetworkAttributes() const
  231. {
  232. return networkState_ ? networkState_->attributes_ : context_->GetNetworkAttributes(GetType());
  233. }
  234. bool Serializable::Load(Deserializer& source)
  235. {
  236. const Vector<AttributeInfo>* attributes = GetAttributes();
  237. if (!attributes)
  238. return true;
  239. for (unsigned i = 0; i < attributes->Size(); ++i)
  240. {
  241. const AttributeInfo& attr = attributes->At(i);
  242. if (!(attr.mode_ & AM_FILE))
  243. continue;
  244. if (source.IsEof())
  245. {
  246. URHO3D_LOGERROR("Could not load " + GetTypeName() + ", stream not open or at end");
  247. return false;
  248. }
  249. Variant varValue = source.ReadVariant(attr.type_);
  250. OnSetAttribute(attr, varValue);
  251. }
  252. return true;
  253. }
  254. bool Serializable::Save(Serializer& dest) const
  255. {
  256. const Vector<AttributeInfo>* attributes = GetAttributes();
  257. if (!attributes)
  258. return true;
  259. Variant value;
  260. for (unsigned i = 0; i < attributes->Size(); ++i)
  261. {
  262. const AttributeInfo& attr = attributes->At(i);
  263. if (!(attr.mode_ & AM_FILE) || (attr.mode_ & AM_FILEREADONLY) == AM_FILEREADONLY)
  264. continue;
  265. OnGetAttribute(attr, value);
  266. if (!dest.WriteVariantData(value))
  267. {
  268. URHO3D_LOGERROR("Could not save " + GetTypeName() + ", writing to stream failed");
  269. return false;
  270. }
  271. }
  272. return true;
  273. }
  274. bool Serializable::LoadXML(const XMLElement& source)
  275. {
  276. if (source.IsNull())
  277. {
  278. URHO3D_LOGERROR("Could not load " + GetTypeName() + ", null source element");
  279. return false;
  280. }
  281. const Vector<AttributeInfo>* attributes = GetAttributes();
  282. if (!attributes)
  283. return true;
  284. XMLElement attrElem = source.GetChild("attribute");
  285. unsigned startIndex = 0;
  286. while (attrElem)
  287. {
  288. String name = attrElem.GetAttribute("name");
  289. unsigned i = startIndex;
  290. unsigned attempts = attributes->Size();
  291. while (attempts)
  292. {
  293. const AttributeInfo& attr = attributes->At(i);
  294. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  295. {
  296. Variant varValue;
  297. // If enums specified, do enum lookup and int assignment. Otherwise assign the variant directly
  298. if (attr.enumNames_)
  299. {
  300. String value = attrElem.GetAttribute("value");
  301. bool enumFound = false;
  302. int enumValue = 0;
  303. const char** enumPtr = attr.enumNames_;
  304. while (*enumPtr)
  305. {
  306. if (!value.Compare(*enumPtr, false))
  307. {
  308. enumFound = true;
  309. break;
  310. }
  311. ++enumPtr;
  312. ++enumValue;
  313. }
  314. if (enumFound)
  315. varValue = enumValue;
  316. else
  317. URHO3D_LOGWARNING("Unknown enum value " + value + " in attribute " + attr.name_);
  318. }
  319. else
  320. varValue = attrElem.GetVariantValue(attr.type_);
  321. if (!varValue.IsEmpty())
  322. OnSetAttribute(attr, varValue);
  323. startIndex = (i + 1) % attributes->Size();
  324. break;
  325. }
  326. else
  327. {
  328. i = (i + 1) % attributes->Size();
  329. --attempts;
  330. }
  331. }
  332. if (!attempts)
  333. URHO3D_LOGWARNING("Unknown attribute " + name + " in XML data");
  334. attrElem = attrElem.GetNext("attribute");
  335. }
  336. return true;
  337. }
  338. bool Serializable::LoadJSON(const JSONValue& source)
  339. {
  340. if (source.IsNull())
  341. {
  342. URHO3D_LOGERROR("Could not load " + GetTypeName() + ", null JSON source element");
  343. return false;
  344. }
  345. const Vector<AttributeInfo>* attributes = GetAttributes();
  346. if (!attributes)
  347. return true;
  348. // Get attributes value
  349. JSONValue attributesValue = source.Get("attributes");
  350. if (attributesValue.IsNull())
  351. return true;
  352. // Warn if the attributes value isn't an object
  353. if (!attributesValue.IsObject())
  354. {
  355. URHO3D_LOGWARNING("'attributes' object is present in " + GetTypeName() + " but is not a JSON object; skipping load");
  356. return true;
  357. }
  358. const JSONObject& attributesObject = attributesValue.GetObject();
  359. unsigned startIndex = 0;
  360. for (JSONObject::ConstIterator it = attributesObject.Begin(); it != attributesObject.End();)
  361. {
  362. String name = it->first_;
  363. const JSONValue& value = it->second_;
  364. unsigned i = startIndex;
  365. unsigned attempts = attributes->Size();
  366. while (attempts)
  367. {
  368. const AttributeInfo& attr = attributes->At(i);
  369. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  370. {
  371. Variant varValue;
  372. // If enums specified, do enum lookup ad int assignment. Otherwise assign variant directly
  373. if (attr.enumNames_)
  374. {
  375. const String& valueStr = value.GetString();
  376. bool enumFound = false;
  377. int enumValue = 0;
  378. const char** enumPtr = attr.enumNames_;
  379. while (*enumPtr)
  380. {
  381. if (!valueStr.Compare(*enumPtr, false))
  382. {
  383. enumFound = true;
  384. break;
  385. }
  386. ++enumPtr;
  387. ++enumValue;
  388. }
  389. if (enumFound)
  390. varValue = enumValue;
  391. else
  392. URHO3D_LOGWARNING("Unknown enum value " + valueStr + " in attribute " + attr.name_);
  393. }
  394. else
  395. varValue = value.GetVariantValue(attr.type_);
  396. if (!varValue.IsEmpty())
  397. OnSetAttribute(attr, varValue);
  398. startIndex = (i + 1) % attributes->Size();
  399. break;
  400. }
  401. else
  402. {
  403. i = (i + 1) % attributes->Size();
  404. --attempts;
  405. }
  406. }
  407. if (!attempts)
  408. URHO3D_LOGWARNING("Unknown attribute " + name + " in JSON data");
  409. it++;
  410. }
  411. return true;
  412. }
  413. bool Serializable::SaveXML(XMLElement& dest) const
  414. {
  415. if (dest.IsNull())
  416. {
  417. URHO3D_LOGERROR("Could not save " + GetTypeName() + ", null destination element");
  418. return false;
  419. }
  420. const Vector<AttributeInfo>* attributes = GetAttributes();
  421. if (!attributes)
  422. return true;
  423. Variant value;
  424. for (unsigned i = 0; i < attributes->Size(); ++i)
  425. {
  426. const AttributeInfo& attr = attributes->At(i);
  427. if (!(attr.mode_ & AM_FILE) || (attr.mode_ & AM_FILEREADONLY) == AM_FILEREADONLY)
  428. continue;
  429. OnGetAttribute(attr, value);
  430. Variant defaultValue(GetAttributeDefault(i));
  431. // In XML serialization default values can be skipped. This will make the file easier to read or edit manually
  432. if (value == defaultValue && !SaveDefaultAttributes())
  433. continue;
  434. XMLElement attrElem = dest.CreateChild("attribute");
  435. attrElem.SetAttribute("name", attr.name_);
  436. // If enums specified, set as an enum string. Otherwise set directly as a Variant
  437. if (attr.enumNames_)
  438. {
  439. int enumValue = value.GetInt();
  440. attrElem.SetAttribute("value", attr.enumNames_[enumValue]);
  441. }
  442. else
  443. attrElem.SetVariantValue(value);
  444. }
  445. return true;
  446. }
  447. bool Serializable::SaveJSON(JSONValue& dest) const
  448. {
  449. const Vector<AttributeInfo>* attributes = GetAttributes();
  450. if (!attributes)
  451. return true;
  452. Variant value;
  453. JSONValue attributesValue;
  454. for (unsigned i = 0; i < attributes->Size(); ++i)
  455. {
  456. const AttributeInfo& attr = attributes->At(i);
  457. if (!(attr.mode_ & AM_FILE) || (attr.mode_ & AM_FILEREADONLY) == AM_FILEREADONLY)
  458. continue;
  459. OnGetAttribute(attr, value);
  460. Variant defaultValue(GetAttributeDefault(i));
  461. // In JSON serialization default values can be skipped. This will make the file easier to read or edit manually
  462. if (value == defaultValue && !SaveDefaultAttributes())
  463. continue;
  464. JSONValue attrVal;
  465. // If enums specified, set as an enum string. Otherwise set directly as a Variant
  466. if (attr.enumNames_)
  467. {
  468. int enumValue = value.GetInt();
  469. attrVal = attr.enumNames_[enumValue];
  470. }
  471. else
  472. attrVal.SetVariantValue(value, context_);
  473. attributesValue.Set(attr.name_, attrVal);
  474. }
  475. dest.Set("attributes", attributesValue);
  476. return true;
  477. }
  478. bool Serializable::SetAttribute(unsigned index, const Variant& value)
  479. {
  480. const Vector<AttributeInfo>* attributes = GetAttributes();
  481. if (!attributes)
  482. {
  483. URHO3D_LOGERROR(GetTypeName() + " has no attributes");
  484. return false;
  485. }
  486. if (index >= attributes->Size())
  487. {
  488. URHO3D_LOGERROR("Attribute index out of bounds");
  489. return false;
  490. }
  491. const AttributeInfo& attr = attributes->At(index);
  492. // Check that the new value's type matches the attribute type
  493. if (value.GetType() == attr.type_)
  494. {
  495. OnSetAttribute(attr, value);
  496. return true;
  497. }
  498. else
  499. {
  500. URHO3D_LOGERROR("Could not set attribute " + attr.name_ + ": expected type " + Variant::GetTypeName(attr.type_) +
  501. " but got " + value.GetTypeName());
  502. return false;
  503. }
  504. }
  505. bool Serializable::SetAttribute(const String& name, const Variant& value)
  506. {
  507. const Vector<AttributeInfo>* attributes = GetAttributes();
  508. if (!attributes)
  509. {
  510. URHO3D_LOGERROR(GetTypeName() + " has no attributes");
  511. return false;
  512. }
  513. for (Vector<AttributeInfo>::ConstIterator i = attributes->Begin(); i != attributes->End(); ++i)
  514. {
  515. if (!i->name_.Compare(name, true))
  516. {
  517. // Check that the new value's type matches the attribute type
  518. if (value.GetType() == i->type_)
  519. {
  520. OnSetAttribute(*i, value);
  521. return true;
  522. }
  523. else
  524. {
  525. URHO3D_LOGERROR("Could not set attribute " + i->name_ + ": expected type " + Variant::GetTypeName(i->type_)
  526. + " but got " + value.GetTypeName());
  527. return false;
  528. }
  529. }
  530. }
  531. URHO3D_LOGERROR("Could not find attribute " + name + " in " + GetTypeName());
  532. return false;
  533. }
  534. void Serializable::ResetToDefault()
  535. {
  536. const Vector<AttributeInfo>* attributes = GetAttributes();
  537. if (!attributes)
  538. return;
  539. for (unsigned i = 0; i < attributes->Size(); ++i)
  540. {
  541. const AttributeInfo& attr = attributes->At(i);
  542. if (attr.mode_ & (AM_NOEDIT | AM_NODEID | AM_COMPONENTID | AM_NODEIDVECTOR))
  543. continue;
  544. Variant defaultValue = GetInstanceDefault(attr.name_);
  545. if (defaultValue.IsEmpty())
  546. defaultValue = attr.defaultValue_;
  547. OnSetAttribute(attr, defaultValue);
  548. }
  549. }
  550. void Serializable::RemoveInstanceDefault()
  551. {
  552. instanceDefaultValues_.reset();
  553. }
  554. void Serializable::SetTemporary(bool enable)
  555. {
  556. if (enable != temporary_)
  557. {
  558. temporary_ = enable;
  559. using namespace TemporaryChanged;
  560. VariantMap& eventData = GetEventDataMap();
  561. eventData[P_SERIALIZABLE] = this;
  562. SendEvent(E_TEMPORARYCHANGED, eventData);
  563. }
  564. }
  565. void Serializable::SetInterceptNetworkUpdate(const String& attributeName, bool enable)
  566. {
  567. AllocateNetworkState();
  568. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  569. if (!attributes)
  570. return;
  571. for (unsigned i = 0; i < attributes->Size(); ++i)
  572. {
  573. const AttributeInfo& attr = attributes->At(i);
  574. if (!attr.name_.Compare(attributeName, true))
  575. {
  576. if (enable)
  577. networkState_->interceptMask_ |= 1ULL << i;
  578. else
  579. networkState_->interceptMask_ &= ~(1ULL << i);
  580. break;
  581. }
  582. }
  583. }
  584. void Serializable::AllocateNetworkState()
  585. {
  586. if (networkState_)
  587. return;
  588. const Vector<AttributeInfo>* networkAttributes = GetNetworkAttributes();
  589. networkState_ = make_unique<NetworkState>();
  590. networkState_->attributes_ = networkAttributes;
  591. if (!networkAttributes)
  592. return;
  593. unsigned numAttributes = networkAttributes->Size();
  594. if (networkState_->currentValues_.Size() != numAttributes)
  595. {
  596. networkState_->currentValues_.Resize(numAttributes);
  597. networkState_->previousValues_.Resize(numAttributes);
  598. // Copy the default attribute values to the previous state as a starting point
  599. for (unsigned i = 0; i < numAttributes; ++i)
  600. networkState_->previousValues_[i] = networkAttributes->At(i).defaultValue_;
  601. }
  602. }
  603. void Serializable::WriteInitialDeltaUpdate(Serializer& dest, unsigned char timeStamp)
  604. {
  605. if (!networkState_)
  606. {
  607. URHO3D_LOGERROR("WriteInitialDeltaUpdate called without allocated NetworkState");
  608. return;
  609. }
  610. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  611. if (!attributes)
  612. return;
  613. unsigned numAttributes = attributes->Size();
  614. DirtyBits attributeBits;
  615. // Compare against defaults
  616. for (unsigned i = 0; i < numAttributes; ++i)
  617. {
  618. const AttributeInfo& attr = attributes->At(i);
  619. if (networkState_->currentValues_[i] != attr.defaultValue_)
  620. attributeBits.Set(i);
  621. }
  622. // First write the change bitfield, then attribute data for non-default attributes
  623. dest.WriteUByte(timeStamp);
  624. dest.Write(attributeBits.data_, (numAttributes + 7) >> 3u);
  625. for (unsigned i = 0; i < numAttributes; ++i)
  626. {
  627. if (attributeBits.IsSet(i))
  628. dest.WriteVariantData(networkState_->currentValues_[i]);
  629. }
  630. }
  631. void Serializable::WriteDeltaUpdate(Serializer& dest, const DirtyBits& attributeBits, unsigned char timeStamp)
  632. {
  633. if (!networkState_)
  634. {
  635. URHO3D_LOGERROR("WriteDeltaUpdate called without allocated NetworkState");
  636. return;
  637. }
  638. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  639. if (!attributes)
  640. return;
  641. unsigned numAttributes = attributes->Size();
  642. // First write the change bitfield, then attribute data for changed attributes
  643. // Note: the attribute bits should not contain LATESTDATA attributes
  644. dest.WriteUByte(timeStamp);
  645. dest.Write(attributeBits.data_, (numAttributes + 7) >> 3u);
  646. for (unsigned i = 0; i < numAttributes; ++i)
  647. {
  648. if (attributeBits.IsSet(i))
  649. dest.WriteVariantData(networkState_->currentValues_[i]);
  650. }
  651. }
  652. void Serializable::WriteLatestDataUpdate(Serializer& dest, unsigned char timeStamp)
  653. {
  654. if (!networkState_)
  655. {
  656. URHO3D_LOGERROR("WriteLatestDataUpdate called without allocated NetworkState");
  657. return;
  658. }
  659. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  660. if (!attributes)
  661. return;
  662. unsigned numAttributes = attributes->Size();
  663. dest.WriteUByte(timeStamp);
  664. for (unsigned i = 0; i < numAttributes; ++i)
  665. {
  666. if (attributes->At(i).mode_ & AM_LATESTDATA)
  667. dest.WriteVariantData(networkState_->currentValues_[i]);
  668. }
  669. }
  670. bool Serializable::ReadDeltaUpdate(Deserializer& source)
  671. {
  672. const Vector<AttributeInfo>* attributes = GetNetworkAttributes();
  673. if (!attributes)
  674. return false;
  675. unsigned numAttributes = attributes->Size();
  676. DirtyBits attributeBits;
  677. bool changed = false;
  678. unsigned long long interceptMask = networkState_ ? networkState_->interceptMask_ : 0;
  679. unsigned char timeStamp = source.ReadUByte();
  680. source.Read(attributeBits.data_, (numAttributes + 7) >> 3u);
  681. for (unsigned i = 0; i < numAttributes && !source.IsEof(); ++i)
  682. {
  683. if (attributeBits.IsSet(i))
  684. {
  685. const AttributeInfo& attr = attributes->At(i);
  686. if (!(interceptMask & (1ULL << i)))
  687. {
  688. OnSetAttribute(attr, source.ReadVariant(attr.type_));
  689. changed = true;
  690. }
  691. else
  692. {
  693. using namespace InterceptNetworkUpdate;
  694. VariantMap& eventData = GetEventDataMap();
  695. eventData[P_SERIALIZABLE] = this;
  696. eventData[P_TIMESTAMP] = (unsigned)timeStamp;
  697. eventData[P_INDEX] = RemapAttributeIndex(GetAttributes(), attr, i);
  698. eventData[P_NAME] = attr.name_;
  699. eventData[P_VALUE] = source.ReadVariant(attr.type_);
  700. SendEvent(E_INTERCEPTNETWORKUPDATE, eventData);
  701. }
  702. }
  703. }
  704. return changed;
  705. }
  706. bool Serializable::ReadLatestDataUpdate(Deserializer& source)
  707. {
  708. const Vector<AttributeInfo>* attributes = GetNetworkAttributes();
  709. if (!attributes)
  710. return false;
  711. unsigned numAttributes = attributes->Size();
  712. bool changed = false;
  713. unsigned long long interceptMask = networkState_ ? networkState_->interceptMask_ : 0;
  714. unsigned char timeStamp = source.ReadUByte();
  715. for (unsigned i = 0; i < numAttributes && !source.IsEof(); ++i)
  716. {
  717. const AttributeInfo& attr = attributes->At(i);
  718. if (attr.mode_ & AM_LATESTDATA)
  719. {
  720. if (!(interceptMask & (1ULL << i)))
  721. {
  722. OnSetAttribute(attr, source.ReadVariant(attr.type_));
  723. changed = true;
  724. }
  725. else
  726. {
  727. using namespace InterceptNetworkUpdate;
  728. VariantMap& eventData = GetEventDataMap();
  729. eventData[P_SERIALIZABLE] = this;
  730. eventData[P_TIMESTAMP] = (unsigned)timeStamp;
  731. eventData[P_INDEX] = RemapAttributeIndex(GetAttributes(), attr, i);
  732. eventData[P_NAME] = attr.name_;
  733. eventData[P_VALUE] = source.ReadVariant(attr.type_);
  734. SendEvent(E_INTERCEPTNETWORKUPDATE, eventData);
  735. }
  736. }
  737. }
  738. return changed;
  739. }
  740. Variant Serializable::GetAttribute(unsigned index) const
  741. {
  742. Variant ret;
  743. const Vector<AttributeInfo>* attributes = GetAttributes();
  744. if (!attributes)
  745. {
  746. URHO3D_LOGERROR(GetTypeName() + " has no attributes");
  747. return ret;
  748. }
  749. if (index >= attributes->Size())
  750. {
  751. URHO3D_LOGERROR("Attribute index out of bounds");
  752. return ret;
  753. }
  754. OnGetAttribute(attributes->At(index), ret);
  755. return ret;
  756. }
  757. Variant Serializable::GetAttribute(const String& name) const
  758. {
  759. Variant ret;
  760. const Vector<AttributeInfo>* attributes = GetAttributes();
  761. if (!attributes)
  762. {
  763. URHO3D_LOGERROR(GetTypeName() + " has no attributes");
  764. return ret;
  765. }
  766. for (Vector<AttributeInfo>::ConstIterator i = attributes->Begin(); i != attributes->End(); ++i)
  767. {
  768. if (!i->name_.Compare(name, true))
  769. {
  770. OnGetAttribute(*i, ret);
  771. return ret;
  772. }
  773. }
  774. URHO3D_LOGERROR("Could not find attribute " + name + " in " + GetTypeName());
  775. return ret;
  776. }
  777. Variant Serializable::GetAttributeDefault(unsigned index) const
  778. {
  779. const Vector<AttributeInfo>* attributes = GetAttributes();
  780. if (!attributes)
  781. {
  782. URHO3D_LOGERROR(GetTypeName() + " has no attributes");
  783. return Variant::EMPTY;
  784. }
  785. if (index >= attributes->Size())
  786. {
  787. URHO3D_LOGERROR("Attribute index out of bounds");
  788. return Variant::EMPTY;
  789. }
  790. AttributeInfo attr = attributes->At(index);
  791. Variant defaultValue = GetInstanceDefault(attr.name_);
  792. return defaultValue.IsEmpty() ? attr.defaultValue_ : defaultValue;
  793. }
  794. Variant Serializable::GetAttributeDefault(const String& name) const
  795. {
  796. Variant defaultValue = GetInstanceDefault(name);
  797. if (!defaultValue.IsEmpty())
  798. return defaultValue;
  799. const Vector<AttributeInfo>* attributes = GetAttributes();
  800. if (!attributes)
  801. {
  802. URHO3D_LOGERROR(GetTypeName() + " has no attributes");
  803. return Variant::EMPTY;
  804. }
  805. for (Vector<AttributeInfo>::ConstIterator i = attributes->Begin(); i != attributes->End(); ++i)
  806. {
  807. if (!i->name_.Compare(name, true))
  808. return i->defaultValue_;
  809. }
  810. URHO3D_LOGERROR("Could not find attribute " + name + " in " + GetTypeName());
  811. return Variant::EMPTY;
  812. }
  813. unsigned Serializable::GetNumAttributes() const
  814. {
  815. const Vector<AttributeInfo>* attributes = GetAttributes();
  816. return attributes ? attributes->Size() : 0;
  817. }
  818. unsigned Serializable::GetNumNetworkAttributes() const
  819. {
  820. const Vector<AttributeInfo>* attributes = networkState_ ? networkState_->attributes_ :
  821. context_->GetNetworkAttributes(GetType());
  822. return attributes ? attributes->Size() : 0;
  823. }
  824. bool Serializable::GetInterceptNetworkUpdate(const String& attributeName) const
  825. {
  826. const Vector<AttributeInfo>* attributes = GetNetworkAttributes();
  827. if (!attributes)
  828. return false;
  829. unsigned long long interceptMask = networkState_ ? networkState_->interceptMask_ : 0;
  830. for (unsigned i = 0; i < attributes->Size(); ++i)
  831. {
  832. const AttributeInfo& attr = attributes->At(i);
  833. if (!attr.name_.Compare(attributeName, true))
  834. return interceptMask & (1ULL << i) ? true : false;
  835. }
  836. return false;
  837. }
  838. void Serializable::SetInstanceDefault(const String& name, const Variant& defaultValue)
  839. {
  840. // Allocate the instance level default value
  841. if (!instanceDefaultValues_)
  842. instanceDefaultValues_ = make_unique<VariantMap>();
  843. instanceDefaultValues_->operator [](name) = defaultValue;
  844. }
  845. Variant Serializable::GetInstanceDefault(const String& name) const
  846. {
  847. if (instanceDefaultValues_)
  848. {
  849. VariantMap::ConstIterator i = instanceDefaultValues_->Find(name);
  850. if (i != instanceDefaultValues_->End())
  851. return i->second_;
  852. }
  853. return Variant::EMPTY;
  854. }
  855. }