Serializable.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //
  2. // Copyright (c) 2008-2020 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. #pragma once
  23. #include "../Core/Attribute.h"
  24. #include "../Core/Object.h"
  25. #include <cstddef>
  26. namespace Urho3D
  27. {
  28. class Connection;
  29. class Deserializer;
  30. class Serializer;
  31. class XMLElement;
  32. class JSONValue;
  33. struct DirtyBits;
  34. struct NetworkState;
  35. struct ReplicationState;
  36. /// Base class for objects with automatic serialization through attributes.
  37. class URHO3D_API Serializable : public Object
  38. {
  39. URHO3D_OBJECT(Serializable, Object);
  40. public:
  41. /// Construct.
  42. explicit Serializable(Context* context);
  43. /// Destruct.
  44. ~Serializable() override;
  45. /// Handle attribute write access. Default implementation writes to the variable at offset, or invokes the set accessor.
  46. virtual void OnSetAttribute(const AttributeInfo& attr, const Variant& src);
  47. /// Handle attribute read access. Default implementation reads the variable at offset, or invokes the get accessor.
  48. virtual void OnGetAttribute(const AttributeInfo& attr, Variant& dest) const;
  49. /// Return attribute descriptions, or null if none defined.
  50. virtual const Vector<AttributeInfo>* GetAttributes() const;
  51. /// Return network replication attribute descriptions, or null if none defined.
  52. virtual const Vector<AttributeInfo>* GetNetworkAttributes() const;
  53. /// Load from binary data. Return true if successful.
  54. virtual bool Load(Deserializer& source);
  55. /// Save as binary data. Return true if successful.
  56. virtual bool Save(Serializer& dest) const;
  57. /// Load from XML data. Return true if successful.
  58. virtual bool LoadXML(const XMLElement& source);
  59. /// Save as XML data. Return true if successful.
  60. virtual bool SaveXML(XMLElement& dest) const;
  61. /// Load from JSON data. Return true if successful.
  62. virtual bool LoadJSON(const JSONValue& source);
  63. /// Save as JSON data. Return true if successful.
  64. virtual bool SaveJSON(JSONValue& dest) const;
  65. /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
  66. virtual void ApplyAttributes() { }
  67. /// Return whether should save default-valued attributes into XML. Default false.
  68. virtual bool SaveDefaultAttributes() const { return false; }
  69. /// Mark for attribute check on the next network update.
  70. virtual void MarkNetworkUpdate() { }
  71. /// Set attribute by index. Return true if successfully set.
  72. /// @property{set_attributes}
  73. bool SetAttribute(unsigned index, const Variant& value);
  74. /// Set attribute by name. Return true if successfully set.
  75. bool SetAttribute(const String& name, const Variant& value);
  76. /// Set instance-level default flag.
  77. void SetInstanceDefault(bool enable) { setInstanceDefault_ = enable; }
  78. /// Reset all editable attributes to their default values.
  79. void ResetToDefault();
  80. /// Remove instance's default values if they are set previously.
  81. void RemoveInstanceDefault();
  82. /// Set temporary flag. Temporary objects will not be saved.
  83. /// @property
  84. void SetTemporary(bool enable);
  85. /// Enable interception of an attribute from network updates. Intercepted attributes are sent as events instead of applying directly. This can be used to implement client side prediction.
  86. void SetInterceptNetworkUpdate(const String& attributeName, bool enable);
  87. /// Allocate network attribute state.
  88. void AllocateNetworkState();
  89. /// Write initial delta network update.
  90. void WriteInitialDeltaUpdate(Serializer& dest, unsigned char timeStamp);
  91. /// Write a delta network update according to dirty attribute bits.
  92. void WriteDeltaUpdate(Serializer& dest, const DirtyBits& attributeBits, unsigned char timeStamp);
  93. /// Write a latest data network update.
  94. void WriteLatestDataUpdate(Serializer& dest, unsigned char timeStamp);
  95. /// Read and apply a network delta update. Return true if attributes were changed.
  96. bool ReadDeltaUpdate(Deserializer& source);
  97. /// Read and apply a network latest data update. Return true if attributes were changed.
  98. bool ReadLatestDataUpdate(Deserializer& source);
  99. /// Return attribute value by index. Return empty if illegal index.
  100. /// @property{get_attributes}
  101. Variant GetAttribute(unsigned index) const;
  102. /// Return attribute value by name. Return empty if not found.
  103. Variant GetAttribute(const String& name) const;
  104. /// Return attribute default value by index. Return empty if illegal index.
  105. /// @property{get_attributeDefaults}
  106. Variant GetAttributeDefault(unsigned index) const;
  107. /// Return attribute default value by name. Return empty if not found.
  108. Variant GetAttributeDefault(const String& name) const;
  109. /// Return number of attributes.
  110. /// @property
  111. unsigned GetNumAttributes() const;
  112. /// Return number of network replication attributes.
  113. unsigned GetNumNetworkAttributes() const;
  114. /// Return whether is temporary.
  115. /// @property
  116. bool IsTemporary() const { return temporary_; }
  117. /// Return whether an attribute's network updates are being intercepted.
  118. bool GetInterceptNetworkUpdate(const String& attributeName) const;
  119. /// Return the network attribute state, if allocated.
  120. NetworkState* GetNetworkState() const { return networkState_.Get(); }
  121. protected:
  122. /// Network attribute state.
  123. UniquePtr<NetworkState> networkState_;
  124. private:
  125. /// Set instance-level default value. Allocate the internal data structure as necessary.
  126. void SetInstanceDefault(const String& name, const Variant& defaultValue);
  127. /// Get instance-level default value.
  128. Variant GetInstanceDefault(const String& name) const;
  129. /// Attribute default value at each instance level.
  130. UniquePtr<VariantMap> instanceDefaultValues_;
  131. /// When true, store the attribute value as instance's default value (internal use only).
  132. bool setInstanceDefault_;
  133. /// Temporary flag.
  134. bool temporary_;
  135. };
  136. /// Template implementation of the variant attribute accessor.
  137. template <class TClassType, class TGetFunction, class TSetFunction>
  138. class VariantAttributeAccessorImpl : public AttributeAccessor
  139. {
  140. public:
  141. /// Construct.
  142. VariantAttributeAccessorImpl(TGetFunction getFunction, TSetFunction setFunction) : getFunction_(getFunction), setFunction_(setFunction) { }
  143. /// Invoke getter function.
  144. void Get(const Serializable* ptr, Variant& value) const override
  145. {
  146. assert(ptr);
  147. const auto classPtr = static_cast<const TClassType*>(ptr);
  148. getFunction_(*classPtr, value);
  149. }
  150. /// Invoke setter function.
  151. void Set(Serializable* ptr, const Variant& value) override
  152. {
  153. assert(ptr);
  154. auto classPtr = static_cast<TClassType*>(ptr);
  155. setFunction_(*classPtr, value);
  156. }
  157. private:
  158. /// Get functor.
  159. TGetFunction getFunction_;
  160. /// Set functor.
  161. TSetFunction setFunction_;
  162. };
  163. /// Make variant attribute accessor implementation.
  164. /// \tparam TClassType Serializable class type.
  165. /// \tparam TGetFunction Functional object with call signature `void getFunction(const TClassType& self, Variant& value)`
  166. /// \tparam TSetFunction Functional object with call signature `void setFunction(TClassType& self, const Variant& value)`
  167. template <class TClassType, class TGetFunction, class TSetFunction>
  168. SharedPtr<AttributeAccessor> MakeVariantAttributeAccessor(TGetFunction getFunction, TSetFunction setFunction)
  169. {
  170. return SharedPtr<AttributeAccessor>(new VariantAttributeAccessorImpl<TClassType, TGetFunction, TSetFunction>(getFunction, setFunction));
  171. }
  172. /// Make member attribute accessor.
  173. #define URHO3D_MAKE_MEMBER_ATTRIBUTE_ACCESSOR(typeName, variable) Urho3D::MakeVariantAttributeAccessor<ClassName>( \
  174. [](const ClassName& self, Urho3D::Variant& value) { value = self.variable; }, \
  175. [](ClassName& self, const Urho3D::Variant& value) { self.variable = value.Get<typeName>(); })
  176. /// Make member attribute accessor with custom post-set callback.
  177. #define URHO3D_MAKE_MEMBER_ATTRIBUTE_ACCESSOR_EX(typeName, variable, postSetCallback) Urho3D::MakeVariantAttributeAccessor<ClassName>( \
  178. [](const ClassName& self, Urho3D::Variant& value) { value = self.variable; }, \
  179. [](ClassName& self, const Urho3D::Variant& value) { self.variable = value.Get<typeName>(); self.postSetCallback(); })
  180. /// Make get/set attribute accessor.
  181. #define URHO3D_MAKE_GET_SET_ATTRIBUTE_ACCESSOR(getFunction, setFunction, typeName) Urho3D::MakeVariantAttributeAccessor<ClassName>( \
  182. [](const ClassName& self, Urho3D::Variant& value) { value = self.getFunction(); }, \
  183. [](ClassName& self, const Urho3D::Variant& value) { self.setFunction(value.Get<typeName>()); })
  184. /// Make member enum attribute accessor.
  185. #define URHO3D_MAKE_MEMBER_ENUM_ATTRIBUTE_ACCESSOR(variable) Urho3D::MakeVariantAttributeAccessor<ClassName>( \
  186. [](const ClassName& self, Urho3D::Variant& value) { value = static_cast<int>(self.variable); }, \
  187. [](ClassName& self, const Urho3D::Variant& value) { self.variable = static_cast<decltype(self.variable)>(value.Get<int>()); })
  188. /// Make member enum attribute accessor with custom post-set callback.
  189. #define URHO3D_MAKE_MEMBER_ENUM_ATTRIBUTE_ACCESSOR_EX(variable, postSetCallback) Urho3D::MakeVariantAttributeAccessor<ClassName>( \
  190. [](const ClassName& self, Urho3D::Variant& value) { value = static_cast<int>(self.variable); }, \
  191. [](ClassName& self, const Urho3D::Variant& value) { self.variable = static_cast<decltype(self.variable)>(value.Get<int>()); self.postSetCallback(); })
  192. /// Make get/set enum attribute accessor.
  193. #define URHO3D_MAKE_GET_SET_ENUM_ATTRIBUTE_ACCESSOR(getFunction, setFunction, typeName) Urho3D::MakeVariantAttributeAccessor<ClassName>( \
  194. [](const ClassName& self, Urho3D::Variant& value) { value = static_cast<int>(self.getFunction()); }, \
  195. [](ClassName& self, const Urho3D::Variant& value) { self.setFunction(static_cast<typeName>(value.Get<int>())); })
  196. /// Attribute metadata.
  197. namespace AttributeMetadata
  198. {
  199. /// Names of vector struct elements. StringVector.
  200. static const StringHash P_VECTOR_STRUCT_ELEMENTS("VectorStructElements");
  201. }
  202. // The following macros need to be used within a class member function such as ClassName::RegisterObject().
  203. // A variable called "context" needs to exist in the current scope and point to a valid Context object.
  204. /// Copy attributes from a base class.
  205. #define URHO3D_COPY_BASE_ATTRIBUTES(sourceClassName) context->CopyBaseAttributes<sourceClassName, ClassName>()
  206. /// Update the default value of an already registered attribute.
  207. #define URHO3D_UPDATE_ATTRIBUTE_DEFAULT_VALUE(name, defaultValue) context->UpdateAttributeDefaultValue<ClassName>(name, defaultValue)
  208. /// Remove attribute by name.
  209. #define URHO3D_REMOVE_ATTRIBUTE(name) context->RemoveAttribute<ClassName>(name)
  210. /// Define an object member attribute.
  211. #define URHO3D_ATTRIBUTE(name, typeName, variable, defaultValue, mode) context->RegisterAttribute<ClassName>(Urho3D::AttributeInfo( \
  212. Urho3D::GetVariantType<typeName >(), name, URHO3D_MAKE_MEMBER_ATTRIBUTE_ACCESSOR(typeName, variable), nullptr, defaultValue, mode))
  213. /// Define an object member attribute. Post-set member function callback is called when attribute set.
  214. #define URHO3D_ATTRIBUTE_EX(name, typeName, variable, postSetCallback, defaultValue, mode) context->RegisterAttribute<ClassName>(Urho3D::AttributeInfo( \
  215. Urho3D::GetVariantType<typeName >(), name, URHO3D_MAKE_MEMBER_ATTRIBUTE_ACCESSOR_EX(typeName, variable, postSetCallback), nullptr, defaultValue, mode))
  216. /// Define an attribute that uses get and set functions.
  217. #define URHO3D_ACCESSOR_ATTRIBUTE(name, getFunction, setFunction, typeName, defaultValue, mode) context->RegisterAttribute<ClassName>(Urho3D::AttributeInfo( \
  218. Urho3D::GetVariantType<typeName >(), name, URHO3D_MAKE_GET_SET_ATTRIBUTE_ACCESSOR(getFunction, setFunction, typeName), nullptr, defaultValue, mode))
  219. /// Define an object member attribute. Zero-based enum values are mapped to names through an array of C string pointers.
  220. #define URHO3D_ENUM_ATTRIBUTE(name, variable, enumNames, defaultValue, mode) context->RegisterAttribute<ClassName>(Urho3D::AttributeInfo( \
  221. Urho3D::VAR_INT, name, URHO3D_MAKE_MEMBER_ENUM_ATTRIBUTE_ACCESSOR(variable), enumNames, static_cast<int>(defaultValue), mode))
  222. /// Define an object member attribute. Zero-based enum values are mapped to names through an array of C string pointers. Post-set member function callback is called when attribute set.
  223. #define URHO3D_ENUM_ATTRIBUTE_EX(name, variable, postSetCallback, enumNames, defaultValue, mode) context->RegisterAttribute<ClassName>(Urho3D::AttributeInfo( \
  224. Urho3D::VAR_INT, name, URHO3D_MAKE_MEMBER_ENUM_ATTRIBUTE_ACCESSOR_EX(variable, postSetCallback), enumNames, static_cast<int>(defaultValue), mode))
  225. /// Define an attribute that uses get and set functions. Zero-based enum values are mapped to names through an array of C string pointers.
  226. #define URHO3D_ENUM_ACCESSOR_ATTRIBUTE(name, getFunction, setFunction, typeName, enumNames, defaultValue, mode) context->RegisterAttribute<ClassName>(Urho3D::AttributeInfo( \
  227. Urho3D::VAR_INT, name, URHO3D_MAKE_GET_SET_ENUM_ATTRIBUTE_ACCESSOR(getFunction, setFunction, typeName), enumNames, static_cast<int>(defaultValue), mode))
  228. /// Define an attribute with custom setter and getter.
  229. #define URHO3D_CUSTOM_ATTRIBUTE(name, getFunction, setFunction, typeName, defaultValue, mode) context->RegisterAttribute<ClassName>(Urho3D::AttributeInfo( \
  230. Urho3D::GetVariantType<typeName >(), name, Urho3D::MakeVariantAttributeAccessor<ClassName>(getFunction, setFunction), nullptr, defaultValue, mode))
  231. /// Define an enum attribute with custom setter and getter. Zero-based enum values are mapped to names through an array of C string pointers.
  232. #define URHO3D_CUSTOM_ENUM_ATTRIBUTE(name, getFunction, setFunction, enumNames, defaultValue, mode) context->RegisterAttribute<ClassName>(Urho3D::AttributeInfo( \
  233. Urho3D::VAR_INT, name, Urho3D::MakeVariantAttributeAccessor<ClassName>(getFunction, setFunction), enumNames, static_cast<int>(defaultValue), mode))
  234. /// Deprecated. Use URHO3D_ACCESSOR_ATTRIBUTE instead.
  235. #define URHO3D_MIXED_ACCESSOR_ATTRIBUTE(name, getFunction, setFunction, typeName, defaultValue, mode) URHO3D_ACCESSOR_ATTRIBUTE(name, getFunction, setFunction, typeName, defaultValue, mode)
  236. }